diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9fee7ce..24d9dc9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,8 @@ jobs: run: npm run validate - name: Versions, hooks, MCP wiring, docs, line endings run: npm run check + - name: Synced skills match the pinned coreflux-skills tag + run: npm run skills:check unit: name: Unit tests (${{ matrix.os }}, Node ${{ matrix.node }}) diff --git a/CHANGELOG.md b/CHANGELOG.md index b35b552..8095cb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,24 @@ All notable changes to the Coreflux plugin for Cursor are documented here. The f (`coreflux.vscode-lot-notebooks`) through the Cursor CLI when it is missing, so `.lotnb` files open as notebooks. - Plugin logo. +- `coreflux-cursor-tools` skill: maps the broker tool names used by the shared skills to this + plugin's MCP tools. +- `lot_deploy` / `lotnb_deploy` deploy `DEFINE AGENT` (`-addAgent`, after routes) and + `DEFINE THING` (every Thing block, templates included, as one `-addThing`, last, as the broker loads projects); + `lot_remove` takes `AGENT` and `THING`. + +### 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`), + 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. + +### Removed + +- The hand-written `lot-authoring`, `broker-commands`, `broker-observability`, + `broker-security` and `lot-projects` skills, replaced by the synced set above. ## [0.1.0] - 2026-09-13 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e1d493..3723dcf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,6 +61,13 @@ npm run e2e # deploys throw-away entities, drives them, removes them ### Writing skills and rules +- The LoT/broker skills under `plugins/coreflux/skills/` (every one listed in `skills.json`) are + 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 `. +- 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 `foo`/`test`. - Action, model, route and rule names are bare identifiers; panel and theme names are quoted. diff --git a/README.md b/README.md index 9dd59e1..1721bb7 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ themes on a Coreflux broker. | Plugin | What it gives the agent | |--------|-------------------------| -| [`plugins/coreflux`](plugins/coreflux) | The full broker command surface over MQTT (`$SYS/Coreflux/Command`), live topic publish/subscribe, LoT lint + ordered deployment of `.lot`/`.lotnb` files, project upload/export, route templates, action tracing, docs search, five LoT/broker skills, two agents, six slash-commands and safety hooks for destructive operations. | +| [`plugins/coreflux`](plugins/coreflux) | The full broker command surface over MQTT (`$SYS/Coreflux/Command`), live topic publish/subscribe, LoT lint + ordered deployment of `.lot`/`.lotnb` files, project upload/export, route templates, action tracing, docs search, the Coreflux LoT/broker skills (synced from coreflux-skills), two agents, six slash-commands and safety hooks for destructive operations. | ## Install @@ -76,7 +76,7 @@ Node 20 and 22, and the end-to-end suite against `coreflux/coreflux-mqtt-broker: ## Contributing Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md) for the checks to run, how to -write skills that stay true to the broker parser, and the release process. +update the synced skills, and the release process. [SECURITY.md](SECURITY.md) covers vulnerability reports. Changes are tracked in [CHANGELOG.md](CHANGELOG.md). diff --git a/package.json b/package.json index d5a872e..6c503f0 100644 --- a/package.json +++ b/package.json @@ -15,9 +15,11 @@ "scripts": { "validate": "node scripts/validate-template.mjs", "check": "node scripts/check-sources.mjs", + "skills:sync": "node scripts/sync-skills.mjs", + "skills:check": "node scripts/sync-skills.mjs --check", "test": "node scripts/run-tests.mjs", "smoke": "node plugins/coreflux/scripts/smoke-test.mjs", "e2e": "node plugins/coreflux/scripts/e2e-test.mjs", - "ci": "npm run validate && npm run check && npm test" + "ci": "npm run validate && npm run check && npm run skills:check && npm test" } } diff --git a/plugins/coreflux/README.md b/plugins/coreflux/README.md index 12c9a23..51c7d11 100644 --- a/plugins/coreflux/README.md +++ b/plugins/coreflux/README.md @@ -52,13 +52,20 @@ workspace file `active` → user file `active` → `default` → `workspace` → ### Skills (`skills/`) -| Skill | Use | -|-------|-----| -| `lot-authoring` | LoT syntax, decision guide, anti-patterns; references for actions, models, routes | -| `broker-commands` | Every broker command, payload rules, envelope shape, sequences | -| `broker-observability` | `$SYS/Coreflux` topic map, status/trace JSON, triage playbook | -| `lot-projects` | `.lotnb` format, project layout, load order, `-addProject` / git commands | -| `broker-security` | RBAC rules, flags, groups, which flag each command needs, anti-lockout | +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. + +| Skill | Source | Use | +|-------|--------|-----| +| `broker-tools` | coreflux-skills | The broker's tool surfaces, registry commands, safe deploy workflow | +| `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 | +| `python-scripts` | coreflux-skills | Python scripts and `CALL PYTHON` | +| `coreflux-cursor-tools` | this plugin | Maps the broker tool names in those skills to this plugin's MCP tools; envelopes; deploying files and projects | ### Rules (`rules/`) diff --git a/plugins/coreflux/agents/broker-operator.md b/plugins/coreflux/agents/broker-operator.md index c75b9fd..92aa5ae 100644 --- a/plugins/coreflux/agents/broker-operator.md +++ b/plugins/coreflux/agents/broker-operator.md @@ -18,13 +18,14 @@ state: every statement about the broker is backed by an envelope or a topic you ## Diagnosing -Follow the `broker-observability` skill playbook: +Use `broker-tools` for what the broker can tell you and `coreflux-cursor-tools` for the tool +to call here: - Actions: `broker_action_trace { action, payload }`, then `$SYS/Coreflux/Actions//Error`. - Routes: status JSON (`errors.consecutive`, `health`), `-checkRouteConnection`, the route source on `$SYS/Coreflux/Routes/`, env/secret names via `-listEnv` / `-listSecrets`. - Data flow: `mqtt_subscribe` on the exact topic for a bounded time; OT values are on `/`. -- Permissions: `Permission denied` → `broker-security` skill; identify the missing flag. +- Permissions: `Permission denied` → `lot-rules` skill; identify the scope and rule that denied. ## Changing things diff --git a/plugins/coreflux/agents/lot-reviewer.md b/plugins/coreflux/agents/lot-reviewer.md index 9eeedb8..2510c56 100644 --- a/plugins/coreflux/agents/lot-reviewer.md +++ b/plugins/coreflux/agents/lot-reviewer.md @@ -12,7 +12,8 @@ the broker parser and runtime will. Be concrete: file, cell, line, wrong text, c 1. Run `lot_lint` on every changed `.lot` / `.lotnb` (path mode) and on any inline LoT. Report every `error`; treat `warning`s as findings to explain. -2. Read the code with the `lot-authoring` skill open and check what the linter cannot: +2. Read the code with the skill for each kind open (`lot-actions`, `lot-models`, `lot-routes`, + `lot-rules`, `lot-panels`, `python-scripts`, …) and check what the linter cannot: - Wildcards and `TOPIC POSITION` indexes match the real topic shape (1-based). - `IF` conditions compare compatible types (`PAYLOAD AS DOUBLE` before `> 85`). - `GET JSON` paths exist in the payload the action really receives. diff --git a/plugins/coreflux/commands/coreflux-new-project.md b/plugins/coreflux/commands/coreflux-new-project.md index 55c1f3c..6c7aca2 100644 --- a/plugins/coreflux/commands/coreflux-new-project.md +++ b/plugins/coreflux/commands/coreflux-new-project.md @@ -8,14 +8,14 @@ description: Scaffold a Coreflux LoT project folder with numbered .lotnb noteboo Ask for: project name (kebab-case), what it should do (devices/sources, outputs), and which broker it targets (an existing profile from `broker_list`, or a new URL). -1. Create the layout described in the `lot-projects` skill: +1. Create the layout (numbered so alphabetical order matches load order): `README.md`, `01-models.lotnb`, `02-actions.lotnb`, `03-routes.lotnb`, `04-rules.lotnb`, `05-dashboard.lotnb` (skip files that would be empty). For the broker, write `.coreflux/brokers.json` with `broker_save { scope: "workspace", name, url, username, passwordEnv, activate: true }` — the password goes in an environment variable or in the user-scope profile of the same name, never in the project. 2. Each notebook starts with a markdown cell (purpose, topics in/out, how to test) followed by - `lot` cells written with the `lot-authoring` skill. Use realistic names from the user's + `lot` cells written with the skill for each kind (`lot-models`, `lot-actions`, …). Use realistic names from the user's domain, never `foo`/`test`. 3. README lists: what the project does, required `-setEnv` / `-setSecret` names, how to deploy (`project_upload` or `-addProject`), how to verify. diff --git a/plugins/coreflux/commands/coreflux-new-route.md b/plugins/coreflux/commands/coreflux-new-route.md index d141bb5..e804358 100644 --- a/plugins/coreflux/commands/coreflux-new-route.md +++ b/plugins/coreflux/commands/coreflux-new-route.md @@ -11,7 +11,7 @@ and out (topics), polling interval for OT routes. 1. `broker_route_template { type }` → use `fields` to know every setting, its type, regex and whether it should come from env (`env: true`). Start from `skeleton` (the `ADD METADATA` block is already removed). -2. Fill the skeleton following `lot-authoring` → `lot-routes.md`: +2. Fill the skeleton following the `lot-routes` skill: - hosts/users → `GET ENV "NAME"`; passwords/keys → `GET SECRET "NAME"`; - OT routes: `ADD MAPPING` with `SOURCE_TOPIC` + `EVERY`, tags indented 8 spaces; values will appear on `/`; diff --git a/plugins/coreflux/commands/coreflux-secure.md b/plugins/coreflux/commands/coreflux-secure.md index 99799eb..b16e6e9 100644 --- a/plugins/coreflux/commands/coreflux-secure.md +++ b/plugins/coreflux/commands/coreflux-secure.md @@ -5,7 +5,8 @@ description: Audit a Coreflux broker's access control — users, permission flag # Secure the broker -Use the `broker-security` skill throughout. +Use the `lot-rules` skill throughout (scopes, priority bands, which scopes a user rule can +change at all). 1. `broker_connection` — which user you are; note if it is `root`. 2. Inventory: `mqtt_read_retained $SYS/Coreflux/Rules/#` (deployed rules), @@ -19,7 +20,6 @@ Use the `broker-security` skill throughout. 6. Propose, in order and with the exact LoT / `-command`: - per-device or per-group publish/subscribe rules (priority 100–999 999, allow-list style); - `FOR Connect` admission if devices have a client-id pattern; - - `SubscribeSys` carve-outs for dashboard users instead of `AllowedSystemConfiguration`; - moving secrets from env to `-setSecret`; - password rotation via `-changeUserPassword` (values supplied by the user, never echoed). 7. For each rule, state which users/clients it affects and confirm `root`/admin stay allowed. diff --git a/plugins/coreflux/rules/coreflux-conventions.mdc b/plugins/coreflux/rules/coreflux-conventions.mdc index 331de82..49051f3 100644 --- a/plugins/coreflux/rules/coreflux-conventions.mdc +++ b/plugins/coreflux/rules/coreflux-conventions.mdc @@ -6,7 +6,10 @@ alwaysApply: true # Coreflux conventions - **LoT is the only configuration language** for actions, models, routes, rules, panels and - themes. Never propose JSON/YAML for these. Read the `lot-authoring` skill before writing LoT. + themes. Never propose JSON/YAML for these. Before writing LoT read the skill for that kind + (`lot-actions`, `lot-models`, `lot-routes`, `lot-rules`, `lot-agents`, `lot-things`, + `lot-panels`, `lot-themes`, `python-scripts`). Those skills come from the broker; where they + name a broker MCP tool, `coreflux-cursor-tools` gives the tool to call here. - **Talk to the broker through the `coreflux-broker` MCP tools**, not ad-hoc shell MQTT clients: `broker_command`, `broker_overview`, `lot_lint`, `lot_deploy`, `lotnb_deploy`, `mqtt_publish`, `mqtt_subscribe`, `mqtt_read_retained`, `broker_action_trace`, diff --git a/plugins/coreflux/rules/lot-files.mdc b/plugins/coreflux/rules/lot-files.mdc index ee6857d..754b5a9 100644 --- a/plugins/coreflux/rules/lot-files.mdc +++ b/plugins/coreflux/rules/lot-files.mdc @@ -20,6 +20,7 @@ alwaysApply: false `{braces}`, credentials via `GET ENV` / `GET SECRET`. - After every edit run `lot_lint { path }` on the file. Before claiming a notebook is done run `lotnb_deploy { path, dryRun: true }` to confirm the plan (order: models → actions → routes → - rules → python → themes → panels), then deploy for real if a broker is configured. + agents → rules → python → themes → panels → things), then deploy for real if a broker is configured. - Do not "fix" a notebook by deleting cells whose meaning you do not understand; ask. -- Follow the `lot-authoring` and `lot-projects` skills for syntax and layout. +- Follow the skill for each kind (`lot-actions`, `lot-models`, `lot-routes`, …) for syntax and + `coreflux-cursor-tools` for deploying files and projects. diff --git a/plugins/coreflux/scripts/hooks/session-context.mjs b/plugins/coreflux/scripts/hooks/session-context.mjs index 814a391..9b1c0e4 100644 --- a/plugins/coreflux/scripts/hooks/session-context.mjs +++ b/plugins/coreflux/scripts/hooks/session-context.mjs @@ -46,7 +46,7 @@ function countNotebooks(dir, depth = 0, acc = { lotnb: 0, lot: 0 }) { const counts = countNotebooks(root); if (counts.lotnb || counts.lot) { - lines.push(`Workspace contains ${counts.lotnb} .lotnb notebook(s) and ${counts.lot} .lot file(s): treat it as a Coreflux LoT project (skills: lot-authoring, lot-projects).`); + lines.push(`Workspace contains ${counts.lotnb} .lotnb notebook(s) and ${counts.lot} .lot file(s): treat it as a Coreflux LoT project (skills: coreflux-cursor-tools, then lot-actions, lot-models, lot-routes, … per kind).`); } respond({ additional_context: `Coreflux plugin: ${lines.join(" ")}` }); diff --git a/plugins/coreflux/scripts/mcp/coreflux-mqtt-mcp.mjs b/plugins/coreflux/scripts/mcp/coreflux-mqtt-mcp.mjs index d29ad50..d959edc 100644 --- a/plugins/coreflux/scripts/mcp/coreflux-mqtt-mcp.mjs +++ b/plugins/coreflux/scripts/mcp/coreflux-mqtt-mcp.mjs @@ -13,7 +13,7 @@ import path from "node:path"; import { randomUUID } from "node:crypto"; import { createInterface } from "node:readline"; import { MqttClient, topicMatches } from "./lib/mqtt-client.mjs"; -import { deployCommand, lintLot, loadLotFile, sortForDeploy, splitLotEntities, ENTITY_COMMANDS } from "./lib/lot.mjs"; +import { deployCommand, deployUnits, lintLot, loadLotFile, splitLotEntities, ENTITY_COMMANDS } from "./lib/lot.mjs"; import { zipDirectory } from "./lib/zip.mjs"; import { describeProfiles, loadProfiles, removeProfile, resolveSettings as resolveProfileSettings, saveProfile, setActiveProfile } from "./lib/brokers.mjs"; @@ -260,7 +260,7 @@ function summarizeEnvelope(envelope) { // --------------------------------------------------------------------------------------------- async function deployEntities(entities, { dryRun = false, stopOnError = true, lint = true, timeoutMs = DEFAULT_TIMEOUT_MS }) { - const plan = sortForDeploy(entities).map((entity) => ({ + const plan = deployUnits(entities).map((entity) => ({ kind: entity.kind, name: entity.name, source: entity.source, @@ -282,7 +282,7 @@ async function deployEntities(entities, { dryRun = false, stopOnError = true, li } const results = []; - for (const entity of sortForDeploy(entities)) { + for (const entity of deployUnits(entities)) { let outcome; try { const envelope = await session.command(deployCommand(entity), { timeoutMs }); @@ -590,7 +590,7 @@ const tools = [ { name: "lot_lint", description: - "Statically check LoT source for the mistakes that break the broker parser (indentation, indented triggers, missing DO/WITH/THEN, MESSAGE keyword, 0-based TOPIC POSITION, quoted action/model/route/rule names, ADD METADATA, hardcoded passwords, PAYLOAD on timers, models without AS TRIGGER…). Pass either code or a path to a .lot/.lotnb file. Run before deploying.", + "Statically check LoT source for the mistakes that break the broker parser (indentation, indented triggers, missing DO/WITH/THEN, MESSAGE keyword, 0-based TOPIC POSITION, quoted action/model/route/agent/rule names, ADD METADATA, hardcoded passwords, PAYLOAD on timers, models without AS TRIGGER (skipped when the model inherits via FROM)…). Pass either code or a path to a .lot/.lotnb file. Run before deploying.", inputSchema: { type: "object", properties: { @@ -615,7 +615,7 @@ const tools = [ { name: "lot_deploy", description: - "Deploy LoT source (one or more DEFINE blocks, or a Python script with a # Script Name header) to the broker. Splits entities, lints them, deploys in broker order (models → actions → routes → rules → python → themes → panels) and returns each envelope. Use dryRun=true to see the plan first.", + "Deploy LoT source (one or more DEFINE blocks, or a Python script with a # Script Name header) to the broker. Splits entities, lints them, deploys in broker order (models → actions → routes → agents → rules → python → themes → panels → things; all Things go as one -addThing) and returns each envelope. Use dryRun=true to see the plan first.", inputSchema: { type: "object", properties: { @@ -668,11 +668,11 @@ const tools = [ }, { name: "lot_remove", - description: "Remove a single LoT entity from the broker (-removeAction / -removeModel / -removeRoute / -removeRule / -removePython / -removeTheme / -removePanel).", + description: "Remove a single LoT entity from the broker (-removeAction / -removeModel / -removeRoute / -removeRule / -removeAgent / -removeThing / -removePython / -removeTheme / -removePanel). Change a Thing's child through its Thing, never directly.", inputSchema: { type: "object", properties: { - kind: { type: "string", enum: ["ACTION", "MODEL", "ROUTE", "RULE", "PYTHON", "THEME", "PANEL"] }, + kind: { type: "string", enum: ["ACTION", "MODEL", "ROUTE", "RULE", "AGENT", "THING", "PYTHON", "THEME", "PANEL"] }, name: { type: "string" }, }, required: ["kind", "name"], diff --git a/plugins/coreflux/scripts/mcp/lib/lot.mjs b/plugins/coreflux/scripts/mcp/lib/lot.mjs index c7049ca..8201c87 100644 --- a/plugins/coreflux/scripts/mcp/lib/lot.mjs +++ b/plugins/coreflux/scripts/mcp/lib/lot.mjs @@ -4,20 +4,27 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; -/** Deploy verb per entity kind, in the order the broker loads projects. */ -export const ENTITY_ORDER = ["MODEL", "ACTION", "ROUTE", "RULE", "PYTHON", "THEME", "PANEL"]; +/** + * Deploy verb per entity kind, in the order the broker loads projects: models, actions, routes, + * agents (after the LLM connector they use), rules, python, themes, panels, then things last + * (ProjectManager load order). + */ +export const ENTITY_ORDER = ["MODEL", "ACTION", "ROUTE", "AGENT", "RULE", "PYTHON", "THEME", "PANEL", "THING"]; export const ENTITY_COMMANDS = { MODEL: { add: "-addModel", remove: "-removeModel" }, ACTION: { add: "-addAction", remove: "-removeAction" }, ROUTE: { add: "-addRoute", remove: "-removeRoute" }, + AGENT: { add: "-addAgent", remove: "-removeAgent" }, RULE: { add: "-addRule", remove: "-removeRule" }, + THING: { add: "-addThing", remove: "-removeThing" }, PYTHON: { add: "-addPython", remove: "-removePython" }, THEME: { add: "-addTheme", remove: "-removeTheme" }, PANEL: { add: "-addPanel", remove: "-removePanel" }, }; -const DEFINE_RE = /^DEFINE\s+(ACTION|MODEL|ROUTE|RULE|THEME|PANEL|VISU|THING)\b\s*("([^"]+)"|([A-Za-z0-9_\-.]+))?/i; +// TEMPLATE is not a Thing's name: `DEFINE THING TEMPLATE "Pump"` defines the template Pump. +const DEFINE_RE = /^DEFINE\s+(ACTION|MODEL|ROUTE|RULE|AGENT|THEME|PANEL|VISU|THING)\b\s*(?:TEMPLATE\s+)?("([^"]+)"|([A-Za-z0-9_\-.]+))?/i; const SCRIPT_NAME_RE = /^\s*#\s*Script Name:\s*([A-Za-z_][A-Za-z0-9_]*)\s*$/im; function stripComments(line) { @@ -128,9 +135,25 @@ export function sortForDeploy(entities) { return [...entities].sort((a, b) => ENTITY_ORDER.indexOf(a.kind) - ENTITY_ORDER.indexOf(b.kind)); } +/** + * Sorted deploy units. All Things travel as one -addThing payload, the way the broker's own + * deploy groups consecutive DEFINE THING blocks, so a root can reference a template beside it. + */ +export function deployUnits(entities) { + const units = []; + for (const entity of sortForDeploy(entities)) { + const previous = units.at(-1); + if (entity.kind === "THING" && previous?.kind === "THING") { + units[units.length - 1] = { ...previous, name: `${previous.name}, ${entity.name}`, code: `${previous.code}\n\n${entity.code}`, source: previous.source === entity.source ? previous.source : `${previous.source}, ${entity.source}` }; + } else { + units.push(entity); + } + } + return units; +} + /** Builds the exact MQTT payload for deploying one entity. */ export function deployCommand(entity) { - if (entity.kind === "THING") throw new Error("DEFINE THING is composed by the notebook runtime and cannot be deployed directly"); const verb = ENTITY_COMMANDS[entity.kind]?.add; if (!verb) throw new Error(`Unsupported entity kind "${entity.kind}"`); return `${verb} ${entity.code}`; @@ -167,7 +190,7 @@ export function lintLot(source) { if (define) { if (indent.length > 0) add("error", lineNo, "DEFINE must start at column 0.", "Remove the leading indentation."); currentKind = define[1].toUpperCase(); - if (["ACTION", "MODEL", "ROUTE", "RULE"].includes(currentKind) && define[3]) { + if (["ACTION", "MODEL", "ROUTE", "AGENT", "RULE"].includes(currentKind) && define[3]) { add("error", lineNo, `${currentKind.charAt(0)}${currentKind.slice(1).toLowerCase()} name "${define[3]}" is quoted; the parser expects a bare identifier.`, `Write DEFINE ${currentKind} ${define[3].replace(/[^A-Za-z0-9_]/g, "_")}.`); } if (currentKind === "MODEL" && /\bFROM\s+"/i.test(trimmed)) { @@ -253,7 +276,7 @@ export function lintLot(source) { // Uppercase keyword check on the first token of a statement line. const firstToken = trimmed.split(/\s+/)[0]; - const knownKeywords = ["DEFINE", "ON", "DO", "SET", "PUBLISH", "KEEP", "IF", "ELSE", "SWITCH", "CASE", "DEFAULT", "LOOP", "UNTIL", "CALL", "TRIGGER", "STORE", "ADD", "WITH", "INPUT", "RETURN", "OUTPUT", "GET", "DELETE", "ALLOW", "DENY", "BIND", "AT", "INVOKE", "FETCH", "NAVIGATE"]; + const knownKeywords = ["DEFINE", "ON", "DO", "SET", "PUBLISH", "KEEP", "IF", "ELSE", "SWITCH", "CASE", "DEFAULT", "LOOP", "UNTIL", "CALL", "TRIGGER", "STORE", "ADD", "WITH", "INPUT", "RETURN", "OUTPUT", "GET", "DELETE", "ALLOW", "DENY", "BIND", "AT", "INVOKE", "FETCH", "NAVIGATE", "USES"]; if (knownKeywords.includes(firstToken.toUpperCase()) && firstToken !== firstToken.toUpperCase()) { add("error", lineNo, `Keyword "${firstToken}" must be uppercase.`, `Write ${firstToken.toUpperCase()}.`); } @@ -276,11 +299,58 @@ export function lintLot(source) { } } - // Model trigger sanity. + // DEFINE AGENT structural checks (mirrors broker ParseAgentDefinition + AgentDefinition.FromRoute). + for (const entity of splitLotEntities(source)) { + if (entity.kind !== "AGENT") continue; + const bodyLines = entity.code + .split("\n") + .slice(1) + .map((line) => stripComments(line).trim()) + .filter((line) => line.length > 0); + if (bodyLines.length === 0) { + add( + "error", + entity.line, + `Agent "${entity.name}" has an empty body.`, + "Start with USES LLM ROUTE (or CONNECTOR), then WITH DEFAULT_USER \"…\".", + ); + } else if (!/^USES\s+LLM\s+(ROUTE|CONNECTOR)\s+[A-Za-z_][A-Za-z0-9_\-.]*\s*$/i.test(bodyLines[0])) { + add( + "error", + entity.line, + `Agent "${entity.name}" must start with USES LLM ROUTE (or CONNECTOR).`, + 'First body line: USES LLM ROUTE GPT55', + ); + } + if (!/\bWITH\s+DEFAULT_USER\b/i.test(entity.code)) { + add( + "error", + entity.line, + `Agent "${entity.name}" is missing required WITH DEFAULT_USER.`, + 'Add WITH DEFAULT_USER "agent_svc".', + ); + } + for (const line of bodyLines) { + if (!/^ADD\s+TOOL\b/i.test(line)) continue; + if (!/^ADD\s+TOOL\s+"[^"]+"\s*$/i.test(line)) { + add( + "error", + entity.line, + `Agent "${entity.name}": ADD TOOL requires a quoted tool name.`, + 'ADD TOOL "read_mqtt"', + ); + } + } + } + + // Model trigger sanity. Child models that inherit via FROM Parent get the parent's + // AS TRIGGER; only warn when this model both binds topics and declares neither. for (const entity of splitLotEntities(source)) { if (entity.kind !== "MODEL") continue; + const header = entity.code.split("\n")[0] ?? ""; + const inheritsTrigger = /\bFROM\s+[A-Za-z_][A-Za-z0-9_\-.]*/i.test(header); const hasTopicBinding = /\bWITH\s+TOPIC\s+"/i.test(entity.code.split("\n").slice(1).join("\n")); - if (hasTopicBinding && !/\bAS\s+TRIGGER\b/i.test(entity.code)) { + if (hasTopicBinding && !/\bAS\s+TRIGGER\b/i.test(entity.code) && !inheritsTrigger) { add("warning", entity.line, `Model "${entity.name}" binds topics but marks none AS TRIGGER, so it will never auto-publish.`, "Add AS TRIGGER to the field whose update should publish the model."); } } diff --git a/plugins/coreflux/skills/LICENSE b/plugins/coreflux/skills/LICENSE new file mode 100644 index 0000000..7d7dfb4 --- /dev/null +++ b/plugins/coreflux/skills/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024-2026 Coreflux + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/coreflux/skills/broker-commands/SKILL.md b/plugins/coreflux/skills/broker-commands/SKILL.md deleted file mode 100644 index 59be474..0000000 --- a/plugins/coreflux/skills/broker-commands/SKILL.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -name: broker-commands -description: Operate a Coreflux MQTT broker through its command surface — every -command on $SYS/Coreflux/Command (routes, models, actions, rules, python, panels, themes, projects, users, groups, env, secrets, audit, trace logs) and the JSON envelope on $SYS/Coreflux/Command/Output. Use when the user wants to list, add, remove, run, diagnose or configure anything on a broker, or asks "what command does X". ---- - -# Coreflux Broker Commands - -Everything the broker can do is a command published to **`$SYS/Coreflux/Command`**; the reply -is a JSON envelope on **`$SYS/Coreflux/Command/Output`**. The `broker_command` tool (MCP -server `coreflux-broker`) does the publish, adds `-requestId`, and returns the matching -envelope. Prefer the specialised tools where they exist: - -| Goal | Tool | -|------|------| -| Any command | `broker_command { command: "-listRoutes" }` | -| Health snapshot | `broker_overview` | -| Deploy LoT text / a file | `lot_deploy` / `lotnb_deploy` (lint + ordered `-addX`) | -| Remove one entity | `lot_remove { kind, name }` | -| Route skeleton for a type | `broker_route_template { type }` | -| Debug an action | `broker_action_trace { action, payload }` | -| Ship / fetch a project folder | `project_upload` / `project_export` | -| Raw MQTT | `mqtt_publish` / `mqtt_subscribe` / `mqtt_read_retained` | -| Which broker am I on? | `broker_connection` | -| Several brokers (dev/edge/prod) | `broker_list` → `broker_use { name }`; add one with `broker_save` | - -Without a configured broker, give the user the exact payload to publish: -`mosquitto_pub -h HOST -u USER -P PASS -t '$SYS/Coreflux/Command' -m '-listRoutes'` and -`mosquitto_sub … -t '$SYS/Coreflux/Command/Output' -v`. - -## Payload rules - -- Plain UTF-8 string: `-commandName [-requestId ]`. Not JSON-wrapped. -- Arguments are quote-aware tokens; quotes are stripped. **Do not wrap LoT bodies in quotes.** - `-addAction DEFINE ACTION X\nON TOPIC "a" DO\n PUBLISH TOPIC "b" WITH PAYLOAD` is correct. -- Multi-word project names: `-loadProject "Traceability System"` or hyphenate. -- Aliases: `--kebab-case` works for every command (`--list-routes`), and `-addVisu` = `-addPanel`. -- RBAC uses the MQTT session username; there is no `-requestUser`. -- `-updateData` produces no Output message; everything else does. - -## Response envelope - -```json -{ "success": true, "command": "AddRoute", "requestId": "…", "message": "Route 'X' added successfully!", - "entityType": "Route", "entityName": "X", "data": {} } -``` - -- `data` is always present (`{}`/`[]` when empty). Lists put arrays in `data`. -- Failures: `success: false`, `errors[]` with `message`, and for parse errors `line`, - `column`, `sourceLines`, `suggestions`. Quote the `line` back to the user and fix the LoT. -- `Permission denied: You are not allowed to execute -x` → RBAC (see `broker-security`). -- `Unknown command: -x` → typo or command not wired for MQTT (`-mqttPacketTrace`, - `-checkActionUsage`, `-loadFolder` are dispatcher-only). -- If the publish itself is rejected (no Output at all), the user lacks `CommandCall`. - -## Command index - -### Routes -| Command | Args | Notes | -|---|---|---| -| `-addRoute` | `DEFINE ROUTE … WITH TYPE …` | Redeploy the **full** route to change one tag | -| `-removeRoute` | `` | | -| `-removeAllRoutes` | | **destructive** | -| `-listRoutes` | | `data[]`: `name`, `type`, `connection`, `health` | -| `-routeCode` | `` | Template LoT in `data` (contains template-only `ADD METADATA`) | -| `-listTemplates` | | Route types available on this build | -| `-checkRouteConnection` | `` | Connection probe details in `data` | -| `-connectionStatus` | | Text report of every route connection | -| `-routeCertificates` | `cert64:` | TLS cert management for routes | -| `-discoverAIProviders` | `[json]` | Detect local/cloud LLM providers | - -### Models -| Command | Args | -|---|---| -| `-addModel` | `DEFINE MODEL Name …` | -| `-removeModel` | `` | -| `-removeAllModels` | **destructive** | - -### Actions -| Command | Args | Notes | -|---|---|---| -| `-addAction` | `DEFINE ACTION Name …` | | -| `-removeAction` | `` | | -| `-removeAllActions` | | **destructive** | -| `-runAction` | ` [json]` | JSON = INPUT bindings, or `{"topic":"…","payload":…}` to simulate an inbound message; returns `data.traceId`, `status`, `published[]` | -| `-actionTrace` | `\|all\|off\|status\|remove ` | Streams to `$SYS/Coreflux/Actions//Trace` for 5 min | -| `-lotDiagnostic` | `model\|action\|route\|rule ` | Static + runtime diagnosis of a deployed entity | -| `-getPendingStatus` | | Models/actions waiting on missing dependencies | - -### Rules (RBAC) -| Command | Args | Notes | -|---|---|---| -| `-addRule` | `DEFINE RULE Name WITH PRIORITY N FOR [TO TOPIC "…"] …` | Priorities `0–99` are reserved | -| `-removeRule` | `` | Built-in rules cannot be removed | -| `-restoreRules` | | Restores `AllowPublishTopic`, `AllowSubscribeTopic`, `AllowConnect` — **confirm first** | - -### Python -| Command | Args | Notes | -|---|---|---| -| `-addPython` | `` starting with `# Script Name: Name` | Whole script as the payload | -| `-removePython` | `` | | -| `-installPythonPackage` | `` | pip install into the embedded runtime | -| `-listPythonPackages` | | | -| `-removeAllPythonScripts` | | **destructive** | - -### Panels & themes (LoTV dashboards) -| Command | Args | -|---|---| -| `-addPanel` / `-addVisu` | `DEFINE PANEL "Name" …` | -| `-removePanel` | `` | -| `-listPanels` | publishes to `$SYS/Coreflux/VoT/Panels/` | -| `-panelCode` | `` → LoT source | -| `-updateVisuState` | ` DRAFT\|PUBLISHED\|ARCHIVED` | -| `-addVisuFile` | `lot64:` | -| `-refreshVisu` | | -| `-addTheme` / `-removeTheme` / `-listThemes` / `-removeAllThemes` | | - -### Projects (see `lot-projects` skill) -| Command | Args | -|---|---| -| `-addProject` | `> [branch\|name] [load]` | -| `-removeProject` | `` — **destructive** | -| `-loadProject` / `-unloadProject` | `` / — | -| `-listProjects` | `data[]` projects with status | -| `-listEntities` | loaded entity manifest with `origin` (`adhoc` or project/file/cell) | -| `-getProject` | `` → base64 zip on `$SYS/Coreflux/Projects//download` | -| `-duplicateProject` | ` ` | -| `-projectCheckout` / `-projectPull` / `-projectPush` / `-projectStatus` / `-projectManifest` | ` [ref]` | - -### Users & groups -| Command | Args | Permission | -|---|---|---| -| `-addUser` | ` ` | `UserManagementCreation` | -| `-removeUser` | `` | `UserManagementRemove` — **destructive** | -| `-changeUserPassword` | ` ` | `UserManagementPasswordChange` | -| `-changeUserSettings` | ` ` e.g. `AllowedSystemConfiguration true` | `UserManagementUpdate` | -| `-addUserToGroup` / `-removeUserFromGroup` | ` ` | `UserManagementUpdate` | -| `-listUserGroups` | `` → `data.groups` | | - -### Environment & secrets -| Command | Args | Notes | -|---|---|---| -| `-setEnv` | `NAME=value` | Read in LoT with `GET ENV "NAME"` / `{env.NAME}` | -| `-removeEnv` / `-listEnv` | | | -| `-setSecret` | `NAME=value` | Encrypted at rest; `GET SECRET "NAME"` / `{secret.NAME}`; never echoed | -| `-removeSecret` / `-listSecrets` | | `-listSecrets` returns names only | - -### Audit, logs, licence, misc -| Command | Args | -|---|---| -| `-auditStatus` / `-auditQuery YYYY-MM-DD[\|filter]` / `-decryptAudit [\|exportPath]` | | -| `-addTraceLog` / `-listTraceLogs` / `-removeTraceLog` / `-removeAllTraceLogs` | trace-log sinks under `$SYS/Coreflux/Log/Traces/` | -| `-loadLicense` | `` | -| `-updateData` | refresh `$SYS` statistics (no reply) | - -## Destructive commands — confirm before running - -`-removeAllRoutes`, `-removeAllModels`, `-removeAllActions`, `-removeAllPythonScripts`, -`-removeAllThemes`, `-removeAllTraceLogs`, `-removeProject`, `-removeUser`, `-restoreRules`, -`-unloadProject` (when a project is active). The plugin's `beforeMCPExecution` hook blocks -them unless the user has explicitly asked in this conversation; state the exact command -and its consequence, get a yes, then run it. - -## Typical sequences - -**Deploy and verify an action** -1. `lot_lint` → `lot_deploy` (or `broker_command -addAction …`) -2. `broker_action_trace { action, payload: {"topic":"…","payload":…} }` -3. `mqtt_subscribe` on the output topic - -**Bring up a route** -1. `broker_route_template MODBUS_TCP` → fill `skeleton`, credentials via `GET SECRET` -2. `broker_command -setSecret PLC_PASS=…` if needed -3. `lot_deploy` → `broker_command -checkRouteConnection Name` → `mqtt_read_retained $SYS/Coreflux/Routes/Name/status` -4. `mqtt_subscribe plc1/read/#` to see polled tags - -**Investigate "nothing happens"** -1. `broker_overview` (routes health, pending status, action errors) -2. `broker_command -lotDiagnostic action Name` -3. `broker_command -getPendingStatus` — a model/action can wait on a missing dependency -4. `mqtt_read_retained $SYS/Coreflux/Actions/Name/Error` diff --git a/plugins/coreflux/skills/broker-observability/SKILL.md b/plugins/coreflux/skills/broker-observability/SKILL.md deleted file mode 100644 index 2956fc6..0000000 --- a/plugins/coreflux/skills/broker-observability/SKILL.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -name: broker-observability -description: Inspect and debug a running Coreflux broker over MQTT — the $SYS/Coreflux topic map (route status, action traces and errors, projects, cluster, version, stats), how to watch live data, verify that an action or route actually produced output, and a triage playbook for "it deployed but nothing happens". Use when troubleshooting, monitoring, or asked what a $SYS topic means. ---- - -# Coreflux Broker Observability - -The broker exposes its state as MQTT topics under `$SYS/Coreflux/…`. Reading them needs -`SubscribeSys` (root, admin, `AllowedSystemConfiguration`; `Command/Output` and -`Projects/#` also allow `AllowedUserManagement`). - -Tools: `mqtt_read_retained` (snapshot of retained state), `mqtt_subscribe` (live stream for a -bounded time), `broker_overview` (routes + projects + pending + action errors in one call), -`broker_action_trace` (arm trace, run, collect). - -## Topic map - -| Topic | Retained | Content | -|-------|----------|---------| -| `$SYS/Coreflux/Version` | yes | Broker version / build payload | -| `$SYS/Coreflux/License/Status` | yes | Tier, expiry, connection count | -| `$SYS/Coreflux/Stats` | — | Throughput, active connections | -| `$SYS/Coreflux/Comms/Logins` | — | Client connect events | -| `$SYS/Coreflux/Comms/Sessions` | yes | Session snapshot | -| `$SYS/Coreflux/Command/Output` | — | Command envelopes (see `broker-commands`) | -| `$SYS/Coreflux/Routes/` | yes | Deployed route LoT source | -| `$SYS/Coreflux/Routes//status` | — (~30 s + on change) | Route status JSON (below) | -| `$SYS/Coreflux/Routes//Tools`, `…/Tools/` | yes | MCP route tool catalogue | -| `$SYS/Coreflux/Routes//Capabilities`, `…/Metrics` | yes | LLM/agent route capabilities + usage | -| `$SYS/Coreflux/Routes//Certificates` | yes | OPC UA / TLS cert store summary | -| `$SYS/Coreflux/Routes//Events/` | — | Publish here to trigger a route event | -| `$SYS/Coreflux/Actions/` | yes (appears a few seconds after the `AddAction` envelope — re-read if empty) | Deployed action LoT source | -| `$SYS/Coreflux/Actions//Error` | yes | Last runtime error of the action | -| `$SYS/Coreflux/Actions//Trace` | — | Per-execution trace while `-actionTrace` is armed | -| `$SYS/Coreflux/Models/`, `Rules/` | yes | Deployed model / rule source | -| `$SYS/Coreflux/Visus/`, `VoT/Panels/`, `VoT/Themes/` | yes | Panel / theme definitions | -| `$SYS/Coreflux/Projects/list` | yes | All projects JSON | -| `$SYS/Coreflux/Projects/active` | yes | Active project (`{"status":"unloaded"}` when none) | -| `$SYS/Coreflux/Projects//status`, `…/manifest` | yes | Git status / content manifest | -| `$SYS/Coreflux/Projects//download` | no | One-shot base64 zip after `-getProject` | -| `$SYS/Coreflux/Entities/ownership` | yes | `type:name → {project,file,cell}`; missing key = ad-hoc entity | -| `$SYS/Coreflux/Cluster/{Role,IsLeader,Leader,Term,Members,Status}` | yes | Cluster state (7 s cadence) | -| `$SYS/Coreflux/Log/Traces//…` | — | Trace-log sinks created with `-addTraceLog` | -| `$SYS/Coreflux/Comms/PacketTrace//{In,Out}` | — | Raw packet trace (dispatcher-only command) | - -## Route status JSON - -```json -{ "name": "PLC1", "type": "MODBUS_TCP", "connection": "Connected", "health": "Green", - "errors": { "total": 5, "consecutive": 0, "rate": 0.0 }, - "messages": { "total": 1042, "succeeded": 1037, "failed": 5 }, - "lastActivity": "…", "lastSuccess": "…", "lastError": "…", - "uptime": "02:15:30", "connectedSince": "…", "timestamp": "…" } -``` - -`connection`: Disconnected | Connecting | Connected | Reconnecting. `health`: Green | Yellow -(error rate rising in the last 20 ops) | Red. `errors.consecutive > 0` with `Connected` means the -endpoint answers but rejects operations (bad query, wrong register, auth). - -## Action trace JSON - -```json -{ "action": "X", "traceId": "…", "trigger": { "topic": "…", "payload": "…", "clientId": "" }, - "timing": { "startUtc": "…", "endUtc": "…", "durationMs": 0 }, - "published": [ { "topic": "…", "payload": "…" } ], "result": "success", "error": null } -``` - -`-runAction X {"topic":"…","payload":…}` returns the same `traceId`, `status`, `published[]` -synchronously — the fastest way to check what an action would publish. - -## Triage playbook - -**Action deployed, no output** -1. `broker_action_trace { action, payload: {"topic": "", "payload": …} }` - — `published: []` means the logic never reached `PUBLISH` (check `IF` conditions and casts). -2. `mqtt_read_retained $SYS/Coreflux/Actions//Error` — runtime cast / null errors. -3. `broker_command -getPendingStatus` — action waiting on a model or Python script. -4. Wildcard mismatch: `ON TOPIC "a/+/b"` needs exactly one segment; `#` only at the end. -5. Timer actions cannot read `PAYLOAD`; use `GET TOPIC`. - -**Route Connected but data missing** -1. OT tags publish on `/`; `mqtt_subscribe plc1/read/#`. -2. `errors.consecutive` in status → wrong address / data type / query. -3. `broker_command -checkRouteConnection ` for a fresh probe. -4. Events fire on `PUBLISH` (not `KEEP`) to `SOURCE_TOPIC`; results need `DESTINATION_TOPIC`. - -**Route Disconnected / Reconnecting** -1. `mqtt_read_retained $SYS/Coreflux/Routes/` — verify host/port/`GET ENV` names. -2. `broker_command -listEnv`, `-listSecrets` — the referenced names must exist. -3. For TLS/OPC UA: `$SYS/Coreflux/Routes//Certificates` → pending rejections. - -**Model never publishes** -- A field must be `AS TRIGGER`; the trigger topic must receive a message; check - `$SYS/Coreflux/Models/` matches what you think is deployed. - -**Permission denied everywhere** -- `broker_connection` shows the user; see `broker-security` for the flags a command needs. - -**Nothing on `Command/Output` at all** -- The user lacks `CommandCall` or `SubscribeSys`; the broker may silently drop the publish. - -## Watching live data safely - -- `mqtt_subscribe` is bounded (`durationMs`, `maxMessages`); default 3 s / 50 messages. Widen - only when the user asks for a longer capture; high-rate topics are truncated to - `maxPayloadChars`. -- Prefer a concrete filter over `#` on production brokers. -- `mqtt_read_retained` returns only retained messages — ideal for state topics, useless for - event streams. - -## Publishing test data - -`mqtt_publish { topic, payload, retain }` — use `retain: true` when seeding a topic that a -rule reads with `TOPIC EXISTS` or that a `GET TOPIC` should find after restart. Say what you -published; test messages on production topics can trigger real routes. diff --git a/plugins/coreflux/skills/broker-security/SKILL.md b/plugins/coreflux/skills/broker-security/SKILL.md deleted file mode 100644 index 6e30920..0000000 --- a/plugins/coreflux/skills/broker-security/SKILL.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -name: broker-security -description: Secure a Coreflux broker — RBAC with LoT DEFINE RULE (priorities, scopes, DENY-wins, locked built-ins, connection admission by client id), users, groups and permission flags (AllowedSystemConfiguration, AllowedUserManagement, AllowedLogManagement), which flag each command needs, secrets vs env, TLS/mTLS, and how not to lock yourself out. Use when a command returns Permission denied, when designing topic ACLs, or when onboarding users/devices. ---- - -# Coreflux Broker Security - -Two mechanisms work together: - -| Mechanism | Granularity | Set with | -|-----------|-------------|----------| -| **Permission flags** on a user | coarse system access | `-changeUserSettings AllowedSystemConfiguration true` | -| **Groups** + **LoT rules** | per topic / per panel / per client id | `-addUserToGroup `, `-addRule DEFINE RULE …` | - -Flags: `AllowedSystemConfiguration` (routes/models/actions/rules/env/secrets/commands), -`AllowedUserManagement` (users, groups, `Command/Output`, `Projects/#`), `AllowedLogManagement` -(trace logs). `root` bypasses everything and is always admitted (anti-lockout). - -## What a command needs - -| Operation | Gate | -|-----------|------| -| Any `$SYS/Coreflux/Command` publish | `CommandCall` → root, admin, `AllowedUserManagement` or `AllowedSystemConfiguration` | -| Reading `$SYS/Coreflux/Command/Output` | same set (`SubscribeSys` carve-out) | -| Other `$SYS/#` subscriptions | root, admin, `AllowedSystemConfiguration` | -| `-addRoute`/`-addModel`/`-addAction`/`-addPanel`/`-addRule` | `*ManagementCreation` → `AllowedSystemConfiguration` | -| `-removeX` | `*ManagementRemove` | -| `-runAction` | `ActionManagementRun` | -| `-setEnv`, `-setSecret`, `-restoreRules`, `-addProject` | `SystemConfiguration` | -| `-addUser` / `-removeUser` / `-changeUserPassword` / `-changeUserSettings` / groups | `UserManagement{Creation,Remove,PasswordChange,Update}` → `AllowedUserManagement` | -| Trace logs | `LogManagement*` → `AllowedLogManagement` | - -`Permission denied: You are not allowed to execute -x` → grant the flag above or use a -different account. No `Command/Output` message at all → the publish was rejected -(`CommandCall`) or the client cannot subscribe (`SubscribeSys`). - -## Rules - -```lot -DEFINE RULE SensorAccess WITH PRIORITY 100 FOR Subscribe TO TOPIC "sensors/#" - IF USER HAS "AllowedSubscribe" OR USER IN GROUP "operators" THEN - ALLOW - ELSE - DENY -``` - -Evaluation: -1. Collect rules whose scope and topic match. -2. Only those with the **lowest priority number** decide. -3. Among them **DENY wins**. -4. No matching rule ⇒ **deny**. - -Bands: `0–99` **reserved / locked built-ins** (`-addRule` rejects them; cannot be removed or -overridden) · `100–999 999` user rules · `1 000 000` the three shipped seeds -(`AllowPublishTopic`, `AllowSubscribeTopic`, `AllowConnect`) which make a fresh broker open to -every *authenticated* client. Restrict with any user-band rule; it outranks the seeds. - -Scopes: `Connect` · `Publish` · `Subscribe` · `PublishSys` · `SubscribeSys` · `CommandCall` · -`ShellCommand` · `SystemConfiguration` · `UserManagement{Creation,Remove,PasswordChange,Update}` · -`RuleManagement{Creation,Remove}` · `ModelManagement{Creation,Remove}` · -`ActionManagement{Creation,Remove,Run}` · `RouteManagement{Creation,Remove}` · -`LogManagement{Creation,Update,Remove,Read}`. - -Conditions: `USER IS "name"` · `USER HAS AllowedX` · `USER IN GROUP "g"` · `CLIENTID IS "…"` · -`CLIENTID IS TOPIC POSITION N` · `CLIENTID MATCHES REGEX "^gw[0-9]+$"` (the `REGEX` keyword is -required; plain `MATCHES` is equality) · `ENDPOINT` · `TOPIC EXISTS ` (retained message -present) · `GET TOPIC IS "true"` · `AND` / `OR` / `NOT`. - -### Per-device topic isolation - -```lot -DEFINE RULE DeviceOwnTopics WITH PRIORITY 200 FOR Publish TO TOPIC "devices/+/#" - IF CLIENTID IS TOPIC POSITION 2 OR USER IS "root" THEN - ALLOW - ELSE - DENY -``` - -### Connection admission (`FOR Connect`, no topic) - -```lot -DEFINE RULE ImeiAdmission WITH PRIORITY 100 FOR Connect - IF CLIENTID MATCHES REGEX "^gw[0-9]{15}$" AND TOPIC EXISTS "devices/" + CLIENTID + "/allowed" THEN - ALLOW - ELSE - DENY -``` - -Maintain the allow-list with **retained** publishes (`mqtt_publish { retain: true }`), not `KEEP`. -`root` is always admitted, so a bad Connect rule is recoverable; `-restoreRules` resets the seeds. - -### Protecting `$SYS` - -Built-ins already deny `$SYS` to non-admins. To *widen* access (e.g. a dashboard user reading -route status) add a `SubscribeSys` rule in the user band: - -```lot -DEFINE RULE OpsRouteStatus WITH PRIORITY 100 FOR SubscribeSys TO TOPIC "$SYS/Coreflux/Routes/+/status" - IF USER IN GROUP "ops" THEN - ALLOW - ELSE - DENY -``` - -## Users and groups - -``` --addUser alice S3cure!pass --changeUserSettings alice AllowedSystemConfiguration true --addUserToGroup alice operators --listUserGroups alice --changeUserPassword alice N3wpass! --removeUser alice # destructive, confirm -``` - -Groups exist by being named; no create step. Prefer groups + rules for data access, flags only -for administration. Default credentials on a fresh broker are `root`/`coreflux` — tell the -user to change them before exposing the broker. - -## Secrets vs environment - -| | `-setEnv NAME=value` | `-setSecret NAME=value` | -|---|---|---| -| Storage | plain | encrypted at rest | -| Listing | values shown | names only | -| LoT | `GET ENV "NAME"`, `{env.NAME}` | `GET SECRET "NAME"`, `{secret.NAME}` | -| Use for | hosts, ports, topics, feature flags | passwords, API keys, tokens | - -Never write a literal password into LoT or a notebook; `lot_lint` warns on `WITH PASSWORD "…"`. -Never echo a secret value back to the user, and do not put secret values in `-setSecret` -examples committed to a repo. - -## Transport - -- `mqtts://host:8883` for TLS; the plugin's `COREFLUX_MQTT_TLS_INSECURE=true` only for - self-signed dev brokers. -- mTLS: broker validates client certificates when a CA is configured; `-routeCertificates` - manages route-side stores (OPC UA, TLS bridges). -- Audit trail: `-auditStatus`, `-auditQuery YYYY-MM-DD`, `-decryptAudit`. - -## Anti-lockout checklist - -- Keep `root` credentials somewhere safe before adding `Connect` or `CommandCall` rules. -- Test a new DENY rule with a second account before applying to production. -- Prefer allow-lists on narrow topics over broad denies at low priority numbers. -- `-restoreRules` is the escape hatch for the seeds; locked built-ins cannot be broken by rules. diff --git a/plugins/coreflux/skills/broker-tools/SKILL.md b/plugins/coreflux/skills/broker-tools/SKILL.md new file mode 100644 index 0000000..54911bd --- /dev/null +++ b/plugins/coreflux/skills/broker-tools/SKILL.md @@ -0,0 +1,322 @@ +--- +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. +--- + +# Broker Tools — Complete Reference + +## Which tool surface you are on + +There are two, with different tool names. Look at the tools you were given and use this table. + +| You are | Your tools are named | Skills come from | +|---------|----------------------|------------------| +| The Hub assistant, or any MCP client of the broker | `deploy_lot`, `validate_lot`, `add_action`, … — no prefix (see "MCP tools" below) | `load_skill` (Hub) or the MCP resource `coreflux://skills/` | +| A `DEFINE AGENT` running inside the broker | `broker__read_mqtt`, `broker__create_lot`, … — only the tools its `ADD TOOL` lines grant, plus `agent____ask` for each peer in `WITH AGENTS` | `broker__load_skill` (always present) | + +There are **no** UI tools on either surface: no `show_approval`, `show_code`, `show_progress`, +`show_option_list` or `create_artifact`. There is also no `run_python`, `list_topics`, +`get_topic_payload`, `publish_topic`, `action_errors`, `trace`, `capture_image`, and no +auto-generated `{RouteName}.trigger_*` / `.query` / `.store` / `{McpRouteName}.*` tools. Those +belonged to the retired `TYPE AGENT` route and do not exist — never call them, and never tell +the user they exist. + +**Insight vs Agent mode (Hub).** In Insight mode the Hub gives you only the tools the broker +marks read-only (the "Read-only" column below). In Agent mode you get every tool, and the Hub +asks the user to approve each call to a write tool before it runs — you do not request +approval yourself. Over a plain MCP client there is no approval step: the call runs. + +The MCP surface can also be narrowed by the operator (`EnableAllTools` false plus an +`EnabledTools` allowlist), so a tool listed here may be absent. Work with what you were given. + +--- + +## MANDATORY WORKFLOW — MCP / Hub assistant + +``` +1. load_skill("lot-actions") ← the skill for the kind you are writing (see list below) +2. explore_topics() / list_routes() / list_entities() + ← know what data flows and what already exists +3. validate_lot(argument=) ← every syntax, resolve, compile and lint error at once; + deploys nothing. Fix and re-validate until "valid": true +4. deploy_lot(source=) ← atomic: rolls back on the first failure +5. diagnose() ← connection status, action errors, pending work +``` + +Prefer **deploy_lot** over the per-entity `add_action` / `add_model` / `add_route` / +`add_rule` tools. For a new OT or database connector, prefer **provision_data_source** (omit +`definition` to fetch the template; pass it to deploy and check the connection) after +loading `lot-routes`. Panels and themes are not handled by deploy_lot: deploy them with +`add_panel` / `add_theme`. Things are deployed with `add_thing` (load `lot-things` first). + +**One logical change, one deploy.** If a deploy fails and only a syntax fix is needed (same +names, same intent, same topics, same trigger, same permission scope), fix the source, +re-validate and deploy again. In Hub Agent mode each write call is approved by the user; do +not ask again in chat for a pure syntax fix. + +## MANDATORY WORKFLOW — DEFINE AGENT + +``` +1. broker__load_skill("lot-actions") ← read the syntax FIRST +2. broker__read_lot() / broker__read_mqtt(topic="…/#") + ← read before you write; never replace an + entity you have not just read +3. broker__create_lot(target="action", lot=) + ← one entity per call +4. broker__read_lot(target=) ← confirm it is loaded +``` + +A DEFINE AGENT has no validate tool and no error-reading tool: `create_lot` returns the add +command's result (`success`, `message`, `errors`, `warnings`) — read it, fix, and call again. + +Which skill to load before each kind: +- Action → `lot-actions` · Model → `lot-models` · Route / connector → `lot-routes` + (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` + +--- + +## MCP tools — the consolidated four + +### explore_topics +Paginated topic discovery with inferred payload schema. Read-only; does not wait for live +publishes. Topics you may not subscribe to are filtered out. +Parameters: `filter` (optional topic prefix, e.g. `"sensors/"`), `limit` (default 50, max 200), +`cursor` (from the previous page's `next_cursor`), `response_format` (`concise` omits payloads; +`detailed` includes payload and field-level schema). + +### diagnose +Aggregate broker health in one call: connection status, action errors and pending status. +Takes no arguments. Partial results come back when one source fails, with the reason in +`errors[]`. Use it after every deploy. + +### provision_data_source +Provision an OT or database connector from a LoT `DEFINE ROUTE` (or `DEFINE CONNECTOR`). +Parameters: `route_type` (required, e.g. `POSTGRESQL`, `MODBUS_TCP`), `name` (required), +`definition` (optional — omit to fetch the connector-type template without deploying), +`filter` (optional topic prefix explored after a successful connection check; defaults to the +connector name). Write tool — not available in Insight mode. + +### deploy_lot +Atomically deploy `DEFINE ACTION`, `MODEL`, `ROUTE` (or `CONNECTOR`), `AGENT`, `RULE` and +`THING` blocks from one source string. Parameter: `source` (required). Blocks are added in +source order, one add command per DEFINE (consecutive DEFINE THING blocks are one `-addThing`); +place an agent after the LLM connector it uses. After each action, compile errors are +checked. On the first failure everything this call added is removed in reverse order and an +entity it overwrote is restored, and the result has `rolled_back: true`. Returns `success`, +`rolled_back`, `deployed`, `failed_entity`, `error`, `action_errors`. Panels and themes are not +accepted. Write tool — not available in Insight mode. + +--- + +## MCP tools — registry commands + +Every broker command that declares the MCP surface is a tool named after its CLI token in +snake_case (`-addAction` → `add_action`). These tools take **one** parameter: + +- `argument` (string) — passed to the command verbatim, exactly what follows the token on the + CLI. For `add_*` it is the full LoT block; for `remove_*`, `disable_*`, `enable_*` and + `check_route_connection` it is the entity name. +- Tools named `list_*`, plus `audit_query` and `get_pending_status`, also take `limit`, + `cursor` and `response_format` (`concise` | `detailed`) and return a page. + +Notes on the ones you will use most: + +- **validate_lot** — `argument` is one or more DEFINE blocks. Prefix with `--isolated` to check + the snippet against itself only (ignore live entities). Returns `valid`, `errors`, + `warnings` and every diagnostic with line and column. Deploys nothing. Read-only. +- **validate_lotnb** — the same for a `.lotnb` notebook JSON, or `--project `. +- **add_action / add_model / add_route / add_rule / add_panel / add_theme / add_agent** — + exactly ONE DEFINE block per call. Re-adding a name replaces it. For several entities use + deploy_lot. +- **add_thing / remove_thing / list_things** — Things deploy as one unit with their children. + Lead `add_thing`'s argument with `--dryRun` to get the plan without changing anything. Never + change a Thing's child entity directly: change the Thing and redeploy it. +- **disable_action / enable_action / disable_route / enable_route** — turn an entity off without + removing it. It is redeployed with a `DISABLE true` line, stays defined and listed, and + stays off across restarts. A disabled action's triggers do not fire and `run_action` refuses + it; a disabled connector opens no connection. `disable_agent` / `enable_agent` do the same + for agents. Prefer these over remove when the user wants something "stopped" or "paused". +- **list_entities** — every deployed entity (kind and name) with its project. Use before you + replace or remove anything. +- **list_routes** — connectors with health (Green/Yellow/Red), events and mappings. Agents are + not listed here. +- **list_agents** — agents with `name`, `llmRoute`, `status` (`online` / `offline` / `error`) and + `description`. +- **check_route_connection** — test one connector's connection by name. +- **run_action** — `argument` is `` or ` `. Each action is also + its own tool, `action_`, with a `payload` parameter; `list_action_tools` lists them. +- **action_trace** — `argument` is ``, `all`, `off`, `status` or + `remove `. Trace records are published (not retained) to + `$SYS/Coreflux/Actions//Trace`; tracing auto-expires after 5 minutes. Runtime errors + are retained on `$SYS/Coreflux/Actions//Error` and summarised by `diagnose`. +- **set_secret / set_env** — never put a credential value you were given in chat into a + tool call or into LoT. Tell the user which secret names to set; connectors read them with + `GET SECRET "…"` / `GET ENV "…"`. + +Hand-written MCP tools (named differently from their command): + +| Tool | Parameters | Purpose | +|------|-----------|---------| +| get_route_template | `routeType` (required) | Template for a connector type (POSTGRESQL, MODBUS_TCP, OPCUA, MCP, LLM, REST_API, …) or a REST API app code (AIRTABLE, SERVICENOW, SAP_S4HANA_CLOUD, …) | +| list_route_templates | `limit`, `cursor`, `response_format` | Every connector template and REST API app; apps carry `connector: true` | +| get_panel_code | `panelName` (required) | LoTV source of a deployed panel | +| add_trace_log | `traceConfig` (required) | `level=,expires=,messageContains=` | +| get_broker_info | — | Version, status and capabilities | +| get_available_commands | `limit`, `cursor`, `response_format` | Every command this MCP server can run | +| list_action_tools | `limit`, `cursor`, `response_format` | The `action_` tools | + +**Templates.** `get_route_template` returns placeholders in the form +`#Name,type,Description,regex,required#` — replace each with a real value. A REST API app is a +pre-built `TYPE REST_API` connector for one vendor; the generated LoT must keep +`WITH TYPE REST_API` (an app code is not a connector type). Templates end with an +`ADD METADATA` block (WITH IMAGE / WITH DESCRIPTION / WITH DOCLINK) — documentation only. +**NEVER include ADD METADATA in the connector LoT you deploy**; the parser rejects it. +Never hardcode credentials — use `GET ENV` / `GET SECRET`. + +There is no MCP tool that publishes an arbitrary MQTT message. To make something happen on a +topic, run an action (`run_action` / `action_`) that publishes it. + +--- + +## DEFINE AGENT tools (`broker__…`) + +A DEFINE AGENT sees `broker__load_skill` plus only what `ADD TOOL` grants (see `lot-agents`). +Every call is checked against the grant's topics or targets and against the broker ACL / +command permissions, as both whoever started the task and the agent's `DEFAULT_USER`. + +| Tool | Parameters | What it does | +|------|-----------|--------------| +| broker__load_skill | `name` | Load a skill body (no grant needed) | +| broker__read_mqtt | `topic` (filter, inside the granted TOPICS), `limit`, `cursor` | Latest payload of every known topic matching the filter. With a wildcard, payloads over 1024 chars are cut to a preview (`payload_truncated`); read the exact topic for the whole payload | +| broker__write_mqtt | `topic` (concrete, inside the granted TOPICS), `payload`, `retain` (default false) | Publish one message, checked against the Publish ACL (`PublishSys` for `$SYS/…`) | +| broker__read_lot | `target` (optional: a kind — action, model, route, rule, panel, agent, python, thing — or an exact entity name) | The loaded entity manifest, narrowed to the target | +| broker__create_lot | `target` (action, model, route, rule or panel — as granted), `lot` (one DEFINE block) | Create or replace one entity through its add command | +| broker__execute_routes | `target` (`.`), `parameters` (optional JSON object) | Trigger one connector event | +| broker__execute_actions | `target` (action name), `arguments` (optional JSON) | Run one granted action (`-runAction`) | +| agent____ask | `question` | Delegate a task to a peer agent | + +Things to know: +- Write grants must be `WITH LEVEL "write"`; confirmed writes (`write_confirm`) are not + available yet, so `create_lot` cannot author agents or skills, and nothing can author a Thing. +- `write_mqtt` refuses wildcards and every agent-bus topic; reach other agents only through + `agent____ask`. Publishing to `$SYS/…` needs a `PublishSys` rule — it is default-deny, + even for `root`, apart from a short built-in list (`$SYS/Coreflux/Command`, `Config/New`, + `Actions/+/Invoke`, `Actions/+/Run`, `Hub/#`). +- `execute_routes` is authorized as a `PublishSys` on + `$SYS/Coreflux/Routes//Events//Trigger`, so the principal needs a rule allowing + that topic. Events whose name starts with `_`, and events of an agent, are always refused. +- A connector event's result arrives on its `DESTINATION_TOPIC`; read it with `read_mqtt` if + that topic is granted. + +--- + +## MCP registry tools — full list + +Generated from the broker command registry. "Read-only" tools are the ones available in Hub +Insight mode. A DEFINE AGENT does not get these tools — only the `broker__` tools above. + +| Tool | Command | Read-only | +|------|---------|-----------| +| action_trace | `-actionTrace` | | +| add_action | `-addAction` | | +| add_agent | `-addAgent` | | +| add_model | `-addModel` | | +| add_panel | `-addPanel` | | +| add_project | `-addProject` | | +| add_python | `-addPython` | | +| add_route | `-addRoute` | | +| add_rule | `-addRule` | | +| add_theme | `-addTheme` | | +| add_thing | `-addThing` | | +| add_trace_log | `-addTraceLog` | | +| add_user | `-addUser` | | +| add_user_to_group | `-addUserToGroup` | | +| add_visu_file | `-addVisuFile` | | +| audit_export | `-auditExport` | | +| audit_query | `-auditQuery` | yes | +| audit_status | `-auditStatus` | yes | +| change_user_settings | `-changeUserSettings` | | +| check_action_usage | `-checkActionUsage` | yes | +| check_route_connection | `-checkRouteConnection` | yes | +| connection_status | `-connectionStatus` | yes | +| decrypt_audit | `-decryptAudit` | yes | +| disable_action | `-disableAction` | | +| disable_agent | `-disableAgent` | | +| disable_route | `-disableRoute` | | +| discover_ai_providers | `-discoverAIProviders` | yes | +| duplicate_project | `-duplicateProject` | | +| enable_action | `-enableAction` | | +| enable_agent | `-enableAgent` | | +| enable_route | `-enableRoute` | | +| get_panel_code | `-panelCode` | yes | +| get_pending_status | `-getPendingStatus` | yes | +| get_project | `-getProject` | yes | +| get_route_template | `-routeCode` | yes | +| install_python_package | `-installPythonPackage` | | +| list_agents | `-listAgents` | yes | +| list_entities | `-listEntities` | yes | +| list_env | `-listEnv` | yes | +| list_panels | `-listPanels` | yes | +| list_projects | `-listProjects` | yes | +| list_python_packages | `-listPythonPackages` | yes | +| list_route_templates | `-listTemplates` | yes | +| list_routes | `-listRoutes` | yes | +| list_secrets | `-listSecrets` | yes | +| list_themes | `-listThemes` | yes | +| list_things | `-listThings` | yes | +| list_trace_logs | `-listTraceLogs` | yes | +| list_user_groups | `-listUserGroups` | yes | +| load_folder | `-loadFolder` | | +| load_project | `-loadProject` | | +| lot_diagnostic | `-lotDiagnostic` | yes | +| mqtt_packet_trace | `-mqttPacketTrace` | | +| project_checkout | `-projectCheckout` | | +| project_manifest | `-projectManifest` | yes | +| project_pull | `-projectPull` | | +| project_push | `-projectPush` | | +| project_status | `-projectStatus` | yes | +| refresh_visu | `-refreshVisu` | | +| remove_action | `-removeAction` | | +| remove_agent | `-removeAgent` | | +| remove_all_actions | `-removeAllActions` | | +| remove_all_models | `-removeAllModels` | | +| remove_all_project_rules | `-removeAllProjectRules` | | +| remove_all_python_scripts | `-removeAllPythonScripts` | | +| remove_all_routes | `-removeAllRoutes` | | +| remove_all_themes | `-removeAllThemes` | | +| remove_all_trace_logs | `-removeAllTraceLogs` | | +| remove_env | `-removeEnv` | | +| remove_model | `-removeModel` | | +| remove_panel | `-removePanel` | | +| remove_project | `-removeProject` | | +| remove_python | `-removePython` | | +| remove_route | `-removeRoute` | | +| remove_rule | `-removeRule` | | +| remove_secret | `-removeSecret` | | +| remove_theme | `-removeTheme` | | +| remove_thing | `-removeThing` | | +| remove_trace_log | `-removeTraceLog` | | +| remove_user | `-removeUser` | | +| remove_user_from_group | `-removeUserFromGroup` | | +| restore_rules | `-restoreRules` | | +| route_certificates | `-routeCertificates` | yes | +| run_action | `-runAction` | | +| set_env | `-setEnv` | | +| set_secret | `-setSecret` | | +| unload_project | `-unloadProject` | | +| update_data | `-updateData` | | +| update_visu_state | `-updateVisuState` | | +| validate_lot | `-validateLot` | yes | +| validate_lotnb | `-validateLotnb` | yes | + +Plus `explore_topics` and `diagnose` (read-only), `provision_data_source` and `deploy_lot`, +`get_broker_info`, `get_available_commands`, `list_action_tools` (read-only) and one +`action_` tool per user action. + +Deliberately not exposed to any agent: licensing and enrollment (`-activateLicense`, +`-loadLicense`, `-refreshLicense`, `-enroll`), credentials (`-changeUserPassword`, +`-createMcpToken`, `-listMcpTokens`, `-revokeMcpToken`, `-brokerCertificates`), and the +`-auditFilter` modifier. If the user needs one of these, tell them to run it themselves. diff --git a/plugins/coreflux/skills/coreflux-cursor-tools/SKILL.md b/plugins/coreflux/skills/coreflux-cursor-tools/SKILL.md new file mode 100644 index 0000000..b53c4c8 --- /dev/null +++ b/plugins/coreflux/skills/coreflux-cursor-tools/SKILL.md @@ -0,0 +1,60 @@ +--- +name: coreflux-cursor-tools +description: How the Coreflux skills map onto this Cursor plugin — which coreflux-broker MCP tool to call where a skill names a broker MCP tool (deploy_lot, validate_lot, diagnose, get_route_template, run_action, …), how to send any broker command over MQTT and read its envelope, and how to deploy .lot/.lotnb files and projects. Read it together with broker-tools before calling a tool. +--- + +# Coreflux skills in Cursor + +The other skills in this plugin (`broker-tools`, `lot-actions`, `lot-models`, `lot-routes`, +`lot-rules`, `lot-agents`, `lot-things`, `lot-panels`, `lot-themes`, `python-scripts`) are +generated from the broker and shared with every Coreflux client. Their LoT syntax is the +broker's. Their **tool names are not this plugin's**: `broker-tools` describes the broker's own +MCP server and the tools a `DEFINE AGENT` is granted inside the broker. In Cursor you talk to +the broker through the `coreflux-broker` MCP server of this plugin, which sends commands over +MQTT. + +## Tool map + +| A skill says | Call in Cursor | +|--------------|----------------| +| `load_skill("x")` (either surface) | Read the skill `x` from this plugin | +| `validate_lot` | `lot_lint` (offline), then `broker_command { command: "-validateLot " }` for the broker's own check | +| `validate_lotnb` | `lot_lint { path }`, then `lotnb_deploy { path, dryRun: true }` | +| `deploy_lot` | `lot_deploy` — not atomic: read every envelope, it does not roll back | +| `add_action` / `add_model` / `add_route` / `add_rule` / `add_agent` / `add_thing` / `add_panel` / `add_theme` / `add_python` | `lot_deploy` (orders and lints for you; all `DEFINE THING` blocks, templates included, go as one `-addThing`) | +| `add_thing --dryRun` | `broker_command { command: "-addThing --dryRun " }` | +| `remove_*` | `lot_remove { kind, name }`, or `broker_command -removeX ` | +| `diagnose` | `broker_overview` | +| `explore_topics` | `mqtt_read_retained` (state) or a bounded `mqtt_subscribe` (live) | +| `get_route_template` / `provision_data_source` | `broker_route_template { type }`, then `lot_deploy` and `broker_command -checkRouteConnection ` | +| `run_action` / `action_trace` | `broker_action_trace { action, payload }` | +| any other registry tool (`list_routes`, `set_env`, `load_project`, …) | `broker_command` with the CLI token: `list_routes` → `-listRoutes`, `set_env` → `-setEnv NAME=value` | +| "no tool publishes an arbitrary MQTT message" | Here one does: `mqtt_publish`. Say what you publish on a non-local broker. | + +`broker_connection` tells you which broker profile and user you are on; `broker_list` / +`broker_use` / `broker_save` manage profiles. Name the profile whenever you deploy. + +## Commands and envelopes + +`broker_command` publishes a plain string to `$SYS/Coreflux/Command` (`-commandName args…`, +LoT bodies unquoted) and returns the JSON envelope from `$SYS/Coreflux/Command/Output`: +`success`, `message`, `data`, and on failure `errors[]` — parse errors carry `line` and +`column`. Fix the LoT to satisfy the broker's message; never retry the same text. +`Permission denied` is a reply. No reply at all means the publish was dropped (the user holds +none of `AllowedSystemConfiguration`, `AllowedUserManagement`, `AllowedLogManagement`), the user +cannot read `Command/Output`, or the command has no MQTT reply (`-updateData`, and today +`-checkActionUsage`, `-loadFolder`, `-mqttPacketTrace`). `broker_action_trace` runs the action for +real: every PUBLISH goes out. + +Destructive commands (`-removeAll*`, `-removeProject`, `-unloadProject`, `-removeUser`, +`-restoreRules`, …) are blocked by this plugin's hook unless the user asked for them in this +conversation. State the command and its consequence, get a yes, then run it. + +## Files and projects + +- `.lot` / `.lotnb` in the workspace: `lot_lint { path }` after every edit, + `lotnb_deploy { path, dryRun: true }` to see the plan, then `lotnb_deploy { path }`. +- A whole project folder: `project_upload { path, name, load: true }`; fetch one back with + `project_export { name, outputPath }`. +- Entities deployed with `lot_deploy` / `lotnb_deploy` are ad-hoc; entities loaded from a + project belong to it and leave with `-unloadProject`. diff --git a/plugins/coreflux/skills/lot-actions/SKILL.md b/plugins/coreflux/skills/lot-actions/SKILL.md new file mode 100644 index 0000000..44f7c8a --- /dev/null +++ b/plugins/coreflux/skills/lot-actions/SKILL.md @@ -0,0 +1,693 @@ +--- +name: lot-actions +description: How to write LOT actions: triggers, variables, topic operations, control flow, callable actions, and integrations (Python, MCP, LLM). +--- + +# LOT Actions — Complete Reference + +## CRITICAL SYNTAX — Read Before Writing Anything + +### Action names are NEVER quoted in DEFINE +``` +WRONG: DEFINE ACTION "Heartbeat" +RIGHT: DEFINE ACTION Heartbeat +``` + +### PUBLISH TOPIC uses WITH, never MESSAGE +``` +WRONG: PUBLISH TOPIC "t" MESSAGE "hello" +RIGHT: PUBLISH TOPIC "t" WITH "hello" + +WRONG: KEEP TOPIC "t" MESSAGE "value" +RIGHT: KEEP TOPIC "t" WITH "value" +``` + +The separator between topic and payload is always WITH (or TO or AS — all equivalent). +MESSAGE is a different keyword used elsewhere. Never use it with PUBLISH/KEEP TOPIC. + +### SET uses quoted variable names and WITH +``` +AVOID: SET performance TO ({a} / {b}) * 100 +RIGHT: SET "performance" WITH ({a} / {b}) * 100 + +AVOID: SET machineId TO TOPIC POSITION 3 +RIGHT: SET "machineId" WITH TOPIC POSITION 3 +``` + +Always write variable names in SET double-quoted, with WITH between the name and value. +The parser also accepts an unquoted name and TO (WITH, TO, AS and IN are the same token), +but the quoted WITH form is the canonical one — use it everywhere. + +### One DEFINE ACTION per broker.add_action call + +broker.add_action accepts exactly ONE DEFINE ACTION block per call. To deploy +multiple actions, make multiple calls - one per action - and check each call's +result before the next (a parse or compile failure comes back as success=false +with the errors) so a syntax failure in action 2 does not hide a problem in +action 1. Errors raised while an action runs are reported by broker.diagnose +(its action_errors field). To deploy several actions atomically, use +broker.deploy_lot instead. + +WRONG - three DEFINE ACTION blocks bundled into a single call: +``` +broker.add_action(argument=" +DEFINE ACTION PublishTopicAEvery5Seconds +ON EVERY 5 SECONDS DO + PUBLISH TOPIC \"topica\" WITH \"tick\" + +DEFINE ACTION ForwardTopicAToTopicB +ON TOPIC \"topica\" DO + PUBLISH TOPIC \"topicb\" WITH PAYLOAD + +DEFINE ACTION CountTopicBEvents +ON TOPIC \"topicb\" DO + SET \"currentCount\" WITH GET TOPIC \"state/topicb/count\" AS INT + KEEP TOPIC \"state/topicb/count\" WITH {currentCount} + 1 + PUBLISH TOPIC \"state/topicb/count/updated\" WITH {currentCount} + 1 +") +``` + +RIGHT - one broker.add_action call per action, each result checked before the next: +``` +broker.add_action(argument="DEFINE ACTION PublishTopicAEvery5Seconds\nON EVERY 5 SECONDS DO\n PUBLISH TOPIC \"topica\" WITH \"tick\"") +# check the result: success=false carries the parse/compile errors + +broker.add_action(argument="DEFINE ACTION ForwardTopicAToTopicB\nON TOPIC \"topica\" DO\n PUBLISH TOPIC \"topicb\" WITH PAYLOAD") +# check the result: success=false carries the parse/compile errors + +broker.add_action(argument="DEFINE ACTION CountTopicBEvents\nON TOPIC \"topicb\" DO\n SET \"currentCount\" WITH GET TOPIC \"state/topicb/count\" AS INT\n KEEP TOPIC \"state/topicb/count\" WITH {currentCount} + 1\n PUBLISH TOPIC \"state/topicb/count/updated\" WITH {currentCount} + 1") +# check the result: success=false carries the parse/compile errors +``` + +If the user asks for N related actions, that is N separate broker.add_action +calls - never one combined call, regardless of how tightly coupled the actions +are. + +--- + +## Basic Structure + +``` +DEFINE ACTION + DO + +``` + +Action names are plain identifiers — no quotes, no spaces. +**The trigger line sits at column 0 (same as `DEFINE`). The body is indented 4 spaces under the trigger.** +Do NOT indent the trigger line under `DEFINE ACTION` — that produces an unexpected INDENT token before the trigger and the parser rejects it. + +## Trigger Types + +### ON EVERY — Interval Timer + +Runs the action body repeatedly at a fixed interval. + +``` +DEFINE ACTION Heartbeat +ON EVERY 10 SECONDS DO + PUBLISH TOPIC "system/heartbeat" WITH TIMESTAMP "ISO" +``` + +All valid time units: +``` +ON EVERY 500 MILLISECONDS DO -- sub-second polling +ON EVERY 5 SECONDS DO -- fast cyclic (sensors, watchdog) +ON EVERY 1 MINUTES DO -- moderate polling +ON EVERY 2 HOURS DO -- periodic aggregation +ON EVERY 1 DAYS DO -- daily tasks +ON EVERY 1 WEEKS DO -- weekly tasks +ON EVERY 1 MONTHS DO -- also YEARS; singular forms (SECOND, MINUTE…) and MS work too +``` +The unit is not checked when the action is deployed: a misspelled unit (`5 SECS`) deploys +cleanly and fails only when scheduled ("Unsupported time unit" in the broker log). + +### ON EVERY \ AT — Scheduled (Day-of-Week + Time) + +Runs once at a specific time on the specified day(s). Time is in 24-hour format "HH:mm:ss". + +``` +-- Specific weekdays: +DEFINE ACTION MondayMeeting +ON EVERY MONDAY AT "09:00:00" DO + PUBLISH TOPIC "calendar/reminder" WITH "Weekly meeting in 30 minutes" + +-- All weekdays (Monday–Friday): +DEFINE ACTION DailyShiftStart +ON EVERY WEEKDAY AT "06:00:00" DO + PUBLISH TOPIC "shift/status" WITH "active" + KEEP TOPIC "state/shift" WITH "day" + +-- Weekend only (Saturday + Sunday): +DEFINE ACTION WeekendMode +ON EVERY WEEKEND AT "08:00:00" DO + KEEP TOPIC "state/mode" WITH "weekend" + +-- Every day of the week independently: +DEFINE ACTION SaturdayBackup +ON EVERY SATURDAY AT "02:00:00" DO + PUBLISH TOPIC "backup/trigger" WITH "start" +``` + +Valid day keywords: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, WEEKDAY, WEEKEND + +Full day-of-week example set: +``` +ON EVERY MONDAY AT "07:00:00" DO +ON EVERY TUESDAY AT "07:00:00" DO +ON EVERY WEDNESDAY AT "07:00:00" DO +ON EVERY THURSDAY AT "07:00:00" DO +ON EVERY FRIDAY AT "07:00:00" DO +ON EVERY SATURDAY AT "10:00:00" DO +ON EVERY SUNDAY AT "10:00:00" DO +ON EVERY WEEKDAY AT "07:00:00" DO -- Mon-Fri only +ON EVERY WEEKEND AT "10:00:00" DO -- Sat-Sun only +``` + +### ON TOPIC (MQTT-triggered) +``` +DEFINE ACTION ProcessSensor +ON TOPIC "sensors/+/data" DO + SET "deviceId" WITH TOPIC POSITION 2 + SET "temp" WITH PAYLOAD AS DOUBLE + IF {temp} > 30 THEN + PUBLISH TOPIC "alerts/" + {deviceId} WITH "High temperature: " + {temp} +``` +Use `+` for single-level wildcard in topic patterns. +PAYLOAD gives the message content. TOPIC POSITION N extracts segment N (1-based). + +### ON CHANGE (MQTT-triggered only when payload bytes change) +``` +DEFINE ACTION ProcessSensorOnChange +ON CHANGE "sensors/+/data" DO + SET "temp" WITH PAYLOAD AS DOUBLE + PUBLISH TOPIC "sensors/processed" WITH {temp} +``` +Same topic patterns as ON TOPIC. Fires on first publish per topic, then only when the payload differs from the last cached value. Use ON TOPIC for every message; use ON CHANGE to skip unchanged repeats. (Not the same as Visu slider ON CHANGE DO PUBLISH — that is client UI only.) + +### ON START (runs once at broker startup) +``` +DEFINE ACTION Init +ON START DO + PUBLISH TOPIC "system/status" WITH "online" +``` +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. + +### 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. + +``` +DEFINE ACTION CalcAverage +INPUT value1 AS DOUBLE +INPUT value2 AS DOUBLE +DO + SET "avg" WITH ({value1} + {value2}) / 2 +RETURN + OUTPUT avg +``` + +Multiple outputs (one OUTPUT per line): +``` +DEFINE ACTION AnalyzeReading +INPUT value AS DOUBLE +INPUT threshold AS DOUBLE +DO + SET "is_above" WITH ({value} > {threshold}) + SET "difference" WITH ({value} - {threshold}) + SET "percentage" WITH ({value} / {threshold} * 100) +RETURN + OUTPUT is_above + OUTPUT difference + OUTPUT percentage +``` + +The number of RETURN variables at the CALL site must match the number of OUTPUTs declared +by the called action — otherwise the upload fails with a clear validation error. + +## Variable Operations + +### SET — assign a value +``` +SET "myVar" WITH "hello" +SET "temp" WITH GET TOPIC "sensor/temp" AS DOUBLE +SET "data" WITH GET JSON "readings.temperature" IN PAYLOAD AS DOUBLE +SET "host" WITH GET ENV "DB_HOST" +SET "pass" WITH GET SECRET "DB_PASSWORD" +``` + +### GET TOPIC — read an MQTT topic's current value +``` +SET "value" WITH GET TOPIC "sensors/temperature" AS DOUBLE +``` +Type casting with AS: INT, DOUBLE (or FLOAT), BOOL, STRING, TIMESTAMP, OBJECT, ARRAY. +`GET TOPIC … AS ARRAY` in a SET currently fails to compile; read it AS STRING and parse it. + +Lookup order (same in actions and rules): +1. In-flight KEEP/PUBLISH this action has not flushed yet +2. The payload that triggered this action (when reading that topic) +3. Live cache — latest KEEP or PUBLISH. PUBLISH replaces KEEP +4. MQTT retain — fallback after restart, before the cache is warm again + +Use KEEP for state another action (or a rule) will GET TOPIC without notifying subscribers. Use TOPIC EXISTS in rules when the grant must be an MQTT retained message. + +In a cluster, a KEEP is copied to every node and saved to disk, so GET TOPIC on any node returns it. The last write by timestamp wins, so a counter updated from two nodes can lose an update: keep one writer per topic. + +### GET JSON — extract from JSON payload +``` +SET "temp" WITH GET JSON "data.temperature" IN PAYLOAD AS DOUBLE +SET "name" WITH GET JSON "device.name" IN {myJson} +SET "ok" WITH (GET JSON "success" IN {result} AS BOOL) +``` +Source must be a JSON string (PAYLOAD, a variable, or CALL PYTHON RETURN AS). Missing keys +and JSON null become "null"; AS BOOL / AS INT / AS DOUBLE safe-parse to false / 0 / 0.0 +instead of throwing. AS STRING yields the text null. + +### GET MODEL — fetch model data from a database route +``` +SET "data" WITH GET MODEL "SensorData" FROM "MyDB" WHERE id EQUALS "sensor1" +PUBLISH TOPIC "sensors/result" WITH GET MODEL "SensorData" FROM "MyDB" +``` +The query runs synchronously inside the action; with no matching row the result is an empty object. + +## Topic Operations + +### PUBLISH vs KEEP — When to Use Which + +Use **PUBLISH** when the message should flow to external consumers: +- Sending data to database routes (route events listen on MQTT and fire on arrival) +- Sending alerts, events, or updates to dashboards and UIs +- Triggering other systems or services +- One-time notifications + +Use **KEEP** when the value is shared internal state between actions: +- Storing a counter, mode flag, or last-known value that another action needs to read +- Values that actions read back with GET TOPIC without broadcasting to subscribers + +KEEP stores the value in the broker cache without MQTT delivery. A later PUBLISH of the same topic replaces it and notifies subscribers. +PUBLISH delivers to current subscribers. It is not MQTT retain (TOPIC EXISTS does not see KEEP). + +``` +-- Use KEEP for state between actions: +DEFINE ACTION IncrementCounter +ON TOPIC "counter/increment" DO + SET "current" WITH GET TOPIC "state/counter" AS INT + KEEP TOPIC "state/counter" WITH {current} + 1 + +-- Use PUBLISH to drive routes, UIs, other systems: +DEFINE ACTION ForwardToDatabase +ON TOPIC "sensors/+/data" DO + SET "zone" WITH TOPIC POSITION 2 + SET "val" WITH PAYLOAD AS DOUBLE + PUBLISH TOPIC "db/insert/readings/" + {zone} WITH {val} +``` + +### PUBLISH TOPIC — non-retained, fires to current subscribers +``` +PUBLISH TOPIC "output/data" WITH "value: " + {temp} +PUBLISH TOPIC "events/alert" WITH TIMESTAMP "ISO" +PUBLISH TOPIC "sensors/" + {zone} + "/processed" WITH {result} +PUBLISH TOPIC "output/state" WITH {state} RETAIN -- optional MQTT retain flag +PUBLISH TOPIC "output/cmd" WITH {cmd} WITH RETAIN QOS1 -- optional RETAIN and QOS0/QOS1/QOS2 +``` +LoT has no JSON object literal (`WITH { "temp": {temp} }` is rejected). Build a structured +payload with PUBLISH MODEL (below) or return a dict from CALL PYTHON. Do not hand-build +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. + +### KEEP TOPIC — stored without broadcast, readable by GET TOPIC from any action +``` +KEEP TOPIC "state/mode" WITH "running" +KEEP TOPIC "state/lastTemp" WITH {temp} +KEEP TOPIC "device/" + {id} + "/config" WITH {config} +``` + +Reading a KÉEPed value from another action: +``` +SET "mode" WITH GET TOPIC "state/mode" AS STRING +SET "lastTemp" WITH GET TOPIC "state/lastTemp" AS DOUBLE +``` + +### KEEP ENV / KEEP SECRET — persist environment variables +``` +KEEP ENV "COUNTER" WITH {counter} + 1 +KEEP SECRET "API_KEY" WITH "sk-abc123" +``` + +### DELETE ENV / DELETE SECRET +``` +DELETE ENV "OLD_CONFIG" +DELETE SECRET "OLD_KEY" +``` + +## Control Flow + +### IF / THEN / ELSE +``` +IF {temp} > 30 THEN + PUBLISH TOPIC "alert" WITH "Hot!" +ELSE + PUBLISH TOPIC "status" WITH "Normal" +``` +Operators: ==, !=, >, <, >=, <=, AND, OR, CONTAINS, MATCHES REGEX "pattern", NOT MATCHES REGEX "pattern". +Word forms also work: EQUALS / IS (==), NOT EQUALS (!=), GREATER THAN / ABOVE (>), LESS THAN / BELOW (<). +There is no prefix NOT (`IF NOT {x} ...` is rejected) and no STARTS_WITH / ENDS_WITH — use +`MATCHES REGEX "^abc"` / `MATCHES REGEX "abc$"`. Do not compare a number with TRUE/FALSE +(type mismatch at deploy). + +### ELSE IF — multi-way branch (there is no SWITCH statement in actions) +``` +IF {status} == "on" THEN + PUBLISH TOPIC "led" WITH "1" +ELSE IF {status} == "off" THEN + PUBLISH TOPIC "led" WITH "0" +ELSE + PUBLISH TOPIC "led" WITH "unknown" +``` +`ELIF` is accepted as a synonym for `ELSE IF`. + +### REPEAT … UNTIL — loop (also LOOP / ITERATE) +``` +SET "i" WITH 0 +REPEAT + SET "i" WITH {i} + 1 +UNTIL {i} >= 3 +``` + + + +## String Transformations + +### FILTER (regex extraction) +``` +SET "digits" WITH FILTER PAYLOAD USING REGEX "[0-9]+" +``` + +### REPLACE +``` +SET "clean" WITH REPLACE "\n" WITH " " IN PAYLOAD +``` +The source after IN is PAYLOAD, a variable, or a string. `IN RESULT` is only valid inside a chain. + +### TRIM +``` +SET "text" WITH PAYLOAD TRIM +``` +TRIM takes no argument and trims the value before it — `TRIM PAYLOAD` is rejected. + +### AND THEN (chaining) +``` +SET "result" WITH FILTER PAYLOAD USING REGEX "[0-9]+" AND THEN TRIM +SET "tidy" WITH FILTER PAYLOAD USING REGEX "[a-z ]+" AND THEN REPLACE " " WITH "_" IN RESULT +``` +The chain keyword is two words, `AND THEN` (`AND_THEN` is rejected). Start the chain with +FILTER or REPLACE; RESULT refers to the output of the previous step. + +## Expressions + +### Arithmetic: +, -, *, /, % +``` +SET "result" WITH {a} + {b} * 2 +``` + +### String concatenation +``` +SET "msg" WITH "Temperature: " + {temp} + "°C" +``` + +### RANDOM +``` +SET "id" WITH RANDOM UUID +SET "roll" WITH RANDOM INT BETWEEN 1 AND 6 +SET "val" WITH RANDOM DOUBLE BETWEEN 0.0 AND 1.0 +``` + +### TIMESTAMP +``` +SET "now" WITH TIMESTAMP "ISO" -- 2026-01-31T14:05:09.123Z +SET "utc" WITH TIMESTAMP "UTC" -- 2026-01-31 14:05:09 +SET "unix" WITH TIMESTAMP "UNIX" -- seconds since epoch +SET "ms" WITH TIMESTAMP "UNIX-MS" -- milliseconds since epoch +SET "day" WITH TIMESTAMP "yyyy-MM-dd" -- any other string is a .NET date format +``` +All timestamps are UTC; there is no local-time format. An unrecognised string is used as a +.NET custom format, so a typo yields odd text rather than an error. + +## Integration Calls + +### CALL ACTION — invoke another action +``` +CALL ACTION "CalcAvg" WITH value1 = {a}, value2 = {b} RETURN avg +``` +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 +``` +CALL PYTHON "utils.calculate" + WITH ({value}) + RETURN AS {result} +``` +Format: "scriptName.functionName". Script must be deployed with broker.add_python first. +WITH and RETURN AS go on their own indented lines under CALL PYTHON. The one-line form +`CALL PYTHON "utils.calculate" WITH (...) RETURN AS {result}` is rejected by the parser. +The same indented layout applies to CALL MCP, CALL LLM and CALL AGENT. + +### CALL MCP — invoke an MCP tool +``` +CALL MCP "MyMcpRoute.search" + WITH (query = "test") + RETURN AS {result} +``` +"RouteName.ToolName" in one string; named arguments inside parentheses. + +### CALL LLM — invoke an LLM route +``` +CALL LLM "MyLlm.generate" + WITH (prompt = "Summarize: " + {data}) + RETURN AS {answer} +``` + +### CALL AGENT — invoke an agent +``` +CALL AGENT "MyAgent.execute" + WITH (task = "Analyze data") + RETURN AS {result} +``` + +### TRIGGER — trigger a route event +``` +TRIGGER "MyDB" WITH "sensor1" FOR "ReadSensors" +``` +Order: route name, WITH the data to send, FOR the route event/mapping name. + +## PUBLISH MODEL — publish a model instance +``` +PUBLISH MODEL SensorData TO "output/data" WITH + temperature = {temp} + status = "active" +``` + +## Python Integration + +Use Python when LOT expressions aren't enough: statistics, complex string manipulation, +JSON reshaping, external library math, or multi-step data processing. + +### Step 1 — Write and deploy the script (once) +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). + +```python +# Script Name: SensorUtils + +import json, statistics + +def analyze(readings_json): + """Return mean/min/max for a JSON array of numbers.""" + readings = json.loads(readings_json) if isinstance(readings_json, str) else readings_json + if not readings: + return {"success": False, "error": "empty"} + return { + "success": True, + "mean": round(statistics.mean(readings), 2), + "min": min(readings), + "max": max(readings), + "count": len(readings) + } + +def classify(value, low, high): + """Return 'low', 'normal', or 'high' based on thresholds.""" + v = float(value) + if v < float(low): return "low" + if v > float(high): return "high" + return "normal" +``` + +### Step 2 — Call from a LOT action +``` +DEFINE ACTION AnalyzeSensorBatch +ON TOPIC "sensors/batch" DO + SET "readings" WITH PAYLOAD + CALL PYTHON "SensorUtils.analyze" + WITH ({readings}) + RETURN AS {stats} + PUBLISH TOPIC "sensors/stats" WITH {stats} + +DEFINE ACTION ClassifyReading +ON TOPIC "sensors/+/temp" DO + SET "temp" WITH PAYLOAD AS DOUBLE + CALL PYTHON "SensorUtils.classify" + WITH ({temp}, 15, 75) + RETURN AS {level} + IF {level} == "high" THEN + PUBLISH TOPIC "alerts/temp" WITH "HIGH: " + {temp} +``` + +### Rules for CALL PYTHON +- Format: `CALL PYTHON "ScriptName.function_name"`, then `WITH (arg1, arg2)` and + `RETURN AS {result}` each on its own line indented under it +- Arguments are positional — order must match the function signature +- Pass scalars or variables. An array literal argument (`WITH ([1, 2, 3])`) fails to compile; + pass a JSON string variable and `json.loads` it in Python. PAYLOAD and untyped values + arrive as Python `str`; use `AS DOUBLE` / `AS INT` in LoT or `float()` in Python +- RETURN AS is always a JSON string. A Python dict / list / number / bool is serialized + automatically — do not require json.dumps(). A Python str (including json.dumps output) + is kept as-is. None becomes null. +- Parse fields with GET JSON "key" IN {result} AS BOOL|INT|DOUBLE|STRING. Missing keys + do not crash: typed extracts become false/0; AS STRING is the text null. +- PUBLISH … WITH {result} sends that same JSON string. +- Script must be deployed with `broker.add_python` before calling it +- If the function raises, or runs past 30 seconds, the call logs an error and the result is + the text null — the action keeps running. Check `GET JSON "success"` instead of assuming data +- Imports: the standard library is available (`math`, `statistics`, `json`, `datetime`, + `collections`, `re`, `csv`, `hashlib`, `base64`, …). Third-party packages must be installed + with `broker.install_python_package` first; a script whose top-level import is missing is + rejected by add_python ("Python import failed") + +### Parsing the returned JSON in LOT +``` +DEFINE ACTION ProcessStats +ON TOPIC "sensors/run" DO + SET "raw" WITH GET TOPIC "sensors/batch/data" + CALL PYTHON "SensorUtils.analyze" + WITH ({raw}) + RETURN AS {stats} + SET "ok" WITH (GET JSON "success" IN {stats} AS BOOL) + IF {ok} EQUALS TRUE THEN + SET "avg" WITH GET JSON "mean" IN {stats} AS DOUBLE + SET "lo" WITH GET JSON "min" IN {stats} AS DOUBLE + SET "hi" WITH GET JSON "max" IN {stats} AS DOUBLE + PUBLISH TOPIC "sensors/summary" WITH {stats} + IF {hi} > 90 THEN + PUBLISH TOPIC "alerts/overtemp" WITH "Max: " + {hi} +``` + +### PUBLISH MODEL + Python (combined pattern) +``` +DEFINE MODEL SensorAnalysis COLLAPSED + ADD STRING "timestamp" WITH TIMESTAMP "UTC" + ADD STRING "zone" + ADD DOUBLE "mean" + ADD DOUBLE "min" + ADD DOUBLE "max" + ADD STRING "status" + +DEFINE ACTION AnalyzeZone +ON TOPIC "zones/+/readings" DO + SET "zone" WITH TOPIC POSITION 2 + SET "raw" WITH PAYLOAD + CALL PYTHON "SensorUtils.analyze" + WITH ({raw}) + RETURN AS {stats} + SET "avg" WITH GET JSON "mean" IN {stats} AS DOUBLE + SET "lo" WITH GET JSON "min" IN {stats} AS DOUBLE + SET "hi" WITH GET JSON "max" IN {stats} AS DOUBLE + SET "status" WITH "normal" + IF {hi} > 85 THEN + SET "status" WITH "critical" + PUBLISH MODEL SensorAnalysis TO "zones/" + {zone} + "/analysis" WITH + zone = {zone} + mean = {avg} + min = {lo} + max = {hi} + status = {status} +``` + +## Complete Example — Sensor Monitor with Alerting +``` +DEFINE ACTION SensorMonitor +ON TOPIC "factory/sensors/+/temperature" DO + SET "zone" WITH TOPIC POSITION 3 + SET "temp" WITH PAYLOAD AS DOUBLE + SET "ts" WITH TIMESTAMP "ISO" + IF {temp} > 85 THEN + PUBLISH TOPIC "factory/alerts/" + {zone} WITH "CRITICAL: " + {temp} + "°C at " + {ts} + KEEP TOPIC "factory/alerts/" + {zone} + "/last" WITH {temp} + ELSE + IF {temp} > 70 THEN + PUBLISH TOPIC "factory/warnings/" + {zone} WITH "WARNING: " + {temp} + "°C" +``` + +## Complete Example — Callable Conversion Utility +``` +DEFINE ACTION CelsiusToFahrenheit +INPUT celsius AS DOUBLE +DO + SET "fahrenheit" WITH {celsius} * 1.8 + 32 +RETURN + OUTPUT fahrenheit +``` + +## Common Mistakes + +| WRONG | RIGHT | Why | +|-------|-------|-----| +| DEFINE ACTION "Heartbeat" | DEFINE ACTION Heartbeat | Action names are plain identifiers — no quotes | +| PUBLISH TOPIC "t" MESSAGE "v" | PUBLISH TOPIC "t" WITH "v" | MESSAGE is not valid here — use WITH | +| KEEP TOPIC "t" MESSAGE "v" | KEEP TOPIC "t" WITH "v" | Same — WITH, not MESSAGE | +| SET x TO "value" | SET "x" WITH "value" | Accepted, but quoted name + WITH is the canonical form | +| SET x "value" | SET "x" WITH "value" | SET requires WITH between name and value | +| TOPIC POSITION 0 | TOPIC POSITION 1 | 1-based; 0 deploys but yields an empty string | +| IF {x} > 5 | IF {x} > 5 THEN | IF always requires THEN | +| ON EVERY 10 SECONDS | ON EVERY 10 SECONDS DO | Trigger always requires DO | +| `DEFINE ACTION X\n ON EVERY 1 SECONDS DO` | `DEFINE ACTION X\nON EVERY 1 SECONDS DO` | Trigger sits at column 0, NOT indented under DEFINE. Indenting the trigger creates a stray INDENT token before the trigger and the parser rejects the action. | +| temp (no braces) | {temp} | Variables always need curly braces | +| RETURN OUTPUT result | RETURN then OUTPUT result on separate lines | Single-line RETURN OUTPUT is rejected | +| RETURN OUTPUT a, b, c | RETURN then one OUTPUT per line | Comma-separated outputs are rejected | +| CALL PYTHON "S.f" WITH (x) RETURN AS {r} | WITH / RETURN AS on indented lines below | One-line CALL PYTHON/MCP/LLM/AGENT is rejected | +| 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 | + +### Trigger indentation - the most common AI mistake + +The trigger line (`ON EVERY ...`, `ON TOPIC ...`, `ON START`) MUST be at the +same column as `DEFINE ACTION`. Only the body is indented. Indenting the trigger +under `DEFINE ACTION` produces a stray INDENT token before the trigger and the +parser rejects the action. + +``` +-- WRONG: trigger indented under DEFINE (parser rejects with an unexpected INDENT) +DEFINE ACTION ToggleInput + ON EVERY 1 SECONDS DO + SET "current" WITH GET TOPIC "plc/input" AS BOOL + IF {current} == true THEN + PUBLISH TOPIC "plc/input" WITH false + ELSE + PUBLISH TOPIC "plc/input" WITH true + +-- RIGHT: trigger at column 0, body indented 4 spaces +DEFINE ACTION ToggleInput +ON EVERY 1 SECONDS DO + SET "current" WITH GET TOPIC "plc/input" AS BOOL + IF {current} == true THEN + PUBLISH TOPIC "plc/input" WITH false + ELSE + PUBLISH TOPIC "plc/input" WITH true +``` + +The same rule applies to every trigger type - `ON TOPIC`, `ON EVERY N `, +`ON EVERY AT`, `ON START`. Callable actions use INPUT lines instead of ON. +When emitting the definition as a +JSON string, this means `\nON EVERY ...\n BODY` - never `\n ON EVERY ...\n BODY`. diff --git a/plugins/coreflux/skills/lot-agents/SKILL.md b/plugins/coreflux/skills/lot-agents/SKILL.md new file mode 100644 index 0000000..66e02f2 --- /dev/null +++ b/plugins/coreflux/skills/lot-agents/SKILL.md @@ -0,0 +1,153 @@ +--- +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. +--- + +# LOT Agents — DEFINE AGENT + +An agent is its own LoT entity, not a connector. It runs on a `TYPE LLM` connector that holds the +provider, model and key, and it can do nothing until `ADD TOOL` grants a tool. It is deployed +with `-addAgent`, never `-addRoute`. An in-broker agent cannot deploy one: `create_lot` refuses +target `agent`. Draft the block for a person to deploy instead. + +## CRITICAL SYNTAX + +- `DEFINE AGENT ` — unquoted name: letters, digits, `_` and `-`. +- `USES LLM ROUTE ` (or `USES LLM CONNECTOR `) is the **first** body line, unquoted. That connector must be `TYPE LLM`. +- `WITH DEFAULT_USER ""` is **required**. It is the broker user a task runs as when no MQTT + user started it (a `CALL AGENT` from an action). There is no implicit admin. +- Every other value is quoted: `WITH DESCRIPTION "…"`. `GET SECRET` / `GET ENV` work anywhere. +- 4-space indent; `ADD TOOL` settings are indented one more level. +- There is no `DEFINE ROUTE … WITH TYPE AGENT` and no `AGENT_CONFIG`; both were removed. + +## Minimal agent + +``` +DEFINE ROUTE Gpt WITH TYPE LLM + ADD LLM_CONFIG + WITH PROVIDER "openai" + WITH MODEL "gpt-5.5" + WITH API_KEY GET SECRET "OPENAI_API_KEY" + +DEFINE AGENT LineAssistant + USES LLM ROUTE Gpt + WITH DESCRIPTION "Answers questions about production line 1" + WITH DEFAULT_USER "line1-agent" + WITH SYSTEM_PROMPT "You watch line 1. Answer from live data and say when data is stale." + WITH INTERACTION_TOPIC "agents/line1" + ADD TOOL "read_mqtt" + WITH TOPICS "lines/1/#" + ADD TOOL "write_mqtt" + WITH TOPICS "reports/line1/#" + WITH LEVEL "write" +``` + +Deploy the LLM connector first, then the agent. + +## Clauses + +| Clause | Default | Meaning | +|---|---|---| +| `USES LLM ROUTE ` | required | The `TYPE LLM` connector the agent runs on | +| `WITH DEFAULT_USER` | required | Principal when no MQTT user started the task | +| `WITH DESCRIPTION` | `"Agent ."` | Card text; peers and the Hub read it | +| `WITH SYSTEM_PROMPT` | — | Persona and operating instructions | +| `WITH GUARDRAILS` | — | Text appended to the prompt. Prompt, not enforcement | +| `WITH AGENTS` | none | Comma-separated peers it may delegate to | +| `WITH MAX_ITERATIONS` | `10` | Tool calls per run | +| `WITH MAX_TOKENS` | `50000` | Token budget for the whole task tree | +| `WITH TASK_TIMEOUT` | `600` | Seconds before `deadline_exceeded` | +| `WITH MAX_IN_FLIGHT` | `4` | Concurrent tasks; more MQTT or delegated tasks answer `agent_busy` | +| `WITH QUEUE_SIZE` | `64` | `CALL AGENT` calls that wait for a slot when it is busy (0 = refuse at once) | +| `WITH QUEUE_TIMEOUT` | `60` | Seconds a queued `CALL AGENT` waits before `agent_busy` | +| `WITH MAX_CHAIN_DEPTH` | `4` | Delegation hops | +| `WITH MEMORY` | `"individual"` | One conversation per session, or `"none"` | +| `WITH MAX_HISTORY_TOKENS` | `12000` | Estimated tokens a session keeps between runs; oldest turns go first (0 = 40-message cap only) | +| `WITH INTERACTION_TOPIC` | — | Enables `{topic}//ask`, `/response`, `/cancel` | +| `WITH HUB_VISIBLE` | `"false"` | Show in the Hub chat picker | + +Refused with a message naming the release that brings them: `WITH SKILLS`, `WITH OUTPUT_MODEL`, +`WITH LONG_TERM_MEMORY`, `MEMORY "shared:…"`, `AGENT_MODE "insight"`, +`TOOL_EXECUTION_MODE "confirm"`, `AGENT_COLLAB_MODE` other than `"delegate"`, +`EXTERNAL_ACCESS "true"`, `WITH EXTERNAL_WRITES`, `ADD TOOL "run_lot_once"`. Legacy settings +(`MODEL`, `PROVIDER`, `TOOLS`, `BROKER_TOOLS`, `MCP_ROUTES`, `ACTIONS`, `ENABLED_COMMANDS`, +`INTERACTION_MODE`) are refused too: model settings belong on the LLM connector, tools on `ADD TOOL`. +Any other clause name is refused as unknown. + +## ADD TOOL grants + +Nothing is granted by default. Each grant names one tool and its scope: + +| Tool | Scope | Level | +|---|---|---| +| `read_mqtt` | `WITH TOPICS "a/#, b/+"` (required) | read | +| `write_mqtt` | `WITH TOPICS` (required) | `WITH LEVEL "write"` | +| `read_lot` | `WITH TARGET ""` (optional) — kinds: action, model, route, rule, panel, agent, python, thing | read | +| `create_lot` | `WITH TARGET "action, rule"` — kinds: action, model, route, rule, panel | `WITH LEVEL "write"` | +| `execute_routes` | `WITH TARGET ""` or `"."` (required) | `WITH LEVEL "write"` | +| `execute_actions` | `WITH TARGET ""` (required) | `WITH LEVEL "write"` | + +- Writing tools need `WITH LEVEL "write"`. The default, `"write_confirm"`, needs approvals, + which are not available yet, so a writing grant without `LEVEL "write"` is refused. +- `+` and `#` must fill a whole topic level. `write_mqtt` can never publish under + `$SYS/Coreflux/Agents/`. +- `create_lot` with target `agent` or `skill` is refused at any level: authoring those always + needs confirmation, which is not available yet. +- `TOPICS` is refused on the other tools, `TARGET` on the MQTT tools, `LEVEL` on read tools. + Grants of one tool are merged. +- A grant is not a permission: every tool call is also checked against the ACL of the user the + task runs as, and of the agent's `DEFAULT_USER`. A call outside the grant fails as + `out_of_scope`; a call the user may not make fails as `unauthorized`. + +## Calling an agent from an action + +``` +DEFINE ACTION TriageAlert +ON TOPIC "alerts/raw/+" DO + CALL AGENT "AlertAnalyst.execute" + WITH (task = PAYLOAD, session_id = TOPIC POSITION 3) + RETURN AS {verdict} + PUBLISH TOPIC "alerts/triaged" WITH {verdict} +``` + +The name is the dotted `"Agent.method"` string; methods are `execute` and `clear_history`. +There is no `METHOD` keyword. `execute` takes `task` (required), `session_id` and +`queue_timeout` (seconds to wait for a busy agent, overriding `QUEUE_TIMEOUT`; 0 = do not wait); +`clear_history` takes `session_id`. The task runs as the agent's `DEFAULT_USER`. A failure comes +back as JSON (`{ "success": false, "status", "code", "message" }`); read it with `GET JSON`. + +## How work arrives + +- **Task topic:** publish to `$SYS/Coreflux/Agents//task//request`; the answer is on + `…/task//response`, progress on `…/status` and `…/stream`, and `…/cancel` stops it. + Publishing under `$SYS` needs a `PublishSys` rule, for `root` too, or it is dropped silently. +- **Interaction topic:** with `INTERACTION_TOPIC "plant/line1"`, publish to + `plant/line1//ask`; the answer comes on `…//response`. +- **`CALL AGENT`** from an action (above). +- **Delegation:** each peer in `WITH AGENTS` is offered as the tool `agent____ask`. + +A body is plain text or JSON `{ "text", "session_id", "mode": "insight", "image", "pdf" }`; +`"insight"` makes the task read-only. A task asked over MQTT runs as the publishing client's +user, never as `DEFAULT_USER`; a delegated task runs as whoever started the chain. + +## Managing agents + +- `-addAgent ` adds an agent, or **updates it in place** if it exists. The new + block is checked first; the agent keeps its conversations. +- `-removeAgent ` cancels its tasks, removes it and forgets its conversations. +- `-listAgents` lists name, LLM connector, status (`online` / `offline` / `error`) and description. +- Agents and connectors share one name space: an agent cannot take a connector's name. +- An LLM connector an agent uses cannot be removed until the agent is removed or updated. +- Agents need a Growth or Enterprise license, like `TYPE LLM`, but take no connector slot. +- Validate before deploying: `-validateLot` checks agent clauses and grants. +- Inside a `DEFINE THING` an agent is a `WITH AGENT` clause, owned by the Thing and named + `_…_`; load `lot-things` before touching one. + +## Common Mistakes + +- **WRONG:** `DEFINE ROUTE Assistant WITH TYPE AGENT` **RIGHT:** `DEFINE AGENT Assistant` + `USES LLM ROUTE ` +- **WRONG:** `WITH MODEL "gpt-5.5"` on the agent **RIGHT:** model, provider and key on the `TYPE LLM` connector +- **WRONG:** `ADD TOOL "write_mqtt"` with no `LEVEL` **RIGHT:** add `WITH LEVEL "write"` +- **WRONG:** `ADD TOOL "read_mqtt"` with no `TOPICS` **RIGHT:** `WITH TOPICS "lines/1/#"` +- **WRONG:** `CALL AGENT "Planner" METHOD "execute"` **RIGHT:** `CALL AGENT "Planner.execute"` with an indented `WITH (task = …)` +- **WRONG:** deploying an agent with `-addRoute` **RIGHT:** `-addAgent` diff --git a/plugins/coreflux/skills/lot-authoring/SKILL.md b/plugins/coreflux/skills/lot-authoring/SKILL.md deleted file mode 100644 index 21d0144..0000000 --- a/plugins/coreflux/skills/lot-authoring/SKILL.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -name: lot-authoring -description: Write, review, lint, and deploy LoT (Language of Things) for the Coreflux broker — actions, models, routes, rules, panels, themes, Python scripts and .lotnb notebooks. Use whenever the user asks to define/fix an action, model, route, rule, panel or theme, edits a .lot or .lotnb file, or a broker rejects LoT with a parse error. ---- - -# LoT Authoring — Coreflux Language of Things - -LoT is the **only** configuration language for Coreflux: **Actions** (event-driven logic), -**Models** (typed JSON schemas), **Routes** (integrations: databases, PLCs, AI, bridges), -**Rules** (MQTT access control) and, for dashboards, **Panels** and **Themes**. -Never propose JSON or YAML to configure these. - -## Workflow (always) - -1. Pick the entity from the decision guide below. -2. Write the LoT following the universal rules — every example must compile as-is. -3. Run the `lot_lint` tool (from the `coreflux-broker` MCP server) on the code. -4. Deploy with `lot_deploy` (inline) or `lotnb_deploy` (file). Read every returned envelope. -5. Verify: `broker_action_trace` for actions, `mqtt_subscribe` on the output topic, - `mqtt_read_retained` on `$SYS/Coreflux/Routes//status` for routes. -6. If the parser rejects something, the broker's message is authoritative — fix the LoT, - do not argue with it. Use `broker_command -lotDiagnostic action ` for runtime issues. - -When a broker is not configured, still lint, and hand the user the LoT plus the exact -`-addX` command to run. - -## Task Decision Guide - -| User goal | Approach | -|-----------|----------| -| React to a topic / sensor data | `DEFINE ACTION` + `ON TOPIC` — [lot-actions.md](lot-actions.md) | -| Skip duplicate telemetry (same payload) | `ON CHANGE "topic/pattern"` instead of `ON TOPIC` | -| Aggregate topics into one JSON document | `DEFINE MODEL` (often `COLLAPSED`) — [lot-models.md](lot-models.md) | -| Connect to database / REST / AI / bridge | `DEFINE ROUTE` with the matching config block — [lot-routes.md](lot-routes.md) | -| Add a PLC tag / register / OPC node | `ADD TAG` under `ADD MAPPING` on the OT route, redeploy the **full** route — never a model | -| Schedule recurring work | `ON EVERY N SECONDS` / `ON EVERY WEEKDAY AT "HH:mm:ss"` | -| Share state between actions | `KEEP TOPIC "state/x" WITH {v}` (no MQTT delivery) + `GET TOPIC` | -| Send data to subscribers / routes | `PUBLISH TOPIC "out/t" WITH {v}` | -| Restrict MQTT access | `DEFINE RULE` with scope + priority (see `broker-security` skill) | -| Complex math / ML / parsing | Python script (`# Script Name:` header) + `CALL PYTHON` | -| Build a dashboard | `DEFINE PANEL`, then `DEFINE THEME` | -| Start a new route from scratch | `broker_route_template TYPE` → fill the `skeleton` | - -**Routes vs models:** many MQTT topics → one typed JSON → model. New device point on a PLC → `ADD TAG` on the route. - -## Universal Syntax Rules (parse errors if violated) - -| Rule | Detail | -|------|--------| -| Indentation | **4 spaces** per level. Never tabs. | -| Keywords | **UPPERCASE**: `DEFINE`, `ADD`, `WITH`, `ON`, `DO`, `SET`, `IF`, `THEN` … | -| Variables | Always `{braces}`: `{temp}`, `{deviceId}` | -| Strings | Always **double quotes** | -| Topic positions | **1-based**: `TOPIC POSITION 1` is the first segment | -| `SET` separator | `SET "x" WITH 5` (`WITH`/`TO`/`AS` interchangeable); `SET x 5` fails | -| `PUBLISH` / `KEEP` | `… WITH ` — **never** `MESSAGE`, never an empty `WITH` | -| `IF` | needs `THEN`; blocks close by indentation, there is no `END IF` | -| Triggers | end with `DO`: `ON EVERY 10 SECONDS DO` | -| **Trigger indentation** | `ON …` sits at the **same column as `DEFINE ACTION`** (or on the DEFINE line). Body indents 4 spaces under it. | -| Action, model, route and rule names | Bare identifiers, never quoted: `DEFINE ACTION Heartbeat`, `DEFINE MODEL SensorReading`, `DEFINE ROUTE PlantDb WITH TYPE …`, `DEFINE RULE SensorAccess …`. The parser rejects `DEFINE MODEL "X"` with *STRING where IDENTIFIER was expected*. | -| Panel and theme names | Quoted string: `DEFINE PANEL "Line 3 Overview"`, `DEFINE THEME "Dark"` (bare identifiers also parse). | -| Model parents | Bare as well: `DEFINE MODEL Child FROM Parent WITH TOPIC "…"` | -| Credentials | `GET ENV "NAME"` / `GET SECRET "NAME"` — never literal passwords | -| `ADD METADATA` | Template-only; the parser rejects it in deployed routes | -| `RETURN` | On its own line, then one indented `OUTPUT var` per line | -| `PAYLOAD` | Only exists for `ON TOPIC` / `ON CHANGE`. Timers read state with `GET TOPIC`. | - -## Naming Conventions - -| Entity | Convention | Example | -|--------|------------|---------| -| Actions | PascalCase, verb-first | `ProcessTemperature`, `AlertOnOverheat` | -| Models | PascalCase, noun | `SensorReading` | -| Rules | PascalCase, descriptive | `ProtectSysTopics` | -| Routes | PascalCase, destination-based | `FactoryDB`, `CloudBridge` | -| Fields | snake_case in quotes | `"device_id"` | -| Topics | lowercase, slash-separated | `sensors/+/temperature` | - -Write **LoT** in prose; use `lot` as the code-block language tag. - -## Actions — quick reference - -```lot -DEFINE ACTION Heartbeat -ON EVERY 10 SECONDS DO - PUBLISH TOPIC "system/heartbeat" WITH TIMESTAMP "ISO" -``` - -```lot -DEFINE ACTION AlertOnOverheat -ON TOPIC "sensors/+/data" DO - SET "deviceId" WITH TOPIC POSITION 2 - SET "temp" WITH PAYLOAD AS DOUBLE - IF {temp} > 85 THEN - PUBLISH TOPIC "alerts/" + {deviceId} WITH "CRITICAL: " + {temp} -``` - -Callable action (no `ON`; invoked with `CALL ACTION`): - -```lot -DEFINE ACTION CalcAverage -INPUT a AS DOUBLE -INPUT b AS DOUBLE -DO - SET "result" WITH ({a} + {b}) / 2 -RETURN - OUTPUT result -``` - -Triggers: `ON TOPIC "p/+"` · `ON CHANGE "p/+"` · `ON EVERY N SECONDS|MINUTES|HOURS|DAYS` · -`ON EVERY WEEKDAY|WEEKEND|MONDAY… AT "06:00:00"` · `ON START` · `ON CONNECT` · `ON DISCONNECT` · -`ON SUBSCRIBE ["pattern"]`. - -Key statements: `SET "v" WITH PAYLOAD AS DOUBLE` · `SET "z" WITH TOPIC POSITION 3` · -`SET "x" WITH GET TOPIC "state/last" AS DOUBLE` · `SET "k" WITH GET JSON "a.b" IN PAYLOAD AS STRING` · -`KEEP TOPIC "state/mode" WITH "active"` · `PUBLISH MODEL "M" TO "out" WITH field = {v}` · -`CALL PYTHON "Script.fn" WITH ({json}) RETURN AS {r}` · `CALL MCP "Route.tool" WITH (q = {x}) RETURN AS {r}` · -`TRIGGER "Event" TO RouteName WITH {payload}`. - -Full reference: [lot-actions.md](lot-actions.md) - -## Models — quick reference - -```lot -DEFINE MODEL SensorReading WITH TOPIC "factory/sensors/data" - ADD STRING "deviceId" WITH TOPIC "factory/sensors/id" AS TRIGGER - ADD DOUBLE "temperature" WITH TOPIC "factory/sensors/temp" - ADD STRING "timestamp" WITH TIMESTAMP "ISO" - ADD STRING "status" WITH "ok" -``` - -`COLLAPSED` publishes one JSON object on the base topic; otherwise each field goes to -`/`. Types: `STRING INT DOUBLE BOOL ARRAY OBJECT TIMESTAMP COLLECTION`. -Mark data fields `AS TRIGGER` (not timestamps). Static defaults use `WITH` directly, never `WITH VALUE`. - -Full reference: [lot-models.md](lot-models.md) - -## Routes — quick reference - -```lot -DEFINE ROUTE SensorDB WITH TYPE POSTGRESQL - ADD SQL_CONFIG - WITH SERVER GET ENV "PG_HOST" - WITH PORT 5432 - WITH DATABASE "factory" - WITH USERNAME GET ENV "PG_USER" - WITH PASSWORD GET SECRET "PG_PASSWORD" - ADD EVENT ReadSensors - WITH SOURCE_TOPIC "sensors/+/query" - WITH DESTINATION_TOPIC "sensors/{topic.2}/result" - WITH QUERY "SELECT * FROM sensors WHERE id = '{payload}'" -``` - -```lot -DEFINE ROUTE PLC1 WITH TYPE MODBUS_TCP - ADD MODBUS_CONFIG - WITH IP "192.168.1.100" - WITH PORT 502 - WITH SLAVE_ID 1 - ADD MAPPING "ReadRegisters" - WITH SOURCE_TOPIC "plc1/read" - WITH EVERY 1 SECONDS - ADD TAG "Temperature" - WITH ADDRESS "40001" - WITH DATA_TYPE "INT16" -``` - -Config block must match the type: `SQL_CONFIG` (POSTGRESQL/MYSQL/MARIADB/SQLSERVER) · -`MONGODB_CONFIG` · `OPENSEARCH_CONFIG` · `CRATEDB_CONFIG` · `FILE_STORAGE_CONFIG` · -`MODBUS_CONFIG` (MODBUS_TCP/MODBUS_SERIAL) · `MODBUS_SERVER_CONFIG` · `S7_CONFIG` · `OPCUA_CONFIG` · -`OPCUA_SERVER_CONFIG` · `ETHERNETIP_CONFIG` · `ALLEN_BRADLEY_CONFIG` · `ADS_CONFIG` · `FINS_CONFIG` · -`BACNET_CONFIG` · `KAFKA_CONFIG` · `REST_API_CONFIG` · `SMTP_CONFIG` (EMAIL) · -`SOURCE_CONFIG`+`DESTINATION_CONFIG` (MQTT_BRIDGE) · `CLUSTER_CONFIG` · `LLM_CONFIG` · `AGENT_CONFIG` · -`MCP_CONFIG` · `MCP_SERVER_CONFIG` · `BARCODE_CONFIG` · `VIDEO_INPUT_CONFIG` · `AUDIO_INPUT_CONFIG` · -`VIDEO_OUTPUT_CONFIG`. `ROUTE_CONFIG` (overload policy) can be added to any route. - -The authoritative template for any type is `broker_route_template TYPE` -(`-routeCode TYPE`). Placeholders in event queries are 1-based: `{payload}`, `{topic.N}`, -`{timestamp}`, `{env.NAME}`, `{secret.NAME}`. **OT tags publish to `/`.** - -Full reference: [lot-routes.md](lot-routes.md) - -## Rules — quick reference - -```lot -DEFINE RULE SensorAccess WITH PRIORITY 100 FOR Subscribe TO TOPIC "sensors/#" - IF USER HAS "AllowedSubscribe" THEN - ALLOW - ELSE - DENY -``` - -Lowest priority number wins; among ties DENY wins; no matching rule ⇒ deny. Priorities -`0–99` are reserved. Scopes: `Connect` · `Subscribe` · `Publish` · `SubscribeSys` · -`PublishSys` · `SystemConfiguration` · `*ManagementCreation` · `CommandCall`. -Details and the RBAC model: `broker-security` skill. - -## Panels & Themes — quick reference - -```lot -DEFINE PANEL "Zone1Dashboard" - WITH TITLE "Zone 1 — Operations" - WITH LAYOUT "grid" COLUMNS 3 - WITH VISIBILITY SHARED - WITH SHARE TO GROUP "zone1-staff" - WITH STATE PUBLISHED - - ADD COMPONENT "TempGauge" WITH TYPE "gauge" - SET LABEL "Temperature" SET UNIT "°C" - SET RANGE FROM 0 TO 150 - BIND VALUE TO TOPIC "zone1/temp" - - ADD COMPONENT "StopBtn" WITH TYPE "button" - SET LABEL "STOP" SET STYLE "danger" - WITH INTERACT FOR GROUP "supervisors" - ON CLICK DO - PUBLISH TOPIC "zone1/emergency/stop" WITH 1 -``` - -```lot -DEFINE THEME "IndustrialDark" - SET "PRIMARY" WITH "#f97316" - SET "BACKGROUND" WITH "#0a0a0f" - SET "FOREGROUND" WITH "#fafafa" -``` - -`WITH STATE PUBLISHED` is required (DRAFT panels are never distributed). `PRIVATE` never -combines with `WITH SHARE TO`. Silent failures: `TYPE` without `WITH` is dropped, `"form"` is -not a type, `BIND` needs ` TO TOPIC`, and the statement after `ON CLICK DO` must be -on its own indented line. - -## Python scripts - -```python -# Script Name: SensorUtils - -import json, statistics - -def analyze(readings_json): - readings = json.loads(readings_json) if isinstance(readings_json, str) else readings_json - return {"mean": statistics.mean(readings), "count": len(readings)} -``` - -Deploy with `-addPython` (a `python` cell in a notebook, or `lot_deploy` `python`). Call with -`CALL PYTHON "SensorUtils.analyze" WITH ({readings}) RETURN AS {stats}`; `RETURN AS` is a JSON -string, read fields with `GET JSON "mean" IN {stats} AS DOUBLE`. Allowed modules: `math`, -`statistics`, `json`, `datetime`, `collections`, `re`, `csv`, `hashlib`, `base64`. -Blocked: `os`, `subprocess`, `socket`, `http`, `importlib`. - -## Anti-patterns the linter catches - -``` -ON EVERY 10 SECONDS <- missing DO -SET x "value" <- missing WITH -PUBLISH TOPIC "t" MESSAGE "hi" <- MESSAGE is not a keyword -DEFINE ACTION X - ON TOPIC "t" DO <- trigger indented under DEFINE -TOPIC POSITION 0 <- 1-based -"Temp: " + temp <- variable without braces -WITH PASSWORD "mypass" <- hardcode; use GET SECRET -ADD METADATA <- template-only -RETURN OUTPUT a, b <- one OUTPUT per line -KEEP TOPIC "db/insert" WITH {p} <- KEEP does not drive route events; PUBLISH does -ON EVERY 5 SECONDS DO - PUBLISH TOPIC "t" WITH PAYLOAD <- no payload on timers -``` - -## Deployment order - -Broker load order (and what `lot_deploy` / `lotnb_deploy` use): models → actions → routes → -rules → python → themes → panels. Parent models before children; callable actions before -their callers; Python scripts before the actions that `CALL PYTHON` them (deploy the script in -its own step if needed). - -## Where the truth lives - -The parser in the connected broker is the ground truth. When the docs and the broker disagree, -trust the broker's error message, then search the `coreflux-docs` MCP server -(`https://docs.coreflux.org`) for the current syntax. diff --git a/plugins/coreflux/skills/lot-authoring/lot-actions.md b/plugins/coreflux/skills/lot-authoring/lot-actions.md deleted file mode 100644 index cb62cd1..0000000 --- a/plugins/coreflux/skills/lot-authoring/lot-actions.md +++ /dev/null @@ -1,603 +0,0 @@ -# LOT Actions — Full Reference - -## Structure - -``` -DEFINE ACTION Name - DO - -``` - -**The trigger line sits at column 0 — same indent as `DEFINE`.** The body is -indented **4 spaces** under the trigger. Do NOT indent the trigger line under -`DEFINE ACTION`: the LOT lexer is Python-style indentation-sensitive, so an -indented trigger emits a stray `INDENT` token before `ON ...` and the parser -rejects the action. - ---- - -## Triggers - -### ON EVERY — interval timer -``` -DEFINE ACTION Heartbeat -ON EVERY 10 SECONDS DO - PUBLISH TOPIC "system/heartbeat" WITH TIMESTAMP "ISO" -``` -Units: `MILLISECONDS`, `SECONDS`, `MINUTES`, `HOURS`, `DAYS`, `WEEKS` - -### ON EVERY \ AT — day-of-week scheduled -Runs once at a specific time on the given day(s). Time is `"HH:mm:ss"` (24-hour). -``` -DEFINE ACTION DailyShiftStart -ON EVERY WEEKDAY AT "06:00:00" DO - PUBLISH TOPIC "shift/status" WITH "active" - -DEFINE ACTION WeekendMode -ON EVERY WEEKEND AT "08:00:00" DO - KEEP TOPIC "state/mode" WITH "weekend" - -DEFINE ACTION SaturdayBackup -ON EVERY SATURDAY AT "02:00:00" DO - PUBLISH TOPIC "backup/trigger" WITH "start" -``` -Day keywords: `MONDAY` `TUESDAY` `WEDNESDAY` `THURSDAY` `FRIDAY` `SATURDAY` `SUNDAY` `WEEKDAY` `WEEKEND` - -### ON TOPIC — MQTT-triggered -``` -DEFINE ACTION ProcessSensor -ON TOPIC "sensors/+/data" DO - SET "deviceId" WITH TOPIC POSITION 2 - SET "temp" WITH PAYLOAD AS DOUBLE - IF {temp} > 30 THEN - PUBLISH TOPIC "alerts/" + {deviceId} WITH "High temp: " + {temp} -``` -- `+` matches one level in the topic pattern -- `PAYLOAD` — the incoming message body -- `TOPIC POSITION N` — segment N of the incoming topic (1-based) - -### ON CHANGE — MQTT-triggered only when payload changes -``` -DEFINE ACTION ProcessSensorOnChange -ON CHANGE "sensors/+/data" DO - SET "temp" WITH PAYLOAD AS DOUBLE - PUBLISH TOPIC "sensors/processed" WITH {temp} -``` -- Same topic patterns and wildcards as `ON TOPIC` -- Runs on the **first** message for a topic, then only when the incoming **payload bytes** differ from the last value on that concrete topic (not JSON-aware) -- Use `ON TOPIC` when every publish must be handled; use `ON CHANGE` to avoid duplicate work on unchanged telemetry - -### ON START — once at broker startup -``` -DEFINE ACTION Init -ON START DO - PUBLISH TOPIC "system/status" WITH "online" - KEEP TOPIC "device/config" WITH "ready" -``` - -### ON CONNECT / ON DISCONNECT / ON SUBSCRIBE — MQTT session lifecycle -``` -DEFINE ACTION AuditConnect -ON CONNECT DO - PUBLISH TOPIC "audit/connect" WITH CLIENTID + "@" + ENDPOINT - -DEFINE ACTION AuditDisconnect -ON DISCONNECT DO - PUBLISH TOPIC "audit/disconnect" WITH DISCONNECTREASON - -DEFINE ACTION TrackSubscriptions -ON SUBSCRIBE "sensors/#" DO - PUBLISH TOPIC "audit/sub" WITH SUBSCRIBETOPIC + " qos=" + SUBSCRIBEQOS -``` - -Session context keywords: `CLIENTID`, `USER`, `ENDPOINT`, `CLEANSESSION`, `DISCONNECTREASON`, `SUBSCRIBETOPIC`, `SUBSCRIBEQOS`. Omit the topic pattern on `ON SUBSCRIBE` to run on every allowed subscription. The broker only evaluates these hooks when at least one action defines them. - -### Callable actions (INPUT / RETURN / OUTPUT) - -Callable actions have no MQTT trigger. Declare `INPUT` parameters, a `DO` body, then `RETURN` with **one `OUTPUT` per line** (one variable each). Comma-separated `RETURN OUTPUT a, b` and single-line `RETURN OUTPUT result` are **rejected**. - -``` -DEFINE ACTION CalcAverage -INPUT value1 AS DOUBLE -INPUT value2 AS DOUBLE -DO - SET "avg" WITH ({value1} + {value2}) / 2 -RETURN - OUTPUT avg -``` - -Multiple outputs: - -``` -DEFINE ACTION AnalyzeReading -INPUT value AS DOUBLE -INPUT threshold AS DOUBLE -DO - SET "is_above" WITH ({value} > {threshold}) - SET "difference" WITH ({value} - {threshold}) - SET "percentage" WITH ({value} / {threshold} * 100) -RETURN - OUTPUT is_above - OUTPUT difference - OUTPUT percentage -``` - -Input types: `STRING`, `INT`, `DOUBLE`, `BOOL`, `JSON` - -The number of `RETURN` variables at a `CALL ACTION` site must match the callee's `OUTPUT` count (validated at upload). - ---- - -## Variable Operations - -### SET — assign a value -``` -SET "myVar" WITH "hello" -SET "count" WITH 0 -SET "temp" WITH GET TOPIC "sensor/temp" AS DOUBLE -SET "raw" WITH PAYLOAD -SET "data" WITH GET JSON "readings.temperature" IN PAYLOAD AS DOUBLE -SET "host" WITH GET ENV "DB_HOST" -SET "pass" WITH GET SECRET "DB_PASSWORD" -SET "seg" WITH TOPIC POSITION 2 -``` - -### Type casting with AS -`AS INT` · `AS DOUBLE` · `AS BOOL` · `AS STRING` · `AS TIMESTAMP` · `AS ARRAY` · `AS OBJECT` - -### GET TOPIC — read a retained/current topic value -``` -SET "value" WITH GET TOPIC "sensors/temperature" AS DOUBLE -SET "config" WITH GET TOPIC "device/config" AS STRING -``` - -Lookup order (same in actions and permission rules): - -1. **In-flight** — a `KEEP` / `PUBLISH` this action queued but has not flushed yet. -2. **Trigger payload** — when reading the topic that fired this action. -3. **Live cache** — latest stored value. `KEEP TOPIC` writes it without broadcasting; `PUBLISH TOPIC` overwrites it and broadcasts. Last write wins. -4. **MQTT retain** — fallback after restart, before the cache is warm again. - -Use `KEEP TOPIC` for state another action (or a rule) will `GET TOPIC` without notifying subscribers. Use `TOPIC EXISTS` in rules when the grant must be an MQTT retained message. Permission checks never dynamically subscribe to a missing topic. - -### GET JSON — extract from JSON -``` -SET "temp" WITH GET JSON "data.temperature" IN PAYLOAD AS DOUBLE -SET "name" WITH GET JSON "device.name" IN {myJson} -SET "nested" WITH GET JSON "a.b.c" IN PAYLOAD AS STRING -SET "ok" WITH (GET JSON "success" IN {result} AS BOOL) -``` -Source is a JSON **string** (`PAYLOAD`, a variable, or `CALL PYTHON` `RETURN AS`). Missing keys -and JSON `null` become `"null"`; `AS BOOL` / `AS INT` / `AS DOUBLE` safe-parse that to -false / 0 / 0.0 instead of throwing. `AS STRING` yields the text `null`. - -### GET MODEL — fetch model data from a DB route -``` -SET "record" WITH GET MODEL "SensorData" FROM "MyDB" WHERE id EQUALS "sensor1" -``` - ---- - -## Publishing - -### PUBLISH vs KEEP — When to Use Which - -**KEEP** — stored in the broker cache with no MQTT delivery, readable by `GET TOPIC`. -**PUBLISH** — overwrites that same cache slot and delivers to current subscribers. - -A later `PUBLISH` of the same topic **replaces** the KEEP'd value for `GET TOPIC`. - -Use KEEP for shared inter-action state (counters, mode flags, last-known values). -Use PUBLISH to send data to routes, dashboards, or external systems. - -``` --- Share state between actions: -KEEP TOPIC "state/mode" WITH "running" -KEEP TOPIC "state/lastTemp" WITH {temp} -SET "mode" WITH GET TOPIC "state/mode" AS STRING -- read it from any action - --- Drive routes/UIs/external systems: -PUBLISH TOPIC "sensors/data" WITH { "temp": {temp} } -PUBLISH TOPIC "alerts/zone1" WITH "CRITICAL" -``` - -### PUBLISH TOPIC — non-retained message -``` -PUBLISH TOPIC "output/data" WITH "value: " + {temp} -PUBLISH TOPIC "output/json" WITH { "temp": {temp}, "status": "ok" } -PUBLISH TOPIC "events/" + {deviceId} WITH TIMESTAMP "ISO" -``` - -### Binary passthrough — `PAYLOAD AS BYTES` - -Use `AS BYTES` when the incoming MQTT payload must be forwarded or retained -bit-for-bit (protobuf, Modbus frames, image chunks). Untyped `WITH PAYLOAD` -still uses the string publish path and may corrupt non-UTF-8 data. - -``` -DEFINE ACTION ForwardBinary -ON TOPIC "binary/in" DO - PUBLISH TOPIC "binary/out" WITH PAYLOAD AS BYTES - -DEFINE ACTION KeepBinaryState -ON TOPIC "binary/in" DO - KEEP TOPIC "state/raw" WITH PAYLOAD AS BYTES - SET "frame" WITH PAYLOAD AS BYTES -``` - -- Do **not** chain string transforms (`TRIM`, `FILTER`, `REPLACE`, `SPLIT`) after - `PAYLOAD AS BYTES` on publish/keep — the parser rejects that combination. -- Empty payloads are not published or stored on the binary path. - -### KEEP TOPIC — stored without broadcast, readable by GET TOPIC -``` -KEEP TOPIC "state/mode" WITH "running" -KEEP TOPIC "device/" + {id} + "/config" WITH {config} -``` - -### PUBLISH MODEL — use a defined model schema -``` -PUBLISH MODEL "SensorReading" TO "output/sensors" WITH - deviceId = "sensor1" - temperature = {temp} - timestamp = TIMESTAMP "ISO" - status = "active" -``` - ---- - -## Persistent State - -### KEEP ENV / KEEP SECRET — store environment variables -``` -KEEP ENV "COUNTER" WITH {counter} + 1 -KEEP SECRET "API_KEY" WITH "sk-abc123" -``` - -### DELETE ENV / DELETE SECRET -``` -DELETE ENV "OLD_CONFIG" -DELETE SECRET "EXPIRED_KEY" -``` - ---- - -## Control Flow - -### IF / THEN / ELSE -``` -IF {temp} > 30 THEN - PUBLISH TOPIC "alert" WITH "Hot!" -ELSE - PUBLISH TOPIC "status" WITH "Normal" -``` -Operators: `==`, `!=`, `>`, `<`, `>=`, `<=`, `AND`, `OR`, `NOT`, `CONTAINS`, `STARTS_WITH`, `ENDS_WITH` - -### IF without ELSE -``` -IF {status} == "error" THEN - PUBLISH TOPIC "alerts/system" WITH "Error detected" -``` - -### SWITCH / CASE -``` -SWITCH {status} - CASE "on" THEN - PUBLISH TOPIC "led" WITH "1" - CASE "off" THEN - PUBLISH TOPIC "led" WITH "0" - DEFAULT THEN - PUBLISH TOPIC "led" WITH "unknown" -``` - -### LOOP / UNTIL -``` -SET "i" WITH 0 -LOOP - SET "i" WITH {i} + 1 - PUBLISH TOPIC "counter" WITH {i} -UNTIL {i} == 10 -``` - ---- - -## Expressions - -### Arithmetic -``` -SET "result" WITH {a} + {b} * 2 -SET "avg" WITH ({x} + {y}) / 2 -SET "remainder" WITH {total} % {batch} -``` - -### String concatenation with + -``` -SET "msg" WITH "Temperature: " + {temp} + "°C" -PUBLISH TOPIC "sensors/" + {deviceId} + "/alert" WITH {msg} -``` - -### RANDOM -``` -SET "id" WITH RANDOM UUID -SET "roll" WITH RANDOM INT BETWEEN 1 AND 6 -SET "val" WITH RANDOM DOUBLE BETWEEN 0.0 AND 1.0 -``` - -### TIMESTAMP -``` -SET "now" WITH TIMESTAMP "ISO" -- ISO 8601: 2026-01-15T10:30:00Z -SET "unix" WITH TIMESTAMP "UNIX" -- Unix epoch seconds -SET "custom" WITH TIMESTAMP "UTC" -``` - ---- - -## String Transforms - -### FILTER (regex extraction) -``` -SET "digits" WITH FILTER PAYLOAD USING REGEX "[0-9]+" -``` - -### REPLACE -``` -SET "clean" WITH REPLACE "\n" WITH " " IN RESULT -``` - -### TRIM -``` -SET "text" WITH PAYLOAD AND_THEN TRIM -``` - -### AND_THEN (chaining transforms) -``` -SET "result" WITH PAYLOAD AND_THEN FILTER USING REGEX "[0-9]+" AND_THEN TRIM -``` - ---- - -## Integration Calls - -### CALL ACTION — invoke another callable action -``` -DEFINE ACTION ProcessPair -ON TOPIC "sensors/pair/data" DO - SET "temp1" WITH (GET JSON "sensor1" IN PAYLOAD AS DOUBLE) - SET "temp2" WITH (GET JSON "sensor2" IN PAYLOAD AS DOUBLE) - CALL ACTION CalcAverage - WITH value1 = {temp1}, value2 = {temp2} - RETURN result - PUBLISH TOPIC "sensors/average" WITH {result} -``` - -Multi-line `CALL` (same rules as multi-line `RETURN` / `OUTPUT`): - -``` - CALL ACTION AnalyzeReading - WITH value = {current_value}, threshold = {threshold} - RETURN above, diff, pct -``` - -The called action must declare `INPUT` parameters and a multi-line `RETURN` / `OUTPUT` block. - -### CALL PYTHON — invoke a Python function - -**Full workflow:** - -**Step 1 — Write and deploy the script** (a `python` cell in a `.lotnb`, or the `lot_deploy` tool's `python` argument). Must include the `# Script Name:` header. -```python -# Script Name: SensorUtils - -import json, statistics - -def analyze(readings_json): - readings = json.loads(readings_json) if isinstance(readings_json, str) else readings_json - if not readings: - return {"success": False, "error": "empty"} - return { - "success": True, - "mean": round(statistics.mean(readings), 2), - "min": min(readings), - "max": max(readings), - "count": len(readings) - } - -def classify(value, low, high): - v = float(value) - if v < float(low): return "low" - if v > float(high): return "high" - return "normal" -``` - -**Step 2 — Call from LOT action:** -``` -DEFINE ACTION AnalyzeBatch -ON TOPIC "sensors/batch" DO - SET "readings" WITH PAYLOAD - CALL PYTHON "SensorUtils.analyze" WITH ({readings}) RETURN AS {stats} - SET "ok" WITH (GET JSON "success" IN {stats} AS BOOL) - IF {ok} EQUALS TRUE THEN - SET "avg" WITH GET JSON "mean" IN {stats} AS DOUBLE - SET "hi" WITH GET JSON "max" IN {stats} AS DOUBLE - PUBLISH TOPIC "sensors/stats" WITH {stats} - IF {hi} > 85 THEN - PUBLISH TOPIC "alerts/overtemp" WITH "Max: " + {hi} -``` - -**Rules:** -- Format: `CALL PYTHON "ScriptName.function_name" WITH (arg1, arg2, ...) RETURN AS {result}` -- Arguments are **positional** — order must match the Python function signature -- `RETURN AS` is always a **JSON string**. A Python `dict` / `list` / number / bool is - serialized automatically — you do **not** need `json.dumps()`. A Python `str` (including - `json.dumps(...)`) is kept as-is. `None` becomes `null`. -- Parse fields with `GET JSON "key" IN {result} AS BOOL|INT|DOUBLE|STRING`. Missing keys - do not crash: typed extracts become false/0; `AS STRING` is the text `null`. -- `PUBLISH … WITH {result}` sends that same JSON string. -- Script must be deployed (`-addPython`, via `lot_deploy` / `lotnb_deploy`) before the action that calls it -- Available modules: `math`, `statistics`, `json`, `datetime`, `collections`, `re`, `csv`, `hashlib`, `base64` -- Blocked: `os`, `subprocess`, `socket`, `http`, `importlib` - -### CALL MCP — invoke a tool exposed by an MCP route -``` -CALL MCP "MyMcpRoute.search" WITH (query = "test") RETURN AS {result} -``` -Tool names are `"."`; discover them on the retained topic `$SYS/Coreflux/Routes//Tools`. The legacy `CALL MCP "Route" TOOL "name"` form is rejected. - -### CALL LLM — invoke an LLM route -``` -CALL LLM "MyLlm" METHOD "generate" WITH prompt = "Summarize: " + {data} RETURN AS {answer} -``` - -### CALL AGENT — invoke an Agent route -``` -CALL AGENT "MyAgent" METHOD "execute" WITH task = "Analyze data" RETURN AS {result} -``` - -### TRIGGER — fire a route event programmatically -``` -TRIGGER "ReadSensors" TO MyDB WITH "sensor1" -``` - ---- - -## Complete Examples - -### Sensor monitor with alerting -``` -DEFINE ACTION SensorMonitor -ON TOPIC "factory/sensors/+/temperature" DO - SET "zone" WITH TOPIC POSITION 3 - SET "temp" WITH PAYLOAD AS DOUBLE - SET "ts" WITH TIMESTAMP "ISO" - IF {temp} > 85 THEN - PUBLISH TOPIC "factory/alerts/" + {zone} WITH "CRITICAL: " + {temp} + "°C at " + {ts} - KEEP TOPIC "state/alerts/" + {zone} + "/last" WITH {temp} - ELSE - IF {temp} > 70 THEN - PUBLISH TOPIC "factory/warnings/" + {zone} WITH "WARNING: " + {temp} + "°C" -``` - -### Periodic data aggregation with Python -``` -DEFINE ACTION DailyReport -ON EVERY WEEKDAY AT "18:00:00" DO - SET "readings" WITH GET TOPIC "sensors/day/buffer" - CALL PYTHON "ReportGen.summarize" WITH ({readings}) RETURN AS {summary} - PUBLISH TOPIC "reports/daily" WITH {summary} - KEEP TOPIC "state/reports/daily/latest" WITH {summary} -``` - -### Callable conversion utility -``` -DEFINE ACTION CelsiusToFahrenheit -INPUT celsius AS DOUBLE -DO - SET "fahrenheit" WITH {celsius} * 1.8 + 32 -RETURN - OUTPUT fahrenheit -``` - ---- - -## Anti-Patterns - -``` --- WRONG: Trigger indented under DEFINE (parser rejects with an unexpected INDENT) -DEFINE ACTION ToggleInput - ON EVERY 1 SECONDS DO - SET "current" WITH GET TOPIC "plc/input" AS BOOL - IF {current} == true THEN - PUBLISH TOPIC "plc/input" WITH false - ELSE - PUBLISH TOPIC "plc/input" WITH true --- RIGHT: trigger at column 0, body indented 4 spaces -DEFINE ACTION ToggleInput -ON EVERY 1 SECONDS DO - SET "current" WITH GET TOPIC "plc/input" AS BOOL - IF {current} == true THEN - PUBLISH TOPIC "plc/input" WITH false - ELSE - PUBLISH TOPIC "plc/input" WITH true -``` - -The same rule applies to every trigger: `ON TOPIC`, `ON EVERY N `, -`ON EVERY AT`, `ON START`. The trigger line MUST sit at the same column as -`DEFINE ACTION` — never indented under it. Callable actions use `INPUT` lines -instead of an `ON` trigger. - -``` --- WRONG: comma-separated or single-line RETURN OUTPUT -RETURN OUTPUT result -RETURN OUTPUT is_above, difference, percentage --- RIGHT: RETURN on its own line, one OUTPUT per line -RETURN - OUTPUT result -RETURN - OUTPUT is_above - OUTPUT difference - OUTPUT percentage -``` - -``` --- WRONG: Quoted action name -DEFINE ACTION "Heartbeat" --- RIGHT: -DEFINE ACTION Heartbeat -``` - -``` --- WRONG: MESSAGE keyword (invalid — parser rejects it) -PUBLISH TOPIC "t" MESSAGE "hello" -KEEP TOPIC "t" MESSAGE "value" --- RIGHT: -PUBLISH TOPIC "t" WITH "hello" -KEEP TOPIC "t" WITH "value" -``` - -``` --- WRONG: Missing DO -ON EVERY 10 SECONDS - PUBLISH TOPIC "t" WITH "x" --- RIGHT: -ON EVERY 10 SECONDS DO - PUBLISH TOPIC "t" WITH "x" -``` - -``` --- WRONG: Missing WITH in SET -SET count 0 --- RIGHT: -SET "count" WITH 0 -``` - -``` --- WRONG: 0-based topic position -SET "seg" WITH TOPIC POSITION 0 --- RIGHT (1-based): -SET "seg" WITH TOPIC POSITION 1 -``` - -``` --- WRONG: Variable without braces -SET "msg" WITH "Temp: " + temp --- RIGHT: -SET "msg" WITH "Temp: " + {temp} -``` - -``` --- WRONG: No THEN after IF -IF {x} > 5 - PUBLISH TOPIC "t" WITH "yes" --- RIGHT: -IF {x} > 5 THEN - PUBLISH TOPIC "t" WITH "yes" -``` - -``` --- WRONG: KEEP to drive a route (unreliable — use PUBLISH) -KEEP TOPIC "db/insert/data" WITH {payload} --- RIGHT for route events: -PUBLISH TOPIC "db/insert/data" WITH {payload} --- KEEP is for state between actions: -KEEP TOPIC "state/lastValue" WITH {payload} -``` diff --git a/plugins/coreflux/skills/lot-authoring/lot-models.md b/plugins/coreflux/skills/lot-authoring/lot-models.md deleted file mode 100644 index 8457dbc..0000000 --- a/plugins/coreflux/skills/lot-authoring/lot-models.md +++ /dev/null @@ -1,330 +0,0 @@ -# LOT Models — Full Reference - -## What Models Do - -Models define **data schemas** that map MQTT topics to structured fields. When a trigger topic receives a message, the broker re-evaluates all fields and publishes the assembled output. - -Two publishing modes: -- **Default**: each field published individually to `/` -- **COLLAPSED**: all fields published as a single JSON object to `` - ---- - -## Basic Structure - -``` -DEFINE MODEL Name [COLLAPSED] [FROM ParentModel] [WITH TOPIC "base/topic"] - ADD "fieldName" WITH TOPIC "field/topic" [AS TRIGGER] - ADD "fieldName" WITH - [STORE IN "RouteName" WITH TABLE "table_name"] - [FETCH FROM "RouteName" WITH TABLE "table_name" WHEN ...] -``` - -Indentation: **4 spaces** per level. - ---- - -## Field Types - -| Type | Description | Example value | -|------|-------------|---------------| -| `STRING` | Text | `"hello"`, `"sensor1"` | -| `INT` | Integer | `0`, `42` | -| `DOUBLE` | Float | `3.14`, `98.6` | -| `BOOL` | Boolean | `true`, `false` | -| `OBJECT` | Raw JSON object/array — embedded directly, not as string | `{"a": 1}` | -| `ARRAY` | JSON array | `[1, 2, 3]` | -| `TIMESTAMP` | Date/time value | ISO, UNIX string | -| `COLLECTION` | Array of another model type | see Collections below | - ---- - -## Field Bindings - -### WITH TOPIC — subscribe to an MQTT topic -``` -ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" -ADD STRING "deviceId" WITH TOPIC "factory/sensors/id" -``` -The field value is updated whenever that topic receives a message. - -### AS TRIGGER — re-fire the model when this topic updates -``` -ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" AS TRIGGER -ADD STRING "deviceId" WITH TOPIC "factory/sensors/id" AS TRIGGER -``` -At least one field should have `AS TRIGGER` for the model to auto-publish. -Multiple triggers are allowed; any one of them firing will publish the model. - -### Static defaults — WITH directly, NEVER WITH VALUE -The parser rejects `WITH VALUE` for expressions. Always use `WITH` alone. -``` -ADD STRING "id" WITH RANDOM UUID -ADD STRING "timestamp" WITH TIMESTAMP "UTC" -ADD STRING "status" WITH "ok" -ADD INT "count" WITH 0 -ADD DOUBLE "offset" WITH 0.0 -ADD BOOL "active" WITH FALSE -``` - -Supported expressions after `WITH`: -- String literals: `"text"` -- Numbers: `42`, `3.14` -- `RANDOM UUID` — generates a UUID -- `TIMESTAMP "ISO"` — ISO 8601 timestamp -- `TIMESTAMP "UNIX"` — Unix epoch seconds -- `TIMESTAMP "UTC"` — UTC formatted timestamp - ---- - -## Model Options (header clauses) - -### COLLAPSED — publish as single JSON object -``` -DEFINE MODEL Event COLLAPSED WITH TOPIC "events/output" - ADD STRING "id" WITH RANDOM UUID - ADD STRING "type" WITH "alert" - ADD DOUBLE "value" WITH TOPIC "sensors/temp" AS TRIGGER -``` -Output: `{"id":"...","type":"alert","value":23.5}` published to `events/output` - -Without COLLAPSED, each field is published to `events/output/id`, `events/output/type`, etc. - -### KEEP — model retains its last output on MQTT (retained flag) -``` -DEFINE MODEL Config KEEP WITH TOPIC "device/config" -``` - -### WITH RETAIN — same as KEEP (alias) -``` -DEFINE MODEL Config WITH TOPIC "device/config" RETAIN -``` - -### QoS -``` -DEFINE MODEL Critical WITH TOPIC "alerts/data" QOS1 -DEFINE MODEL Best WITH TOPIC "sensors/data" QOS0 -``` -Options: `QOS0` (default), `QOS1`, `QOS2` - ---- - -## Model Inheritance (FROM) - -``` -DEFINE MODEL AdvancedSensor FROM SensorReading WITH TOPIC "sensors/advanced" - ADD STRING "firmware" WITH "v2.0" - ADD DOUBLE "batteryLevel" WITH TOPIC "sensors/battery" -``` -Child inherits all parent fields. **Parent must be defined first.** - ---- - -## Database Storage (STORE IN) - -``` -DEFINE MODEL SensorLog WITH TOPIC "sensors/log" - ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" AS TRIGGER - ADD STRING "timestamp" WITH TIMESTAMP "ISO" - STORE IN "MyDB" WITH TABLE "sensor_readings" -``` - -### Conditional storage -``` - STORE IN "MyDB" WITH TABLE "alerts" WHEN {temperature} > 50 -``` - ---- - -## Database Fetch (FETCH FROM) - -``` - FETCH FROM "MyDB" WITH TABLE "sensors" WHEN id EQUALS "sensor1" LIMIT 10 -``` - ---- - -## Collections (arrays of another model) - -``` -DEFINE MODEL Reading - ADD DOUBLE "value" - ADD STRING "unit" - -DEFINE MODEL SensorBatch COLLAPSED WITH TOPIC "sensors/batch" - ADD STRING "deviceId" WITH TOPIC "sensors/id" AS TRIGGER - ADD COLLECTION "readings" OF "Reading" -``` - ---- - -## Complete Examples - -### Simple topic-mapped model (Default behavior) -``` -DEFINE MODEL SensorReading WITH TOPIC "factory/sensors/data" - ADD STRING "deviceId" WITH TOPIC "factory/sensors/id" AS TRIGGER - ADD DOUBLE "temperature" WITH TOPIC "factory/sensors/temp" - ADD DOUBLE "humidity" WITH TOPIC "factory/sensors/humidity" - ADD STRING "timestamp" WITH TIMESTAMP "ISO" - ADD STRING "status" WITH "ok" -``` -Publishes to: -- `factory/sensors/data/deviceId` -- `factory/sensors/data/temperature` -- `factory/sensors/data/humidity` -- etc. - -### COLLAPSED JSON model -``` -DEFINE MODEL Alert COLLAPSED WITH TOPIC "alerts/active" - ADD STRING "id" WITH RANDOM UUID - ADD STRING "zone" WITH TOPIC "factory/zone" AS TRIGGER - ADD DOUBLE "value" WITH TOPIC "factory/sensors/temp" AS TRIGGER - ADD STRING "severity" WITH "critical" - ADD STRING "timestamp" WITH TIMESTAMP "ISO" -``` -Publishes one JSON payload: `{"id":"...","zone":"A1","value":92.3,"severity":"critical","timestamp":"..."}` - -### Model with database storage -``` -DEFINE MODEL SensorHistory COLLAPSED WITH TOPIC "sensors/history" - ADD STRING "deviceId" WITH TOPIC "sensors/id" AS TRIGGER - ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" - ADD DOUBLE "humidity" WITH TOPIC "sensors/humidity" - ADD STRING "recordedAt" WITH TIMESTAMP "ISO" - STORE IN "FactoryDB" WITH TABLE "sensor_history" -``` - -### Inherited model -``` -DEFINE MODEL BaseSensor WITH TOPIC "sensors/base" - ADD STRING "deviceId" WITH TOPIC "sensors/id" AS TRIGGER - ADD STRING "timestamp" WITH TIMESTAMP "ISO" - -DEFINE MODEL TemperatureSensor FROM BaseSensor WITH TOPIC "sensors/temperature" - ADD DOUBLE "celsius" WITH TOPIC "sensors/temp" - ADD DOUBLE "fahrenheit" WITH TOPIC "sensors/temp_f" - ADD STRING "location" WITH "Zone-A" -``` - ---- - -## When to Use PUBLISH MODEL vs Topic Bindings - -### Pattern 1 — Topic-binding model (simple pass-through, no logic) -Fields bind directly to MQTT topics. Model fires automatically on TRIGGER. No action needed. -``` -DEFINE MODEL BoilerStatus COLLAPSED WITH TOPIC "factory/boiler/data" - ADD STRING "boilerId" WITH TOPIC "factory/boiler/id" AS TRIGGER - ADD DOUBLE "temperature" WITH TOPIC "factory/boiler/temp" - ADD DOUBLE "pressure" WITH TOPIC "factory/boiler/pressure" - ADD STRING "timestamp" WITH TIMESTAMP "UTC" -``` -Good for: simple dashboards, pass-through aggregation, static display. - -### Pattern 2 — PUBLISH MODEL from action (recommended for streaming data) -Use when data needs processing, multi-source aggregation, or logic before publishing. - -**Key rule:** Put static/repeating fields in DEFINE MODEL — timestamps, unit labels, constants, -firmware version, location. The action only passes what actually changes per event. - -``` --- Schema: static fields auto-fill, action only sends the 3 dynamic ones -DEFINE MODEL SensorReading COLLAPSED - ADD STRING "timestamp" WITH TIMESTAMP "UTC" -- always auto-generated - ADD STRING "unit" WITH "celsius" -- always the same - ADD STRING "plant" WITH "Factory-A" -- always the same - ADD STRING "deviceId" -- action fills this - ADD DOUBLE "temperature" -- action fills this - ADD STRING "status" -- action fills this - -DEFINE ACTION StreamSensor -ON TOPIC "sensors/+/raw" DO - SET "id" WITH TOPIC POSITION 2 - SET "temp" WITH PAYLOAD AS DOUBLE - SET "st" WITH "ok" - IF {temp} > 85 THEN - SET "st" WITH "critical" - PUBLISH MODEL SensorReading TO "sensors/" + {id} + "/data" WITH - deviceId = {id} - temperature = {temp} - status = {st} -``` - -### Decision guide -| Scenario | Use | -|----------|-----| -| Simple topic→JSON pass-through, no logic | Topic-binding model (no action) | -| Data needs computation or filtering | PUBLISH MODEL from action | -| Same structure for many assets/machines | PUBLISH MODEL from action | -| Need to call Python, MCP, or LLM first | PUBLISH MODEL from action | -| Static config/metadata display | Topic-binding with RETAIN | - -## PUBLISH MODEL in Actions - -Use inside a `DEFINE ACTION` body to send a model instance: -``` -DEFINE ACTION PublishSensorData -ON TOPIC "sensors/+/raw" DO - SET "id" WITH TOPIC POSITION 2 - SET "temp" WITH PAYLOAD AS DOUBLE - PUBLISH MODEL "SensorReading" TO "sensors/" + {id} + "/processed" WITH - deviceId = {id} - temperature = {temp} - timestamp = TIMESTAMP "ISO" - status = "active" -``` - -For `OBJECT` type fields, the value is embedded as raw JSON (not as a string): -``` -DEFINE MODEL KafkaMessage COLLAPSED - ADD STRING "componentId" - ADD STRING "topic" - ADD OBJECT "payload" - --- In an action: -PUBLISH MODEL "KafkaMessage" TO {targetTopic} WITH - componentId = "sensor1" - topic = {targetTopic} - payload = (GET JSON "data" IN PAYLOAD AS STRING) -``` - ---- - -## Anti-Patterns - -``` --- WRONG: No field type -ADD "temperature" WITH TOPIC "sensors/temp" - --- RIGHT: -ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" -``` - -``` --- WRONG: No base topic -DEFINE MODEL Sensor - ADD DOUBLE "temp" WITH TOPIC "sensors/t" AS TRIGGER - --- RIGHT: -DEFINE MODEL Sensor WITH TOPIC "sensors/data" - ADD DOUBLE "temp" WITH TOPIC "sensors/t" AS TRIGGER -``` - -``` --- WRONG: Child model before parent -DEFINE MODEL Child FROM Parent WITH TOPIC "c/data" - ... -DEFINE MODEL Parent WITH TOPIC "p/data" -- too late - ... - --- RIGHT: define Parent first -``` - -``` --- WRONG: COLLAPSED with individual subtopic expectations --- COLLAPSED publishes ONE JSON to the base topic, not per-field subtopics. --- If downstream consumers read "data/temperature", "data/humidity", etc., --- don't use COLLAPSED. -``` diff --git a/plugins/coreflux/skills/lot-authoring/lot-routes.md b/plugins/coreflux/skills/lot-authoring/lot-routes.md deleted file mode 100644 index 0ab87c1..0000000 --- a/plugins/coreflux/skills/lot-authoring/lot-routes.md +++ /dev/null @@ -1,574 +0,0 @@ -# LOT Routes — Full Reference - -## What Routes Do - -Routes connect the broker to external systems: databases, OT devices (PLCs, sensors), REST APIs, AI models, and message bridges. Each route defines: -- A **CONFIG** block — connection settings -- **EVENT** blocks — MQTT-triggered queries/actions -- **MAPPING** blocks — scheduled/periodic polling (OT routes) - ---- - -## Basic Structure - -``` -DEFINE ROUTE Name WITH TYPE - ADD - WITH - ... - ADD EVENT EventName - WITH SOURCE_TOPIC "mqtt/topic/+" - WITH DESTINATION_TOPIC "mqtt/result/{topic.2}" - WITH QUERY "SELECT * FROM table WHERE id = '{payload}'" - ADD MAPPING "MappingName" - WITH SOURCE_TOPIC "plc/read" - WITH EVERY 5 SECONDS - ADD TAG "TagName" - WITH ADDRESS "40001" - WITH DATA_TYPE "INT16" -``` - -**OT `ADD MAPPING` + `ADD TAG`:** mapping `SOURCE_TOPIC` is the MQTT prefix; each tag publishes to `SOURCE_TOPIC` + `/` + tag name (e.g. `plc/read/TagName`). Do not use `DESTINATION_TOPIC` as the topic where polled tag values appear. Non-OT mappings (bridges, etc.) may still use `DESTINATION_TOPIC` per their template. - -Indentation: **4 spaces** per level. `ADD TAG` inside a `MAPPING` is indented 8 spaces. - ---- - -## ENV & Secrets in Config - -**Always use `GET ENV` / `GET SECRET` for credentials and host names.** Never hardcode passwords. - -``` -WITH SERVER GET ENV "PG_HOST" -WITH PASSWORD GET SECRET "DB_PASSWORD" -WITH USERNAME GET ENV "PG_USER" -``` - -Inside event `WITH QUERY` strings, use placeholder syntax instead: -``` -WITH QUERY "SELECT * FROM sensors WHERE zone = '{env.ZONE}' AND key = '{secret.API_KEY}'" -``` - ---- - -## Event Query Placeholders (1-based) - -| Placeholder | Value | -|-------------|-------| -| `{payload}` | Raw MQTT message payload | -| `{payload.json}` | Full JSON payload object | -| `{payload.json.key}` | Nested JSON extraction (dot path) | -| `{payload.csv.N}` | CSV column by index | -| `{topic}` | Full MQTT topic string | -| `{topic.N}` | Topic segment by position (**1-based**) | -| `{timestamp}` | ISO 8601 timestamp | -| `{timestamp.unix}` | Unix epoch seconds | -| `{timestamp.unix_ms}` | Unix milliseconds | -| `{env.NAME}` | Environment variable | -| `{secret.NAME}` | Encrypted secret | - ---- - -## Overload / Backpressure Configuration (`ADD ROUTE_CONFIG`) - -Unlike every other config block, `ADD ROUTE_CONFIG` is **cross-type** — it may be added to any -route, alongside the route's own type-specific config block, to control what happens when the -shared route channel is saturated. All three settings are optional and independently defaulted; -an absent block inherits the broker-wide default (`COREFLUX_ROUTE_OVERLOAD_POLICY` / -`COREFLUX_ROUTE_CHANNEL_FULL_TIMEOUT_MS`). Search the `coreflux-docs` MCP server for -"route overload configuration" for the full operator-facing reference. - -``` -DEFINE ROUTE CloudBridge WITH TYPE MQTT_BRIDGE - ADD ROUTE_CONFIG - WITH OVERLOAD_POLICY "lossless" - 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 -``` - -| Setting | Values | Default | Description | -|---------|--------|---------|-------------| -| `OVERLOAD_POLICY` | `lossless` \| `balanced` \| `realtime` | `balanced` | `lossless` waits indefinitely and never sheds; `balanced` waits up to `OVERLOAD_TIMEOUT` then sheds the arriving message; `realtime` never waits and sheds immediately | -| `OVERLOAD_TIMEOUT` | milliseconds | `50` | Wait budget for `balanced` only — ignored for `lossless`/`realtime` | -| `OVERLOAD_CAPACITY` | integer | unbounded | Max messages from THIS route in flight at once — per-route admission budget, for cross-route isolation | - -`OVERLOAD_CAPACITY` is **rejected with `lossless`**: a capacity is an admission budget that sheds -once exhausted, which would silently break the "lossless never sheds" guarantee. Declaring both -logs an error and the route runs with capacity forced back to unbounded — lossless always wins. - ---- - -## Database Routes - -### PostgreSQL -``` -DEFINE ROUTE ProductionDB WITH TYPE POSTGRESQL - ADD SQL_CONFIG - WITH SERVER GET ENV "PG_HOST" - WITH PORT 5432 - WITH DATABASE "factory" - WITH USERNAME GET ENV "PG_USER" - WITH PASSWORD GET SECRET "PG_PASSWORD" - WITH USE_SSL true - ADD EVENT GetOrders - WITH SOURCE_TOPIC "orders/query" - WITH DESTINATION_TOPIC "orders/result" - WITH QUERY "SELECT * FROM orders WHERE status = '{payload}'" - ADD EVENT InsertReading - WITH SOURCE_TOPIC "sensors/+/store" - WITH QUERY "INSERT INTO readings (device, value, ts) VALUES ('{topic.2}', {payload}, NOW())" -``` - -Config keys for SQL routes: `SERVER`, `PORT`, `DATABASE`, `USERNAME`, `PASSWORD`, `USE_SSL`, `SCHEMA` - -### MySQL / MariaDB -Same as PostgreSQL but `WITH TYPE MYSQL` or `WITH TYPE MARIADB`. Default port: 3306. - -### SQL Server / MSSQL -``` -DEFINE ROUTE ERPSQL WITH TYPE SQLSERVER - ADD SQL_CONFIG - WITH SERVER GET ENV "SQL_HOST" - WITH PORT 1433 - WITH DATABASE "ERP" - WITH USERNAME GET ENV "SQL_USER" - WITH PASSWORD GET SECRET "SQL_PASSWORD" -``` - -### MongoDB -``` -DEFINE ROUTE LogsDB WITH TYPE MONGODB - ADD MONGODB_CONFIG - WITH CONNECTION_STRING GET ENV "MONGO_URI" - WITH DATABASE "logs" - ADD EVENT StoreLogs - WITH SOURCE_TOPIC "system/logs/+" - WITH QUERY "INSERT logs {payload.json}" - ADD EVENT QueryLogs - WITH SOURCE_TOPIC "logs/query" - WITH DESTINATION_TOPIC "logs/result" - WITH QUERY "FIND logs WHERE level = '{payload}' LIMIT 100" -``` - -### OpenSearch / Elasticsearch -``` -DEFINE ROUTE SearchIndex WITH TYPE OPENSEARCH - ADD OPENSEARCH_CONFIG - WITH SERVER GET ENV "OS_HOST" - WITH PORT 9200 - WITH USERNAME GET ENV "OS_USER" - WITH PASSWORD GET SECRET "OS_PASSWORD" - ADD EVENT IndexDocument - WITH SOURCE_TOPIC "documents/+" - WITH QUERY "INDEX documents/{topic.2} {payload.json}" -``` - -### File Storage -``` -DEFINE ROUTE DataFiles WITH TYPE FILE_STORAGE - ADD FILE_STORAGE_CONFIG - WITH PATH "/data/exports" - WITH FORMAT "CSV" - ADD EVENT SaveReading - WITH SOURCE_TOPIC "sensors/+/log" - WITH QUERY "APPEND {topic.2}.csv {timestamp},{payload}" -``` - ---- - -## OT (Operational Technology) Routes - -Polled tag values are published on MQTT as **`SOURCE_TOPIC/`** per mapping (unless a tag sets its own `WITH SOURCE_TOPIC`). Subscribe or read those topics — not `DESTINATION_TOPIC`. - -### Modbus TCP -``` -DEFINE ROUTE PLC1 WITH TYPE MODBUS_TCP - ADD MODBUS_CONFIG - WITH IP "192.168.1.100" - WITH PORT 502 - WITH SLAVE_ID 1 - ADD MAPPING "ReadRegisters" - WITH SOURCE_TOPIC "plc1/read" - WITH EVERY 1 SECONDS - ADD TAG "Temperature" - WITH ADDRESS "40001" - WITH DATA_TYPE "INT16" - WITH SCALING 0.1 - ADD TAG "Pressure" - WITH ADDRESS "40002" - WITH DATA_TYPE "FLOAT32" - ADD TAG "Running" - WITH ADDRESS "00001" - WITH DATA_TYPE "BOOL" -``` - -Data types: `INT16`, `INT32`, `UINT16`, `UINT32`, `FLOAT32`, `FLOAT64`, `BOOL`, `STRING` -Tag options: `ADDRESS`, `DATA_TYPE`, `SCALING`, `OFFSET`, `DEADBAND`, `PUBLISH_MODE` - -### Modbus Serial (RTU) -``` -DEFINE ROUTE SerialPLC WITH TYPE MODBUS_SERIAL - ADD MODBUS_CONFIG - WITH PORT "COM3" - WITH BAUD_RATE 9600 - WITH PARITY "None" - WITH STOP_BITS 1 - WITH SLAVE_ID 1 -``` - -### Siemens S7 -``` -DEFINE ROUTE S7PLC WITH TYPE SIEMENS_S7 - ADD S7_CONFIG - WITH IP "192.168.1.50" - WITH CPU_TYPE "S71500" - WITH RACK 0 - WITH SLOT 1 - ADD MAPPING "ReadDB" - WITH SOURCE_TOPIC "s7/read" - WITH EVERY 500 MILLISECONDS - ADD TAG "Speed" - WITH ADDRESS "DB1.DBD0" - WITH DATA_TYPE "REAL" - ADD TAG "Count" - WITH ADDRESS "DB1.DBW4" - WITH DATA_TYPE "INT" - ADD TAG "Enable" - WITH ADDRESS "DB1.DBX8.0" - WITH DATA_TYPE "BOOL" -``` - -CPU types: `S7300`, `S7400`, `S71200`, `S71500`, `LOGO` - -### OPC UA -``` -DEFINE ROUTE OpcServer WITH TYPE OPCUA - ADD OPCUA_CONFIG - WITH ENDPOINT_URL "opc.tcp://192.168.1.200:4840" - WITH SECURITY_MODE "None" - WITH USERNAME GET ENV "OPC_USER" - WITH PASSWORD GET SECRET "OPC_PASSWORD" - ADD MAPPING "ReadNodes" - WITH SOURCE_TOPIC "opc/read" - WITH EVERY 1 SECONDS - ADD TAG "Temperature" - WITH ADDRESS "ns=2;s=Channel1.Device1.Tag1" - WITH DATA_TYPE "DOUBLE" -``` - -Security modes: `None`, `Sign`, `SignAndEncrypt` - -### EtherNet/IP (Allen-Bradley / Rockwell) -``` -DEFINE ROUTE ABController WITH TYPE ETHERNETIP - ADD ETHERNETIP_CONFIG - WITH IP "192.168.1.75" - WITH SLOT 0 - ADD MAPPING "ReadTags" - WITH SOURCE_TOPIC "ab/read" - WITH EVERY 250 MILLISECONDS - ADD TAG "MotorSpeed" - WITH ADDRESS "Motor_Speed" - WITH DATA_TYPE "REAL" - ADD TAG "LineRunning" - WITH ADDRESS "Line_Running" - WITH DATA_TYPE "BOOL" -``` - -### Beckhoff TwinCAT (ADS) -``` -DEFINE ROUTE TwinCatPLC WITH TYPE ADS - ADD ADS_CONFIG - WITH AMS_NET_ID "192.168.1.100.1.1" - WITH PORT 851 - ADD MAPPING "ReadVariables" - WITH SOURCE_TOPIC "tc/read" - WITH EVERY 100 MILLISECONDS - ADD TAG "Velocity" - WITH ADDRESS "MAIN.Velocity" - WITH DATA_TYPE "LREAL" -``` - -### Omron FINS -``` -DEFINE ROUTE OmronPLC WITH TYPE FINS - ADD FINS_CONFIG - WITH IP "192.168.1.80" - WITH PORT 9600 - WITH PC_NODE 0 - WITH PLC_NODE 1 -``` - -### BACnet/IP -``` -DEFINE ROUTE BMS WITH TYPE BACNET - ADD BACNET_CONFIG - WITH IP "192.168.1.50" - WITH PORT 47808 - WITH DEVICE_ID 1234 - ADD MAPPING "RoomSensors" - WITH SOURCE_TOPIC "bacnet/bms" - WITH EVERY 1 SECONDS - ADD TAG "RoomTemp" - WITH ADDRESS "AI:0" - WITH DATA_TYPE "FLOAT" - WITH UNIT "degC" - ADD TAG "Setpoint" - WITH ADDRESS "AV:0" - WITH DATA_TYPE "FLOAT" - WITH WRITABLE true - WITH DESTINATION_TOPIC "bacnet/bms/setpoint/write" -``` - ---- - -## AI Routes - -### LLM Route (local or remote) -``` -DEFINE ROUTE LocalLLM WITH TYPE LLM - ADD LLM_CONFIG - WITH BASE_URL "http://localhost:11434" - WITH MODEL "llama3.2" - WITH TEMPERATURE 0.7 - WITH MAX_TOKENS 2048 -``` - -For OpenAI / cloud providers: -``` -DEFINE ROUTE OpenAI WITH TYPE LLM - ADD LLM_CONFIG - WITH BASE_URL "https://api.openai.com" - WITH MODEL "gpt-4o" - WITH API_KEY GET SECRET "OPENAI_API_KEY" -``` - -### MCP Client Route -``` -DEFINE ROUTE FilesystemMCP WITH TYPE MCP - ADD MCP_CONFIG - WITH TRANSPORT "stdio" - WITH COMMAND "npx" - WITH ARGS "-y @modelcontextprotocol/server-filesystem /data" -``` - -``` -DEFINE ROUTE DatabaseMCP WITH TYPE MCP - ADD MCP_CONFIG - WITH TRANSPORT "sse" - WITH URL "http://localhost:3000/sse" -``` - -### Agent Route -``` -DEFINE ROUTE Assistant WITH TYPE AGENT - ADD AGENT_CONFIG - WITH MODEL "llama3.2" - WITH BASE_URL "http://localhost:11434" - WITH MAX_ITERATIONS 10 - WITH BROKER_TOOLS true - WITH MCP_ROUTES "FilesystemMCP" - WITH SYSTEM_PROMPT "You are a factory assistant. Help operators monitor and control the production line." -``` - -Key agent config options: -| Setting | Default | Description | -|---------|---------|-------------| -| `MODEL` | — | LLM model name (required) | -| `BASE_URL` | — | LLM provider base URL | -| `BROKER_TOOLS` | false | Give agent access to broker tools | -| `MCP_ROUTES` | — | Comma-separated list of MCP route names | -| `MAX_ITERATIONS` | 10 | Max tool call loops per response | -| `SYSTEM_PROMPT` | — | Agent persona and instructions | -| `TEMPERATURE` | 0.7 | LLM creativity | -| `MAX_TOKENS` | 4096 | Max tokens per response | - ---- - -## REST API Routes - -### REST API Client (outbound) -``` -DEFINE ROUTE WeatherAPI WITH TYPE REST_API - ADD REST_API_CONFIG - WITH BASE_ADDRESS "https://api.weather.com" - WITH AUTHORIZATION GET SECRET "WEATHER_API_KEY" - ADD EVENT GetForecast - WITH SOURCE_TOPIC "weather/request" - WITH DESTINATION_TOPIC "weather/forecast" - WITH METHOD "GET" - WITH ENDPOINT "/v1/forecast?city={payload}" - ADD EVENT PostReading - WITH SOURCE_TOPIC "sensors/upload" - WITH METHOD "POST" - WITH ENDPOINT "/v1/readings" - WITH BODY "{payload.json}" -``` - -### REST API Server (inbound — expose broker data over HTTP) -``` -DEFINE ROUTE BrokerAPI WITH TYPE REST_API - ADD REST_API_CONFIG - WITH SERVER_PORT 8080 - ADD EVENT GetStatus - WITH METHOD "GET" - WITH ENDPOINT "/api/status" - WITH SOURCE_TOPIC "system/status" - ADD EVENT SendCommand - WITH METHOD "POST" - WITH ENDPOINT "/api/command" - WITH DESTINATION_TOPIC "system/commands" -``` - ---- - -## MQTT Bridge -``` -DEFINE ROUTE CloudBridge WITH TYPE MQTT_BRIDGE - ADD SOURCE_CONFIG - WITH BROKER SELF - ADD DESTINATION_CONFIG - WITH BROKER_ADDRESS "broker.example.com" - WITH BROKER_PORT 8883 - WITH CLIENT_ID "bridge-client" - WITH USERNAME GET ENV "BRIDGE_USER" - WITH PASSWORD GET SECRET "BRIDGE_PASSWORD" - WITH USE_TLS true - ADD MAPPING "ForwardSensors" - WITH SOURCE_TOPIC "sensors/#" - WITH DESTINATION_TOPIC "cloud/factory/sensors/#" - WITH DIRECTION "out" -``` - ---- - -## Email Route -``` -DEFINE ROUTE AlertEmail WITH TYPE EMAIL - ADD SMTP_CONFIG - WITH SERVER "smtp.example.com" - WITH PORT 587 - WITH USERNAME GET ENV "SMTP_USER" - WITH PASSWORD GET SECRET "SMTP_PASSWORD" - WITH FROM "alerts@factory.com" - WITH USE_TLS true - ADD EVENT SendAlert - WITH SOURCE_TOPIC "alerts/critical" - WITH TO "ops@factory.com" - WITH SUBJECT "Critical Alert: {topic.2}" - WITH BODY "Alert received: {payload} at {timestamp}" -``` - ---- - -## TRIGGER from LOT Actions - -Invoke a route event programmatically from an action: -``` -TRIGGER "ReadSensors" TO ProductionDB WITH "sensor1" -``` - ---- - -## Common Mistakes - -``` --- WRONG: Missing WITH TYPE -DEFINE ROUTE MyDB - ADD SQL_CONFIG ... - --- RIGHT: -DEFINE ROUTE MyDB WITH TYPE POSTGRESQL - ADD SQL_CONFIG ... -``` - -``` --- WRONG: Wrong config block for route type -DEFINE ROUTE MyDB WITH TYPE POSTGRESQL - ADD MODBUS_CONFIG ... -- wrong! - --- RIGHT: -DEFINE ROUTE MyDB WITH TYPE POSTGRESQL - ADD SQL_CONFIG ... -``` - -``` --- WRONG: Hardcoded password -WITH PASSWORD "mysecretpassword" - --- RIGHT: -WITH PASSWORD GET SECRET "DB_PASSWORD" -``` - -``` --- WRONG: 0-based topic position -WITH QUERY "SELECT * FROM t WHERE zone = '{topic.0}'" - --- RIGHT (1-based): -WITH QUERY "SELECT * FROM t WHERE zone = '{topic.1}'" -``` - -``` --- WRONG: Missing DESTINATION_TOPIC when result is expected -ADD EVENT GetData - WITH SOURCE_TOPIC "data/query" - WITH QUERY "SELECT * FROM data" --- Result goes nowhere! - --- RIGHT: -ADD EVENT GetData - WITH SOURCE_TOPIC "data/query" - WITH DESTINATION_TOPIC "data/result" - WITH QUERY "SELECT * FROM data" -``` - -``` --- WRONG: Using DESTINATION_TOPIC on OT TAG mapping as the topic for live values -ADD MAPPING "Poll" - WITH SOURCE_TOPIC "plc/read" - WITH DESTINATION_TOPIC "plc/data" --- Values are on plc/read/, not plc/data - --- RIGHT: -ADD MAPPING "Poll" - WITH SOURCE_TOPIC "plc/read" - WITH EVERY 1 SECONDS - ADD TAG "Temperature" ... -``` - -``` --- WRONG: ADD METADATA in route definitions (parser rejects it) -DEFINE ROUTE PLC1 WITH TYPE MODBUS_TCP - ADD MODBUS_CONFIG - WITH IP "192.168.1.1" - ADD MAPPING "Poll" - ... - ADD METADATA -- wrong! Parser does not support ADD METADATA - WITH DESCRIPTION "..." -- strip this from templates - --- ADD METADATA blocks appear in route templates (-routeCode TYPE / the --- broker_route_template tool) for documentation only. broker_route_template --- returns a `skeleton` with the block already removed — deploy that. -``` - -``` --- WRONG: ADD TAG outside MAPPING block -DEFINE ROUTE PLC1 WITH TYPE MODBUS_TCP - ADD MODBUS_CONFIG - WITH IP "192.168.1.1" - ADD TAG "Temp" -- wrong! TAG must be inside MAPPING - WITH ADDRESS "40001" - --- RIGHT: - ADD MAPPING "Poll" - WITH SOURCE_TOPIC "plc/read" - WITH EVERY 1 SECONDS - ADD TAG "Temp" - WITH ADDRESS "40001" - WITH DATA_TYPE "INT16" -``` diff --git a/plugins/coreflux/skills/lot-models/SKILL.md b/plugins/coreflux/skills/lot-models/SKILL.md new file mode 100644 index 0000000..4e5812a --- /dev/null +++ b/plugins/coreflux/skills/lot-models/SKILL.md @@ -0,0 +1,329 @@ +--- +name: lot-models +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 + +## CRITICAL SYNTAX + +Model names are NEVER quoted in DEFINE. Field names and topic strings ARE quoted. +``` +WRONG: DEFINE MODEL "SensorReading" WITH TOPIC "sensors/data" +RIGHT: DEFINE MODEL SensorReading WITH TOPIC "sensors/data" +``` + +Static field defaults use WITH directly — NEVER use WITH VALUE (parser rejects it for anything but a plain literal). +``` +WRONG: ADD STRING "timestamp" WITH VALUE TIMESTAMP "ISO" +RIGHT: ADD STRING "timestamp" WITH TIMESTAMP "ISO" + +WRONG: ADD STRING "id" WITH VALUE RANDOM UUID +RIGHT: ADD STRING "id" WITH RANDOM UUID + +AVOID: ADD STRING "status" WITH VALUE "ok" (accepted for literals only) +RIGHT: ADD STRING "status" WITH "ok" +``` + +Model names that are a LoT keyword in any case are rejected with LOT1001 — e.g. `Device`, +`Event`, `Unit`, `Tag`, `Table`, `Type`, `Alarm`, `Metric`, `Store`, `Fetch`. Use a compound +name such as `DeviceInfo` or `EventRecord`. + +## Basic Structure + +``` +DEFINE MODEL WITH TOPIC "" + ADD "" WITH TOPIC "" [AS TRIGGER] + ADD "" WITH +``` + +Models define data schemas that map MQTT topics to typed fields. + +## Field Types +- STRING — text values (timestamps too: `ADD STRING "ts" WITH TIMESTAMP "ISO"`) +- INT — integer numbers +- DOUBLE — floating-point numbers (FLOAT / SINGLE are accepted; protobuf wire alias) +- BOOL — true/false +- ARRAY (or LIST) — JSON arrays; `ARRAY ` is an array of another model +- OBJECT (or MAP / DICTIONARY) — nested JSON objects (embedded as-is, not as string) +- `` — a nested model: `ADD Reading "last"` (or `ADD MODEL Reading "last"`) + +`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. + +## Field Bindings + +### WITH TOPIC — bind field to an MQTT topic +``` +ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" +``` + +### AS TRIGGER — field topic triggers model update +``` +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. + +### 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. +``` +ADD STRING "id" WITH RANDOM UUID +ADD STRING "timestamp" WITH TIMESTAMP "ISO" +ADD STRING "timestamp" WITH TIMESTAMP "UTC" +ADD STRING "status" WITH "ok" +ADD INT "count" WITH 0 +ADD BOOL "active" WITH FALSE +ADD DOUBLE "offset" WITH 0.0 +``` + +## Complete Example + +``` +DEFINE MODEL SensorReading WITH TOPIC "factory/sensors/data" + ADD STRING "deviceId" WITH TOPIC "factory/sensors/id" AS TRIGGER + ADD DOUBLE "temperature" WITH TOPIC "factory/sensors/temp" + ADD DOUBLE "humidity" WITH TOPIC "factory/sensors/humidity" + ADD STRING "timestamp" WITH TIMESTAMP "ISO" + ADD STRING "status" WITH "ok" +``` + +## Model Options + +### RETAIN — retain model output on MQTT +``` +DEFINE MODEL Config WITH TOPIC "device/config" RETAIN +``` +RETAIN and QOS are applied when an action runs `PUBLISH MODEL`. A topic-bound model +(published by its AS TRIGGER fields) currently publishes non-retained at QoS 0 whatever the +header says. + +### QoS levels +``` +DEFINE MODEL Critical WITH TOPIC "alerts/data" QOS1 +``` +Options: QOS0 (default), QOS1, QOS2 + +### FORMAT — wire format +`WITH FORMAT PROTOBUF` (or `JSON`, the default, or `BOTH`: JSON on the topic, protobuf on +`/protobuf`). Header clauses (FROM, COLLAPSED, KEEP, WITH TOPIC, RETAIN, QOS, FORMAT) +may appear in any order. + +## Model Behaviors + +### Default — whole JSON plus one subtopic per field +The full JSON object is published on ``, and each field is also published to +`/`. + +### COLLAPSED — all fields as single JSON object +``` +DEFINE MODEL EventRecord COLLAPSED WITH TOPIC "events/data" + ADD STRING "id" WITH RANDOM UUID + ADD STRING "type" WITH "alert" + ADD STRING "timestamp" WITH TIMESTAMP "ISO" + ADD DOUBLE "value" WITH TOPIC "sensors/temp" AS TRIGGER +``` +Output: a single JSON payload `{"id":"...","type":"alert","timestamp":"...","value":23.5}` on `events/data`. + +### KEEP — field subtopics stay inside the broker +``` +DEFINE MODEL LineState KEEP WITH TOPIC "line/state" + ADD DOUBLE "speed" WITH TOPIC "line/speed" AS TRIGGER +``` +The JSON on `` is published as usual, but the per-field `/` +values are only stored in the broker's topic cache (readable with GET TOPIC), not sent to +MQTT subscribers. With `PUBLISH MODEL`, a KEEP model stores the JSON too and publishes nothing. + +## Model Inheritance (FROM) + +Child models inherit ALL fields from their parent and can add new ones. +Use inheritance when multiple models share common structure but differ in specialization. + +**Rules:** +- Parent model MUST be defined BEFORE the child (order matters) +- Child CANNOT remove inherited fields +- Child CAN add new fields with ADD +- Child CAN override inherited field topics by re-declaring them +- Inheritance can be multi-level (grandparent → parent → child) + +### Step 1 — Define the base model first +``` +DEFINE MODEL BaseSensor WITH TOPIC "sensors/base" + ADD STRING "deviceId" WITH TOPIC "sensors/id" AS TRIGGER + ADD STRING "location" WITH TOPIC "sensors/location" + ADD STRING "timestamp" WITH TIMESTAMP "ISO" + ADD STRING "status" WITH "ok" +``` + +### Step 2 — Specialize it with child models +``` +DEFINE MODEL TemperatureSensor FROM BaseSensor WITH TOPIC "sensors/temperature" + ADD DOUBLE "celsius" WITH TOPIC "sensors/temp/celsius" AS TRIGGER + ADD DOUBLE "fahrenheit" WITH TOPIC "sensors/temp/fahrenheit" + ADD STRING "unit" WITH "°C" + +DEFINE MODEL HumiditySensor FROM BaseSensor WITH TOPIC "sensors/humidity" + ADD DOUBLE "humidity" WITH TOPIC "sensors/humidity/value" AS TRIGGER + ADD DOUBLE "dewPoint" WITH TOPIC "sensors/humidity/dewpoint" +``` + +Each child publishes all base fields (deviceId, location, timestamp, status) PLUS its own. + +### Multi-level inheritance +``` +-- Level 1: base with identity fields +DEFINE MODEL DeviceBase WITH TOPIC "devices/base" + ADD STRING "deviceId" WITH TOPIC "devices/id" AS TRIGGER + ADD STRING "firmware" WITH TOPIC "devices/firmware" + ADD STRING "timestamp" WITH TIMESTAMP "ISO" + +-- Level 2: sensor adds measurement fields +DEFINE MODEL Sensor FROM DeviceBase WITH TOPIC "sensors/base" + ADD STRING "unit" WITH TOPIC "sensors/unit" + ADD DOUBLE "value" WITH TOPIC "sensors/value" + +-- Level 3: specialized sensor for a specific measurement +DEFINE MODEL PressureSensor FROM Sensor WITH TOPIC "sensors/pressure" + ADD DOUBLE "bar" WITH TOPIC "sensors/pressure/bar" AS TRIGGER + ADD STRING "grade" WITH "industrial" +``` + +### Inheritance + COLLAPSED +``` +-- Parent: shared fields +DEFINE MODEL EventBase WITH TOPIC "events/base" + ADD STRING "id" WITH RANDOM UUID + ADD STRING "timestamp" WITH TIMESTAMP "ISO" + ADD STRING "source" WITH TOPIC "system/name" AS TRIGGER + +-- Child: specialized event type, collapsed to one JSON +DEFINE MODEL AlertEvent COLLAPSED FROM EventBase WITH TOPIC "events/alerts" + ADD STRING "severity" WITH TOPIC "alerts/severity" + ADD STRING "message" WITH TOPIC "alerts/message" + ADD STRING "zone" WITH TOPIC "alerts/zone" +``` + +### When to use inheritance +Use inheritance when: same base fields appear in many models (device ID, timestamp, location). +Define the base once, extend everywhere. If a field changes (e.g. timestamp format), update in one place. + +## Database Storage (STORE IN) + +``` +DEFINE MODEL SensorLog WITH TOPIC "sensors/log" + ADD DOUBLE "temperature" WITH TOPIC "sensors/temp" AS TRIGGER + ADD STRING "timestamp" WITH TIMESTAMP "ISO" + STORE IN "MyDB" WITH TABLE "sensor_readings" +``` + +### Conditional storage +``` + STORE IN "MyDB" WITH TABLE "alerts" WHEN {temperature} > 50 +``` + +## Database Fetch (FETCH FROM) + +Accepted but not run yet (warning LOT4005, ENG-417): the model publishes without querying the route. + +``` + FETCH FROM "MyDB" WITH TABLE "sensors" WHEN id EQUALS "sensor1" LIMIT 10 +``` + +## When to Use PUBLISH MODEL vs Topic Bindings + +### Pattern 1 — Topic-binding model (simple streaming, no logic) +Use when data flows directly from MQTT topics into a structured output with no computation. +The model fires automatically when a TRIGGER topic receives a message. +``` +DEFINE MODEL BoilerStatus COLLAPSED WITH TOPIC "factory/boiler/data" + ADD STRING "boilerId" WITH TOPIC "factory/boiler/id" AS TRIGGER + ADD DOUBLE "temperature" WITH TOPIC "factory/boiler/temp" + ADD DOUBLE "pressure" WITH TOPIC "factory/boiler/pressure" + ADD STRING "timestamp" WITH TIMESTAMP "UTC" +``` +Good for: pass-through aggregation, display dashboards, simple monitoring. + +### Pattern 2 — PUBLISH MODEL from an action (streaming with logic/aggregation) +Use when data needs processing, conditional logic, external calls, or multiple source aggregation. +RECOMMENDED for most data streaming scenarios — it gives full control and clean schema. + +**Key design rule:** Put static and repeating fields in DEFINE MODEL — IDs, timestamps, +unit labels, firmware version, location constants. These fill automatically. +The action only passes the fields that actually change per event. + +``` +-- Step 1: Define the schema. Static/repeating fields go HERE. +DEFINE MODEL SensorReading COLLAPSED + ADD STRING "timestamp" WITH TIMESTAMP "UTC" -- auto-generated every time + ADD STRING "unit" WITH "celsius" -- always the same + ADD STRING "firmware" WITH "v2.1" -- constant + ADD STRING "deviceId" -- dynamic — action fills this + ADD DOUBLE "temperature" -- dynamic — action fills this + ADD STRING "status" -- dynamic — action fills this + +-- Step 2: The action handles logic and only passes the 3 dynamic fields. +DEFINE ACTION StreamSensorData +ON TOPIC "sensors/+/raw" DO + SET "id" WITH TOPIC POSITION 2 + SET "temp" WITH PAYLOAD AS DOUBLE + SET "status" WITH "ok" + IF {temp} > 85 THEN + SET "status" WITH "critical" + PUBLISH MODEL SensorReading TO "sensors/" + {id} + "/processed" WITH + deviceId = {id} + temperature = {temp} + status = {status} +``` + +Result: the agent produces `{timestamp, unit, firmware, deviceId, temperature, status}` — the +schema is fully defined, the action is clean, and static fields never need repeating. + +### Pattern 3 — PUBLISH MODEL for repeated multi-asset streaming +When the same model structure is published for many assets (machines, sensors, zones), +define the schema once with all static fields, and let the action loop or react per-asset. + +``` +DEFINE MODEL MachineStatus COLLAPSED + ADD STRING "timestamp" WITH TIMESTAMP "UTC" + ADD STRING "plant" WITH "Factory-A" + ADD STRING "machineId" + ADD STRING "state" + ADD DOUBLE "cycleTime" + ADD INT "partCount" + +DEFINE ACTION TrackMachines +ON TOPIC "machines/+/cycle" DO + SET "machine" WITH TOPIC POSITION 2 + SET "cycles" WITH GET JSON "count" IN PAYLOAD AS INT + SET "time" WITH GET JSON "cycleMs" IN PAYLOAD AS DOUBLE + PUBLISH MODEL MachineStatus TO "machines/" + {machine} + "/status" WITH + machineId = {machine} + state = "running" + cycleTime = {time} + partCount = {cycles} +``` + +### Decision guide + +| Scenario | Use | +|----------|-----| +| Simple topic→JSON pass-through, no logic | Topic-binding model (no action needed) | +| Data needs computation, filtering, or logic | PUBLISH MODEL from action | +| Same structure published for many assets | PUBLISH MODEL from action | +| Need to call Python, MCP, or LLM first | PUBLISH MODEL from action | +| Fields come from different systems/routes | PUBLISH MODEL from action | +| Static display model (config, metadata) | PUBLISH MODEL from action with a RETAIN model (topic-bound models ignore RETAIN) | + +## Common Mistakes + +| WRONG | RIGHT | +|-------|-------| +| DEFINE MODEL "SensorReading" | DEFINE MODEL SensorReading | +| ADD STRING "ts" WITH VALUE TIMESTAMP "ISO" | ADD STRING "ts" WITH TIMESTAMP "ISO" — no VALUE keyword | +| ADD STRING "id" WITH VALUE RANDOM UUID | ADD STRING "id" WITH RANDOM UUID — no VALUE keyword | +| 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" | +| 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 new file mode 100644 index 0000000..e0c5cc8 --- /dev/null +++ b/plugins/coreflux/skills/lot-panels/SKILL.md @@ -0,0 +1,1968 @@ +--- +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. +--- + +# LoTV Panel Authoring — Coreflux Visual Language + +ALWAYS call broker.load_skill("lot-panels") before broker.add_panel. + +--- + +## Dashboard Generation Best Practices (read before writing any panel) + +These rules apply to EVERY panel you generate. Follow them by default — only +deviate when the user explicitly asks for something different. + +### Rule 0 — CANONICAL INDENTATION (mandatory; mixed indent breaks the parser) + +Every panel-level `WITH …` line AND every top-level `ADD COMPONENT` line must +be indented EXACTLY 4 spaces under `DEFINE PANEL`. Component child lines +(`SET`, `BIND`, `ON …`, nested `ADD COMPONENT`) indent a further 4 spaces. +NEVER mix flush-left and indented `WITH` lines in the same panel. The parser +re-aligns the panel-level `WITH` lines that come before the first `ADD COMPONENT` +and returns a warning, but any other mixed indentation shifts lines to the wrong +nesting level. + +```lot +// ❌ WRONG — WITH VISIBILITY at column 0 mixes indentation; the parser +// re-aligns it and warns "had mixed panel-level WITH indentation". +DEFINE PANEL "OperationalKpiDashboard" + WITH TITLE "Operational KPI Dashboard" + WITH LAYOUT COLUMNS 3 + WITH STATE PUBLISHED +WITH VISIBILITY PUBLIC + + ADD COMPONENT value WITH ID MessageCountValue + ... +``` + +```lot +// ✅ CORRECT — every panel-level WITH and every top-level ADD COMPONENT +// at exactly 4 spaces under DEFINE PANEL. +DEFINE PANEL "OperationalKpiDashboard" + WITH TITLE "Operational KPI Dashboard" + WITH LAYOUT "grid" COLUMNS 3 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "MessageCountGauge" WITH TYPE "gauge" + SET LABEL "Message Count" + SET UNIT "msg" + SET RANGE FROM 0 TO 200 + BIND VALUE TO TOPIC "kpi/operational/messageCount" +``` + +If a `broker.add_panel` response ever contains a warning like +`had mixed panel-level WITH indentation`, your panel is malformed. Re-emit +it with consistent 4-space indentation. + +### Rule 0.5 — GRID-FIRST (mandatory; never omit `WITH LAYOUT`) + +EVERY panel you emit MUST declare `WITH LAYOUT "grid" COLUMNS N` immediately +after `DEFINE PANEL` (right after `WITH TITLE`). Omitting `WITH LAYOUT` falls +back to the legacy `vertical` default, which renders every widget as a single +full-width row stacked top-to-bottom — that is BROKEN output, not a layout. + +**Pick `N` (`COLUMNS`) by counting top-level `ADD COMPONENT` lines in the panel:** + +| Top-level component count | `COLUMNS` value | +|---|---| +| 1 | `COLUMNS 1` (single full-width widget — rare; usually means you should add more) | +| 2 | `COLUMNS 2` | +| 3 | `COLUMNS 3` | +| 4–6 | `COLUMNS 3` | +| 7+ | `COLUMNS 4` | +| Form-only panel (only `text-field` / `switch` / `slider` / `button`) | `COLUMNS 2` | + +**Only exception:** HMI / SCADA / P&ID / control-panel screens use +`WITH LAYOUT "positioned"` (see Decision A below). Every other panel — every +dashboard, monitoring view, KPI screen, form, overview — uses `grid`. + +```lot +// ❌ WRONG — no WITH LAYOUT line. Every widget renders full-width, stacked. +DEFINE PANEL "OperationalKpiDashboard" + WITH TITLE "Operational KPI Dashboard" + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "MessageCountGauge" WITH TYPE "gauge" ... + ADD COMPONENT "MessagesPerMinuteGauge" WITH TYPE "gauge" ... + ADD COMPONENT "StatusIndicator" WITH TYPE "indicator" ... + ADD COMPONENT "TrendChart" WITH TYPE "realtime-chart" ... +``` + +```lot +// ✅ CORRECT — 4 top-level components → COLUMNS 3 by the count rule. +DEFINE PANEL "OperationalKpiDashboard" + WITH TITLE "Operational KPI Dashboard" + WITH LAYOUT "grid" COLUMNS 3 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "MessageCountGauge" WITH TYPE "gauge" ... + ADD COMPONENT "MessagesPerMinuteGauge" WITH TYPE "gauge" ... + ADD COMPONENT "StatusIndicator" WITH TYPE "indicator" ... + ADD COMPONENT "TrendChart" WITH TYPE "realtime-chart" ... +``` + +If a `broker.add_panel` response contains a warning like `has N top-level +components but no WITH LAYOUT line; defaulting to 'vertical'`, your panel is +broken. Re-emit it with `WITH LAYOUT "grid" COLUMNS N` chosen via the table +above. + +**Self-check before calling `broker.add_panel`:** read your own source — +does the line immediately after `DEFINE PANEL`/`WITH TITLE` start with +`WITH LAYOUT "grid" COLUMNS` (or `WITH LAYOUT "positioned"` for an HMI)? +If not, re-emit before deploying. + +### Rule 1 — VISUAL-FIRST (mandatory; never emit a panel of plain "value" widgets) + +Dashboards must be GRAPHICAL. Operators read shape and colour faster than +numbers. Pick the most visual component for each data shape — `value` is a +fallback, not a default. + +| Data shape | REQUIRED component | +|---|---| +| Numeric scalar with a known/inferable range | `gauge` (and add a `realtime-chart` beside it if it updates continuously) | +| Numeric scalar with unknown range | Ask via `agent.ask_user` for the range, THEN use `gauge`. Do NOT fall back to `value`. | +| Continuously updating scalar (live trend) | `realtime-chart` (often paired with a `gauge` for the instantaneous reading) | +| Historical JSON array with timestamps | `chart` + `SET COLUMNS "timestamp,..."` + `BIND DATA` | +| Boolean / discrete state (on/off, run/idle, alarm)| `indicator` (color changes by state). ALWAYS the default. Do NOT also add a `switch` unless the user explicitly asks for a toggle (see Rule 1.5). | +| Command / write action | ONLY when user explicitly asks for a control. `button` (one-shot, requires `ON CLICK DO PUBLISH`) or `switch` (boolean toggle, requires `ON TOGGLE DO PUBLISH ... WITH STATE`). NEVER a `value`. NEVER auto-add. | +| Setpoint or any user-editable number | ONLY when user explicitly asks. `slider` or `text-field` with `ON CHANGE DO PUBLISH ... WITH VALUE`. | +| Status string / text counter / non-numeric label | `text` (or `value` only if `text` is wrong) | +| GPS position, fleet locations | `map` with `BIND LOCATION` / `BIND MARKERS` | +| JSON array of records | `table` (with `SET COLUMNS`) — NEVER repeated `value` widgets | + +**Hard ban:** `WITH TYPE "value"` is FORBIDDEN for any numeric scalar that +has (or can have) a sensible range. Replace it with `gauge`. Every panel you +emit MUST contain at least one `gauge`, `chart`, `realtime-chart`, `indicator`, +`map`, or `svg` widget. A panel made entirely of `value` / `text` widgets is +considered broken and must be re-emitted. + +### Rule 1.5 — DO NOT AUTO-CREATE WRITE CONTROLS (mandatory) + +`switch`, `slider`, `text-field`, and write-style `button` components are +INTERACTIVE WRITE CONTROLS. They send data back to the broker. Never add one +"because the topic looks writable" or "to pair with an indicator". Only emit +a write control when the user EXPLICITLY asks for it (e.g. "let me toggle X", +"add a button to start the pump", "I want to set the setpoint from the UI"). + +For booleans the DEFAULT is read-only `indicator`. A `switch` next to an +`indicator` is FORBIDDEN unless the user asked for the toggle. Topic paths +that look like writes (e.g. `.../write`, `.../cmd`, `.../setpoint`) are NOT a +license to auto-add a control — still wait for an explicit user request. + +When (and ONLY when) you do emit a `switch`, it MUST contain an +`ON TOGGLE DO PUBLISH TOPIC "..." WITH STATE` block. A `switch` bound only +with `BIND VALUE TO TOPIC ...` (no `ON TOGGLE`) is a DEAD toggle and is +considered broken output — either remove it, or add the publish action. The +same rule applies to `button` (requires `ON CLICK DO PUBLISH`), `slider` +(requires `ON CHANGE DO PUBLISH ... WITH VALUE`), and `text-field` used as a +setpoint (requires `ON CHANGE DO PUBLISH ... WITH VALUE`). + +```lot +// ❌ WRONG — auto-added next to an indicator, no publish action. Dead toggle. +ADD COMPONENT "BoolWriteIndicator" WITH TYPE "indicator" + BIND STATE TO TOPIC "s7/simulator/io/BoolWrite" +ADD COMPONENT "BoolWriteSwitch" WITH TYPE "switch" + SET LABEL "Write BoolWrite" + BIND VALUE TO TOPIC "s7/simulator/io/BoolWrite/write" + +// ✅ CORRECT — read-only by default; no switch unless user explicitly asked. +ADD COMPONENT "BoolWriteIndicator" WITH TYPE "indicator" + SET LABEL "BoolWrite Input" + BIND STATE TO TOPIC "s7/simulator/io/BoolWrite" + +// ✅ CORRECT — user explicitly asked "add a toggle to write BoolWrite". +// The switch has the mandatory ON TOGGLE DO PUBLISH ... WITH STATE block. +ADD COMPONENT "BoolWriteSwitch" WITH TYPE "switch" + SET LABEL "Write BoolWrite" + BIND VALUE TO TOPIC "s7/simulator/io/BoolWrite/write" + ON TOGGLE DO + PUBLISH TOPIC "s7/simulator/io/BoolWrite/write" WITH STATE +``` + +### Digital twin renderer extensions + +Updated Hub renderers support `web-view` for scoped static iframe surfaces +(`SET SRC`, optional `SET ALLOWED_ORIGIN` for an exact remote HTTPS origin, +`SET HEIGHT`) and `twin-controls` for acknowledged supervisory commands +(`SET CONTRACT_TOPIC`, optional comma-separated `SET ACTIONS`). Do not treat +`frame` as an iframe: it remains a transparent layout group. On a card, +`SET LIVE_CONTRACT` and comma-separated `SET LIVE_MODELS` enable identity, +wall-clock freshness and monotonic-sequence guards in the matching Hub. +Use exact MQTT topics with explicit `WITH JSON_PATH` for collapsed JSON fields. +Do not generate static reused command envelopes or report publish receipts as +host acceptance. These extensions require a compatible Hub renderer; there is +no negotiated capability handshake yet. + +### Rule 2 — TIME-SERIES FIRST + +Any time-based data uses a chart (`realtime-chart` for live scalars, `chart` +for historical JSON arrays). Never render trends as a single value or gauge +alone. + +### Rule 3 — Naming and labels + +Give widgets descriptive PascalCase IDs (`NozzleTempGauge`, `AlarmsTable`) +and human-readable labels with units (e.g. `'Nozzle Temp (°C)'`). Never name +widgets `Comp1` or reuse topic paths as labels. + +### Rule 4 — Layout order + +Arrange top-to-bottom: headline gauges + indicators first, then realtime-charts, +then tables, then controls. The `COLUMNS` value itself is set by the +widget-count rule in Rule 0.5 (1–3 → COLUMNS = count, 4–6 → 3, 7+ → 4, +forms-only → 2) — never emit a panel without `WITH LAYOUT "grid" COLUMNS N`. + +### Rule 5 — CANONICAL `SET` vs `WITH` vs `BIND` (mandatory; mixing them silently breaks panels) + +`WITH` is **only** for the `ADD COMPONENT` header and a short list of header +clauses. Every *property* of a component goes on its own indented `SET` line. +Every *data source* goes on its own indented `BIND` line. The broker parser +now emits a warning on `$SYS/Coreflux/Command/Output` every time you get this +wrong, and `broker.add_panel` returns those warnings in its response — **read +the warnings and re-emit the panel in canonical form**. + +**`WITH` is allowed only for (component header):** `TYPE`, `ID`, `COLUMN_SPAN`, +`ROW_SPAN`, `LABEL`, `STYLE`, `TEXT`, `MIN`, `MAX`, `TOPIC`, `INTERACT`, +`INTERACT_DENY`. Everything else on a component goes under an indented `SET` +line. + +**Every bind needs both `TO` and a source keyword.** The canonical form is: +`BIND TO "reference"`, where ` ∈ VALUE / STATE / +CONTENT / COLOR / TITLE / LABEL / MAX / MIN / VISIBLE / DATA / SPEED / +LOCATION / MARKERS / TRACE` and ` ∈ TOPIC / MODEL / QUERY`. Any +shorthand that omits the target or the `TO` keyword is wrong — the parser +auto-corrects the common cases but **you must not emit them**. + +| Anti-pattern (WRONG) | Canonical (CORRECT) | +|---|---| +| `WITH UNIT "msg"` (on component body) | `SET UNIT "msg"` (indented under component) | +| `WITH RANGE 0, 200` / `WITH RANGE 0 TO 200` | `SET RANGE FROM 0 TO 200` | +| `WITH RANGE "0,200"` / `WITH RANGE "0-127"` (quoted CSV/dash) | `SET RANGE FROM 0 TO 200` — the quoted form silently rendered gauges as NaN before the parser learned to split it | +| `WITH DECIMALS 2` | `SET DECIMALS 2` | +| `WITH PLACEHOLDER "…"` | `SET PLACEHOLDER "…"` | +| `WITH Y_MIN 0` / `WITH Y_MAX 100` | `SET Y_MIN 0` / `SET Y_MAX 100` | +| `WITH CHART_TYPE "line"` | `SET CHART_TYPE "line"` | +| `WITH ZOOM 6` / `WITH CENTER_LAT 35.0` / `WITH CLUSTER true` / `WITH TILE_URL "…"` | `SET ZOOM 6` / `SET CENTER_LAT 35.0` / `SET CLUSTER true` / `SET TILE_URL "…"` | +| `WITH SERIES "Message Count"` on a realtime-chart | `BIND VALUE TO TOPIC "…"` + indented `SET SERIES_LABEL "Message Count"` | +| `WITH TRACE_DEPTH 20` / `WITH LAT_FIELD "lat"` | Indented `SET TRACE_DEPTH 20` / `SET LAT_FIELD "lat"` **under the matching BIND** | +| `WITH TYPE "line"` **inside a component body** after `ADD COMPONENT "X" TYPE "realtime-chart"` | Remove the duplicate line — TYPE goes **only** on the `ADD COMPONENT` header | +| `BIND TOPIC "kpi/x"` (no target, no `TO`) | `BIND VALUE TO TOPIC "kpi/x"` | +| `BIND MODEL "M.f"` / `BIND QUERY "Route"` | `BIND VALUE TO MODEL "M.f"` / `BIND DATA TO QUERY "Route"` | +| `BIND VALUE TOPIC "kpi/x"` (missing `TO`) | `BIND VALUE TO TOPIC "kpi/x"` | +| `BIND SERIES "Label" TO TOPIC "…"` (SERIES is not a bind target) | `BIND VALUE TO TOPIC "…"` + `SET SERIES_LABEL "Label"` | +| `BIND ROWS TO TOPIC "…"` / `BIND RECORD TO TOPIC "…"` on a table | `BIND DATA TO TOPIC "…"` + `SET COLUMNS "field1,field2"` | +| `BIND VALUE TO TOPIC "…" AS LENGTH` / `AS COUNT` / `AS JSON` | Gauges cannot count JSON arrays. Bind a **scalar number** topic with `AS NUMBER`, or `WITH JSON_PATH "countField"`. Tables use `BIND DATA`. | +| `ADD COMPONENT StatusGauge OF TYPE gauge` | `ADD COMPONENT "StatusGauge" WITH TYPE "gauge"` | +| `BIND STATE TO TOPIC "MbtaAlertsFeed/status"` | Route health lives at `$SYS/Coreflux/Routes//status` — then `WITH JSON_PATH "health"` or `"connection"` | +| `ON CLICK PUBLISH TOPIC "…"` (missing `DO`) | `ON CLICK DO PUBLISH TOPIC "…" WITH "{}"` | +| `BIND TEXT TO TOPIC "status"` on `value`/`text` widgets (SVG-only form) | `BIND VALUE TO TOPIC "status"` (or `BIND CONTENT` for `text` type) | +| `BIND TEXT "id" TO TOPIC "t"` outside an `svg` component | Move into `WITH TYPE "svg"` or use `BIND VALUE TO TOPIC` on gauges/values | + +**Five failures from a real broken panel, with fixes:** + +```lot +// WRONG — every one of these lines used to parse "successfully" and the dashboard +// rendered gauges stuck at 0.0 and charts stuck on "Waiting for data…". +ADD COMPONENT "MessageCountGauge" TYPE "gauge" + WITH LABEL "Message Count" + WITH RANGE 0, 200 // only 0 reached min; 200 eaten + WITH UNIT "msg" // stored as Props["UNIT"]; renderer reads "unit" + BIND TOPIC "kpi/…" // binding SILENTLY DROPPED + +ADD COMPONENT "MessageCountTrend" TYPE "realtime-chart" + BIND TOPIC "kpi/…" // binding SILENTLY DROPPED + WITH SERIES "Message Count" // unknown prop; series never shown + WITH TYPE "line" // OVERWROTE realtime-chart → "line" → card placeholder + +// CORRECT +ADD COMPONENT "MessageCountGauge" TYPE "gauge" + SET LABEL "Message Count" + SET RANGE FROM 0 TO 200 + SET UNIT "msg" + BIND VALUE TO TOPIC "kpi/…" + +ADD COMPONENT "MessageCountTrend" TYPE "realtime-chart" + BIND VALUE TO TOPIC "kpi/…" + SET SERIES_LABEL "Message Count" + SET UNIT "msg" +``` + +**Pre-deploy self-check — run this on your source BEFORE calling `broker.add_panel`:** + +1. Does every numeric gauge use `SET RANGE FROM x TO y`? (Reject **any** + `WITH RANGE` form — including the quoted `WITH RANGE "min,max"` trap + that historically rendered gauges as NaN because the entire "min,max" + string was stored as `min`.) +2. Does every `BIND` line start with `BIND TO `? (Reject + `BIND TOPIC`, `BIND MODEL`, `BIND QUERY`, and `BIND ` — + the `TO` keyword is mandatory.) +3. Does every numeric `BIND VALUE TO TOPIC "…"` on a gauge / chart / + value end with `AS NUMBER` — and ONLY `AS NUMBER`? Valid coerce suffixes + are `AS NUMBER`, `AS BOOLEAN`, and `AS STRING`. NEVER invent `AS LENGTH`, + `AS COUNT`, `AS JSON`, or `AS ARRAY`. MQTT JSON objects/arrays are NOT + numbers; a gauge bound to a JSON blob renders 0.0 even when the topic is + live. If `explore_topics` / `broker__read_mqtt` shows `type=object` + or `type=array`, either pick a sibling scalar topic (e.g. `…/metrics/alerts_active`) + or add `WITH JSON_PATH "numericField"`. Tables: `BIND DATA` + `SET COLUMNS`. +4. Does every `ADD COMPONENT` header declare the type exactly once? (Reject + any body-line `WITH TYPE` — the header is authoritative. Reject + `ADD COMPONENT Name OF TYPE type` — use `ADD COMPONENT "Name" WITH TYPE "type"`.) +5. Do realtime-chart series use `BIND VALUE TO TOPIC` + indented + `SET SERIES_LABEL`? (Reject `WITH SERIES` and `BIND SERIES`.) +6. Do units / decimals / placeholders / chart axes / map zoom-and-center + properties use indented `SET`? (Reject them under `WITH`.) +7. After deploy, read the `broker.add_panel` response — if it includes + warnings about non-canonical forms, rewrite the panel and redeploy. Do + not tell the user the dashboard is live while warnings remain. +8. Does every `ON CLICK` / `ON CHANGE` / `ON TOGGLE` line include `DO` before + the action verb? Reject `ON CLICK PUBLISH TOPIC` — the canonical form is + `ON CLICK DO PUBLISH TOPIC`. +9. Do tables have `BIND DATA` + `SET COLUMNS` + (for JSON:API `{"data":[…]}`) + `WITH JSON_PATH "data"`? A table without columns stays empty even when + the topic is live. + +--- + +## STEP 0 — Choose Layout AND Components Before Writing Any Code + +Before writing a single line of LoTV, make TWO decisions in order: + A) Which LAYOUT type? (grid vs positioned) + B) Which COMPONENT types? (gauge vs svg vs table vs button…) + +Picking the wrong layout or component type is the most common source of broken panels. + +--- + +### Decision A — Which layout type? + +**Use WITH LAYOUT "grid" COLUMNS N (MANDATORY for any dashboard / monitoring / form panel):** +- Dashboard-style content: cards with gauges, charts, values, tables +- Responsive content that fills available space +- Forms and data entry +- Any panel where exact pixel placement doesn't matter +- When the user says: "dashboard", "overview", "monitoring", "form" +- Pick `N` via the widget-count rule in Rule 0.5 (1–3 → `COLUMNS = count`, + 4–6 → `COLUMNS 3`, 7+ → `COLUMNS 4`, forms-only → `COLUMNS 2`). + +```lot +DEFINE PANEL "ProductionDashboard" + WITH LAYOUT "grid" COLUMNS 3 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "TempGauge" WITH TYPE "gauge" ... + ADD COMPONENT "TrendChart" WITH TYPE "chart" ... + ADD COMPONENT "AlertTable" WITH TYPE "table" ... +``` + +**Use WITH LAYOUT "positioned" (use this for HMI / SCADA / control panels):** +- When the user says: "HMI", "SCADA", "P&ID", "control panel", "process screen", + "plant view", "operator screen", "mimic diagram" +- When exact pixel placement matters — controls must be at specific X/Y coordinates +- When controls overlay a background SVG image or plant diagram +- When components need to overlap (Z_INDEX stacking) +- When the user provides a drawing, diagram, or screenshot to replicate + +```lot +DEFINE PANEL "PumpStationHMI" + WITH TITLE "Pump Station Control" + WITH LAYOUT "positioned" + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED +``` + +**RULES for positioned layout — ALL of these are mandatory:** +- EVERY component MUST have SET POSITION X n Y n +- EVERY component MUST have SET WIDTH n and SET HEIGHT n +- Without position/size, components will stack at (0,0) and overlap each other +- Ask the user for canvas size (e.g. 1280x800) or assume 1200x800 as default + +--- + +### Decision A — Summary table + + User says... Layout + ────────────────────────────── ──────────────────────────── + "show a dashboard" grid + "monitoring screen" grid + "data table / list" grid + "form / data entry" grid + "HMI" / "SCADA" positioned + "control panel" positioned + "P&ID" / "process diagram" positioned + "operator screen" positioned + "plant view" / "mimic" positioned + "I want controls on a diagram" positioned (SVG background + components on top) + "match this drawing/screenshot" positioned + +--- + +### How to build a positioned HMI — full pattern + +A positioned HMI typically has: +1. A full-canvas SVG background (plant diagram, P&ID, floor plan image) +2. Positioned gauges/indicators/buttons overlaid at exact coordinates on top + +```lot +DEFINE PANEL "PumpStationHMI" + WITH TITLE "Pump Station" + WITH LAYOUT "positioned" + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + // Background diagram — covers the full canvas + ADD COMPONENT "Background" WITH TYPE "svg" + SET INLINE " + + + + Tank 1 + +" + SET POSITION X 0 Y 0 + SET WIDTH 1200 + SET HEIGHT 800 + SET Z_INDEX 0 + BIND CSS "--tank1-level" TO TOPIC "tank1/level" RANGE FROM 0 TO 100 OUTPUT FROM 0 TO 148 UNIT "px" + BIND TEXT "tank1-fill" TO TOPIC "tank1/level" SUFFIX "% full" DECIMALS 0 + + // Gauge overlaid at specific position on the canvas + ADD COMPONENT "Tank1Level" WITH TYPE "gauge" + SET LABEL "Tank 1 Level" + SET UNIT "%" + SET RANGE FROM 0 TO 100 + SET POSITION X 130 Y 420 + SET WIDTH 140 + SET HEIGHT 140 + SET Z_INDEX 10 + BIND VALUE TO TOPIC "tank1/level" + + // Status indicator at pump location + ADD COMPONENT "Pump1Status" WITH TYPE "indicator" + SET LABEL "Pump 1" + SET POSITION X 420 Y 310 + SET WIDTH 60 + SET HEIGHT 60 + SET Z_INDEX 10 + BIND STATE TO TOPIC "pump1/state" + + // Control button at specific location + ADD COMPONENT "Pump1Start" WITH TYPE "button" + SET LABEL "START P1" + SET STYLE "primary" + SET POSITION X 410 Y 390 + SET WIDTH 80 + SET HEIGHT 36 + SET Z_INDEX 10 + ON CLICK DO + PUBLISH TOPIC "pump1/cmd" WITH "start" + + // Live flow rate — gauge (NOT value) so the operator sees the range at a glance + ADD COMPONENT "FlowRate" WITH TYPE "gauge" + SET LABEL "Flow" + SET UNIT "L/min" + SET RANGE FROM 0 TO 200 + SET DECIMALS 1 + SET POSITION X 600 Y 200 + SET WIDTH 140 + SET HEIGHT 140 + SET Z_INDEX 10 + BIND VALUE TO TOPIC "flow/main" +``` + +**Before writing a positioned HMI, ask the user:** +1. What is the canvas size? (width × height in pixels, default 1200 × 800) +2. Do you have a background image/diagram? If yes, use it as the SVG background. +3. Where should each instrument/control be placed? (X, Y coordinates from top-left) +4. What MQTT topics feed each instrument? + +--- + +### Decision B — Single panel or multi-panel navigation? + +**BEFORE deciding layout, decide navigation structure.** + +COUNT THE SECTIONS. If the user's panel has 3 or more distinct sections +(e.g. Overview / Process / Setpoints / Production / History), you MUST use +multi-panel navigation. A single scrolling grid is NEVER acceptable for +operator panels — it is confusing, unprofessional, and operators reject it. + +**Use a SINGLE PANEL when:** +- 1 or 2 logical sections that fit in one screen without scrolling +- Simple monitoring dashboard (4–8 gauges/values) +- A form or data entry screen + +**Use MULTI-PANEL NAVIGATION when:** +- 3+ distinct sections or topics (e.g. Overview, Process, Setpoints, Production) +- Operator panel / HMI with named views +- The user says "tabs", "sections", "pages", or lists named groups +- Operator panels for machines (injection molding, pump station, conveyor, etc.) + +**How to build multi-panel navigation (the correct pattern):** + +Deploy MULTIPLE panels — one per section — plus a navigation home panel. +Navigation between them uses ON CLICK DO NAVIGATE TO PANEL. + +```lot +// ── NAV HOME — shown first, always visible at top or as main entry ── +DEFINE PANEL "INJ001Nav" + WITH TITLE "INJ-001 Operator Panel" + WITH LAYOUT "grid" COLUMNS 5 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + ADD COMPONENT "OverviewBtn" WITH TYPE "button" + SET LABEL "Overview" + ON CLICK DO + NAVIGATE TO PANEL "INJ001Overview" + ADD COMPONENT "ProcessBtn" WITH TYPE "button" + SET LABEL "Process" + ON CLICK DO + NAVIGATE TO PANEL "INJ001Process" + ADD COMPONENT "SetpointsBtn" WITH TYPE "button" + SET LABEL "Setpoints" + ON CLICK DO + NAVIGATE TO PANEL "INJ001Setpoints" + ADD COMPONENT "ProductionBtn" WITH TYPE "button" + SET LABEL "Production" + ON CLICK DO + NAVIGATE TO PANEL "INJ001Production" + ADD COMPONENT "HistoryBtn" WITH TYPE "button" + SET LABEL "History" + ON CLICK DO + NAVIGATE TO PANEL "INJ001History" + +// ── OVERVIEW section panel ── +DEFINE PANEL "INJ001Overview" + WITH TITLE "INJ-001 — Overview" + WITH LAYOUT "grid" COLUMNS 4 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + ADD COMPONENT "BackBtn" WITH TYPE "button" + SET LABEL "← Back" + ON CLICK DO + NAVIGATE BACK + ADD COMPONENT "MachineState" WITH TYPE "indicator" + SET LABEL "Machine State" + BIND STATE TO TOPIC "inj001/state" + ADD COMPONENT "CyclePhase" WITH TYPE "text" + SET LABEL "Current Phase" + BIND VALUE TO TOPIC "inj001/cycle/phase" + ADD COMPONENT "AutoMode" WITH TYPE "indicator" + SET LABEL "Auto Mode" + BIND STATE TO TOPIC "inj001/mode/auto" + +// ── PROCESS section panel ── +DEFINE PANEL "INJ001Process" + WITH TITLE "INJ-001 — Process" + WITH LAYOUT "grid" COLUMNS 4 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + ADD COMPONENT "BackBtn" WITH TYPE "button" + SET LABEL "← Back" + ON CLICK DO + NAVIGATE BACK + ADD COMPONENT "NozzleTemp" WITH TYPE "gauge" + SET LABEL "Nozzle Temp" + SET UNIT "°C" + SET RANGE FROM 0 TO 400 + BIND VALUE TO TOPIC "inj001/temp/nozzle" + ADD COMPONENT "MoldTemp" WITH TYPE "gauge" + SET LABEL "Mold Temp" + SET UNIT "°C" + SET RANGE FROM 0 TO 400 + BIND VALUE TO TOPIC "inj001/temp/mold" + ADD COMPONENT "InjPressure" WITH TYPE "gauge" + SET LABEL "Injection Pressure" + SET UNIT "bar" + SET RANGE FROM 0 TO 200 + BIND VALUE TO TOPIC "inj001/pressure/injection" + +// ── SETPOINTS section panel ── +DEFINE PANEL "INJ001Setpoints" + WITH TITLE "INJ-001 — Setpoints" + WITH LAYOUT "grid" COLUMNS 3 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + ADD COMPONENT "BackBtn" WITH TYPE "button" + SET LABEL "← Back" + ON CLICK DO + NAVIGATE BACK + ADD COMPONENT "NozzleSP" WITH TYPE "text-field" + SET LABEL "Nozzle Setpoint (°C)" + BIND VALUE TO TOPIC "inj001/setpoint/nozzle" + ON CHANGE DO + PUBLISH TOPIC "inj001/setpoint/nozzle" WITH VALUE + ADD COMPONENT "MoldSP" WITH TYPE "text-field" + SET LABEL "Mold Setpoint (°C)" + BIND VALUE TO TOPIC "inj001/setpoint/mold" + ON CHANGE DO + PUBLISH TOPIC "inj001/setpoint/mold" WITH VALUE +``` + +**Rules for multi-panel navigation:** +- Every section panel MUST have a "← Back" button with NAVIGATE BACK +- Use NAVIGATE TO PANEL (not links or URLs) — the Hub manages the navigation stack +- The broker auto-splits multi-panel source at DEFINE PANEL boundaries +- Deploy all panels in ONE broker.add_panel call (all source joined — broker handles splitting) +- Bake `WITH STATE PUBLISHED` into every `DEFINE PANEL` header so each section + goes live on the first deploy. Do NOT chain `broker.update_visu_state` calls + after `broker.add_panel` — they are unnecessary when the header already + declares the desired state. +- The broker.add_panel response will confirm which panel names were deployed + +**NEVER make a single flat grid when the user has 3+ named sections.** +"Sections" in a flat grid means operators must scroll endlessly. +Multi-panel navigation means one clean screen per topic — that IS the HMI standard. + +--- + +### What does the user want to display? + +SINGLE LIVE NUMBER (temperature, pressure, speed, count) + → WITH TYPE "gauge" DEFAULT — set RANGE + UNIT so the operator sees the scale. + → WITH TYPE "indicator" when it is a state (running/stopped/fault) + → WITH TYPE "realtime-chart" pair with the gauge if the value updates continuously + → WITH TYPE "value" ONLY for non-numeric counters / status strings where "text" is wrong. + ❌ Banned for any numeric scalar — use "gauge" instead. + DO NOT use SVG for this. A gauge is always better. + +TREND OVER TIME (last N readings of a scalar) + → WITH TYPE "realtime-chart" if the topic sends one value at a time (subscribe live) + → WITH TYPE "chart" if the topic sends a JSON array of historical records + DO NOT use SVG for this. + +TABLE OF RECORDS (list of machines, alarms, orders, readings) + → WITH TYPE "table" with SET COLUMNS, SET SORTABLE, SET FILTERABLE, etc. + DO NOT use SVG for this. + +ON/OFF CONTROL (button, toggle, slider) — EXPLICIT REQUEST ONLY + Only emit these when the user explicitly asks for a control. Never auto-add + one beside an indicator just because the topic looks writable. See Rule 1.5. + → WITH TYPE "button" publishes on click — REQUIRES `ON CLICK DO PUBLISH` + → WITH TYPE "switch" toggle — REQUIRES `ON TOGGLE DO PUBLISH ... WITH STATE` + → WITH TYPE "slider" range input — REQUIRES `ON CHANGE DO PUBLISH ... WITH VALUE` + A control without its publish action is a DEAD widget; do not emit it. + DO NOT use SVG for this. + +LIVE TRACKING — anything with a position (vehicles, vessels, people, drones, + containers, animals, sensors, delivery riders, field workers, packages, robots) + → WITH TYPE "map" with BIND LOCATION / BIND MARKERS / BIND TRACE + Use when the user needs to show ANY moving or positioned thing on a map. + Single entity: BIND LOCATION TO TOPIC "thing/gps" + All entities: BIND MARKERS TO TOPIC "things/+" (wildcard — each topic = one marker) + History trail: BIND TRACE TO TOPIC "thing/gps" (polyline from trace buffer) + The pattern is always the same regardless of WHAT is being tracked. + +CUSTOM INDUSTRIAL DIAGRAM (tank, pipe, HVAC schematic, machine layout) + → WITH TYPE "svg" using SET INLINE + BIND TEXT/CSS/ELEMENT + ONLY use this when no built-in component can represent the visual. + LOAD draw-svg-visu skill BEFORE writing any SVG. + +### Decision tree — should I use SVG? + +Ask these questions in order. Stop at the first YES that applies: + + 1. Can the user's need be met by gauge, value, indicator, chart, or table? + YES → use that component. Do NOT load draw-svg-visu. + + 2. Does the user explicitly ask for a diagram, schematic, or custom graphic? + NO → do NOT generate SVG. Ask the user what visual they actually need. + + 3. Is the shape geometrically simple (tanks, pipes, circles, rectangles, arrows)? + NO → do NOT generate SVG. Recommend uploading a pre-drawn SVG file. + Tell the user: "This diagram is too complex to generate as code. + Please upload an SVG file and I will bind live data to it." + + 4. Do you have all the MQTT topic paths for the data to display? + NO → call explore_topics (MCP) or broker__read_mqtt (DEFINE AGENT) first. + + 5. Are you confident the SVG will render correctly on the first attempt? + NO → do NOT generate SVG yet. Ask the user to confirm the exact shapes needed. + + ALL YES → call broker.load_skill("draw-svg-visu") and proceed. + +### Quick reference — components + + User says... Use this + ───────────────────────────────── ─────────────────────────────────────── + "show temperature as a gauge" WITH TYPE "gauge" + "show current value of X" WITH TYPE "gauge" (DEFAULT for numeric); "value" only for non-numeric strings + "show if machine is running" WITH TYPE "indicator" + "show history/trend of readings" WITH TYPE "chart" or "realtime-chart" + "show a table of records" WITH TYPE "table" + "show a tank with fill level" WITH TYPE "svg" — load draw-svg-visu + "show an HVAC diagram" WITH TYPE "svg" — load draw-svg-visu + "show machine layout/schematic" WITH TYPE "svg" if simple; else ask user to upload SVG + "show assets on a map" WITH TYPE "map" + BIND MARKERS + "track vehicle/person/drone" WITH TYPE "map" + BIND LOCATION + BIND TRACE + "show fleet/group positions" WITH TYPE "map" + BIND MARKERS + SET CLUSTER true + "show ALL boats/trucks/people/..." WITH TYPE "map" + BIND MARKERS TO TOPIC "prefix/+" (wildcard!) + "where are my [things]?" WITH TYPE "map" + BIND LOCATION or BIND MARKERS + "show movement history/trace" WITH TYPE "map" + BIND TRACE (polyline on map) + "show live scrolling chart" WITH TYPE "realtime-chart" + BIND VALUE + "table of all [entities]" WITH TYPE "table" + BIND DATA TO TOPIC "prefix/+" (wildcard!) + "compare [metric] across [things]" WITH TYPE "realtime-chart" + BIND VALUE TO TOPIC "prefix/+" (wildcard!) + "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 + +### Quick reference — layout and navigation + + User says... Structure + ───────────────────────────────── ─────────────────────────────────────── + "dashboard" (1 page) single panel, grid layout + "monitoring screen" (1 page) single panel, grid layout + "table / list / form" (1 page) single panel, grid layout + "operator panel" with sections MULTI-PANEL — one panel per section + nav panel + "tabs" / "pages" / "sections" For full-screen operator views with 3+ topics, use + MULTI-PANEL (one panel per section + NAVIGATE TO PANEL). + For in-panel tab strips within a single dashboard, use + ADD COMPONENT … TYPE "tabs" with ADD TAB "Title" lines. + "Overview / Process / Setpoints…" MULTI-PANEL — always when 3+ named sections + "HMI" / "SCADA" (full screen) positioned layout + ask for canvas size + "P&ID" / "mimic diagram" positioned layout + ask for canvas size + "match this drawing" positioned layout + ask for canvas size + + ⚠️ 3+ NAMED SECTIONS = MULTI-PANEL. Never use a flat scrolling grid. + ⚠️ POSITIONED LAYOUT: every component must have SET POSITION X Y + SET WIDTH + SET HEIGHT + +--- + +## Mode awareness — deploying a panel is a write + +Insight mode is read-only: the broker refuses every writing tool in an +insight-mode task with `out_of_scope`, and deploying a panel is a write. Only +the read tools (reading topics, reading LoT such as the panel source) run in +Insight mode. In Insight mode, show the panel source and say what you would +deploy instead of trying. + +In Agent mode, call `broker.add_panel` directly. The deploy response is the +confirmation. Do NOT respond with phrases like "the panel source is ready for +deployment" when you are in Agent mode and allowed to deploy. + +--- + +## Mandatory Workflow + +``` +broker.load_skill("lot-panels") ← load this skill FIRST +explore_topics(filter="factory/") ← discover topics (MCP; DEFINE AGENT: broker__read_mqtt(topic="factory/#")) +explore_topics(filter="sensor/readings", response_format="detailed") ← INSPECT PAYLOAD before binding + ← is it a number? JSON object? JSON array? + ← determines whether to use JSON_PATH +broker.get_panel_code(name="X") ← retrieve existing panel source (if updating) +broker.add_panel(definition=...) ← deploy directly — publishes to $Visu + ← NO broker.show_approval beforehand — + the deploy response IS the confirmation; + show_approval is also blocked in Insight mode +broker.refresh_visu() ← if Hub can't see panel after deploy +``` + +> **No approval card for panels.** Bake `WITH STATE PUBLISHED` into every +> `DEFINE PANEL` header so the panel goes live on the first deploy and you +> never need `broker.update_panel_state` (which is Agent-mode only). + +> **Inspect every topic payload before binding.** JSON objects need `WITH JSON_PATH "field"`. +> JSON arrays need `WITH JSON_PATH "0.field"` for first element, or `BIND DATA` for charts/tables. +> **For maps:** if lat/lng are inside a JSON object, use `BIND LOCATION TO TOPIC` + `SET LAT_FIELD` / `SET LNG_FIELD`. +> NEVER assume sub-topics exist. NEVER invent new LoTV keywords (WITH TEXT, WITH MIN, etc.). + +--- + +## Minimal Panel Template + +```lot +DEFINE PANEL "PanelName" + WITH TITLE "Human Readable Title" + WITH LAYOUT "grid" COLUMNS 3 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "GaugeID" WITH TYPE "gauge" + SET LABEL "Temperature" + SET UNIT "°C" + SET RANGE FROM 0 TO 150 + BIND VALUE TO TOPIC "factory/zone1/temp" +``` + +--- + +## Panel Header Options + +| Keyword | Required | Example | +|---|---|---| +| `WITH TITLE "..." ` | No | `WITH TITLE "Zone 1 Dashboard"` | +| `WITH LAYOUT "grid" COLUMNS n` | No | `WITH LAYOUT "grid" COLUMNS 4` | +| `WITH VISIBILITY PUBLIC` | No | PUBLIC / SHARED / PRIVATE (default: PRIVATE) | +| `WITH SHARE TO GROUP "g"` | When SHARED | One line per group | +| `WITH SHARE TO USER "u"` | When SHARED | One line per user | +| `WITH STATE PUBLISHED` | Yes (to be visible) | DRAFT / PUBLISHED / ARCHIVED | +| `WITH THEME "light" \| "dark"` | No | Built-in Hub palette (`light` or `dark` only — not a deployed VoT theme name; use `DEFINE THEME` + `broker.add_theme` for custom design tokens) | + +> NEVER combine `WITH VISIBILITY PRIVATE` with `WITH SHARE TO` — PRIVATE means no sharing. + +--- + +## Component Types + +Listed in PREFERENCE ORDER — pick from the top of the table first. `value` is +a FALLBACK and is forbidden for numeric scalars (use `gauge` instead). + +| Type | Use case | Notes | +|---|---|---| +| `"gauge"` | DEFAULT for numeric scalars (temperature, pressure, level, count, KPI) | Requires `SET RANGE FROM a TO b` and `SET UNIT` | +| `"realtime-chart"` | DEFAULT for continuously updating scalars (live trend) | Uses DataPoint Store trace buffer; pair with a `gauge` | +| `"chart"` | Historical JSON arrays with timestamps | Requires `SET COLUMNS` | +| `"indicator"` | DEFAULT for booleans / discrete states (run/stop, alarm) | Color changes by state | +| `"map"` | Anything with a position (GPS, fleets, vehicles, people) | `BIND LOCATION` / `BIND MARKERS` / `BIND TRACE` | +| `"svg"` | Custom industrial diagrams (tanks, P&ID) | Load `draw-svg-visu` skill first | +| `"table"` | Tabular display for JSON arrays | Requires `SET COLUMNS`; NEVER repeat `value` widgets per row | +| `"button"` | One-shot commands (start, stop, reset) — ONLY when user explicitly asks for a control. NEVER auto-add. | MUST include `ON CLICK DO PUBLISH`; without it the button is dead | +| `"switch"` | ONLY when user explicitly asks for a write/toggle control. NEVER auto-create next to an `indicator`. (Booleans default to `indicator`.) | MUST include `ON TOGGLE DO PUBLISH TOPIC "..." WITH STATE` — without the publish block it is a dead toggle | +| `"slider"` | Numeric setpoint editor — ONLY when user explicitly asks for a control. | MUST include `ON CHANGE DO PUBLISH ... WITH VALUE` | +| `"text-field"` | Free-text or numeric setpoint entry | Publishes on change | +| `"text"` | Static or bound text strings | **Use this, NOT `"label"`** | +| `"card"` | Layout container — groups child components | — | +| `"value"` | **FALLBACK ONLY** — non-numeric counters or status strings where `text` is wrong | ❌ HARD BAN: never use for numeric scalars (use `gauge`) — every panel must contain at least one `gauge`/`chart`/`realtime-chart`/`indicator`/`map`/`svg` | + +> ❌ NEVER use `WITH TYPE "label"` — there is no `label` renderer. The parser rewrites it to `"text"` and warns. +> ✅ Use `WITH TYPE "text"` for all text display (static labels, bound strings, timestamps). + +### ⚠️ Component type tokens MUST be the kebab-case lowercase strings above + +The Hub renderer matches the type **case-sensitively**. PascalCase / +camelCase variants are auto-corrected by the broker (and emit a warning), but +you MUST emit the canonical form so the panel renders identically across +broker versions and so the warning channel stays clean for real bugs. + +```lot +// ❌ WRONG — PascalCase. The parser rewrites it to the kebab-case form and +// warns ("is not a canonical LoTV type token"); emit the canonical form. +ADD COMPONENT RealtimeChart "MessagesPerMinuteChart" +ADD COMPONENT Gauge "MessageCountGauge" +ADD COMPONENT Indicator "OperationalStatusIndicator" + +// ✅ CORRECT — quoted, lowercase, kebab-case where applicable. +ADD COMPONENT "MessagesPerMinuteChart" WITH TYPE "realtime-chart" +ADD COMPONENT "MessageCountGauge" WITH TYPE "gauge" +ADD COMPONENT "OperationalStatusIndicator" WITH TYPE "indicator" +``` + +Common offenders and their canonical form: + +| Wrong (PascalCase / camelCase) | Correct (kebab-case lowercase) | +|---|---| +| `RealtimeChart`, `realtimeChart`, `realtime_chart` | `realtime-chart` | +| `Gauge`, `GAUGE` | `gauge` | +| `Indicator` | `indicator` | +| `TextField`, `text_field` | `text-field` | +| `NumberField`, `number_field` | `number-field` | +| `DatePicker`, `date_picker` | `date-picker` | +| `label` (any case) | `text` *(`label` has no renderer; use `text`)* | + +### ADD COMPONENT — three accepted header forms + +All three forms parse and assign a **stable id** to the component (required so +the Hub doesn't collapse two `gauge` widgets into one ghost card). Pick **one +style and stick with it for the whole panel** — mixing them within a panel +makes diff review harder. + +```lot +// ✅ Form 1 — quoted id first, then explicit type (RECOMMENDED for new code) +ADD COMPONENT "MessageCountGauge" WITH TYPE "gauge" + +// ✅ Form 2 — bare lowercase type, id given via WITH ID +ADD COMPONENT gauge WITH ID MessageCountGauge + +// ✅ Form 3 — bare lowercase type, quoted positional id +ADD COMPONENT gauge "MessageCountGauge" + +// ❌ WRONG — bare PascalCase type AND no id. The parser lowercases the type +// (with a warning) and assigns an auto-id such as "gauge-1", which nothing +// else in your source can refer to. +ADD COMPONENT Gauge + +// ❌ WRONG — SQL/Pascal-flavoured `AS` form. The parser auto-corrects +// (extracting the id from the bare token and the type from after AS, +// then lowercasing the type) and emits warnings. NEVER emit this. +ADD COMPONENT EfficiencyGauge AS GAUGE +ADD COMPONENT MessageCountGauge AS Gauge +``` + +**Canonical fix for the `AS` form:** quote the id, lowercase the type, and use +`WITH TYPE`: + +```lot +// ✅ CORRECT +ADD COMPONENT "EfficiencyGauge" WITH TYPE "gauge" +ADD COMPONENT "MessageCountGauge" WITH TYPE "gauge" +``` + +**⚠️ Component properties use SET, NOT WITH. These are non-canonical — the parser +auto-corrects some with a warning and drops others, so never emit them:** +- `WITH TEXT "..."` → use `SET LABEL "..."` or `SET CONTENT "..."` +- `WITH TITLE "..."` on a component → use `SET LABEL "..."` (WITH TITLE is panel-level only; on a component it is stored as an unknown prop with a warning) +- `WITH MIN 0` / `WITH MAX 100` → use `SET RANGE FROM 0 TO 100` +- `WITH UNIT "°C"` → use `SET UNIT "°C"` +- `WITH POSITION "1,2,8,6"` → use `SET POSITION X 1 Y 2` + `SET WIDTH 8` + `SET HEIGHT 6` (positioned layout). The quoted form is dropped with a warning. +- `BIND ... AND ...` → NOT VALID. Everything after the first topic is ignored. Each BIND is a separate statement. + +--- + +## Forms and Data Entry — Correct Pattern + +LoTV has **NO "form" component type** and **NO "ADD FIELD" keyword**. +Neither raises an error or a warning: `ADD FIELD` lines are dropped, and +`WITH TYPE "form"` is passed through as an unknown type the Hub has no renderer for. + +The correct pattern: a `"card"` container + nested `"text-field"` / `"switch"` components + a `"button"` to submit. + +```lot +// ── CORRECT form pattern ── +DEFINE PANEL "BoothLeadsPanel" + WITH TITLE "Booth Leads" + WITH LAYOUT "grid" COLUMNS 1 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "leadCard" WITH TYPE "card" + SET TITLE "Visitor Lead Form" + ADD COMPONENT "nameField" WITH TYPE "text-field" + SET LABEL "Name" + SET PLACEHOLDER "Enter name" + ON CHANGE DO + PUBLISH TOPIC "booth/leads/input/name" WITH VALUE + ADD COMPONENT "surnameField" WITH TYPE "text-field" + SET LABEL "Surname" + SET PLACEHOLDER "Enter surname" + ON CHANGE DO + PUBLISH TOPIC "booth/leads/input/surname" WITH VALUE + ADD COMPONENT "companyField" WITH TYPE "text-field" + SET LABEL "Company" + SET PLACEHOLDER "Enter company" + ON CHANGE DO + PUBLISH TOPIC "booth/leads/input/company" WITH VALUE + ADD COMPONENT "emailField" WITH TYPE "text-field" + SET LABEL "Email" + SET PLACEHOLDER "Enter email" + ON CHANGE DO + PUBLISH TOPIC "booth/leads/input/email" WITH VALUE + ADD COMPONENT "phoneField" WITH TYPE "text-field" + SET LABEL "Phone" + SET PLACEHOLDER "Enter phone" + ON CHANGE DO + PUBLISH TOPIC "booth/leads/input/phone" WITH VALUE + ADD COMPONENT "otherInfoField" WITH TYPE "text-field" + SET LABEL "Other Info" + SET PLACEHOLDER "Any additional notes" + ON CHANGE DO + PUBLISH TOPIC "booth/leads/input/otherInfo" WITH VALUE + ADD COMPONENT "submitBtn" WITH TYPE "button" + SET LABEL "Submit Lead" + SET STYLE "primary" + ON CLICK DO + PUBLISH TOPIC "booth/leads/form/submit" WITH 1 +``` + +**For a setpoint field (show current value AND let user change it):** + +```lot +ADD COMPONENT "TempSP" WITH TYPE "text-field" + SET LABEL "Temperature Setpoint (°C)" + BIND VALUE TO TOPIC "machine/setpoint/temp" // shows current retained value + ON CHANGE DO + PUBLISH TOPIC "machine/setpoint/temp" WITH VALUE // writes new value +``` + +**Component types for inputs:** + +| Type | Use case | +|---|---| +| `"text-field"` | Any text/number input (name, email, setpoint, comment) — must include `ON CHANGE DO PUBLISH ... WITH VALUE` for setpoints | +| `"switch"` | Boolean on/off toggle — ONLY when user explicitly asks for a control; NEVER auto-add next to an indicator. MUST include `ON TOGGLE DO PUBLISH TOPIC "..." WITH STATE` (see Rule 1.5). | +| `"slider"` | Numeric range input — must include `ON CHANGE DO PUBLISH ... WITH VALUE` | +| `"button"` | Trigger, submit, or navigate — must include `ON CLICK DO PUBLISH` (or `ON CLICK DO NAVIGATE`) | + +**NEVER use `"form"` as a component type — it does not exist. Use `"card"` to group fields.** + +--- + +## Data Binding — Topic Payloads + +```lot +// Simple scalar topic (value is a plain number or string) +BIND VALUE TO TOPIC "sensors/zone1/temp" +BIND STATE TO TOPIC "machines/pump/state" + +// JSON OBJECT topic — extract ONE field with WITH JSON_PATH +// Topic payload example: {"temperature": 31.4, "pressure": 1.9, "machine_id": "m1"} +BIND VALUE TO TOPIC "plant/machine1/readings" WITH JSON_PATH "temperature" +BIND VALUE TO TOPIC "plant/machine1/readings" WITH JSON_PATH "pressure" +BIND CONTENT TO TOPIC "plant/machine1/readings" WITH JSON_PATH "machine_id" + +// JSON ARRAY topic — extract field from FIRST element (index 0) +// Topic payload example: [{"id":19,"temperature":31.4,"pressure":1.9}, ...] +BIND VALUE TO TOPIC "plant/machine1/readings/last50" WITH JSON_PATH "0.temperature" +BIND VALUE TO TOPIC "plant/machine1/readings/last50" WITH JSON_PATH "0.pressure" +BIND CONTENT TO TOPIC "plant/machine1/readings/last50" WITH JSON_PATH "0.timestamp" + +// Whole JSON array goes to chart or table only — NEVER a gauge/value/text +BIND DATA TO TOPIC "plant/machine1/readings/last50" // for chart or table component + +// Model field +BIND VALUE TO MODEL "SensorReading.temperature" + +// GPS position — for map component +BIND LOCATION TO TOPIC "vehicle/gps" // payload: {lat, lng} or [lat, lng] + +// Multiple markers — for map component +BIND MARKERS TO TOPIC "fleet/positions" // payload: [{id, lat, lng, name}, ...] + +// Historical trace — for map polyline or realtime-chart +BIND TRACE TO TOPIC "vehicle/gps" // uses DataPoint Store ring buffer + SET TRACE_DEPTH 200 // how many points to keep +``` + +Bind targets (the ONLY tokens that may follow `BIND `): +VALUE / STATE / CONTENT / COLOR / TITLE / LABEL / MAX / MIN / VISIBLE / DATA / SPEED / LOCATION / MARKERS / TRACE + +❌ `SERIES` is NOT a bind target. `BIND SERIES "…" TO TOPIC "…"` is invalid. +Write `BIND VALUE TO TOPIC "real/topic"` and put the legend on an indented +`SET SERIES_LABEL`. (The parser auto-corrects this form, but you must not emit it.) + +❌ `ROWS` is NOT a bind target. Tables use `BIND DATA TO TOPIC "…"` + `SET COLUMNS`. + +❌ `AS LENGTH` / `AS COUNT` / `AS JSON` are NOT coerce types. Only `AS NUMBER`, +`AS BOOLEAN`, `AS STRING`. Binding a JSON:API feed (`{"data": […]}`) to a gauge +with `AS LENGTH` leaves the needle at 0.0. + +❌ Route status is NOT `/status`. It is +`$SYS/Coreflux/Routes//status` (JSON with `health` / `connection`). +Bind `BIND STATE TO TOPIC "$SYS/Coreflux/Routes/MbtaAlertsFeed/status" WITH JSON_PATH "health"`. + +--- + +## ⚠️ MANDATORY — Inspect the Topic Payload Before Writing ANY BIND Statement + +**You MUST inspect the payload — `explore_topics(filter="...", response_format="detailed")` over MCP, `broker__read_mqtt(topic="...")` in a DEFINE AGENT — BEFORE writing any BIND statement.** +**Skipping this step is the #1 cause of broken panels. NEVER guess the payload structure.** + +Both tools return the latest payload the broker has seen and do not wait for a live publish. If "parent/sub" is not in the result, the sub-topic is not being published. +Read the parent topic instead — it likely publishes JSON. + +Then follow these rules: + +- Plain number (31.4): BIND VALUE TO TOPIC "t" AS NUMBER +- Plain string (running): BIND STATE TO TOPIC "t" +- JSON object ({"temp": 31.4, ...}): BIND VALUE TO TOPIC "t" WITH JSON_PATH "temperature" AS NUMBER +- JSON:API / wrapped array ({"data":[…]}): table → BIND DATA TO TOPIC "t" WITH JSON_PATH "data" + SET COLUMNS +- JSON array first element: BIND VALUE TO TOPIC "t" WITH JSON_PATH "0.temperature" AS NUMBER +- JSON array for chart or table: BIND DATA TO TOPIC "t" plus SET COLUMNS "field1,field2" +- Count of a JSON array: NEVER AS LENGTH. Bind a sibling scalar (…/metrics/alerts_active) or a model field. +- Route health: BIND STATE TO TOPIC "$SYS/Coreflux/Routes//status" WITH JSON_PATH "health" +- GPS position ({lat, lng}): BIND LOCATION TO TOPIC "t" (for map component) +- Rich JSON with lat/lng inside: BIND LOCATION TO TOPIC "t" + SET LAT_FIELD / SET LNG_FIELD +- Nested JSON {data:{pos:{lat,lng}}}: BIND LOCATION TO TOPIC "t" WITH JSON_PATH "data.pos" +- Array of positions ([{id,lat,lng}]): BIND MARKERS TO TOPIC "t" (for map component) + +**If explore_topics schema is object or array, a gauge/realtime-chart MUST NOT bind VALUE to that topic without JSON_PATH or a different scalar topic.** Prefer already-projected metrics (models/actions) over the raw feed. + +**NEVER** assume sub-topics exist just because the parent topic publishes JSON with those fields. +Topic plant/machine1/readings may publish {"temperature":31.4} as a JSON object, +but plant/machine1/readings/temperature is a SEPARATE topic that may not exist. +Always verify with explore_topics / broker__read_mqtt before writing any BIND. + +```lot +// WRONG — assumes sub-topics exist; they may not +ADD COMPONENT "Gauge" WITH TYPE "gauge" + BIND VALUE TO TOPIC "plant/machine1/readings/temperature" // might not exist! + +// CORRECT — parent topic publishes JSON object {"temperature": 31.4, "pressure": 1.9} +ADD COMPONENT "Gauge" WITH TYPE "gauge" + BIND VALUE TO TOPIC "plant/machine1/readings" WITH JSON_PATH "temperature" + +// CORRECT — parent topic publishes JSON array [{"temperature":31.4,...}, ...] +ADD COMPONENT "Gauge" WITH TYPE "gauge" + BIND VALUE TO TOPIC "plant/machine1/readings/last50" WITH JSON_PATH "0.temperature" +``` + +--- + +## Chart Configuration + +Charts need `SET COLUMNS` to know which JSON fields to render. +**Without `SET COLUMNS`, a chart bound to JSON data will appear empty.** + +```lot +// ✅ CORRECT — chart from JSON array +ADD COMPONENT "ReadingsChart" WITH TYPE "chart" + SET LABEL "Temperature & Pressure" + SET COLUMNS "timestamp,temperature,pressure" ← exact JSON field names + BIND DATA TO TOPIC "plant/machine1/readings/last50" + +// ✅ CORRECT — realtime chart from a live scalar topic +ADD COMPONENT "LiveTemp" WITH TYPE "realtime-chart" + SET LABEL "Live Temperature" + SET UNIT "°C" + SET TIME_WINDOW 300 + BIND VALUE TO TOPIC "plant/machine1/temperature" + +// ❌ WRONG — chart without SET COLUMNS; shows empty +ADD COMPONENT "Chart" WITH TYPE "chart" + BIND DATA TO TOPIC "plant/machine1/readings/last50" + // missing SET COLUMNS → chart is empty +``` + +Column rules: +- Names must match the exact JSON field names in the payload (case-sensitive) +- For charts: first column = X axis (time/label), remaining columns = Y series + +--- + +## Table Component — Full CRUD Data Grid + +The table component is a full-featured data grid: sort, filter, search, pagination, +row selection, and CRUD operations that publish back to the broker via MQTT. + +```lot +// ── READ-ONLY MONITORING TABLE ── +ADD COMPONENT "AlertsTable" WITH TYPE "table" + BIND DATA TO TOPIC "alarms/active" + SET COLUMNS "severity,message,source,timestamp" + SET COLUMN_LABELS "Severity,Message,Source,Time" + SET COLUMN_TYPES "badge,string,string,datetime" + SET SORTABLE true + SET SEARCHABLE true + SET PAGE_SIZE 15 + SET SELECTABLE "single" + ON ROW_CLICK DO + NAVIGATE TO PANEL "AlarmDetail" WITH "id" = VALUE + +// ── FULL CRUD TABLE ── +ADD COMPONENT "MachinesGrid" WITH TYPE "table" + BIND DATA TO TOPIC "machines/list" + SET COLUMNS "id,name,location,status,last_seen" + SET COLUMN_LABELS "ID,Name,Location,Status,Last Seen" + SET COLUMN_TYPES "number,string,string,badge,datetime" + SET COLUMN_WIDTHS "60,160,160,100,180" + SET SORTABLE true + SET FILTERABLE true + SET SEARCHABLE true + SET SELECTABLE "single" + SET PAGE_SIZE 25 + SET ALLOW_CREATE true + SET ALLOW_UPDATE true + SET ALLOW_DELETE true + ON SELECT DO + PUBLISH TOPIC "ui/selected/machine" WITH VALUE + ON CREATE DO + INVOKE ACTION "RegisterMachine" WITH "data" = VALUE + ON UPDATE DO + INVOKE ACTION "UpdateMachine" WITH "data" = VALUE + ON DELETE DO + PUBLISH TOPIC "machines/remove" WITH VALUE + +// ── MULTI-SELECT BULK OPERATIONS ── +ADD COMPONENT "OrdersTable" WITH TYPE "table" + BIND DATA TO MODEL "OrderList" + SET COLUMNS "order_id,customer,product,quantity,status" + SET COLUMN_TYPES "string,string,string,number,badge" + SET SORTABLE true + SET FILTERABLE true + SET SELECTABLE "multi" + SET PAGE_SIZE 50 + SET ALLOW_DELETE true + ON SELECT DO + PUBLISH TOPIC "orders/selected" WITH VALUE + ON DELETE DO + INVOKE ACTION "BulkCancelOrders" WITH "ids" = VALUE +``` + +**SET properties for table:** + +- SET COLUMNS "f1,f2,f3" exact JSON field names, comma-separated +- SET COLUMN_LABELS "L1,L2,L3" display headers (defaults to field names) +- SET COLUMN_TYPES "t1,t2,t3" number / string / datetime / boolean / badge +- SET COLUMN_WIDTHS "w1,w2,w3" pixel widths per column +- SET SORTABLE true/false click column headers to sort +- SET FILTERABLE true/false per-column filter inputs below headers +- SET SEARCHABLE true/false global search bar in toolbar +- SET SELECTABLE "single" / "multi" / "none" +- SET PAGE_SIZE N rows per page +- SET ALLOW_CREATE true/false show + button in toolbar +- SET ALLOW_UPDATE true/false show ✎ button in toolbar +- SET ALLOW_DELETE true/false show 🗑 button in toolbar + +**Events:** +- ON SELECT DO fires when row selection changes (VALUE = selected row JSON) +- ON ROW_CLICK DO fires on row click (VALUE = row JSON) +- ON CREATE DO fires when create form is submitted (VALUE = new record JSON) +- ON UPDATE DO fires when edit form is submitted (VALUE = updated record JSON) +- ON DELETE DO fires when delete confirmed (VALUE = id of deleted row) + +--- + +## Map Component — Track Anything With a Position + +The map component shows markers, current positions, and historical traces on an +interactive map. It works for ANY entity that has lat/lng coordinates: vehicles, +vessels, people, drones, containers, sensors, delivery riders, robots, animals, +field workers — the pattern is identical regardless of what you're tracking. + +It uses BIND LOCATION (one entity), BIND MARKERS (many entities), and BIND TRACE +(historical path). Use MQTT wildcard ("+") in the topic to show ALL entities. + +```lot +// ── SIMPLE — topic publishes only {lat, lng} ── +ADD COMPONENT "AssetTracker" WITH TYPE "map" + SET ZOOM 14 + SET CENTER_LAT 38.7169 + SET CENTER_LON -9.1399 + BIND LOCATION TO TOPIC "vehicle/gps" + BIND TRACE TO TOPIC "vehicle/gps" + SET TRACE_DEPTH 200 + SET TRACE_COLOR "#3b82f6" + SET TRACE_WIDTH 3 + +// ── RICH JSON — topic publishes {machine_id, temp, lat, lng, speed, status} ── +// The lat/lng are INSIDE a bigger JSON object, not a separate GPS topic +ADD COMPONENT "TelemetryMap" WITH TYPE "map" + SET ZOOM 14 + SET CENTER_LAT 38.7169 + SET CENTER_LON -9.1399 + BIND LOCATION TO TOPIC "fleet/telemetry" + SET LAT_FIELD "lat" + SET LNG_FIELD "lng" + BIND TRACE TO TOPIC "fleet/telemetry" + SET TRACE_DEPTH 200 + +// ── NESTED JSON — topic publishes {id, data: {position: {latitude, longitude}}} ── +ADD COMPONENT "NestedMap" WITH TYPE "map" + SET ZOOM 14 + SET CENTER_LAT 38.7169 + SET CENTER_LON -9.1399 + BIND LOCATION TO TOPIC "fleet/telemetry" WITH JSON_PATH "data.position" + SET LAT_FIELD "latitude" + SET LNG_FIELD "longitude" + +// ── FLEET — multiple markers + custom field names + clustering ── +ADD COMPONENT "FleetMap" WITH TYPE "map" + SET ZOOM 10 + SET CENTER_LAT 38.7169 + SET CENTER_LON -9.1399 + SET CLUSTER true + BIND MARKERS TO TOPIC "fleet/positions" + ON MARKER_CLICK DO + NAVIGATE TO PANEL "VehicleDetail" WITH "vehicleId" = VALUE + +// ── FLEET with custom field names — payload uses latitude/longitude not lat/lng ── +ADD COMPONENT "SensorMap" WITH TYPE "map" + SET ZOOM 12 + SET CENTER_LAT 38.7169 + SET CENTER_LON -9.1399 + BIND MARKERS TO TOPIC "sensors/locations" + SET LAT_FIELD "latitude" + SET LNG_FIELD "longitude" + SET MARKER_ID_FIELD "device_id" + SET MARKER_LABEL_FIELD "label" + +// ── COMBINED — fleet markers + selected vehicle trace ── +ADD COMPONENT "TrackingMap" WITH TYPE "map" + SET ZOOM 11 + SET CENTER_LAT 38.7169 + SET CENTER_LON -9.1399 + SET CLUSTER true + BIND MARKERS TO TOPIC "fleet/positions" + BIND LOCATION TO TOPIC "fleet/selected/gps" + BIND TRACE TO TOPIC "fleet/selected/gps" + SET TRACE_DEPTH 300 + SET TRACE_COLOR "#f97316" + SET TRACE_WIDTH 3 + ON MARKER_CLICK DO + PUBLISH TOPIC "fleet/selected" WITH VALUE + +// ── WILDCARD — all entities from prefix/+ as markers ── +// The pattern is IDENTICAL for any trackable entity: + +// Vessels: vessels/live/+ → {mmsi, name, lat, lon, sog, ...} +ADD COMPONENT "AllVesselsMap" WITH TYPE "map" + SET ZOOM 6 + SET CENTER_LAT 35.0 + SET CENTER_LON -9.0 + SET CLUSTER true + BIND MARKERS TO TOPIC "vessels/live/+" + SET LAT_FIELD "lat" + SET LNG_FIELD "lon" + SET MARKER_ID_FIELD "mmsi" + SET MARKER_LABEL_FIELD "name" + SET STALE_AFTER 300 + ON MARKER_CLICK DO + NAVIGATE TO PANEL "VesselDetail" WITH "mmsi" = VALUE + +// Delivery riders: riders/+/location → {rider_id, name, latitude, longitude, status} +ADD COMPONENT "RiderMap" WITH TYPE "map" + SET ZOOM 12 + SET CENTER_LAT 38.72 + SET CENTER_LON -9.14 + BIND MARKERS TO TOPIC "riders/+/location" + SET LAT_FIELD "latitude" + SET LNG_FIELD "longitude" + SET MARKER_ID_FIELD "rider_id" + SET MARKER_LABEL_FIELD "name" + SET STALE_AFTER 120 + +// Drones: drones/telemetry/+ → {drone_id, lat, lng, alt, battery, mission} +ADD COMPONENT "DroneMap" WITH TYPE "map" + SET ZOOM 14 + SET CENTER_LAT 41.15 + SET CENTER_LON -8.61 + BIND MARKERS TO TOPIC "drones/telemetry/+" + SET MARKER_ID_FIELD "drone_id" + SET MARKER_LABEL_FIELD "drone_id" + +// Field workers: workers/gps/+ → {employee_id, name, lat, lng, zone} +ADD COMPONENT "WorkerMap" WITH TYPE "map" + SET ZOOM 16 + SET CENTER_LAT 40.42 + SET CENTER_LON -3.70 + BIND MARKERS TO TOPIC "workers/gps/+" + SET MARKER_ID_FIELD "employee_id" + SET MARKER_LABEL_FIELD "name" + SET STALE_AFTER 60 +``` + +**SET properties for map:** + +- SET ZOOM N initial zoom level (1–18, default 12) +- SET CENTER_LAT N initial center latitude (decimal degrees) +- SET CENTER_LON N initial center longitude (decimal degrees) +- SET CLUSTER true/false cluster nearby markers (default false) +- SET TILE_URL "url" custom tile URL (default OpenStreetMap) + +**BIND targets for map:** + +- BIND LOCATION TO TOPIC "t" single GPS position — payload: {lat, lng} or [lat, lng] or "lat,lng" + WITH JSON_PATH "path" navigate into larger JSON first (e.g. "data.position", "0") + SET LAT_FIELD "fieldname" override lat field name (default "lat", also tries "latitude") + SET LNG_FIELD "fieldname" override lng field name (default "lng", also tries "longitude") +- BIND MARKERS TO TOPIC "t" array of markers — payload: [{id, lat, lng, name, ...}, ...] + SET LAT_FIELD "fieldname" override lat field name for each marker + SET LNG_FIELD "fieldname" override lng field name for each marker + SET MARKER_ID_FIELD "field" which field is the unique marker ID (default "id") + SET MARKER_LABEL_FIELD "f" which field is the marker popup label (default "name") + SET STALE_AFTER N seconds before unmarked entities are removed (optional) +- BIND TRACE TO TOPIC "t" historical path polyline — uses DataPoint Store trace buffer + SET TRACE_DEPTH N max trace points (default 100) + SET TRACE_COLOR "#hex" polyline color (default "#3b82f6") + SET TRACE_WIDTH N polyline width in pixels (default 3) + +**WILDCARD TOPICS — multi-entity aggregation (CRITICAL):** + +Use MQTT wildcards (+ or #) in the topic to aggregate multiple sources: +- BIND MARKERS TO TOPIC "vessels/live/+" → each matching topic becomes a marker +- BIND DATA TO TOPIC "sensors/+/readings" → each matching topic becomes a table row +- BIND VALUE TO TOPIC "fleet/+/speed" → each matching topic becomes a chart series + +When the topic contains + or #, the broker emits "wildcard": true in the A2UI binding. +The Hub subscribes to the wildcard and aggregates messages into a collection automatically. +Each entity is keyed by its actual topic (e.g. "vessels/live/636025061"). + +**Events:** +- ON MARKER_CLICK DO fires when a marker is clicked (VALUE = marker data JSON) + +// ── WILDCARD TABLE — any prefix/+ as rows (same pattern for any entity) ── +// Vessels: +ADD COMPONENT "VesselsTable" WITH TYPE "table" + SET COLUMNS "mmsi,name,lat,lon,sog,heading,timestamp" + SET COLUMN_LABELS "MMSI,Name,Latitude,Longitude,Speed,Heading,Last Update" + SET COLUMN_TYPES "string,string,number,number,number,number,datetime" + SET SORTABLE true + SET SEARCHABLE true + SET PAGE_SIZE 25 + BIND DATA TO TOPIC "vessels/live/+" + ON ROW_CLICK DO + NAVIGATE TO PANEL "VesselDetail" WITH "mmsi" = VALUE + +// Workers: +ADD COMPONENT "WorkerTable" WITH TYPE "table" + SET COLUMNS "employee_id,name,zone,lat,lng,timestamp" + SET COLUMN_LABELS "ID,Name,Zone,Lat,Lng,Last Seen" + SET COLUMN_TYPES "string,string,string,number,number,datetime" + SET SORTABLE true + SET SEARCHABLE true + BIND DATA TO TOPIC "workers/gps/+" + +--- + +## Realtime Chart — Trace-Driven Time Series + +The realtime-chart component builds a scrolling time series from the DataPoint +Store's trace buffer. Unlike "chart" (which receives a full JSON array snapshot), +realtime-chart accumulates individual values over time. + +```lot +// ── SINGLE SERIES ── +ADD COMPONENT "TempTrace" WITH TYPE "realtime-chart" + SET LABEL "Temperature Over Time" + SET UNIT "°C" + SET TRACE_DEPTH 100 + SET Y_MIN 0 + SET Y_MAX 150 + BIND VALUE TO TOPIC "sensor/temperature" + +// ── MULTIPLE SERIES — overlay two topics ── +ADD COMPONENT "ProcessVars" WITH TYPE "realtime-chart" + SET LABEL "Process Variables" + SET TRACE_DEPTH 200 + BIND VALUE TO TOPIC "sensor/temperature" + SET SERIES_LABEL "Temperature" + SET SERIES_COLOR "#ef4444" + BIND VALUE TO TOPIC "sensor/pressure" + SET SERIES_LABEL "Pressure" + SET SERIES_COLOR "#3b82f6" +``` + +**SET properties for realtime-chart:** + +- SET TRACE_DEPTH N max data points to show (default 100) +- SET Y_MIN N / SET Y_MAX N fixed Y axis range (auto-scale if omitted) +- SET UNIT "°C" Y axis label +- SET CHART_TYPE "line" chart type: line (default) or bar + +**Per-series properties (after each BIND VALUE):** + +- SET SERIES_LABEL "name" legend label for this series +- SET SERIES_COLOR "#hex" line color for this series +- SET SERIES_LABEL_FIELD "f" extract series label from payload field (for wildcard topics) + +> **Series labels live on `SET SERIES_LABEL`, NOT on `BIND`.** `BIND` only takes a +> target keyword (`VALUE`, `STATE`, …). The label is a per-binding SET that must +> be **indented under** the `BIND VALUE TO TOPIC` line it belongs to. + +### ❌ ANTI-PATTERNS — non-canonical forms the parser has to repair + +```lot +// ❌ WRONG — `SERIES` is not a valid BIND target. The parser rewrites it to +// BIND VALUE TO TOPIC "…" with the quoted text as the series label, and +// warns. (Older brokers subscribed to a topic named "TOPIC".) +ADD COMPONENT "Trend" WITH TYPE "realtime-chart" + BIND SERIES "Messages / Minute" TO TOPIC "kpi/messagesPerMinute" + +// ❌ WRONG — `WITH UNIT` on a component body is non-canonical: the parser +// rewrites it to SET UNIT and warns. Chart-scoped properties MUST use `SET`. +ADD COMPONENT "Trend" WITH TYPE "realtime-chart" + WITH LABEL "Messages / Minute Trend" + WITH UNIT "msg/min" + BIND VALUE TO TOPIC "kpi/messagesPerMinute" + +// ✅ CORRECT — `SET` for properties, `BIND VALUE` + indented `SET SERIES_LABEL` +ADD COMPONENT "MessagesPerMinuteTrend" WITH TYPE "realtime-chart" + SET LABEL "Messages / Minute Trend" + SET UNIT "msg/min" + SET TRACE_DEPTH 100 + BIND VALUE TO TOPIC "kpi/messagesPerMinute" + SET SERIES_LABEL "Messages / Minute" +``` + +**Rule of thumb for charts (and every other component):** +- Component-level configuration → **`SET `** (`SET LABEL`, `SET UNIT`, `SET TRACE_DEPTH`, `SET Y_MIN`, `SET CHART_TYPE`, …). +- Header-only modifiers (the line that starts with `ADD COMPONENT`) → `WITH TYPE`, `WITH ID`, `WITH COLUMN_SPAN`, `WITH ROW_SPAN`, `WITH INTERACT`. Nothing else belongs on a `WITH` sub-line for a chart. +- Bindings → **`BIND TO TOPIC "…"`** then optionally indented `SET SERIES_LABEL` / `SET SERIES_COLOR` / `SET SERIES_LABEL_FIELD` / `SET TRACE_DEPTH` / `SET STALE_AFTER`. + +**Wildcard realtime-chart — each matching topic becomes a series:** + +```lot +// Each vessel/live/ topic → separate speed line on the chart +ADD COMPONENT "SpeedChart" WITH TYPE "realtime-chart" + SET LABEL "Vessel Speeds" + SET UNIT "kn" + SET TRACE_DEPTH 100 + SET Y_MIN 0 + SET Y_MAX 40 + BIND VALUE TO TOPIC "vessels/live/+" + SET SERIES_LABEL_FIELD "name" +``` + +--- + +## Interaction — Visibility vs Interact + +Viewing a panel ≠ permission to interact with every component. +Use `WITH INTERACT` per component to restrict who can write: + +```lot +ADD COMPONENT "StopBtn" WITH TYPE "button" + SET LABEL "⚠ STOP" + SET STYLE "danger" + WITH INTERACT FOR GROUP "supervisors" ← only supervisors can click + WITH INTERACT_DENY NOTIFY ← sends denial message to UI + ON CLICK DO + PUBLISH TOPIC "zone1/emergency/stop" WITH 1 + +ADD COMPONENT "SpeedSlider" WITH TYPE "slider" + WITH INTERACT PUBLIC ← any viewer can slide + SET RANGE FROM 0 TO 100 + BIND VALUE TO TOPIC "zone1/speed" + ON CHANGE DO + PUBLISH TOPIC "zone1/speed/cmd" WITH VALUE +``` + +| Keyword | Who can interact | +|---|---| +| `WITH INTERACT PUBLIC` | Anyone who can view the panel | +| `WITH INTERACT FOR GROUP "g"` | Only members of group g | +| `WITH INTERACT FOR USER "u"` | Only the named user | +| *(omitted)* | Anyone who can view the panel (same as `PUBLIC`) — omitting it does NOT make the component view-only | + +Denial modes: +- `WITH INTERACT_DENY SILENT` — the interaction is dropped with no feedback (default) +- `WITH INTERACT_DENY NOTIFY` — broker publishes to `$Visu/Session//Denied` + +--- + +## Event Handlers — CRITICAL SYNTAX RULES + +**Multi-line action bodies:** the canonical form ends the `ON ... DO` line at `DO` and puts +each action on the NEXT lines, indented MORE than the `ON` line. A single action on the +same line as `DO` also parses, but use the multi-line form so every handler looks the same. + +```lot +// ✅ CORRECT — actions indented under DO on separate lines +ADD COMPONENT "StartBtn" WITH TYPE "button" + SET LABEL "Start" + ON CLICK DO + PUBLISH TOPIC "machine/cmd" WITH "start" + +// ✅ CORRECT — multiple actions under one DO +ADD COMPONENT "StartBtn" WITH TYPE "button" + SET LABEL "Start Machine" + ON CLICK DO + PUBLISH TOPIC "machine/state" WITH "running" + PUBLISH TOPIC "alarm/ack" WITH 1 + NAVIGATE TO PANEL "RunningView" + +// ✅ CORRECT — navigation button +ADD COMPONENT "NavBtn" WITH TYPE "button" + SET LABEL "Go to Dashboard" + ON CLICK DO + NAVIGATE TO PANEL "DashboardMain" + +// ✅ CORRECT — navigate back +ADD COMPONENT "BackBtn" WITH TYPE "button" + SET LABEL "Back" + ON CLICK DO + NAVIGATE BACK + +// ✅ CORRECT — invoke a LOT action +ADD COMPONENT "ProcessBtn" WITH TYPE "button" + SET LABEL "Process" + ON CLICK DO + INVOKE ACTION "ProcessOrder" WITH "id" = VALUE + +// ✅ CORRECT — conditional +ADD COMPONENT "AlarmBtn" WITH TYPE "button" + ON CLICK DO + IF VALUE EQUALS "fault" THEN NAVIGATE TO PANEL "FaultPanel" + +// ✅ CORRECT — other events +ADD COMPONENT "SpeedSlider" WITH TYPE "slider" + ON CHANGE DO + PUBLISH TOPIC "machine/speed" WITH VALUE + +ADD COMPONENT "LampSwitch" WITH TYPE "switch" + ON TOGGLE DO + PUBLISH TOPIC "lamp/cmd" WITH STATE +``` + +**Avoid writing actions inline after DO on the same line** (they parse, but are not canonical): +```lot +// ⚠️ NON-CANONICAL — parses, but write the action on its own indented line +ON CLICK DO NAVIGATE TO PANEL "Dashboard" +ON CLICK DO PUBLISH TOPIC "x" WITH 1 +``` + +--- + +## Absolute Positioning (Positioned Layout) + +For HMI and SCADA screens where every element has a fixed pixel position: + +```lot +DEFINE PANEL "HMIScreen" + WITH TITLE "Machine HMI" + WITH LAYOUT "positioned" + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "TempGauge" WITH TYPE "gauge" + SET LABEL "Temperature" + SET UNIT "°C" + SET RANGE FROM 0 TO 100 + SET POSITION X 50 Y 80 + SET WIDTH 200 + SET HEIGHT 200 + BIND VALUE TO TOPIC "sensor/temperature" + + ADD COMPONENT "StartBtn" WITH TYPE "button" + SET LABEL "START" + SET POSITION X 300 Y 100 + SET WIDTH 120 + SET HEIGHT 48 + ON CLICK DO + PUBLISH TOPIC "machine/cmd" WITH "start" +``` + +Position properties: +- `SET POSITION X 100 Y 200` — absolute pixel position +- `SET X 100` / `SET Y 200` — individual axis +- `SET WIDTH 300` / `SET HEIGHT 200` — component size +- `SET Z_INDEX 10` — stacking order +- `SET ROTATION 45` — rotation in degrees + +--- + +## Other Supported Clauses — thresholds, state colours, grid placement, accordions, model writes, route events + +```lot +DEFINE PANEL "LineOverview" + WITH TITLE "Line Overview" + WITH LAYOUT "grid" COLUMNS 3 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "OvenTemp" WITH TYPE "gauge" AT COLUMN 1 ROW 1 SPAN 2 COLUMNS + SET LABEL "Oven Temp" + SET UNIT "°C" + SET RANGE FROM 0 TO 300 + ADD THRESHOLD AT 200 WITH COLOR "#f59e0b" LABEL "High" + ADD THRESHOLD AT 250 WITH COLOR "#ef4444" LABEL "Critical" + BIND VALUE TO TOPIC "line1/oven/temp" + + ADD COMPONENT "OvenState" WITH TYPE "indicator" + SET LABEL "Oven" + SET ON_VALUE "running" WITH COLOR "#22c55e" + SET ON_VALUE "fault" WITH COLOR "#ef4444" + BIND STATE TO TOPIC "line1/oven/state" + + ADD COMPONENT "Details" WITH TYPE "accordion" + ADD SECTION "Setpoints" + ADD COMPONENT "OvenSP" WITH TYPE "slider" + SET LABEL "Oven Setpoint" + SET RANGE FROM 0 TO 300 + ON CHANGE DO + SET MODEL "OvenControl.setpoint" WITH VALUE + ADD SECTION "Maintenance" + ADD COMPONENT "FlushBtn" WITH TYPE "button" + SET LABEL "Flush" + ON CLICK DO + TRIGGER ROUTE "LineDB" EVENT "LogFlush" WITH "line" = "line1" +``` + +- `AT COLUMN n ROW m [SPAN n COLUMNS] [SPAN m ROWS]` on the `ADD COMPONENT` line places a + component in a grid cell (grid layout only). +- `ADD THRESHOLD AT WITH COLOR "" [LABEL ""]` adds a colour band to a gauge. +- `SET ON_VALUE "" WITH COLOR ""` maps an indicator state to a colour (repeat per state). +- `ADD COMPONENT … WITH TYPE "accordion"` + indented `ADD SECTION "Title"` lines group + components into collapsible sections (`"tabs"` + `ADD TAB "Title"` works the same way). +- `SET MODEL "Model.field" WITH VALUE` in a `DO` body writes the field's topic of a deployed + model. It does not work on a `COLLAPSED` model yet (the write is logged and skipped). +- `TRIGGER ROUTE "Route" EVENT "Event" [WITH "key" = value …]` fires a route event as the + clicking user. It is refused (logged, not run) for an event whose name starts with `_` + and for an agent route. + +--- + +## Visibility Decision Tree + +``` +Everyone should see it? → WITH VISIBILITY PUBLIC +Specific groups/users only? → WITH VISIBILITY SHARED + WITH SHARE TO GROUP "operators" + WITH SHARE TO GROUP "supervisors" +Only the creator (me)? → WITH VISIBILITY PRIVATE +``` + +> **`WITH VISIBILITY` takes a BARE keyword — never a string and never the +> wrong word.** The only valid values are `PUBLIC`, `SHARED`, `PRIVATE`. A +> common silent failure is confusing visibility with state and writing +> `WITH VISIBILITY "published"`. The parser maps any word other than +> PUBLIC / SHARED / PRIVATE to `PRIVATE` and the panel is **never published to `$Visu`**, +> so dashboard clients never see it. Nothing rewrites the quoted form for +> you, so the canonical source must be: + +```lot +// ❌ WRONG — quoted, lowercase, AND not even a valid visibility value. +// Falls through to PRIVATE → panel invisible to every dashboard client. +WITH VISIBILITY "published" + +// ⚠️ NON-CANONICAL — the parser strips the quotes and ignores case, so this +// is PUBLIC, but write the bare keyword. +WITH VISIBILITY "public" + +// ✅ CORRECT — bare uppercase keyword. +WITH VISIBILITY PUBLIC + +// (And `published` belongs on STATE, not VISIBILITY.) +WITH STATE PUBLISHED +``` + +--- + +## Common Mistakes — NEVER DO THESE + +```lot +-- ❌ FLAT GRID for a multi-section operator panel — operators will reject this +DEFINE PANEL "INJ001OperatorPanel" +WITH LAYOUT "grid" COLUMNS 4 +// 20 gauges and values in one endless scrolling grid +// WRONG: when user says Overview/Process/Setpoints/Production/History +// → always use multi-panel navigation: one panel per section + nav panel + +-- ✅ CORRECT — multi-panel navigation for operator panels with 3+ sections +// Nav panel: INJ001Nav (buttons that NAVIGATE TO PANEL each section) +// Section panels: INJ001Overview, INJ001Process, INJ001Setpoints, INJ001Production +// Each section has a "← Back" button with NAVIGATE BACK + +-- Missing WITH STATE PUBLISHED → panel is DRAFT and invisible +DEFINE PANEL "X" +WITH VISIBILITY PUBLIC +// no WITH STATE PUBLISHED ← WRONG: panel stays in DRAFT + +-- PRIVATE + SHARE (contradictory) +WITH VISIBILITY PRIVATE +WITH SHARE TO GROUP "ops" ← WRONG: use SHARED instead + +-- No BIND on a data component → shows static blank value +ADD COMPONENT "Temp" WITH TYPE "gauge" + SET LABEL "Temp" + // missing BIND VALUE TO TOPIC ← WRONG: gauge shows nothing + +-- ❌ Wrong component type for text — use "text" not "label" +ADD COMPONENT "Status" WITH TYPE "label" ← WRONG: no label renderer; parser rewrites it to "text" and warns +ADD COMPONENT "Status" WITH TYPE "text" ← CORRECT + +-- ❌ Wrapping SVG in a card + text component — NEVER do this +ADD COMPONENT "BoxSvg" WITH TYPE "card" + ADD COMPONENT "BoxSvgText" WITH TYPE "text" + SET CONTENT "" ← WRONG: text renders as string, SVG not painted + ← card title shows component ID, not SET LABEL value + ← static content shows "---" because no BIND fires + +-- ✅ CORRECT — even for static SVG with no live data, always use WITH TYPE "svg" +ADD COMPONENT "BoxSvg" WITH TYPE "svg" + SET INLINE " + + + +" + SET WIDTH 220 + SET HEIGHT 180 + // No BIND statements needed for static SVG — it just renders as a graphic + +-- ❌ Using SET TITLE on a card vs SET LABEL — card header uses TITLE not LABEL +ADD COMPONENT "MyCard" WITH TYPE "card" + SET LABEL "Box Counter" ← WRONG: Hub card uses props.title, LABEL is ignored +ADD COMPONENT "MyCard" WITH TYPE "card" + SET TITLE "Box Counter" ← CORRECT + +-- ❌ Binding a JSON topic WITHOUT JSON_PATH — assumes sub-topics exist +-- Topic plant/machine1/readings publishes: {"temperature": 31.4, "pressure": 1.9} +BIND VALUE TO TOPIC "plant/machine1/readings/temperature" ← WRONG: sub-topic doesn't exist! +BIND VALUE TO TOPIC "plant/machine1/readings" WITH JSON_PATH "temperature" ← CORRECT + +-- ❌ Binding a JSON ARRAY topic to a scalar widget without JSON_PATH — shows [object Object] +-- Topic last50 publishes: [{"temperature": 31.4, ...}, ...] +-- (Use "gauge" for numeric scalars, never "value" — "value" is forbidden for numbers.) +ADD COMPONENT "TempGauge" WITH TYPE "gauge" + SET RANGE FROM 0 TO 100 + SET UNIT "°C" + BIND VALUE TO TOPIC "plant/machine1/readings/last50" ← WRONG: whole array → [object Object] + +ADD COMPONENT "TempGauge" WITH TYPE "gauge" + SET RANGE FROM 0 TO 100 + SET UNIT "°C" + BIND VALUE TO TOPIC "plant/machine1/readings/last50" WITH JSON_PATH "0.temperature" ← CORRECT + +-- ❌ Chart without SET COLUMNS — renders empty even with data +ADD COMPONENT "Chart" WITH TYPE "chart" + BIND DATA TO TOPIC "plant/machine1/readings/last50" ← WRONG: no columns = nothing shown + +ADD COMPONENT "Chart" WITH TYPE "chart" + SET COLUMNS "timestamp,temperature,pressure" + BIND DATA TO TOPIC "plant/machine1/readings/last50" ← CORRECT + +-- ⚠️ Inline action after DO — parses, but is not the canonical form +ADD COMPONENT "Btn" WITH TYPE "button" + ON CLICK DO NAVIGATE TO PANEL "X" ← NON-CANONICAL: write the action on the next line + +-- ✅ Correct: DO ends the line, action is indented on the next line +ADD COMPONENT "Btn" WITH TYPE "button" + ON CLICK DO + NAVIGATE TO PANEL "X" ← CORRECT + +-- ❌ ❌ ❌ MAP + JSON TOPIC — THE MOST COMMON MAP MISTAKE ❌ ❌ ❌ +-- Topic vessels/live/636025061 publishes ONE JSON payload: +-- {"mmsi":"636025061","name":"CHARLESTON","lat":31.92,"lon":34.27,"sog":0,"heading":317,...} + +-- ❌ WRONG — assumes each field is a separate sub-topic (they DON'T EXIST) +BIND LOCATION TO TOPIC "vessels/live/636025061/lat" ← sub-topic doesn't exist! +BIND VALUE TO TOPIC "vessels/live/636025061/name" ← sub-topic doesn't exist! +BIND VALUE TO TOPIC "vessels/live/636025061/sog" ← sub-topic doesn't exist! + +-- ❌ WRONG — invented AND syntax (does not exist in LoTV) +BIND LOCATION TO TOPIC "vessels/live/+/lat" AND "vessels/live/+/lon" ← NOT VALID SYNTAX + +-- ❌ WRONG — non-canonical component WITH lines (auto-corrected or dropped; never emit) +WITH TEXT "some text" ← NON-CANONICAL: use SET LABEL or SET CONTENT +WITH POSITION "1,2,8,6" ← DROPPED with a warning: use SET POSITION X n Y n (positioned layout only) +WITH MIN 0 ← NON-CANONICAL: use SET RANGE FROM 0 TO 40 +WITH MAX 40 ← NON-CANONICAL: use SET RANGE FROM 0 TO 40 +WITH UNIT "kn" ← NON-CANONICAL (rewritten to SET UNIT with a warning): use SET UNIT "kn" +WITH TITLE "Speed" ← This IS valid for panels; for components use SET LABEL + +-- ✅ CORRECT — single JSON topic with JSON_PATH for each field + SET LAT_FIELD for map +ADD COMPONENT "VesselMap" WITH TYPE "map" + SET ZOOM 8 + SET CENTER_LAT 31.92 + SET CENTER_LON 34.27 + BIND LOCATION TO TOPIC "vessels/live/636025061" + SET LAT_FIELD "lat" + SET LNG_FIELD "lon" ← payload uses "lon" not "lng"! + BIND TRACE TO TOPIC "vessels/live/636025061" + SET TRACE_DEPTH 200 + SET TRACE_COLOR "#3b82f6" + +ADD COMPONENT "SpeedGauge" WITH TYPE "gauge" + SET LABEL "Speed Over Ground" + SET UNIT "kn" + SET RANGE FROM 0 TO 40 + BIND VALUE TO TOPIC "vessels/live/636025061" WITH JSON_PATH "sog" + +ADD COMPONENT "VesselName" WITH TYPE "text" ← "text" not "value" for strings! + SET LABEL "Vessel Name" + BIND CONTENT TO TOPIC "vessels/live/636025061" WITH JSON_PATH "name" + +ADD COMPONENT "Heading" WITH TYPE "gauge" + SET LABEL "Heading" + SET UNIT "°" + SET RANGE FROM 0 TO 360 + BIND VALUE TO TOPIC "vessels/live/636025061" WITH JSON_PATH "heading" + +ADD COMPONENT "LastUpdate" WITH TYPE "text" ← "text" not "value" for timestamps! + SET LABEL "Last Update" + BIND CONTENT TO TOPIC "vessels/live/636025061" WITH JSON_PATH "timestamp" + +-- KEY RULES for map + JSON topics: +-- 1. ALWAYS inspect the payload FIRST (explore_topics / broker__read_mqtt) +-- 2. If it's a JSON object → use ONE topic + WITH JSON_PATH for each field +-- 3. For map: BIND LOCATION TO TOPIC "parent" + SET LAT_FIELD / SET LNG_FIELD +-- 4. Check the EXACT field names — "lon" ≠ "lng", "latitude" ≠ "lat" +-- 5. NEVER invent sub-topics — if "parent/field" is not in the explore_topics / broker__read_mqtt result, the sub-topic isn't being published +-- 6. String fields (name, source, timestamp) → type "text" + BIND CONTENT +-- 7. Numeric fields (speed, heading, pressure) → type "value" or "gauge" + BIND VALUE +-- 8. LoTV keywords are SET not WITH for component properties (SET LABEL, SET UNIT, SET RANGE) +-- 9. For ALL entities from a base topic → use MQTT wildcard: BIND MARKERS TO TOPIC "base/+" +-- Each matching topic becomes a marker/row/series automatically. NEVER loop over topics manually. +-- Works for ANYTHING: vessels, trucks, people, drones, sensors, containers, animals, robots. + +-- ✅ WILDCARD DASHBOARD — all entities on a map + table from one base topic +-- This is the CORRECT way to show ALL things when each publishes to prefix/ +-- Replace "vessels/live" with any base topic: "trucks/gps", "workers/location", "drones/telemetry" +DEFINE PANEL "VesselFleetDashboard" + WITH TITLE "Fleet Overview" + WITH LAYOUT "grid" COLUMNS 2 + WITH VISIBILITY PUBLIC + WITH STATE PUBLISHED + + ADD COMPONENT "FleetMap" WITH TYPE "map" + SET ZOOM 6 + SET CENTER_LAT 35.0 + SET CENTER_LON -9.0 + SET CLUSTER true + BIND MARKERS TO TOPIC "vessels/live/+" + SET LAT_FIELD "lat" + SET LNG_FIELD "lon" + SET MARKER_ID_FIELD "mmsi" + SET MARKER_LABEL_FIELD "name" + SET STALE_AFTER 300 + ON MARKER_CLICK DO + NAVIGATE TO PANEL "VesselDetail" WITH "mmsi" = VALUE + + ADD COMPONENT "FleetTable" WITH TYPE "table" + SET COLUMNS "mmsi,name,lat,lon,sog,heading,timestamp" + SET COLUMN_LABELS "MMSI,Name,Lat,Lon,Speed,Heading,Last Update" + SET COLUMN_TYPES "string,string,number,number,number,number,datetime" + SET SORTABLE true + SET SEARCHABLE true + BIND DATA TO TOPIC "vessels/live/+" + ON ROW_CLICK DO + NAVIGATE TO PANEL "VesselDetail" WITH "mmsi" = VALUE + +-- ❌ ❌ ❌ FORM ANTI-PATTERNS — NO PARSE ERROR ❌ ❌ ❌ +-- None of these fails to parse; each one is wrong or non-canonical. + +-- ⚠️ TYPE without WITH — parses (TYPE "x" is sugar for WITH TYPE "x"), but WITH TYPE is canonical +ADD COMPONENT "myForm" TYPE "card" ← NON-CANONICAL +ADD COMPONENT "myForm" WITH TYPE "card" ← CORRECT + SET TITLE "Visitor Lead Form" + +-- ❌ "form" is NOT a valid component type — passed through with no warning; the Hub has no renderer for it +ADD COMPONENT "myForm" WITH TYPE "form" ← WRONG: "form" type does not exist +ADD COMPONENT "leadCard" WITH TYPE "card" ← CORRECT: card is the grouping container + +-- ❌ BIND TOPIC "..." — missing target keyword AND TO +-- The parser rewrites it to BIND VALUE TO TOPIC "..." and warns; tables need BIND DATA. +BIND TOPIC "booth/leads/submit" ← WRONG: no target, no TO +BIND DATA TO TOPIC "booth/leads/submit" ← CORRECT +BIND VALUE TO TOPIC "sensor/reading" ← CORRECT +BIND STATE TO TOPIC "machine/status" ← CORRECT +-- BIND always requires: BIND TO TOPIC "..." — all three parts are mandatory. + +-- ❌ ADD FIELD — NOT a LoTV keyword; silently ignored, produces nothing +ADD FIELD "name" TYPE "text" WITH LABEL "Name" ← WRONG: keyword doesn't exist +ADD COMPONENT "nameField" WITH TYPE "text-field" ← CORRECT + SET LABEL "Name" + SET PLACEHOLDER "Enter name" + ON CHANGE DO + PUBLISH TOPIC "form/input/name" WITH VALUE + +-- ⚠️ Inline NAVIGATE with parameters — parses, but put it on its own line under DO +ON MARKER_CLICK DO NAVIGATE TO PANEL "Detail" WITH "id" = VALUE ← NON-CANONICAL +ON MARKER_CLICK DO + NAVIGATE TO PANEL "Detail" WITH "id" = VALUE ← CORRECT + +-- ❌ Deploying without loading the skill +broker.add_panel(...) ← WRONG: always load skill first +broker.load_skill("lot-panels") +broker.add_panel(...) ← RIGHT +``` + +--- + +## Updating an Existing Panel + +Call `broker.add_panel` with the same panel name — it performs an upsert: +the old panel is retracted from `$Visu` and the new version is compiled and published. +This works in BOTH Agent and Insight mode. + +To change only the lifecycle state without redeploying the source (Agent mode only): +``` +broker.update_visu_state("Zone1Dashboard ARCHIVED") +broker.update_visu_state("Zone1Dashboard PUBLISHED") +``` + +> The tool is `update_visu_state` (command `-updateVisuState`); its one argument +> is `" "`. There is no `update_panel_state`. +> Any other state word becomes DRAFT. You can also redeploy via +> `broker.add_panel` with the desired `WITH STATE` value in the header. + +To retrieve the source code of an existing panel (e.g. before modifying it): +``` +broker.get_panel_code(name="Zone1Dashboard") +``` +Returns the full LoTV DEFINE PANEL source text. Available in both Agent and Insight mode. diff --git a/plugins/coreflux/skills/lot-projects/SKILL.md b/plugins/coreflux/skills/lot-projects/SKILL.md deleted file mode 100644 index 24ee2d0..0000000 --- a/plugins/coreflux/skills/lot-projects/SKILL.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -name: lot-projects -description: Structure, author, deploy and version Coreflux projects — the .lotnb notebook JSON format (markdown / lot / python / shellscript cells), project folder layout, load order, ad-hoc vs project-owned entities, and the -addProject / -loadProject / -getProject / -project* git commands including zip64 upload. Use when creating or editing .lotnb files, scaffolding a project, or moving a project between a workspace and a broker. ---- - -# Coreflux Projects and LoT Notebooks - -A **project** is a folder of `.lotnb` notebooks (plus optional `.lot`, `.py`, `README.md`) -that the broker loads as one unit. Entities loaded from a project are *owned* by it -(`$SYS/Coreflux/Entities/ownership`); anything deployed with a bare `-addX` is *ad-hoc* and -survives `-unloadProject`. - -## `.lotnb` format - -A JSON **array** of cells — no wrapper object: - -```json -[ - { "kind": 1, "language": "markdown", "value": "# Line 3 monitoring\nWhat this notebook does." }, - { "kind": 2, "language": "lot", "value": "DEFINE MODEL Reading COLLAPSED WITH TOPIC \"line3/reading\"\n ADD DOUBLE \"temp\" WITH TOPIC \"line3/plc/read/Temp\" AS TRIGGER" }, - { "kind": 2, "language": "python", "value": "# Script Name: Line3Stats\nimport statistics\n\ndef mean(values):\n return {\"mean\": statistics.mean(values)}" }, - { "kind": 2, "language": "shellscript", "value": "mosquitto_sub -t 'line3/#' -v" } -] -``` - -| Property | Values | -|----------|--------| -| `kind` | `1` markdown (docs only) · `2` code | -| `language` | `markdown` · `lot` · `python` · `shellscript` | -| `value` | Raw text; escape newlines as `\n` and quotes as `\"` | - -- One `lot` cell may hold several `DEFINE` blocks; the broker splits them. -- `python` cells **must** start with `# Script Name: Name` (first 10 lines; valid identifier). -- `shellscript` cells are documentation only — never executed by the broker. -- Tell the story in markdown cells: purpose, topics in/out, how to test. Notebooks are the - project's documentation. - -When writing a notebook file, build the JSON with a real serializer mentally: every LoT line -break inside `value` is `\n`, indentation stays 4 spaces, and the file must parse as JSON. -`lot_lint { path }` parses the notebook and lints every cell — run it after editing. - -## Load order - -models → actions → routes → rules → python → themes → panels. Within a kind, cells load in -file order, files alphabetically. Put parents before children (models with `FROM`), callable -actions before callers, and scripts before the actions that `CALL PYTHON` them (a Python cell -is still loaded after actions — the action stays *pending* until the script exists; check -`-getPendingStatus`). - -## Recommended layout - -``` -my-project/ -├── README.md # what, why, broker prerequisites (env/secrets to set) -├── 01-models.lotnb -├── 02-actions.lotnb -├── 03-routes.lotnb # credentials via GET ENV / GET SECRET only -├── 04-rules.lotnb -├── 05-dashboard.lotnb # themes + panels -└── scripts/ # optional: .py sources mirrored into python cells -``` - -Numbered prefixes make alphabetical order match intent. Keep secrets out of the repo: list the -`-setEnv` / `-setSecret` names in the README. - -## Deploying - -| Situation | Do | -|-----------|----| -| Iterate on one notebook against a dev broker | `lotnb_deploy { path, dryRun: true }` → `lotnb_deploy { path }` (ad-hoc entities) | -| Ship the whole folder | `project_upload { path, name, load: true }` (zips → `-addProject zip64:… name load`) | -| Broker can reach git | `broker_command -addProject https://github.com/org/proj.git main` then `-loadProject proj` | -| Folder or zip already on the broker host | `-addProject /path/to/folder` · `-addProject /path/file.zip [name] [load]` | -| Pull a broker project into the workspace | `project_export { name, outputPath }` → unzip | - -`-addProject … load` returns the entity manifest (`entities[]`, `counts`) in the envelope; -`-loadProject` reports `errors[]` per failed entity — fix and reload. - -## Project commands - -| Command | Effect | -|---------|--------| -| `-listProjects` | Projects with status (`data[]`); also retained on `$SYS/Coreflux/Projects/list` | -| `-listEntities` | Loaded manifest with `origin` (`adhoc` or `project/file/cell`) | -| `-loadProject ` | Activate; remembered across restarts | -| `-unloadProject` | Remove project-owned entities, keep ad-hoc ones; clears the restart marker | -| `-removeProject ` | Delete from disk — **destructive, confirm** | -| `-duplicateProject ` | Copy with fresh git init | -| `-getProject ` | Export zip on `$SYS/Coreflux/Projects//download` | -| `-projectStatus ` | Git status → also `$SYS/Coreflux/Projects//status` | -| `-projectManifest ` | File hashes + declared entities | -| `-projectCheckout ` · `-projectPull ` · `-projectPush ` | Git ops on the broker's clone | - -Multi-word names: quote them (`-loadProject "Traceability System"`) or hyphenate. -`--project ` on the broker CLI loads at startup and overrides the remembered one. - -## Review checklist for a project - -- Every route credential is `GET ENV` / `GET SECRET`; README lists the names. -- Every action has a trigger or `INPUT`; timers do not read `PAYLOAD`. -- Models that should auto-publish have an `AS TRIGGER` field. -- Rules use priorities ≥ 100 and do not lock out `root`/admin (`broker-security`). -- Panels are `WITH STATE PUBLISHED` with an explicit visibility. -- `lot_lint { path }` is clean for each notebook; `lotnb_deploy dryRun` shows the expected plan. diff --git a/plugins/coreflux/skills/lot-routes/SKILL.md b/plugins/coreflux/skills/lot-routes/SKILL.md new file mode 100644 index 0000000..1df350e --- /dev/null +++ b/plugins/coreflux/skills/lot-routes/SKILL.md @@ -0,0 +1,526 @@ +--- +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. +--- + +# LOT Connectors — Complete Reference + +Connectors are written `DEFINE ROUTE`; `DEFINE CONNECTOR` is a synonym (and `ADD CONNECTOR_CONFIG` of +`ADD ROUTE_CONFIG`). Both spellings deploy the same connector and are stored exactly as typed. The +examples below use `DEFINE ROUTE`, which every broker version accepts. + +## CRITICAL SYNTAX + +Connector, event, and mapping names are NEVER quoted (bare identifiers). String values ARE quoted. +``` +WRONG: DEFINE ROUTE "ProductionDB" WITH TYPE POSTGRESQL +RIGHT: DEFINE ROUTE ProductionDB WITH TYPE POSTGRESQL + +WRONG: DEFINE ROUTE "MyLLM" WITH TYPE LLM +RIGHT: DEFINE ROUTE MyLLM WITH TYPE LLM +``` + +## Shapes by connector family + +Not every connector uses the same blocks. Match **WITH TYPE** to the config block and pattern below. Call **`broker.get_route_template("TYPE")`** for the authoritative template with all available settings for any connector type. + +**Vendor REST APIs:** when the user names a SaaS or vendor API (Airtable, ServiceNow, SAP, Salesforce, AWS, Azure, Slack, …), load **`rest-api-connectors`** first. It lists REST API apps — ready-made `TYPE REST_API` connectors — by app code; `load_skill("rest-api-connectors/")` returns one with auth, events and topics already written. An app code is never a `WITH TYPE`. + +| Family | Typical pattern | +|--------|-----------------| +| SQL / document DB / search / warehouse / file storage | **ADD *_CONFIG** + **ADD EVENT** (QUERY) | +| OT (Modbus, S7, OPC UA, EtherNet/IP, ADS, Allen-Bradley, Fins) | **ADD *_CONFIG** + optional **ADD EVENT** + **ADD MAPPING** with nested **ADD TAG** | +| OT servers (MODBUS_SERVER, OPCUA_SERVER) | **ADD MODBUS_SERVER_CONFIG** / **OPCUA_SERVER_CONFIG** + **ADD MAPPING** with nested **ADD TAG**; no **ADD EVENT** (see **OT server connectors** below) | +| REST_API | **ADD REST_API_CONFIG** + **ADD EVENT** | +| LLM / MCP | **ADD LLM_CONFIG** / **MCP_CONFIG** (agents are `DEFINE AGENT`, not a connector) | +| EMAIL / BARCODE / VIDEO_* / AUDIO_INPUT | **ADD SMTP_CONFIG** / **BARCODE_CONFIG** / **VIDEO_*_CONFIG** / **AUDIO_INPUT_CONFIG** + **ADD EVENT** | +| KAFKA (STREAMING) | **ADD KAFKA_CONFIG** + **ADD EVENT** with **DIRECTION** "in"/"out" (same SOURCE_TOPIC/DESTINATION_TOPIC keywords as MQTT_BRIDGE; "out" = MQTT to Kafka, "in" = Kafka to MQTT) | +| GRPC (STREAMING) | **ADD GRPC_CONFIG** + **ADD EVENT** with **SOURCE_TOPIC**/**DESTINATION_TOPIC**; **RPC_TYPE** UNARY / SERVER_STREAM / CLIENT_STREAM / BIDI; empty payload = CloseSend on streams; **SESSION_SCOPE** TOPIC (default) or EVENT (one BIDI Call shared across SOURCE `+` topics until **IDLE_TIMEOUT** / CloseSend) | +| MQTT_BRIDGE (SYSTEM) | **ADD SOURCE_CONFIG** + **ADD DESTINATION_CONFIG** + **ADD MAPPING** | +| MQTT_CLUSTER (SYSTEM) | **ADD CLUSTER_CONFIG** | +| FEDERATION (SYSTEM) | **ADD FEDERATION_CONFIG** (REMOTE_CLUSTER_ID, REMOTE_ADDRESS/REMOTE_PORT or REMOTE_ENDPOINTS, CONTROL_LANE/CONTROL_PUSH/CONTROL_SCOPE, DATA_LANE/DATA_OUTBOUND/DATA_INBOUND); no template, so `get_route_template` has nothing for it | +| SPARKPLUG_B (SYSTEM) | **ADD SPARKPLUG_CONFIG** + optional **ADD METRIC** / **ADD DEVICE**; no **ADD EVENT** | +| SPARKPLUG_HOST (SYSTEM) | **ADD SPARKPLUG_HOST_CONFIG** + optional command-overlay **ADD METRIC**; no **ADD EVENT** | + +A broker runs at most one Sparkplug connector that decodes the `spBv1.0` namespace: one SPARKPLUG_HOST, or one SPARKPLUG_B with MODE DECODE/BOTH. ENCODE-only SPARKPLUG_B connectors may coexist. +| MQTT_TO_REST | **ADD MQTT_CONFIG** + **ADD REST_API_CONFIG** + **ADD MAPPING** | + +**OT device points** (registers, nodes, PLC addresses) belong in **ADD TAG** under **ADD MAPPING** on the OT connector, not in **DEFINE MODEL**. + +## OT mappings — MQTT topics for TAG polling + +For **ADD MAPPING** with nested **ADD TAG** (Modbus, S7, OPC UA, EtherNet/IP, etc.): +- Set **SOURCE_TOPIC** on the mapping to the **prefix** where each tag's value is published: **`/`** (tag names are case-sensitive as defined in **ADD TAG**). +- When telling users what topic to **subscribe** to or what **explore_topics** / **broker__read_mqtt** should use for live values, use that **SOURCE_TOPIC** path — **not** **DESTINATION_TOPIC**. +- Omit **DESTINATION_TOPIC** on these OT TAG read/poll mappings unless you have a specific legacy/query pattern that requires it; it is **not** the "display" topic for per-tag data. +- A tag may override with its own **WITH SOURCE_TOPIC** on **ADD TAG**; otherwise it inherits **`/`**. + +## OT TAG WRITABLE — DESTINATION_TOPIC is the write topic + +When an OT TAG is bidirectional (read + write to the PLC), set on **ADD TAG**: +- **WITH WRITABLE "true"** +- **WITH SOURCE_TOPIC ""** — Device → MQTT (current/polled value is published here). +- **WITH DESTINATION_TOPIC ""** — MQTT → Device (the broker subscribes to this topic and forwards the payload to the PLC). + +**DESTINATION_TOPIC on a writable TAG is REQUIRED.** Without it, the broker logs `TAG '' is WRITABLE but has no DESTINATION_TOPIC - skipping` and the write path is never registered. + +Do **NOT** put the "write to PLC" topic in **SOURCE_TOPIC** — **SOURCE_TOPIC** is only the topic where the polled (read) value is published. The write topic always goes in **DESTINATION_TOPIC**. + +## Basic Structure + +OT **ADD MAPPING** with **ADD TAG**: mapping **SOURCE_TOPIC** is the per-tag publish prefix (see **OT mappings - MQTT topics for TAG polling** above). + +``` +DEFINE ROUTE WITH TYPE + ADD + WITH + ADD EVENT + WITH SOURCE_TOPIC "" + WITH DESTINATION_TOPIC "" + WITH QUERY "" + ADD MAPPING + WITH SOURCE_TOPIC "" + WITH EVERY + ADD TAG "TagName" + ... +``` + +Non-OT **ADD MAPPING** blocks (e.g. some bridge templates) may still use **WITH DESTINATION_TOPIC** per their connector template. + +## Connector Types + +### Database Connectors +| Type | Config Block | Default Port | +|------|-------------|--------------| +| POSTGRESQL | SQL_CONFIG | 5432 | +| MYSQL / MARIADB | SQL_CONFIG | 3306 | +| SQLSERVER / MSSQL | SQL_CONFIG | 1433 | +| MONGODB | MONGODB_CONFIG | 27017 | +| OPENSEARCH | OPENSEARCH_CONFIG | 9200 | +| CRATEDB | CRATEDB_CONFIG | 5432 | +| FILE_STORAGE | FILE_STORAGE_CONFIG | — | +| SNOWFLAKE | SNOWFLAKE_CONFIG | — | + +### OT (Operational Technology) Connectors +| Type | Config Block | +|------|-------------| +| MODBUS_TCP | MODBUS_CONFIG | +| MODBUS_SERIAL | MODBUS_CONFIG | +| MODBUS_SERVER / MODBUS_TCP_SERVER | MODBUS_SERVER_CONFIG | +| SIEMENS_S7 / S7 | S7_CONFIG | +| ETHERNETIP / EIP | ETHERNETIP_CONFIG | +| OPCUA / OPC_UA | OPCUA_CONFIG | +| OPCUA_SERVER / OPC_UA_SERVER | OPCUA_SERVER_CONFIG | +| ADS / BECKHOFF / TWINCAT | ADS_CONFIG | +| FINS / OMRON / OMRONFINS | FINS_CONFIG | +| BACNET / BACNET_IP / BACNET_MSTP | BACNET_CONFIG | +| ALLEN_BRADLEY / AB / ALLENBRADLEY | ALLEN_BRADLEY_CONFIG | + +### AI Connectors +| Type | Config Block | +|------|-------------| +| LLM | LLM_CONFIG | +| MCP | MCP_CONFIG | + +### Other Connectors +| Type | Config Block | +|------|-------------| +| REST_API | REST_API_CONFIG | +| MQTT_BRIDGE | SOURCE_CONFIG + DESTINATION_CONFIG (see template) | +| MQTT_CLUSTER | CLUSTER_CONFIG | +| FEDERATION | FEDERATION_CONFIG | +| KAFKA (STREAMING) | KAFKA_CONFIG | +| GRPC (STREAMING) | GRPC_CONFIG | +| SPARKPLUG_B / SPARKPLUG | SPARKPLUG_CONFIG | +| SPARKPLUG_HOST | SPARKPLUG_HOST_CONFIG | +| MQTT_TO_REST (REST API) | MQTT_CONFIG + REST_API_CONFIG | +| EMAIL | SMTP_CONFIG | +| BARCODE | BARCODE_CONFIG | +| VIDEO_INPUT | VIDEO_INPUT_CONFIG | +| AUDIO_INPUT | AUDIO_INPUT_CONFIG | +| VIDEO_OUTPUT | VIDEO_OUTPUT_CONFIG | + +VIDEO_INPUT always publishes JPEG frames. Do not use WITH FORMAT on the connector — FORMAT is reserved for models and the parser will reject it. Use SOURCE webcam:N (or Windows video=Device Name), FRAME_RATE, WIDTH, HEIGHT. WIDTH/HEIGHT is a request: if the camera rejects that size, the broker retries without it and streams at the camera's native resolution, with no error. FFmpeg must be on PATH; local ./run.sh --install-ffmpeg installs it for the detected OS. + +AUDIO_INPUT always publishes raw 16-bit little-endian PCM chunks. Do not use WITH FORMAT. Use SOURCE mic:N (macOS/Linux), audio=Device Name (Windows), anullsrc, or tone:440. SAMPLE_RATE defaults to 16000, CHANNELS to 1, CHUNK_MS to 100. + +## Overload / Backpressure Configuration (ADD ROUTE_CONFIG — cross-type) + +Unlike every other config block above, **ADD ROUTE_CONFIG** is not tied to a connector type — it may be +added to **any** connector, alongside its type-specific config block, to control what happens when the +shared connector channel is saturated (and, on a cluster, where the connector runs). Every setting is optional; an absent block inherits the +broker-wide default. + +``` +DEFINE ROUTE CloudBridge WITH TYPE MQTT_BRIDGE + ADD ROUTE_CONFIG + WITH OVERLOAD_POLICY "lossless" + 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 +``` + +| Setting | Values | Description | +|---------|--------|--------------| +| OVERLOAD_POLICY | `lossless` / `balanced` / `realtime` | `lossless` waits indefinitely and never sheds; `balanced` (default) waits up to OVERLOAD_TIMEOUT then sheds the arriving message; `realtime` never waits and sheds immediately | +| OVERLOAD_TIMEOUT | milliseconds, default 50 | Wait budget for `balanced` only — ignored for `lossless`/`realtime` | +| OVERLOAD_CAPACITY | integer, default unbounded | Max messages from THIS connector in flight at once, for cross-connector isolation | +| CLUSTER_NODE | node name, default none | Cluster only. Pins the connector to the named node: an exclusive connector (a device client, a serial server) runs there or, while that node is down, nowhere. Without it the cluster picks an owner and moves it on failure. Ignored on a standalone broker | + +**`OVERLOAD_CAPACITY` is incompatible with `lossless`** — a capacity is an admission budget that +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. + +## Environment Variables and Secrets + +Use GET ENV and GET SECRET for sensitive configuration: +``` +DEFINE ROUTE MyDB WITH TYPE POSTGRESQL + ADD SQL_CONFIG + WITH SERVER GET ENV "PG_HOST" + WITH PORT 5432 + WITH DATABASE GET ENV "PG_DATABASE" + WITH USERNAME GET ENV "PG_USER" + WITH PASSWORD GET SECRET "PG_PASSWORD" +``` + +## Events (triggered by MQTT messages) + +``` +ADD EVENT ReadSensor + WITH SOURCE_TOPIC "sensors/+/read" + WITH DESTINATION_TOPIC "sensors/{topic.2}/result" + WITH QUERY "SELECT * FROM sensors WHERE id = '{payload}'" +``` + +### Query Placeholders +| Placeholder | Value | +|-------------|-------| +| {payload} | Raw MQTT message payload | +| {payload.json.key} | Nested JSON extraction | +| {topic} | Full MQTT topic | +| {topic.N} | Topic segment by position (1-based) | +| {timestamp} | 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) | +| {fieldName} | Top-level field of a JSON payload (e.g. `{sensor_id}`) | +| {env.NAME} | Environment variable | +| {secret.NAME} | Encrypted secret | + +In SQL queries, `{payload.json.*}` values have single quotes doubled; REST_API passes values unchanged. + +An event runs when a message arrives on its **SOURCE_TOPIC**, or on a timer when it has **WITH EVERY ** +instead. A scheduled (EVERY) event must have a **DESTINATION_TOPIC** or the connector fails to load. An event with +neither SOURCE_TOPIC nor EVERY is accepted but never runs. **DESTINATION_TOPIC** is only where results are published, +so a write-only event (an INSERT) can omit it. KAFKA rejects EVERY on events; KAFKA and GRPC events need both topics. +Every event that registers (SOURCE_TOPIC or EVERY) uses one action slot of the license's action limit. + +## Mappings (scheduled / periodic polling) + +OT **ADD TAG** mappings: polled values publish to **SOURCE_TOPIC/tagName** (no **DESTINATION_TOPIC** for that). + +``` +ADD MAPPING PollSensors + WITH SOURCE_TOPIC "factory/plc1/read" + WITH EVERY 5 SECONDS + ADD TAG "Temperature" + WITH ADDRESS "0" + WITH ADDRESS_TYPE "HOLDING_REGISTER" + WITH DATA_TYPE "INT16" +``` + +Subscribes / **explore_topics** / **broker__read_mqtt**: e.g. **factory/plc1/read/Temperature**. + +Writable TAG (read + write the PLC). The read value publishes on **SOURCE_TOPIC**; publishing to **DESTINATION_TOPIC** writes to the PLC: + +``` +ADD MAPPING ControlSetpoint + WITH SOURCE_TOPIC "factory/plc1/control" + WITH EVERY 1 SECONDS + ADD TAG "Setpoint" + WITH ADDRESS "200" + WITH ADDRESS_TYPE "HOLDING_REGISTER" + WITH DATA_TYPE "FLOAT" + WITH SOURCE_TOPIC "factory/plc1/control/setpoint" + WITH DESTINATION_TOPIC "factory/plc1/control/setpoint/write" + WITH WRITABLE "true" +``` + +Read value publishes on **factory/plc1/control/setpoint**; publishing to **factory/plc1/control/setpoint/write** writes the value to the PLC. + +## Database Connector Examples + +### PostgreSQL +``` +DEFINE ROUTE ProductionDB WITH TYPE POSTGRESQL + ADD SQL_CONFIG + WITH SERVER GET ENV "PG_HOST" + WITH PORT 5432 + WITH DATABASE "factory" + WITH USERNAME GET ENV "PG_USER" + WITH PASSWORD GET SECRET "PG_PASSWORD" + WITH USE_SSL true + ADD EVENT GetOrders + WITH SOURCE_TOPIC "orders/query" + WITH DESTINATION_TOPIC "orders/result" + WITH QUERY "SELECT * FROM orders WHERE status = '{payload}'" + ADD EVENT InsertReading + WITH SOURCE_TOPIC "sensors/+/store" + WITH QUERY "INSERT INTO readings (device, value, ts) VALUES ('{topic.2}', {payload}, NOW())" +``` + +### MongoDB +``` +DEFINE ROUTE LogsDB WITH TYPE MONGODB + ADD MONGODB_CONFIG + WITH CONNECTION_STRING GET ENV "MONGO_URI" + WITH DATABASE "logs" + ADD EVENT StoreLogs + WITH SOURCE_TOPIC "system/logs/+" + WITH QUERY "CLEAN:{collection: logs, document: {source_topic: {source_topic}, data: {value.json}}}" +``` + +A MongoDB insert QUERY must name both `collection:` and `document:`; any other QUERY is treated as a find. + +## OT Connector Examples + +### Modbus TCP +``` +DEFINE ROUTE PLC1 WITH TYPE MODBUS_TCP + ADD MODBUS_CONFIG + WITH IP "192.168.1.100" + WITH PORT 502 + WITH SLAVE_ID 1 + ADD MAPPING ReadRegisters + WITH SOURCE_TOPIC "plc1/read" + WITH EVERY 1 SECONDS + ADD TAG "Temperature" + WITH ADDRESS "0" + WITH ADDRESS_TYPE "HOLDING_REGISTER" + WITH DATA_TYPE "INT16" + WITH SCALING 0.1 + ADD TAG "Pressure" + WITH ADDRESS "1" + WITH ADDRESS_TYPE "HOLDING_REGISTER" + WITH DATA_TYPE "FLOAT32" +``` + +Modbus TAGs need **ADDRESS_TYPE** (`HOLDING_REGISTER`, `INPUT_REGISTER`, `COIL`, `DISCRETE_INPUT`): without it the +connector deploys but every poll fails with `Unsupported address type`. A plain **ADDRESS** is the zero-based register +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. + +### BACnet/IP +``` +DEFINE ROUTE BMS WITH TYPE BACNET + ADD BACNET_CONFIG + WITH IP "127.0.0.1" + WITH PORT 47808 + WITH DEVICE_ID 1234 + WITH DIRECT_IP true + ADD MAPPING RoomSensors + WITH SOURCE_TOPIC "bacnet/bms" + WITH EVERY 1 SECONDS + ADD TAG "RoomTemp" + WITH ADDRESS "AI:0" + WITH DATA_TYPE "FLOAT" + WITH UNIT "degC" + ADD TAG "Setpoint" + WITH ADDRESS "AV:0" + WITH DATA_TYPE "FLOAT" + WITH WRITABLE true + WITH DESTINATION_TOPIC "bacnet/bms/setpoint/write" +``` + +### Siemens S7 +``` +DEFINE ROUTE S7PLC WITH TYPE SIEMENS_S7 + ADD S7_CONFIG + WITH IP "192.168.1.50" + WITH CPU_TYPE "S71500" + WITH RACK 0 + WITH SLOT 1 + ADD MAPPING ReadDB + WITH SOURCE_TOPIC "s7/read" + WITH EVERY 500 MILLISECONDS + ADD TAG "Speed" + WITH ADDRESS "DB1.DBD0" + WITH DATA_TYPE "REAL" +``` + +### OPC UA +``` +DEFINE ROUTE OpcServer WITH TYPE OPCUA + ADD OPCUA_CONFIG + WITH ENDPOINT_URL "opc.tcp://192.168.1.200:4840" + WITH USE_SECURITY false + ADD MAPPING ReadNodes + WITH SOURCE_TOPIC "opc/read" + WITH EVERY 1 SECONDS + ADD TAG "Temperature" + WITH ADDRESS "ns=2;s=Channel1.Device1.Tag1" + WITH DATA_TYPE "DOUBLE" +``` + +### 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** +(`/` by default) sets the served value. +``` +DEFINE ROUTE PlantModbus WITH TYPE MODBUS_SERVER + ADD MODBUS_SERVER_CONFIG + WITH PORT 502 + WITH UNIT_ID 1 + ADD MAPPING Registers + WITH SOURCE_TOPIC "plant/modbus" + ADD TAG "Setpoint" + WITH ADDRESS "0" + WITH ADDRESS_TYPE "HOLDING_REGISTER" + WITH DATA_TYPE "FLOAT" + WITH WRITABLE "true" + WITH DESTINATION_TOPIC "plant/modbus/setpoint/written" +``` +On MODBUS_SERVER every TAG needs ADDRESS and ADDRESS_TYPE, and a master's write to a WRITABLE HOLDING_REGISTER/COIL is +published to **DESTINATION_TOPIC**. On OPCUA_SERVER (OPCUA_SERVER_CONFIG: SERVER_PORT default 4840, ALLOW_ANONYMOUS +default true) a client's write to a WRITABLE node is published back to the tag's **SOURCE_TOPIC**. Call +`get_route_template` for the full setting list of either. + +## REST API Connector + +``` +DEFINE ROUTE WeatherAPI WITH TYPE REST_API + ADD REST_API_CONFIG + WITH BASE_ADDRESS "https://api.weather.com" + ADD EVENT GetForecast + WITH SOURCE_TOPIC "weather/request" + WITH DESTINATION_TOPIC "weather/forecast" + WITH METHOD "GET" + WITH ENDPOINT "/v1/forecast?city={payload}" +``` + +## REST API Server Connector + +``` +DEFINE ROUTE MyAPI WITH TYPE REST_API + ADD REST_API_CONFIG + WITH ENABLE_SERVER true + WITH SERVER_PORT 8080 + ADD EVENT GetStatus + WITH METHOD "GET" + WITH ENDPOINT "/api/status" + WITH DESTINATION_TOPIC "api/status/request/{session}" + WITH REPLY_TOPIC "api/status/reply/{session}" + WITH REPLY_TIMEOUT 10 +``` + +Server mode needs **WITH ENABLE_SERVER true**; without it the connector is an HTTP client and requires BASE_ADDRESS. +Each event with METHOD + ENDPOINT is an HTTP endpoint: the request body is published to **DESTINATION_TOPIC**. With +**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. + +## AI Connectors + +### LLM Connector +``` +DEFINE ROUTE LocalLLM WITH TYPE LLM + ADD LLM_CONFIG + WITH BASE_URL "http://localhost:11434" + WITH MODEL "llama3.2" + WITH TEMPERATURE 0.7 +``` + +### MCP Client Connector — stdio transport + +IMPORTANT: SERVER_ARGUMENTS is COMMA-SEPARATED — each argument is a separate comma-delimited token. + +``` +DEFINE ROUTE ToolServer WITH TYPE MCP + ADD MCP_CONFIG + WITH SERVER_COMMAND "npx" + WITH SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-filesystem, /data" + WITH CLIENT_NAME "CorefluxBroker" +``` + +To pass environment variables to the server process, add one `WITH SERVER_ENV "NAME" ` line per variable +(the value may be `GET SECRET "..."` or `GET ENV "..."`). + +### MCP Client Connector — Docker Desktop gateway (manages all servers in a profile) +``` +DEFINE ROUTE DockerGateway WITH TYPE MCP + ADD MCP_CONFIG + WITH SERVER_COMMAND "docker" + WITH SERVER_ARGUMENTS "mcp, gateway, run, --profile, default" + WITH CLIENT_NAME "CorefluxBroker" +``` + +### MCP Client Connector — DesktopCommander (terminal access: docker ps, shell commands, file ops) +Runs on the host via npx. The agent can execute any shell command including docker ps, +docker run, docker stop, etc. Requires Node.js. Auto-updates on first use each session. +``` +DEFINE ROUTE DesktopCommander WITH TYPE MCP + ADD MCP_CONFIG + WITH SERVER_COMMAND "npx" + WITH SERVER_ARGUMENTS "-y, @wonderwhy-er/desktop-commander@latest" + WITH CLIENT_NAME "CorefluxBroker" +``` + +### MCP Client Connector — Docker container/image control via Docker MCP gateway +Uses Docker Desktop's built-in `docker` catalog server. No Node.js required. +``` +DEFINE ROUTE DockerControl WITH TYPE MCP + ADD MCP_CONFIG + WITH SERVER_COMMAND "docker" + WITH SERVER_ARGUMENTS "mcp, gateway, run, --servers, docker" + WITH CLIENT_NAME "CorefluxBroker" +``` + +### MCP Client Connector — HTTP/SSE (remote server, no SERVER_ARGUMENTS needed) +``` +DEFINE ROUTE RemoteMCP WITH TYPE MCP + ADD MCP_CONFIG + WITH SERVER_URL "https://mcp.example.com/mcp" + WITH CLIENT_NAME "CorefluxBroker" +``` + +### Agents (DEFINE AGENT, not a connector type) +An agent is its own entity, deployed with `-addAgent`, and runs on a `TYPE LLM` connector. There is no +`WITH TYPE AGENT` / `AGENT_CONFIG` (removed). Load `lot-agents` before writing one. + +## STORE IN targets + +`STORE IN ""` in a model or action reaches only these connector types: POSTGRESQL, MYSQL, MARIADB, +SQLSERVER/MSSQL, MONGODB, CRATEDB, SNOWFLAKE, OPENSEARCH, FILE_STORAGE and REST_API. Any other type logs +`Unsupported route type for storage` and drops the row. + +## Managing and monitoring connectors + +- Deploying a connector that already exists (`broker.add_route`) updates it in place; `broker.remove_route` stops it and removes its events and mappings. +- A `DISABLE true` line inside the `DEFINE ROUTE` block keeps the connector defined and listed but never starts it (`-disableConnector` / `-enableConnector` add and remove the line). +- `$SYS/Coreflux/Routes/` holds the connector's retained LoT definition; `$SYS/Coreflux/Routes//status` is published periodically (not retained) with its health and connection JSON. +- MQTT_BRIDGE, FEDERATION, LLM, MCP, VIDEO_INPUT, AUDIO_INPUT and VIDEO_OUTPUT need a Growth or Enterprise license. On a Community broker they are refused, and a saved one is skipped at startup with a warning in the log. +- BARCODE runs only on Windows; on other platforms the connector is skipped with a warning. + +## 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) +- **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) +- An event with no SOURCE_TOPIC and no EVERY never runs; a scheduled (EVERY) event without DESTINATION_TOPIC fails to load +- Forgetting quotes around topic patterns and query strings +- Events use {payload} and {topic.N} for dynamic values — N is 1-based +- GET ENV / GET SECRET must have quotes around the variable name +- An unknown TAG DATA_TYPE is not an error: it silently becomes INT16. Use a listed type (BOOL, INT16, UINT16, INT32, UINT32, INT64, FLOAT/REAL, DOUBLE/LREAL, STRING, ...) +- OPC UA client: there is no SECURITY_MODE setting (it is ignored). Use USE_SECURITY, SECURITY_POLICY and MESSAGE_SECURITY +- MCP connector: use SERVER_COMMAND and SERVER_ARGUMENTS (NOT "COMMAND" and "ARGS" — those are invalid) +- MCP connector: SERVER_ARGUMENTS is COMMA-SEPARATED — each CLI argument is a separate comma-delimited token + WRONG: WITH SERVER_ARGUMENTS "mcp gateway run --profile default" + RIGHT: WITH SERVER_ARGUMENTS "mcp, gateway, run, --profile, default" +- MCP connector: use SERVER_URL (NOT "URL") for HTTP/SSE transport; no SERVER_ARGUMENTS needed +- MCP connector via Docker gateway: SERVER_COMMAND is "docker", SERVER_ARGUMENTS is "mcp, gateway, run, --profile, " +- MCP connector via Docker container control: SERVER_COMMAND is "docker", SERVER_ARGUMENTS is "mcp, gateway, run, --servers, docker" (uses Docker Desktop gateway — no socket mount needed, works on Windows) diff --git a/plugins/coreflux/skills/lot-rules/SKILL.md b/plugins/coreflux/skills/lot-rules/SKILL.md new file mode 100644 index 0000000..aa31433 --- /dev/null +++ b/plugins/coreflux/skills/lot-rules/SKILL.md @@ -0,0 +1,245 @@ +--- +name: lot-rules +description: How to write LOT permission rules: ALLOW/DENY, topic patterns, user/group conditions, priority-based evaluation, and operation scopes. +--- + +# LOT Rules — Complete Reference + +## Basic Structure + +``` +DEFINE RULE WITH PRIORITY FOR [TO TOPIC ""] + IF THEN + ALLOW + ELSE + DENY +``` + +`TO TOPIC` is required for Publish, Subscribe, PublishSys and SubscribeSys, and is a parse +error on every other scope. Rule names are unquoted (`DEFINE RULE "X"` is LOT1001). + +Rules control MQTT topic access. **Lower priority numbers win** — priority 100 is stronger than +priority 1000, the same way BACnet write priority and ISA-18.2 alarm priority work. + +| Priority | Band | +|---|---| +| `0`–`99` | Reserved for locked system rules — rejected if you try to use it | +| `100`–`999` | Specific allow/deny rules (typical) | +| `1000`–`999999` | Coarser fallback rules | +| `1000000` | The shipped permissive catch-alls (`AllowPublishTopic` / `AllowSubscribeTopic` / `AllowConnect`) — weakest; above it is rejected | + +## Operation Scopes + +| Scope | Controls | +|-------|----------| +| Connect | Whether a client may connect at all (no TO TOPIC clause) | +| Subscribe | MQTT subscribe permissions | +| Publish | MQTT publish permissions | +| SubscribeSys | Access to $SYS topics | +| PublishSys | Publishing to $SYS topics | +| ActionManagementCreation | Creating/modifying actions | +| ModelManagementCreation | Creating/modifying models | +| RouteManagementCreation | Creating/modifying routes | +| RuleManagementCreation | Creating/modifying rules | +| UserManagementCreation | Creating/modifying users | +| SystemConfiguration | System-level configuration | +| CommandCall | Executing broker commands | +| ActionManagementRun | Running an action on demand | +| ActionManagementRemove / ModelManagementRemove / RouteManagementRemove / RuleManagementRemove | Removing entities | +| AgentManagementCreation / AgentManagementRemove / ThingManagementCreation / ThingManagementRemove | Agents and things | +| UserManagementUpdate / UserManagementPasswordChange / UserManagementRemove | User changes | +| LogManagementCreation / LogManagementUpdate / LogManagementRemove / LogManagementRead | Log traces | +| ShellCommand / McpTokenManagement | Shell commands, MCP tokens | + +`ConnectorManagementCreation` / `ConnectorManagementRemove` are accepted aliases for the Route scopes. + +**Which scopes a user rule can change.** Locked built-in rules sit at priority 10 (1 for some +`$SYS` carve-outs), and a user rule can't go below 100, so the locked rule always decides. A user +rule has effect only on: Publish, Subscribe, Connect, ModelManagementCreation, +ActionManagementRun (their built-ins sit at 1000000), and PublishSys on `$SYS` topics no +built-in covers. A user rule for SystemConfiguration, CommandCall, any `*Remove` scope, +Route/Rule/User/Action/Agent/Thing creation, or SubscribeSys is accepted but never consulted. + +## Conditions + +### User identity +``` +IF USER IS "admin" THEN + ALLOW +``` + +### User permissions +USER HAS reads a boolean flag on the user. Only three exist: `AllowedSystemConfiguration`, +`AllowedUserManagement`, `AllowedLogManagement`. Any other name is silently false; the +validator does not flag it. +``` +IF USER HAS "AllowedSystemConfiguration" THEN + ALLOW +``` + +### Group membership +``` +IF USER IN GROUP "operators" THEN + ALLOW +``` + +### Combined conditions +``` +IF USER IS "admin" OR USER IS "operator" THEN + ALLOW +ELSE + DENY +``` + +### With AND +``` +IF USER IN GROUP "monitoring" AND USER IS "monitor" THEN + ALLOW +``` + +### Client id, endpoint (available in every scope; the main use is Connect) +``` +IF CLIENTID IS "gateway-1" THEN + ALLOW +``` + +### Regex matching — MATCHES REGEX +The REGEX keyword is REQUIRED. Plain MATCHES is a string equality test, not a regex. +Anchor patterns with ^ and $, or they match substrings. Negate with NOT MATCHES REGEX. +``` +IF CLIENTID MATCHES REGEX "^gpay[0-9]{15}$" THEN + ALLOW +ELSE + DENY +``` + +### Retained-topic allow-lists — TOPIC EXISTS +True only when the topic holds an MQTT RETAINED message, so the answer does not depend on when the +device last published. The operand is an expression, so build the topic from CLIENTID. Write +allow-list topics with a retained MQTT publish. KEEP TOPIC stores a value for GET TOPIC without +broadcasting; PUBLISH TOPIC overwrites that value and notifies subscribers. TOPIC EXISTS does not +see KEEP. Retained state survives a broker restart only when durability is enabled (off by default). +``` +IF TOPIC EXISTS "coreflux/devices/" + CLIENTID + "/allowed" THEN + ALLOW +ELSE + DENY +``` +Bare TOPIC EXISTS ignores the payload, so a device whose flag says "false" is still admitted. +To test the value, compare it — these three are all value tests, and the first two are the same: +``` +IF TOPIC EXISTS "coreflux/devices/" + CLIENTID + "/allowed" IS "true" THEN +IF GET TOPIC "coreflux/devices/" + CLIENTID + "/allowed" IS "true" THEN +IF GET TOPIC "coreflux/devices/" + CLIENTID + "/allowed" THEN +``` +A bare GET TOPIC condition is true for "true"/"1"/"yes"/"on" (any case) and non-zero +numbers; a missing topic or empty payload is false. GET TOPIC lookup order (actions and +rules): in-flight, trigger payload, live cache (KEEP or PUBLISH; last write wins), then +MQTT retain as a restart fallback. Use TOPIC EXISTS when the grant must be an MQTT +retained message. + +## Topic Patterns + +Use MQTT wildcards: +- `+` matches one level: `sensors/+/data` matches `sensors/temp/data` +- `#` matches any remaining levels: `sensors/#` matches `sensors/temp/data/raw` + +``` +DEFINE RULE SensorAccess WITH PRIORITY 200 FOR Subscribe TO TOPIC "sensors/#" + IF USER IN GROUP "sensor-readers" THEN + ALLOW + ELSE + DENY +``` + +## Complete Examples + +### Admin-only model deployment +``` +DEFINE RULE AdminOnlyModels WITH PRIORITY 100 FOR ModelManagementCreation + IF USER IS "admin" THEN + ALLOW + ELSE + DENY +``` + +### Restrict publishing to alerts +``` +DEFINE RULE AlertPublish WITH PRIORITY 100 FOR Publish TO TOPIC "alerts/#" + IF USER IS "admin" OR USER IS "supervisor" THEN + ALLOW + ELSE + DENY +``` + +### Allow all users to subscribe to public topics +``` +DEFINE RULE PublicRead WITH PRIORITY 500 FOR Subscribe TO TOPIC "public/#" + IF USER IS "admin" OR USER IN GROUP "viewers" THEN + ALLOW + ELSE + DENY +``` + +### Restrict on-demand action runs +``` +DEFINE RULE ActionRunners WITH PRIORITY 100 FOR ActionManagementRun + IF USER IS "admin" OR USER IN GROUP "operators" THEN + ALLOW + ELSE + DENY +``` + +### Admit only provisioned IMEI devices +Devices connect with their IMEI as the client id (prefixed "gpay"), and a provisioning +system retains one topic per approved device. Both tests must pass: the right client-id +shape AND a provisioned topic for that specific device. +``` +DEFINE RULE ImeiAdmission WITH PRIORITY 100 FOR Connect + IF CLIENTID MATCHES REGEX "^gpay[0-9]{15}$" AND TOPIC EXISTS "coreflux/devices/" + CLIENTID + "/allowed" THEN + ALLOW + ELSE + DENY +``` + +### Restrict a device to its own subtree +`TOPIC POSITION N` (1-based) reads a level of the requested topic, so position 3 of +`coreflux/devices//...` must equal the client id. +``` +DEFINE RULE DeviceOwnTree WITH PRIORITY 100 FOR Subscribe TO TOPIC "coreflux/devices/#" + IF CLIENTID MATCHES REGEX "^gpay[0-9]{15}$" AND CLIENTID IS TOPIC POSITION 3 THEN + ALLOW + ELSE + DENY +``` + +## Priority Evaluation + +Only the rules matching the operation (and topic) at the LOWEST priority number decide +(100 beats 1000). Among those, a DENY beats an ALLOW. If NO rule matches, the engine denies. +Publish/Subscribe catch-alls and AllowConnect sit at 1000000. Restrict Publish, +Subscribe, or Connect with any user-band rule (100–999999). Connect has no topic, so a +user Connect rule overlays the seed for every connection. Priorities 0–99 are reserved +and -addRule rejects them. Restore the three shipped seeds with -restoreRules (requires root +or AllowedSystemConfiguration). + +## Common Mistakes +- Missing WITH PRIORITY — every rule must have a priority number +- Missing FOR — the operation scope is required +- TO TOPIC is required for Publish/Subscribe/PublishSys/SubscribeSys and rejected on every other scope +- A bare ALLOW or DENY body is valid. An IF without ELSE does the opposite when the condition + is false (IF … THEN ALLOW denies everyone else at that priority) +- -addRule refuses a name that already exists — remove the rule first to change it +- USER HAS with a flag that does not exist (e.g. "AllowedSubscribe") is always false +- A user rule on a scope a locked rule covers (SystemConfiguration, CommandCall, SubscribeSys, …) + is accepted but never consulted +- Lower number = stronger (priority 100 beats priority 1000). 0–99 is reserved. +- Writing MATCHES without REGEX — that is a string equality test, not a regex +- Unanchored regex — "gpay[0-9]{15}" also matches "evil-gpay123456789012345"; use ^...$ +- Expecting TOPIC EXISTS to see a non-retained publish — it only sees retained messages +- Expecting bare TOPIC EXISTS to check the payload — add IS "true" (or use GET TOPIC) when + the value matters, or a device flagged "false" is admitted +- A Connect DENY locks real clients out of the broker. Only root is exempt (anti-lockout + backstop), so always show the rule to the user for approval before deploying it. +- A Connect rule at 100–999999 outranks AllowConnect (priority 1000000). Write a complete + IF/THEN/ELSE policy — Connect has no topic, so the winning rule applies to every connection. diff --git a/plugins/coreflux/skills/lot-themes/SKILL.md b/plugins/coreflux/skills/lot-themes/SKILL.md new file mode 100644 index 0000000..fd299a6 --- /dev/null +++ b/plugins/coreflux/skills/lot-themes/SKILL.md @@ -0,0 +1,188 @@ +--- +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. +--- + +# LoTV Theme Authoring — Design Token System + +ALWAYS call broker.load_skill("lot-themes") before broker.add_theme. + +--- + +## Mandatory Workflow + +``` +broker.load_skill("lot-themes") ← load this skill FIRST +broker.add_theme() ← compile + publish themeUpdate JSON +``` + +`add_theme` (command `-addTheme`) is a write: it is refused in an insight-mode task. +It is an MCP tool; a `DEFINE AGENT` cannot deploy a theme, because `create_lot` +has no `theme` kind. + +--- + +## DEFINE THEME — Basic Syntax + +```lot +DEFINE THEME "ThemeName" + // Brand colors + SET PRIMARY WITH "#f97316" + SET SECONDARY WITH "#fb923c" + SET ACCENT WITH "#0ea5e9" + + // Status colors + SET SUCCESS WITH "#22c55e" + SET WARNING WITH "#f59e0b" + SET CRITICAL WITH "#ef4444" + + // Surfaces + SET BACKGROUND WITH "#0a0a0f" + SET SURFACE WITH "#111118" + SET FOREGROUND WITH "#fafafa" + SET FOREGROUND_MUTED WITH "#a1a1aa" + + // Typography + SET FONT_FAMILY WITH "'Inter', sans-serif" + SET FONT_FAMILY_MONO WITH "'JetBrains Mono', monospace" +``` + +Token names → CSS custom properties automatically: +`PRIMARY` → `--primary`, `FONT_SIZE_SM` → `--font-size-sm`, `SURFACE_ELEVATED` → `--surface-elevated` +In the `tokens` map of the published JSON the same names are camelCase: `FONT_SIZE_SM` → `fontSizeSm`. + +--- + +## Key Token Reference + +### Colors +`PRIMARY` · `SECONDARY` · `ACCENT` · `SUCCESS` · `WARNING` · `CRITICAL` · `INFO` +`RUNNING` · `STOPPED` · `FAULT` · `MAINTENANCE` · `STANDBY` · `DISABLED` +`BACKGROUND` · `SURFACE` · `SURFACE_ELEVATED` · `CARD` · `BORDER` · `DIVIDER` +`FOREGROUND` · `FOREGROUND_MUTED` · `FOREGROUND_SUBTLE` + +### Typography +`FONT_FAMILY` · `FONT_FAMILY_DISPLAY` · `FONT_FAMILY_MONO` +`FONT_SIZE_XS/SM/BASE/LG/XL/2XL/3XL/4XL/5XL` +`FONT_WEIGHT_LIGHT/NORMAL/MEDIUM/SEMIBOLD/BOLD` + +### Spacing & Radius +`SPACING_0/1/2/3/4/5/6/8/10/12/16` · `RADIUS_SM/MD/LG/XL/2XL/3XL/FULL` + +### Effects +`SHADOW_SM/MD/LG/XL/2XL/INNER` · `GLOW_PRIMARY/SUCCESS/WARNING/CRITICAL` +`BLUR_SM/MD/LG/XL` · `TRANSITION_INSTANT/FAST/NORMAL/SLOW/SLOWER` + +--- + +## Theme Inheritance — EXTENDS + +```lot +DEFINE THEME "CorefluxBase" + SET PRIMARY WITH "#f97316" + SET BACKGROUND WITH "#0a0a0f" + SET FOREGROUND WITH "#fafafa" + +DEFINE THEME "CorefluxBlue" EXTENDS "CorefluxBase" + SET PRIMARY WITH "#3b82f6" // override only this token + SET SECONDARY WITH "#60a5fa" // all other tokens inherited from CorefluxBase +``` + +The parent theme must be deployed first, or come **before** the child in the same call. +Inheritance is resolved when the child is published: a parent that arrives later +(even later in the same call) does not reach the child until the child is redeployed. + +--- + +## Light/Dark Mode — WHEN MODE + +```lot +DEFINE THEME "Adaptive" + SET MODE "auto" // auto | light | dark + SET SYSTEM_PREFERENCE true // follow OS light/dark preference + SET PRIMARY WITH "#f97316" // same in both modes + + WHEN MODE "light" + SET BACKGROUND WITH "#ffffff" + SET SURFACE WITH "#f4f4f5" + SET FOREGROUND WITH "#18181b" + + WHEN MODE "dark" + SET BACKGROUND WITH "#0a0a0f" + SET SURFACE WITH "#111118" + SET FOREGROUND WITH "#fafafa" +``` + +Time-based switching: +```lot + SET TIME_BASED true + DARK_START "18:00" + DARK_END "06:00" + TIMEZONE "local" +``` + +--- + +## Component-Level Overrides — DEFINE THEME_VARIANT + +```lot +DEFINE THEME_VARIANT "gauge:industrial" + SET TRACK_COLOR WITH "var(--surface)" + SET FILL_GRADIENT WITH "linear-gradient(135deg, var(--primary), var(--secondary))" + SET GLOW_ON_THRESHOLD WITH true + +DEFINE THEME_VARIANT "button:scada" + SET FONT_WEIGHT WITH "var(--font-weight-semibold)" + SET BORDER_RADIUS WITH "var(--radius-md)" + SET TRANSITION WITH "var(--transition-fast)" +``` + +Variants are published to `$SYS/Coreflux/VoT/ThemeVariants/{component}/{variant}`. +Multiple DEFINE blocks can be sent in a single `broker.add_theme` call. + +--- + +## What the Broker Publishes + +After `broker.add_theme`, the broker publishes to `$SYS/Coreflux/VoT/Themes/{ThemeName}`: + +```json +{ + "themeUpdate": { + "themeId": "CorefluxBlue", + "inherits": "CorefluxBase", + "tokens": { "primary": "#3b82f6", "background": "#0a0a0f" }, + "cssVariables": { "--primary": "#3b82f6", "--background": "#0a0a0f" }, + "modes": { + "light": { "tokens": {...}, "cssVariables": {...} }, + "dark": { "tokens": {...}, "cssVariables": {...} } + }, + "modeConfig": { "mode": "auto", "systemPreference": true } + } +} +``` + +--- + +## Common Mistakes + +```lot +-- WITH is optional and a bare value is read up to the first space, so these all parse: +SET PRIMARY "#f97316" +SET PRIMARY WITH #f97316 +SET PRIMARY WITH "#f97316" ← canonical: always WITH and a quoted value + +-- Unquoted value containing spaces → truncated at the first space +SET FONT_FAMILY WITH 'Inter', sans-serif ← WRONG: value becomes 'Inter', +SET FONT_FAMILY WITH "'Inter', sans-serif" ← RIGHT + +-- EXTENDS before parent is deployed +broker.add_theme("DEFINE THEME \"Child\" EXTENDS \"Parent\" ...") +// Parent not yet deployed → the child carries "inherits" but none of the parent's tokens +// Fix: deploy the parent first, or put its DEFINE THEME block before the child in the same call + +-- Deploying without loading the skill +broker.add_theme(...) ← WRONG +broker.load_skill("lot-themes") +broker.add_theme(...) ← RIGHT +``` diff --git a/plugins/coreflux/skills/lot-things/SKILL.md b/plugins/coreflux/skills/lot-things/SKILL.md new file mode 100644 index 0000000..88b9226 --- /dev/null +++ b/plugins/coreflux/skills/lot-things/SKILL.md @@ -0,0 +1,176 @@ +--- +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. +--- + +# LOT Things — DEFINE THING + +A Thing groups the connectors, models, agents, actions, rules and panels of one asset (a pump, +a line, a site) under one name. A **template** describes the asset once; a **root** deploys it. +The broker expands each root into ordinary `DEFINE` declarations, its **children**, and keeps +owning them. + +**You cannot deploy Things from inside the broker.** `create_lot` has no `thing` target, and +`-addThing` / `-removeThing` run only from the CLI, over MQTT or through MCP. You can read them: +`read_lot` with target `thing` lists every Thing. Use this skill to explain a Thing, review one, +or draft one for a person to deploy. + +## CRITICAL SYNTAX + +- A clause is a standalone declaration with `DEFINE` replaced by `WITH`, indented one level + (4 spaces) under `DEFINE THING`. Every kind keeps its full syntax. +- An action clause's trigger (`ON TOPIC … DO`), `INPUT`, `DO` and `RETURN` sit at the **same + column as its `WITH ACTION` line**, exactly as under a standalone `DEFINE ACTION`. +- `{{name}}` is an expansion-time placeholder. Single-brace `{x}` is runtime (action variables, + `{payload}`, `{topic.2}`) and is never substituted. +- `OF` must name a `DEFINE THING TEMPLATE`. Naming a root, an unknown Thing or a cycle is an error. +- Names match `[A-Za-z_][A-Za-z0-9_]*`: no spaces, `-` or `.`. Placeholders are not allowed in names. + +## Minimal Thing + +``` +DEFINE THING TEMPLATE TempSensor + WITH PARAM limit 80 + WITH MODEL Reading WITH TOPIC "{{path}}/reading" + ADD DOUBLE "temperature" WITH TOPIC "{{path}}/temp" AS TRIGGER + ADD STRING "ts" WITH TIMESTAMP "ISO" + WITH ACTION Overheat + ON TOPIC "{{path}}/temp" DO + SET "temp" WITH PAYLOAD AS DOUBLE + IF {temp} > {{limit}} THEN + PUBLISH TOPIC "{{path}}/alarm" WITH "overheat " + {temp} + +DEFINE THING Oven + WITH THING inlet OF TempSensor + WITH THING outlet OF TempSensor + WITH PARAM limit 120 +``` + +`TempSensor` deploys nothing. `Oven` deploys four children: models `Oven_inlet_Reading` and +`Oven_outlet_Reading` (topics `Oven/inlet/reading`, `Oven/outlet/reading`) and actions +`Oven_inlet_Overheat` (alarms above 80) and `Oven_outlet_Overheat` (alarms above 120). + +## Declarations and clauses + +| Line | Meaning | +|---|---| +| `DEFINE THING TEMPLATE ` | Template. Stored, never deployed by itself | +| `DEFINE THING ` | Root. Deploys its whole instance tree | +| `DEFINE THING OF