On this page

PatternverseDocumentation

Language 1

Pattern Language

Readable source for guided practices.

Pattern Language describes questions, choices, and steps in plain text. You write it as Pattern Markdown: the words remain readable, while a small vocabulary tells Patternverse when to ask for a response or move to another step.

The features below all use :language 1. Types, optional values, and reusable flows are additive; existing source remains supported. The editor preview and practices run through the same compiler and runtime.

Read the code. Try the result.

Each runnable example pairs highlighted source with the real preview. Answer questions, change choices, or edit the code and select Run changes. The panes sit side by side on wide screens and stack on smaller screens. Examples are temporary; AI steps use explicitly selected sample replies.

Your first pattern

This complete example asks a question, uses the answer in a short reflection, and ends. The text inside each block is what the person sees.

a-small-check-in.pattern.md
 1
 "A small check-in"

focus = !ask {
    What would you like to explore?
}

!show {
    You named {{focus}}. Take a moment with that.
}

-> end
Live result

The interactive example loads as you reach it.

Reading the source

Headers describe the pattern. Instructions describe its steps. A named response can be used in later text.

SyntaxMeaning
:language 1Declares the language version.
:titleGives the practice a title.
focus = !askWaits for a text response and names it focus.
{{focus}}Places that response into later text.
!showDisplays authored text.
-> endFinishes the pattern explicitly.

Use name = expression for a value and name = !action for an interaction result. Bindings are immutable: a name cannot be reassigned. Put the text for a question or display inside explicit braces. Lines beginning with # are comments.

Document structure

Start with :language 1, then metadata, input/output declarations, imports, types, helpers, and flows before the main steps. Put attributes before the text in their action block. Close each explicit block with a brace and finish each execution path with -> end. Declarations describe the program; steps run in authored order.

DeclarationContract
:language 1The language tag for all supported features in this guide.
:title "A check-in"An optional title for the practice.
:input topic: textA required, typed value supplied by the caller.
:output answer: textA value every successful completion must return; the annotation is optional.
:import …A pinned executable dependency or a named reference-data resource.

Markdown, references, and literal syntax

Question and display bodies support Markdown paragraphs, headings, emphasis, lists, links, and quotations. {{binding}} inserts a value and {{entry.answer}} reads a known field. Choices display their labels. Inserted participant or model text stays data; it cannot introduce another language step.

markdown.pattern.md
 1

topic = "A small next step"
!show {
    ## {{topic}}

    **Notice** what matters, then choose one action.

    - Make it manageable.
    - Leave room to change your mind.

    > There is no need to solve everything at once.

    Literal syntax: \!ask and \{{not_a_reference}}.
}
-> end
Live result

The interactive example loads as you reach it.

Prefix reserved syntax with a backslash when it should appear as text, such as \!ask, \-> end, or \{{name}}. Common indentation is removed from a body while relative indentation is preserved. Explicit braces keep annotation-shaped prose and lines such as Given: inside the intended body. Earlier shorthand bodies remain compatible.

Bindings and types

Types are inferred unless you add an annotation such as topic: text. An annotation checks the value; it does not convert it. For example, a quoted number remains text and cannot be assigned to a number binding.

typed-entry.pattern.md
 1
 entry: {topic: text, ratings: list[number]}

topic: text = !ask {
    What would you like to explore?
}
ratings: list[number] = []
entry = {topic: topic, ratings: ratings}
!show {
    Topic: {{entry.topic}}
}
-> end
Live result

The interactive example loads as you reach it.

TypeValues
textText, including an empty string.
numberNumeric values and rating results.
booleantrue or false.
choiceA choice with a stable .value and display .label.
list[T]An ordered list whose elements share a type, such as list[text] or list[choice].
{topic: text}A record with named, typed fields; read them with entry.topic.
Optional[T]A present value of type T, or explicit absence with None.

Declare public inputs with :input topic: text and outputs with :output entry or a typed output declaration. Every completing path must supply each output. An annotation can give an empty list its element type, as above; the compatible list<text> and []:text spellings also remain supported.

Inputs and outputs

Inputs are supplied when a run starts, rather than read from surrounding chat or another pattern’s variables. Every declared input must be supplied with its declared type. Outputs identify which completed bindings a caller receives; internal bindings remain local.

typed-inputs.pattern.md
 1
 topic: text
 answer: text

answer = !ask {
    What is one useful next step for {{topic}}?
}
!show {
    Your next step: {{answer}}
}
-> end
Live result

The interactive example loads as you reach it.

Annotations on outputs supply expected types throughout the program. For example, :output notes: list[text] permits notes = [] because the element type is known. Omitting an output annotation keeps inference. Every path ending with -> end must provide every declared output, including paths that finish early.

The compatible :input topic text spelling also works. Input values are explicit data, never source text to execute. When another flow calls the practice, it supplies inputs with :with and receives a record of declared outputs.

Optional values and presence checks

Use Optional[text] when a value may be absent. Assign None for absence, or a text value for presence. Optional is built in and needs no import. A binding initialized with None needs an expected type, for example note: Optional[text] = None.

optional-note.pattern.md
 1
 note: Optional[text]
 description: text

?branch {
 note != None {
        description = trim(note)
    }
 {
        description = "No note was supplied."
    }
}
!show {
    {{description}}
}
-> end
Live result

