Writing FormaSL — a practical step-by-step tutorial
This is a hands-on tutorial for writing admitted FormaSL source. It is
deliberately shorter on “will the runtime do this” than on “will the checker
accept this.” Source admission and runtime execution are different layers; each
step below lists both the parse/elaboration boundary and the run boundary
so you never confuse a positive check with a productive runtime result.
It maps onto the examples shipped in examples/. After each step you can run
the corresponding fixture to compare with real output. This file is parsed by
user_docs_gate (crates/cli/tests/user_docs_gate.rs): every tagged block is
a witness that the current parser admits it.
Two units, two planes
.fsl— a source unit. Exactly onemoduleper file. Imports resolve only against the modules you hand to the CLI; there is no directory search..fsp— a realization unit. Exactly onerealization. It is a binding plan, not a semantic module; it never contains amoduledeclaration and it never accepts$or?values in realization-value positions.
The public run is not cumulative:
formasl run --app Name --gas Nevaluates one selected application. There is no pipeline that carries the inferred facts from oneruninto another. If you need to reason about that assumption, readdocs/book/src/autoridades/user/SUPPORT-LIMITATIONS.md. Authoring inside a project (forma.tomlmanifest, lockfile,formasl test,formasl package seal)? Readdocs/book/src/autoridades/user/PROJECTS.mdalongside this guide. Every step below works identically in project mode — the module language is the same; only source discovery and the test/seal workflow differ.
Step 1 — a minimal, checkable module
Start with the pieces the checker needs to admit your program: one module,
types, and at least one relation with named roles. A relation has named roles,
and each role uses one of the two admissibility forms (role name: Type or
role name accepts Q).
module minimal_surface {
type Artifact
type Position
relation States {
role subject: Artifact
role position: Position
}
}
Run boundary. This module has no application, so run has nothing to select.
You are authoring the admittance layer (formasl check / formasl inspect).
See the full type/relation witness in
examples/F01-types-specialization-subtyping/canonical.fsl
for subtypes, specializes, and role contracts.
Step 2 — claims and the lifecycle vocabulary
Claims are relation occurrences with an authored lifecycle. The current surface
is not claim import; an imported claim leads with import:
import claim Q as local_claim
assert claim name : Relation(role: value, …) { by: expression … }
adopt claim existing_claim as local_name { by: expression … }
retract claim local_name { by: expression … }
supersede claim old_name with new_name { by: expression … }
The standard contract-field vocabulary is by, for, under, based_on,
valid_at, recorded_at, scope, frame, and support. The assertion body
must include its by attribution. supersede records a lifecycle edge; it does
not delete the old occurrence and does not, by itself, calculate a unique
“current” claim.
module claim_surface {
type Artifact
type Position
relation Tracks {
role artifact: Artifact
role position: Position
}
assert claim open_v1 : Tracks(artifact: $release, position: $open) {
by : $registry
valid_at : $t1
recorded_at : $t2
}
adopt claim open_v1 as accepted_open {
by : $reviewer
based_on : $review_basis
}
retract claim accepted_open {
by : $reviewer
based_on : $later_evidence
}
assert claim open_v2 : Tracks(artifact: $release, position: $open) {
by : $registry
based_on : $correction
}
supersede claim open_v1 with open_v2 {
by : $registry
based_on : $correction
}
}
Run boundary. retract/adopt/supersede are carried in the checked
carrier but the public run does not mutate a world. retract does not
delete the prior occurrence and run does not hide it. Do not treat a
post-retract query as evidence that the old claim vanished. See
examples/F07-claim-lifecycle-conflict-time/canonical.fsl
for the checked conflict/time witness.
Step 3 — queries with match: the engine-backed bridge
A match application names a query over relation occurrences; it does not
match a type declaration. Its using Q header is optional (all other families
require using Q):
match Name($parameter: Type, …) [using Q] [-> Result] {
query-clause …
}
A pattern witness begins with ? and uses a relation role map. Every referenced
relation and role must be declared. The query-clause surface is:
pattern ?occurrence: Relation(role: ?value, …)
path ?p from ?from to ?to { step Relation from role to role … }
where bound_expression
optional { … }
exists { … }
not exists { … }
alternative [using Q] { branch { … } … }
select expression [as alias], …
distinct expression, …
aggregate OP(expression) [by expression, …] [as ?aggregate]
group by expression, …
having bound_expression
order by expression [asc|desc], …
any N | offset N | limit N | top N by expression … ties Q
view graph Name { include bound_expression | field: expression … }
The implemented query engine evaluates pattern conjunctions, filters
(where, having), optional, exists/not exists, alternative branches,
grouping (group by, aggregate), projection (select, distinct), ordering
and slicing (order by, any, offset, limit, top … ties), and
view graph clauses — the full admitted surface executes:
path— executes its contract pipeline (endpoint correlation, role-exact steps, reuse policy, admissible family, selector, post-filter) and binds a structured path value distinct from any reference; an unboundedrepeatis rejected at check time withINVALID_UNBOUNDED_PATH_FORMATION.COUNT,SUM,MIN,MAXaggregates — spelled exactly (uppercase, resolved against the exact language/operator basis, never from a content name);SUMfolds under an exact commutative-monoid reducer domain andMIN/MAXunder an exact determining-order contract.
The authoring rule: a clause that cannot complete under its owner’s contract
fails closed with a typed run outcome — never a silent skip and never a
laundered COMPLETE.
module query_surface {
type Artifact
relation DependsOn {
role dependent: Artifact
role prerequisite: Artifact
}
content QueryContract
match FullQueryMatrix($g: Artifact) using QueryContract {
pattern ?edge: DependsOn(dependent: ?x, prerequisite: ?y)
where ?x == $g
optional {
pattern ?next: DependsOn(dependent: ?y, prerequisite: ?z)
}
exists {
pattern ?exists: DependsOn(dependent: ?x, prerequisite: ?y)
}
not exists {
pattern ?missing: DependsOn(dependent: ?z, prerequisite: ?x)
}
alternative {
branch { pattern ?left: DependsOn(dependent: ?x, prerequisite: ?y) }
branch { pattern ?right: DependsOn(dependent: ?y, prerequisite: ?z) }
}
group by ?x
having ?x == $g
select ?x as dependent
distinct ?x
aggregate COUNT(?edge) by ?x as ?n
order by ?x desc
any 3
offset 1
limit 10
top 5 by ?x desc ties QueryContract
view graph DependencyView {
include ?x
}
}
}
realization QueryRealization {
app QueryContract {
require capability: Engine
bind capability to external "reference/formasl-r1"
}
}
Run evidence.
match DirectDependencies()(basic.fsl) — pattern-only →COMPLETEwith solutions.match WithOptionalNextHop(...)and the counting match inexamples/F04-query-semantics/advanced.fsl—optional,not exists,group by,aggregate COUNTall execute through the engine.match BoundedPaths(...)(advanced.fsl) — contains apathclause → executes through the engine; on this fixture it reports 0 solutions with completionEXHAUSTED_DOMAIN(the contract’s minimum path length cannot arrive without a cycle), and the run itself completes — an honest zero, not a refusal.
The single-pattern, pattern-only match that the bridge evaluates:
module language_query {
type Name
relation Greets {
role greeter: Name
role greeted: Name
}
assert claim greeting : Greets(greeter: "world", greeted: "formasl") {
by : $guide
}
match FindGreetings() {
pattern ?g: Greets(greeter: ?who)
}
}
$ formasl check examples/F04-query-semantics/basic.fsl
ACCEPTED module query_basic
$ formasl run examples/F04-query-semantics/basic.fsl --app DirectDependencies --gas 1000
query DirectDependencies -> 3 solution(s) (completion EXHAUSTED_DOMAIN)
Machine consumers request JSON and an explicit schema revision:
$ formasl run examples/F04-query-semantics/basic.fsl --app DirectDependencies --gas 1000 --format json --schema-revision 1
"aggregate_status":"COMPLETE"
--schema-revision 1 is required for the modern
machine envelope; --schema-revision 0 fails closed for families it cannot
represent.
A path body also admits
repeat min..max,alternative set|multiset,each ?item in ?group where …,summarize Q(…) as ?summary,reuse: Q, andselector: Q. The grammar readsrepeat 1..*but the check boundary rejects an unbounded path withINVALID_UNBOUNDED_PATH_FORMATION; use a finite upper bound when the intent is checkable.
Step 4 — bounded inference (R1/R2/R3) under gas
A rule must lead with a declared using basis. Rule variables are witness
variables (?x), not lexical $x variables. A derived-head witness must be
range-restricted by the body; every variable in a naf atom must already be
positively bound in the same rule.
rule Name using Relation(?x: Type, …) {
when Relation(role: ?x, …)
naf Relation(role: ?x, …)
where bound_expression
exists ?w
aggregate ?n = AggregateQ(?value) by ?key
derive [positive|negative] Relation(role: expression, …)
}
infer Name($parameter: Type, …) using Basis {
theory: Q
goal Relation(role: ?w, …)
}
Aggregate by group components admit exactly three forms
(OD-RC-R2-AGG-03): by Source.role (member-derived; no same-named
binder is synthesized), by Source.role as ?g (seeded when ?g is
positively bound elsewhere in the rule body, otherwise an explicit
output binder), and by ?key (compatibility shorthand: exactly one
DISTINCT exact-source role must positively bind the shorthand over the
whole rule — zero candidates reject with
AGGREGATE_GROUP_CORRELATION_REQUIRED, several with
AMBIGUOUS_AGGREGATE_GROUP_CORRELATION; spelling/order/first-match
never decide). Inside a rule body, the aggregate clause’s operator name
is a declared aggregate basis (for example a content), distinct from
the uppercase language operators used in match aggregates.
The implemented inference route covers the positive R1 closure path, the R2
route (including its admitted stratified-negation/expression subset), and the R3
warded-existential route. It is bounded by --gas: a nonconverged route is not a
successful result.
Rule using basis semantics (spatiality closure). The using target of a
rule is formation-checked on the public run path against its resolved
declaration kind:
using target resolves to | Disposition on the public run path |
|---|---|
theory / ontology | Reasoning authority — the rule executes under that exact authority. |
relation | Content/dependency coordinate — the rule joins the executable chain when the relation is reachable through admitted rule heads or named by the application’s goal set. |
content | Named basis coordinate under the application’s selected authority — never independently authority-bearing. |
anything else (rule, constraint, policy, type, …) | Typed run-time rejection (RULE_WIRE_REJECTION) — no kind without defined rule-basis semantics is silently relation-like. |
check alone does not reject an ungoverned using target; the rejection
happens when the rule is admitted onto the executable path. A rule is not
executable merely because it parsed. Goals never introduce reasoning authority,
and a foreign rule head never admits a foreign theory.
module reasoning_surface {
type Node
relation Edge {
role from: Node
role to: Node
}
relation Reach {
role from: Node
role to: Node
}
rule Seed using Edge(?x: Node) {
when Edge(from: ?a, to: ?b)
derive positive Reach(from: ?a, to: ?b)
}
rule Step using Edge(?x: Node) {
when Edge(from: ?a, to: ?b)
when Reach(from: ?b, to: ?c)
naf Edge(from: ?c, to: ?a)
derive positive Reach(from: ?a, to: ?c)
}
content Basis
infer Reachability() using Basis {
goal Reach(from: ?from, to: ?to)
}
}
A complete, checkable inference program that adds two assertions to drive the closure:
module language_inference {
type Node
relation Edge {
role from: Node
role to: Node
}
relation Reach {
role from: Node
role to: Node
}
rule Seed using Edge(?x: Node) {
when Edge(from: ?from, to: ?to)
derive positive Reach(from: ?from, to: ?to)
}
rule Step using Edge(?x: Node) {
when Edge(from: ?from, to: ?to)
when Reach(from: ?to, to: ?through)
derive positive Reach(from: ?from, to: ?through)
}
assert claim edge_ab : Edge(from: "a", to: "b") { by : $guide }
assert claim edge_bc : Edge(from: "b", to: "c") { by : $guide }
content Basis
infer Reachability() using Basis {
goal Reach(from: ?from, to: ?to)
}
}
$ formasl check examples/F05-reasoning-completion/canonical.fsl
ACCEPTED module reasoning_completion
$ formasl run examples/F05-reasoning-completion/canonical.fsl --app TransitiveDependencies --gas 5000
infer TransitiveDependencies -> FIXPOINT_REACHED (extension: 6 fact(s))
Expected outcome: a typed closure status (FIXPOINT_REACHED, or for R3
COMPLETE_UNDER_GOALS / OUT_OF_GAS / WITNESS_BUDGET_EXHAUSTED). A zero
count over a same-stratum derived relation is not a
substitute for negation-as-failure — see F05 for the stratified-negation
witness.
Step 5 — transformation executes through the T1 kernel
A transformation has a mandatory match block, a contribution mode, and one or
more construct blocks. The admitted modes are per match,
per distinct_key by expression, …, and per group by expression, …. Authored
rules execute productively through the native T1 kernel over the accredited
query matcher: collision coalesces ONLY exact-content targets and preserves
every source origin as a material dependence edge, and coverage asserts no
preservation claim the source did not declare. A construct shape outside the
productive route fails closed; a rule-less declaration is recognized as
contract-only (nothing to run).
transform Signature($param: Type, …) using Q {
rule name {
match { pattern ?occurrence: Relation(…) }
per match | per distinct_key by expression | per group by expression
construct Target as $binding { role: expression … }
}
}
module transformation_surface {
type Sensor
type Device
type Value
relation ReportedReading {
role sensor: Sensor
role device: Device
role value: Value
}
relation NormalizedReading {
role device: Device
role value: Value
}
transform Normalize($d: Device) using ReportedReading {
rule normalize {
match {
pattern ?r: ReportedReading(device: ?device, value: ?value)
}
per match
construct NormalizedReading as $n {
role device: ?device
role value: ?value
}
}
}
}
$ formasl check examples/F08-transformation-lineage-dependence/canonical.fsl
ACCEPTED module transformation_lineage_dependence
$ formasl run examples/F08-transformation-lineage-dependence/canonical.fsl --app Normalize --gas 500
transform Normalize -> T1 executed (target elements 1, dependence edges 2) (1 rule(s), 1 construct(s))
Expected outcome: the productive T1 route executes. r1 and r2 project
the same device/value, so the single target element coalesces them under
the exact-content law — and the dependence graph keeps BOTH source origins
reconstructible (dependence edges 2). Provenance is never the same thing
as the derived content. The outcome is still intentionally not evidence
that a new external target was materialized.
Step 6 — governed applications: typed local outcomes, no external mutation
validate, admit, authorize, decide, and revise are governed
application families. They return typed local outcomes; they do not grant a
real-world permission or execute a decision externally.
validate | admit | authorize | decide Signature using Q [ { field: expression … } ]
revise Signature using Q [ { field: expression … } ]
module language_governance {
type Agent
content ValidationPolicy
content AdmissionPolicy
content AuthorizationPolicy
content DecisionPolicy
validate ValidateAgent($agent: Agent) using ValidationPolicy {}
admit AdmitAgent($agent: Agent) using AdmissionPolicy {}
authorize AuthorizeAgent($agent: Agent) using AuthorizationPolicy {}
decide DecideAgent($agent: Agent) using DecisionPolicy {}
}
$ formasl check examples/F10-access-control-governed-decision/canonical-rbac-sod.fsl
ACCEPTED module access_control_governed_decision
Expected outcome: check admits the forms. run returns typed governance
outcomes (including denied/recorded results); an evaluated result is not a
global conformance certificate.
revisedoes not have afromclause. Areviserun is a typed local revision outcome with no external durable mutation.
Step 7 — composition: declarative stages, not an implicit orchestrator
A top-level composition is selected by run like an application. Its body can
carry local invocation, staged invocation, ordering, coupling, case branches,
a returned expression, and an explicit unresolved marker. The current composer
forms supported stage/order/coupling coordinates; it is not an external
scheduler, and body forms without an authorized public carrier — for example
case — fail typed rather than being ignored.
composition Name($input: Type, …) [-> Result] {
let $value = Application(arg: expression, …)
stage stage_name = Application(arg: expression, …) [as $result]
order earlier before later
couple { stage_a, stage_b, … } using CouplingContract
case expression { outcome($binding) => statement-or-block … }
return expression
unresolved expression
}
The full checked witness is the two-file F06 fixture. Pass both .fsl files,
not only the importing file. The case clause, when present, returns a typed
UnsupportedStmt { kind: "case" } result.
$ formasl check examples/F06-dag-composition-realization/artifact-model.fsl examples/F06-dag-composition-realization/canonical.fsl
ACCEPTED module artifact_model
ACCEPTED module dag_composition
Step 8 — realization (.fsp): binding, not execution
A realization names a target and declares binding/requirement preferences. It
does not contain a module and does not accept $ or ? values in
realization-value positions.
realization Plan {
app ApplicationName {
bind slot to external "adapter/reference"
require slot: Capability
limit slot: value
prefer slot: value
budget slot: value
}
stage CompositionName#stage_name { … }
group GroupName {
member app ApplicationName
require slot: value
}
}
bind uses to; require, limit, prefer, and budget use :. A
realization value is a literal, qualified reference, external "…", list, or
typed record. A .fsl pure call and either variable class reject in that
position.
realization LocalReference {
app CandidateBasis {
require capability: Engine
bind capability to external "reference/formasl-r1"
}
app ValidateTransfer {
require capability: Engine
bind capability to external "reference/governance-library"
}
}
$ formasl realize examples/RP01-bank-transfer/program.fsl --for examples/RP01-bank-transfer/local.fsp
BOUND CandidateBasis
Run boundary: realize produces a BOUND result when the checked plan matches a
checked application under the implemented binder. The binding evaluates
bind/require coordinates; the current binder does not evaluate
limit/prefer/budget constraints against the candidate — those preference
fields are parsed and retained but are not runtime-enforced by the public
realize. Keep all required source modules on the command line; imports resolve
against the supplied source set only.
Step 9 — the standard library and situated worlds
The repository ships stdlib/sources/std/ — the frozen standard library —
with std::forma::* and std::world::* modules (classification,
communication, dynamics, information, measure, money, normative,
observation, party, reference, security, space, time, and the
environment foundation). These are ordinary .fsl modules with the same
admission rules as your own sources. Two consequences:
- An import does not resolve implicitly. Pass the stdlib module explicitly:
formasl check mystuff.fsl stdlib/sources/std/world/space.fsl. importalone does not bring names into scope. Selective import names the admissible declarations (import std::world::space { SpatialContains }), and references stay qualified (std::world::space::Region).
std::world::space provides spatial referents, representations, and
qualitative constitutive laws (Place, Region, SpatialReferenceSystem,
SpatialRepresentation, SpatialContains, SpatialOverlaps,
SpatialAdjacent, SpatialDisjoint, plus transitive/symmetric derivation
rules). It is the shared spatial vocabulary for situated programs; the
executable-witness demos built on it live in demos/executable-world/.
A complete user module over the spatial vocabulary needs both files on the command line — the stdlib module first, then the user module that imports it:
module language_space {
import std::world::space { SpatialContains }
type Site
relation HostedAt {
role site: Site
role place: std::world::space::Region
}
assert claim hosted : HostedAt(site: $site, place: $region) { by : $guide }
match Containment() {
pattern ?c: SpatialContains(container: ?big, contained: ?small)
}
}
$ formasl check stdlib/sources/std/world/space.fsl
ACCEPTED module std::world::space
Import without selection admits nothing usable: import std::world::space
with no selective braces parses, but space::Place and unqualified role
references still fail with UNRESOLVED_REFERENCE. Selective import
(import std::world::space { SpatialContains }) names the admissible
declarations; fully qualified references
(std::world::space::Region) always work.
In project mode (
forma.toml) the stdlib is not passed by hand: exact dependency resolution supplies the declared stdlib package, and its provider digest is recorded informa.lock. Seedocs/book/src/autoridades/user/PROJECTS.md.
Step 10 — authoring workflow and exit semantics
- Start with a complete
.fslmodule or.fsprealization, never a bare clause pasted into an unrelated plane. - Declare types, relations, and content bases before the claims, rules, and
applications that name them. Supply every imported
.fslmodule explicitly. - Run
formasl checkafter each structural change; use its typed diagnostic code and locus rather than treating a parse failure as an execution failure. - Run
formasl inspect --view declarations | claims | applications | subtypesto inspect whatcheckretained. - Run only the intended item with
formasl run --app NAME --gas N. TreatREJECTED,RESOURCE_EXHAUSTED, andUNSUPPORTEDas distinct outcomes. The aggregate status collapses to the worst member in this order:REJECTED>RESOURCE_EXHAUSTED>UNSUPPORTED>COMPLETE. - Use
formasl realizeonly with exactly one.fspplan via--for; a realization plan is a binding artifact, not an instruction to create an external resource.
runnever convertsREJECTED,UNSUPPORTED, orRESOURCE_EXHAUSTEDinto a successful no-op.--schema-revision 1is required for new machine consumers; revision 0 is frozen and fails closed for outcomes it cannot represent.
What “works” vs. what “is admitted” — the single rule to remember
Every construct in this tutorial has a witness block that the documentation gate
parses against the live frontend. If a form is admitted here, it parses and
elaborates today. Whether run executes it is a separate, family-specific
boundary documented in SUPPORT-LIMITATIONS.md. When in doubt:
formasl check→ admission and elaboration only.formasl run --app NAME --gas N→ the implemented family bridge only.formasl realize … --for plan.fsp→ binding only; not execution of a bound capability.