Find implicit state machines, review state bugs, and check or visualize statecharts with Stately.
95%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Medium
Suggest reviewing before use
#!/usr/bin/env node
// Spike: a bounded explicit-state checker over the native statechart graph.
// Plain Node, no Java, no downloads. See .scratch/js-checker-spike.md.
//
// Input: a model (native XGraph or an XState machine config) plus a rules file.
// Output: check-result.json (stately.check-result.v1) and graph.json (the native
// model with a stately.check-report.v1 attached), so counterexample paths point
// at native node and edge IDs directly.
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { basename, join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { createRequire } from 'node:module';
import { parseArgs } from 'node:util';
import { artifact, parseCheckResult, sha256 } from './check-result.mjs';
import { attachReport } from './checked-view.mjs';
export const CHECKER_NAME = 'stately-native-check';
export const CHECKER_VERSION = '0.1.0-spike';
const record = (value) =>
value !== null && typeof value === 'object' && !Array.isArray(value);
function fail(message) {
throw new Error(`native-check: ${message}`);
}
// ---------------------------------------------------------------------------
// Expression language: guards, actions and rule predicates share one grammar.
// literals: numbers, 'strings', true, false
// identifiers: context variables; event.x reads an event payload field
// operators: || && ! == != < <= > >= + - * / % (precedence as in JS)
// calls: in('State.path'), min(a,b), max(a,b), abs(a)
// Everything else is rejected at parse time, so a rules file cannot run code.
// ---------------------------------------------------------------------------
const TOKEN =
/\s*(?:(\d+(?:\.\d+)?)|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)|(==|!=|<=|>=|&&|\|\||[-+*/%<>!(),?:]))/y;
export function parseExpression(source) {
if (typeof source !== 'string' || !source.trim())
fail(`empty expression`);
const tokens = [];
TOKEN.lastIndex = 0;
let position = 0;
while (position < source.length) {
TOKEN.lastIndex = position;
const match = TOKEN.exec(source);
if (!match) {
if (!source.slice(position).trim()) break;
fail(`cannot read expression near "${source.slice(position, position + 12)}" in: ${source}`);
}
position = TOKEN.lastIndex;
if (match[1] !== undefined) tokens.push({ kind: 'number', value: Number(match[1]) });
else if (match[2] !== undefined)
tokens.push({ kind: 'string', value: match[2].slice(1, -1).replace(/\\(.)/g, '$1') });
else if (match[3] !== undefined) {
const word = match[3];
if (word === 'true' || word === 'false') tokens.push({ kind: 'bool', value: word === 'true' });
else tokens.push({ kind: 'name', value: word });
} else tokens.push({ kind: 'op', value: match[4] });
}
let index = 0;
const peek = () => tokens[index];
const take = (value) => {
const token = tokens[index];
if (!token || (value !== undefined && token.value !== value))
fail(`expected ${value ?? 'a value'} in: ${source}`);
index++;
return token;
};
const binary = (levels, level = 0) => {
if (level === levels.length) return unary();
let left = binary(levels, level + 1);
while (peek()?.kind === 'op' && levels[level].includes(peek().value)) {
const op = take().value;
const right = binary(levels, level + 1);
left = { op, left, right };
}
return left;
};
const unary = () => {
if (peek()?.kind === 'op' && peek().value === '!') {
take();
return { op: '!', arg: unary() };
}
if (peek()?.kind === 'op' && peek().value === '-') {
take();
return { op: 'neg', arg: unary() };
}
return primary();
};
const primary = () => {
const token = take();
if (token.kind === 'op' && token.value === '(') {
const inner = expression();
take(')');
return inner;
}
if (token.kind === 'number' || token.kind === 'string' || token.kind === 'bool')
return { lit: token.value };
if (token.kind === 'name') {
if (peek()?.kind === 'op' && peek().value === '(') {
take('(');
const args = [];
if (!(peek()?.kind === 'op' && peek().value === ')'))
do args.push(expression());
while (peek()?.kind === 'op' && peek().value === ',' && take());
take(')');
if (!['in', 'min', 'max', 'abs'].includes(token.value))
fail(`unknown function ${token.value} in: ${source}`);
return { call: token.value, args };
}
return { ref: token.value };
}
fail(`unexpected ${token.value} in: ${source}`);
};
const expression = () => {
const test = binary([['||'], ['&&'], ['==', '!='], ['<', '<=', '>', '>='], ['+', '-'], ['*', '/', '%']]);
if (peek()?.kind === 'op' && peek().value === '?') {
take('?');
const then = expression();
take(':');
return { cond: test, then, otherwise: expression() };
}
return test;
};
const ast = expression();
if (index !== tokens.length) fail(`trailing input in: ${source}`);
return ast;
}
/** Free variable references of an expression (dotted names kept whole). */
export function expressionRefs(ast, out = new Set()) {
if (!ast) return out;
if (ast.ref) out.add(ast.ref);
if (ast.left) expressionRefs(ast.left, out);
if (ast.right) expressionRefs(ast.right, out);
if (ast.arg) expressionRefs(ast.arg, out);
if (ast.cond) expressionRefs(ast.cond, out), expressionRefs(ast.then, out), expressionRefs(ast.otherwise, out);
if (ast.args) ast.args.forEach((arg) => expressionRefs(arg, out));
return out;
}
export function evaluate(ast, scope) {
if ('lit' in ast) return ast.lit;
if (ast.cond) return evaluate(ast.cond, scope) ? evaluate(ast.then, scope) : evaluate(ast.otherwise, scope);
if (ast.ref) {
const [head, ...rest] = ast.ref.split('.');
let value;
if (head === 'event' && scope.event && !Object.hasOwn(scope.vars, 'event')) value = scope.event;
else if (Object.hasOwn(scope.vars, head)) value = scope.vars[head];
else throw new Unresolved(`unknown variable ${ast.ref}`);
for (const key of rest) {
if (!record(value) || !Object.hasOwn(value, key))
throw new Unresolved(`unknown field ${ast.ref}`);
value = value[key];
}
return value;
}
if (ast.call) {
const args = ast.args.map((arg) => evaluate(arg, scope));
switch (ast.call) {
case 'in':
return scope.inState(String(args[0]));
case 'min':
return Math.min(...args);
case 'max':
return Math.max(...args);
case 'abs':
return Math.abs(args[0]);
}
}
switch (ast.op) {
case '!':
return !evaluate(ast.arg, scope);
case 'neg':
return -evaluate(ast.arg, scope);
case '&&':
return evaluate(ast.left, scope) && evaluate(ast.right, scope);
case '||':
return evaluate(ast.left, scope) || evaluate(ast.right, scope);
}
const a = evaluate(ast.left, scope),
b = evaluate(ast.right, scope);
switch (ast.op) {
case '==':
return a === b;
case '!=':
return a !== b;
case '<':
return a < b;
case '<=':
return a <= b;
case '>':
return a > b;
case '>=':
return a >= b;
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return Math.trunc(a / b);
case '%':
return a % b;
}
fail(`cannot evaluate ${JSON.stringify(ast)}`);
}
// ---------------------------------------------------------------------------
// Model normalization. Both inputs become one tree:
// node { id, key, path, parentId, type: 'compound'|'parallel'|'atomic'|'final',
// initialId, children[], entry[], exit[] }
// edge { id, sourceId, targetIds[], eventType, guard, actions[], internal, order }
// ---------------------------------------------------------------------------
// Editor XGraphs name state completion `@statelyai.state.done.<node id>` (legacy
// `@stately.`); the checker and exporter use the XState event type.
const canonicalEventType = (eventType) => eventType.replace(/^@stately(?:ai)?\.state\.done\./, 'xstate.done.state.');
// Built-in actions that enqueue an event change the macrostep; neither engine models them.
const EVENT_QUEUE_ACTIONS = new Set(['xstate.raise', 'raise']);
function normalizeXGraph(graph) {
if (!Array.isArray(graph.nodes) || !Array.isArray(graph.edges))
fail('XGraph needs nodes and edges arrays');
const actions = (value, owner) => {
if (value == null) return [];
if (!Array.isArray(value) || value.some((action) => !record(action) || typeof action.type !== 'string' || !action.type.trim()))
fail(`${owner} actions must be an array of objects with a non-empty type`);
return value;
};
const nodes = new Map();
for (const node of graph.nodes) {
if (!record(node.data) || typeof node.data.key !== 'string') fail(`node ${node.id} lacks data.key`);
nodes.set(node.id, {
id: node.id,
key: node.data.key,
parentId: node.parentId ?? null,
rawType: node.data.type ?? null,
history: node.data.history ?? false,
initialId: node.data.initialId ?? null,
children: [],
entry: actions(node.data.entry, `node ${node.id} entry`),
exit: actions(node.data.exit, `node ${node.id} exit`),
always: [],
});
}
// Graph-level startup applies where node data names no initial child; the root id
// itself means no startup override.
const startup = typeof graph.initialNodeId === 'string' ? nodes.get(graph.initialNodeId) : undefined;
for (let child = startup, parent = startup && nodes.get(startup.parentId); parent; child = parent, parent = nodes.get(parent.parentId))
parent.initialId ??= child.id;
const edges = graph.edges.map((edge, order) => {
if (edge.data?.context != null)
fail(`edge ${edge.id} updates context in its transition; move the update to a named action with an assignment in the rules file`);
return {
id: edge.id,
sourceId: edge.sourceId,
targetIds:
edge.data?.transitionType === 'targetless'
? []
: [edge.targetId, ...(edge.data?.additionalTargetIds ?? [])].filter(Boolean),
eventType: canonicalEventType(edge.data?.eventType ?? ''),
guard: edge.data?.guard ?? null,
actions: actions(edge.data?.actions, `edge ${edge.id}`),
reenter: edge.data?.transitionType === 'reenter',
order,
};
});
const implementations = record(graph.data?.implementations) ? graph.data.implementations : {};
const initialContext = record(graph.data?.context) ? graph.data.context : {};
return finishTree(nodes, edges, initialContext, implementations);
}
function normalizeXStateConfig(config) {
const nodes = new Map();
const edges = [];
let order = 0;
const actions = (list) =>
(Array.isArray(list) ? list : list ? [list] : []).map((item) =>
typeof item === 'string' ? { type: item } : record(item) ? item : { type: String(item) },
);
const walk = (state, id, key, parentId) => {
const node = {
id,
key,
parentId,
rawType: state.type ?? null,
history: state.type === 'history' ? state.history ?? 'shallow' : false,
initialId: state.initial != null ? `${id}.${state.initial}` : null,
children: [],
entry: actions(state.entry),
exit: actions(state.exit),
always: [],
};
nodes.set(id, node);
for (const [childKey, child] of Object.entries(state.states ?? {}))
walk(child ?? {}, `${id}.${childKey}`, childKey, id);
const addEdges = (eventType, value) => {
for (const item of Array.isArray(value) ? value : [value]) {
const transition = typeof item === 'string' ? { target: item } : item ?? {};
const targets = transition.target == null ? [] : [].concat(transition.target);
edges.push({
id: `${id}:${eventType}:${order}`,
sourceId: id,
targetIds: targets.map((target) => resolveTarget(target, id, parentId)),
eventType,
guard:
transition.guard == null
? null
: typeof transition.guard === 'string'
? { type: transition.guard }
: transition.guard,
actions: actions(transition.actions),
reenter: transition.reenter === true,
order: order++,
});
}
};
for (const [eventType, value] of Object.entries(state.on ?? {})) addEdges(eventType, value);
if (state.always) addEdges('', state.always);
for (const [delay, value] of Object.entries(state.after ?? {})) addEdges(`xstate.after.${delay}`, value);
if (state.onDone) addEdges(`xstate.done.state.${id}`, state.onDone);
for (const invoke of [].concat(state.invoke ?? [])) {
if (invoke.onDone) addEdges(`xstate.done.actor.${invoke.id ?? invoke.src ?? 'actor'}`, invoke.onDone);
if (invoke.onError) addEdges(`xstate.error.actor.${invoke.id ?? invoke.src ?? 'actor'}`, invoke.onError);
}
};
const resolveTarget = (target, sourceId, parentId) => {
if (target.startsWith('#')) {
const [head, ...rest] = target.slice(1).split('.');
const root = [...nodes.values()].find((node) => node.parentId === null);
return [head === (config.id ?? 'machine') || head === root?.key ? rootId : head, ...rest].join('.');
}
if (target.startsWith('.')) return `${sourceId}${target}`;
return parentId === null ? `${sourceId}.${target}` : `${parentId}.${target}`;
};
const rootId = config.id ?? 'machine';
walk(config, rootId, rootId, null);
// `#id` targets referring to custom state ids are rare in configs the skill handles; a
// target that is not a known node fails closed below.
return finishTree(nodes, edges, config.context ?? {});
}
function finishTree(nodes, edges, initialContext = {}, implementations = {}) {
const roots = [...nodes.values()].filter((node) => node.parentId === null);
if (roots.length !== 1) fail('exactly one root node is required');
const root = roots[0];
for (const node of nodes.values()) {
if (node.parentId === null) continue;
const parent = nodes.get(node.parentId);
if (!parent) fail(`node ${node.id} has unknown parent ${node.parentId}`);
parent.children.push(node);
}
const paths = new Map();
const assignPath = (node, prefix) => {
node.path = prefix;
paths.set(prefix.join('.'), node.id);
for (const child of node.children) assignPath(child, [...prefix, child.key]);
};
assignPath(root, []);
for (const node of nodes.values()) {
if (node.history) fail(`history states are not supported (${node.id})`);
if (node.rawType === 'choice') fail(`choice pseudo-states are not supported (${node.id})`);
node.type =
node.rawType === 'parallel'
? 'parallel'
: node.rawType === 'final'
? 'final'
: node.children.length
? 'compound'
: 'atomic';
if (node.type === 'compound') {
if (node.initialId === null) node.initialId = node.children[0].id;
if (!node.children.some((child) => child.id === node.initialId))
fail(`initial ${node.initialId} is not a child of ${node.id}`);
}
}
const rejectQueued = (list, owner) => {
const queued = list.find((action) => EVENT_QUEUE_ACTIONS.has(action.type));
if (queued) fail(`${owner}: ${queued.type} raises an event inside the macrostep, which is not supported`);
};
for (const node of nodes.values()) {
rejectQueued(node.entry, `node ${node.id} entry`);
rejectQueued(node.exit, `node ${node.id} exit`);
}
for (const edge of edges) {
rejectQueued(edge.actions, `edge ${edge.id}`);
if (!nodes.has(edge.sourceId)) fail(`edge ${edge.id} has unknown source`);
for (const target of edge.targetIds)
if (!nodes.has(target)) fail(`edge ${edge.id} has unknown target ${target}`);
if (edge.eventType === '' || edge.eventType === 'xstate.always' || edge.eventType === 'always')
edge.eventType = '';
}
const outgoing = new Map();
for (const edge of [...edges].sort((a, b) => a.order - b.order))
outgoing.set(edge.sourceId, [...(outgoing.get(edge.sourceId) ?? []), edge]);
// External alphabet: every edge event except eventless ones and state completion events,
// which are raised internally when a final child becomes active.
const events = [
...new Set(
edges
.map((edge) => edge.eventType)
.filter((event) => event !== '' && !event.startsWith('xstate.done.state.')),
),
].sort();
return { nodes, edges, outgoing, root, paths, events, initialContext, implementations };
}
// ---------------------------------------------------------------------------
// Inline guard and assign extraction. Editor-authored models carry guard code as
// `edge.data.guard.code` or `data.implementations.guards[].code.body`, and context
// updates as `xstate.assign` params. The simple subset that fits the rules-file
// grammar is used directly; anything else stays unresolved and is reported.
// ---------------------------------------------------------------------------
/** A JS expression body reduced to the rules grammar, or null. */
export function extractExpression(source) {
if (typeof source !== 'string') return null;
let body = source.trim().replace(/;\s*$/, '');
body = body.replace(/^(?:async\s+)?(?:function\s*\w*\s*)?\(?\s*(?:\{[^}]*\}|\w+)?\s*(?:,\s*(?:\{[^}]*\}|\w+))*\s*\)?\s*=>\s*/, '');
const block = body.match(/^\{\s*return\s+([\s\S]*?);?\s*\}$/);
if (block) body = block[1];
if (/^\(([\s\S]*)\)$/.test(body) && !/^\(\s*\{/.test(body)) body = body.slice(1, -1);
body = body
.replace(/\bcontext\.([A-Za-z_][A-Za-z0-9_]*)/g, '$1')
.replace(/===/g, '==')
.replace(/!==/g, '!=');
if (/\b(?:context|snapshot|self|system|this|new|function|await|=>)\b|[\[\]{}=](?!=)/.test(body.replace(/[!<>=]=/g, ''))) return null;
try {
return parseExpression(body);
} catch {
return null;
}
}
/** `{ key: expr, ... }` object literal bodies (assign objects) reduced to [key, ast] pairs, or null. */
export function extractAssignments(source) {
if (typeof source !== 'string') return null;
let body = source.trim().replace(/;\s*$/, '');
body = body.replace(/^(?:\(?\s*(?:\{[^}]*\}|\w+)?\s*(?:,\s*(?:\{[^}]*\}|\w+))*\s*\)?\s*=>\s*)/, '');
const block = body.match(/^\{\s*return\s+([\s\S]*?);?\s*\}$/);
if (block) body = block[1];
if (/^\(([\s\S]*)\)$/.test(body)) body = body.slice(1, -1).trim();
if (!/^\{[\s\S]*\}$/.test(body)) return null;
const inner = body.slice(1, -1);
const pairs = [];
let depth = 0, start = 0;
const parts = [];
for (let i = 0; i < inner.length; i++) {
const ch = inner[i];
if ('([{'.includes(ch)) depth++;
else if (')]}'.includes(ch)) depth--;
else if (ch === ',' && depth === 0) parts.push(inner.slice(start, i)), (start = i + 1);
}
parts.push(inner.slice(start));
for (const part of parts) {
if (!part.trim()) continue;
const match = part.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([\s\S]+)$/);
if (!match) return null;
const ast = extractExpression(match[2]);
if (!ast) return null;
pairs.push([match[1], ast]);
}
return pairs.length ? pairs : null;
}
/** Guard and action expressions found in the model, keyed by name; explicit rules win. */
export function extractImplementations(model) {
const guards = {}, actions = {}, skipped = [];
const literal = (value) => ({ lit: value });
for (const item of model.implementations.guards ?? []) {
const ast = extractExpression(item.code?.body);
if (ast) guards[item.name ?? item.id] = ast;
else if (item.code?.body) skipped.push(`guard ${item.name ?? item.id}`);
}
for (const item of model.implementations.actions ?? []) {
const pairs = extractAssignments(item.code?.body);
if (pairs) actions[item.name ?? item.id] = pairs;
else if (item.code?.body) skipped.push(`action ${item.name ?? item.id}`);
}
for (const edge of model.edges) {
const guard = edge.guard;
if (guard?.code && !guards[guard.type]) {
const ast = extractExpression(guard.code);
if (ast) guards[guard.type] = ast;
else skipped.push(`guard ${guard.type} (${edge.id})`);
}
}
const assignActions = [...model.nodes.values()].flatMap((node) => [...node.entry, ...node.exit]).concat(model.edges.flatMap((edge) => edge.actions));
for (const action of assignActions) {
if (action?.type !== 'xstate.assign' || !record(action.params)) continue;
const assignment = record(action.params.assignment) ? action.params.assignment : action.params;
const pairs = [];
let ok = true;
for (const [key, value] of Object.entries(assignment)) {
if (value === null || ['number', 'string', 'boolean'].includes(typeof value)) pairs.push([key, literal(value)]);
else if (record(value) && value['@type'] === 'code' && typeof value.expr === 'string') {
const ast = extractExpression(value.expr);
if (!ast) ok = false;
else pairs.push([key, ast]);
} else ok = false;
}
const name = action.id ?? `xstate.assign:${JSON.stringify(assignment)}`;
if (ok && pairs.length) {
action.resolvedType = name;
actions[name] = pairs;
} else skipped.push(`xstate.assign ${JSON.stringify(assignment).slice(0, 60)}`);
}
return { guards, actions, skipped };
}
/**
* Adds the guards and assignments extracted from the model's inline implementations
* to `rules`; rules-file expressions take precedence. Shared by the checker and the
* exporters so all of them read the same expressions.
*/
export function mergeImplementations(model, rules) {
const extracted = extractImplementations(model);
for (const [name, ast] of Object.entries(extracted.guards)) rules.guards[name] ??= ast;
for (const [name, pairs] of Object.entries(extracted.actions)) {
if (rules.actions[name]) continue;
for (const [variable] of pairs) if (!rules.domains[variable]) fail(`extracted action ${name} assigns ${variable}, which has no context domain (declare it in rules.context)`);
rules.actions[name] = pairs;
}
return extracted;
}
export function normalizeModel(input) {
if (!record(input)) fail('model must be a JSON object');
if (Array.isArray(input.nodes) && Array.isArray(input.edges)) return normalizeXGraph(input);
if (input.states || input.initial || input.on) return normalizeXStateConfig(input);
fail('model is neither an XGraph (nodes/edges) nor an XState config (states/initial)');
}
// ---------------------------------------------------------------------------
// Rules file.
// ---------------------------------------------------------------------------
const RULE_KINDS = ['never', 'initially', 'eventually', 'eventually-always', 'leads-to', 'no-dead-ends', 'reachable'];
// Work budgets that keep one small request from running unbounded inside a single step
// or rule loop, where the per-state maxStates and timeoutMs checks do not reach.
export const MAX_RULES = 1000;
export const MAX_STEP_REPLAYS = 1024; // guard case-split replays for one event from one state
export const MAX_COUNTEREXAMPLE_STEPS = 200_000; // total states across all stored counterexamples
export function parseRules(input) {
if (!record(input)) fail('rules must be a JSON object');
for (const key of Object.keys(input))
if (!['context', 'init', 'guards', 'actions', 'events', 'rules', 'bounds', 'fairness', 'assumptions', 'citations'].includes(key))
fail(`unknown rules key ${key}`);
const domains = {};
for (const [name, spec] of Object.entries(input.context ?? {})) {
if (Array.isArray(spec)) domains[name] = { kind: 'enum', values: spec };
else if (spec === 'bool' || spec === 'boolean') domains[name] = { kind: 'bool' };
else if (record(spec) && Number.isInteger(spec.min) && Number.isInteger(spec.max) && spec.min <= spec.max)
domains[name] = { kind: 'int', min: spec.min, max: spec.max };
else fail(`context domain ${name} must be [values], "bool", or {min,max}`);
}
const guards = {};
for (const [name, source] of Object.entries(input.guards ?? {})) guards[name] = parseExpression(source);
const actions = {};
for (const [name, assignments] of Object.entries(input.actions ?? {})) {
if (!record(assignments)) fail(`action ${name} must map variables to expressions`);
actions[name] = Object.entries(assignments).map(([variable, source]) => {
if (!domains[variable]) fail(`action ${name} assigns ${variable}, which has no context domain`);
return [variable, parseExpression(source)];
});
}
const events = {};
for (const [name, spec] of Object.entries(input.events ?? {})) {
if (!record(spec) || !Array.isArray(spec.payloads) || !spec.payloads.length)
fail(`event ${name} needs { payloads: [...] }`);
events[name] = spec.payloads;
}
const rules = (input.rules ?? []).map((rule, index) => {
if (!record(rule) || !RULE_KINDS.includes(rule.kind)) fail(`rule ${index} needs kind in ${RULE_KINDS.join('/')}`);
const id = rule.id ?? `rule_${index}`;
const compiled = { id, kind: rule.kind, description: rule.description };
if (['never', 'initially', 'reachable', 'eventually', 'eventually-always'].includes(rule.kind))
compiled.then = parseExpression(rule.when ?? rule.then);
if (rule.kind === 'leads-to') {
compiled.when = parseExpression(rule.when);
compiled.then = parseExpression(rule.then);
}
if (rule.kind === 'no-dead-ends') compiled.allowFinal = rule.allowFinal !== false;
return compiled;
});
if (!rules.length) fail('rules.rules must list at least one rule');
if (new Set(rules.map((rule) => rule.id)).size !== rules.length) fail('duplicate rule ids');
let fairness = input.fairness ?? 'weak';
if (fairness === 'weak' || fairness === 'none') fairness = { kind: fairness };
else if (record(fairness) && Array.isArray(fairness.weak) && fairness.weak.every((item) => typeof item === 'string'))
fairness = { kind: 'events', events: fairness.weak };
else fail('fairness must be "weak", "none", or { "weak": [eventTypes] }');
const init = input.init === undefined ? [{}] : Array.isArray(input.init) ? input.init : [input.init];
if (input.citations !== undefined && !record(input.citations)) fail('citations must map a guard, action, or transition id to "path:line" strings');
const citations = {};
for (const [name, value] of Object.entries(input.citations ?? {})) {
const list = Array.isArray(value) ? value : [value];
if (!list.length || !list.every((item) => typeof item === 'string' && CITATION.test(item)))
fail(`citation ${name} must be a "path:line" string or a non-empty list of them`);
citations[name] = list;
}
if (!init.length || !init.every(record)) fail('init must be an object or a non-empty list of objects');
if (input.bounds !== undefined && !record(input.bounds)) fail('bounds must be an object');
// Exporters write bounds into generated source, so they must be plain integers.
const bound = (key, fallback, min) => {
const value = input.bounds?.[key] ?? fallback;
if (!Number.isSafeInteger(value) || value < min) fail(`bounds.${key} must be an integer of at least ${min}`);
return value;
};
return {
domains,
init,
guards,
actions,
events,
rules,
fairness,
bounds: {
maxStates: bound('maxStates', 50_000, 1),
maxAlwaysSteps: bound('maxAlwaysSteps', 50, 1),
// Wall-clock cap for exploration; hosted callers set it. 0 disables it.
timeoutMs: bound('timeoutMs', 0, 0),
},
assumptions: input.assumptions ?? [],
citations,
};
}
/** `path:line` or `path:line-line`. */
const CITATION = /^\S(?:.*\S)?:\d+(?:-\d+)?$/;
/** Citation keys name a guard, an action, or a transition (edge id) in the model or rules. */
function validateCitations(model, rules) {
const known = new Set([...Object.keys(rules.guards), ...Object.keys(rules.actions)]);
for (const edge of model.edges) {
known.add(edge.id);
if (edge.guard?.type) known.add(edge.guard.type);
for (const action of edge.actions) known.add(action.type);
}
for (const node of model.nodes.values()) for (const action of [...node.entry, ...node.exit]) known.add(action.type);
for (const item of [...(model.implementations.guards ?? []), ...(model.implementations.actions ?? [])]) known.add(item.name ?? item.id);
for (const name of Object.keys(rules.citations))
if (!known.has(name)) fail(`citations: ${JSON.stringify(name)} is not a guard, action, or transition id in the model or rules`);
}
/**
* Every guarded transition whose guard has no source citation, by guard name or edge id.
* A rule that holds still depends on these conditions matching the application.
*/
export function uncitedConditions(model, citations) {
return model.edges
.filter((edge) => edge.guard && !(edge.guard.type && citations[edge.guard.type]) && !citations[edge.id])
.map((edge) => ({
edgeId: edge.id,
...(edge.guard.type ? { guard: edge.guard.type } : {}),
eventType: edge.eventType || 'xstate.always',
source: model.nodes.get(edge.sourceId).path.join('.') || edge.sourceId,
}));
}
/**
* Resolves a state reference (node id, state path, unique key, or unique trailing path)
* to one native node id. With `within`, the reference resolves among that node and its
* descendants, and paths are relative to it.
*/
export function resolveStateReference(model, ref, owner, within) {
const base = within ? model.nodes.get(within) : undefined;
const nodes = [...model.nodes.values()].filter((node) => !base || node.path.slice(0, base.path.length).join('.') === base.path.join('.'));
const path = (node) => node.path.slice(base ? base.path.length : 0).join('.');
const found =
typeof ref === 'string' && ref
? nodes.filter((node) => node.id === ref || path(node) === ref || node.key === ref || path(node).endsWith(`.${ref}`)).map((node) => node.id)
: [];
if (!found.length) {
const suffix = nodes.map((node) => node.id).filter((id) => id.endsWith(`.${ref}`));
const suggestions = (suffix.length ? suffix : nodes.map((node) => node.id)).slice(0, 3);
fail(`${owner}: unknown state reference ${JSON.stringify(ref)} in in(); use a node ID such as ${suggestions.join(', ')}`);
}
if (found.length > 1)
fail(`${owner}: ambiguous state reference ${JSON.stringify(ref)} in in(); use a unique node ID or state path: ${found.join(', ')}`);
return found[0];
}
/** Resolves every in() reference in `ast` into `references` (ref string to node id). */
export function addStateReferences(model, references, ast, owner) {
if (!ast) return;
if (ast.call === 'in') {
if (ast.args.length !== 1 || typeof ast.args[0]?.lit !== 'string')
fail(`${owner}: in() needs one literal state name or node ID`);
const ref = ast.args[0].lit;
if (!references.has(ref)) references.set(ref, resolveStateReference(model, ref, owner));
}
for (const child of [ast.left, ast.right, ast.arg, ast.cond, ast.then, ast.otherwise]) addStateReferences(model, references, child, owner);
for (const arg of ast.args ?? []) addStateReferences(model, references, arg, owner);
}
function validateStateReferences(model, rules) {
const references = new Map();
const visit = (ast, owner) => addStateReferences(model, references, ast, owner);
for (const [name, ast] of Object.entries(rules.guards)) visit(ast, `guard ${name}`);
for (const [name, assignments] of Object.entries(rules.actions))
for (const [, ast] of assignments) visit(ast, `action ${name}`);
for (const rule of rules.rules) {
visit(rule.when, `rule ${rule.id}`);
visit(rule.then, `rule ${rule.id}`);
}
return references;
}
export function nativeCheckExitCode(result) {
if (result.rules.some((rule) => rule.outcome === 'broken')) return 1;
return !result.checker.complete || result.rules.some((rule) => rule.outcome === 'not-checked') ? 2 : 0;
}
/**
* Runs `attempt(assume)` for every combination of guard assumptions it requests.
* Each replay decides one new guard both ways; assumption sets are deduplicated by
* their sorted entries, so independent guards cost one replay per combination.
*/
function caseSplit(attempt, canReplay = () => true) {
const pending = [{}];
const seen = new Set();
while (pending.length) {
if (!canReplay()) return;
const assume = pending.shift();
const key = JSON.stringify(Object.entries(assume).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
if (seen.has(key)) continue;
seen.add(key);
const wanted = attempt(assume);
if (wanted.size) {
const [name] = wanted;
pending.push({ ...assume, [name]: true }, { ...assume, [name]: false });
}
}
}
// ---------------------------------------------------------------------------
// Statechart semantics come from XState v6's pure transition functions. The
// checker only interns snapshots, enumerates events and searches the graph.
// configuration = sorted list of active atomic/final node ids (native ids).
// ---------------------------------------------------------------------------
function loadXState() {
// The spike resolves the v6 beta through graph-tools (repo checkout) or a plain
// `xstate` install next to the skill; a packaged skill would bundle it.
// The repo path is assembled at runtime so bundlers (Turbopack, webpack) do not try to
// resolve it statically; hosted builds pass `xstate` in and never reach this.
const repoGraphTools = ['..', '..', '..', '..', '..', 'packages', 'graph-tools', 'package.json'].join('/');
const candidates = [
[new URL(repoGraphTools, import.meta.url), 'xstate-v6'],
[import.meta.url, 'xstate'],
];
const errors = [];
for (const [from, name] of candidates) {
try {
const require = createRequire(from);
const xstate = require(name);
if (typeof xstate.getMicrosteps !== 'function') throw new Error(`${name} is not XState v6`);
return { ...xstate, version: require(`${name}/package.json`).version };
} catch (error) {
errors.push(error.message);
}
}
fail(`xstate v6 (getMicrosteps) is required: ${errors.join('; ')}`);
}
export class Unresolved extends Error {}
function ancestors(model, node) {
const list = [];
for (let current = node; current; current = model.nodes.get(current.parentId)) list.push(current);
return list; // node first, root last
}
export function activeSet(model, configuration) {
const active = new Set();
for (const id of configuration) for (const node of ancestors(model, model.nodes.get(id))) active.add(node.id);
return active;
}
/**
* Builds the XState v6 machine for a normalized model. Every state gets a synthetic
* `#x<n>` id so native ids (which may contain dots) never collide with XState's path
* syntax; `meta.edgeId` on each transition carries the native edge id back out.
* Guards and actions become `to`/entry/exit functions that evaluate the rules-file
* expressions; unknown guards read an assumption carried on the event (the driver
* enumerates both values), unknown assigns are reported through `collector`.
*/
class Engine {
constructor(model, rules, diagnostics, xstate, stateReferences) {
this.model = model;
this.rules = rules;
this.diagnostics = diagnostics;
this.xstate = xstate ?? loadXState();
this.stateReferences = stateReferences;
this.xid = new Map([...model.nodes.keys()].map((id, index) => [id, `x${index}`]));
this.native = new Map([...this.xid].map(([id, xid]) => [xid, id]));
this.current = null; // the pre-step configuration, for in() inside guards and actions
this.collector = null; // { unresolved: boolean, wanted: Set<guardName> }
this.initialAssume = null; // guard assumptions for initial(), which has no event to carry them
this.machine = this.xstate.createMachine({ ...this.stateConfig(model.root, true), options: { maxIterations: rules.bounds.maxAlwaysSteps } });
}
scope(configuration, context, event) {
const active = activeSet(this.model, configuration);
return {
vars: context,
event,
inState: (ref) => {
const id = this.stateReferences.get(ref);
if (id === undefined) fail(`unvalidated state reference ${JSON.stringify(ref)} in in()`);
return active.has(id);
},
};
}
guardHolds(edge, context, event) {
const name = edge.guard?.type;
const expression = this.rules.guards[name];
const assume = this.initialAssume ?? event['@assume'] ?? {};
const askAssumption = (label) => {
this.diagnostics.unresolvedGuards.add(label);
// One decision per guard and context: a later read after an action changed the
// context may get a different answer.
const key = `${name ?? label} ${JSON.stringify(context)}`;
if (Object.hasOwn(assume, key)) {
this.collector.unresolved = true;
return assume[key];
}
this.collector.wanted.add(key);
return false;
};
if (!expression) return askAssumption(name ?? '(inline code)');
try {
return Boolean(evaluate(expression, this.scope(this.current, context, event)));
} catch (error) {
if (!(error instanceof Unresolved)) throw error;
return askAssumption(`${name}: ${error.message}`);
}
}
applyActions(actions, context, event, ownerId) {
let next = context;
for (const action of actions) {
const name = action?.resolvedType ?? action?.type;
const assignments = this.rules.actions[name];
if (!assignments) {
if (name === 'xstate.assign' || name === 'assign' || name === undefined) {
this.diagnostics.unresolvedActions.add(name ?? '(inline code)');
this.diagnostics.unresolvedEdges.add(ownerId);
this.collector.unresolved = true;
this.collector.unknownContext = true;
}
continue;
}
const updated = { ...next };
for (const [variable, expression] of assignments) {
try {
updated[variable] = evaluate(expression, this.scope(this.current, next, event));
} catch (error) {
if (!(error instanceof Unresolved)) throw error;
this.diagnostics.unresolvedActions.add(`${name}: ${error.message}`);
this.diagnostics.unresolvedEdges.add(ownerId);
this.collector.unresolved = true;
this.collector.unknownContext = true;
}
}
next = updated;
}
return next;
}
transitionConfig(edge) {
const target = edge.targetIds.length ? edge.targetIds.map((id) => `#${this.xid.get(id)}`) : undefined;
const base = { ...(target ? { target } : {}), reenter: edge.reenter, meta: { edgeId: edge.id } };
if (!edge.guard && !edge.actions.length) return base;
return {
...base,
to: ({ context, event }) => {
if (edge.guard && !this.guardHolds(edge, context, event)) return undefined;
const next = edge.actions.length ? this.applyActions(edge.actions, context, event, edge.id) : context;
return { ...base, ...(next !== context ? { context: next } : {}) };
},
};
}
stateConfig(node, root = false) {
const config = { id: this.xid.get(node.id) };
if (root) config.context = ({ input }) => input;
if (node.type === 'parallel') config.type = 'parallel';
if (node.type === 'final') config.type = 'final';
if (node.type === 'compound') config.initial = this.xid.get(node.initialId);
if (node.children.length) config.states = Object.fromEntries(node.children.map((child) => [this.xid.get(child.id), this.stateConfig(child)]));
if (node.entry.length)
config.entry = ({ context, event }) => {
const next = this.applyActions(node.entry, context, event, node.id);
return next === context ? undefined : { context: next };
};
if (node.exit.length)
config.exit = ({ context, event }) => {
const next = this.applyActions(node.exit, context, event, node.id);
return next === context ? undefined : { context: next };
};
const on = {};
for (const edge of this.model.outgoing.get(node.id) ?? []) {
const transition = this.transitionConfig(edge);
if (edge.eventType === '') (config.always ??= []).push(transition);
else if (edge.eventType === `xstate.done.state.${node.id}`) (config.onDone ??= []).push(transition);
else if (edge.eventType.startsWith('xstate.done.state.')) fail(`edge ${edge.id}: a state done event must be handled on that state`);
else (on[edge.eventType] ??= []).push(transition);
}
if (Object.keys(on).length) config.on = on;
return config;
}
configurationOf(snapshot) {
return snapshot.nodes
.map((stateNode) => this.model.nodes.get(this.native.get(stateNode.id)))
.filter((node) => node && (node.type === 'atomic' || node.type === 'final'))
.map((node) => node.id)
.sort();
}
/**
* Initial snapshots for one initial context (eventless transitions already settled):
* [{ snapshot, configuration, context, edgeIds, unresolved }]. Guards without an
* expression are case-split as in step().
*/
initial(context, { canReplay } = {}) {
const results = [];
try {
caseSplit((assume) => {
this.current = [];
this.collector = { unresolved: false, unknownContext: false, wanted: new Set() };
this.initialAssume = assume;
let steps;
try {
steps = this.xstate.getInitialMicrosteps(this.machine, context);
} catch (error) {
if (error instanceof this.xstate.InfiniteTransitionError) fail(`eventless transitions do not settle from the initial state: ${error.message}`);
throw error;
}
if (this.collector.wanted.size) return this.collector.wanted;
const snapshot = steps.at(-1)[0];
const edgeIds = steps.flatMap(([, , transitions]) => transitions.map((t) => t.meta?.edgeId).filter(Boolean));
results.push({
snapshot,
configuration: this.configurationOf(snapshot),
context: snapshot.context,
edgeIds,
unresolved: this.collector.unresolved,
unknownContext: this.collector.unknownContext,
});
return this.collector.wanted;
}, canReplay);
} finally {
this.initialAssume = null;
}
return results;
}
/**
* Macrostep results for one event from one snapshot: [{ snapshot, configuration,
* context, edgeIds, unresolved }]. Guards without an expression are case-split by
* rerunning with every requested assumption.
*/
step(state, eventType, payload, { keepIgnored = false, canReplay } = {}) {
const results = [];
caseSplit((assume) => {
this.current = state.configuration;
this.collector = { unresolved: false, unknownContext: false, wanted: new Set() };
const event = { type: eventType, ...(payload ?? {}), ...(Object.keys(assume).length ? { '@assume': assume } : {}) };
let microsteps;
try {
microsteps = this.xstate.getMicrosteps(this.machine, state.snapshot, event);
} catch (error) {
if (error instanceof this.xstate.InfiniteTransitionError)
fail(`eventless transitions do not settle after ${eventType} in ${state.configuration.join(',')}: ${error.message}`);
throw error;
}
if (this.collector.wanted.size) return this.collector.wanted;
const snapshot = microsteps.at(-1)?.[0] ?? state.snapshot;
const edgeIds = microsteps.flatMap(([, , transitions]) => transitions.map((t) => t.meta?.edgeId).filter(Boolean));
if (!edgeIds.length && snapshot === state.snapshot) {
// Unhandled. Conformance keeps it so a trace can assert the event was ignored.
if (keepIgnored)
results.push({ snapshot, configuration: state.configuration, context: state.context, edgeIds, unresolved: this.collector.unresolved, unknownContext: this.collector.unknownContext, assume, ignored: true });
return this.collector.wanted;
}
results.push({
snapshot,
configuration: this.configurationOf(snapshot),
context: snapshot.context,
edgeIds,
unresolved: this.collector.unresolved,
unknownContext: this.collector.unknownContext,
assume,
});
return this.collector.wanted;
}, canReplay);
return results;
}
}
// ---------------------------------------------------------------------------
// Exploration and rule evaluation.
// ---------------------------------------------------------------------------
export function inDomain(domains, context) {
for (const [name, domain] of Object.entries(domains)) {
const value = context[name];
if (domain.kind === 'int' && !(Number.isInteger(value) && value >= domain.min && value <= domain.max)) return false;
if (domain.kind === 'bool' && typeof value !== 'boolean') return false;
if (domain.kind === 'enum' && !domain.values.includes(value)) return false;
}
return true;
}
/**
* Strongly connected components (Tarjan) of the explored graph restricted to `inside`
* states, reachable from `startIds`. Returns [{ members:Set, nontrivial:boolean }].
*/
function components(byId, startIds, inside) {
const index = new Map(),
low = new Map(),
onStack = new Set(),
stack = [],
out = [];
let counter = 0;
const visit = (root) => {
const frames = [{ id: root, iterator: byId(root).steps[Symbol.iterator]() }];
index.set(root, counter), low.set(root, counter++), stack.push(root), onStack.add(root);
while (frames.length) {
const frame = frames.at(-1);
const next = frame.iterator.next();
if (!next.done) {
const to = next.value.to;
if (!inside(byId(to))) continue;
if (!index.has(to)) {
index.set(to, counter), low.set(to, counter++), stack.push(to), onStack.add(to);
frames.push({ id: to, iterator: byId(to).steps[Symbol.iterator]() });
} else if (onStack.has(to)) low.set(frame.id, Math.min(low.get(frame.id), index.get(to)));
continue;
}
frames.pop();
if (frames.length) low.set(frames.at(-1).id, Math.min(low.get(frames.at(-1).id), low.get(frame.id)));
if (low.get(frame.id) === index.get(frame.id)) {
const members = new Set();
let id;
do (id = stack.pop()), onStack.delete(id), members.add(id);
while (id !== frame.id);
const nontrivial = [...members].some((member) => byId(member).steps.some((step) => members.has(step.to)));
out.push({ members, nontrivial });
}
}
};
for (const id of startIds) if (inside(byId(id)) && !index.has(id)) visit(id);
return out;
}
/**
* Normalizes and validates a model and rules file and builds the engine. Shared by
* `check` and trace conformance so both step the model the same way.
* `xstate` may be an already loaded XState v6 module (for example the cached copy from
* `ensureXState` in toolchain.mjs, imported by the caller); without it the module is
* resolved next to graph-tools or the skill.
*/
// ---------------------------------------------------------------------------
// Rules stored on the model. Acceptance criteria in `data.statelySpec` carry a
// rule each; context domains come from `data.schemas.context`, a map of property
// JSON Schemas (or a root object schema), for integer with minimum and maximum,
// boolean, or enum fields with an initial
// value in `data.context`. Guards and actions are
// extracted from implementations by prepare(), as for a rules file.
// ---------------------------------------------------------------------------
function schemaDomains(schema, initialContext) {
const domains = {};
if (!record(schema)) return domains;
// The editor stores a map of property schemas; a root object schema also works.
const properties = schema.type === 'object' && record(schema.properties) ? schema.properties : schema;
for (const [name, property] of Object.entries(properties)) {
// A domain needs an initial value; fields missing from the initial context stay out.
if (!record(property) || !Object.hasOwn(initialContext, name)) continue;
if (Array.isArray(property.enum) && property.enum.length && property.enum.every((value) => ['string', 'number', 'boolean'].includes(typeof value)))
domains[name] = property.enum;
else if (property.type === 'boolean') domains[name] = 'bool';
else if (property.type === 'integer' && Number.isInteger(property.minimum) && Number.isInteger(property.maximum) && property.minimum <= property.maximum)
domains[name] = { min: property.minimum, max: property.maximum };
}
return domains;
}
/**
* A rules file built from the rules on a model's acceptance criteria, or null
* when no criterion has one. Retired requirements are skipped. Each rule id is
* `<requirement id>/<criterion id>`.
*/
export function rulesFromModel(model) {
const spec = record(model?.data?.statelySpec) ? model.data.statelySpec : null;
const rules = [];
for (const requirement of Array.isArray(spec?.requirements) ? spec.requirements : []) {
if (!record(requirement) || requirement.status === 'retired') continue;
for (const criterion of Array.isArray(requirement.acceptance) ? requirement.acceptance : [])
if (record(criterion) && record(criterion.rule))
rules.push({ ...criterion.rule, id: `${requirement.id}/${criterion.id}`, description: criterion.text });
}
if (!rules.length) return null;
const context = schemaDomains(model.data.schemas?.context, record(model.data.context) ? model.data.context : {});
return { ...(Object.keys(context).length ? { context } : {}), rules };
}
// Only an omitted rules file falls back to the model; null is invalid rules input.
const resolveRules = (modelInput, rulesInput) =>
rulesInput !== undefined ? rulesInput : rulesFromModel(modelInput) ?? fail('no rules: pass a rules file, or add rules to the acceptance criteria of the model\'s requirements');
export function prepare({ model: modelInput, rules: rulesInput, xstate, limits }) {
const model = normalizeModel(modelInput);
const rules = parseRules(resolveRules(modelInput, rulesInput));
// `limits` lets a host cap the run below what the rules file asks for.
if (limits?.maxStates) rules.bounds.maxStates = Math.min(rules.bounds.maxStates, limits.maxStates);
if (limits?.timeoutMs) rules.bounds.timeoutMs = rules.bounds.timeoutMs ? Math.min(rules.bounds.timeoutMs, limits.timeoutMs) : limits.timeoutMs;
const extracted = mergeImplementations(model, rules);
const stateReferences = validateStateReferences(model, rules);
validateCitations(model, rules);
const diagnostics = { unresolvedGuards: new Set(), unresolvedActions: new Set(), unresolvedEdges: new Set(), extracted };
if (xstate && typeof xstate.getMicrosteps !== 'function') fail('the supplied xstate module is not XState v6');
const engine = new Engine(model, rules, diagnostics, xstate, stateReferences);
const initialContexts = rules.init.map((init) => {
const full = { ...model.initialContext, ...init };
for (const name of Object.keys(rules.domains))
if (!Object.hasOwn(full, name)) fail(`context variable ${name} has a domain but no initial value (set rules.init)`);
return full;
});
const project = (context) => {
const projected = {};
for (const name of Object.keys(rules.domains)) projected[name] = context[name];
return projected;
};
return { model, rules, diagnostics, engine, stateReferences, initialContexts, project, extracted };
}
// `clock` lets tests drive the time limits deterministically.
export function check({ model: modelInput, rules: suppliedRules, modelContent, rulesContent, modelPath = 'model.json', rulesPath = 'rules.json', xstate, limits, clock = () => performance.now() }) {
const started = clock();
// Rules derived from the model are bound through the model artifact.
const fromModel = suppliedRules === undefined;
const rulesInput = resolveRules(modelInput, suppliedRules);
const { model, rules, diagnostics, engine, initialContexts, project, extracted } = prepare({ model: modelInput, rules: rulesInput, xstate, limits });
// Evaluating rules is the only place the rule count costs work; TLA export and
// trace conformance parse the same file without this cap.
if (rules.rules.length > MAX_RULES) fail(`rules.rules lists ${rules.rules.length} rules; the limit is ${MAX_RULES}`);
const states = []; // { id, snapshot, configuration, context, initial, boundary, steps: [{to, edgeIds, event, unresolved}], unresolved }
const index = new Map();
const key = (configuration, context) => JSON.stringify([configuration, project(context)]);
const intern = (item, initial = false) => {
const k = key(item.configuration, item.context);
let id = index.get(k);
if (id === undefined) {
id = `s${states.length}`;
index.set(k, id);
states.push({
id,
snapshot: item.snapshot,
configuration: item.configuration,
context: item.context,
initial,
boundary: !inDomain(rules.domains, item.context),
steps: [],
resolvedStart: false, // reached at startup without any guard assumption or unresolved assignment
unknownStart: false,
});
}
if (initial) states[Number(id.slice(1))].initial = true;
return id;
};
const byId = (id) => states[Number(id.slice(1))];
let complete = true;
let incompleteReason;
// Guard replay can grow exponentially before the first settled state exists.
let startupReplays = 0;
const canReplay = () => {
if (startupReplays >= rules.bounds.maxStates || states.length >= rules.bounds.maxStates) {
complete = false;
incompleteReason = `startup exploration hit maxStates replay budget (${rules.bounds.maxStates})`;
return false;
}
if (rules.bounds.timeoutMs && clock() - started > rules.bounds.timeoutMs) {
complete = false;
incompleteReason = `startup exploration hit the ${rules.bounds.timeoutMs} ms time limit`;
return false;
}
startupReplays++;
return true;
};
for (const context of initialContexts) {
for (const start of engine.initial(context, { canReplay })) {
const id = intern(start, true);
if (!start.unresolved) byId(id).resolvedStart = true;
if (start.unknownContext) byId(id).unknownStart = true;
}
if (!complete) break;
}
const eventAlphabet = model.events;
const timedOut = () => rules.bounds.timeoutMs && clock() - started > rules.bounds.timeoutMs;
// Unresolved guards in many parallel regions split one step 2^n ways, so each step gets
// its own replay budget and the deadline is checked on every replay.
let stepReplays = 0;
let stepCut = false;
const canStepReplay = () => {
if (stepReplays >= MAX_STEP_REPLAYS) {
stepCut = true;
complete = false;
incompleteReason = `one step needed more than ${MAX_STEP_REPLAYS} guard case-split replays after ${states.length} states`;
return false;
}
if (timedOut()) {
stepCut = true;
complete = false;
incompleteReason = `exploration hit the ${rules.bounds.timeoutMs} ms time limit after ${states.length} states`;
return false;
}
stepReplays++;
return true;
};
explore: for (let cursor = 0; cursor < states.length; cursor++) {
const state = states[cursor];
if (states.length > rules.bounds.maxStates) {
complete = false;
incompleteReason = `exploration hit maxStates (${rules.bounds.maxStates})`;
break;
}
if (state.boundary) continue;
if (timedOut()) {
complete = false;
incompleteReason = `exploration hit the ${rules.bounds.timeoutMs} ms time limit after ${states.length} states`;
break;
}
const stepKeys = new Set();
for (const event of eventAlphabet) {
const payloads = rules.events[event] ?? [undefined];
for (const payload of payloads) {
stepReplays = 0;
for (const result of engine.step(state, event, payload, { canReplay: canStepReplay })) {
const to = intern(result);
const label = payload === undefined ? event : `${event} ${JSON.stringify(payload)}`;
const stepKey = JSON.stringify([to, label, result.edgeIds]);
if (stepKeys.has(stepKey)) continue;
stepKeys.add(stepKey);
state.steps.push({ to, event: label, eventType: event, edgeIds: result.edgeIds, unresolved: result.unresolved });
}
// Only this step's own cutoff stops here; an earlier startup cutoff keeps exploring.
if (stepCut) break explore;
}
}
// A state cut off mid-expansion has partial steps, so it is not evidence of a dead end.
state.expanded = true;
}
const explored = states;
// Rule evaluation has its own timeoutMs window. Every state visit and predicate
// evaluation checks it, so one expensive rule cannot overrun the window.
const RULE_DEADLINE = Symbol('rule deadline');
let ruleDeadline = Infinity;
const tick = () => {
if (clock() > ruleDeadline) throw RULE_DEADLINE;
};
const evalIn = (state, expression) => {
tick();
try {
return Boolean(evaluate(expression, engine.scope(state.configuration, state.context, undefined)));
} catch (error) {
if (error instanceof Unresolved) return null;
throw error;
}
};
const describe = (state) => ({ state: state.configuration.map((id) => model.nodes.get(id).path.join('.')), ...project(state.context) });
const isTerminalFinal = (state) =>
state.configuration.every((id) => {
const node = model.nodes.get(id);
return node.type === 'final' && (node.parentId === model.root.id || node.parentId === null);
});
const enabledEvents = (state) => new Set(state.steps.map((step) => step.eventType));
/** Under per-event weak fairness an infinite loop must not keep an enabled event waiting forever. */
const fairLoop = (members) => {
if (rules.fairness.kind !== 'events') return true;
const taken = new Set();
for (const id of members) for (const step of byId(id).steps) if (members.has(step.to)) taken.add(step.eventType);
return rules.fairness.events.every((event) => taken.has(event) || [...members].some((id) => !enabledEvents(byId(id)).has(event)));
};
const shortestPath = (targetPredicate, resolvedOnly = false, from = null) => {
const parent = new Map();
const queue = (from ?? explored.filter((state) => state.initial).map((state) => state.id)).filter(
(id) => !(resolvedOnly && from === null && !byId(id).resolvedStart),
);
for (const id of queue) parent.set(id, null);
while (queue.length) {
tick();
const id = queue.shift();
if (targetPredicate(byId(id))) {
const path = [];
for (let current = id; current !== null; current = parent.get(current)?.from ?? null) path.unshift(current);
return path;
}
for (const step of byId(id).steps)
if (!parent.has(step.to) && !(resolvedOnly && step.unresolved))
parent.set(step.to, { from: id, step }), queue.push(step.to);
}
return null;
};
/** A cycle inside `members` starting and ending at `entry`. */
const cycleFrom = (entry, members) => {
const parent = new Map([[entry, null]]);
const queue = [entry];
while (queue.length) {
tick();
const id = queue.shift();
for (const step of byId(id).steps) {
if (!members.has(step.to)) continue;
if (step.to === entry) {
const path = [];
for (let current = id; current !== null; current = parent.get(current)) path.unshift(current);
return [...path, entry];
}
if (!parent.has(step.to)) parent.set(step.to, id), queue.push(step.to);
}
}
return null;
};
/**
* Lasso search for liveness: from `startIds` through `inside` states, find a run that
* stays inside forever and whose loop satisfies `loopBad`. Returns { path, loopStart,
* stutters } with path from an initial state, or null.
*/
const lasso = (startIds, inside, loopBad = () => true) => {
const region = new Set();
const queue = [...startIds].filter((id) => inside(byId(id)));
for (const id of queue) region.add(id);
while (queue.length) {
tick();
const id = queue.shift();
for (const step of byId(id).steps) if (inside(byId(step.to)) && !region.has(step.to)) region.add(step.to), queue.push(step.to);
}
const reachable = (id) => region.has(id);
if (rules.fairness.kind === 'none') {
const path = shortestPath((state) => reachable(state.id) && !state.boundary && loopBad(new Set([state.id])));
return path && { path, loopStart: path.length - 1, stutters: true, stuck: false };
}
const dead = shortestPath((state) => reachable(state.id) && state.expanded && !state.boundary && !state.steps.length && loopBad(new Set([state.id])));
if (dead) return { path: dead, loopStart: dead.length - 1, stutters: true, stuck: true };
const bad = components(byId, [...region], (state) => reachable(state.id) && !state.boundary)
.filter((component) => component.nontrivial && loopBad(component.members) && fairLoop(component.members));
let best = null;
for (const component of bad) {
tick();
const prefix = shortestPath((state) => component.members.has(state.id));
if (!prefix || (best && prefix.length >= best.prefix.length)) continue;
best = { prefix, component };
}
if (!best) return null;
const entry = best.prefix.at(-1);
const cycle = cycleFrom(entry, best.component.members);
return { path: [...best.prefix.slice(0, -1), ...cycle], loopStart: best.prefix.length - 1, stutters: false, stuck: false };
};
const edgeBetween = (from, to) =>
byId(from).steps.find((step) => step.to === to && !step.unresolved) ?? byId(from).steps.find((step) => step.to === to);
const ruleResults = [];
const counterexamples = [];
let counterexampleSteps = 0;
const omittedViolations = []; // [stateId, ruleId] for broken rules whose trace was omitted
const anyUnresolved = diagnostics.unresolvedGuards.size + diagnostics.unresolvedActions.size > 0;
// Unresolved guards are explored both ways (a true over-approximation, so safety that holds
// is sound). An unresolved assignment keeps the old value, which under-approximates: no
// safety verdict of holds is sound after one.
const underApproximated = diagnostics.unresolvedActions.size > 0;
const ruleKind = (rule) => (rule.kind === 'never' || rule.kind === 'initially' ? 'invariant' : rule.kind === 'no-dead-ends' ? 'deadlock' : 'property');
const emit = (rule, outcome, reason, path) => {
const entry = {
id: `${ruleKind(rule)}:${rule.id}`,
kind: ruleKind(rule),
name: rule.id,
outcome,
...(rule.description ? { description: rule.description } : {}),
...(reason ? { reason } : {}),
nativeKind: rule.kind,
};
ruleResults.push(entry);
if (path && outcome === 'broken' && counterexampleSteps + path.path.length > MAX_COUNTEREXAMPLE_STEPS) {
entry.reason = `${reason ? `${reason}; ` : ''}counterexample omitted: stored counterexamples reached the ${MAX_COUNTEREXAMPLE_STEPS}-state budget`;
omittedViolations.push([path.path.at(-1), entry.id]);
return entry;
}
if (path && outcome === 'broken') {
counterexampleSteps += path.path.length;
const transitions = [];
for (let i = 0; i + 1 < path.path.length; i++) {
const step = edgeBetween(path.path[i], path.path[i + 1]);
transitions.push(stepId(path.path[i], step));
}
counterexamples.push({
id: `counterexample_${counterexamples.length}`,
ruleId: entry.id,
states: path.path,
transitions,
...(path.loopStart !== undefined ? { loopStart: path.loopStart } : {}),
...(path.stutters !== undefined ? { stutters: path.stutters } : {}),
});
}
return entry;
};
const stepId = (from, step) => `${from}>${step.to}:${step.event}:${step.edgeIds.join('+')}`;
const unresolvedNote = () =>
`unresolved guards/actions: ${[...diagnostics.unresolvedGuards, ...diagnostics.unresolvedActions].join('; ')}`;
const undecidable = (expression) => explored.some((state) => evalIn(state, expression) === null);
// Rule evaluation gets its own timeoutMs window so a slow exploration still leaves
// time to report the rules it can decide.
if (rules.bounds.timeoutMs) ruleDeadline = clock() + rules.bounds.timeoutMs;
let ruleIncompleteReason;
for (const rule of rules.rules) {
if (!ruleIncompleteReason && clock() > ruleDeadline)
ruleIncompleteReason = `rule evaluation hit the ${rules.bounds.timeoutMs} ms time limit`;
if (ruleIncompleteReason) {
emit(rule, 'not-checked', ruleIncompleteReason);
continue;
}
try {
if (rule.kind === 'never') {
const forbidden = (state) => evalIn(state, rule.then) === true;
// A fully resolved path proves the violation even when a shorter uncertain path exists.
const certain = shortestPath(forbidden, true);
const path = certain ?? shortestPath(forbidden);
if (certain) emit(rule, 'broken', undefined, { path: certain });
else if (path) emit(rule, 'not-checked', `a path reaches the forbidden condition but crosses ${unresolvedNote()}; it may be spurious`);
else if (undecidable(rule.then)) emit(rule, 'not-checked', 'the predicate references unknown variables in some state');
else if (!complete) emit(rule, 'not-checked', incompleteReason);
else if (underApproximated) emit(rule, 'not-checked', `an unresolved assignment kept a stale value; ${unresolvedNote()}`);
else emit(rule, 'holds', anyUnresolved ? `holds under over-approximation of ${unresolvedNote()}` : undefined);
} else if (rule.kind === 'initially') {
const initials = explored.filter((state) => state.initial);
const values = initials.map((state) => evalIn(state, rule.then));
if (values.includes(null)) emit(rule, 'not-checked', 'the predicate references unknown variables in an initial state');
else {
const failing = initials.filter((_, index) => values[index] === false);
const certain = failing.find((state) => state.resolvedStart);
if (certain) emit(rule, 'broken', 'an initial state does not satisfy the condition', { path: [certain.id] });
else if (failing.length) emit(rule, 'not-checked', `only an initial state reached through ${unresolvedNote()} fails the condition; it may be spurious`);
else if (!complete) emit(rule, 'not-checked', incompleteReason);
else if (initials.some((state) => state.unknownStart)) emit(rule, 'not-checked', `an unresolved startup assignment kept a stale value; ${unresolvedNote()}`);
else emit(rule, 'holds');
}
} else if (rule.kind === 'reachable') {
const goal = (state) => evalIn(state, rule.then) === true;
if (undecidable(rule.then)) {
emit(rule, 'not-checked', 'the predicate references unknown variables in some state');
continue;
}
const certain = shortestPath(goal, true);
const path = certain ?? shortestPath(goal);
if (certain) emit(rule, 'holds');
else if (path) emit(rule, 'not-checked', `only reached through ${unresolvedNote()}`);
else if (!complete || anyUnresolved) emit(rule, 'not-checked', complete ? unresolvedNote() : incompleteReason);
else emit(rule, 'broken', 'no reachable state satisfies the condition');
} else if (rule.kind === 'no-dead-ends') {
const path = shortestPath((state) => state.expanded && !state.boundary && !state.steps.length && !(rule.allowFinal && isTerminalFinal(state)));
if (path) {
if (anyUnresolved) emit(rule, 'not-checked', `a dead end was found but ${unresolvedNote()}`);
else emit(rule, 'broken', undefined, { path, loopStart: path.length - 1, stutters: true });
} else if (!complete || anyUnresolved) emit(rule, 'not-checked', complete ? unresolvedNote() : incompleteReason);
else emit(rule, 'holds');
} else if (rule.kind === 'eventually' || rule.kind === 'leads-to' || rule.kind === 'eventually-always') {
if (!complete) {
emit(rule, 'not-checked', incompleteReason);
continue;
}
if (anyUnresolved) {
emit(rule, 'not-checked', `liveness needs fully resolved guards and actions; ${unresolvedNote()}`);
continue;
}
if (undecidable(rule.then) || (rule.when && undecidable(rule.when))) {
emit(rule, 'not-checked', 'the predicate references unknown variables in some state');
continue;
}
const goal = (state) => evalIn(state, rule.then) === true;
const startIds =
rule.kind === 'leads-to'
? explored.filter((state) => evalIn(state, rule.when) === true).map((state) => state.id)
: explored.filter((state) => state.initial).map((state) => state.id);
const found =
rule.kind === 'eventually-always'
? // <>[]P fails on a run that keeps leaving P: a loop or dead end with some state outside P.
lasso(startIds, () => true, (members) => [...members].some((id) => !goal(byId(id))))
: lasso(startIds, (state) => !goal(state));
if (!found) {
emit(rule, 'holds');
continue;
}
const prefix = rule.kind === 'leads-to' ? shortestPath((state) => state.id === found.path[0]) : [found.path[0]];
const path = [...prefix.slice(0, -1), ...found.path];
const loopStart = found.loopStart + prefix.length - 1;
emit(
rule,
'broken',
found.stutters
? found.stuck
? 'the path ends in a dead end and stutters forever'
: 'without fairness the path may stutter forever here'
: 'the path loops forever without satisfying the rule',
{ path, loopStart, stutters: found.stutters },
);
}
} catch (error) {
if (error !== RULE_DEADLINE) throw error;
// Discard this rule's partial work; rules already decided keep their verdicts.
ruleIncompleteReason = `rule evaluation hit the ${rules.bounds.timeoutMs} ms time limit`;
emit(rule, 'not-checked', ruleIncompleteReason);
}
}
const elapsedMs = clock() - started;
const transitions = [];
const transitionIds = new Set();
for (const state of explored)
for (const step of state.steps) {
const id = stepId(state.id, step);
if (transitionIds.has(id)) continue;
transitionIds.add(id);
transitions.push({ id, from: state.id, to: step.to, action: step.event, label: step.event, eventType: step.eventType, edgeIds: step.edgeIds, unresolved: step.unresolved });
}
const brokenRules = new Map();
for (const path of counterexamples)
for (const id of path.states.slice(-1)) brokenRules.set(id, [...(brokenRules.get(id) ?? []), path.ruleId]);
for (const [id, ruleId] of omittedViolations) brokenRules.set(id, [...(brokenRules.get(id) ?? []), ruleId]);
const fairnessText =
rules.fairness.kind === 'none'
? 'No fairness: any state may stutter forever, so liveness breaks at the first state where the goal does not hold.'
: rules.fairness.kind === 'events'
? `Weak fairness on every transition plus per-event weak fairness for ${rules.fairness.events.join(', ')}: a loop that keeps one of these events enabled must take it.`
: 'Weak fairness: a run never stutters forever while some transition is enabled. Liveness counterexamples are real-step loops or dead ends.';
const assumptions = [
'Every external event may occur in any state; unhandled events are ignored. Delays, actor completions and errors are modeled as nondeterministic events.',
'Statechart semantics are XState v6 (pure transition functions). Guards and actions are evaluated only through the expressions supplied in the rules file; inline code is not executed.',
fairnessText,
'Bounded context domains act as constraints: a state outside its domain is recorded but not explored further.',
...(Object.keys(extracted.guards).length + Object.keys(extracted.actions).length
? [`Inline implementations used from the model: guards ${Object.keys(extracted.guards).join(', ') || 'none'}; actions ${Object.keys(extracted.actions).map((name) => name.split(':')[0]).join(', ') || 'none'}. Explicit rules-file expressions take precedence.`]
: []),
...(extracted.skipped.length ? [`Inline code outside the supported expression subset stays unresolved: ${extracted.skipped.join('; ')}`] : []),
...(anyUnresolved ? [`Unresolved guards/actions explored both ways (over-approximation): ${unresolvedNote()}`] : []),
...(fromModel ? ["Rules come from the model's acceptance criteria; context domains from its context schema."] : []),
...rules.assumptions,
];
const result = parseCheckResult({
schemaVersion: 'stately.check-result.v1',
kind: explored.length ? 'explored-configurations' : 'summary-only',
binding: {
artifacts: [
artifact('model', modelPath, modelContent ?? JSON.stringify(modelInput, null, 2) + '\n'),
...(fromModel ? [] : [artifact('scope', rulesPath, rulesContent ?? JSON.stringify(rulesInput, null, 2) + '\n')]),
],
},
checker: {
name: CHECKER_NAME,
version: CHECKER_VERSION,
command: fromModel ? ['native-check', modelPath] : ['native-check', modelPath, rulesPath],
complete,
bounds: {
maxStates: rules.bounds.maxStates,
domain: rules.domains,
fairness: rules.fairness.kind === 'events' ? rules.fairness.events : rules.fairness.kind,
events: eventAlphabet,
exploredStates: explored.length,
...(incompleteReason ? { incompleteReason } : {}),
...(ruleIncompleteReason ? { ruleIncompleteReason } : {}),
boundaryStates: explored.filter((state) => state.boundary).length,
transitions: transitions.length,
elapsedMs: Math.round(elapsedMs * 100) / 100,
engine: `xstate@${engine.xstate.version ?? 'v6'}`,
},
assumptions,
checkedAt: new Date().toISOString(),
},
rules: ruleResults,
states: explored.map((state) => ({
id: state.id,
variables: describe(state),
initial: state.initial,
violations: brokenRules.get(state.id)?.filter((ruleId) => ruleId.startsWith('invariant:')) ?? [],
nodeIds: state.configuration,
boundary: { past: false, excluded: state.boundary },
})),
transitions,
counterexamples,
uncitedConditions: uncitedConditions(model, rules.citations),
});
return { result, model, rules, diagnostics, elapsedMs };
}
// ---------------------------------------------------------------------------
// Native graph with the attached report.
// ---------------------------------------------------------------------------
function modelToXGraph(modelInput, model) {
if (Array.isArray(modelInput.nodes)) return structuredClone(modelInput);
const nodes = [...model.nodes.values()].map((node) => ({
id: node.id,
parentId: node.parentId,
data: {
key: node.key,
...(node.type === 'parallel' ? { type: 'parallel' } : node.type === 'final' ? { type: 'final' } : {}),
...(node.type === 'compound' ? { initialId: node.initialId } : {}),
},
}));
const edges = model.edges.map((edge) => ({
id: edge.id,
sourceId: edge.sourceId,
targetId: edge.targetIds[0] ?? edge.sourceId,
data: {
eventType: edge.eventType || 'xstate.always',
...(edge.targetIds.length > 1 ? { additionalTargetIds: edge.targetIds.slice(1) } : {}),
...(edge.guard ? { guard: edge.guard } : {}),
...(edge.actions.length ? { actions: edge.actions } : {}),
...(edge.targetIds.length ? {} : { transitionType: 'targetless' }),
},
}));
return { id: model.root.id, nodes, edges, annotations: [], data: {} };
}
const uncitedSummary = ({ uncitedConditions: uncited = [] }) =>
uncited.length
? ` ${uncited.length} guarded ${uncited.length === 1 ? 'transition has' : 'transitions have'} no source citation, so verdicts that depend on ${uncited.length === 1 ? 'it are' : 'them are'} unconfirmed against the application.`
: '';
const conditionText = (item) => `${item.guard ?? '(unnamed guard)'} on ${item.eventType} from ${item.source} (edge ${item.edgeId})`;
/** The check report for a run, independent of any graph; `nativeGraph` attaches it. */
export function checkReport({ result }, { summary } = {}) {
const states = new Map(result.states.map((state) => [state.id, state]));
const steps = new Map(result.transitions.map((step) => [step.id, step]));
const traces = result.counterexamples.map((trace) => ({
id: trace.id,
ruleId: trace.ruleId,
states: trace.states.map((id) => ({ rawStateId: id, nodeIds: states.get(id).nodeIds, variables: states.get(id).variables })),
steps: trace.transitions.map((id) => {
const step = steps.get(id);
return { id, action: step.action, edgeIds: step.edgeIds, eventTypes: [step.eventType], targetNodeIds: states.get(step.to).nodeIds };
}),
...(trace.loopStart !== undefined ? { loopStart: trace.loopStart } : {}),
...(trace.stutters !== undefined ? { stutters: trace.stutters } : {}),
}));
const counts = (outcome) => result.rules.filter((rule) => rule.outcome === outcome).length;
return {
schemaVersion: 'stately.check-report.v1',
runId: `run_${sha256(JSON.stringify([result.binding.artifacts.map((a) => a.sha256), result.rules])).slice(0, 24)}`,
status: result.rules.some((rule) => rule.outcome === 'not-checked') || !result.checker.complete ? 'incomplete' : 'complete',
checker: {
name: result.checker.name,
version: result.checker.version,
complete: result.checker.complete,
bounds: result.checker.bounds,
assumptions: result.checker.assumptions,
},
rules: result.rules.map(({ nativeKind, ...rule }) => rule),
traces,
artifacts: result.binding.artifacts.map(({ role, path, sha256 }) => ({ role, path, sha256 })),
documents: [],
uncitedConditions: result.uncitedConditions ?? [],
summary:
summary ??
`${CHECKER_NAME} explored ${result.states.length} configurations and ${result.transitions.length} steps over the native model. ${counts('holds')} rules hold, ${counts('broken')} broken, ${counts('not-checked')} not checked.${uncitedSummary(result)} Model checks do not prove application behavior.`,
checkedAt: result.checker.checkedAt,
applicationChecks: [],
};
}
export function nativeGraph(run, modelInput, { summary } = {}) {
const { result, model } = run;
const graph = modelToXGraph(modelInput, model);
graph.data ??= {};
graph.data.meta ??= {};
// The editor stores an explicit 'normal' type on every ordinary state; the view digest
// must be computed over that form or the Checks panel reports the view as stale.
for (const node of graph.nodes) if (node.data.type == null) node.data.type = 'normal';
const report = checkReport(run, { summary });
graph.data.meta['@statelyai.checkBinding'] = { artifacts: report.artifacts };
graph.data.meta['@statelyai.checkSummary'] = {
schemaVersion: result.schemaVersion,
checker: result.checker.name,
version: result.checker.version,
complete: result.checker.complete,
bounds: result.checker.bounds,
assumptions: result.checker.assumptions,
rules: report.rules,
states: result.states.length,
transitions: result.transitions.length,
partial: false,
};
for (const node of graph.nodes) {
const broken = report.traces.filter((trace) => trace.states.at(-1).nodeIds.includes(node.id) && trace.ruleId.startsWith('invariant:'));
if (broken.length) node.data.color = 'red';
}
return attachReport(graph, report);
}
export function humanReport({ result }) {
const lines = [`# ${CHECKER_NAME} ${CHECKER_VERSION}`, ''];
lines.push(
`Explored ${result.states.length} configurations and ${result.transitions.length} steps in ${result.checker.bounds.elapsedMs} ms (complete: ${result.checker.complete}).`,
'',
);
const states = new Map(result.states.map((state) => [state.id, state]));
for (const rule of result.rules) {
lines.push(`## ${rule.name} (${rule.nativeKind}): ${rule.outcome}`);
if (rule.reason) lines.push(rule.reason);
for (const trace of result.counterexamples.filter((item) => item.ruleId === rule.id)) {
const steps = new Map(result.transitions.map((step) => [step.id, step]));
trace.states.forEach((id, index) => {
const variables = states.get(id).variables;
const marker = trace.loopStart === index ? ' <- loop' : '';
const via = index ? ` (${steps.get(trace.transitions[index - 1]).action})` : '';
lines.push(`${index}.${via} ${JSON.stringify(variables)}${marker}`);
});
if (trace.stutters) lines.push(' ... stutters');
}
lines.push('');
}
lines.push('## Assumptions', '', ...result.checker.assumptions.map((item) => `- ${item}`), '');
const uncited = result.uncitedConditions ?? [];
lines.push(
'## Uncited conditions',
'',
...(uncited.length
? [
'These guards have no source citation in the rules file. A rule that holds is unconfirmed until each condition it depends on is checked against the application.',
'',
...uncited.map((item) => `- ${conditionText(item)}`),
]
: ['Every guarded transition has a source citation.']),
'',
);
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// CLI: node native-check.mjs MODEL.json RULES.json --out DIR [--json]
// ---------------------------------------------------------------------------
/** The checksum-verified XState copy from the Stately cache, downloaded on first use. */
export async function loadCachedXState({ offline = false, progress = (line) => console.error(line) } = {}) {
const { ensureXState } = await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ './toolchain.mjs');
const ensured = await ensureXState({ offline, progress });
const xstate = await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ pathToFileURL(ensured.file).href);
return { ...xstate, version: ensured.version };
}
export async function main(argv) {
const { values, positionals } = parseArgs({
args: argv,
allowPositionals: true,
options: { out: { type: 'string' }, json: { type: 'boolean' }, offline: { type: 'boolean' } },
});
// Without RULES.json, the rules on the model's acceptance criteria are checked.
if (positionals.length < 1 || positionals.length > 2) fail('usage: native-check MODEL.json [RULES.json] --out DIR');
const [modelPath, rulesPath] = positionals;
const modelContent = await readFile(modelPath, 'utf8');
const rulesContent = rulesPath === undefined ? undefined : await readFile(rulesPath, 'utf8');
const run = check({
model: JSON.parse(modelContent),
rules: rulesContent === undefined ? undefined : JSON.parse(rulesContent),
modelContent,
rulesContent,
modelPath: basename(modelPath),
...(rulesPath === undefined ? {} : { rulesPath: basename(rulesPath) }),
xstate: await loadCachedXState({ offline: values.offline === true }),
});
const graph = nativeGraph(run, JSON.parse(modelContent));
if (values.out) {
await mkdir(values.out, { recursive: true });
await writeFile(join(values.out, 'check-result.json'), JSON.stringify(run.result, null, 2) + '\n');
await writeFile(join(values.out, 'graph.json'), JSON.stringify(graph, null, 2) + '\n');
await writeFile(join(values.out, 'check-report.json'), JSON.stringify(graph.data.meta['@statelyai.checkReport'], null, 2) + '\n');
await writeFile(join(values.out, 'report.md'), humanReport(run));
}
if (values.json)
console.log(JSON.stringify({ rules: run.result.rules, states: run.result.states.length, transitions: run.result.transitions.length, elapsedMs: run.result.checker.bounds.elapsedMs, out: values.out }, null, 2));
else process.stdout.write(humanReport(run));
return nativeCheckExitCode(run.result);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(error.message);
process.exit(2);
},
);.tessl-plugin
agents
references
scripts
engine