The interactive example loads as you reach it.

Switch the input to see which branch runs. Both inputs satisfy Optional[text].

Defaults for absent values

optional ?? fallback returns the contained value when present and evaluates the fallback only for None. The fallback must match the contained type. Empty text, zero, false, and empty lists are present values and stay unchanged.

optional-fallback.pattern.md
 1

notes: list[text] = []
summary = first(notes) ?? "No notes yet."
note: Optional[text] = ""
kept = note ?? "This fallback is not used."
!show {
    Summary: {{summary}}
    Present empty text stays empty: [{{kept}}]
}
-> end
Live result

The interactive example loads as you reach it.

Chains associate right to left: a ?? b ?? fallback means a ?? (b ?? fallback). Arithmetic binds more tightly than ??; comparisons, Boolean operators, and pipelines bind less tightly. For example, note ?? " default " |> trim trims the selected text. Parenthesize a pipeline inside the fallback when only that branch should be transformed.

Inside :when note != None, the compiler knows that note is text, so it can be passed to trim or used in a text reference. Check presence before accessing an optional record’s fields, doing arithmetic, or calling a helper that expects the contained type. Direct == None checks work too. A presence check applies within the branch it proves; it does not automatically carry past a branch join.

list[Optional[text]] allows absent entries in a list; Optional[list[text]] allows the whole list to be absent. An empty list [], empty text "", and None are different values. There is no implicit truthiness or optional chaining.

Optional values and optional questions

[optional] on a form question permits empty text; it does not produce None. A standalone !ask also returns text, including an empty answer. Assigning that result to Optional[text] wraps it as present. An optional input is still required: its caller must explicitly supply a value or typed absence. Missing inputs are not filled with None.

Expressions and immutable data

Expressions derive values without asking questions or calling a model. Parentheses make grouping explicit, records expose named fields, and lists keep a single element type. The compiler checks every field path and operation.

expressions.pattern.md
 1

score = 3 * (2 + 1)
available = score >= 7 and not false
entry = {score: score, available: available}
!show {
    Score: {{entry.score}}
    Enough capacity: {{entry.available}}
}
-> end
Live result

The interactive example loads as you reach it.

OperatorsRule, from strongest to weakest precedence
(…), entry.field, helper(…)Grouping, known field access, literals, and function calls.
-value, *, +, -Unary minus, then multiplication, then addition/subtraction. Operands are numbers.
??Use a fallback only for None. Right-associative; lower precedence than arithmetic and higher than comparisons.
<, <=, >, >=, ==, !=Non-chained comparisons. Ordering requires numbers; equality compares compatible types, including structural lists/records and choice IDs.
not, and, orBoolean negation, then short-circuit AND, then short-circuit OR. No implicit truthiness.
|>Pass the left value as the first argument of the next pure call; pipelines have the lowest precedence.
|>>Map the next pure call over one list level, inserting each item as its first argument. Both pipes share the lowest precedence and run left to right.

Use commas between list items and record fields; trailing commas are accepted. An empty list needs an expected type or a compatible explicit element annotation. Use concat to combine text or lists. Effects such as !ask, !agent, and semantic suggestions are whole statements, so they cannot be hidden inside a record, list, helper argument, or pure transformation.

Command reference

Choose the interaction that fits the step. These are the basic building blocks; responses are confirmed by the person using the practice.

InstructionUse it to
!askCollect a text response.
!chooseOffer a single choice, or multiple choices with [multi].
!rankAsk the person to arrange the offered items in order.
!rateCollect a rating within an authored range.
!showPresent text or a reflection.
!formGroup text, questions, and timers into one worksheet step.
!timerAdd a countdown with an authored duration.
!image, !videoShow media with authored alternatives, captions, or playback settings.
!collectBuild a bounded list of participant-created entries.
!useCall a local flow or pinned imported pattern with explicit inputs.
!refineReview and revise wording with explicit participant acceptance.
!agentRequest a model result with a declared type and explicitly supplied context.
!turnRequest an explicit model-generated conversational turn under its authored contract.

Questions and ratings

answer = !ask returns text. A standalone question allows an intentionally empty answer. Use a form for a nonblank required answer or several related fields confirmed together. Prompt references can use earlier bindings, such as What matters about {{topic}}?.

rate-energy.pattern.md
 1
 energy: number

energy = !rate 0..10 {
 "Very little"
 "Plenty"
    How much energy is available today?
}
!show {
    You rated your energy {{energy}} out of 10.
}
-> end
Live result

The interactive example loads as you reach it.

!rate minimum..maximum returns a finite number within inclusive bounds. Bounds may be negative or decimal. :low and :high supply endpoint labels; :prefer slider is a presentation preference. The numeric range remains authoritative, whichever control the host uses. An invalid or out-of-range reply leaves the question pending.

Single choice, multiple choice, and ranking

Give each option a stable ID and a quoted label. A single choice returns choice; [multi] returns list[choice] in catalogue order. A ranking returns every offered item exactly once, in the participant’s confirmed order.

choices-and-ranking.pattern.md
 1

selected = !choose [multi, min=0, max=2] {
    Which possibilities would you like to consider?
    - pause: "Take a pause"
    - ask: "Ask for help"
    - plan: "Make a small plan"
}
ordered = !rank [from=selected] {
    What order would you like to try them in?
}
!show {{ordered}} {
}
-> end
Live result

