コンテンツにスキップ

Scenario schema

This page covers the scenario model (steps, assertions, preconditions). It also covers the loaders that parse a *.yaml, expand its component and data references, and serialize the scenario back.

bajutsu.common.scenario

Scenario spec — the structure normalized from natural language.

The package keeps the data shapes (models), parsing (load), compile-time expansion (expand), tag selection (select), and serialization (serialize) in separate modules so a change to one rarely touches the others (BE-0043). The full public API is re-exported here, so from bajutsu.common.scenario import Scenario, load_scenarios, ... keeps working unchanged.

ComponentResolver

Bases: ScopedResolve

Resolve a use: { component: <ref> } ref by the ref's own shape (BE-0422).

Binding a file's own components: map, the suite root, and the directory refs resolve against into one object is what lets the deterministic run gate and the device-free readers expand the same scenario file identically — the two built separate resolvers before, and had already drifted on how a malformed component file reported (BE-0150).

scope_for(ref)

The resolver ref's own steps expand under: the file scope for a path ref, else self.

for_component_file()

A sibling bound to no local names, for expanding a component file's own steps.

A component file is a bare params + steps mapping and declares no components:, so every bare ref inside one is undefined however the including scenario file spelled its own map. A component-file scope is already that, so it answers with itself; every other resolver builds its sibling once and reuses it, keeping one ref cache across the whole expansion.

App

Bases: _Model

Activate an app and run inner steps against its own UI (iOS XCUITest and Android adb).

bundle_id is a plain scenario-level string, not a value drawn from a fixed set — any installed app can be named, including one the scenario's own target has no way to open itself. On Android it is the app's package name. Inner steps address that app's own accessibility tree, exactly as they address the test target's outside this block; control returns to whatever was active before the block once it ends, matching Web's enter/leave contract.

Assertion

Bases: _Model

One machine check. Exactly one kind may be set.

AttributeMatch

Bases: _Model

attribute: exactly one of equals / contains / matches / absent: true, on attribute name.

Read on demand by the web driver (Driver.read_attributes) when the assertion is evaluated, so the element snapshot never carries attributes no assertion names.

Background

Bases: _Model

Send the app to the background, as pressing the Home button does.

Backgrounds without terminating (SpringBoard is brought to the front), so the app's state survives for a later foreground.

CaptureRule

Bases: _Model

A capturePolicy rule — capture the artifacts in capture when its on trigger fires.

CleanupRule

Bases: _Model

One cleanup entry (BE-0392): the teardown steps to run for one scenario outcome.

on names the outcome this entry answers — always, or the scenario's own machine-checked verdict (success / failure). failure is the word capturePolicy's Trigger.result spells for a failed outcome too (there one step's, here the whole scenario's), so one word names a failed outcome everywhere (BE-0452); always is the one addition, for cleanup that does not depend on the outcome at all. More than one entry may carry the same on and they compose in declaration order, the same way two capturePolicy rules may share a trigger. The steps share the enclosing scenario's vars.*, so an entry can delete the very record an earlier http step's saveBody captured.

ClearClipboard

Bases: _Model

Clear the Simulator's pasteboard.

ClearKeychain

Bases: _Model

Reset the Simulator's keychain (saved passwords, certificates).

ClearStatusBar

Bases: _Model

Remove any status bar overrides (restore the live status bar).

ClipboardMatch

Bases: _Model

clipboard: verify what the app copied to the pasteboard — exactly one of equals / matches.

Read off the device (simctl pbpaste on iOS; the BajutsuAndroid receiver on Android, BE-0233), so it needs the per-device control channel and is unavailable on the fake driver / in parallel runs.

Component

Bases: _Model

A reusable, parameterized sequence of steps.

params are the names a caller must supply via use: { with: {...} }; the steps reference them as ${params.<name>}.

CountMatch

Bases: _Model

count: exactly one of equals / atLeast / atMost.

CountOp

Bases: _Model

A count comparison with no element selector — exactly one of equals / atLeast / atMost.

