PrismDevRelOpen the app
How-to guides: How to build a state machine app

Build

How to build a decision table appHow to build a policy decision appHow to build a state machine appHow to verify an app before you publish itHow to publish an app on GitHub PagesHow to give an AI agent the prism_prompt tool

// how-to guide · Build

How to build a state machine app

Write a prompt for a state machine app, check it, prove it with the gate and publish it.

Choose this pattern when its answer is the one your app gives. The answer is the next state, given the current state and an event. This is a UML state machine written as one pure function. The state travels in the request, so the app keeps nothing between requests. The builder proves what holds over every run.

The standard is OMG UML 2.5.1 behavioral state machine. The guide builds the Vault escrow lifecycle example; put your own rules in its place.

The steps, in order1. Write the prompt: start from Vault escrow lifecycle 2. Check the prompt: node builder/cli.mjs check 3. Build it and pass the gate: just vv in the locked SDK 4. Publish it: GitHub Pages01Write the promptstart from Vaultescrow lifecycle02Check the promptnodebuilder/cli.mjscheck03Build it andpass the gatejust vv in thelocked SDK04Publish itGitHub PagesThe steps, in order1. Write the prompt: start from Vault escrow lifecycle 2. Check the prompt: node builder/cli.mjs check 3. Build it and pass the gate: just vv in the locked SDK 4. Publish it: GitHub Pages01Write the promptstart from Vault escrow lifecycle02Check the promptnode builder/cli.mjs check03Build it and pass the gatejust vv in the locked SDK04Publish itGitHub Pages
The steps, in order. 4 steps. Each section below is one of them.
The data in this figure
StepWhat happens
1. Write the promptstart from Vault escrow lifecycle
2. Check the promptnode builder/cli.mjs check
3. Build it and pass the gatejust vv in the locked SDK
4. Publish itGitHub Pages

1. Write the prompt

Start from the Vault escrow lifecycle prompt, the state machine example with the fewest rules (6 rules). Keep pattern set to stateMachine. Replace the fields, answers, rules and examples of its app with your own.