The interactive example loads as you reach it.

ParameterMeaning
multiAllow multiple selections; without it, choose exactly one.
min=N, max=NInclusive multi-selection bounds. The default minimum is 1 and maximum is the offered count. min=0 permits an explicit empty selection.
from=selectedUse an existing choices catalogue or list of choices instead of literal options.
label=descriptionWhen ranking records, use a nonblank text field for labels and return the complete original records.
prefer=…radio/chips for single choice, checklist/chips for multi, and reorder for ranking. These affect presentation.

.value is an option’s stable ID; .label is its display wording. Use IDs in matches. Dynamic catalogues cannot be combined with literal options. Duplicate IDs, unknown selections, repeated ranking items, and contradictory bounds are rejected. To rank a subset, choose it first, then pass the returned list to !rank.

Multi-selection and ranking have explicit confirmation controls. The preview uses the editor’s controls; a host may present single-choice confirmation differently. The accepted result, type checks, and stable option identities are shared. The legacy :option id "Label" and :from source forms remain supported.

Grouped forms

A form keeps related content together. For example, a single step can show an instruction with a timer directly beneath it.

timed-reflection.pattern.md
 1
 "A timed reflection"

reflection = !form {
 "Take a moment"
    !show {
        Consider what you would like to do next.
    }
    thought = !ask {
        What would you like to try?
    }
    notes = !ask [optional] {
        Anything else you want to remember?
    }
    !timer pause {
 60
 true
 false
        Start when you are ready.
    }
}

-> end
Live result

The interactive example loads as you reach it.

Text fields in a form are required and multiline by default. [optional] permits an empty answer; :multiline false requests a single-line field, and :placeholder "A small next step" supplies a hint. A form can also group ratings and choices. Its completed result is a record, such as reflection.thought and reflection.notes, available after the whole form is submitted. Sibling fields cannot read one another’s unfinished answers.

A form supports ordered !show, !ask, !rate, !choose, and !timer blocks. Ranking, branching, model requests, child calls, and nested forms belong between forms. Required text must be nonblank; ratings and choices use the same typed contracts as standalone steps. All fields are validated and accepted together, so a rejected field keeps the complete form draft open.

:duration 60
Sets the countdown to 60 seconds.
:blocking true
Keeps Continue unavailable until the timer finishes. The person then confirms continuation.
:sticky false
Keeps the timer in this step. With true, a started timer moves to the practice’s sticky timer area.

Countdown timers

A timer binds an immutable receipt containing duration_seconds, elapsed_seconds, and completed. Its widget provides start, pause, resume, and reset; the participant explicitly confirms continuation.

adjustable-timer.pattern.md
 1

pause = !timer {
 10
 true
 5
 120
 false
 false
    Take a brief pause. Continue when you are ready.
}
!show {
    Continued after {{pause.elapsed_seconds}} seconds.
}
-> end
Live result

The interactive example loads as you reach it.

AttributeContract
:duration NRequired whole seconds, from 1 to 86,400.
:blocking true/falseRequired. A blocking timer must finish before continuation; a nonblocking standalone timer permits continuation after starting.
:adjustable truePermit duration changes before starting. Both :min N and :max N are then required and must contain the initial duration.
:sticky true/falseDefaults to true: a started timer moves to the practice’s timer area. False keeps it in its authored step.
:persistent trueA form attribute that keeps its nonblocking timer controls available in the visible completed step while the run continues.

Durations in source are seconds even when an editor control displays minutes. A nonblocking receipt records the clock at continuation; later clock changes do not rewrite that value. Pausing a run pauses its clocks, and leaving removes the countdowns. Reopening historical receipts does not start them again.

Images and video

Media are standalone display effects. They do not bind an answer or block the next step. Attributes are literal configuration; references may appear in the Markdown caption or guidance. The examples below load their external media only when you run them.

Images

image.pattern.md
 1

!image {
 "https://patternverse.org/icons/patternverse-mark.png"
 "The Patternverse mark: a geometric leaf shape."
 "An image with a caption"

    Add a short caption or an instruction here.
}
-> end
Live result

Run the example to see it rendered here.

Run this example to load the image from its HTTPS source.

:url requires an HTTPS source and :alt requires a meaningful text alternative. Use exactly "" for a purely decorative image. An optional :title supplies a visible heading. The Markdown body is the caption. Meaningful images can be enlarged with the pointer or keyboard; a failed load keeps the alternative and source link available.

Video excerpts

video.pattern.md
 1

!video {
 "https://youtu.be/M7lc1UVf-VE"
 "A video excerpt"
 "0:10"
 "0:30"
 false
 false
 false
 "en"

    Watch the excerpt, then notice what stood out.
}
-> end
Live result

Run the example to see it rendered here.

Run this example to load the external video player. Playback starts only when you press play.

AttributeMeaning
:url, :titleRequired HTTPS video source and optional visible/accessibility title.
:start, :endWhole seconds or quoted M:SS/H:MM:SS. Both are absolute positions; end must exceed start. Start defaults to zero and end is otherwise the source’s end.
:autoplay, :muted, :loopBoolean preferences, all false by default. Browser playback policies still apply; looping repeats the excerpt.
:captions "en"Prefer an available caption language; it cannot create a missing track.

