Skip to content

mex-memory/mex / skills/mex-statechart

mex-statechart

Verified

Explain complicated existing behavior using checked state diagrams. Use when asked for a state diagram, to diagram the previous explanation, show a bug or recovery path, compare a proposed fix or existing TLA+ spec, or derive a model from an agreed chart. Generates native Mermaid and a readable terminal fallback; optionally view and explicitly save in MEX Hub.

upstream/scripts/chart-to-tla.mjs

View on GitHub
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { parseMermaid } from "./lib.mjs";

const USAGE = "Usage: node chart-to-tla.mjs CHART.mmd --module NAME [--dir OUT]";

const args = {};
for (let i = 2; i < process.argv.length; i++) {
  const a = process.argv[i];
  if (a === "--module") args.module = process.argv[++i];
  else if (a === "--dir") args.dir = process.argv[++i];
  else if (!a.startsWith("-") && !args.chart) args.chart = a;
  else {
    console.error(`unknown argument ${a}.`);
    process.exit(2);
  }
}
if (!args.chart || !/^[A-Za-z][A-Za-z0-9_]*$/.test(args.module ?? "")) {
  console.error(USAGE);
  process.exit(2);
}
const dir = args.dir ?? path.dirname(args.chart);
const { regions, nevers } = parseMermaid(fs.readFileSync(args.chart, "utf8"));

const RESERVED = new Set(["vars", "Init", "Next", "Spec", "TypeOK", "Settled"]);
const taken = new Set(RESERVED);
function ident(words, lower) {
  const parts = words
    .normalize("NFKD")
    .replace(/[^A-Za-z0-9]+/g, " ")
    .trim()
    .split(" ")
    .filter(Boolean);
  let id =
    parts
      .map((p, i) => (lower && i === 0 ? p[0].toLowerCase() : p[0].toUpperCase()) + p.slice(1))
      .join("") || "Step";
  if (/^[0-9]/.test(id)) id = `${lower ? "r" : "S"}${id}`;
  let unique = id;
  for (let n = 2; taken.has(unique); n++) unique = `${id}${n}`;
  taken.add(unique);
  return unique;
}
const str = (s) => `"${s.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
const set = (xs) => `{${[...xs].map(str).join(", ")}}`;

const vars = Object.entries(regions).map(([name, r]) => {
  if (r.states.size === 0) throw new Error(`region ${name} has no states`);
  if (r.initial.size === 0) throw new Error(`region ${name} has no [*] --> start`);
  return { name, v: ident(name, true), ...r };
});

function guardOf(g) {
  if (!g) return null;
  const parts = Object.entries(g.states).map(([name, states]) => {
    const { v } = vars.find((x) => x.name === name);
    return states.length === 1 ? `${v} = ${str(states[0])}` : `${v} \\in ${set(states)}`;
  });
  return g.not ? `~(${parts.join(" \\/ ")})` : parts.join(" /\\ ");
}

const actions = [];
const byLabel = new Map();
for (const [ri, r] of vars.entries()) {
  for (const t of r.transitions) {
    let a = t.label ? byLabel.get(t.label) : null;
    if (!a) {
      a = { label: t.label, moves: new Map() };
      actions.push(a);
      if (t.label) byLabel.set(t.label, a);
    }
    if (!a.moves.has(ri)) a.moves.set(ri, []);
    const moves = a.moves.get(ri);
    const when = guardOf(t.guard);
    if (!moves.some((m) => m.from === t.from && m.to === t.to && m.when === when))
      moves.push({ from: t.from, to: t.to, when });
  }
}
for (const a of actions) {
  const only = a.label ? null : [...a.moves.values()][0][0];
  a.name = ident(a.label || `${only.from} to ${only.to}`, false);
}

const out = [];
const conjuncts = (lines) => lines.map((l) => `    /\\ ${l}`);
out.push(`---- MODULE ${args.module} ----`);
out.push(`\\* Generated by chart-to-tla.mjs from ${path.basename(args.chart)}.`);
out.push("\\* Each region is one variable and each transition label is one action.");
out.push("\\* Once you add guards and variables from the real code, this file is the source.");
out.push(
  `\\* statechart.mjs from-chart ${path.basename(args.chart)} keeps it, checks it, and compares it with the chart.`,
);
out.push("");
out.push(`VARIABLES ${vars.map((x) => x.v).join(", ")}`);
out.push(`vars == <<${vars.map((x) => x.v).join(", ")}>>`);
out.push("");
for (const x of vars)
  out.push(`\\* Region ${x.name}`, `${x.v}States == ${set([...x.states].sort())}`);
out.push("");
out.push("TypeOK ==", ...conjuncts(vars.map((x) => `${x.v} \\in ${x.v}States`)));
out.push("");
out.push(
  "Init ==",
  ...conjuncts(
    vars.map((x) =>
      x.initial.size === 1 ? `${x.v} = ${str([...x.initial][0])}` : `${x.v} \\in ${set(x.initial)}`,
    ),
  ),
);
const enabled = (v, m) => `${v} = ${str(m.from)}${m.when ? ` /\\ ${m.when}` : ""}`;
function whetherTakes(a, ri) {
  const { v } = vars[ri];
  const moves = a.moves.get(ri);
  if (moves.every((m) => !m.when)) {
    const from = set(new Set(moves.map((m) => m.from)));
    return { can: `${v} \\in ${from}`, cannot: `${v} \\notin ${from}` };
  }
  const any = moves.map((m) => `(${enabled(v, m)})`).join(" \\/ ");
  return { can: any, cannot: `~(${any})` };
}
for (const a of actions) {
  out.push("");
  if (a.label) out.push(`\\* ${a.label}`);
  out.push(`${a.name} ==`);
  const moving = [...a.moves.keys()];
  const shared = moving.length > 1;
  if (shared) out.push(`    /\\ (${moving.map((ri) => whetherTakes(a, ri).can).join(" \\/ ")})`);
  for (const ri of moving) {
    const { v } = vars[ri];
    const ds = a.moves.get(ri).map((m) => `(${enabled(v, m)} /\\ ${v}' = ${str(m.to)})`);
    if (shared) ds.push(`(${whetherTakes(a, ri).cannot} /\\ UNCHANGED ${v})`);
    out.push(`    /\\ \\/ ${ds[0]}`);
    for (const d of ds.slice(1)) out.push(`       \\/ ${d}`);
  }
  const still = vars.filter((_, ri) => !a.moves.has(ri)).map((x) => x.v);
  if (still.length) out.push(`    /\\ UNCHANGED <<${still.join(", ")}>>`);
}
out.push("");
out.push(actions.length ? `Next == ${actions.map((a) => a.name).join(" \\/ ")}` : "Next == FALSE");
out.push("");
out.push("Spec == Init /\\ [][Next]_vars");

