Skip to content

Cheat Sheet

Everything on this page is runnable as written. For the full declaration inventory see Declarations; for how a project hangs together see Architecture; for the idea behind the language see the Mental Model.

One program, every core move — record types with intent, pure functions with contracts, structural matching with typed regex groups, f-strings:

struct Invoice: # nominal record type
sem "One parsed invoice line" # machine-readable intent
vendor: str
cents: int
def total(invoices: list[Invoice]) -> int !{}: # !{} = provably pure
require len(invoices) > 0 # precondition (blames caller)
ensure result >= 0 # postcondition (blames body)
return sum([i.cents for i in invoices])
def parse(line: str) -> Invoice !{}:
match line: # structural match; must be exhaustive
case re"^(?P<vendor>[A-Z]+) (?P<cents:int>[0-9]+)$":
return Invoice(vendor=vendor, cents=cents) # regex groups bind, typed
case _:
return Invoice(vendor="unknown", cents=0)
def main() -> str !{}:
invoices = [parse(l) for l in ["ACME 1200", "GLOBEX 800"]]
report = f"total = {total(invoices)} cents" # f-string interpolation
print(report) # prints: total = 2000 cents
return report
Command What it does When
sema check <proj> Static checks: parse, arity, struct fields, effect-row discipline, unrecognized directives. After every edit — it’s milliseconds.
sema run <proj> Execute main(). Running the program.
sema assure <proj> --grade bronze|silver|gold Verification engine: test blocks, fuzzed ensure properties, mutation testing at gold. Before merging. There is no separate sema test.
sema doc <proj> Generate API docs from signatures, sem descriptors, and contracts into docs/api/ (--html, --skills). Publishing or feeding docs to a model.
sema repl Interactive session. Exploring the language.
sema circuit run|resume|list|show|cancel Durable, resumable runs recorded under .sema/runs/. Long or interruptible jobs.
sema debug serve|run|replay Run-inspector web UI; replay verifies determinism against a recorded run. Debugging; auditing a run.
sema add|remove|list Dependencies: exact-pin PyPI (name==version) or local native Sema packages. Managing deps.

Environment switches (all fail-closed on bad values):

  • SEMA_STRICT=1 sema run <proj> — every recovered degradation becomes a hard, typed error. Use in tests and CI.
  • SEMA_VM=1 — run compilable bodies on the bytecode VM (identical results, transparent fallback).
  • SEMA_DETERMINISTIC=1 — hermetic built-in engine for model-backed ops (same as [engine] deterministic = true). An explicit mock run — never a silent fallback for a failed real backend.
Kind Surface Notes
Scalars int f64 bool str bytes int is arbitrary-precision; arithmetic is checked — overflow and /0 raise, never wrap. Sized forms i8u64, f16 f32 f64 exist; wrap only via explicit cast.
Collections list[T] dict[K, V] tuple set Python-shaped literals: [1, 2], {"k": v}, (a, b).
No null Option[T] = Some(x) / None Consume with match, combinators, or ? — never an identity test.
Fallibility Result[T, E] = Ok(x) / Err(e) expr? propagates the typed failure upward.
Nominal struct / enum / trait + impl Structs carry sem intent and invariant clauses; enums have payload variants; traits have laws and impl Trait for Type.
def head(xs: list[int]) -> Option[int] !{}:
return Some(xs[0]) if len(xs) > 0 else None
def main() -> int !{}:
match head([3, 1, 4]): # consume by matching -- exhaustive
case Some(x): return x # -> 3
case None: return -1
Form Meaning
"…" / '…' Interchangeable quote styles.
"""…""" / '''…''' Triple = raw multiline — no escape processing.
f"{expr:spec}" Interpolation with format specs [[fill]align][0][width][.precision][type]; types f e d x X o b % s.
r"…" Raw — backslashes kept literally.
rf"…" / fr"…" Raw and interpolated (either order).
re"…" Compiled regex literal (raw rules).
sql"…" Tagged SQL literal.
Escapes \n \t \r \\ \" \' \0 \xHH \uXXXX \UXXXXXXXX, \<newline> continuation. An unknown escape is a loud error, never passed through.
def main() -> str !{}:
raw = r"C:\data\raw" # raw: backslashes kept
pat = re"^[0-9]+$" # compiled regex literal
q = sql"select * from t where id = ?" # tagged SQL literal
doc = """triple quotes are raw
and multiline"""
banner = f"{3.14159:.2f} | {255:>6x} | {0.075:.1%}"
print(banner) # prints: 3.14 | ff | 7.5%
return banner