1. Write the prompt 411 lines
{
  "schema": "prism/prompt/1",
  "goal": "Find the next status of an escrow in the PrismPM Vault from the step applied to it. Then locking, release and refund can be replayed.",
  "pattern": "stateMachine",
  "machine": {
    "state": "state",
    "initial": "none",
    "final": [
      "released",
      "refunded"
    ]
  },
  "repository": "afflom/aistudio-experiment",
  "license": "Apache-2.0",
  "app": {
    "name": "vault-escrow-lifecycle",
    "title": "Vault escrow lifecycle",
    "purpose": "Decide the next status of one escrow agreement from its status, the operation, the depositor funds, the preimage and the epochs.",
    "fields": [
      {
        "name": "state",
        "kind": "choice",
        "values": [
          "none",
          "active",
          "released",
          "refunded"
        ],
        "means": "the escrow status now; none means it has not been locked"
      },
      {
        "name": "event",
        "kind": "choice",
        "values": [
          "lock",
          "release",
          "refund"
        ],
        "means": "the Vault operation applied: LockEscrow, ReleaseEscrow or RefundEscrow"
      },
      {
        "name": "funds",
        "kind": "choice",
        "values": [
          "sufficient",
          "insufficient"
        ],
        "means": "whether the depositor balance covers a positive amount"
      },
      {
        "name": "preimage",
        "kind": "choice",
        "values": [
          "given",
          "empty"
        ],
        "means": "whether a condition preimage is supplied with a release"
      },
      {
        "name": "epoch",
        "kind": "number",
        "means": "the current ledger epoch"
      },
      {
        "name": "timeout",
        "kind": "number",
        "means": "the epoch at which the escrow expires"
      }
    ],
    "outcomes": [
      "none",
      "active",
      "released",
      "refunded"
    ],
    "meanings": {
      "none": "no escrow is locked and no funds are held",
      "active": "the amount is locked and counted in totalEscrowLocked",
      "released": "the amount went to the beneficiary; the escrow is settled",
      "refunded": "the amount went back to the depositor after timeout; the escrow is settled"
    },
    "rules": [
      {
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "released"
          }
        ],
        "then": "released",
        "why": "src/model/engine.ts: an escrow whose status is not active answers already released"
      },
      {
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "refunded"
          }
        ],
        "then": "refunded",
        "why": "src/model/engine.ts: an escrow whose status is not active answers already refunded"
      },
      {
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "none"
          },
          {
            "field": "event",
            "op": "is",
            "value": "lock"
          },
          {
            "field": "funds",
            "op": "is",
            "value": "sufficient"
          }
        ],
        "then": "active",
        "why": "src/model/engine.ts LockEscrow: a positive amount within the depositor balance is locked as active"
      },
      {
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "none"
          }
        ],
        "then": "none",
        "why": "src/model/engine.ts: release and refund answer escrow-not-found; a lock without funds answers insufficient-funds or invalid-amount"
      },
      {
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "active"
          },
          {
            "field": "event",
            "op": "is",
            "value": "release"
          },
          {
            "field": "preimage",
            "op": "is",
            "value": "given"
          }
        ],
        "then": "released",
        "why": "src/model/engine.ts ReleaseEscrow: conditionMatch holds for any non-empty preimage"
      },
      {
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "active"
          },
          {
            "field": "event",
            "op": "is",
            "value": "refund"
          },
          {
            "field": "epoch",
            "op": ">=",
            "value": {
              "field": "timeout"
            }
          }
        ],
        "then": "refunded",
        "why": "src/model/engine.ts RefundEscrow: currentEpoch below timeoutEpoch answers escrow-not-expired"
      }
    ],
    "otherwise": "active",
    "otherwiseWhy": "an empty preimage is a condition mismatch, an early refund is escrow-not-expired, and a lock creates a separate escrow",
    "properties": [
      {
        "kind": "never",
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "active"
          },
          {
            "field": "event",
            "op": "is",
            "value": "refund"
          },
          {
            "field": "epoch",
            "op": "<",
            "value": {
              "field": "timeout"
            }
          }
        ],
        "then": "refunded",
        "why": "src/model/engine.ts: refund is unavailable until timeout"
      },
      {
        "kind": "never",
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "active"
          },
          {
            "field": "event",
            "op": "is",
            "value": "release"
          },
          {
            "field": "preimage",
            "op": "is",
            "value": "empty"
          }
        ],
        "then": "released",
        "why": "src/model/engine.ts: an empty preimage does not satisfy the condition hash"
      },
      {
        "kind": "never",
        "when": [
          {
            "field": "state",
            "op": "is",
            "value": "none"
          },
          {
            "field": "funds",
            "op": "is",
            "value": "insufficient"
          }
        ],
        "then": "active",
        "why": "src/model/vaultSource.ts balanceNonNegativity: no lock exceeds the balance"
      }
    ],
    "examples": [
      {
        "request": "none lock sufficient empty 104 112",
        "response": "active"
      },
      {
        "request": "active release sufficient given 105 110",
        "response": "released"
      },
      {
        "request": "active refund sufficient empty 105 110",
        "response": "active"
      },
      {
        "request": "active refund sufficient empty 110 110",
        "response": "refunded"
      },
      {
        "request": "released refund sufficient empty 120 110",
        "response": "released"
      },
      {
        "request": "none lock insufficient empty 104 112",
        "response": "none"
      },
      {
        "request": "active release insufficient empty 105 110",
        "response": "active"
      }
    ]
  },
  "stakeholders": [
    {
      "name": "Depositor",
      "text": "Locks funds for a beneficiary and needs them back after timeout, and never twice.",
      "concerns": [
        "Correct answers",
        "Settled once"
      ]
    },
    {
      "name": "Beneficiary",
      "text": "Receives the escrow on release and needs a refund impossible before the timeout epoch.",
      "concerns": [
        "Proved guarantees"
      ]
    }
  ],
  "concerns": [
    {
      "name": "Settled once",
      "text": "A released or refunded escrow is never released or refunded again.",
      "model": "quality"
    }
  ],
  "components": [
    {
      "name": "PrismPM Model and Runtime Studio",
      "kind": "staticSite",
      "text": "The Vite studio that runs the Vault engine, the simulated build pipeline and the proof verifier in the browser."
    },
    {
      "name": "PrismPM toolchain",
      "kind": "cliAdapter",
      "text": "The prismpm check, lexlean build, codegen and holo compose stages the studio simulates for the Vault model."
    }
  ],
  "threats": [
    {
      "name": "Any preimage releases",
      "text": "A caller releases an escrow with any non-empty preimage, since the engine does not compare it with the condition hash.",
      "stride": "spoofing",
      "asset": "request",
      "likelihood": "high",
      "impact": "critical",
      "accepted": "This mirrors src/model/engine.ts as it is: conditionMatch holds for any non-empty preimage. The studio is a simulation, and a real hash check belongs to the LexLean Vault source it models."
    },
    {
      "name": "Early refund",
      "text": "A depositor refunds an active escrow before its timeout epoch.",
      "stride": "tampering",
      "asset": "answer",
      "likelihood": "medium",
      "impact": "major",
      "control": {
        "name": "Timeout guard",
        "text": "Refund leaves active only at or after the timeout epoch.",
        "evidence": [
          {
            "kind": "proof",
            "reference": "VaultEscrowLifecycleProofs::inv001Holds"
          },
          {
            "kind": "review",
            "reference": "src/model/engine.ts RefundEscrow"
          }
        ]
      }
    },
    {
      "name": "Double settlement",
      "text": "A settled escrow is released or refunded again, paying its amount twice.",
      "stride": "tampering",
      "asset": "answer",
      "likelihood": "medium",
      "impact": "critical",
      "control": {
        "name": "Final states",
        "text": "Released and refunded are final and never left; the builder derives and proves both invariants from machine.final.",
        "evidence": [
          {
            "kind": "proof",
            "reference": "VaultEscrowLifecycleProofs::inv004Holds"
          },
          {
            "kind": "proof",
            "reference": "VaultEscrowLifecycleProofs::inv005Holds"
          }
        ]
      }
    }
  ],
  "quality": [
    {
      "characteristic": "Functional suitability",
      "subcharacteristic": "Functional correctness",
      "requirement": "No refund before timeout",
      "text": "An active escrow is refunded only when the epoch has reached its timeout.",
      "measure": "Early refunds",
      "measureText": "Requests with epoch below timeout that refund an active escrow.",
      "threshold": 0
    },
    {
      "characteristic": "Reliability",
      "subcharacteristic": "Faultlessness",
      "requirement": "Settled escrows stay settled",
      "text": "No event moves a released or refunded escrow to another status.",
      "measure": "Transitions out of a final state",
      "measureText": "Requests in a final state that answer a different state.",
      "threshold": 0
    }
  ],
  "journeys": [
    {
      "stakeholder": "Depositor",
      "steps": [
        "REQ-003",
        "otherwise",
        "REQ-006",
        "INV-005"
      ]
    },
    {
      "stakeholder": "Beneficiary",
      "steps": [
        "REQ-003",
        "REQ-005",
        "INV-001",
        "INV-004"
      ]
    }
  ]
}