Supported sources include YouTube, Vimeo, Dailymotion, and direct MP4/WebM files. Explicit excerpt attributes override timestamps in the shared URL. Dailymotion requires the host’s player configuration. Pause/end controls pause players; playback position is local presentation state rather than a returned binding. Media failures do not fabricate a participant response.

Control flow

A practice can follow a different path based on a response, or repeat a step. The paths are written in the source.

InstructionPurpose
?matchChoose an authored path based on a value, such as a selected choice.
?branchChoose an authored path using explicit conditions.
?loopRepeat a step, with an optional maximum number of iterations. The person can stop the loop.
-> endComplete the practice.
choose-a-path.pattern.md
 1

route = !choose {
    Where would you like to begin?
    - explore: "Explore a situation"
    - finish: "Leave it here"
}
?match route {
 explore {
        note = !ask {
            What would you like to explore?
        }
        !show {
            You named {{note}}.
        }
    }
 finish {
        -> end
    }
}
-> end
Live result

The interactive example loads as you reach it.

Local :case arms continue after the match unless they explicitly end. A static single-choice question can omit :else when every offered ID is covered, as above. Closed enums work the same way. Text, numbers, and choices without a known catalogue need a final :else. Match choice IDs, rather than their display labels.

?branch checks :when conditions in order and always needs a final :else. A value read after a decision must be supplied with the same type on every path that continues to that read. Mutually exclusive arms may supply the same name.

conditional-path.pattern.md
 1

energy = !rate 0..10 {
    How much energy is available?
}
?branch {
 energy >= 7 {
        suggestion = "Choose one focused action."
    }
 energy >= 3 {
        suggestion = "Make the next step smaller."
    }
 {
        suggestion = "Make room to rest."
    }
}
!show {
    {{suggestion}}
}
-> end
Live result

The interactive example loads as you reach it.

Arms can contain local decisions, but not labels or jumps that escape their region. Braces do not introduce mutable variables: mutually exclusive arms can provide one binding, while a later possible reassignment is rejected. Legacy forward labels and :case value -> label remain compatible. Backward jumps are not loops.

Functional loops

?loop[max] name = initial carries an explicitly typed state value through repeated interactions. Each iteration gets fresh immutable locals, and -> repeat expression supplies the next state of the same type.

bounded-loop.pattern.md
 1

initial = "a manageable next step"
?loop[3] topic = initial {
    next = !ask {
        What would make {{topic}} a little easier?
    }
    -> repeat next
}
!show {
    You can leave the loop at any point.
}
-> end
Live result

The interactive example loads as you reach it.

The optional bracket is the total number of iterations, including the first. [0] skips the body. Omitting it means no authored maximum; host resource limits still apply. -> break, reaching the maximum, or the participant’s Leave loop control continues below the loop. Ending the whole run is a separate action.

A repeated body must include a participant interaction, and its final repeat/break must be last. Bodies are straight-line; loop state and iteration locals do not escape the loop or shadow outer names. Nested same-run repetition and branching are rejected rather than inferred.

Pure helpers, lambdas, and pipelines

Declare a helper with fn before the practice’s steps. Its parameters and result have explicit types. Helpers use only their parameters and earlier helpers; they do not ask questions, call models, or read surrounding bindings.

clean-notes.pattern.md
 1
 cleaned: list[text]

fn clean(value: text) -> text => value |> trim |> normalize_whitespace

notes = ["  Take a pause  ", "Ask   for help"]
cleaned = notes |>> clean
!show {{cleaned}} {
}
-> end
Live result

The interactive example loads as you reach it.

Inline lambdas

map, filter, fold, reduce, find, any, and all accept inline callbacks as well as named helpers. An underscore marks a parameter whose type is inferred from the input list. Use _.name for a field or trim(_) for a call. Earlier immutable values, such as threshold, can be captured by an inline lambda.

lambda-placeholders.pattern.md
 1

threshold = 7
scores = [2, 8, 9]
high = filter(scores, _ >= threshold)
names = map([{name: "Pause"}, {name: "Ask for help"}], _.name)
total = fold(scores, 0, _ + _)
!show {
    High scores: {{high}}
    Names: {{names}}
    Total: {{total}}
}
-> end
Live result

The interactive example loads as you reach it.

Each _ occurrence introduces a separate parameter, from left to right: _ + _ means (accumulator, item) => accumulator + item in a fold. To reuse the same parameter, name it: n => n * n. Two-parameter lambdas use parentheses: (total, item) => total + item.

lambda-named.pattern.md
 1

threshold = 7
scores = [2, 8, 9]
squares = map(scores, n => n * n)
middle = filter(scores, n => n >= 3 and n <= 8)
groups = [[2, 8], [7, 9]]
filtered = map(groups, group => filter(group, _ >= threshold))
!show {
    Squares: {{squares}}
    Middle scores: {{middle}}
    Filtered groups: {{filtered}}
}
-> end
Live result

The interactive example loads as you reach it.

For nested transforms, name the outer parameter so each inner underscore has a clear owner. Parameters are local to their lambda; captured values must already be available. Predicate callbacks must return Boolean values, folds must return the seed’s type, and reducers must return the list element type. Bodies contain pure expressions; questions, AI calls, and unseeded shuffle are not allowed. Inline lambdas are supported in callback positions and cannot be stored or returned as function values. Named fn helpers keep their explicit-parameter contracts.