Every function signature carries an effect row — the capabilities it may use:

Row Meaning
!{} Provably pure — no I/O, no model calls. Compiler-enforced, not a comment.
!{fs.read, net.connect} Exactly these capabilities, nothing else.
(omitted) Inferred minimal row, fail-closed. assure silver+ requires it written out.
!{*} The loud escape hatch — warned at bronze, an error at silver+.

Namespaces: model fs net proc code db env observe ui event memory config package policy clock random ffi human agent. Effect rows are an open vocabulary — declare your own capability names and the checker enforces caller containment for them too (see the Effects Catalog).

Contract clauses, in one line each — require (precondition, blames the caller), ensure (postcondition on result, blames the body), invariant (holds throughout a body or on every struct instance), check (soft: records graded evidence instead of failing hard; check semantics(…, alpha=…) types the region statistical(α)).

def clamp(x: int, lo: int, hi: int) -> int !{}:
require lo <= hi # precondition: caller's fault
ensure lo <= result and result <= hi # postcondition: body's fault
return min(max(x, lo), hi)
def main() -> int !{}:
print(clamp(99, 0, 10)) # prints: 10
return clamp(99, 0, 10)
One-liner What it does
a ~= b Graded similarity → Sim, never a bare bool. if a ~= b: is legal only under a calibrated judge (region types statistical(α)); (a ~= b).score is always readable.
semantic.filter(xs, "…") Keep items matching a natural-language criterion. Siblings: rank(xs, by="…"), dedup(xs, 0.99), map, classify, summarize.
semantics("claim", x, alpha=0.05) A natural-language predicate as a typed guard, with a stated error budget.
simulate def f(x) -> T by m: The model writes the body; sem steers it, budget caps it, ensure gates the output deterministically.
loop until <cond> max_iters N: Convergence loop with a mandatory bound.
with meter as u: / with budget(calls=…, tokens=…) as b: Ambient usage accounting; budget is the hard cap that raises instead of overspending.
model writer = model("qwen3-8b-instruct")
simulate def slogan(product: str) -> str by writer: # body is generated,
sem "A short, upbeat slogan for the product." # steered by intent,
budget tokens=64, time="2s" # capped per call,
ensure len(result) > 0 # gated deterministically
def main() -> str !{model.invoke, model.embed}:
s = "the cat sat" ~= "a cat was sitting" # Sim (graded), never bool
notes = ["refund issued", "cat photos", "invoice overdue"]
money = semantic.filter(notes, "notes about money")
if semantics("the notes concern finance", money, alpha=0.05):
print(f"sim={s.score:.2f} money={money}")
return slogan("solar kettle")
def main() -> int !{model.embed}:
mut tries = 0
loop until tries >= 3 max_iters 10: # bounded convergence loop
tries = tries + 1
with budget(calls=10, tokens=10_000) as b: # hard cap: raises, never overspends
kept = semantic.dedup(["cat", "cat", "dog"], 0.99)
print(f"tries={tries} kept={kept}") # prints: tries=3 kept=["cat", "dog"]
return tries

Model-backed ops need a configured backend or the explicit deterministic opt-in ([engine] deterministic = true / SEMA_DETERMINISTIC=1); otherwise they fail loud with a typed error — never a silent mock.

Path What lives there
sema.toml The manifest (optional): [package] name/edition, [engine] deterministic, [assurance] default.
src/*.sema One module per file; src/main.sema defines main(). pub marks the public surface — everything else is module-private.
tests/ Nothing special — Sema has no separate test tree. Tests are inline test "…": blocks next to the code they defend in src/*.sema, executed by sema assure.
docs/api/ Default output of sema doc — Markdown per module, HTML with --html.
.sema/ Runtime state: recorded runs and journals under .sema/runs/, installed native packages under .sema/packages/.
from std.x import … The stdlib: agent_loop agents belief cache circuits collections completion document provenance usage web. Library modules need an import; effect capabilities (fs, net, …) stay ambient because the effect row already declares them.