QubeScript reference

QubeScript (.qube, also called QSS) describes a questionnaire as readable source. This reference covers the constructs the parser and runtime implement. Start with your first script, then use the QubeSurvey extension or qube to check and run the complete instrument.

The full authoring guide is also available as a text download. The examples here are small enough to try in the QubeSurvey extension.

How this page is organised

A complete script

@survey feedback @language en @mode cawi
 
-- Author comments do not appear in the interview.
@question helpful boolean
Was the information helpful?
 
@question comment text @multiline @optional
What could we improve?
 
@outcome complete
Thank you.

A source starts with one @survey header. Questions have stable names, typed answer contracts and Markdown text. An outcome ends the interview. Indentation helps reading but does not define blocks.

Question and option identities belong to the data contract. Keep them stable when changing wording. A new hosted upload creates a version; it does not change an already started attempt.

Source rules

  • Directives begin with @ at the start of a logical line.
  • -- starts an author comment that runs to the end of the line.
  • Directive names and code keywords are lowercase ASCII. Identifiers are case-sensitive, so Q1 and q1 are different names.
  • A physical newline ends a header or statement unless it falls inside () or [], after a trailing \, or before a continuation line that starts with ..
  • Semicolons separate code statements on one logical line. They are not used between declarations.
  • Write prompts, labels and messages as ordinary Markdown. Quotation marks in an option label are visible text.
  • Directive-looking text inside a fenced, quoted or indented code block is content, not a declaration.
  • Source is UTF-8. A leading byte-order mark is accepted and preserved by the editor. Newlines may be LF or CRLF.

A -- comment is lossless syntax: it is kept in the source tree and omitted from what the respondent reads.

Questions

A question has a name, an answer contract and Markdown content:

@question age integer
How old are you?

age is the question’s stable identity. It names the answer in data and in expressions, and renaming it is a data change. The text beneath it is what the respondent reads.

ContractAnswer
displayInformation with a Continue action; no answer
booleanTrue or false
integerWhole number
decimalDecimal number
textFree text; @multiline requests a larger input
date, time, datetime, durationTyped temporal value
singleOne option
multiMultiple options
rankingOrdered selected options
allocationInteger or decimal amounts distributed across rows
struct <name>Named fields in one answer

Questions and struct fields are required by default. @optional allows an answer to remain absent; @required states the default explicitly. A display question has no required or optional answer modifier.

Unanswered, unasked and answered-empty are different states. Missing answers do not become zero, false or an empty string. Expressions over answers carry absence; an absent condition is not true.

Question anchors

@question intro display
Welcome. This will take about five minutes.
 
@question newsletter boolean
Would you like the summary emailed to you?
 
@question joined date @optional
When did you first take out a policy?

A display question is a screen, not an answer: answers.intro is not a legal answer reference.

Options and domains

Use inline options for a one-off question. Declare a named domain when its options are shared by questions, ordering or row and column definitions.

@question devices multi
Which devices do you use?
@options
1: Phone
2: Computer
98: Other @specify
99: None of these @exclusive
ModifierMeaning
@specifyAttached text for the selected option. Bare @specify means text; @specify integer gives it another scalar contract.
@exclusiveMust be the only selected option; mixed whole-cell answers are rejected
@noreadAn interviewer should not read the option aloud; it remains selectable
@group id: HeadingGroup heading within an option domain
@first, @last, @fixed, @stoprandomPosition hints, combined into an order plan
@if conditionOffers the option only when the condition evaluates to true

Option identifiers may be numeric or text. A quoted text identifier such as "01" preserves its leading zero. Do not use numeric conversion for identifiers. All entries in one domain use the same identifier type; mixing numeric and symbolic identities is an error.

Groups and option hints

@group gives a contiguous set of options a heading. The bare form groups without displaying anything.

@options transport
@group public: Public transport
1: Bus
2: Train
@group private: Private transport
3: Car
4: Bicycle
99: Prefer not to answer @noread @exclusive
 
@question journey single
How did you travel?
@options transport

An option’s group is part of its presentation, not its identity. Pinning an option that belongs to a group tears it out of that group, and a page whose groups are no longer contiguous is rejected at projection. Declare options you intend to pin outside any group.

Reusing a domain

@options brands
1: Sunnyfield
2: Grainford
98: Other @specify text
 
@question awareness single
Which cereal brand have you heard of?
@options brands
 
@question purchase single
Which cereal brand did you buy?
@options brands
 
@question latest_purchase single
Which cereal brand did you buy most recently?
@options brands recapture

When a question reuses a named option list, a selected @specify answer is carried into the next question that offers the same option. If the respondent selects Other and enters Pams in the awareness question, the purchase question shows Pams as the option label and does not ask for the text again. Other keeps the same code in exported data, with the specified answer alongside it.

Add recapture to a question’s @options reference when it should ask for the specified text again. In this example, latest_purchase asks for a fresh value for Other. If the respondent selects Pams again in purchase, that answer also records the selected option and its specified text.

