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

infer-view.mjsscripts/

/**
 * Infers a projection view (`state(vars)`) for a TLA+ specification so its TLC
 * state graph draws as a statechart over the spec's control variables instead
 * of one node per raw configuration. The result is an ordinary view file that
 * `stately-check check SPEC.tla --view FILE` consumes; the engine still checks
 * projection consistency and falls back to parent states when regions lie.
 */

import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';

/** Removes `\*` line comments and nested `(* *)` block comments, keeping strings. */
export function stripComments(source) {
  let out = '';
  let depth = 0;
  for (let i = 0; i < source.length; i++) {
    const c = source[i];
    const next = source[i + 1];
    if (depth === 0 && c === '"') {
      let j = i + 1;
      while (j < source.length && source[j] !== '"' && source[j] !== '\n')
        j += source[j] === '\\' ? 2 : 1;
      out += source.slice(i, j + 1);
      i = j;
    } else if (c === '(' && next === '*') {
      depth++;
      i++;
    } else if (depth > 0 && c === '*' && next === ')') {
      depth--;
      i++;
    } else if (depth > 0) {
      if (c === '\n') out += '\n';
    } else if (c === '\\' && next === '*') {
      while (i < source.length && source[i] !== '\n') i++;
      out += '\n';
    } else out += c;
  }
  return out;
}

/** Declared state variables, in declaration order. */
export function declaredVariables(source) {
  const names = [];
  const pattern =
    /\bVARIABLES?\b\s+([A-Za-z_][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z_][A-Za-z0-9_]*)*)/g;
  for (const match of stripComments(source).matchAll(pattern))
    for (const name of match[1].split(','))
      if (!names.includes(name.trim())) names.push(name.trim());
  return names;
}

const STRING = '"(?:[^"\\\\\\n]|\\\\.)*"';
const STRINGS = new RegExp(STRING, 'g');

/**
 * The specification followed by every local module it EXTENDS, transitively,
 * so variables declared in an extended module are visible to inference.
 */
export function readSpecSources(file) {
  const seen = new Set();
  const sources = [];
  const visit = (path) => {
    if (seen.has(path) || !existsSync(path)) return;
    seen.add(path);
    const source = readFileSync(path, 'utf8');
    sources.push(source);
    for (const [, list] of stripComments(source).matchAll(
      /\bEXTENDS\b\s+([A-Za-z_][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z_][A-Za-z0-9_]*)*)/g,
    ))
      for (const name of list.split(','))
        visit(join(dirname(path), `${name.trim()}.tla`));
  };
  visit(file);
  return sources.join('\n');
}

/** Code with comments removed and string contents blanked, for evidence matching. */
const evidenceCode = (source) => stripComments(source).replace(STRINGS, '""');

/**
 * Model values a TLC configuration binds: `C = C`, `C = [model value]`, and
 * members of model-value sets such as `RM = {r1, r2}`.
 */