A pipeline passes the value on its left as the first argument on its right: value |> trim means trim(value). Use trim, lowercase, and normalize_whitespace for text; count, concat, map, filter, flatten, fold, and reduce for collections. map, filter, and fold take named helpers or inline lambdas. Lists stay homogeneous, and transformations produce new values.

Use items |>> clean to map a pure helper or built-in over one list level. scores |>> clamp(0, 10) calls clamp(item, 0, 10) for each score. Mix both pipes freely: notes |>> clean |> join("; ") cleans each note, then joins the resulting list. Order and length are preserved, including typed empty results. List-valued results stay nested; additional list arguments are passed whole. |>> provides explicit mapping without recursive or multi-list broadcasting.

FunctionInput and result
trim(text)Remove leading and trailing whitespace.
lowercase(text)Return lowercase text.
normalize_whitespace(text)Normalize runs of whitespace in text.
clamp(n, min, max)Bound a number; reject minimum greater than maximum.
concat(a, b)Join two texts or two lists of the same element type.
count(items)Return the number of elements in a list or choices catalogue.
map(items, helper)Call a pure callback once per element; preserve order and length.
filter(items, helper)Keep items whose pure callback returns true, in their original order.
flatten(items)Remove one list layer.
shuffle(items[, seed])Return a new permutation. Without a text seed, use a whole binding; the order is stable when the run resumes. A seeded call is pure.
fold(items, seed, helper)Call a pure callback with accumulator then item; the result keeps the seed’s type.
reduce(items, helper)Start with the first element and combine remaining elements in order; return Optional[T], with None for an empty list.
records(library)Return a reference library’s typed record list.
lookup(library, key)Return the record for a typed reference, or an optional record when the key is arbitrary text.

Browse the Functions reference for signatures, parameters, return types, and editable examples of every built-in.

Use join and split to combine or separate texts, and contains, starts_with, and ends_with for literal text checks. sum totals numbers; min and max return optional extrema. first, last, and predicate-based find return optional elements. Use ?? for an explicit default. any and all test predicates with short-circuit evaluation; distinct keeps each value’s first occurrence in order.

Reducing without a seed

reduce(items, callback) uses the first element as its initial accumulator. The callback receives the accumulator and next item and must return the same element type. A singleton returns its element without invoking the callback; an empty list returns None. Use ?? for an explicit fallback, or fold for an explicit seed or a different accumulator type. Optional element types are not supported because directly nested Optional values are not allowed.

reduce-scores.pattern.md
 1

scores = [2, 4, 8]
total = reduce(scores, _ + _) ?? 0
empty: list[number] = []
fallback = reduce(empty, (total, value) => total + value) ?? 0
!show {
    Total: {{total}}
    Explicit empty-list fallback: {{fallback}}
}
-> end
Live result

The interactive example loads as you reach it.

Helpers declare parameter and result types, cannot recurse or capture surrounding values, and may call only earlier helpers. They are named declarations rather than stored function values or closures. For a multiline pipeline, put |> or |>> at the start of each continuation line. Empty map/filter results retain their type; an empty fold returns its seed.

Collecting and traversing entries

Use each to run a sequence of interactions once for each item in an existing list or set of choices. A final -> yield expression chooses each iteration’s result. The completed binding is a list of those results, in source order.

two-questions.pattern.md
 1
 answers

questions = ["What matters today?", "What is one small next step?"]
answers = each question in questions {
    response = !ask {
        {{question}}
    }
    -> yield {question: question, answer: trim(response)}
}
!show {{answers}} {
}
-> end
Live result

The interactive example loads as you reach it.

Each iteration has fresh local bindings. An empty input runs no interactions and returns a typed empty list. For an open-ended collection, use entries = !collect with a required finite :max and optional :min. The participant chooses whether to add another entry after the minimum is met. An explicit final yield chooses the exported value; existing language-one collections without it keep their record output.

Collection bodies are straight-line sequences. Put more complex branching or nested procedures in a called flow or child pattern. Pausing preserves the current entry and accepted answers; ending the practice does not manufacture a successful collection result.

Participant-created entries

open-collection.pattern.md
 1

ideas = !collect {
 0
 3
    idea = !ask {
        What is one small idea?
    }
    effort = !rate 1..5 {
        How much effort would {{idea}} take?
    }
    -> yield {name: idea, effort: effort}
}
!show {{ideas}} {
 effort asc
}
-> end
Live result

The interactive example loads as you reach it.

:min defaults to 1 and cannot exceed :max. With :min 0, the participant first chooses whether to start. A record is appended only after its whole body completes. At the maximum, collection ends without asking to add another entry. A final yield exports exactly its expression; legacy language-one collections without a yield export their body’s record fields.

The compatible mapped form !collect with :from items and :as item traverses a frozen source and has no add/finish question. each makes the per-item yield explicit. Empty sources produce typed empty lists, and invalid replies preserve previously completed entries.

Reusable flows

A flow packages interactive steps behind explicit inputs and outputs. Declare it before the main steps, then call it with !use. The returned record contains its declared outputs.

ask-a-topic.pattern.md
 1