Dynamic answer domains

Follow-up questions can derive their option lists directly from earlier answers:

@options brands
  1: Alpha
  2: Brightline
  3: Cadence
  997: None of these @exclusive
 
@question used_brands multi
Which of these brands have you used in the past 12 months?
@options brands
 
@question most_frequent single @if not answers.used_brands.contains(997)
Which of the brands you selected do you use most often?
@options brands.select(answers.used_brands).except(997)

A multi-selection answer can also be bound directly to @options (such as @options answers.used_brands or @options answers.used_brands.except(997)). A declared domain can be filtered using answered selections directly without requiring .ids(): brands.select(answers.used_brands) or brands.except(answers.used_brands).

Content and interpolation

Question content is Markdown. {expression} inserts a value:

@question age integer
How old are you?
 
@question age_check integer
You told us you are {answers.age}. How old were you when you joined?

Interpolation is checked: a reference to a question that does not exist is an error, not a blank. Interpolation is recognised only outside code spans, code blocks, autolinks and raw HTML; \{ produces a literal brace.

Loops and expressions bind the same way as elsewhere:

  • {answers.question_name} reads an answer.
  • {loop_item.id}, {loop_item.label} and {loop_item.position} describe the current repeat member.
  • {function_name()} calls a checked function.
  • {launch.param("id")} reads frozen launch text.

Audience spans

:interviewer[...] marks text for the interviewer’s eye. It renders as a separate audience segment, so a CAWI page can hide it or style it differently without changing the answer.

@question note display
Everyone sees this line. :interviewer[Only the interviewer sees this one.]
 
@question ready boolean
Continue?

Audience spans contain inline Markdown and interpolation. They do not contain block Markdown or QubeScript declarations.

Pages and sections

By default each question is its own screen. @page groups questions that must be shown together:

@page contact
How can we reach you?
 
@question email text @optional
Email address
 
@question phone text @optional
Phone number
 
@end_page

The page’s own text is shown above its questions. @end_page closes the group, and so does the next page, section or lifecycle declaration; the closing directive is therefore optional. The grouping is explicit and never inferred from layout.

Questions on one page are answered as a unit: if any of them fails validation, none of them commits and the answers already given are held for correction. For the same reason, a question on a page may not condition on another question on that page — at the moment the page is shown, neither has been answered.

@page visit
@question visits integer @required
How many visits did you make?
@question note text @optional @multiline
Anything you would like to add?
@end_page

@section names a larger part of the questionnaire and is a routing target. Its Markdown is an optional title or introduction.

@section experience @checkpoint
@question helpful boolean
Was the visit helpful?
@section closing
@question thanks display
Thank you.

@checkpoint asks the host to save a background snapshot when accepted forward progress leaves that section. It is a section modifier and takes no value. Newer snapshots replace older ones. Ordinary pages stay local; Back, restoration and replay do not upload. Empty or skipped sections do not trigger a snapshot, and a terminal outcome uses the final submission instead. The runtime reports the section reached on the executed route; it performs no network operation itself.

A marked section inside @foreach is rejected. Mark an outer section that contains the repeat instead.

Routing

Questions are asked in source order until something says otherwise. Use a named @route for branching: arms are tested in order and the first true arm wins. @goto target is an unconditional jump. Targets can name sections, questions or declared endings.

@question consent boolean
Do you agree to participate?
 
@route consent_check
if answers.consent != true -> screenout
else -> details
 
@section details
About your experience
 
@question visits integer
How many times have you visited?
 
@question reason text @optional @if answers.visits > 1
What brought you back?
 
@goto complete
 
@outcome screenout
Thank you for your time.
 
@outcome complete
Finished.

@goto target @if condition performs a conditional jump; if the condition is false, execution falls through to the next element in source order. For simple early exits or screenouts, a conditional @goto can replace a single-arm @route:

@question consent boolean
Do you agree to participate?
 
@goto screenout @if answers.consent != true
 
@outcome complete
Finished.
 
@outcome screenout
Thank you for your time.

There is no questionnaire-level @if/@end_if wrapper. An else arm in a @route must be last; without it, an unmatched route simply falls through to the next declaration in source order.

Name every route. An unnamed one takes if as its identity, and a second unnamed route then collides with it.

Repeats

@foreach item in source … @end_foreach repeats a body for option-shaped members. A multiselect answer can be its source, and so can a domain or an order plan.

@options tools
1: Calendar
2: Messaging
 
@question used multi
Which tools do you use?
@options tools
 
@foreach tool in answers.used
@question rating integer
How would you rate {tool.label} from 1 to 5?
@validate rating_range answers.rating >= 1 and answers.rating <= 5
Enter a rating from 1 to 5.
@end_foreach

Within the body, tool.id, tool.label and tool.position identify the current member. Each answer is keyed by the whole chain of members, so a nested repeat has a distinct answer for every combination. The repeat syntax is @foreach, not @repeat.

A body is not a restricted dialect: questions, pages, validations, conditions and nested loops all work inside one, and a body @if is evaluated once per member.

@options tour_products
1: Motor
2: Home
 
@question tour_owned multi
Which?
@options tour_products
 
@foreach product in order(tour_products).reverse()
@question tour_note text @optional
Anything about {product.label}?
@end_foreach

A @route or @goto in a body that targets something outside the loop abandons the remaining members. Answers already given are kept; members never reached stay unasked rather than counting as skipped. The decision is made per member, so the same condition can let one member continue and send the next onward. From a nested loop, a jump clear of both loops abandons both.

Reading a question inside a loop from outside it is not possible: there is no single member to mean. Reading outwards is fine, because the outer member is fixed for the whole inner iteration. Jumping into a loop from outside is likewise prohibited.

Structs and fields

@struct answers several named things as one answer:

@struct contact
@field name text @length 60
Your name
@field email text @optional @pattern /@/
Email address
 
@question who struct contact
How can we reach you?

A struct contains consecutive @field declarations. The first directive other than @field ends it, so no closing directive is needed.

Field constraints are part of the contract and are checked when the answer is submitted:

ConstraintMeaning
@range 1..10Inclusive numeric range
@min 2, @max 8One-sided bounds
@length 60At most 60 characters
@length 2..5Between 2 and 5 characters
@pattern /…/Must match the regular expression
@default valueDeclared default; accepted and type-checked, but the current renderer does not prefill it
@if conditionIncludes and validates the field only when the condition evaluates to true
@required, @optionalRequiredness

@length counts characters, not bytes. A bound applies to an answer that is there — an absent optional field violates nothing.

@struct visit_details
@field visits integer @min 0 @max 20
Number of visits
@field rating integer @range 1..5
Rating from 1 to 5
@field label text @length 40 @required
A short label
@field reference text @pattern /^[A-Z]{2}$/ @optional
Optional two-letter reference
 
@question details struct visit_details
Tell us about your visits.

A field may use struct for a nested record. Direct and indirect struct cycles are rejected; repetition belongs on frame axes, not in a recursive value.

@struct quantity
@field amount integer @default 1
Amount
@question amount struct quantity
Enter an amount.

Frames, grids and allocation

A frame asks one question once per row, or once per row and column, without inventing a grid type. @rows and @columns attach the axes.

@options channels
1: Broker
2: Direct
 
@options satisfaction
1: Poor
2: Fair
3: Good
 
@options frame_products
1: Motor
2: Home
 
@question rate_products integer
Rate each product from 1 to 5.
@rows frame_products
 
@question grid single
For each product, how satisfied are you on each channel?
@rows frame_products
@columns channels
@options satisfaction

For a rating grid, use single, bind the item domain with @rows, and bind the rating domain with @options. A numeric frame can use both axes:

@options products
1: Product A
2: Product B
@options occasions
1: Weekday
2: Weekend
 
@question counts integer
How many times did you use each product?
@rows products
@columns occasions

An allocation distributes a total across rows. @values integer chooses whole-number values; decimal permits fractions. @total declares the sum and is optional, so a historical questionnaire without a declared target can still be replayed.

@options benefits
1: Convenience
2: Reliability
3: Price
 
@question importance allocation
Divide 100 points between these benefits.
@rows benefits
@values integer @range 0..100
@total 100

@range, @min and @max on @values limit each individual amount, and a correct total does not override those limits. For fractional limits, use @values decimal @min 0.5 @max 99.5. A scalar earlier answer can supply a limit, such as @max answers.budget. In a hosted interview, an unavailable limit is an error; it does not silently remove the bound. An absent optional cell does not violate a numeric bound.

The answer keeps one value per coordinate, and the runtime rejects a total other than the declared one. Nothing is merged, so analysis can address any cell.

Ordering options

An order plan is a value: you name it, reuse it and inspect it, rather than hiding a modifier on a question. @order order(domain).… applies one. When used on a question with declared @options, shorthands like @order shuffle, @order reverse, and @order shuffle_groups apply directly, and order() without arguments binds to the question’s own offered domain (e.g. order().shuffle() or order().reuse("prior_question")).

@options tools
1: Calendar
2: Messaging
3: Notes
 
@question main_tool single
Which tool do you use most?
@options tools
@order order(tools).first(tools.get(2))
 
@question other_tools multi
Which other tools do you use?
@options tools.except(answers.main_tool.ids())
OperationEffect
.only(entities…)Keep only those option entities or bare option IDs / ID ranges
.first(entities…), .last(entities…)Move entities, IDs, or ranges to the front or back
.fixed(entity, position)Place an entity at a one-based position
.before(entity, anchor), .after(entity, anchor)Move an entity relative to another
.reverse(), .reverse_if(condition)Reverse unconditionally or conditionally
.shuffle([domain])Seeded shuffle of all members or the named subset
.groups(domains…), .shuffle_groups()Define groups; shuffle whole blocks while keeping their internal order
.stop_at(entity), .stoprandom(entity)Keep the sequence through that entity, including it
.reuse("prior_question")Reuse the accepted offered option order of an answered scalar question

Bare option IDs and ranges can be passed directly to order methods such as order(d).first(3), order(d).first(2..3), and order(d).only(1, 2) without wrapping them in domain.get(...).

@first, @last, @fixed and @stoprandom declared on option entries are folded into shuffle() automatically. Pinning wins over randomisation: .last(…) after a .shuffle() keeps its options at the end.

Seeded randomisation

Randomisation is seeded per case, so the same case always draws the same order. A page re-shown after a validation error does not rearrange itself under the respondent, and replaying an answer log shows what they actually saw. Different cases draw differently, and two questions randomising the same domain draw independently.

@options benefits
1: Convenience @first
2: Reliability @fixed
3: Price
4: Support @stoprandom
99: Cannot judge @last
 
@question benefit single
Which benefit matters most?
@options benefits
@order order(benefits).shuffle()

Groups come from the domain’s own @group headers unless .groups(…) names them explicitly.

Reusing a prior order

order(products).reuse("earlier") reads the accepted offered order of the checked scalar selection or ranking question earlier, scoped to the same repeat member. The receiver keeps its own eligible identities: surviving identities follow the saved order and newly eligible identities append in the receiver’s declared order. Selected membership and mention or rank order are separate facts and are not reused.

A missing or cleared source refuses rather than returning a default order. The target must be one literal question name; unknown, self-referencing, same-page and unsupported grid or struct sources are rejected. Back and explicit Continue use accepted history; saved answers do not advance the interview by themselves.

Filtering with a domain

For a filtered follow-up, use domain.select(ids) or domain.except(ids). Domains and answered selections also support get(id), contains(ids...), ids() and count(). select and except accept answered multi-selections directly (such as domain.select(answers.prior) or domain.except(answers.prior)) without requiring .ids(), as well as bare scalar IDs and ID ranges.

Multi-code and range .contains(...) checks evaluate whether any of the specified options are present: answers.q.contains(1, 2) and answers.q.contains(1..3).

Guard answer-derived filters with answers.q.is_answered() or answers.q != none when the source answer can be absent. Missing selectors refuse; they are not interpreted as an empty set or an unrelated code. A matrix needs an explicit cell projection.

Validation

@validate name condition declares a check, followed by the respondent-facing message. Error is the default severity and blocks progress. Warning and confirm checks require an explicit acknowledgement. @focus question_name identifies the input to highlight.

@question age integer
How old are you?
@validate age_range answers.age >= 18 and answers.age <= 120 @severity error @focus age
Enter an age from 18 to 120.
@validate age_unusual answers.age < 100 @severity confirm @focus age
Please confirm this age.
SeverityBehaviour
errorBlocks submission; the answer is not accepted
warningProjected as a soft check
confirmRequires the respondent’s acknowledgement before acceptance

Constraints also include numeric bounds, text length and pattern, and selection limits — the same rules a struct field declares. Check the whole source and run invalid-answer cases; parser acceptance alone does not show that routing or measurements are correct.

Languages and overlays

The survey header declares the primary @language and @mode. Another @language starts an overlay for existing content. @fallback names the language and mode to use for content omitted from that overlay. Keep question identities and answer contracts in the primary source.

@survey translated @language en @mode cawi
 
@question helpful boolean
Was this helpful?
 
@outcome complete
Thank you.
 
@language nl @mode cawi @fallback en cawi
 
@question helpful
Was dit nuttig?
 
@outcome complete
Dank je wel.

An overlay carries content only. It cannot add contracts, routing or code, so a translator cannot change what the instrument measures. Fallbacks are explicit: an overlay with no @fallback does not inherit the primary content implicitly.

Endings

@outcome declares a terminal ending. @suspension declares a resumable stopping point; it is not a completed interview. The optional @code annotation is checked source metadata; the Run still maps the named outcome to its collection and retention policy.

@question ready display
We will continue this later.
@suspension later @code 2
Paused.
@question helpful boolean
Was this helpful?
@outcome complete @code 1
Thank you.

A host must distinguish these lifecycle states. No current page does not, by itself, mean successful completion. The Run’s outcome and retention policy decides what a named outcome means for hosted collection, and a script cannot authorize acceptance or retries.

An interview that reaches a suspension stops there and can be picked up later. Because both a finished and a suspended interview show no page, ask the session which it is rather than inferring it. Resuming is recorded, so replaying a case that was never resumed leaves it suspended rather than running on to the outcome.

Values and functions

value NAME = expression declares an immutable package constant. It cannot depend on answers or case state. A function computes from current answers.

value MONTHS = 12
 
@question monthly_cost decimal
What is the monthly cost?
 
function annual_cost() returns answer(decimal) = answers.monthly_cost * MONTHS
 
@question estimate display
The annual estimate is {annual_cost()}.

function owns every reusable calculation, with or without parameters. Both forms are ordinary functions: callers use parentheses and dependency analysis follows their calls.

value satisfied_from = 4
 
function is_satisfied(rating integer) returns boolean = rating >= satisfied_from
 
@question rating integer
How satisfied are you?
 
@question satisfied display @if is_satisfied(answers.rating)
Thank you for the positive rating.

A block body uses let, assignment, if/elseif/else, for, return and end:

function band(score integer) returns text
if score < 3 then return "low" end
if score < 7 then return "medium" end
return "high"
end
 
@question score integer
How would you score the visit from 0 to 10?
 
@question band_label display
Band: {band(5)}. Thank you.

Statements belong inside functions only. A bare assignment at questionnaire level is prose and can be shown to the respondent. Recursive call cycles are rejected.

Passing an answer to a function

A function that expects an ordinary value accepts an answer. What propagates is absence: a function applied to a missing answer is missing, and its body does not run. The condition is then not true and the question it guards is not shown, rather than the answer quietly becoming 0.

value adult_from = 18
 
function is_adult(age integer) returns boolean = age >= adult_from
 
@question age integer
How old are you?
 
@question adult display @if is_adult(answers.age)
You are an adult.

If age was never asked, is_adult(answers.age) and its negation are both false. An unanswered question routes nowhere. Ranges behave the same way, so 1..answers.age is a range when the age is there and absent when it is not.

Standard library

The following calls execute in the native runtime. In signatures, x is an ordinary value, a is an answer wrapper, items is a collection, and domain is a declared option domain. Square brackets in a signature mark an optional argument; they are not part of the call syntax. ... means that several arguments may be supplied.

Read answers and handle absence

answers.note carries both the answer state and its payload. Arithmetic and answer methods propagate absence. Text and regex functions need plain text: extract the payload, choosing an explicit fallback when absence is acceptable.

An answer can be tested directly against none: answers.q == none is true when the question has no answered payload (unasked or left unanswered), and answers.q != none is true when an answer is present.

Both prefix functions and postfix methods on answers are supported:

Call / MethodResult
answer.is_answered(a) / a.is_answered()Whether an answer has a payload.
answer.is_unanswered(a) / a.is_unanswered()Whether it was asked but has no answer.
answer.is_unasked(a) / a.is_unasked()Whether it has not been asked.
answer.value(a) / a.value()Payload; refuses if no payload is available.
answer.value_or(a, fallback) / a.value_or(fallback)Payload, or the supplied fallback when absent.
answer.reason(a) / a.reason()Recorded absence reason, or none.
@question note text @optional
Add a short note, or leave it blank.
@validate note_length text.length(answer.value_or(answers.note, "")) <= 80
Use at most 80 characters.
 
function cleaned_note() returns text = text.trim(answer.value_or(answers.note, ""))
 
@question note_summary display
Characters: {text.length(cleaned_note())}. Contains a letter: {regex.is_match(/[A-Za-z]/, cleaned_note())}.

For a multiselect, answers.used.count() and answers.used.ids() retain the answer wrapper. Use answer.value(...) or answer.value_or(...) when passing their results to a function that needs an ordinary collection or number.

Numbers and totals

CallResult
abs(x), sign(x)Absolute value; sign as -1, 0 or 1.
min(items...), max(items...)Smallest or largest comparable value.
clamp(x, lower, upper)Value bounded by the two limits.
sum(items...), mean(items...), median(items...)Total, arithmetic mean or middle value.
round(x [, digits])Decimal rounding; ties go away from zero. Digits default to zero.
round_even(x [, digits])Decimal rounding; ties go to the even result.
floor(x), ceil(x)Integer at or below/above the value.
percent(part, whole)part / whole * 100; zero whole refuses.

Use a decimal operand for fractional division: 1.0 / 8 is 0.125, while integer division returns a whole number. Empty aggregates, invalid arithmetic and overflow refuse evaluation rather than manufacture a result.

function score_mean() returns decimal = mean([2, 4, 6])
function safe_rating() returns integer = clamp(12, 0, 10)
function share() returns decimal = percent(3, 8)
 
@question number_summary display
Mean: {score_mean()}. Bounded rating: {safe_rating()}. Share: {share()}.
Rounded: {round(2.5)}; even rounding: {round_even(2.5)}; fraction: {1.0 / 8}.

Text and regular expressions

CallResult
text.length(text), text.bytes(text)Unicode scalar count; UTF-8 byte count. Neither counts visible graphemes.
text.trim(text)Remove surrounding whitespace.
text.lower(text), text.upper(text)Unicode lower/uppercase conversion.
text.casefold(text)Currently the same lowercase conversion as text.lower.
text.starts_with(text, part), text.ends_with(text, part), text.contains(text, part)Boolean text tests.
text.replace(text, old, new)Replace every literal occurrence.
text.split(text, separator)List of pieces; empty pieces are retained.
regex(pattern [, flags])Compiled pattern. Flags i, m, s, x control case, line boundaries, dot and whitespace.
regex.is_match(pattern, text)Boolean match test.
regex.find(pattern, text)First matching text, or none.
regex.find_all(pattern, text)List of matching texts.
regex.replace(pattern, text, replacement)Replace all matches; captures can be used in the replacement.
regex.split(pattern, text)List split at matches.

Regex literals such as /^[A-Z]{2}$/ are also supported. These are Rust-style regular expressions, not JavaScript patterns; lookaround and backreferences are not supported. Extract optional text with answer.value_or before matching.

function code_clean() returns text = text.upper(text.trim(" ab-12 "))
function digits() returns list(text) = regex.find_all(/[0-9]+/, "A12 B34")
 
@question text_summary display
Code: {code_clean()}. Characters/bytes: {text.length("Māori")}/{text.bytes("Māori")}.
Digits found: {collection.count(digits())}. Replaced: {regex.replace(/[0-9]+/, "A12 B34", "#")}.

Collections and ranges

[1, 2, 3] is a finite range-shaped collection. list(...) keeps duplicates; set(...) and select(...) remove them. Constructors flatten their collection arguments. Collection indexes and order positions start at one.

CallResult
range(start, end [, step]), r(start, end [, step])Inclusive range; an explicit step requires integers and cannot be zero.
select(items...), list(items...), set(items...)Distinct range, ordered list or distinct set.
collection.count(items), range.count(items)Number of members.
collection.is_empty(items)Whether there are no members.
collection.contains(items, x), range.contains(items, x)Membership test.
collection.first(items), collection.last(items)First/last member, or none.
range.min(items), range.max(items)First/last member in the supplied order; use min/max for numeric extrema.
collection.distinct(items)List with duplicates removed, retaining first occurrence.
collection.take(items, count), collection.drop(items, count)First members, or the remainder; count must be nonnegative.
range.union(left, right), range.intersection(left, right), range.difference(left, right)Set operations retaining left-hand order, with new union members appended.
function steps() returns range(integer) = range(1, 5, 2)
function distinct_count() returns integer = collection.count(collection.distinct(list(2, 2, 4)))
 
@question collection_summary display
Steps: {range.count(steps())}; first: {collection.first(steps())}; last: {collection.last(steps())}.
Distinct count: {distinct_count()}; remaining: {collection.count(collection.drop(steps(), 1))}.

Option domains, selections and order plans

A code such as 2 identifies an option within a domain. domain.get(2) returns the option entity, which carries its stable source identity. Use codes for selection and filtering and option entities for order anchors.

Domain callResult
domain.select(ids...), domain.except(ids...)Keep/remove matching codes while preserving domain order.
domain.union(other), domain.intersection(other), domain.difference(other)Combine or filter declared option entities.
domain.get(id)Option entity; refuses if unavailable.
domain.ids(), domain.count(), domain.is_empty()Codes, count or empty test.
domain.contains(id)Whether that code is present.
domain.label(id)Label, or none if unavailable.
domain.source(id)Declared source-domain identity; refuses if unavailable.

Methods on a selection are available as selection.NAME(value, ...) too.

Selection callResult
picked.select(ids...), picked.except(ids...)Derive a dynamic domain by selecting or excluding matching codes.
picked.union(other), picked.intersection(other), picked.difference(other)Combine or filter selections and domains.
picked.contains(id), picked.count(), picked.is_empty()Membership and size.
picked.ids(), picked.first()Codes, or first selected option entity (none if empty).
picked.other_value([id])Associated Other payload for that option, or the first such payload; none if absent.
picked.offered_order(), picked.selected_order()Recorded stable option identities, not numeric codes.

Use order(domain) to construct a plan. An order plan can drive @order or @foreach. Each iterated entity has id, label and one-based position.

Order callEffect
plan.only(entities...)Retain those option entities.
plan.first(entities...), plan.last(entities...)Move entities to the front/back, preserving their relative order.
plan.before(entity, anchor), plan.after(entity, anchor)Move an entity relative to another.
plan.fixed(entity, position)Move an entity to a one-based position.
plan.reverse(), plan.reverse_if(condition)Reverse unconditionally or conditionally.
plan.shuffle([domain])Seeded shuffle of all members or the named subset.
plan.groups(domains...), plan.shuffle_groups()Define groups; shuffle whole blocks while keeping their internal order.
plan.stop_at(entity), plan.stoprandom(entity)Keep the sequence through that entity, including it.
plan.reuse("prior_question")Reuse the offered option order of an answered scalar selection/ranking question.

Plan operations compose in their written order. A repeated source must belong to the active member. An unanswered or cleared source, a source outside that scope, or a grid or struct source is refused. See Ordering options for the full reuse contract.

Dates, times and durations

Temporal values retain precision: a year-only date is not January 1. When two partial dates overlap, temporal.before and temporal.after can return none.

CallResult
date(year [, month [, day]])Date with year, month or day precision.
time(hour [, minute [, second]])Time with hour, minute or second precision.
datetime(date [, time [, zone]])Date/time with optional zone text.
duration(years, months, weeks, days, hours, minutes, seconds)Positional integer parts; omitted trailing parts are zero. For seven days, use duration(0, 0, 0, 7).
temporal.precision(x), temporal.year(x)Precision name; year.
temporal.month(x), temporal.day(x)Month or day, or none when that precision is absent.
temporal.add(x, duration [, policy])Add a duration. Month-end policy is "reject" (default) or "clamp".
temporal.between(start, end [, unit])Duration from start to end; optional exact unit is "days" or "seconds".
temporal.before(a, b), temporal.after(a, b)Boolean relation, or none if precision makes it indeterminate.
temporal.overlaps(a, b)Whether the values overlap or have equal boundaries.
function anniversary() returns date = temporal.add(date(2024, 2, 29), duration(1), "clamp")
 
@question temporal_summary display
Anniversary: {anniversary()}. Year-only precision: {temporal.precision(date(2026))}.
Month known: {temporal.month(date(2026)) != none}. Same day: {temporal.overlaps(date(2026, 3, 1), date(2026, 3, 1))}.

Calendar operations do not perform timezone conversion. datetime stores the zone text; it does not infer one from the respondent’s location. Calendar durations (months, years) stay distinct from fixed elapsed durations.

Records and reusable validation checks

Use a struct’s value for these functions, extracting it with answer.value when needed. Field access such as answers.details.rating remains the usual way to read a known field.

CallResult
struct.has(value, field), struct.get(value, field)Field presence; value or none. Field is text.
struct.with(value, field, replacement)Copy with that field replaced or added; the collected answer is unchanged.
struct.fields(value)List of field names in sorted order.
validate.required(x)Presence and nonempty check; an answered wrapper passes even if its text is empty.
validate.range(x, allowed), validate.count(items, allowed)Value or count belongs to the allowed range.
validate.length(text, allowed), validate.pattern(text, regex)Unicode scalar length or regex test.
validate.unique(items)Whether collection members are distinct.
@struct visit_record
@field rating integer @range 1..5
Rating
@field note text @optional
Note
 
@question visit struct visit_record
Describe the visit.
 
function rating_copy() = struct.with(answer.value(answers.visit), "rating", 5)
 
@question record_summary display
Original rating: {struct.get(answer.value(answers.visit), "rating")}; copy: {struct.get(rating_copy(), "rating")}.
Fields: {collection.count(struct.fields(answer.value(answers.visit)))}; note present: {struct.has(answer.value(answers.visit), "note")}.
@question reference text
Enter a two-letter code.
@validate reference_valid validate.length(answer.value(answers.reference), 2..2) and validate.pattern(answer.value(answers.reference), /^[A-Z]{2}$/)
Use exactly two uppercase letters.

Host facts and services

These operations consume a recorded host result rather than doing local I/O. The binding and host determine the result contract. An unavailable result suspends the native runtime; it does not produce a guessed value.

CallResult or purpose
environment.now(), environment.today()Recorded datetime or date.
environment.random_integer(range, decision_id)Recorded integer decision; ids make replay explicit.
environment.allocate(capability, input)Recorded allocation decision; configured campaign quotas return a boolean.
environment.read(capability, input, request_id)Recorded read result.
environment.request(effect, input, request_id)Recorded effect result; declared unit contract.
service.call(binding, payload), service.evaluate(binding, payload)Typed configured service result.
launch.param("literal_name")Frozen optional launch text; missing is none, blank remains blank.

See Services for actual hosted bindings and Fieldwork for quota calls. The current library does not execute proposed formatting, parsing or frame mapping helpers; use the calls above.

Services and quotas

service.call("name", payload) and service.evaluate("name", payload) use the recorded environment boundary. An unresolved call suspends until the host supplies a typed result. The host owns service configuration, authorization, credentials and budgets. Repeated reads of the same call and scope reuse the saved observation. Language support does not mean a service is configured or available offline.

environment.allocate("campaign-quota", "binding_name") suspends for a recorded boolean quota admission result. The host verifies the preceding answers and checks the configured shared quota cells; the script routes on the result. Admission and final completed membership are different facts: changed final answers can take a cell over target.

service.call("quota-score", "binding_name") uses the same primitive for a configured advisory expression. For a completed-cell rim binding, pass a LIST or range containing the binding name followed by one declared category id from each dimension:

function joint_priority() returns integer = service.call("quota-score", ["joint-priority", "young", "north"]).score

The host checks these ids against the verified current answers and explicit tuple support. A script must supply its actual classification; the literal example applies only to the Young/North tuple. Priority fits final quota targets to the authoritative joint completed counts, then uses desired final completions divided by max(completed, 1), normalized to 0..1000. It uses completed interviews, not held places or eligible sample inventory. When every achieved margin meets its target, actionable scores are zero. Unavailable classification, unsupported tuples or a failed actionable fit refuse a fresh score.

The completed-cell result has exactly six fields:

FieldType and meaning
scoreInteger 0..1000; advisory priority.
target_revisionInteger; quota target revision used by the fit.
plan_revisionInteger; cached fit revision.
contribution_revisionInteger; authoritative completed-tensor revision.
policy_revisionText; immutable quota policy revision.
semantic_versionText; completed-target-rim-v1.

Replay reuses the original recorded result for the full typed call and repeat scope, even after targets or counts change. Scripts own thresholds and routing; a score does not grant admission or undo completion. Use the allocation call separately; score 1000 cannot override a full hard quota. Repeat-question classification and old inventory-rim bindings are outside this hosted door. Quota collection must be enabled for the Run’s deployment; see Fieldwork.

Launch parameters

launch.param("id") reads an optional text value supplied by the host, preserving leading zeros and short strings. A missing name is none; a present blank is empty text. Each name must be a literal matching [A-Za-z_][A-Za-z0-9_-]{0,63}; checked source declares which URL values the hosted attempt retains.

@question launch_info display
Interview {launch.param("id")} in municipality {launch.param("gkz")}.
 
@question missing_identifier display @if launch.param("id") == none
The link did not include an interview identifier.

The first successful Start freezes these untrusted values. Reload and resume keep them even if the URL changes. They do not identify an authorized account or sample record, and displaying a value does not turn it into an answer.

At most 64 names, 4,096 UTF-8 bytes per value and 16 KiB of map JSON are accepted. launch.param is a pure read, separate from answers, privileged bindings and recorded service calls.

Back and replay

Back is a runtime navigation action, not an authored @back directive. It preserves history: an unchanged continuation reuses it, while changed answers create a new branch. Derived calculations and applicability follow the current answers. Back does not undo an external action already performed.

Recorded service and quota results are reused for the same call and repeat scope, so replay does not re-execute a host action.

Current limits

These are known gaps in the current implementation, not syntax you should design around.

  • @default is not prefilled. The parser and type checker accept it; the current renderer does not populate the input.
  • Formatting, parsing and frame helpers. Proposed helpers such as format.number, parse.integer, temporal.format, frame.map and domain.where have design entries but no runtime dispatch. Use the calls listed above.
  • Cross-member aggregates. There is no way to total or count a loop’s answers from outside it.
  • Constructing options in code. A function can return an existing domain or a union of domains, but there is no way to build one dynamically.
  • Comparing durations. date - date gives a duration, but two durations cannot be ordered without a reference date.
  • General named saved orders. .reuse("prior_question") is supported for an accepted scalar selection or ranking question; independent order registries and ambiguous grid or struct sources are not.
  • Checkpoints inside a repeat. A @checkpoint section inside @foreach is rejected; mark an outer section instead.

Directive index

DirectiveKindPurpose
@surveyheaderNames the instrument, its primary language and its mode.
@language, @modeheader, overlayPrimary projection, or the start of an overlay.
@fallbackoverlay headerLanguage and mode to use for omitted content.
@optionsdeclaration, clauseNamed domain, inline domain, or a question’s domain reference.
@groupdomain entryHeading over a contiguous set of options.
@specify, @exclusive, @noreadoption modifierAttached text, exclusive selection, interviewer non-read.
@first, @last, @fixed, @stoprandomoption modifierPresentation position hints.
@ifquestion, option, fieldConditional applicability (also conditional jump on @goto).
@questiondeclarationA question, its name and its answer contract.
@required, @optional, @multilinequestion, fieldRequiredness and text input size.
@rows, @columnsquestion clauseFrame axes.
@values, @totalquestion clauseCell value contract and allocation total.
@orderquestion clausePresentation order plan.
@validatequestion clauseNamed check with a message.
@severity, @focusvalidation modifierHow hard the check is; which input it highlights.
@struct, @fielddeclarationComposite answer and its fields.
@range, @min, @max, @length, @pattern, @defaultfield modifierTyped field constraints.
@sectiondeclarationNamed part of the questionnaire, and a routing target.
@checkpointsection modifierAsk the host for a background snapshot on exit.
@page, @end_pagedeclarationSeveral questions on one screen.
@routedeclarationOrdered conditional branching.
@gotodeclarationUnconditional or conditional (@goto target @if condition) jump.
@foreach, @end_foreachdeclarationRepeat a block per option.
@outcomedeclarationTerminal ending.
@suspensiondeclarationResumable stopping point.
@codelifecycle modifierChecked ending code metadata.

Code declarations use value and function; both are keywords rather than directives. Statements inside a function use let, if, elseif, else, for, return and end.

Check a complete instrument

Use the fictional studies to inspect complete instruments and independent behavioral requirements. Use qube check and run the instrument before uploading. A complete source has one survey header and an explicit ending; broken buffers may still produce editor diagnostics.

For a hosted Run, the source is checked again and the interview is replayed from its recorded input trace. Fieldwork explains how the source is used in a hosted Run.