export function modelValues(config = '') {
  const values = new Set();
  const code = config.replace(/\\\*[^\n]*/g, '').replace(/\(\*[\s\S]*?\*\)/g, '');
  for (const [, name, value] of code.matchAll(
    /\b([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(\[\s*model value\s*\]|\{[^}]*\}|[A-Za-z_][A-Za-z0-9_]*)/g,
  )) {
    if (value === name || value.startsWith('[')) values.add(name);
    else if (value.startsWith('{'))
      for (const member of value.slice(1, -1).split(','))
        if (identifier.test(member.trim())) values.add(member.trim());
  }
  return [...values];
}

/**
 * How a variable is compared with or assigned string literals or model
 * values: `scalar` for `v = "x"`, `v' = "x"`, `v \in {"x", ...}`; `function` for
 * `v[k] = "x"`, `[v EXCEPT ![k] = "x"]`, `v = [k \in S |-> "x"]`; `fields` for
 * `v.f = "x"`, `[v EXCEPT !.f = "x"]`, `v = [f |-> "x", ...]`.
 */
export function stringEvidence(source, name, { models = [] } = {}) {
  const code = evidenceCode(source);
  // A record field selector such as `msg.pc` is not the variable `pc`.
  const v = `(?<![.\\w])${name}\\b`;
  const literal = models.length
    ? `(?:${STRING}|\\b(?:${models.join('|')})\\b(?!\\s*[\\[.(]))`
    : STRING;
  const count = (pattern) =>
    [...code.matchAll(new RegExp(pattern, 'g'))].length;
  const scalar =
    count(`${v}'?(?![.\\[])\\s*(?:=|#|/=)\\s*${literal}`) +
    count(`${v}'?\\s*\\\\in\\s*\\{\\s*${literal}`) +
    count(`${literal}\\s*(?:=|#|/=)\\s*${v}(?!\\s*[\\[.])`);
  const fn =
    count(`${v}'?\\s*\\[[^\\]\\n]*\\]\\s*(?:=|#|/=)\\s*${literal}`) +
    count(`${v}\\s*\\[[^\\]\\n]*\\]\\s*\\\\in\\s*\\{\\s*${literal}`) +
    count(`\\[\\s*${name}\\s+EXCEPT\\s+!\\[[^\\]]*\\]\\s*=\\s*${literal}`) +
    count(`${v}'?\\s*=\\s*\\[[^\\]|]*\\\\in[^\\]|]*\\|->\\s*(?:CASE\\b[^\\]]*?->\\s*)?${literal}`);
  const fields = {};
  const add = (field) => (fields[field] = (fields[field] ?? 0) + 1);
  for (const [, field] of code.matchAll(
    new RegExp(`${v}'?\\.(\\w+)\\s*(?:=|#|/=)\\s*${literal}`, 'g'),
  ))
    add(field);
  for (const [, field] of code.matchAll(
    new RegExp(`${v}'?\\.(\\w+)\\s*\\\\in\\s*\\{\\s*${literal}`, 'g'),
  ))
    add(field);
  for (const [except] of code.matchAll(
    new RegExp(`\\[\\s*${name}\\s+EXCEPT\\s+[^\\]]*`, 'g'),
  ))
    for (const [, field] of except.matchAll(
      new RegExp(`!\\.(\\w+)\\s*=\\s*(?:IF\\b[^\\n]*?THEN\\s*)?${literal}`, 'g'),
    ))
      add(field);
  for (const [record] of code.matchAll(
    new RegExp(`${v}'?\\s*=\\s*\\[(?![^\\]]*\\\\in)[^\\]]*\\]`, 'g'),
  ))
    for (const [, field] of record.matchAll(
      new RegExp(`(\\w+)\\s*\\|->\\s*${literal}`, 'g'),
    ))
      add(field);
  return { scalar, function: fn, fields };
}

const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/;

const strongestField = (fields) =>
  Object.entries(fields).sort((a, b) => b[1] - a[1])[0];

/** The control shape a variable's evidence supports. */
function controlOf(name, evidence, field) {
  if (field) return { name, kind: 'field', field };
  const best = strongestField(evidence.fields);
  if (best && best[1] > evidence.scalar && best[1] >= evidence.function)
    return { name, kind: 'field', field: best[0] };
  return {
    name,
    kind: evidence.function > evidence.scalar ? 'function' : 'scalar',
  };
}

/**
 * Chooses the control variables: `pc` when the spec has one (PlusCal), else
 * every variable compared with string literals or model values, unless
 * `state` names them (`var` or `var.field`).
 */
export function inferControl(source, { state, config } = {}) {
  const variables = declaredVariables(source);
  if (!variables.length)
    throw Error('No VARIABLE or VARIABLES declaration found in the specification.');
  const models = modelValues(config);
  const evidence = Object.fromEntries(
    variables.map((name) => [name, stringEvidence(source, name, { models })]),
  );
  const total = ({ scalar, function: fn, fields }) =>
    scalar + fn + Object.values(fields).reduce((sum, n) => sum + n, 0);
  let control;
  if (state?.length) {
    const unknown = state.filter(
      (item) => !variables.includes(item.split('.')[0]),
    );
    if (unknown.length)
      throw Error(
        `Not a declared variable: ${unknown.join(', ')}. Declared: ${variables.join(', ')}.`,
      );
    control = state.map((item) => {
      const [name, field, extra] = item.split('.');
      if (extra !== undefined || (field !== undefined && !identifier.test(field)))
        throw Error(`Pass --state as VAR or VAR.FIELD: ${item}`);
      return controlOf(name, evidence[name], field);
    });
  } else if (variables.includes('pc')) {
    // PlusCal: labels can come from named operators, so pc wins without string evidence.
    control = [
      total(evidence.pc) > 0
        ? controlOf('pc', evidence.pc)
        : {
            name: 'pc',
            kind: /(?<![.\w])pc\s*\[/.test(evidenceCode(source))
              ? 'function'
              : 'scalar',
          },
    ];
  } else {
    const strung = variables.filter((name) => total(evidence[name]) > 0);
    control = strung.map((name) => controlOf(name, evidence[name]));
  }
  if (!control.length)
    throw Error(
      `No control variable found: no variable is compared with a string literal or model value. Pass --state with one or more of: ${variables.join(', ')}.`,
    );
  for (const { name } of control)
    if (!identifier.test(name)) throw Error(`Invalid variable name: ${name}`);
  return { variables, control, evidence };
}

/** View module source for the chosen control variables. */
export function viewSource({ module, control }) {
  const read = ({ name, kind, field }) =>
    kind === 'field'
      ? `vars[${JSON.stringify(name)}][${JSON.stringify(field)}]`
      : `vars[${JSON.stringify(name)}]`;
  const shown = control.map(({ name, kind, field }) =>
    kind === 'field' ? `${name}.${field}` : name,
  );
  const region = ({ name, kind, field }) =>
    kind === 'function'
      ? control.length === 1
        ? `...regions(${read({ name, kind })})`
        : `...regions(${read({ name, kind })}, ${JSON.stringify(`${name} `)})`
      : `${JSON.stringify(kind === 'field' ? `${name}.${field}` : name)}: label(${read({ name, kind, field })})`;
  const [only] = control;
  const body =
    control.length === 1 && only.kind !== 'function'
      ? `label(${read(only)})`
      : `({ ${control.map(region).join(', ')} })`;
  return `// Generated by \`stately-check infer-view\` from ${module}.tla.
// Chart states come from: ${shown.join(', ')}. Every other variable stays in the
// checked configurations. Replace TLA+ names with domain words where useful.
export const title = ${JSON.stringify(module)};
const label = (value) =>
  typeof value === 'string' && value !== '' ? value : JSON.stringify(value);
const regions = (value, prefix = '') =>
  Object.fromEntries(
    Object.entries(value).map(([key, item]) => [prefix + key, label(item)]),
  );
export const state = (vars) => ${body};
`;
}

export function inferView(source, { module, state, config } = {}) {
  const name =
    module ?? stripComments(source).match(/-{4,}\s*MODULE\s+(\w+)/)?.[1];
  if (!name) throw Error('No MODULE header found in the specification.');
  const inferred = inferControl(source, { state, config });
  return { module: name, ...inferred, content: viewSource({ module: name, ...inferred }) };
}

.mcp.json

LICENSE

README.md

SKILL.md

tile.json