CLI version and updates
This guide is released with xgg v3.1.0.xgg update --check Check only,xgg update check and upgrade confirmed npm global installations; neither requires Mi Home or gateway authentication. After the official npm fails, try npmmirror; you can use --registry <https-url> or XGG_UPDATE_REGISTRY to specify a trusted source, with command-line options taking priority. Mirrors may be delayed or unreachable; you must retain the source and fallback boundaries in the results, and must not state that offline or mirror no-new-version means officially confirmed latest.
Limited foreground read-only commands automatically check after command-line parsing and before business queries; after a successful check, at least 24 hours apart, and after a failure, at least 1 hour.XGG_AUTO_UPDATE=0 Disable automatic checks and upgrades; explicit update is still available. daemon, login/QR scan, logout, write operations, raw api, continuous watch/follow, help/version, and CI do not trigger. After an upgrade, this query is executed immediately by the new CLI; the old CLI does not execute business actions first, and the new process skips duplicate updates, so the query is executed only once. Prompts are written only to stderr; business stdout/exit code come from the CLI that actually executes the query; update failures such as being offline continue the original query. Do not proactively logout/relogin for upgrades; the existing daemon maintains the session, and Agent code is updated at the next normal login.
Source checkouts, project-local dependencies, npx caches, pnpm links, or installations that cannot be confirmed are not automatically overwritten; handle them according to the returned instructions using the original installation method, and do not use sudo or another prefix to disguise the original entry point as upgraded. First verify the actual xgg --version. The complete Skill in the package is updated with the upgrade; standalone copies in the Agent global directory must still be explicitly synchronized and verified; when GitHub is unreachable, copy the entire directory from the installed CLI's skills/xgg-rule-authoring/ , retain existing customized modifications, and do not copy only SKILL.md or assume that npm has completed registration.
Cloud task routing
For QR scan login, direct device read/write/observe, and bidirectional cloud-gateway joint debugging, first read references/cloud-workflows.md. Prefer Mi Home App QR scan cloud authorization, then autonomously obtain the hub six-digit code; existing authorization and live daemon are both reused; QR scan continuation uses the returned nextCommand.argv, and after gateway bootstrapping, retain the returned baseUrl and the selected session file for subsequent commands. When the hosting device, DID, or address is unknown, read references/gateway-discovery.md, covering the five candidate categories of standalone hub, router, screen, speaker, and smart storage; first locate, then use the same command to discover the address and obtain the code. The hub is not required to have built-in Bluetooth/Mesh gateway, and the model list does not prove that both RPCs have been actually tested. For cloud-only operations, there is no need to read the rule card directory. For pre-write, post-write, and recovery verification, use get/watch --source device; auto/cache cannot masquerade as real-time status; when direct device reading fails, cache must not be treated as proof of recovery. Rule tasks continue to follow the complete compilation and acceptance contract below, and gateway spec/log proof must not be omitted just because the cloud can control it.
Goals
Compile the user's natural language into a Xiaomi hub gateway geek editiondirected rule graph, rather than merely assembling a string of commands that return ok . Completion means:
- event, state, time, internal state, reset/stop, and side effects are correctly separated;
- accurate cards, pins, and parameters are selected, and device enumeration comes from the target spec;
- writes remain safe, rollback-capable, and pass schema, spec, topology, and truth-aware reachability;
- if the user authorizes execution, prove behavior with logs, traces, variable readback, or device results.
The rule JSON is not LLM common knowledge. Do not guess wire from field names, ordinary Mijia automation experience, or any historical or third-party JSON fragments that have not been verified against the current xgg.
Evidence Boundaries
Always distinguish three layers:
- Current xgg static contract: CLI flags, typed synthesis, schema, node/pin projector, static lint/reachability, export/import, and tests jointly prove the currently modeled structure; they do not prove firmware executor behavior.
- Target gateway current metadata: live inventory and
device specprove a specific device's property/event/action, access, push, and value range. - Target gateway runtime evidence: logs, traces, variables, or device readback prove firmware runtime timing, state persistence, action success/failure, and log retention.
Executor behavior not proven by the current xgg's static schema, validator, and projector must be written as "card intent/to be verified on real hardware" and must not masquerade as a real runtime conclusion. This applies especially to counter's exact threshold tick, loop's first tick, delay concurrency, statusLast reset, eventSequence concurrency, register/modeSwitch lifecycle, and action output success timing.
Required Reading Routing
The first time you design or rewrite a rule in a session, first read:
- references/graph-model.md: natural language→E/S graph, wire, truth-aware reachability, control cards, and runtime probes.
- references/node-catalog.md: complete pins for the 25 execution cards + nop, per-type flags/defaults, canonical JSON, and prohibited non-canonical writing styles.
Then read depending on the task:
- For any device property/event/action: read references/device-semantics.md。
- For sequence/condition/hold/counter/limit/register/loop/modeSwitch/dynamic action: read references/recipes.md。
- For cloud login, device get/set/watch, or gateway integration testing: read references/cloud-workflows.md。
- For unknown hub device/DID/IP, candidates that cannot be located, or when a manual login fallback is needed: read references/gateway-discovery.md。
- For real gateway writes, variables/expressions, logs/traces, backup, or restore: read references/operations.md。
- For first-time configuration of a new home, 24-hour to one-week behavior observation, area semantic revisit, or profile reuse: read references/habit-learning.md。
These references are all linked directly from this entry point; do not read only the SKILL summary and then guess the details.
If the current project does not yet have a usable home profile, before directly designing the first business automation, first explain the optional habit-learning process to the user. After the user agrees, first do a privacy and coverage plan, then establish a unified observation graph with no physical output; the same learning session must not be pre-split by number of sources, room, priority, A/B zones, or untested capacity estimates. By default, zone presence sensors retain the overall state, all zone states, all notifiable overall and zone illuminance, zone events and parameters,people-num and the raw zone codes; do not collect only overall presence/absence. During the profile stage, then proactively ask the user to confirm in the Mijia App the actual locations corresponding to codes such as A-1、B-2、Zone-1 and others;people-num can only be treated as an instantaneous sensor estimate and cannot be used to infer the number of people in the household.
The standard CLI lifecycle for home learning is learn plan → start(disabled)→ start --enable --plan-id <reviewed-plan-id> → capture → status → finish →(如需澄清:clarify → 再次 finish)→ profile. The first start only creates and accepts a disabled single graph; the second start must, after explicit authorization, carry the reviewed plan ID, and must not skip it to capture directly, nor switch to a generic rule enable。capture --follow is the main path for a 24-hour to one-week recoverable journal; any new Agent session should first run learn status and resume according to its durable phase/next action.finish must be completed before disable and fsync the final capture; unexplained region codes will be transferred to clarification rather than generating a guessed profile; append clarify after correction, you must run finish again to rebuild the profile;profile only when the freshness determination allows reuse can it serve as evidence for subsequent rule thresholds and time periods. Command parameters and private file contracts are subject to references/habit-learning.md .
Natural language compilation process
1. First restate the determinable requirements
Before writing commands, list:
触发 event:谁在何时发出一次事件?
持续 state:触发瞬间哪些条件必须为真/假?
主动 query:是否要在 event 到来后读取设备/变量再分支?
时间关系:延迟、保持、有序窗口、循环、次数、轮换是哪一种?
内部状态:是否需要 latch/counter/持久变量?何时 reset/stop/初始化?
副作用:哪些设备写/action/变量写必须被 event 路径驱动?
运行状态:保持 disabled,还是获授权 enable 并实测?
If reset, crossing midnight, state after power loss/restart, the subsequent chain after an action failure, etc. would change the business result and the user has not specified it, point out the ambiguity; you may first construct a disabled draft, but must not arbitrarily choose high-risk runtime semantics.
When the diagram contains a device card,--spec-aware is a hard acceptance item before enabling regular business rules and after replay. Ordinary validate does not read the current MIoT spec/live device and cannot prove notify/read/write access, pushAvailable, native type/value range, action index, or whether the output ref falls into the boolean/value-list literal-only path. Errors for regular rules must be zero; warnings must be audited one by one, explained, and explicitly accepted. The only case where a spec-aware error is allowed is the explicitly authorized isolated no-push runtime probe described below; it must still execute spec-aware and record that expected diagnostic.
2. Draw the node/pin plan
需求事实 | E/S | node.type/mode | source pin | consumer:input pin | 参数证据 | reset/stop
Core choices:
| Requirement | Choice |
|---|---|
| Physical/device event | deviceInput event |
| Continuous property state | deviceInput property; when the device does not push, prefer changing to event→deviceGet |
| Actively query on trigger and branch on true/false | deviceGet / varGet; output=satisfied,output2=not satisfied |
| Branch by state on trigger | condition: event→trigger,state→condition |
| Merge events / states | signalOr / `logicOr |
| Delay / hold / ordered two events / loop | delay / statusLast / eventSequence / loop |
| First N times / cumulative threshold / latch / rotation | onlyNTimes / counter / register / modeSwitch |
| Capture device value | push/event→deviceInputSetVar; triggered query→deviceGetSetVar |
| Persistent computation or text | varSetNumber / varSetString |
| Timed event / time window state | alarmClock / timeRange |
Do not treat timeRange as alarmClock, do not treat counter as onlyNTimes, do not connect state directly to an event input, and do not pile multiple lines onto the same input.
3. Check current facts, do not guess parameters
xgg status
xgg device list --pretty
xgg device spec <did> --pretty
xgg rule list --pretty
xgg rule view <rid> --pretty
xgg rule node add --help
The default machine spec is in .spec.services. Record short-name, SIID/PIID/EIID/AIID, format/access, value-list/range, event arguments, action.in/out. Chinese labels are used for explanation; the wire still uses spec value.
For any device card, spec first; for the same short-name across services, use --device-siid. property source/capture requires notify, query requires read, property output requires write; the two types of push source also require the target device pushAvailable=true. value-list is a closed set, range is [min,max,step]。action --params must exactly cover action.in corresponding short-name, and preserve the native JSON type.
The actual types of gateway variables are only number|string. Online diagram writing, validate, and strict export will, for eachdiscoverable modeled reference path, check the actual type; opaque/future --cfg internal references cannot be proven by these gates, and the boundaries are described below.varSetString target must be string, but operand can combine number|string. boolean capture uses number + canonical dtype number (0/1). boolean or anything with value-list field (including []) device output is literal-only; dynamic boolean first branches by number 0/1, then writes literal false/true.
New typed nodes omit --id and generate a n + 32-bit hexadecimal; explicit IDs may only be nonempty ASCII alphanumeric [A-Za-z0-9]+, and cannot contain - _ . :, whitespace, or Unicode. Legacy graph IDs must be preserved faithfully: use --allow-legacy-idonly when replaying modeled typed nodes from an existing export; it does not apply to newly created, raw --cfg, opaque type, or IDs that are already canonical. The CLI cannot prove the provenance of non-canonical IDs, so "replay only, never create new" is also a safety contract that Agents must follow.
4. Author disabled first
xgg rule new --name "<规则名>"
xgg rule node add --rule-id <rid> --type <type> --id <stable-id> ...
xgg rule edge add --rule-id <rid> --from <source:pin> --to <target:pin>
xgg rule layout <rid>
Each card may only use the authoring flags allowed for that type/mode in the node catalog. Ignoring any business flag in a command is unacceptable; the CLI should reject irrelevant or mutually exclusive flags before session/RPC.
typed node-add omits --pos: XGG computes frontend-equivalent dimensions based on card content and edit mode/minimal mode; do not copy a uniform envelope to all cards.rule layout first fixes the width/height of already-modeled execution cards in the legacy graph, then lays them out with a 32px horizontal column gap.nop dimensions and position are fully preserved; cards that are unknown/opaque, whose MIoT spec cannot be parsed, or whose device/variable display list and semantic projection are temporarily unavailable preserve only width and height, and still participate in dataflow layout. Only when the online list succeeds and genuinely has no display records does a minimal device fall back to 190px wide, following gateway editor behavior; network/interface failures must not be mistaken for an empty list. Use --keep-sizes。
node/edge/layout/set writes preserve live enableby default; multi-step edits with rules already enabled may take effect immediately, so the final enable must not be treated as the effective boundary. Read back first; when isolation is needed, disable first as authorized, or construct offline and then perform a single atomic set. The default graph write path checks online whether discoverable modeled variable references exist and their actual types; opaque/future payloads are outside that proof.--no-var-check is only for explicit raw probe/repair and does not disable scope/schema/spec/enable gates.
--allow-no-push only allows this typed deviceInput / deviceInputSetVar property/event to run a probe against the target gateway; it does not persist, bypass notify/read/write, or prove that the device will emit. Online spec-aware preserves path-based no-push errors, and strict lint also preserves no-push warning/exit 1 for the same source, so the graph cannot pass itself off as passing the regular error gate. Only when the user explicitly authorizes validating a firmware extension may the spec-aware error be treated as the only allowed error in a dedicated temporary rule with no physical side effects, while explicitly accepting the same-source warning from strict lint: all other errors must be zero, all other warnings must still be audited item by item, logs/readback must be taken immediately after enable, then disable and preserve them for the user to check, deleting only when the user requests cleanup. strict export still rejects no-push; only permissive export warns and restores the transient flag; this exception cannot be used as production-rule acceptance.
Prefer typed shortcuts. Use raw only in the following scenarios:
- full fidelity for unmodeled future cards;
- extension fields that shortcuts cannot preserve;
- the need to write the entire graph atomically in one operation.
raw must come from the default JSON rule view/export, and cannot come from pretty or any JSON fragment that has not been validated by the current xgg. A complete node is {id,type,cfg,inputs,outputs,props}; the JSON wire stores only source outputs, endpoint uses node.pin。
The CLI's ordinary edge endpoint is node:pin. If the old node ID itself contains :, you must switch to the four lossless parameters --from-node-id/--from-pin/--to-node-id/--to-pin; the current export/import will automatically use this structured replay, and cannot rely on the first colon to guess the boundary.
Export/replay must first be written to disk for review. When npm has not yet synced, first build the current checkout, and use XGG_NODE_ENTRY=<绝对 dist/cli.js>(a separate NODE_BINcan be configured) to make the generation script execute the source code as a Bash argv array; do not stuff multi-word commands into XGG. replay first performs a read-only assertion that all discoverable modeled global dependencies exist and are of type number|string, then pre-checks the already captured local variables, and only after that is the first variable/rule write allowed; global is never created, modified, or renamed. If old JSON contains undeclared discoverable global references or ones without expectedType , it will fail closed before rendering. opaque --cfg will not be parsed; its internal local/global references are neither within the preflight proof nor safely rewritable; same-ID fidelity replay must be independently reviewed and separately proven, and clone will refuse. Preflight is not a cross-command transaction, and other writers must still be isolated during execution. For the full command and clone/same-ID order, see operations.md。
5. After each batch of modifications, pass four gates
xgg rule layout <rid>
xgg rule validate --rule-id <rid> --spec-aware
xgg rule lint --rule-id <rid> --strict
xgg rule view <rid>
- validate: nodes/schema, legal scope, online variable existence/actual type;
--spec-awarethen check access, push, native literal/value range, action input and output-ref canonical boundaries. - lint: edge, pin color, fan-in, required input, saved keys; strict additionally checks sink reachability.
- enable: finally hard-blocks unreachable sinks, and performs a focused fail-closed spec proof for persisted output refs, but does not replace the full spec-aware; success also does not prove operation.
- readback: prove the actually saved nodes, wires, and enable state.
rule lint The top-level ok:true only indicates that command execution has completed. You must check the exit code and summary.errors/warnings; exit 1=warning, 2=error. Rules containing device cards must never omit --spec-aware。
6. Enable and prove only per authorization
When the user requests a disabled draft: confirm enable=false then stop. When the user authorizes running:
xgg rule enable <rid>
# 执行安全、可控触发;物理 source 请用户触发或等待真实条件
xgg rule logs <rid> --tail 50 --json
xgg rule trace <rid> --pretty
proof chain: source/node logs → edge logs → branch values → action success/failed → variable/device readback. Empty logs do not prove it was not triggered; trace must check completeness, not just frames.
For complex runtime, at least verify a positive case and a negative case that would change the conclusion, e.g. sequence forward/reverse/timeout, condition true/false, onlyNTimes N+1/reset, loop stop, modeSwitch multiple rotations.
Constraints that the rule graph must not violate
E→E、S→S; only sourceBcan connect to E or S.- At most one edge per target input; for multiple events, first
signalOr, for multiple states, firstlogicOr/logicAnd。 - Every action/write-variable node must have a satisfiable upstream event path; the auxiliary pin
stop/zero/setFalseis not the main trigger. condition.triggermust be event-reachable; condition is state. When state is not connected, the XGG static model only allows unmet.eventSequenceBoth inputs must be reachable;logicAndevery declared input must have state.statusLastrequires a state that may be true; for inverted requirements uselogicNot。onlyNTimesandcounter'szerois an optional control pin; connect it only when the business needs to open a new counting window/allow clearing. For daily reset use alarmClock→zero; lifecycle accumulation or a one-time first N times gate may omit zero.loopThere must be a start; for bounded or cancellable business, a stop should be designed. If permanent polling is explicitly required, stop may be omitted, and it should be explained that termination depends on disable/delete, a positive interval is used, and the risk of event storms is assessed. The target gateway has previously verifiedoutput→同节点 stoplimited feedback; other feedback and firmware still need real-world testing.modeSwitchoutputs are consecutive from 0; dynamic logic/event inputs are at least 2.- device/action/set/query output can continue to be chained; the current static pin contract does not prove that it is sent only after success, and critical links must be checked in the logs.
Real-device safety
For login, snapshot, exit codes, concurrent editing, and backup details, refer to operations.md . Minimum baseline:
export XGG_AGENT_MODE=1
export XGG_SNAPSHOTS_DIR="$PWD/snapshots"
- If auth required/expired or exit 3 occurs, stop the current write and distinguish the authentication domain: cloud authorization goes through QR code scanning; gateway sessions prefer
cloud gateway loginto obtain the code autonomously; when cloud discovery/code retrieval is not supported, fall back to the full address plus a new code according to the positioning guide. Login codes must never enter the repository, Issue/PR, or reports; writes with unknown results are not automatically replayed. - Modifications to node/edge/layout/set of enabled rules may take effect immediately. Read enable before writing; when isolation is needed, disable first according to authorization, or construct offline and then perform a single set.
- The mutation lease only serializes xgg; it is not a web CAS; stop web editing during writes.
- Do not use
--no-snapshot/--no-validate/--no-var-checkto bypass normal failures. - After CLI writes, the web page may cache stale graphs/variables: first perform CLI readback, then ask the user to press F5.
- restore/delete/config-set and real device actions are not capability probes; execute them only under explicit user authorization and rollback-capable conditions.
Diagnostic order
When automation "does not work":
1. rule view:节点、pins、enable 是否是预期
2. device spec / variable readback:参数和值域是否漂移
3. validate --spec-aware:卡片、变量、access/push、action.in/output ref
4. lint --strict:拓扑、颜色、required、truth-aware reachability
5. logs/trace completeness:source 是否出现、哪条 edge/branch 停止
6. 可控重放:仅在完整下游已审查且获授权
7. 最小目标化修复,再重复 1-6
Do not rewrite the graph just because there are "no logs"; also do not rebuild variables first because the web page shows that variables are missing. First variable get-value、rule view, F5, then judge.
Completion criteria
The deliverable includes at least:
- natural language→node/pin plan and key semantic choices;
- device spec/variable evidence and all enum label→wire value mappings;
- final
rule view, validate/lint exit + summary, enable status; - if authorized to run, logs/trace/readback for positive/negative triggers and evidence limits;
- unproven items regarding reset/stop, internal state lifecycle, and action failure;
- snapshot/backup and cleanup status of temporary rules/variables;
- web page F5 reminder.
The content build marker is the SHA-256 of the entire Skill file tree: after sorting relative POSIX paths, each item is computed by path, byte length, and raw bytes, and only the marker line of this file and its newline do not participate. It is used to identify copies with the same version number but outdated body or references. Repositories, package mirrors, and installed copies from the same version source should be compared recursively; for different rule versions, only reviewed increments should be synchronized, and newer rule capabilities must not be overwritten for byte consistency.