flow ask_topic {
 topic: text
 answer: text
    answer = !ask {
        What comes to mind about {{topic}}?
    }
    -> end
}

result = !use ask_topic {
 topic = "today"
}
!show {
    You wrote: {{result.answer}}
}
-> end
Live result

The interactive example loads as you reach it.

Flows have isolated bindings and cannot capture the caller’s local values. Pass each input with :with; -> end returns the flow’s outputs. A flow can call sibling flows or pinned imported patterns, but recursive calls are rejected.

Inputs are passed exactly once. :with topic forwards an input of the same name; :with topic = another_value supplies an expression under a different name. Missing, extra, or mistyped inputs fail compilation. Only declared outputs are exposed on the returned record. The caller waits for the child to complete.

Executable imports and reference data

Pinned executable patterns

Mira’s saved-pattern import picker supplies an exact artifact identity and compiled content revision. The template below shows where that value belongs. A title, ordinal version, file path, or URL cannot replace a content pin.

pinned-import.pattern.md
 1
 "artifact-id@exact-compiled-revision" as helper

result = !use helper {
 topic = "today"
}
!show {
    {{result.answer}}
}
-> end

Template: replace the explanatory pin with the exact value from your saved-pattern import picker.

An import only makes a dependency available; !use executes it. Input and output contracts are checked across the dependency closure, including unused imports. Missing dependencies and cycles are errors. Existing runs keep the exact imported sources with which they started.

Named reference-data libraries

A published content entry can register a JSON resource through its libraries metadata. The resource declares a record_type and a records list; each record must exactly match its schema and have a unique, nonblank text ID. A source-qualified ID such as commons:materials identifies that resource.

data-import.pattern.md
 1
 materials from "commons:materials"

items = records(materials)
!show {{items}} {
 name asc
}
-> end

Template: publish a materials resource before running this source. The resource ID and schema must match your data.

records(materials) returns the typed record list. A ref[materials] is a validated ID in that resource, so lookup(materials, reference) returns its record. An arbitrary text lookup can miss and returns Optional[record type]; check for None before reading fields. References from another resource are rejected.

Reference data resolves when a new run starts and is frozen with its schema and values in that run. A resource update affects new runs; reopening an existing run uses its original copy. Both forms of import are declarative, with their own validation and resource limits.

Active-pattern message handlers

An events declaration can route on user.message -> handle_message to a local flow while a pattern is waiting for a text answer. The handler takes text inputs message and prompt, and returns disposition as pass or handled. Passing delivers the original answer; handling returns to the same unanswered question after the side conversation. These handlers run within active patterns; they do not listen to all chat or operate pause/end controls.

message-handler.pattern.md
 1

flow handle_message {
 message: text
 prompt: text
 disposition: text
    ?branch {
 message == "help" {
            !show {
                Name any manageable topic. Your answer can be brief.
            }
            disposition = "handled"
        }
 {
            disposition = "pass"
        }
    }
    -> end
}
events {
    on user.message -> handle_message
}
answer = !ask {
    What would you like to explore? Type help for an explanation.
}
!show {
    You chose {{answer}}.
}
-> end
Live result

The interactive example loads as you reach it.

Try help to show an explanation and return to the same pending question. Any other message passes through as its answer. This example makes the routing decision deterministically. A handler may also use an explicit classifier with declared context.

The nearest enclosing handler receives active text questions, including questions in called flows. It receives only the submitted message and rendered prompt. Handlers do not intercept themselves, ratings, choice confirmations, or review decisions. A paused or completed pattern receives no new messages. Unsupported event kinds fail compilation.

Data visualization & display

Pass an existing collection to !show to display its records. Describe the attributes to map, group, or order; the renderer chooses a readable presentation and keeps the original fields available as text.

Mapping

Effort is horizontal and impact is vertical. Edit a number and run changes to move its point.

show-mapping.pattern.md
 1

ideas = [
    {name: "Take a pause", effort: 1, impact: 3, category: "Rest"},
    {name: "Ask for help", effort: 2, impact: 5, category: "Support"},
    {name: "Take a walk", effort: 3, impact: 4, category: "Rest"},
]
!show {{ideas}} {
 effort, impact
}
-> end
Live result

The interactive example loads as you reach it.

Grouping

Rest contains two ideas and Support contains one. Change a category to move an idea into another labelled group.

show-grouping.pattern.md
 1

ideas = [
    {name: "Take a pause", effort: 1, impact: 3, category: "Rest"},
    {name: "Ask for help", effort: 2, impact: 5, category: "Support"},
    {name: "Take a walk", effort: 3, impact: 4, category: "Rest"},
]
!show {{ideas}} {
 category
}
-> end
Live result

The interactive example loads as you reach it.

Ordering

Highest impact comes first: Ask for help, Take a walk, then Take a pause. Change desc to asc to reverse the order.

show-ordering.pattern.md
 1

ideas = [
    {name: "Take a pause", effort: 1, impact: 3, category: "Rest"},
    {name: "Ask for help", effort: 2, impact: 5, category: "Support"},
    {name: "Take a walk", effort: 3, impact: 4, category: "Rest"},
]
!show {{ideas}} {
 impact desc
}
-> end
Live result

The interactive example loads as you reach it.

Relationships

A parent field connects each step to its parent. Notice branches into Pause and Explore; Explore leads to Try.

