# Lyrebird — Claude Context Native macOS/iOS audio synthesis framework in Swift. Users implement `Generator` and `Synthesizer` protocols; Lyrebird engine handles Core Audio I/O and signal-graph evaluation. No separate scripting language. ## Pick the Right Agent First Eight agents live in `~/.claude/agents/` (maintainer's source of truth) and are mirrored into the repo at `.claude/agents/` (auto-discovered) and `claude/agents/` (installer source). Invoked automatically when task description matches; you can also invoke explicitly. | Agent | Use when | |---|---| | `lyrebird_demo_agent` | **Any demo work** — CLI demos, macOS GUI, iOS GUI, NoteController, Xcode project edits. | | `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. | | `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. | | `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. | | `lyrebird_swiftui_agent` | LyrebirdUI module — @UIParam, ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. | | `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** | | `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. | | `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. | **Repo mirror sync** (after editing working copies in `~/.claude/`): ``` bash scripts/sync-claude-from-working.sh # dry-run bash scripts/sync-claude-from-working.sh --apply bash scripts/sync-claude-from-working.sh --check # CI: exit 1 on drift ``` Edit only in `~/.claude/`. Script keeps `.claude/` and `claude/` in sync. New agents/skills must be added to the repo manually the first time, then this script keeps them in sync. **Pre-commit hook** (one-time setup per clone — blocks commits with stale repo mirror): ``` git config core.hooksPath .githooks ``` The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/agents/` is absent (contributors without working copies are not blocked). Bypass for one commit with `git commit --no-verify`. ## Task → Doc Map **Engine / RT core** - Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md` - Bus memory / In / Out → `docs/engine/bus-system.md` - Sample-accurate scheduling → `docs/engine/scheduling.md` - ParallelGroup / multi-core → `docs/engine/multi-core.md` - Multi-engine host (`EngineHost`) + NRT batch render pool → `docs/engine/multi-engine-host.md` **Generators** - Generator protocol + DemandGenerator → `docs/protocols/generator.md` - **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers) - Built-in generator catalog → `docs/stdlib/generators.md` - Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md` - Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section) - Physical models (BowedString, Flute, Clarinet, ScannedSynthesizer) → `Sources/Lyrebird/Lyrebird.docc/Generators/PhysicalModels.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/ScannedSynthesis.md` - Oversampling primitives (`HalfbandUpsampler`/`HalfbandDownsampler` 2×/4×) → `Sources/Lyrebird/Lyrebird.docc/Generators/Oversampling.md` - Spectral processors / FFT chain → `docs/stdlib/spectral.md` - Extension SDK / out-of-tree generator packages (SPI surface, versioning) → `docs/protocols/extension-sdk.md` **Synthesizer / language side** - Synthesizer protocol → `docs/protocols/synthesizer.md` - Node tree / Group nesting / bus routing → `docs/protocols/node-tree.md` - Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md` - `Pattern` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md` - MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md` - Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md` - TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md` - Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md` - Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md` - Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md` - NRT / offline render → `docs/tooling/nrt-guide.md` **Tooling / project** - CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md` - Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md` - Dev workflow / phase branches / build → `docs/tooling/workflow.md` - Xcode project templates → `docs/tooling/xcode-templates.md` - AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md` **UI** - LyrebirdUI / parameter binding → `docs/ui/gui-system.md` - Live-compile scratchpad (`LyrebirdScratchView`, `LyrebirdLiveCompile`, `LyrebirdLiveCompileUI`) → `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`. **Lives in the separate `LiveCompile/` SwiftPM sub-package** (Phase 167) — cross-package dependency forces `libLyrebirdLiveCompile.dylib` to dynamic-link `libLyrebird.dylib` instead of statically embedding it, eliminating the ObjC class double-registration crash that aborted full `swift test` runs in the single-package layout. Build sub-package with `(cd LiveCompile && swift build)` / `(cd LiveCompile && swift test)`. **Diagnostics** - User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md` **Planning** - What to build next → `docs/00-working-order.md` - Completed phases → `docs/01-completed-working-order.md` ## Hard Constraints One-liners. Detail and rationale lives in linked docs. **Platform / build** - macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15. - No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS. - No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`). **RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md` - No allocation, locks, blocking, `print`, `String` construction, or `is`/`as?` runtime type checks. Classify inputs at `init`. - No `!` force unwraps. Use `guard let`, `if let`, `?? fallback`, or `throws`. - All bus memory pre-allocated at `start()`. Never resized. - Generator output buffers pre-allocated to `lyrebirdDefaultResultBufferSize` (512). `SynthesisEngine.init` enforces `blockSize ≤ 512`. Every `_computeSamples` opens with `_checkCount(count)` (inherited from `GeneratorBase`). No grow path. - No shared mutable state between Synthesizer instances — graph-copy-per-instance. **Module layering** - No `SwiftUI`, `AppKit`, or `UIKit` imports in core `Lyrebird` module. UI lives in `LyrebirdUI` only. - Platform-specific input sources (e.g. AppKit `NSEvent` mouse monitors) live in `LyrebirdUI` and conform to a core protocol/base class (e.g. `MouseInputBridge`) that core Generators read from. Install via the registry (e.g. `MouseInput.install(_:)`) at app startup. **Generator protocol** — `docs/protocols/writing-generators.md` - `GeneratorBase` is the required base class. Provides `_segmentSerial`, `_cachedResult`, `_subBlockBuffer`, **and `_result`** (mono, pre-allocated to `lyrebirdDefaultResultBufferSize`, zero-filled). Never redeclare these as stored properties. - Mono generators inherit `_result` directly — no declaration, no init line. Multi-row generators call `super.init(channels: N)` from their designated `init` to allocate N rows in one shot. Dynamic channel counts pass `channels: outChannels` computed in `init`. - Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate. - `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target. - Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer. - Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. - `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode. - Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule. - Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`. - `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`. ## File Organisation **Every new `.swift` file starts with the MIT SPDX header.** First five lines, before any `import`: ```swift // .swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT ``` (Blank line after the header, then the file body.) Applies to all source under `Sources/`, `Tests/`, `Demos/`, and `LiveCompile/`. **Exception:** Xcode file-template resources at `Sources/LyrebirdCLI/Resources/XcodeTemplates/*.xctemplate/___FILEBASENAME___.swift` — these keep only Xcode's injected `//___FILEHEADER___` (the header belongs to whoever instantiates the template, not to Lyrebird). Likewise, scaffolder/exporter code that *emits* user-facing Swift source must not bake the Lyrebird copyright into the generated string. Review-blocking: a new tracked `.swift` without the header is a violation. **One public type per Swift source file.** Generator enums, classes, protocols, support types each in their own file. - Generator family per file (`OscSawtooth.swift`, `LFSquare.swift`, `Clip.swift`, etc.). - Shared file-scope helpers go in `*Helpers.swift` (e.g. `OscBandLimitedHelpers.swift`). Access `internal` (no modifier) so visible across files. - Type-coupled support types (error enums, format enums) each in their own file (e.g. `DiskInError.swift`, `DiskOutFormat.swift`). - One `@Suite` per test file, named `Tests.swift`. **Never drop new files at `Sources/Lyrebird/` root.** Every new `.swift` file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical): `AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `ValueCompute/` `Voices/` Rule: 1. Place into an existing subfolder if function matches (`Generators/` = concrete `Generator` implementations, `GeneratorCore/` = protocol layer + `MulAdd`, `Engine/` = RT core, `Buses/` = bus memory + allocation, `NodeTree/` = `Group`/`ParallelGroup`/`NodePosition`/`PreparedNode`, `Math/` = constants + numeric utilities, `Kinds/` = cross-cutting enum descriptors, etc.). 2. If no folder fits, **propose a new subfolder in the PR description** (one-line rationale, list of files going in) rather than landing files at root. Reviewers accept or redirect. 3. Subfolder may have further nesting when a family is large (e.g. `Generators/BufferIO/`, `TemporalStream/Algorithms/`). Loose .swift at `Sources/Lyrebird/` root is a review-blocking violation. `Sources/Lyrebird/Lyrebird.docc/` is the only non-folder exception at root. Review agents flag any new file introducing a second unrelated public type without explicit prior approval, and flag any new .swift landed at `Sources/Lyrebird/` root. ## Interface Conventions **Filter resonance parameter naming**: - `q:` — used for filters parameterised by a **quality factor** (RBJ cookbook, SVF, Butterworth cascade, resonator banks). `q = 1/sqrt(2) ≈ 0.707` is Butterworth (no peak); higher values produce sharper peaks. Range typically `[0.1, ~100]`. - `resonance:` — used for filters parameterised by a **raw feedback factor** (Moog ladder and other emulation filters). Range typically `[0.0, ~1.0]` where `1.0` is the self-oscillation threshold. Engine may clamp slightly above 1.0 to avoid runaway. Both are documented at the parameter level; the distinction is principled (different DSP families parameterise resonance differently), and call-site choice should reflect the underlying model rather than a uniform name. New filters route to whichever parameter the underlying algorithm uses naturally. **`engine.add` / `engine.schedule` are throwing** (Phase 196). Replaced the legacy `Bool`-returning signatures with structured `throws` on all four add/schedule entry points: ```swift public func add(_ synth: any Synthesizer) throws public func add(_ synth: any Synthesizer, position: NodePosition) throws public func schedule(_ synth: any Synthesizer, at time: SampleTime) throws public func schedule(_ synth: any Synthesizer, after seconds: Double) throws ``` Throws `EngineAddError`: `.boundToOtherEngine(current:prior:)` (cross-engine), `.doubleAdd(engine:)` (same-engine re-add), `.pendingQueueFull`, `.rebuildFailed(underlying:)`. Both UUIDs surface in cross-engine errors via `SynthesisEngine.identifier: UUID`. Internal `_bind(to:) throws` / `_unbind(from:)` on `SynthesizerBase` back the precondition via single-shot atomic CAS. `LyrebirdBuffer` has opt-in two-tier binding (`bindExclusive` / `bindReadOnly`) for cross-engine sharing — see `docs/engine/multi-core.md` § Object ownership rules. `engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance. Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern. ## Swift Code Style Rules Hard rules. Review agents flag violations. ### No force unwraps Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`. ```swift // WRONG vDSP_vsmulD(buf.baseAddress!, 1, &gain, out.baseAddress!, 1, n) // RIGHT buf.withUnsafeMutableBufferPointer { b in guard let base = b.baseAddress else { return } vDSP_vsmulD(base, 1, &gain, outBase, 1, n) } ``` ### No magic numbers Every non-trivial literal needs a named `let`. Exempt: `0`, `1`, `-1`, `2` when arithmetic meaning is obvious. Hotspots: queue capacities, trig scale factors (`1.0/sqrt(2.0)`, `0.5*.pi`), vDSP delay-state sizes, normalisation/gain constants. ```swift // WRONG: SPSCQueue(capacity: 32) // RIGHT: let killQueueCapacity = 32; SPSCQueue(capacity: killQueueCapacity) ``` ### Doc comments on public Generator init parameters Every new public Generator type documents `init` parameters **in two places** so Xcode Quick Help works from both type name and call site: 1. **Class-level `/// - Parameters:` block** on the `Audio` / `Control` class. 2. **Init-level `/// - Parameters:` block** on the `init` itself. Each entry states: what it does, unit (Hz / dB / seconds / ratio / [0, 1] / frames), valid range or clamping, default when non-obvious. ```swift /// Audio-rate lowpass filter. /// /// - Parameters: /// - input: Signal to filter. /// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist. /// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. public final class Audio: _Base, AudioGenerator { /// - Parameters: /// - input: Signal to filter. /// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist. /// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`. /// - mul: Output multiplier. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. public init(input: any ValidGeneratorInput, freq: any ValidGeneratorInput, q: any ValidGeneratorInput = 0.707, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0) { … } } ``` Exception: unary/binary math operators where the class-level formula makes every param self-evident (`Abs`, `Sign`, `Floor`, etc.) only need `/// - Parameter signal: Input signal.` at both levels. ### Multi-line declarations Multi-line format required when ≥ 2 type aliases or ≥ 2 init parameters: ```swift // GeneratorEnum extension Wrap: GeneratorEnum { public typealias AudioType = Wrap.Audio public typealias ControlType = Wrap.Control } // Init with ≥ 2 params public init( input: any ValidGeneratorInput, freq: any ValidGeneratorInput, q: any ValidGeneratorInput, mul: any ValidGeneratorInput = 1.0 ) { … } // Single-param exception public init(_ signal: any ValidGeneratorInput) { … } ``` ### Explicit type annotations on bindings Every `let` / `var` binding — stored properties on classes/structs/enums, locals inside functions, and `for x in …` loops — must carry an explicit `: Type` annotation. Inferred bindings (`let x = expr`) are a review-blocking violation in new and modified code. ```swift // WRONG let buf = LyrebirdBuffer(count: tableSize) let intPhase = Int(phase) let frac = phase - Double(intPhase) for i in 0.., _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper. - `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`. - `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`. - `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`. - `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`. - `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` — `ResultBuffer.swift`; replaces the `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literal - `_mulAdd.applyIfNeeded(to:graph:count:)` - `fillRampedResult(into:from:to:mulAdd:graph:count:)` - `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`. - `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` - `xorshift64Next(_:)` - `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`) Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here. ## Code Review `/lyrebird_review` required before every merge to `main`. Run on feature branch after all work complete. No merge with blocking findings — fix and re-run until clean. Skill behaviour: 1. `swift test` — stops on failure 2. Invokes `lyrebird_review_agent` (RT safety, bus rules, protocol correctness, helper usage, test coverage) 3. Clean pass → appends one-line phase-completion entry to `MEMORY.md` Phase completion checklist + branch policy: `docs/00-working-order.md`. After merging a phase to `main`, move its section from `docs/00-working-order.md` into `docs/01-completed-working-order.md` and update the summary table. ## Protocol Hierarchy ``` Generator (base) ├── AudioGenerator (.audio rate — sample-rate processing) └── ControlGenerator (.control rate — block-rate processing, may sub-block) DemandGenerator (NOT a Generator — pure value source, pull-based) ├── DemandSequence (sequential cycling) └── DemandRandom (random pick, xorshift64 PRNG) Consumed by Demand.Audio (sample-accurate) / Demand.Control (didTrigger gate) one value per ≤0→>0 trigger edge. Owned by exactly one puller. ValidGeneratorInput ├── Float / Double / Int literals ├── any Generator └── Closure (wraps ClosureBody) Synthesizer └── DAG of Generator instances (direct wiring) └── In/Out generators communicate via bus system Node tree SynthesisEngine └── rootGroup (Group, persistent) ├── [pre-main nodes] ← .before(engine.mainGroup) ├── mainGroup (Group, persistent) ← engine.add(_:) default target (head-insertion) │ └── Synthesizer instances └── [post-main nodes] ← .after(engine.mainGroup) ``` ## Legacy Code `legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — useful patterns: - `LyrebirdTypes.swift` — ValidGeneratorInput protocol, type aliases - `LyrebirdUgen.swift` — Generator base - `LyrebirdNode.swift` — node tree / groups - `LyrebirdGraph.swift` — build closure pattern, graph copy - `UGens/` — oscillators, filters, envelopes, delays (modernize as Generators, don't copy)