The element-free counterpart to CountMatch, for aggregating over the network timeline (e.g. an event's multiplicity) rather than over screen elements.

DatetimeValue

Bases: _Model

generate: { datetime: … } — the current time as text, optionally shifted and zoned.

format is a strftime pattern (ISO 8601 when omitted); the four offset* fields are signed and additive, so a value an hour before tomorrow is offsetDays: 1, offsetHours: -1. timezone is an IANA name; the default is UTC, so a scenario matching a date the app renders in the device's own zone must name that zone (pinning the device's zone is BE-0158's concern).

Drag

Bases: _Model

drag action — a real pointer drag of an element (on) in a direction (BE-0227).

Where swipe's directional form scrolls (revealing off-screen content), drag grabs the element and moves it — a resize divider, a slider thumb, a reorder handle, a map inside a canvas: any control you drag rather than scroll. amount sets how far to travel as a fraction of the screen (0 < amount ≤ 1); omitted, a small default distance is used. It matters on the web backend, where a directional swipe is a wheel scroll (which does not move a grabbed element) but a drag is a genuine pointer drag (move → down → move → up). On iOS / Android a real OS drag both scrolls and moves handles, so swipe's directional form and drag coincide there.

Email

Bases: _Model

email — poll a mailbox until a matching message arrives, extract a value into ${vars.*}.

match selects the awaited message, extract pulls the value, and timeout (seconds, required) bounds the poll — a condition wait, never a fixed sleep (BE-0046). The mailbox endpoint lives in config (targets.<name>.mailbox), so the scenario stays app-agnostic and credential-free.

EmailExtract

Bases: _Model

Pull a value from the matched message body into ${vars.<var>} via a regex.

bodyMatches is a regex; its first capturing group (or the whole match, if it has none) is the value written to var. A matched message whose body the regex does not hit fails the step.

EmailMatch

Bases: _Model

Which message email waits for: recipient and/or subject, AND-ed. At least one is required.

Eval

Bases: _Model

eval — run a list of operations over a string and store the result in ${vars.*}.

Despite the name it runs no code: ops draws from a fixed vocabulary (eval_ops.SIGNATURES) a scenario cannot extend, and the loader checks every argument and the string/list type flow before the run starts. A list result is stored as compact JSON array text. Local and deterministic — no model, no network.

EvalTarget

Bases: _Model

into of an eval step: one ${vars.*} slot, or one slot per list element.

vars spreads a list result over several names in order — the first element into the first name, and so on. A list longer than vars leaves its extra elements unassigned; a shorter one fails the step at run time, since a name left unset would surface later as an unrelated mismatch.

names property

Every variable this target writes, in order.

EventMatch

Bases: _EndpointMatch

An analytics / telemetry event the app sent (BE-0048).

Matched over the captured request timeline by endpoint (url / urlMatches / path / pathMatches / method, AND-ed, same meaning as RequestMatch) and the query / body key/value dictionaries (BE-0463; a flat body of top-level text equalities is still its simplest form). count is the expected multiplicity (default: at least one). At least one of an endpoint criterion, query, or body is required, so an event always pins something.

ExcludeRegion

Bases: _Model

A rectangular region to ignore during visual comparison (e.g. status bar, clock).

Coordinates are in screenshot pixels — a fixed box, stable only while the layout is. Use SelectorRegion to mask by element instead, which survives reflow and resolution changes.

Exists

Bases: _Model

exists: { <selector>, negate? } (selector inline, optional negate).

Extract

Bases: _Model

Capture a UI element's property into a runtime variable (vars.*).

ForEach

Bases: _Model

Iterate over elements matching a selector.

Each element's identifier is stored as vars.<as> and the nested steps are executed.

Foreground

Bases: _Model

Resume a backgrounded app to the foreground (simctl launch, without terminating it).

The other half of background. It adds no settle sleep — any wait after resuming is the scenario's own condition wait.

Generate

Bases: _Model

generate — compute a random or current-datetime value into ${vars.*} (BE-0377).

Exactly one generator kind produces the value, and into.var names the slot a later type / assert reads it from — the same placement totp uses. Local and deterministic: a generator draw or a clock read, never a model and never the network. Only the value varies between runs; a step the validator accepted always executes and always succeeds.

GoldenMatch

Bases: _Model

golden: compare the live element tree against a recorded golden file (BE-0006).

The path is resolved against the golden context's base directory. The comparison is field-level per BE-0006 rules: exact on identity/state, set-equal on traits, tolerant (sanity only) on frame geometry.

Gone

Bases: _Model

until: { gone: <Selector> } — wait until a selector no longer matches any element.

Group

Bases: _Model

A named run of steps, expanded in place before run.

Purely an authoring/report convenience: expand_components replaces a group step with its own steps, tagging each with name for report.html to fold. run never sees group.

HandleSystemAlert

Bases: _Model

handleSystemAlert action — tap a button on an iOS SpringBoard permission prompt (BE-0316).

A permission alert lives outside the app's accessibility tree (SpringBoard owns it), so it carries no app-assigned identifier, trait set, or value — only its visible text. sel therefore accepts the label-based fields alone (label / labelMatches / index) and rejects the rest at parse time. timeout bounds the condition wait for the prompt, required exactly as wait's is.

Two ways to name the button, exactly one per step: handleSystemAlert: { sel: { label: "Allow" }, timeout: 10 } handleSystemAlert: { prompt: notifications, choice: grant, timeout: 10 }

The second form states the intent and lets the run resolve the label from the scenario's locale (BE-0320), for the prompts a permissions preset cannot pre-answer — notification authorization, App Tracking Transparency, and the cross-process paste consent (BE-0369). It is worth reaching for because the literal text is easy to get subtly wrong: English's own deny button spells its apostrophe typographically, not as the ASCII character a hand-typed label carries. Every other alert keeps naming its button through sel, unchanged.

Not every covered prompt is nameable here. This step reads the SpringBoard query alone, so a prompt iOS raises into the application's own process — savePassword — is rejected below and declared as a systemAlert interrupts entry instead (BE-0406, BE-0473).

resolved(locale)

This step with prompt/choice turned into the sel the locale's SpringBoard renders.

A sel form returns unchanged, so the resolution is a no-op for every alert outside the prompts the lookup covers. Under a language the label table does not cover, a prompt with a position rule (role) also returns unchanged: that rule is resolved against the live alert instead, since the label it lands on is exactly what this run cannot know in advance (BE-0445).

Raises:

Type Description
UncoveredSystemAlertLocale

the lookup has no labels for the locale's language and the prompt has no position rule either — the step fails loudly rather than tapping a guessed button.

role()

The position rule naming this step's button, for a prompt/choice step that has one.

HttpRequest

Bases: _Model

Issue an HTTP request (for test-data setup, webhook triggers, API calls).

The response status is checked against status (if given); a mismatch fails the step. saveBody stores the response body text as vars.<saveBody> for subsequent ${vars.*} interpolation. extractBody (BE-0440) pulls one or more named fields out of a JSON response body, by path, into vars.* — independent of saveBody, which a step may set alongside it, neither, or both.

duplicate_extract_var()

The first var that collides — repeated in extractBody, or equal to saveBody — or None.

If

Bases: _Model

Conditional execution.

Evaluate an assertion as the condition, then run then steps if it passes or else steps otherwise.

InstallApp

Bases: _Model

Install the build of the device-group member from onto the device the step runs against.

The scenario names a target, never a path: the build artifact stays in that target's config (appPath), so the scenario stays app-agnostic. keepData (default true) installs over an existing build of the same identifier and keeps its data container; false uninstalls that identifier first. The step launches nothing — a foreground addressed to the member does.

Interrupt

Bases: _Model

A handler for an interstitial screen that can appear at an unpredictable point (BE-0314).

condition is the same assertion the if step evaluates; the runner checks it opportunistically against trees it has already fetched (a wait's poll tick, an act step's pre-action read), wherever in the step sequence the screen happens to surface, and runs steps to clear it when it matches. The steps share the enclosing scenario's vars.*, the same as if's branches do.

target names which of the scenario's declared targets the entry watches (BE-0438). Unlike Step.target it stays optional however many targets the scenario declares: an omitted value resolves to the primary target. A step in steps that omits its own target runs on the target the entry watches, not on the primary one — or, nested under an if / forEach that names a target, on that step's target.

LongPress

Bases: _Model

longPress action — press and hold a selector for duration seconds.

Manual

Bases: _Model

manual action — a human-takeover marker recorded during record (BE-0185).

Emitted when a blocker is an operation the AI cannot perform (a CAPTCHA, a biometric prompt, a repeatedly unresolvable gesture): the human operated the device live and record recorded this marker of the observed transition, not the raw gesture. It has no deterministic run-time equivalent, so at run time it fails loudly with label — never a silent pass, never a hang (directives 1 and 2). bypass, when set, names the deterministic bridge an author can wire to make the step replayable (a test-build flag, a device-control / device-state primitive, BE-0035 / BE-0052); None means no such bridge exists (a real CAPTCHA).

Mock

Bases: _Model

A deterministic network stub.

When an outgoing request matches match, BajutsuKit returns respond instead of hitting the network (so tests don't depend on a live server). match reuses the request matcher's request-side fields (method / url / urlMatches / path / pathMatches / bodyMatches); status / count do not apply here, and query / body are refused (see _no_dictionaries).

MockResponse

Bases: _Model

The canned response a mock returns (defaults to an empty 200).

Navigate

Bases: _Model

navigate: <url> — load url in the current page, resolved against the target's baseUrl.

The YAML value is a plain string; url is only how the model stores it. Step rejects a mapping, so {url: ...} never becomes a public shape a later option would have to stay compatible with, while Navigate(url=...) still constructs.

Network

Bases: _Model

Per-scenario network settings.

filter scopes which observed requests are interleaved into the report's Steps timeline.

NetworkFilter

Bases: _Model

Which observed requests to interleave into the report's Steps timeline.

With domains set, only exchanges whose URL host matches one of them — exactly or as a parent suffix (example.com matches api.example.com) — appear in Steps; empty / unset shows every captured exchange. The Network tab always lists them all.

OpenUrl

Bases: _Model

openUrl: <url> — hand url to the OS for the app the driver addresses right now.

The YAML value is a plain string; url is only how the model stores it. Step rejects a mapping, so {url: ...} never becomes a public shape, while OpenUrl(url=...) still constructs.

Otp

Bases: _Model

otp — write the current code of a named TOTP generator into ${vars.*}.

from names a generator an earlier totp step registered with name; the step reads the clock when it runs, so a scenario fetches a fresh code at any point without restating the secret. Registration follows execution order: an otp whose generator has not been registered yet fails the step. minRemaining is the same window wait totp offers (BE-0474).

OverrideStatusBar

Bases: _Model

Override the Simulator's status bar for deterministic screenshots.

All fields are optional; only the provided fields are overridden.

Paste

Bases: _Model

paste action — focus the field, then trigger the platform paste of the clipboard.

The counterpart of copy and setClipboard: whatever the clipboard holds — a copy from an earlier select, or text seeded with setClipboard — is inserted at the focused field's caret, replacing any active selection. The step holds no state of its own; its outcome is verified with the existing value assertion on the field, never by reading anything this step recorded.

Pinch

Bases: _Model

Two-finger magnify. scale > 1 zooms in, 0 < scale < 1 zooms out.

Preconditions

Bases: _Model

Per-test environment setup: the target's subject overridden, and the device state.

resolved_locale(target_locale, platform='ios')

The locale this scenario runs under: its own device value, else the target's locale.

The one place the precedence lives, so everything that acts on it agrees — the app's launch arguments, the Simulator's own system language, and the system-alert label lookup that predicts what SpringBoard renders (BE-0320). Takes the target's value rather than the whole config, keeping the scenario schema a portable inner contract.

Parameters:

Name Type Description Default
target_locale str

The target's resolved runsOn.ios.locale.

required
platform str

The platform the target is driven as; only an iOS one reads the scenario's device.ios.locale.

'ios'

app_locale_for(platform)

The scenario's own per-app locale for platform, or None when it sets none.

iOS's lives in resolved_locale, which also pins the system language; Android's reaches the app alone (BE-0478), so it is kept apart from the locale system alerts are matched in.

resolve_seed_photos(resolve)

Rewrite device.ios.seedPhotos and device.android.seedPhotos through resolve, in place.

A file loader passes the scenario-file-relative resolution dataFile uses (contained_ref), so a path never escapes the suite root and no later reader depends on the working directory.

seed_photos_for(platform)

The scenario's seedPhotos for platform, or None when the scenario does not set them.

Push

Bases: _Model

Deliver a simulated push notification (simctl push) to the app under test.

Carries this APNs payload, e.g. {"aps": {"alert": "..."}}.

RandomValue

Bases: _Model

generate: { random: … } — exactly one generator kind (BE-0377).

Redact

Bases: _Model

Redaction config — element labels, network headers, and JSON fields to scrub from evidence.

Each list names items that are zeroed out before evidence is written to the report. A standard set of credential-bearing headers (authorization, cookie, set-cookie, …) is masked by default (BE-0130); unmask_headers is the explicit, visible opt-out that releases a specific default — turning off protection is never the mere absence of redact:.

Two element-level defaults join that header set (BE-0331) and take the same shape of opt-out: a field the platform itself marks secret, and a field whose identifier or label names a credential. Both cover cases a caller should never have to configure, so each releases only through its own explicit flag.

Relaunch

Bases: _Model

relaunch action — restart the app process, optionally overriding its launch env/args.

RequestMatch

Bases: _EndpointMatch

Network-traffic matcher, shared by the request assertion and until: { request: ... }.

The fields (method / url / urlMatches / path / pathMatches / query / body / status / bodyMatches) are AND-ed; count is how many exchanges matched — exact for the assertion, a lower bound for the wait. The endpoint can be pinned by url (exact full URL) or urlMatches (regex/substring), or just the path; query / body check query parameters and JSON body fields by key (BE-0463), and bodyMatches is a regex over the raw request body. At least one match field is required.

ResponseSchemaMatch

Bases: _Model

Validate a captured response body against a stored JSON Schema (BE-0048).

request selects the exchange whose response is checked (reusing the request matcher); schema is the schema file, resolved against the app's schemas dir. schema_path carries the value (the field is aliased schema to avoid shadowing pydantic's own schema attribute).

Rotate

Bases: _Model

Two-finger rotation. radians > 0 rotates clockwise.

Scenario

Bases: _Model

One scenario.

device_groups property

Every device group in declared order, a bare name read as a group of one (BE-0447).

target_names property

Every declared target name in declared order, device groups flattened (BE-0447).

later_targets property

The device-group members that start with nothing installed, in declared order (BE-0447).

A member of a group of two or more that is neither the primary (the first declared name) nor listed in installs: it comes alive only through an installApp step and a foreground.

final_primary property

The primary in force after the last top-level step: what an omitted expect target names.

screens property

The screen entries of interrupts (condition + steps), in order.

dismisses_tips property

Whether the scenario's interrupts carries - tipKit: dismiss (BE-0473).

The run writes the target's and the flag's choice onto this entry before the scenario runs, so it is the one value the loop reads.

source_stem property

The stem of the file this scenario was loaded from, or None outside a file loader.

record_final_primary(name)

Record the primary the target walk ended on (BE-0447).

set_source_stem(stem)

Record the stem of the file this scenario was loaded from (BE-0417).

ScenarioFile

Bases: _Model

A scenario file: an optional file-level description plus the scenarios it defines.

Two on-disk forms are accepted: the bare list of scenarios (no file description), or a {description: "...", scenarios: [...]} mapping. Only the mapping form can carry components:, since the bare-list form has nowhere to put it.

Scroll

Bases: _Model

scroll action — scroll a region until to is on-screen, or fail at a bound (BE-0326).

Where swipe's directional form is a single gesture, scroll is a bounded condition wait: it scrolls one non-inertial step, re-queries, and stops the moment to resolves with its frame's center inside the viewport — the point a following coordinate tap would aim at. It fails deterministically when it spends maxScrolls steps, or as soon as a step no longer changes the scrolled region's subtree (the region has bottomed out and the target is not there).

direction names the direction the content scrolls, so down reveals items below the fold — the inverse of swipe, whose direction is the finger's. within scopes the gesture (and the end-of-content comparison) to one scrollable container; omitted, the whole screen scrolls.

amount sets how far one step travels, as a fraction of the viewport (0 < amount ≤ 1) — the same unit swipe and drag take — for a screen whose content the default step size overshoots or creeps across. Omitted, the loop keeps its own default. It sets only where the loop starts: the overshoot recovery still shrinks the step toward its own fixed floor from wherever amount put it (BE-0400).

SelectOption

Bases: _Model

selectOption action — set a native <select> to the option with the given value.

Web-only: a <select> lives in the DOM but has no native counterpart on iOS / Android, so those backends refuse it (UnsupportedAction). option matches an option's value (not its visible label), mirroring the value assertion — which reads the <select>'s current value — so a picked option is directly assertable. A <select>'s dropdown is not in the DOM, so this is how a web <select> (e.g. the BE-0191 theme picker) is switched deterministically rather than by a coordinate click.

Selector

Bases: _Model

How to address an element. Provided fields are combined with AND.

id / idMatches accept a single value or a list of candidates; a list matches an element whose identifier equals (or glob-matches) any candidate — an OR. This lets one shared scenario carry every platform's form of an id (id: [stable.refresh, stable_refresh]), so it runs unchanged where the native id syntax differs — e.g. Android's android:id, which allows neither . nor -, surfaces stable.refresh as stable_refresh (BE-0221). Ambiguity is unchanged: 2+ matching elements on screen still fail fast.

List the canonical (dotted SPEC) form first. OR matching is order-independent, but single-id consumers take the first candidate as the representative — first_id(), audit.referenced_ids coverage bucketing (namespace_of splits on .), and the XCUITest / Playwright codegen emitters. Leading with the dotted SPEC id keeps their output correct; an underscore-first list would still resolve at runtime but skew coverage and generate the non-portable id.

as_selector()

Convert to the TypedDict consumed by base.resolve_unique.

first_id()

The primary id candidate (the first when id is a list), or None (BE-0221).

For single-id consumers — triage rename suggestions, capturePolicy on: matching, the WebView host — that want one representative id rather than the whole OR set. Selectors list the canonical (dotted SPEC) form first (see the class docstring), so "first" is the portable id.

SelectorRegion

Bases: _Model

An element to ignore during visual comparison, addressed by selector (BE-0171).

Resolved to the element's frame at evaluation time and masked exactly as an ExcludeRegion rectangle is. Robust where a pixel box is not: it follows the element across reflow, resolution, and locale changes. A selector matching nothing is a masking no-op (nothing on screen to hide); an ambiguous one fails, like every other selector resolution (prime directive 2).

SelectPhotos

Bases: _Model

selectPhotos action — pick one or more images from an open system photo picker grid.

Gated on Capability.SELECT_PHOTOS: iOS's PHPickerViewController over XCUITest (device / Intel Simulator) and Android 13+'s photo picker over adb. On iOS every grid cell shares one identifier (PXGGridLayout-Info), so indices names each cell by its ordinal position — the same "nth of multiple matches" mechanism handleSystemAlert already relies on for a SpringBoard button no author-assignable identifier ever names. A cell carries no label an author could ask for by name, only its position in the grid the picker renders, so no sel field is offered here the way tap or setPickerValue take one.

timeout bounds the condition wait for the grid (the picker must already be open) and for the confirm control that follows the last tap.

SetClipboard

Bases: _Model

Seed the device clipboard with text, for paste flows.

simctl pbcopy on iOS; on Android, the BajutsuAndroid in-app receiver (BE-0233).

SetLocation

Bases: _Model

Override the device's GPS location (simctl on iOS; the console or an in-app mock on Android).

SetPickerValue

Bases: _Model

setPickerValue action — move a picker wheel to the row whose value is value.

iOS-only: a wheel-style UIPickerView / UIDatePicker exposes no separately addressable row, so no coordinate drag can guarantee stopping on one — XCUITest's own adjust(toPickerWheelValue:) acts on the resolved element instead, which is what makes this deterministic (BE-0356). Other backends have no such control and refuse it (UnsupportedAction).

sel addresses exactly one wheel. A multi-component picker (a year wheel beside a month wheel) exposes each component as its own pickerWheel element, disambiguated by the within / traits / index fields every selector already carries, so value stays a plain string and each component is set by its own step.

SetPrimaryTarget

Bases: _Model

From this step on, a step, interrupts entry, or expect entry omitting target runs on target.

It changes routing and nothing else: each target keeps its own config, driver, and environment, so the move needs no mid-run swap. Leasing, evidence, and crash recovery stay with the primary the scenario declared.

Sleep

Bases: _Model

sleep action — pause for seconds, the one sanctioned exception to "condition waits only".

For a wait no condition on the screen, the tree, or the network log can observe (a server-side throttle, an animation that outlives until: settled). reason is mandatory so every fixed pause says why a wait could not express it; the report shows it and the determinism audit lists it as a fixed-sleep finding.

Step

Bases: _Model

One action plus optional modifiers (capture / name / extract).

resolved_target property

The target this step runs against: its own target, else the primary it resolved to.

resolve_target(target)

Record the primary target an omitted target defaults to, or None for none (BE-0436).

Swipe

Bases: _Model

swipe action — by direction on an element (on), or between two points (from/to).

amount (only with on/direction) sets how far to travel as a fraction of the screen (0 < amount ≤ 1): ~0.2 nudges, ~0.5 scrolls half a screen, ~0.9 nearly a full one. Omitted, a small default distance is used — so the caller can dial the scroll to the instruction.

SystemAlertInterrupt

Bases: _Model

An operating-system prompt the reactive guard answers, by name (BE-0406, BE-0473).

systemAlert names the prompt and choice the answer, in the vocabulary the handleSystemAlert step takes, so the same entry grants or denies under any locale bajutsu.common.scenario.system_alerts covers. leave answers nothing: a scenario writes it to turn off the target's answer for that prompt, typically because its own handleSystemAlert step does the work. An alert no entry names is left alone rather than answered by a guessed button.

SystemAlertRule

Bases: _Model

The choice the guard makes on one named prompt, once the layers have resolved.

A systemAlert entry of interrupts (BE-0473) whose choice is not leave becomes one of these after the scenario's entries are layered over the target's; a leave answers nothing, so it produces none.

prompt and choice reuse the vocabulary the proactive handleSystemAlert step already takes (its prompt/choice form) instead of a literal button label, so the same rule grants or denies the prompt under any locale bajutsu.common.scenario.system_alerts covers. The reactive guard identifies which alert is on screen from that prompt's own identifying labels, which is why BE-0406 made this the guard's only declaration: a button label names a button, never the alert it sits on, so it could never say which prompt an author actually expected.

A prompt not every answer path can reach is still declarable here — savePassword is answered by the in-tree dismissal alone, since iOS raises it into the application's own process where the SpringBoard query never sees it. system_alerts.alert_surfaces records which paths each prompt reaches, and run reads it when it resolves these rules.

TapPoint

Bases: _Model

tapPoint action — tap a screen location by normalized coordinates (0..1), not a selector.

The bottom rung of the stability ladder (DESIGN §5), for a control the accessibility tree does not expose as an addressable element — most notably a tab-bar tab on an app with no accessibility ids, which iOS's accessibility tree collapses into one opaque group. record's agent locates it in the screenshot and emits its center here; run replays it against the current screen size. x/y are fractions of the app window (top-left origin), so the tap survives a resolution change a raw-pixel tap would not — but it is still coordinate-based and unverifiable by selector, so prefer a real selector whenever the element is addressable.

TextMatch

Bases: _Model

value / label: exactly one of equals / contains / matches.

TipKitInterrupt

Bases: _Model

Apple's TipKit popover: dismiss clears a blocking tip, leave keeps it (BE-0473).

iOS only. Off unless an entry asks for it, since a tip is sometimes the very thing a scenario asserts on; a scenario writes leave to turn off its target's dismiss.

Totp

Bases: _Model

totp — generate an RFC 6238 time-based one-time password into ${vars.*} (BE-0046).

secret is the shared base32 key (commonly ${secrets.*}); the current code is written to into.var for a later type / assert to consume. name, when set, also registers the secret as a named generator, so a later otp step can fetch a fresh code without restating it — which is why into may be omitted when name is given. Local and deterministic — no LLM, no network, no scripting escape hatch. minRemaining (BE-0474), when set, makes the run loop wait for the next 30-second window first whenever the current one has fewer seconds left, so the code outlives the steps that carry it to the app.

Trigger

Bases: _Model

A capturePolicy trigger that fires its CaptureRule when a condition holds.

The condition is exactly one of action / event / result; idMatches narrows an action trigger to a specific element ID.

TypeText

Bases: _Model

type action — enter text, optionally into a selector and optionally submitting after.

Use

Bases: _Model

Invoke a reusable component, substituting its declared params with with.

The use step is expanded away (replaced by the component's steps) before the run, so it is a compile-time macro, not a runtime action — determinism is unaffected.

VarTarget

Bases: _Model

into: { var: <name> } — the ${vars.<name>} slot a step writes its produced value to.

VisualMatch

Bases: _Model

Visual regression assertion — compare a screenshot to a baseline image.

By default the whole screen is compared. element (BE-0171) scopes the comparison to one element's frame: the screenshot is cropped to it and the baseline is that crop, so unrelated on-screen changes no longer churn the baseline.

Wait

Bases: _Model

wait step — block until a selector appears (for) or a condition holds (until).

Bounded by timeout; always a condition wait, never a fixed sleep.

WaitRequest

Bases: _Model

until: { request: <RequestMatch> } — wait until a matching network exchange has been observed.

Requires the run's network collector to be active.

Web

Bases: _Model

Enter the web context: resolve a native WebView host, then run inner steps against its DOM.

The within selector resolves natively to exactly one WKWebView element; inner steps address the normalized DOM (data-testid → Element.identifier), not the native a11y tree.

RawScenario dataclass

One scenario's verbatim source text and each of its steps' original line number.

AlertSurfaces

Bases: TypedDict

Which of Bajutsu's three answer paths a prompt can actually be declared and answered on.

Recorded per prompt because savePassword is the first to diverge (BE-0406): iOS raises it into the application's own process, so springboard.alerts never sees it and only the guard's in-tree dismissal can clear it. Three consumers read this — the handleSystemAlert step rejects a prompt it could never resolve, the in-tree paths arm only on rules a tree match can reach, and the interruption policy pushed to the runner drops a rule that surface can never meet.

ResolvedAlertShape dataclass

One shape of one prompt, resolved for a locale and a choice.

The scenario layer's half of orchestrator.types.ResolvedAlertRule, kept here so the schema stays a portable inner contract that pulls in no orchestrator layer; run pairs each of these with the prompt's AlertSurfaces to build the rule the guard matches with.

SystemAlertRole dataclass

Which button of a SpringBoard prompt carries a choice, by its place among the prompt's buttons.

The rule BE-0445 measured to hold across Simulator languages: SpringBoard lists a permission prompt's buttons in the same order whatever the language it renders them in. count is part of the rule rather than a detail of it — an alert offering any other number of buttons is not the prompt the rule describes, so the rule names no button on it instead of tapping by position on an alert it was never measured against.

The count is over the buttons Driver.system_alert_labels reports, which leaves out a button with no label. Every button of every measured prompt carried one, so the rule is as strong as that measurement: an alert padded to the right size by an unlabeled button would pass it.

pick(buttons)

The label of the button this rule names on an alert offering buttons, if it names one.

describe()

The rule in the words a report shows, e.g. "button 2 of 2".

UncoveredSystemAlertLocale

Bases: ValueError

A prompt / choice pair was asked for under a language the table does not cover.

Raised rather than guessed at: a wrong label would tap nothing (or, worse, the other button), and BE-0320 exists to remove exactly that kind of accident.

declared_name(run_scenario)

The name a suite declares for the scenario a run recorded as run_scenario.

Strips the row suffix _row_name appends; a name carrying none is returned unchanged, so a scenario that is not data-driven passes through.

expand_components(scenarios, resolve, max_depth=25)

Replace every use step with the referenced component's steps, recursively and in place.

Pure compile-time expansion: a component may itself use another, and after this no use steps remain — inside an if / forEach / web / app body too — so the run loop is unaffected. A use: or group: step naming target stamps it onto every step it produces that omits its own, down through if / forEach bodies and nested calls, stopping at a web: / app: block (BE-0446).

Parameters:

Name Type Description Default
scenarios list[Scenario]

The scenarios to expand; their steps, their setup / cleanup lifecycle steps, and every interrupts entry's recovery steps are rewritten in place.

required
resolve Callable[[str], Component]

Maps a component name to its Component (e.g. by loading a shared file). One that also satisfies ScopedResolve re-scopes each ref's nested expansion, and owns whatever caching it needs — this function itself resolves every occurrence.

required
max_depth int

The deepest use nesting allowed before giving up on a runaway chain.

25

Raises:

Type Description
ValueError

A required param is missing, an unknown param is passed, a ${params.*} token references an undeclared param, a reference cycle is detected, nesting exceeds max_depth, an expanded step names a target other than its caller's, or a group lands inside a body or another group.

expand_data(scenarios, resolve_csv)

Expand each data-driven scenario into one scenario per data row.

${row.<col>} tokens are substituted per row. A scenario with neither data nor dataFile passes through unchanged. Each derived scenario keeps the original's preconditions (erase default intact), so every row runs in its own clean environment — isolation is preserved.

Parameters:

Name Type Description Default
scenarios list[Scenario]

The scenarios to expand.

required
resolve_csv Callable[[str], list[dict[str, str]]]

Loads a dataFile reference into a list of {column: value} rows.

required

Returns:

Type Description
list[Scenario]

The scenarios with every data-driven one replaced by its per-row instances, in order.

expand_steps(steps, resolve, max_depth=25)

One step list with every use replaced by its component's steps, as expand_components does.

For a step list that belongs to no scenario: a target's hooks in the config, whose components resolve when the config loads (BE-0452). The scenario-level checks expand_components runs afterwards are the caller's to make, since a config hook has rules of its own.

Parameters:

Name Type Description Default
steps list[Step]

The steps to expand.

required
resolve Callable[[str], Component]

Maps a component reference to its Component.

required
max_depth int

The deepest use nesting allowed before giving up on a runaway chain.

25

Returns:

Type Description
list[Step]

The expanded steps; steps itself is left unchanged.

Raises:

Type Description
ValueError

As expand_components does.

read_csv(text)

Parse CSV text into a list of {column: value} row dicts (header row required).

load_component(text)

Parse a YAML string (a single component mapping) into a validated Component.

load_scenario_file(text)

Parse a scenario file: a list of scenarios, or a {description, scenarios} mapping.

Raises:

Type Description
ValueError

The top level is neither a list nor a mapping (§6.1), or the file declares a schema version newer than this bajutsu supports (BE-0119).

load_scenarios(text)

Parse a scenario file into validated Scenario objects (any file-level description dropped).

load_stored_scenario_file(text)

Parse the scenario.yaml a finished run stored, reading pre-BE-0452 spellings as today's.

The offline readers of a run directory (the report re-render, trace, triage) use this rather than load_scenario_file, which rejects the old names an author must rewrite.

Raises:

Type Description
ValueError

As load_scenario_file.

renamed_outcome(value)

value with the failed-outcome word BE-0452 renamed (error) read as failure.

contained_ref(root, base, ref)

Resolve a scenario ref (base / ref) and require its real path to stay within root.

The one containment choke point for a scenario's component / data refs (BE-0174): every device-free resolver routes ref resolution through here, so a scenario cannot make the loader read a file outside its suite. resolve follows symlinks, so an out-of-root link is caught the same as a .. chain or an absolute path — the three ways a ref leaves the tree. On rejection the error names only the offending ref, never the target's contents, so the check happens before the read and closes the leak as well as the read.

Parameters:

Name Type Description Default
root Path

The suite root the ref must stay within (the scenarios dir the load started from).

required
base Path

The directory refs resolve against (the referring scenario file's directory).

required
ref str

The use: component or dataFile reference to resolve.

required

Returns:

Type Description
Path

The resolved real path, ready to read.

Raises:

Type Description
ValueError

The ref is absolute, escapes the root via .., or symlinks outside it.

load_expanded_scenarios(path, root=None, *, text=None)

Load a scenario file and expand its components + data rows, resolving refs relative to the file.

Parameters:

Name Type Description Default
path Path

The scenario file to load.

required
root Path | None

The suite root every component / data ref must stay within (BE-0174). Defaults to the scenario file's own directory, so a single-file load confines refs to that directory; a suite loader passes the shared scenarios dir instead.

None
text str | None

The file's content when the caller already holds it, such as the serve editor's unsaved buffer; path then only places its refs and names its stem.

None

Raises:

Type Description
OSError

The scenario file or a referenced component / CSV cannot be read.

ValueError

The content is invalid, the YAML does not parse — parse_yaml_named normalizes a yaml.YAMLError into a ValueError naming the offending file (the scenario or a referenced component), so its callers' except (OSError, ValueError) guard a malformed file as cleanly as a structurally-invalid one (BE-0150) — a ref resolves outside root (contained_ref), or a bare use ref names no entry in this file's own components: (ComponentResolver).

load_scenarios_dir(scenarios_dir)

Every expanded scenario in scenarios_dir's *.yaml files, sorted by filename.

The device-free suite loader shared by coverage on the CLI and in the serve Web UI, so both read a target's suite identically. The scenarios dir is the containment root passed to each file's load, so a scenario's refs stay inside the suite (BE-0174).

Raises:

Type Description
(OSError, ValueError)

as load_expanded_scenarios — an unreadable or invalid file, or a ref that escapes the suite root.

parse_yaml_named(file, parse)

Read and parse a YAML file, re-raising a syntax error as a ValueError naming file.

A yaml.YAMLError is not a ValueError subclass, so a caller's except (OSError, ValueError) would leak it as a traceback. Normalizing per file — so a malformed referenced component is attributed to the component, not the top-level scenario — and collapsing PyYAML's multi-line text keeps the one-line error clean and actionable (BE-0150). An OSError (unreadable file) is left to propagate unchanged.

check_interrupt_entries(entries, where)

Refuse two entries for one prompt, or two TipKit entries, within one list.

Silently taking the first of two would hide an authoring mistake — the same reason an ambiguous selector fails rather than tapping its first match.

Raises:

Type Description
ValueError

A prompt, or the TipKit entry, appears more than once in where.

screen_entries(entries)

The screen entries of an interrupts list, in order.

system_alert_entries(entries)

The system-alert entries of an interrupts list, in order.

tip_kit_entry(entries)

The TipKit entry of an interrupts list, or None when it has none.

scenario_sources(text)

Each scenario's verbatim slice of text, aligned with load_scenario_file(text).scenarios.

select_scenarios(scenarios, include, exclude)

Filter scenarios by tag, preserving order.

Pure metadata filtering — never mutates or reorders.

Parameters:

Name Type Description Default
scenarios list[Scenario]

The scenarios to filter.

required
include list[str]

A scenario is kept only if it carries at least one of these tags; an empty include keeps everything.

required
exclude list[str]

A scenario carrying any of these tags is dropped. exclude wins over include.

required

Returns:

Type Description
list[Scenario]

The kept scenarios, in their original order.

dump_block(items)

Serialize models as a - … YAML sequence block — one alias-keyed item each.

Alias keying matches scenario_dict, but a scoped block also drops default-valued fields (exclude_defaults), so a single spliced step / assertion stays as terse as the author wrote it rather than sprouting submit: false and other model defaults. Used by the Author editor's scoped round-trip edits (BE-0261) to re-serialize just the changed step / expect block.

dump_mocks(mocks)

Serialize a scenario's mocks to the compact JSON BajutsuKit reads from BAJUTSU_MOCKS.

Alias keys, omitting unset fields.

dump_scenario_file(scenarios, description=None)

Serialize a scenario file.

With a file-level description, emits the {description, scenarios} mapping form; otherwise the bare list (round-trips through load_scenario_file).

dump_scenarios(scenarios)

Serialize scenarios back to YAML (round-trips through load_scenarios).

redact_totp_secrets(scenario)

A copy of scenario with literal totp.secret seeds masked, for on-disk evidence (BE-0152).

The executed scenario is snapshotted into the run's artifacts; a literal base32 seed there is durable credential material, so it is replaced with a placeholder before the snapshot is written. A ${secrets.*} reference is left intact (its resolved value never reaches the snapshot — BE-0032). Round-trips through the model so the result stays a valid scenario.

exclude_defaults is what keeps that round-trip total: a field validator may reject a value the author can never write but a dump still emits — a default_factory's own empty list, which exclude_none does not drop — so re-validating a model's own dump would fail on a field nobody declared (BE-0401 met this on the since-removed labels of the alert-guard declaration). Excluding default-valued fields hands model_validate only what was declared, and re-validation restores each default, so the returned model is field-for-field the input.

scenario_dict(scenario)

An alias-keyed dict of one scenario, with unset fields dropped (for the rich report view).

Drops default-valued fields for the same reason redact_totp_secrets does: a model dump that emits every default is not reloadable, because a validator reading model_fields_set cannot tell a default the dump added from a value the author wrote. VisualMatch._engine_fields is the case — it rejects colorTolerance / antialiasing alongside compare: exact, and both carry non-None defaults that exclude_none keeps — so the scenario.yaml written beside a run's results failed to reload, against dump_scenarios' own round-trip contract. Excluding them also keeps the snapshot as terse as the author wrote it, which is what dump_block already does.

Nothing here touches a value once model_dump has produced it: a step's own fieldless action (back: {}) must survive verbatim or reloading fails the one-of-N-required invariant (§6.2 / §6.4), and a free-form dict[str, Any] field (push.payload) is author data pydantic's own exclude_none/exclude_defaults never look inside — a generic post-pass dropping None / [] there would silently change what a re-run sends, which used to be this function's bug.

covered_languages(prompt)

The language subtags this table covers for prompt, sorted — the documented, testable surface.

labels_cover(prompt, locale)

Whether the label table knows prompt's buttons under locale's language.

system_alert_label(prompt, choice, locale)

The button label SpringBoard renders for prompt's choice under locale.

For the handleSystemAlert step, which taps one button. Only a step-capable prompt reaches here, and every one of those renders a single shape — a test pins that, so the indexing below cannot silently start answering with the first of several.

Parameters:

Name Type Description Default
prompt SystemAlertPrompt

Which of the covered OS prompts the step is answering.

required
choice SystemAlertChoice

What the author means by the tap, rather than which button says it.

required
locale str

The scenario's resolved locale (Preconditions.resolved_locale, over runsOn.<platform>.locale); only its language subtag selects the labels, since SpringBoard localizes by language, not by region.

required

Raises:

Type Description
UncoveredSystemAlertLocale

the table has no entry for that language.

system_alert_shapes(prompt, choice, locale)

Every shape of prompt under locale, each with the label choice taps on it.

For the reactive guard, which identifies an alert before tapping it and so needs all of a prompt's renderings rather than one button (BE-0406).

Raises:

Type Description
UncoveredSystemAlertLocale

the table has no entry for that language.