# 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 — ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. (@UIParam/UIParamNode themselves live in core `Lyrebird`.) | | `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`. ## Repo Guard Scripts These guards catch classes of regression that **`swift build` / `swift test` structurally cannot**. Both are manual/CI (too slow for pre-commit). Run before a release or a merge that touches their surface. | Script | Guards | Run when | |---|---|---| | `bash scripts/check-swift6-consumer.sh` | The zero-annotation consumer guarantee — builds `RegressionFixtures/MainActorConsumer` under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`. The main package **does not build under that flag**, so the test suite cannot catch an isolation regression. | Any change to `SynthesizerBase` / `Synthesizer` actor isolation. Non-negotiable: `swift test` passing is *not* evidence here. | | `bash scripts/check-docc.sh` | New DocC warnings — broken symbol links, ambiguous refs, article/symbol collisions. DocC links pin a symbol's **full signature**, so adding one parameter silently breaks every link to it. Nothing else checks this. | Any change to a public signature, or edits to `.docc` / doc comments. | | `bash scripts/check-doc-impact.sh [range]` | **Reports** (never fails) which docs a diff's public-API changes may have invalidated. Doc rot is usually *caused* by an API change, and a diff-only read cannot find the stale references — they live in files the diff never touches. Run by `/lyrebird_review` step 2b; suppresses refs the compile guard already covers. | Any change to a public signature. | | `bash scripts/check-doc-snippets.sh` | Doc **examples** that stop compiling. `swift build` never sees a code fence and `check-docc.sh` only validates links, so examples rot silently — `engine.add` became throwing and 11 examples kept calling it without `try`; `LyrebirdFloat` was deleted and 75 references outlived it. Both are type errors, so the fences are typechecked against the real API. | Any change to a public signature, or edits to `.docc` / doc comments. | `check-docc.sh` is a **ratchet**: it fails on warnings absent from `scripts/docc-warnings-baseline.txt`. That baseline is now **empty** — the catalog is at zero warnings — so in practice any new warning fails the build. Keep it that way; the baseline may only shrink. (`--strict` asserts zero explicitly and is equivalent while the baseline is empty. `--update-baseline` exists for the rare deliberate exception — prefer fixing the link.) **Golden values need a test, not a guard.** A typecheck proves an example still *compiles*; it cannot see a documented result drift. Where a doc asserts concrete output (`// → 0.744, 0.046, …`), pin it with a test — `DistributionKindGoldenValueTests` and `_DocTheorySnippetCheckTests` are the two instances. This is not optional pedantry: three of the four `DistributionKind` sequences had silently drifted, and their fences also passed a `seed:` argument to a type that has no such parameter. `check-doc-snippets.sh` checks the fences recorded in `scripts/doc-snippets-manifest.txt` (currently **426** of 1458). That set is produced by asking the **compiler** which fences compile — `--classify` — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, `Package.swift` snippets and pseudo-code drop out with no skip list. **Coverage is therefore partial by construction**: a fragment like `try engine.add(MySynth())`, which needs both an `engine` and a `MySynth` in scope, is *not* checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run `--classify` after adding examples or deliberately changing what is checkable. ## 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` - Linux live audio (`ALSAAudioDriver`, `makeDefaultAudioDriver()`, libasound build requirement) → `docs/engine/alsa-audio-driver.md` - Portable WAV read/write off Apple (`WavFileWriter` / `WavFileReader`, header layout, `WavFileError`) → `docs/engine/portable-wav-codec.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) - Inline custom per-sample DSP / single-sample feedback without a new Generator type (`SampleLoop` — pre-allocated output, typed `inout` feedback state, channel inference + broadcast) → `Sources/Lyrebird/Generators/Core/SampleLoop.swift` - 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` - Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift` - Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift` - 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` - Pitch / scale theory toolkit (spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale mapping; → notation + Hz/seconds for synthesis) → `docs/stdlib/theory.md` (types under `Sources/Lyrebird/Score/Theory/`) - 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` - Linux user setup (toolchain, VS Code, build/test, run a sample) → `docs/linux-getting-started.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)`. - Interpreted graph-DSL (`LyrebirdGraphDSL` target — cross-platform, no swiftc) + its code-gen (`Tools/DSLRegistryGen`, separate SwiftPM package so swift-syntax stays out of the main build; run `scripts/generate-dsl-registry.sh`, committed output, `--check` drift guard) → `docs/tooling/graph-dsl-design.md`. Registry (`Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift`) is generated from generator init signatures — regenerate + commit after changing a public generator init. In progress (LC-8); language/parser not yet built. **Diagnostics** - User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md` - Developer-side debugging (per-instance RT debug tap `SynthesizerBase.debugTap`, `GeneratorBase.debugTag`, LLDB breakpoint recipes for inspecting a live voice / generator) → `Sources/Lyrebird/Lyrebird.docc/Debugging.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, blocking `snd_pcm_writei` on a dedicated thread (ALSA) on Linux. - Never name a concrete driver in code that is meant to build on more than one platform — call `makeDefaultAudioDriver()`. Which drivers exist depends on how Lyrebird itself was built (a Linux build without libasound, or one cross-compiled from macOS, has no `ALSAAudioDriver`), so a consumer-side `#if` is a guess. Code already locked to one platform is exempt and should name its driver directly — e.g. the AppKit-only `ui-demo` scaffold template emits `CoreAudioDriver()`. - 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 sub-blocking `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. **Exception:** `BlockRateControlGenerator` conformers never sub-block and omit the call (see the bypass bullet below). - `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode. - Control generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers) must advance once per audio block, bypassing the sub-block loop. Conform to `BlockRateControlGenerator` (marker protocol in `GeneratorCore/BlockRateControlGenerator.swift`) — its `calculatedSamples` default routes to the block-rate gateway and the conformer skips `_setupSubBlockBuffer()`. This replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder. A true sub-blocking Control must NOT conform. See `docs/protocols/writing-generators.md` §15 for the 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/` `Utilities/` `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. `engine.stop()` also unbinds every non-persistent synth it was hosting (including ones nested inside drained `Group` subtrees) as part of its node-tree teardown, so a stop-then-re-add of the same instance — to the same engine or a different one — needs no such wait; the RT thread is already halted before `stop()`'s unbind pass runs. See `docs/engine/synthesis-engine.md` § `stop()` node-tree teardown contract. 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 phase numbers in code or docs Never write phase numbers (`Phase 228`, `Phase 228c`, `phase-224`, `pre-Phase-209c`, `// Phase 216:`, `(Phase 201)`, `— Phase 214`) in source comments, doc-comments (`///`), `.docc` markdown, `@Suite`/`@Test` display strings, or test function / type / file names. Phase numbers are meaningless to external readers — they belong **only** in planning docs (`docs/00-working-order.md`, `docs/01-completed-working-order.md`), commit messages, and `MEMORY.md`/phase history. Describe the **behavior or reason** instead: ```swift // WRONG // Phase 216: emit a tempo direction for this measure when a TempoChange targets it. let cap = ... // Phase 228c /// > Note: Phase 224 wires this as model state. @Suite("EngineHost (Phase 197)") // RIGHT // Emit a tempo direction for this measure when a TempoChange targets it. let cap = ... /// > Note: this is model state. @Suite("EngineHost") ``` Exception: the DSP term **"phase"** that is NOT a planning reference — oscillator `phase`, `phase accumulator`, `phase offset`, `_phase`, `initPhase`, `phase modulation`, "Phase 0.25 in an 8-sample table" — is a real audio term, never touch it. The rule targets `Phase ` planning tags only. ### 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.. Double`. - `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure. - `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls. - `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there. - `onePoleLowPassStep(state:x:b1:comp:)` — `Generators/Filters/FilterHelpers.swift`; `y = b1·state + comp·x`, mutates state, returns y. `comp = 1 − b1` precomputed by caller. Used by `Lag.Audio` / `Lag2.Audio` (cascade two) / `LagUpDown.Audio` / `Lag2UpDown.Audio` (after asymmetric coefficient selection). - `leakyIntegratorStep(state:x:b1:)` — `Generators/Filters/FilterHelpers.swift`; `y = x + b1·state`, mutates state, returns y. SC `Decay`/`Decay2` convention (input not attenuated by `1 − b1`). Used by `Decay.Audio` + `Decay2.Audio` (cascade two for attack/decay difference). - `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — `Generators/Dynamics/DynamicsHelpers.swift`; asymmetric attack/release smoother step with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`). - `sampleOrZero(_ p: UnsafePointer, _ 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 across many multi-input generators (`Flute`, `Clarinet`, `KarplusStrong`/`GatedKarplusStrong`, `BowedString`, `PlayBuffer`, `SpatialDistance`, `MuTronIII`, `Hilbert`, the spatial panners, and more). 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`. - `fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)` — `MulAdd.swift`; held-constant counterpart of `fillScalarRampedResult` — fills a block with one value, applies mul/add, sets `previousOutputValue` to the last sample. For block-rate `Control` paths whose output holds one value (one-pole smoothers `Lag`/`Decay`/`LeakDC`/`Slew`/`Formlet`, block-constant analysis `ZeroCrossing`/`Slope`/`RunningMin`/`Max`, trigger/counter latches `Trig`/`Schmidt`/`PulseCount`/`Stepper`; 20 sites). No-op at `count == 0`. NOT for per-sample-varying output. - `MulAddSpec.applyScalar(_:graph:)` — `MulAdd.swift`; folds scalar `mul`/`add` into one block-constant `target` (returns it unchanged on identity). The scalar counterpart of `applyIfNeeded`; used by the 36 scalar-fold paths (Math.Control plus Routing/Waveshaping crossfades and shapers) before `fillScalarRampedResult`. - `firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` / `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate read of a generator-or-scalar input. `first…` reads the block's first sample (`0` if empty) — oscillator/LF/noise `Control` paths; `last…` reads the final sample (ramp endpoint) — dynamics + delay-time paths. Both fall back to `floatValue` for non-generators - `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`) - `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`). - `RTScratchBuffer` — `Buffers/RTScratchBuffer.swift`; a `~Copyable` single-owner heap scratch buffer that replaces hand-paired `allocate`/`deinitialize`/`deallocate` in scratch-owning generators (the Spectral/FFT family). `init(count:)` zero-fills (`Element: Numeric`); `init(count:repeating:)` fills any value. `@inline(__always)` `baseAddress`/`count`/`subscript` (`nonmutating set`) so the hot loop matches the raw pointer. Store as a `let` assigned in `init` — never a per-call local. Not for `[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` cannot be `Array`-stored) or capacity-1 scalar boxes used via `.pointee`. `@_spi(LyrebirdExtensions) public`. 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)