The prompt as raw JSON · Open it in the builder

It sets these members. Each meaning is quoted from the input schema of prism_prompt.

1. Write the prompt 26 rows
MemberPresenceIn this promptMeaning
goaloptionaltextThe goal the app is built toward, in one sentence a developer would say. It becomes the spec purpose when app.purpose is left out.
patternoptionalstateMachineThe pattern the behavior follows: decisionTable (OMG DMN 1.5, hit policy FIRST, the default), policyDecision (OASIS XACML 3.0: the answers are exactly permit, deny, not-applicable and indeterminate) or stateMachine (OMG UML 2.5.1: the answer is the next state, and machine is required).
machineoptionalstate, initial, finalFor a stateMachine: which choice field carries the current state, the initial state, and the final states. The answers are exactly the state values. The builder proves that a final state is never left and that no run from the initial state reaches a state outside the reachable set.
machine.staterequiredstateThe choice field whose values are the states.
machine.initialrequirednoneThe state every run starts in.
machine.finaloptional2 entriesStates a run never leaves once it reaches them (UML FinalState).
repositoryoptionalafflom/aistudio-experimentowner/name of the repository the app will live in, for its page and links.
licenseoptionalApache-2.0The SPDX license expression; MIT OR Apache-2.0 when left out.
apprequiredname, title, purpose, fields, outcomes, meanings, rules, otherwise, otherwiseWhy, properties, examplesThe whole app as a prism/spec/1 spec, the input of prism-code's prism_spec. Its members are below.
app.nameoptionalvault-escrow-lifecycleLower case and hyphens, such as loan-approval.
app.titleoptionalVault escrow lifecycle
app.purposerequiredtextWhat the app decides, in one sentence.
app.fieldsrequired6 entriesOne request is these values in order, separated by spaces.
app.outcomesrequired4 entriesLower-case words; invalid is reserved.
app.meaningsoptionalnone, active, released, refundedWhat each answer means, such as {"review": "a person must decide"}.
app.rulesrequired6 entriesIn order; the first that matches decides.
app.otherwiserequiredactiveThe answer when no rule matches.
app.otherwiseWhyoptionaltextWhy, in a few words, such as "it enforces INV-001".
app.propertiesoptional3 entriesWhat must never or always happen; each becomes a theorem Lean proves.
app.examplesoptional7 entriesRequests and their expected answers; each becomes an acceptance vector.
stakeholdersoptional2 entriesWho the app is for. A Verifier, anyone who replays the holo before trusting it, is always added.
concernsoptional1 entryWhat the stakeholders care about, each viewed in one model.
componentsoptional2 entriesSystems outside the app that send it requests or read its answers.
threatsoptional3 entriesWhat can go wrong, beyond the threats every app has (an oversized or malformed request, a substituted holo or source, a granted capability, an answer a property rules out).
qualityoptional2 entriesHow good is good enough, as ISO/IEC 25010:2023 requirements with a measure and its threshold.
journeysoptional2 entriesOrdered steps a stakeholder takes. A step is a rule ID (REQ-001), a property ID (INV-001), otherwise or refuse.