function resolve(item) {
  const hits = [];
  for (const [ri, x] of vars.entries()) {
    const inside = x.states.has(item)
      ? [item]
      : [...x.states].filter((s) => s.startsWith(`${item}.`));
    if (inside.length) hits.push({ ri, inside });
  }
  if (hits.length === 0)
    throw new Error(`never line names "${item}", which is not a state in the chart`);
  if (hits.length > 1)
    throw new Error(
      `never line names "${item}", which is a state in regions ${hits.map((h) => vars[h.ri].name).join(" and ")}; rename one`,
    );
  return hits[0];
}
const invariants = [];
for (const n of nevers) {
  if (taken.has(n.name)) throw new Error(`never name ${n.name} is already used in the spec`);
  taken.add(n.name);
  const parts = n.states.map(resolve);
  const regionsUsed = new Set(parts.map((p) => p.ri));
  if (regionsUsed.size !== parts.length)
    throw new Error(
      `never ${n.name} names two states of one region; one region is in one state at a time`,
    );
  const cond = parts.map((p) =>
    p.inside.length === 1
      ? `${vars[p.ri].v} = ${str(p.inside[0])}`
      : `${vars[p.ri].v} \\in ${set(p.inside)}`,
  );
  out.push("");
  if (n.sentence) out.push(`\\* ${n.sentence}`);
  out.push(`${n.name} == ~(${cond.join(" /\\ ")})`);
  invariants.push(n.name);
}
out.push("", "====", "");

const rules = ["TypeOK", ...invariants];
const cfg = ["SPECIFICATION Spec", ...rules.map((r) => `INVARIANT ${r}`), ""];

const labels = Object.fromEntries(actions.map((a) => [a.name, a.label]));
const map = [
  `// Generated by chart-to-tla.mjs from ${path.basename(args.chart)}. Reader states are the chart's own states.`,
  `export const regions = ${JSON.stringify(vars.map((x) => x.v))};`,
  `const LABELS = ${JSON.stringify(labels, null, "\t")};`,
  "",
  "// The actions the reader takes. facts.settled needs them. Add cause() and detail() as the spec grows.",
  "export const readerActions = [];",
  'export const state = (v) => regions.map((r) => v[r]).join(" | ");',
  "export const step = (action) => LABELS[action] ?? action;",
  "",
];

fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `${args.module}.tla`), out.join("\n"));
fs.writeFileSync(path.join(dir, `${args.module}.cfg`), cfg.join("\n"));
fs.writeFileSync(path.join(dir, `${args.module}.map.mjs`), map.join("\n"));
console.error(
  `${args.module}: ${vars.length} region variable(s), ${actions.length} action(s), rules ${rules.join(" ")} -> ${path.join(dir, args.module)}.{tla,cfg,map.mjs}`,
);

slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall