CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

statelyai/stately

Find implicit state machines, review state bugs, and check or visualize statecharts with Stately.

Quality

95%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Medium

Suggest reviewing before use

Overview
Quality
Evals
Security
Files

static-tla.mjsscripts/

/**
 * Static statechart extraction from TLA+ source, without running TLC.
 *
 * Reads PlusCal translations and hand-written specs whose actions guard and
 * update control variables with literals: `pc = "a" /\ pc' = "b"`,
 * `pc[self] = "a" /\ pc' = [pc EXCEPT ![self] = "b"]`, `v \in {"a", "b"}`,
 * `v # "a"`, `v.f = "a"`, `[v EXCEPT !.f = "b"]`, and IF/CASE alternatives.
 * Each top-level definition that primes a control is one action. The result
 * over-approximates reachability: it does not evaluate other variables, so a
 * transition whose guard can never hold still appears. Function-valued
 * controls (PlusCal processes) yield one region shape for every key.
 */
import { inferControl, modelValues, stripComments } from './infer-view.mjs';

const STRING = '"(?:[^"\\\\\\n]|\\\\.)*"';

const unquote = (literal) =>
  literal.startsWith('"') ? JSON.parse(literal) : literal;

/** Top-level `Name(params) == body` definitions, in source order. */
export function definitions(code) {
  const header = /^([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm;
  const found = [...code.matchAll(header)];
  return found.map((match, i) => ({
    name: match[1],
    body: code.slice(
      match.index + match[0].length,
      i + 1 < found.length ? found[i + 1].index : code.length,
    ),
  }));
}

/** Text from `start` up to the next top-level `/\` or `\/` (or the end). */
function segment(body, start) {
  let depth = 0;
  for (let i = start; i < body.length; i++) {
    const c = body[i];
    if ('([{'.includes(c)) depth++;
    else if (')]}'.includes(c)) {
      if (depth === 0) return body.slice(start, i);
      depth--;
    } else if (
      depth === 0 &&
      ((c === '/' && body[i + 1] === '\\') || (c === '\\' && body[i + 1] === '/'))
    )
      return body.slice(start, i);
  }
  return body.slice(start);
}

/** Text inside the brackets that open at `start` (exclusive). */
function bracketed(body, start) {
  let depth = 0;
  for (let i = start; i < body.length; i++) {
    if ('([{'.includes(body[i])) depth++;
    else if (')]}'.includes(body[i]) && --depth === 0)
      return body.slice(start + 1, i);
  }
  return body.slice(start + 1);
}

/** Static chart for the given or inferred control variables. */
export function staticChart(source, { config = '', state } = {}) {
  const code = stripComments(source);
  const models = modelValues(config);
  const literal = models.length
    ? `(?:${STRING}|\\b(?:${models.join('|')})\\b(?!\\s*[\\[.(]))`
    : STRING;
  const literals = (text) =>
    [...text.matchAll(new RegExp(literal, 'g'))].map(([value]) => unquote(value));
  const { control } = inferControl(source, { config, state });
  const defs = definitions(code);
  const init = defs.find((def) => def.name === 'Init');
  const regions = control.map((item) => {
    const { name, kind, field } = item;
    const v = `(?<![.\\w!])${name}`;
    const access =
      kind === 'function' ? `${v}\\s*\\[[^\\]]*\\]` : kind === 'field' ? `${v}\\.${field}\\b` : `${v}\\b`;
    const region =
      kind === 'function' ? `${name}[*]` : kind === 'field' ? `${name}.${field}` : name;
    const guards = (body) => {
      const positive = [];
      const negative = [];
      for (const m of body.matchAll(new RegExp(`${access}(?!')\\s*(=|#|/=)\\s*(${literal})`, 'g')))
        (m[1] === '=' ? positive : negative).push(unquote(m[2]));
      for (const m of body.matchAll(new RegExp(`(${literal})\\s*(=|#|/=)\\s*${access}(?!')`, 'g')))
        (m[2] === '=' ? positive : negative).push(unquote(m[1]));
      for (const m of body.matchAll(new RegExp(`${access}(?!')\\s*\\\\in\\s*\\{`, 'g')))
        positive.push(...literals(bracketed(body, m.index + m[0].length - 1)));
      return { positive, negative };
    };
    const updates = (body) => {
      const targets = [];
      const primed = new RegExp(`${v}'\\s*=\\s*`, 'g');
      for (const m of body.matchAll(primed)) {
        const rest = body.slice(m.index + m[0].length);
        const except = rest.match(new RegExp(`^\\[\\s*${name}\\s+EXCEPT\\b`));
        if (kind === 'scalar') {
          if (!except) targets.push(...literals(segment(rest, 0)));
          continue;
        }
        if (!except) continue;
        const inner = bracketed(rest, 0);
        const marker = kind === 'function' ? /!\[[^\]]*\]\s*=\s*/g : new RegExp(`!\\.${field}\\s*=\\s*`, 'g');
        for (const e of inner.matchAll(marker)) {
          const value = inner.slice(e.index + e[0].length).split(/,\s*!/)[0];
          targets.push(...literals(value));
        }
      }
      return targets;
    };
    const values = new Set();
    const initial = [];
    if (init) {
      const body = init.body;
      if (kind === 'scalar') {
        initial.push(...guards(body).positive);
      } else {
        for (const m of body.matchAll(new RegExp(`${v}\\s*=\\s*\\[`, 'g'))) {
          const inner = bracketed(body, m.index + m[0].length - 1);
          if (kind === 'function') {
            const map = inner.split('|->').slice(1).join('|->');
            initial.push(...literals(map));
          } else {
            const f = inner.match(new RegExp(`\\b${field}\\s*\\|->\\s*(${literal})`));
            if (f) initial.push(unquote(f[1]));
          }
        }
        initial.push(...guards(body).positive);
      }
    }
    initial.forEach((value) => values.add(value));
    const actions = [];
    for (const def of defs) {
      if (def === init) continue;
      const targets = updates(def.body);
      if (!targets.length) continue;
      const { positive, negative } = guards(def.body);
      actions.push({ name: def.name, positive, negative, targets });
      [...positive, ...negative, ...targets].forEach((value) => values.add(value));
    }
    const transitions = new Set();
    for (const { name: action, positive, negative, targets } of actions) {
      const sources = positive.length
        ? positive
        : [...values].filter((value) => !negative.includes(value));
      for (const from of sources)
        for (const to of targets)
          if (from !== to) transitions.add(`${region}.${from} -[${action}]-> ${region}.${to}`);
    }
    return {
      region,
      control: item,
      initial: [...new Set(initial)],
      states: [...values].map((value) => `${region}.${value}`).sort(),
      transitions: [...transitions].sort(),
    };
  });
  return {
    control,
    regions,
    states: regions.flatMap((r) => r.states).sort(),
    transitions: regions.flatMap((r) => r.transitions).sort(),
  };
}

.mcp.json

LICENSE

README.md

SKILL.md

tile.json