relationships.pattern.md
 1

steps = [
    {id: "notice", name: "Notice", parent: ""},
    {id: "pause", name: "Pause", parent: "notice"},
    {id: "explore", name: "Explore", parent: "notice"},
    {id: "try", name: "Try", parent: "explore"},
]
!show {{steps}} {
 parent
}
-> end
Live result

The interactive example loads as you reach it.

Split views

Expected and Optimistic appear in separate panels with the same effort and impact scales, so their positions are comparable.

show-split-views.pattern.md
 1

scenarios = [
    {name: "Take a pause", effort: 1, impact: 3, scenario: "Expected"},
    {name: "Ask for help", effort: 2, impact: 5, scenario: "Expected"},
    {name: "Take a walk", effort: 3, impact: 4, scenario: "Expected"},
    {name: "Take a pause", effort: 1, impact: 4, scenario: "Optimistic"},
    {name: "Ask for help", effort: 2, impact: 6, scenario: "Optimistic"},
    {name: "Take a walk", effort: 3, impact: 5, scenario: "Optimistic"},
]
!show {{scenarios}} {
 effort, impact
 scenario
}
-> end
Live result

The interactive example loads as you reach it.

Combining properties

Mapping, grouping, and ordering can describe the same collection together.

show-ideas.pattern.md
 1

ideas = [
    {name: "Take a pause", effort: 1, impact: 3, category: "Rest"},
    {name: "Ask for help", effort: 2, impact: 5, category: "Support"},
]
!show {{ideas}} {
 effort, impact
 category
 impact desc
}
-> end
Live result

The interactive example loads as you reach it.

:map accepts one or two dimensions. :group creates labelled groups, :order sorts ascending or descending, :link describes relationships by ID, and :split separates context views. All are optional. Displays do not change the collection or ask for a response.

PropertyPresentation
:map valueA numeric spectrum, inferred time axis, or categorical bands.
:map effort, impactTwo dimensions: first horizontal, second vertical.
:group categoryLabelled groups without changing mapped positions.
:order score descStable ordering; asc is the default.
:link parentDirected relationships to text IDs, lists of IDs, or choices. A field named parent points from the parent to the current item.
:split scenarioSeparate context views sharing the same axis domains.

All properties are optional and may appear once in any order. Without them, the result is a labelled collection. Numbers preserve distance, enums preserve declaration order, and consistent ISO date text can become a timeline. There is no separate date type. Nested scalar attributes work; transform values before showing them.

Labels prefer name, title, label, idea, text, then id. Relationships need stable IDs; empty text or an empty list means no link. Cycles are labelled and shown with dashed edges. Invalid relationships produce warnings and a labelled fallback. Small screens keep readable lists with complete attributes, rather than relying on a cramped graphic.

AI and participant control

Ordinary authored text and response references do not request AI wording. An explicit ~ marker can ask for a different phrasing of a predetermined conversational move.

wording = ~ binds generated text for later use; it does not display or accept the wording. !agent declares its result with :returns, including typed records and lists. Repeated :context attributes explicitly share bound values, and :min/:max constrain list results. Other bindings and chat history are not automatically included.

Typed generation

typed-agent.pattern.md
 1

topic = !ask {
    What would you like help planning?
}
result = !agent {
 {suggestion: text, confidence: number}
 topic
    Suggest one manageable next step for the supplied topic.
}
!show {
    Suggestion: {{result.suggestion}}
    Model confidence: {{result.confidence}}
}
-> end
Live result

The interactive example loads as you reach it.

The sample is a fixed reply. The runtime validates its declared record type before displaying it.

:returns is a result contract, including exact record fields, homogeneous lists, optional values, and resource references. :min/:max bound a returned list. Repeated :context attributes pass explicit values separately from the authored instructions. Invalid model replies leave the request pending. A type-correct confidence score is still a model claim, not a measured probability.

Authored intent, flexible wording

realized-wording.pattern.md
 1

answer = !ask {
    ~ Ask what would help the person take a small next step.
}
!show {
    You named {{answer}}.
}
-> end
Live result

The interactive example loads as you reach it.

Use the sample wording to see a realization become an ordinary question. No model is called.

~ instruction and ~ { … } request wording for a fixed authored move. A realized question or display contains one realization without mixed literal body text. The returned wording does not decide the next step. A bound realization stores text; a standalone realization displays it. !turn is an explicit delegated conversational generation step under its own authored prompt.

Closed categories and semantic suggestions

Declare a closed enum with type and a classifier with descriptions for its categories, explicit context, and a fallback. ?~ requests a model interpretation within those categories. The authored match determines the next step.

classify-a-message.pattern.md
 1
type Intent = answer | question | other
classifier intent -> Intent {
 prompt text
 answer "Answers the supplied prompt."
 question "Asks what the prompt means."
 other
}

prompt = "What would you like to explore?"
message = !ask {
    {{prompt}}
}
meaning = message ?~ intent {
 prompt
}
?match meaning {
 answer {
        !show {
            Thank you for sharing.
        }
    }
 question {
        !show {
            The question invites you to choose a topic.
        }
    }
 other {
        !show {
            We can leave that open for now.
        }
    }
}
-> end
Live result

The interactive example loads as you reach it.

Answer the question, then choose a sample model interpretation to follow its authored branch.

