Repository Public
1# Automation: the ORIX Script implementation23This document describes how ORIX Script is implemented: the compiler, the plan it produces, the runtime that executes the plan in beat time, the live scheduler that turns the runtime's output into sample-stamped control events, the console, the simulator and debugger, and the two built-in producers of scripts (presets and Auto DJ). It is written from the source; file names and constants are quoted as they appear in the code.45The language itself is documented for users in [`docs/orix-script/`](../orix-script/introduction.md). Related engineering documents: [overview](overview.md), [audio engine](audio-engine.md), [deck engine](deck-engine.md), [mixer](mixer.md), [AI integration](ai-integration.md), [persistence](persistence.md), [security report](../reports/security.md), [performance](../development/performance.md), [testing](../development/testing.md).67## Source layout89| File | Role |10| --- | --- |11| `Packages/ORIXDJCore/Sources/ORIXScript/Lexer.swift` | Source text to tokens, including unit literals (`-12dB`, `20Hz`, `4bars`, `1/4beat`, `50%`). Also produces highlight spans for text that does not parse. |12| `ORIXScript/Parser.swift`, `AST.swift` | Recursive-descent parser with error recovery; block and expression nesting limited to 20 levels (`maxNesting`). |13| `ORIXScript/Schema.swift` | The single table of everything a script can name: deck, mixer, master and effect parameters, actions, events, builtins, keywords. |14| `ORIXScript/Compiler.swift` | Semantic analysis and lowering: `ScriptCompiler`, `Capabilities`, `CompileLimits`. |15| `ORIXScript/Plan.swift` | The plan (`Program`, `CompiledAutomation`, `PStmt`, `PExpr`), `ScriptRuntimeError`, and the pure `Evaluator` shared by constant folding and the runtime. |16| `ORIXScript/Runtime.swift` | `AutomationInstance`, `AutomationTarget`, `RuntimeLimits`, trace and statistics types. |17| `ORIXScript/Simulator.swift` | `SimulatedRig`, `DebugSession`, `Simulator`. |18| `ORIXScript/Tools.swift` | `ScriptFormatter`, `ConsoleParser`, `Autocomplete`. |19| `ORIXScript/Presets.swift` | `PresetLibrary` (24 presets). |20| `ORIXScript/Reference.swift` | `ReferenceGenerator`: generated reference chapters and the language brief sent to Claude. |21| `ORIXDJEngine/AutomationHost.swift` | Live binding to `DJEngine`: scheduler thread, look-ahead, console execution, statistics. |22| `ORIXDJEngine/AutoDJ.swift`, `Session.swift` | Auto DJ planner and the session code that runs its generated scripts. |2324The `ORIXScript` module imports only `Foundation` and `ORIXDSP` (for the `EffectKind` catalogue). It has no dependency on the engine: the runtime talks to an `AutomationTarget` protocol with four members (`read`, `write`, `perform`, `clockBPM`), implemented by `AutomationHost` for the live engine and by `SimulatedRig` for the simulator.2526### Why an interpreter of our own2728The code does not contain a comment comparing this design with embedding an existing scripting engine, so no such comparison is claimed here. What the code does state, and what the design follows from, is:2930- `Runtime.swift` header: the runtime "never runs on the audio render thread: it only emits timestamped parameter writes and actions".31- `Compiler.swift`: `Capabilities` is "what the host can run. Scripts that need more are rejected before execution"; recursion is rejected because "automations must be bounded".32- `Reference.swift` (`completeReference`): "Every path listed here is accepted by the compiler; nothing else is"; (`languageBrief`): "No file, network, shell or system access exists in the language."33- `ScriptAssistant.swift` header: "Nothing a model writes reaches the engine without passing the same validation as a hand-written script."3435A language whose whole vocabulary is one schema table makes these properties checkable at compile time, and lets time be a first-class notion (beats, bars, `over`, `at`, `every`) instead of a library on top of a general-purpose language.3637## Compiler pipeline3839```mermaid40flowchart TD41 SRC["Source text (max 256 KB)"] --> LEX["Lexer: tokens and unit literals"]42 LEX --> PAR["Parser: recursive descent with recovery"]43 PAR --> AST["AST: ScriptFile with constants, functions, automations"]44 AST --> SEM["Semantic analysis: names, types, units, ranges"]45 SEM --> CAP["Capability validation: deck count and effect set"]46 CAP --> BND["Bound checks: loop limits, recursion, handler and statement counts"]47 BND --> PLAN["Plan: Program of CompiledAutomation and PFunction"]48 PLAN --> RT["Runtime tasks: AutomationInstance"]49 RT --> SCH["Scheduler: AutomationHost tick with look-ahead"]50 SCH --> EVT["Timestamped control events in the RenderCore queue"]51 SEM -. "any error" .-> DIAG["Diagnostics with code, line, column; no Program"]52 CAP -. "any error" .-> DIAG53 BND -. "any error" .-> DIAG54```5556`ScriptCompiler.compile(_:capabilities:)` returns a `CompileResult`. `program` is non-nil only when there is no diagnostic of severity `.error`; warnings (`W-SHADOW`, `W-UNREACHABLE`, `W-OVER`, `W-RAMP`, `W-UNUSED`, `W-AT`) do not block. Diagnostics are sorted by line and column. A script with no `automation` is rejected with `E-EMPTY`.5758What the semantic pass (`Compilation`) does, in the order of the code:59601. **Top-level constants** must fold to a value (`E-CONST` otherwise).612. **Functions** are declared first so they can call each other in any order, then compiled. A function with a return type is a pure function (`BodyContext.pureFunction`): no timing statements, no writes, no actions, no reads of live values, no `print`, no `random()` (`E-PURE`), and it must return on every path (`E-RETURN`). A function without a return type is a timed procedure.623. **Recursion detection** walks the call graph depth-first and reports `E-RECURSION` for any cycle, direct or indirect.634. **Automations**: each body is lowered to `PStmt` values. Paths are resolved against `ScriptSchema` by `resolveParam`, `deckPrefix` and `effectKind`; an unknown name is `E-PATH`, `E-DECK`, `E-EFFECT` or `E-UNDECLARED`, with a "Did you mean" hint computed by Levenshtein distance (`suggestion(for:in:)`).645. **Type and unit checks**: `Evaluator.binaryType` decides which operand types combine; gains, frequencies, durations and plain numbers never mix (`E-TYPE`, with a hint such as "Add the unit: 3dB"). The one implicit conversion is a plain number assigned to a gain parameter, treated as a linear level in 0…4 and converted by the internal `linearToGain` builtin.656. **Range checks** on constants against the parameter definition (`E-RANGE`); read-only properties (`E-READONLY`); only rampable parameters inside `over` (`E-RAMP`).667. **Capability validation**: a deck index at or beyond `capabilities.deckCount`, or an effect outside `capabilities.effects`, is `E-CAPABILITY`. The defaults are four decks and every `EffectKind`.678. **Constant folding** (`fold`) uses the same `Evaluator` as the runtime. Mixed beat/second arithmetic and `random`, `toBeats`, `toSeconds` are left for run time because they depend on the tempo or on state.689. **Requirements** are collected per automation (`AutomationRequirements`): decks addressed by a constant path, effects addressed, `usesEvents`, `usesAbsoluteTime`, and `lengthBeats` when `Compilation.extent` can determine the length statically (nil when it depends on run-time values or the automation has event handlers).6970`ScriptCompiler.compileConsole` parses in console mode and wraps loose statements into one anonymous automation named `console` with `quantize none`.7172## The runtime7374An `AutomationInstance` is one running automation. It is single-threaded by contract ("create, advance and inspect it from one queue") and is driven by one call: `advance(to: beat)`, which runs everything due up to that beat of the master clock.7576- **Tasks.** The main body is task 0. `at` blocks (`.spawn`) and event handler runs become additional `ScriptTask` values, each with a wake beat and a stack of `Activation` records (body, program counter, frame, loop kind). `advance` repeatedly picks the task with the smallest `(wake, id)` that is due, runs it until it waits or ends, and removes it when finished. Tasks are cooperative: a statement returns the beat at which the task must resume (`wait`, `over`, `every`).77- **Start quantisation.** `quantize beat` or `quantize bar` moves `startBeat` to the next boundary (`nextBoundary`, four beats per bar from `ORIXScriptLanguage.beatsPerBar`).78- **Ramps.** `over` reads the current value through the target, registers an `ActiveRamp` per parameter and suspends the task for the duration. `updateRamps` writes an interpolated value at each `advance` (curve from `RampCurve.shape`; frequencies are interpolated geometrically when both ends are positive) with `rampBeats` equal to the step, so the engine glides between scheduler steps. `finishRamps(upTo:)` writes the exact target at the ramp's end beat before the statements that follow it run. A direct write to a ramped parameter cancels its ramp.79- **Events.** `on` registers a `Handler` keyed by `EventKey`. `post(_:atBeat:)` spawns a handler task; beat and bar events are generated inside `advance` (at most 64 beats per call).80- **Values written** pass through `conform`, which clamps to the parameter's range and counts the clamp in `AutomationStats.clampedValues`; a non-finite number becomes the parameter's minimum.81- **Determinism.** `random()` is a xorshift generator with a fixed seed (`0x2545F4914F6CDD1D`) per instance; `RuntimeTests.randomIsDeterministic` checks that two runs print the same values.82- **Trace.** Every write, action, wait, spawn, ramp, handler run, print, warning, error and finish is reported through `onTrace` as a `TraceEvent`. The live log, the console, the simulator and the debugger all consume this one stream.8384## Live scheduling8586`AutomationHost` (`ORIXDJEngine/AutomationHost.swift`) owns the running instances and a dedicated scheduler thread.8788| Property | Value in the code |89| --- | --- |90| Thread name | `ai.spboucher.orix.dj.automation`, QoS `.userInteractive` |91| Scheduling class | Mach `THREAD_TIME_CONSTRAINT_POLICY`: period 4 ms, computation 0.4 ms, constraint 2 ms, preemptible |92| Period | 4 ms (`ticks(4_000_000)`), waited with `mach_wait_until`; when a tick overruns, the next wake is a quarter period after now |93| Look-ahead | `lookaheadSeconds = 0.03` (30 ms) by default; adjustable from 5 to 50 ms in Settings |94| Horizon | `clock.beat + lookaheadSeconds * clock.bpm / 60` |95| Control queue | `SPSCQueue<ControlEvent>(minimumCapacity: 4096)` in `RenderCore`; a failed push increments `droppedControlEvents` |96| Pending list on the render thread | 512 events (`pendingCapacity`), kept sorted by time |97| Live log | last 2000 lines; finished runs: last 50 |9899Note on the look-ahead value: one sentence of the user documentation ([scheduling](../orix-script/scheduling.md), "up to 15 ms before the beat") and the heading printed by the benchmark say 15 ms, but the default in `AutomationHost` is 30 ms and the benchmark does not override it. The application stores the Settings value in `UserDefaults` (key `automation.lookahead`, default 30) and applies it at start-up, clamped to 5 to 50 ms (`AppModel.swift`, `AppSettings.swift`, as read on 2026-11-21; this part of the application was being edited while this document was written). Only the test `scriptActionsLandOnExactSamples` sets it explicitly (to 20 ms). The measurements below were therefore taken with 30 ms (benchmark, offline mixes) and 20 ms (test).100101```mermaid102flowchart TD103 T["Scheduler thread wakes every 4 ms"] --> S["engine.service: drain render notices, advance master clock"]104 S --> H["horizon = clock beat + look-ahead in beats"]105 H --> P["post pending deck and trigger events to every instance"]106 P --> A["instance.advance to horizon"]107 A --> W["write or perform at beat b"]108 W --> ST["engine.sampleTime for beat b"]109 ST --> Q["push ControlEvent with sample time into SPSC queue"]110 Q --> R["Render thread intake: due now is applied, future goes to sorted pending list"]111 R --> X["Render block is cut at the next pending timestamp, event applied on that sample"]112 X --> M["If the event is tracked: lateness = render sample time minus timestamp"]113 A --> RP["reap finished or failed runs, update SchedulerStats"]114```115116One `tick()`:1171181. `engine.service()` drains render-thread notices and advances the master clock; it returns `ClockState` (beat, BPM, sample time, master deck).1192. The horizon is computed. Deck events collected since the last tick (`handle(_:)`) and triggers (`fire(trigger:)`) are posted to every instance.1203. Each instance is advanced to the horizon. Its writes and actions call back into the host (`AutomationTarget`), which converts the beat to a sample time with `engine.sampleTime(forBeat:)` (`clockAnchorSample + round((beat - clockAnchorBeat) * 60 / max(20, bpm) * sampleRate)`) and calls the engine with `at: time`.1214. The engine pushes a `ControlEvent` carrying that time. In `RenderCore`, `intake()` applies events whose time is not in the future and inserts the others into a time-ordered pending list; the render loop limits each sub-block to `pending[0].time - sampleTime` frames, so a scheduled event is applied on its sample rather than at a buffer boundary. See [audio engine](audio-engine.md).1225. Statement-issued writes and actions are marked `tracked`; the render thread counts them and measures how many arrived after their sample (`lateEvents`, `maxLateSamples`, `totalLateSamples`). Intermediate ramp updates are not tracked (`tracked: rampBeats == 0`); they carry a smoothing time instead.1236. Finished and failed runs are moved to `finishedRuns`; tick duration and the gap since the previous tick are recorded in `SchedulerStats`.124125The scheduler thread takes an `NSRecursiveLock`; the render thread never does. The only shared structures between them are the lock-free queues and the published render state.126127Consequences of look-ahead, all visible in the code: a value read by a script is the state at the time of the tick, up to one look-ahead before the beat the statement is scheduled for; an event is delivered at the tick after it occurs; a console line cannot act earlier than "now".128129`AutomationHost.renderOffline(frames:)` calls `tick()` between offline render blocks of `max(16, bufferFrames)` frames. Tests, the benchmark and the offline mix renderer use it, so they exercise the same scheduling path without the real-time thread.130131The application starts the scheduler in `AppModel.start()` and stops it in `shutdown()`.132133## Console execution134135```mermaid136flowchart TD137 L["Console line"] --> CP["ConsoleParser.parse"]138 CP -->|"first word is a command"| CMD["command: help, list, run, stop, pause, resume, status, decks, fx, trigger, panic, clear, version"]139 CP -->|"anything else"| CC["ScriptCompiler.compileConsole"]140 CC -->|"errors"| INV["invalid: print each diagnostic with its code, count a validation error"]141 CC -->|"program"| ST["host.start as automation named console, origin console"]142 ST --> ADV["advance once to current beat plus look-ahead, capturing the trace"]143 ADV --> OUT["print lines as results, errors as errors, warnings as info"]144 OUT -->|"instance still alive"| SCHED["report: Automation scheduled with run id"]145 OUT -->|"instance finished"| OK["report: OK when nothing was printed"]146 CMD --> RUN["run Name: load source by name, full compile, start"]147```148149`AutomationHost.execute(console:)` runs under the host lock. A line is a command when its first word is in `ConsoleParser.commands` and is not followed by `=`, `.` or `(` (so `stop` alone is the console command, not the statement). Otherwise the line is compiled with the same compiler and limits as a file. The resulting automation is started and advanced once synchronously so that an expression such as `deck.B.volume` prints its value immediately; anything that waits stays in the run list and is advanced by the scheduler like any other run. `run "Name"` resolves the name through `scriptSource` (the library's saved scripts first, then `PresetLibrary`), and prints at most six diagnostics when the script does not compile. `panic` calls `emergencyStop()`.150151`AutomationLiveTests.consoleDrivesTheRealEngine` checks this path against a real `DJEngine`. User documentation: [console](../orix-script/console.md).152153## Safety limits154155### `CompileLimits` (Compiler.swift)156157| Field | Value | Enforced as |158| --- | --- | --- |159| `maxLoopIterations` | 10000 | `E-LIMIT` for constant `repeat`, `for` and `every` counts; the `while … limit N` constant must be 1…10000 (`E-UNBOUNDED`) |160| `maxArrayLength` | 256 | `E-LIMIT` |161| `maxSourceBytes` | 256 * 1024 (256 KB) | `E-LIMIT`, checked before parsing |162| `maxStatements` | 20000 | `E-LIMIT` |163| `minEveryPeriodBeats` | 1/64 beat | `E-LIMIT` |164| `maxHandlers` | 32 | `E-LIMIT` |165166Other compile-time bounds that are literals in the code rather than `CompileLimits` fields: 512 variables per automation or function; a constant wait, ramp or `at` position of at most 100000 beats; block and expression nesting of 20 levels (`Parser.maxNesting`); string literals of 512 characters (lexer).167168### `RuntimeLimits` (Runtime.swift)169170| Field | Value | Behaviour when exceeded |171| --- | --- | --- |172| `maxOperationsPerStep` | 20000 | `E-BUDGET` (operations in one `advance` without a wait) |173| `maxTotalOperations` | 5000000 | `E-BUDGET` (life of one automation) |174| `maxTasks` | 256 | `E-LIMIT` on the `at` that would exceed it |175| `maxRamps` | 128 | `E-LIMIT` |176| `maxHandlers` | 32 (`CompileLimits.maxHandlers`) | `E-LIMIT` |177| `maxCommandsPerBeat` | 512 | `E-RATE` (statement-issued writes and actions; ramp updates are not counted) |178| `maxLoopIterations` | 10000 (`CompileLimits.maxLoopIterations`) | `E-LIMIT` for counts computed at run time |179| `maxCallDepth` | 16 | `E-LIMIT` for nested value-returning calls; procedure calls are bounded by an activation stack of `maxCallDepth * 4` = 64 entries |180| `maxArrayLength` | 256 (`CompileLimits.maxArrayLength`) | declared; the compiler enforces the length of array literals and the language has no operation that grows an array |181| `maxSpanBeats` | 100000 | `E-LIMIT` for a computed wait, ramp or position |182| `maxPendingHandlerTasks` | 64 | further events are dropped and counted in `droppedEvents`; not an error |183184An operation is charged (`charge`) for each statement executed, each loop turn, each binary operator, each live read and each builtin call. Strings built with `+` are limited to 2048 characters (`E-LIMIT`) and the text of one `print` is cut at 2048 characters.185186`RuntimeLimits` is a plain struct; `AutomationHost.limits` and `SimulationConfig.limits` both default to `RuntimeLimits()`. The Settings screen shows the limits as fixed values and offers no control for them.187188## Failure behaviour189190| Situation | What happens |191| --- | --- |192| Compile error | No `Program` is produced, so nothing can start. Diagnostics carry a stable code, line, column and token length. `AppModel.run(source:origin:)` returns them and counts a validation error (`SchedulerStats.validationErrors`). |193| Run-time error (`E-ACTION`, `E-UNAVAILABLE`, `E-MATH`, `E-RANGE`, `E-TYPE`, …) | `AutomationInstance.fail`: all tasks, ramps and handlers of that automation are removed; every effect the automation itself switched on (tracked in `enabledEffects` from `enable()`, `toggle()` and `enabled = true`) receives a `disable` action and a `bypassed … after the failure` warning is traced; state becomes `.failed(error)` with the line that was executing; the error is traced. |194| Budget exhaustion (`E-BUDGET`, `E-RATE`, run-time `E-LIMIT`, `E-UNBOUNDED`) | Thrown as `ScriptRuntimeError` from `charge` / `chargeCommand` / the statement; handled exactly like any other run-time error. |195| Engine refuses a write (no beat grid, full rack, …) | `AutomationHost.write` logs a warning line (`engine` origin); the automation continues. An action the engine refuses returns a message and becomes `E-ACTION`. |196| `stop` statement, `stop` command, `host.stop` | State `.stopped`; tasks, ramps and handlers removed; ramps stop where they are; nothing is restored and no effect is bypassed. |197| Emergency stop (`panic` in the console, the `automation.panic` control target, the Emergency Stop buttons and menu command, Shift-Command-Escape) | `stopAll()`, then `engine.bypassAllEffects()` (a `.panic` control event): every effect in every rack is bypassed. Decks keep playing; faders and EQ are untouched. |198199What is not undone on failure: faders, EQ, filters, crossfader and effect parameter values stay where the script left them. Other automations are unaffected; each instance fails on its own.200201What happens to the audio: nothing in the runtime executes on the render thread, and the render thread does not wait for the scheduler, so a failing or slow script changes only which control events arrive. `AutomationLiveTests.failingScriptLeavesAudioRunningAndBypassesItsEffects` runs a script that enables a bitcrusher and then fails with `deck.C.play()` on an empty deck: the deck is still playing, the run is recorded as failed, `runtimeErrors == 1`, the effect is disabled, and from 1.5 s to 2.0 s the output equals the 1 kHz source sine within `1e-5` per sample. If the control queue were full, the push would fail and be counted in `droppedControlEvents`; the benchmark and both offline mixes report zero.202203User-facing description: [errors](../orix-script/errors.md), [security](../orix-script/security.md).204205## Simulator and debugger206207The simulator is not a second implementation of the language. `DebugSession` creates a `SimulatedRig` (an `AutomationTarget` that models four decks, a parameter store seeded from schema defaults, a beat clock and a small fake library) and the same `AutomationInstance` class the live host uses, then steps time in increments of `1 / stepsPerBeat` beats (16 steps per beat by default) until the automation ends, a breakpoint is hit, or `maxBeats` (256 by default) is reached, in which case `timedOut` is set. The rig produces deck events (`play`, `pause`, `beat`, `trackEnd`, `loaded`) that are posted back to the instance, and configured triggers are fired at their beats.208209`Simulator.run(_:automation:config:)` wraps a `DebugSession` and returns a `SimulationResult`: the full trace, sampled curves for every parameter the automation wrote, per-deck play spans, final state, statistics and final variables.210211Debugging is a property of the runtime, not of the simulator: `AutomationInstance` has `breakpoints` (a set of line numbers), `stepping`, and `pausedAtLine`. A breakpoint fires before the statement runs; `advance` returns false and the caller resumes with `continueFromBreakpoint(step:)`. `DebugSession.resume()` and `stepOver()` wrap this. `ToolTests.debuggerBreakpointsAndStepping` checks the paused line, the beat and the variable values at each stop. The live host never sets breakpoints.212213How the application uses it (`App/Sources/Features/AutomationStudio/`):214215- `SimSettings` (tempo, which decks are loaded and playing, `maxBeats`, triggers) is converted to a `SimulationConfig`.216- **Simulate** compiles the active document and calls `Simulator.run` off the main thread; `AutomationSimulatorPanel` draws the result as a timeline (play spans, parameter curves, action markers) and a trace, and marks it stale when the script has changed since.217- **Debug** uses `DebugController`, which owns one `DebugSession` on a private serial queue (`ai.spboucher.orix.dj.debugger`). It starts with the editor's breakpoints, or in stepping mode when there are none, and publishes a `DebugSnapshot` (paused line, beat, variables, tasks, ramps, handlers, trace, statistics) after each `resume` or `step`. The panel states that debugging runs in the simulator and never pauses or changes live audio.218- The same `Simulator.run` is used by Claude Studio to validate proposals ([AI integration](ai-integration.md)), by the documentation viewer to check examples, and by the visual builder.219220User documentation: [debugger](../orix-script/debugger.md).221222The simulated rig is a model, not the engine: it has no audio, its `level` readings are derived from fader values, and `load("title")` searches a fixed list of five titles. A script that passes the simulator can still fail live, for example when a deck is empty.223224## Presets225226`PresetLibrary.all` contains 24 `ScriptPreset` values in 11 categories (`PresetCategory`): Transitions, Crossfades, Filters, Echo, Reverb, Beat effects, Build-ups, Drops, Loops, Auto DJ, Creative performance. A preset is a name, a category, a one-line summary and ORIX Script source text; there is no separate preset format or privileged code path. Opening a preset in the editor gives ordinary text, and `run "Name"` in the console falls back to `PresetLibrary` when no saved script has that name.227228`PresetTests.everyPresetCompilesAndSimulates` requires, for every preset: no compile errors and no warnings, the automation named like the preset, a simulated run (deck A playing, 160 beats, trigger 1 at beat 24) with no error, no warning and no clamped value, completion for presets without event handlers, and canonical formatting. `eightBarTransitionDoesWhatItSays` checks the timeline of one preset in detail (deck B plays at beat 0, deck A pauses at beat 32, its fader is below -55 dB at beat 31.9 and back to 0 dB at 32). User documentation: [presets](../orix-script/presets.md).229230## Auto DJ expressed as scripts231232Auto DJ has no mixing code of its own. `AutoDJPlanner` (`ORIXDJEngine/AutoDJ.swift`) does two things:233234- **Ordering.** `order(_:settings:)` is a greedy nearest-neighbour ordering starting from the first track, deterministic (ties keep the original order). The cost of playing `b` after `a` is a tempo term (percentage change after folding half and double time, plus a penalty of 20 above `maxTempoChange`, 8 % by default; 6 when unknown) plus a key term from the Camelot wheel distance (0.5 per step up to distance 1, 2 per step beyond; 3 when unknown). No network and no model are involved.235- **Transition generation.** `transitionScript(from:to:settings:)` returns ORIX Script text for one of five styles (`blend`, `bassSwap`, `echoOut`, `filterSweep`, `cut`), with the bar count clamped to 1…64 and an optional `deck.X.sync(true)` line. Every generated automation is `quantize bar` and restores the controls it moved on the outgoing deck.236237`DJSession.autoDJTick()` computes the lead time (`leadSeconds`: transition bars + 3 bars, at the deck's tempo), generates the script, compiles it with `ScriptCompiler.compile` and starts it with `host.start(program, origin: "auto-dj")`. If the compiler rejects the generated text, Auto DJ stops with the state "Transition script rejected: …". The last generated script is kept in `AutoDJStatus.lastScript`, and the Auto DJ screen (`App/Sources/Features/AutoDJ/`) describes each style in one sentence and shows the order the planner will play.238239`SessionTests.autoDJMixesTheQueueWithARealTransitionScript` runs three synthesised demo tracks through two transitions offline and checks that exactly one deck is playing afterwards, that the last script compiles, and that there were no run-time errors. `plannerIsDeterministicAndPrefersCompatibleNeighbours` covers the ordering.240241## Schema and generated reference242243`ScriptSchema` is the only place where the vocabulary is defined: four decks, eight hot cues, sixteen triggers, the parameter tables with type, range, default, unit, writable and rampable flags, the action and event tables, and the builtins. Four consumers read it:244245- the compiler (name resolution, type and range checks);246- `Autocomplete` (completions and hover documentation, also `help <path>` in the console);247- `ReferenceGenerator.generatedChapters`, which produces `deck-api.md`, `mixer-api.md`, `effects-api.md` and `api-reference.md` under `docs/orix-script/` (regenerated with `swift run orix-dj-bench docs`);248- `ReferenceGenerator.languageBrief`, the compact description sent to Claude as the system prompt ([AI integration](ai-integration.md)).249250`DocsTests` keeps the documentation and the implementation from drifting apart:251252- `generatedChaptersAreUpToDate` compares the four generated files byte for byte with the generator's output;253- `everyExampleCompilesAndRuns` compiles and simulates every `orixdj` code block in `docs/orix-script/`, requires every `orixdj-error` block to be rejected by the compiler or the simulator, and parses every `> ` line of every `console` block;254- `everyPresetAndErrorCodeIsDocumented` requires each preset name and each of 30 error codes to appear in the documentation;255- `PresetTests.referenceOnlyDocumentsWhatCompiles` compiles a read of every path in the generated tables (more than 150).256257Result of the run used for this document (`swift test --no-parallel`, debug build):258259```text260=== ORIX-DOCS === 150 examples compiled and simulated, 59 error examples rejected, 59 console lines parsed === END ===261```262263## Measured timing264265All figures below are from offline rendering (`renderOffline`), which calls `tick()` once per 256-frame block instead of running the 4 ms real-time thread. They measure whether commands computed with look-ahead reach the render core before their sample; they do not measure the jitter of the real-time scheduler thread under load, which has not been measured for this document.266267**Benchmark** (`docs/reports/engine-benchmark.txt`, release build, Apple M5 Max, `orix-dj-bench bench`; 48 kHz, 256-frame buffers; two automations, one issuing sixteen commands per beat and one running three continuous ramps):268269```text270Automation scheduling (offline, 256-frame buffers, 15 ms look-ahead)271 ticks 3750 tick mean 2.5 µs max 343.9 µs272 timed commands 687 late 0 worst lateness 0 samples dropped control events 0 runtime errors 0273```274275The heading's "15 ms" is a label in `Benchmarks.swift`; the host in that benchmark runs with the default 30 ms (see the note above). The maximum tick time includes preemption, since the benchmark does not run on a real-time thread.276277**Test** (`AutomationLiveTests.scriptActionsLandOnExactSamples`, debug build, look-ahead 20 ms, 120 BPM click tracks on decks A and B, `deck.B.play()` and `deck.B.pause()` scheduled with `at bar` and `at beat`):278279```text280=== ORIX-AUTOMATION-TIMING === tracked 3 late 0 maxLate 0 samples; worst click offset 0 samples === END ===281```282283The test's tolerance is 2 samples between each deck B click and the nearest deck A click, and zero late events. `rampsAreSmoothAndReachTheirTargets` checks a scripted `over 4beats` fader ramp against a DC input: -10 dB within 0.25 dB at the half-way point, -20 dB within 0.05 dB at the end, back to 0 dB within 0.01 dB after the following write, and a largest sample-to-sample output step below 0.0005 during the ramp.284285**Offline mixes of real music** (`orix-dj-bench mix`: decode two tracks, analyse, set gain and key lock, run a preset through `AutomationHost`, write a WAV):286287| Preset | Tracks | Timed commands | Late | Other results |288| --- | --- | --- | --- | --- |289| Bass Swap | 124 BPM into 122 BPM | 10 | 0 | deck B played at 124.00 BPM; 0 clipped blocks; peak -6.99 dBFS; the rendered file analyses at 124.00 BPM with tempo stability 0.98 |290| Eight Bar Transition | two 119 BPM tracks | 9 | 0 | peak -3.71 dBFS; the rendered file analyses at 119.00 BPM with tempo stability 0.98 |291292Nobody has listened to these two renders yet. The figures say that the commands were on time and that the result has a steady tempo and does not clip; they say nothing about how the transitions sound.293294Not measured: the scheduler thread's tick gap (`maxTickGapMillis`) and late-event counts on a real audio device during a long session, and behaviour with dozens of concurrent automations.295