2. Check the prompt

In a clone of prism-devrel, run the check on your prompt. It checks the prompt and prints what the app will claim, writing nothing.

git clone https://github.com/afflom/prism-devrel.git && cd prism-devrel
node builder/cli.mjs check examples/vault-escrow-lifecycle.prompt.json

For the Vault escrow lifecycle prompt it prints this.

Vault escrow lifecycle: State machine (OMG UML 2.5.1 behavioral state machine), 82 files, 55 acceptance vectors
machine: 4 states from none; reachable none, active, released, refunded; final released, refunded; derived INV-004, INV-005
VE-01: The app never answers refunded when state is active and event is refund and epoch is below timeout
VE-02: The app never answers released when state is active and event is release and preimage is empty
VE-03: The app never answers active when state is none and funds is insufficient
VE-04: The app always answers released when state is released
VE-05: The app always answers refunded when state is refunded
VE-06: The architecture description declares every stakeholder, concern, component, edge, viewpoint and view it references
VE-07: The ISO/IEC 25010 quality model numbers every characteristic, subcharacteristic, requirement and measure, and every parent it names is declared
VE-08: Every compliance obligation is numbered in order and names its evidence

Exit codes: 0 done, 2 the prompt was refused (the reason is printed), 64 usage.

3. Build it and pass the gate

Save this script as verify.sh in the clone, with PROMPT set to your prompt. It is the pages workflow's own steps for an example.

3. Build it and pass the gate 36 lines
set -euo pipefail
PROMPT=examples/vault-escrow-lifecycle.prompt.json
RUNNER_TEMP=$(mktemp -d)
field() { node -e 'process.stdout.write(JSON.parse(require("fs").readFileSync("frame.lock", "utf8")).source[process.argv[1]])' "$1"; }
instance="$RUNNER_TEMP/instance"
git init -q "$instance"
git -C "$instance" fetch -q --depth 1 "https://github.com/$(field repository)" "$(field commit)"
git -C "$instance" checkout -q --detach FETCH_HEAD
test "$(git -C "$instance" rev-parse HEAD)" = "$(field commit)"
node builder/cli.mjs build "$PROMPT" --out "$instance"
image=$(sed -n 's/.*"sdk_image":"\([^"]*\)".*/\1/p' prismpm.lock)
if [[ ! $image =~ ^[a-z0-9.-]+(:[0-9]{1,5})?/[a-z0-9./_-]+@sha256:[0-9a-f]{64}$ ]]; then
  printf '%s\n' 'prismpm.lock does not select an immutable SDK image' >&2
  exit 64