items |> select ~, filter ~, and rank ~ request suggestions constrained to the offered items. Each returns a record with outcome (decided or uncertain) and a typed items list. These are whole binding statements. Pure filter(items, helper) stays deterministic. A valid model result is still an interpretation or suggestion, and consequential choices should be reviewed by the participant. A classifier fallback means ambiguity; model errors leave the step pending instead.

semantic-suggestion.pattern.md
 1

items = [
    {name: "Take a pause", score: 2},
    {name: "Ask for help", score: 5},
]
suggestion = items |> rank ~ {
    Order by score, highest first.
}
?match suggestion.outcome {
 decided {
        !show {{suggestion.items}} {
        }
    }
 uncertain {
        !show {
            No confident suggestion is available.
        }
    }
}
-> end
Live result

The interactive example loads as you reach it.

Compare a sample decided result with explicit uncertainty. Items keep their original identity.

OperationDecided result
select ~Exactly one offered item.
filter ~Zero or more originals in catalogue order.
rank ~Every offered original once, in suggested order.

Every uncertain result has an empty typed list. A decided empty filter is different from uncertainty. Invented IDs, duplicates, incorrect selection counts, and incomplete rankings are rejected. Model interpretation does not stand in for a person’s choice, cancellation, acceptance, or permission to renew a revision budget.

Reviewing and refining wording

!refine presents the initial wording for review before any revision. Its body runs only when the participant requests a change. End that body with -> propose to offer the next candidate.

review-wording.pattern.md
 1
 reviewed

original = "I would like a little more space."
reviewed = !refine[rounds=2] original {
 current
    edited = !ask {
        How would you change this wording?
        {{current}}
    }
    -> propose edited
}
!show {
    Wording: {{reviewed.value}}
    Review outcome: {{reviewed.outcome.label}}
}
-> end
Live result

The interactive example loads as you reach it.

The result includes reviewed.value and reviewed.outcome.value. Outcomes include accepted, unresolved, and limit_reached; completion alone does not mean acceptance. rounds bounds revisions, and an optional renewable flag permits another budget only with explicit participant approval.

Wording and steps

Where AI is used to phrase a step, that wording is bounded by the authored step. It does not silently invent a new path or make the person’s choices for them.

The source stays portable and inspectable. The person supplies their responses and remains in control of whether to continue.

Pause, end, and replay

Execution waits at an explicit participant or model step. A reply is checked against its exact pending request before it is accepted. Invalid replies leave that step pending; already accepted work remains intact.

ActionResult
Pause / resumePreserve accepted answers and the pending step; resume returns to it.
Leave loopExit the current functional loop and continue below it.
End runCancel the run and active children, with no successful outputs or authored continuation.
-> endComplete successfully and return declared outputs.
Keep wordingExplicitly accept the current refinement candidate.
Finish without keeping itFinish refinement with an unfinished outcome; inspect the outcome before treating text as accepted.

Editing a definition never patches an active run. Saved runs pin their source, executable dependencies, reference data, and accepted results. Reopening uses that snapshot and verified reply history, without regenerating already accepted model results. Late or duplicate replies cannot advance a different pending step. These documentation examples keep only a temporary browser run and reset when restarted or left.

Errors, limits, and compatibility

The source editor reports compiler diagnostics with line positions. In an example, edit the code and run changes to see the same checks. A failed compilation shows diagnostics instead of pretending to render a valid program.

SymptomWhat to check
Unknown binding or fieldDeclare the value first, use a known record path, and read form fields only after submission.
Optional value used as text/numberCheck == None or != None in the branch where the contained value is used.
Empty list has no typeSupply an annotation such as items: list[text] = [] or a typed output.
Binding may already be assignedUse a new name for a derived value; only mutually exclusive branches may supply the same binding.
Missing output / branch valueSupply it with the same type on every relevant completing/continuing path.
Incomplete matchCover every known enum variant or static option ID; otherwise add a final :else.
Declaration treated as body textUse explicit braces to close the preceding question or display before the next binding.
Rejected model or participant replyCheck exact types, required fields, offered IDs, selection counts, and current request identity.
Unavailable importUse a complete executable pin or a published source-qualified data ID with a matching schema.

Source size, expression complexity, collection sizes, dependency depth, helper expansion, model results, and display graphics are bounded. Exceeding an execution limit fails explicitly; large visualizations can use a labelled data fallback with warnings. Keep open collections bounded and place substantial reusable procedures behind explicit interfaces.

All current features in this guide use :language 1. Legacy bindings, forward labels, list<T>, and prior supported version tags retain their interpretation. New syntax is additive and does not rewrite stored source or active runs. First-class functions, payload-bearing enum variants, and global event listeners remain outside the supported language described here. Extension packages have a separate authoring and delivery design; they are distinct from the executable and data imports above.

Try the editor

Open the editor to explore a practice’s source and preview. Change a line, then restart the preview to try the updated version. Blocks expose common steps, forms, and local decisions; use Source for types, helpers, flows, and other advanced constructs. Ctrl+Space opens source suggestions, and compiler diagnostics identify invalid types or missing values.

Mock replies let you explore AI steps without a model call. Preview does not change an already running practice. Start with a small complete example, then add declarations, interactions, and branches one at a time so each compiler check has a clear purpose.

Open the editor