fi
docker_config=$(mktemp -d)
# The SDK's /tmp is a private directory on the runner's own disk, so the
# build's scratch space is bounded by the disk the runner has, not by a
# fixed size; it is removed with the credentials when the step ends.
scratch=$(mktemp -d)
mkdir -p "$scratch/prismpm-home/.docker"
trap 'rm -rf "$docker_config" "$scratch"' EXIT
printf '{}\n' >"$docker_config/config.json"
docker run --rm \
  --user "$(id -u):$(id -g)" \
  --group-add "$(stat -c '%g' /var/run/docker.sock)" \
  --volume "$scratch:/tmp" \
  --volume "$instance:$instance" \
  --volume /var/run/docker.sock:/var/run/docker.sock \
  --volume "$docker_config:/tmp/prismpm-home/.docker:ro" \
  --workdir "$instance" \
  --env DOCKER_CONFIG=/tmp/prismpm-home/.docker \
  --env BUILDX_CONFIG=/tmp/prismpm-buildx \
  --env HOME=/tmp/prismpm-home \
  --env PRISMPM_EPHEMERAL_HOME=1 \
  "$image" just vv

It calls git, node and docker. Run it, and keep the log.

bash verify.sh 2>&1 | tee verify.log

When it passes, the verified holo is in the instance the script made under RUNNER_TEMP, at "$instance"/app/.prism/build/*/*.holo.

4. Publish it

What the gate proves

The State machine obligation of OMG UML 2.5.1 behavioral state machine names its evidence: VaultEscrowLifecycle::judge, VaultEscrowLifecycleProofs::inv004Holds, VaultEscrowLifecycleProofs::inv005Holds.

Each property of the Vault escrow lifecycle prompt is a theorem the Lean kernel checks for every request.

PropertyStatementTheorem
INV-001It never answers refunded when state is active and event is refund and epoch is below timeout.VaultEscrowLifecycleProofs::inv001Holds
INV-002It never answers released when state is active and event is release and preimage is empty.VaultEscrowLifecycleProofs::inv002Holds
INV-003It never answers active when state is none and funds is insufficient.VaultEscrowLifecycleProofs::inv003Holds
INV-004It always answers released when state is released.VaultEscrowLifecycleProofs::inv004Holds
INV-005It always answers refunded when state is refunded.VaultEscrowLifecycleProofs::inv005Holds

Every state machine example

Every state machine example 6 items
  • MCP task lifecycle. Find an MCP task's next state, so a client that polls, updates or cancels it always sees the state the protocol would write.
  • Container lifecycle. Move a PrismPM holo container through its Docker life. A holo that fails its check never runs, and a running one is never removed.
  • Atlas walk controls. Find the next state of the Atlas Explorer view from the button pressed. Then each walk through the E8 orbit can be replayed step by step.
  • Vault escrow lifecycle. Find the next status of an escrow in the PrismPM Vault from the step applied to it. Then locking, release and refund can be replayed.
  • Release lifecycle. Move a template release from build to accept, one step at a time. No release is accepted before every step has passed in order.
  • Organization lifecycle. Move a Foundry organization through its life. Only its own admins can switch it on, pause it or retire it.

Other patterns

how-to guideBuildMarkdown

Words on this page 7
Lean kernel
The small checker at the heart of the Lean prover. It accepts a proof only if every step follows the rules.
theorem
A statement about the model that the Lean kernel has checked, so it holds for every input, not only the ones tested.
holo
The app Prism builds: one signed, verified file that a browser or a device runs.
MCP
Model Context Protocol: an open protocol through which AI agents call tools such as the Prism builder.
XACML
OASIS eXtensible Access Control Markup Language 3.0: a policy decides permit, deny, not applicable or indeterminate.
state machine
A model of something that is always in one state and moves between states on events, as in UML 2.5.1.
prompt
One JSON document that describes an app. The builder turns it into every facet of a Prism model.