bugfixes, better MusicXML support and 1.1.0

This commit is contained in:
2026-06-10 08:41:07 -07:00
parent 6d3a0930a1
commit f59fd3b55a
228 changed files with 32271 additions and 2586 deletions
+89 -495
View File
@@ -2,7 +2,7 @@
Phases are ordered by dependency. Each phase should have tests before moving on.
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D) are archived in `docs/01-completed-working-order.md`.
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222) are archived in `docs/01-completed-working-order.md`.
## Phase Completion Checklist
@@ -161,7 +161,7 @@ Full details in `docs/01-completed-working-order.md`.
| 92 | `MoogLadder.Audio` — Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling via Phase 91 `HalfbandUpsampler2x` + `HalfbandDownsampler2x`, and SC-style half-sample feedback compensation (`xfb = x − k·(y4 − 0.5·x)`). Self-oscillates near `resonance = 1.0`, clamped to `moogLadderMaxResonance = 1.4`; cutoff coefficient capped at `0.999`. Mono Audio-only (no GeneratorEnum, no `.Control`). `cutoff`/`resonance` `ValidGeneratorInput`. tanh count optimised: 5 per oversampled sample by caching `tanh(yN)` between stages. `denormalsToZero` on every stage. New "Saturating Ladder Filters" section in `Filters.md` DocC. | 2949 |
| 93 | `ConvolutionReverb.Audio` — uniformly partitioned FFT overlap-save convolution against an `LyrebirdBuffer` IR. `partitionSize` (power of two, default 256) sets FFT size `N = 2P` and inherent latency. IR is partitioned into `ceil(ir.count / P)` blocks at init; each partition's `vDSP_fft_zrip` forward FFT is precomputed once into per-channel split-complex storage. RT path: input accumulator fills P samples, runs forward FFT into a numPartitions-slot frequency-delay line, dispatches `vDSP_zvma` complex multiply-accumulate against every IR partition spectrum (with scalar fix-up for the packed bin-0 DC/Nyquist real values), inverse FFT, scales by `1/(4N)` (forward ×2 × forward ×2 × inverse ×N), copies last P samples (overlap-save) into a per-channel output stage. `outputChannelCount` matches `ir.channelCount`; mono input is convolved separately against each IR channel. `mix`, `mul`, `add` are `ValidGeneratorInput`. All FFT/FDL/IR storage uses `UnsafeMutablePointer<Float>` allocated in `init`, freed in `deinit`. `convolutionReverbMaxPartitionSize` = 8192, `convolutionReverbMaxPartitionCount` = 16384 cap total IR length. | 2962 |
| 94 | `MIDIFile` SMF parser (formats 0 + 1, PPQ division) + `MIDIFilePlayer` clock-driven playback. Pure language-side parser in `Sources/Lyrebird/MIDI/SMF/`: `MIDIFileError` enum, `MIDIFileEvent` (beat-stamped event with `Kind` covering `.midi(MIDIMessage)` channel events + `.tempo`/`.timeSignature`/`.keySignature`/`.trackName`/`.instrumentName`/`.text`/`.copyright`/`.lyric`/`.marker`/`.cuePoint`/`.endOfTrack` meta), `MIDIFileTrack`, `MIDIFile`. Internal `SMFParser` reads MThd/MTrk chunks, decodes VLQ delta times, honours running status, surfaces meta events through `decodeMetaEvent`, silently skips SysEx / unknown meta. Tick→beat conversion at parse time (`beat = tick / ticksPerQuarter`) so result is tempo-independent. `allEvents`/`allChannelEvents`/`tempoMap`/`totalBeats` convenience views; merge across tracks is stable on `(beat, trackIndex)`. `MIDIFilePlayer` owns a `LyrebirdRoutine`, walks `allEvents` calling `ctx.wait(beats:)` between events, dispatches `.midi` to `handler`, applies `.tempo` to `clock.bpm` when `applyTempoMap == true` (else forwards), routes everything else to optional `metaHandler`. `play`/`stop`/`reset`/`state` lifecycle. Rejects format 2 + SMPTE division at parse time. | 2983 |
| 96a | `MIDIClockFollower` language-side BPM follower (`Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`): rolling window of last *N* tick `SampleTime`s (default 24 = quarter-note window) → inter-tick avg → `60 / (avgSec * 24)` BPM, clamped to `[minBPM, maxBPM]`, epsilon-gated push to `clock.bpm` *outside* the follower's lock to avoid lock-ordering vs `LyrebirdClock._lock`. Default `_isRunning = true` so free-running clock sources without transport messages work; `.stop` gates `_handleClock` until `.start`/`.continue` re-enables. New `MIDIMessage.continue` (0xFB) added to enum (keyword-escaped), parser, and `bytes()`. Internal `init(timeProvider:)` allows synthetic-clock test injection. Phase 96b (Ableton Link) deferred — stub at `docs/roadmap/ableton-link.md`. | 3122 |
| 96a | `MIDIClockFollower` language-side BPM follower (`Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`): rolling window of last *N* tick `SampleTime`s (default 24 = quarter-note window) → inter-tick avg → `60 / (avgSec * 24)` BPM, clamped to `[minBPM, maxBPM]`, epsilon-gated push to `clock.bpm` *outside* the follower's lock to avoid lock-ordering vs `LyrebirdClock._lock`. Default `_isRunning = true` so free-running clock sources without transport messages work; `.stop` gates `_handleClock` until `.start`/`.continue` re-enables. New `MIDIMessage.continue` (0xFB) added to enum (keyword-escaped), parser, and `bytes()`. Internal `init(timeProvider:)` allows synthetic-clock test injection. Phase 96b (Ableton Link) not planned. | 3122 |
| 95 | `ScannedSynthesizer.Audio` — Mathews/Verplank 2000 1D mass-spring scanned synthesis. Power-of-two ring of N masses (default 64, max 1024). Per audio block: two-pass Jacobi explicit-Euler update — pass 1 fills `_accelerations[]` from old positions/velocities (avoiding in-place Gauss-Seidel asymmetry), pass 2 integrates `v += a·dt` and `x += v·dt`. Per-mass: discrete 1D Laplacian × stiffness − damping·v − centeringForce·x + excitationForce[i]. Excitation injected at single configurable mass index, sampled once per block via `lastGeneratorSampleOrFloat`. Per-sample audio-rate phasor scans `_positions[]` as a wavetable through `oscillatorTableRead` (none/linear/cubic). New `[Double]` overloads of `oscillatorTableRead*` helpers added in `OscillatorTableReadHelpers.swift`. New `ScannedSynthesizerShape` enum (`.gaussian`/`.sine`/`.impulse`/`.zeros`) for init-time displacement preset. Audio-only, no `.Control`, no `GeneratorEnum`. New DocC topic `Generators/ScannedSynthesis.md`. | 3138 |
| 97 | `MuTronIII` — envelope-controlled resonant filter (Audio + Control) modelling the Musitronics Mu-Tron III (1972) auto-wah. Topology: full-wave rectify × `sensitivity` → asymmetric one-pole envelope follower (inlined, not composed) → exponential cutoff sweep `freqLo·pow(freqHi/freqLo, env)` → inlined Chamberlin SVF (selectable `MuTronIIIMode` `.lowpass`/`.bandpass`/`.highpass` and `MuTronIIISweep` `.up`/`.down` — both `let` constants set at init). Mono output. Guards: `_inputIsGenerator` classification + scalar fast path (avoids `Double.calculatedSamples` heap alloc), sensitivity clamped ≥ 0, `freqLo`/`freqHi` clamped to `[0.001, Nyquist]` with monotone ratio, peak floor `1.0` (Chamberlin stability `q1 + f < 2` at `f → 1.0` from Nyquist sweep), denormals zeroed on `_prevAmp` + `_svfLow` + `_svfBand`. `Control` uses standard `calculatedSamples` bypass for once-per-block IIR state advancement; output `fillRampedResult` from previous to current target. New types: `MuTronIIIMode`, `MuTronIIISweep`. 24 tests including deterministic Chamberlin sample 0/1 verification at `1e-12`. | 3162 |
| 102a | Ambisonic Toolkit (FOA extra encoders) — `FoaEncodeOmni` (omni: W=input, X=Y=Z=0; full amplitude on W vs FoaPanB's plane-wave 1/√2 convention) + `FoaEncodeStereo` (left, right, angle) summing two opposing FoaPanB encodes at ±angle. Static `angle: Double` arg; coefficients (`foaRsqrt2`, `cos(angle)`, `sin(angle)`) pre-computed at init. Direct `GeneratorBase, AudioGenerator` finals with 4-row output. lyrebird_review clean on first pass. 28 new tests. | 3595 |
@@ -218,504 +218,98 @@ Full details in `docs/01-completed-working-order.md`.
| 196 | Engine Ownership + Lifecycle Safety — set-once atomic binding (`SynthesizerBase._engineBinding: Atomic<UInt>` storing engine pointer bit pattern, two-pass CAS-loop with stale-pointer recovery via `EngineLifecycleCoordinator` registry lookup), opt-in two-tier binding on `LyrebirdBuffer` (exclusive CAS + saturated-subtract read-only refcount); new `engine.identifier: UUID`; new internal `EngineLifecycleCoordinator` singleton holding weak refs keyed by UUID under `NSLock` (lifecycle-lock site around `start`/`stop` deferred to Phase 197 host scope); new public `EngineAddError` enum (`boundToOtherEngine(current:prior: UUID?)`, `doubleAdd`, `pendingQueueFull`, `rebuildFailed` reserved); new internal typed `RetainQueue<T>` centralising the 8 RT-side `Unmanaged.passRetained` enqueue sites in `applyEvent`. Breaking pre-ship: `engine.add(_:)` / `add(_:position:)` / `schedule(_:at:)` / `schedule(_:after:)` Bool → throws, mechanical sweep of ~357 call sites across `Sources/`, `Tests/`, `Demos/`; `LyrebirdEventList.addPreMaster` / `addPostMaster` also throws. Partial-state rollback in `LyrebirdEventList._firstEventSetup` and `VoicePool.init` (committed-array + reverse-`engine.remove` on throw; instance-state writes deferred until full success). New `Tests/LyrebirdTests/MultiEngineRegressionTests.swift` (8 tests) covers two-engines-two-threads-1000-segments, cross-engine + double-add throws, remove + re-add, stale-pointer recovery (with documented address-reuse known limit and skip path), buffer read-only share, buffer exclusive blocks cross-engine, buffer unbind saturation. Docs: `synthesis-engine.md` gains Engine Identity + Ownership Binding sections; `multi-core.md` gains Object Ownership Rules subsection with canonical cross-engine wavetable share pattern; `CLAUDE.md` Interface Conventions gains `engine.add` throws entry. Review skills updated to `swift test --no-parallel` (canonical command per memory). Four `/lyrebird_review` cycles (3 with substantive fixes, 4th clean). 15 commits on `phase-196`. | ~4180 |
| 197 | `EngineHost` Multi-Engine Facade — creation-owning `public final class EngineHost` (NSLock-protected role→engine + UUID→role maps); `public enum EngineHostRole` (`.nrtRender`, `.rtOutput(deviceID:)`, `.auxiliary`, `.custom`) — `.rtOutput` device-exclusivity enforced by role-Hashable identity, no separate `_claimedDevices` set; `public enum EngineHostError`; `public struct SynthesisEngineConfig` value carrier (not Sendable — driver field). APIs: `makeEngine(role:config:) throws`, `engine(for:)`/`role(for:)`/`engines`/`roles`/`engineCount` (lookup), `startAll() throws` / `stopAll()` (snapshot-and-iterate-unlocked with rollback on partial-start failure — failing engine captured inside loop's catch, no fragile re-iteration-by-elimination), `adopt(existing:role:) throws` (verifies engine in EngineLifecycleCoordinator). NRT batch render pool: `renderConcurrent(jobs:maxConcurrent:) -> AsyncThrowingStream<NRTResult, Error>` using `withThrowingTaskGroup` + `addTaskUnlessCancelled` seed-and-refill; pool engines inline (not host-registered); `defer { engine.stop() }` post-render; monotonic `DispatchTime` elapsed measurement. New `public struct NRTJob: Sendable` + `public struct NRTResult: Sendable`. **Lock-nesting safety**: host releases `_lock` before touching `EngineLifecycleCoordinator` (which has its own NSLock) — pre-validate under host lock, release, construct/query coordinator outside, re-acquire for commit with second validation. Closes the latent host→coordinator deadlock window. New 220-line `docs/engine/multi-engine-host.md`; `multi-core.md` "See also" updated; `CLAUDE.md` doc-map gains row. New `EngineHostTests.swift` (15 tests) + `MultiEngineRegressionTests.twoEnginesViaHostUniformityContract` proving host path produces identical observable behaviour to direct-ctor. **Five `/lyrebird_review` cycles** (passes 1-4 substantive fixes, pass 5 clean): lock-nesting, snapshot-and-iterate-unlocked, NRTJob numInputChannels silent-discard, magic 44100, false @MainActor doc, missing defer on pre-check (`.duplicateRole` would leak lock causing instance-wide deadlock), stale class-level + role + adopt + multi-engine-host.md docs on `.duplicateDevice` semantics, magic 1_000_000_000.0 literal, `addTaskUnlessCancelled` refill bug, cancellation doc accuracy, NRTJob.numInputChannels doc contradiction, doc-comment merging bug (class Quick Help mis-attributed to file-scope const). 9 commits on `phase-197`. | ~4204 |
| 198 | Host Footgun Cleanup — discharges the eleven non-blocking findings (F1–F11) captured in POST_197_FIXES.md after the five-cycle phase-197 review. **F1 code fix**: `EngineHost.renderConcurrent` outer catch distinguishes caller-initiated cancel from a user `build` closure deliberately throwing `CancellationError` via `Task.isCancelled` guard — caller break ends stream cleanly; build-thrown surfaces as stream throw. Two regression tests cover both paths. **F2–F7 docs**: new "Caveats and footguns" section in `docs/engine/multi-engine-host.md` covering NRT pool memory cost (per-engine working-set table, mobile cap recommendation), in-flight files written after cancel (caller-side `Set<URL>` cleanup pattern), cross-job synth-instance sharing (WRONG vs RIGHT examples), cooperative pool starvation (user-side cap; host-side `DispatchQueue` redesign deferred to Phase 199+), `adopt` TOCTOU benign via ARC takeover. **F6 role doc**: `EngineHostRole.swift` `.rtOutput(deviceID:)` rewrote for macOS/iOS asymmetry — iOS deviceID is host-bookkeeping only because RemoteIO doesn't address devices. **F8 source-break**: dropped `.duplicateDevice(UInt32)` case from `EngineHostError` — had no producer (`.rtOutput` Hashable role discriminates by deviceID directly) and forced consumer switches to handle dead code. **F11 code comment**: `// TODO(phase-future, F11)` at `SynthesisEngine.init` call in `makeEngine` documenting non-throwing-init dependency. **Cleanup**: deleted `POST_197_FIXES.md`. F9 + F10 skipped after evaluation. **Two `/lyrebird_review` cycles** — pass 1 found one blocking (CancellationError-from-`build`-vs-caller-cancel ambiguity), pass 2 clean (review-agent no blocking; caveman LGTM on arch + 3 nits applied: rethrow caught CancellationError instance, `>= 1` result count robustness, `onTermination` fires-on-finished comment). 5 commits on `phase-198`. | ~4205 |
| 204 | Score / MusicXML demo + CLI templates — `Demos/LyrebirdScoreDemo/` NRT-render demo + `ProjectTemplate.score` + `LyrebirdScore.xctemplate`, all driven by the existing Score DSL + MusicXML round-trip (no new core API). | 4214 |
| 222 | `LyrebirdPaths` filesystem conveniences — `projectRoot(from:marker:)` (source-anchored via default-arg `#filePath`, extension-marker match) + sandbox-standard dir accessors; score template writes output via it. | 4516 |
| 223 | `Generate` / `PatternNotes` algorithmic score generators — index-driven + `Pattern`-driven `[ScoreElement]` helpers (no new result-builder type); demo/template/docc examples. | 4526 |
| 224 | `TimeSignature` + `MeterMap` model — `beatGrouping` primitive (compound/simple/additive), segmented meter map + anacrusis; `Score.meterMap` + `Part.meterMap?` polymeter override. Model-only foundation for the beat-timeline group. | 4544 |
| 225 | `ScoreTimeline.fill` + shared `fillRests` — place elements at 0-based quarter beats, auto-fill rests, throw on overlap. Generic helper dedups all three gap-fill sites (Timeline/parser Fraction, MIDI Double); `Fraction: AdditiveArithmetic`. | 4558 |
| 226 | `BeatPosition` musical addressing — `.quarters`/`.beat`/`.bar(_:beat:)`/`.bar(_:division:)` resolved to absolute quarters via `MeterMap`; `beat` = felt/conducted pulse (consistent across 4/4, compound 6/8, additive 3+3+2). Anacrusis + mid-piece meter accumulation; meter-layer naming aligned (`pulse*`→`beat*`, `beatUnitQuarters`→`divisionQuarters`). | 4579 |
| 227 | `ScoreTimeline` overlap policies (`.trap`/`.truncatePrevious`) + multi-voice (`fillVoices` explicit, `fillAutoVoiced` greedy distribution). Double + BeatPosition overloads; `ScoreTimelineError.invalidVoice`. | 4586 |
| 228 | Mid-piece meter-change notation (encoder) — `Score+MusicXMLEncode` consumes `meterMap`: `<time>` on change, per-measure capacity in both loops, `measureCount(atoms:meterMap:)`. Constant-meter byte-identical. Encoder-only (round-trip/anacrusis → 228b). | 4595 |
| 228b | Parser meter round-trip — reads all `<time>` → `MeterMap` segments (sort, bar-1 guarantee, dedupe); `annotateBeams` per-measure capacity. Constant-meter byte-identical. Grouping re-inferred (MusicXML carries no grouping). | 4600 |
| 228c | Anacrusis (pickup) notation + round-trip — `<measure number="0" implicit="yes">` (capacity = `anacrusis`), full bars 1-based, both loops + `measureCount` + beam accounting; parser recovers `anacrusis`. No-anacrusis byte-identical. | 4611 |
| 229 | Polymeter notation — per-part `MeterMap` renders each part against its own meter (independent bar groupings/counts). Tests + `Meter`/`Polymeter`/`Beat timelines` docc + ScoreDemo material samples. Closes the beat-timeline group (223–229). | 4615 |
---
## Upcoming Phases
Phases ordered by dependency and value/effort. Each phase needs tests before moving on.
### Phase 201 — Swift 6 main-actor isolation for `Synthesizer` (zero-annotation consumer subclassing)
**Goal.** A consumer building under Xcode 26's default
`SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` must be able to subclass
`SynthesizerBase` with **no concurrency annotations**:
```swift
import LyrebirdSynth
final class ToneSynth: SynthesizerBase { // no nonisolated, no @preconcurrency
@UIParam var freq: Double = 440
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
```
This must hold for the **core package, Quartet (local-path reference), and Test
(remote gitea reference)** simultaneously — those three are the acceptance gate.
**Problem (reproduced).** Core compiles in Swift 5 language mode, so
`SynthesizerBase.build()` / `init()` are *nonisolated*. A consumer whose project
defaults to `@MainActor` makes its subclass's `build()`/`init()` main-actor
isolated → **"main actor-isolated method has different actor isolation from
nonisolated overridden declaration."** Today's only workarounds live on the
consumer (`nonisolated override func build()`, `@preconcurrency`,
`nonisolated override init()`) — exactly what we will not ship. Verified: no
core annotation that keeps `build` nonisolated fixes it (the consumer's own
default-isolation governs its own override declaration). The fix is to make the
*language-side* surface of `Synthesizer` **main-actor isolated** so the
consumer's MainActor default *matches* instead of conflicts, while the single
RT entry point (`evaluate`) stays `nonisolated`.
**Isolation split — the core design.** `Synthesizer` has exactly one RT-thread
entry point; everything else is language-side (main thread):
| Member | Thread | Phase 201 isolation |
|---|---|---|
| `build()` | main (called once at add) | `@MainActor` |
| `release(engine:)` | main only (doc-stated) | `@MainActor` |
| `free(engine:)` | main only (doc-stated) | `@MainActor` |
| `evaluate(graph:count:)` | **RT render thread** | **`nonisolated`** |
| `@LiveParam` / `@UIParam` setters | main / atomic store | inherit main; atomic store is already cross-thread-safe |
`evaluate()` reads only two members: `parameterTable` (immutable `let`) and
`outputGenerators` (`var`, written in `build()` on main, read on RT after the
add-event barrier). Both are touched cross-thread **safely today** via the
engine's existing scheduling contract (the add event is applied on the RT thread
only after `build()` has fully returned on main — a happens-before edge through
the SPSC `pendingQueue`). Phase 201 makes that contract explicit to the compiler
with `nonisolated(unsafe)` on exactly those two stored properties, with a
comment citing the barrier. No new runtime synchronisation is added — the safety
argument is the one already in `ARCHITECTURE.md` §2/§9.
**Plan of work.**
1. **Protocol (`Synthesizer.swift`).** Annotate the protocol so language-side
requirements are `@MainActor` and `evaluate` is `nonisolated`. Options to
evaluate during implementation (pick whichever the compiler accepts most
cleanly): `@MainActor protocol Synthesizer` with `nonisolated func
evaluate(...)`, vs. per-requirement isolation. Update the default-extension
implementations (`evaluate` no-op, `release` throws, `free`) to match.
2. **`SynthesizerBase.swift`.** Mark the class `@MainActor`. Mark
`evaluate(graph:count:)` `nonisolated final`. Mark `parameterTable` and
`outputGenerators` `nonisolated(unsafe)` (the only state `evaluate` reads),
each with a `// RT-read after add-barrier; see ARCHITECTURE.md §9` comment.
Confirm `@LiveParam`/`@UIParam` wrapper-backed properties still compile (the
earlier whole-class-`nonisolated` experiment failed *because* wrappers reject
`nonisolated`; `@MainActor` does not have that problem — verify).
3. **`Group` / `ParallelGroup` (`NodeTree/`).** Both conform to `Synthesizer`
and call `evaluate` on the RT thread. Apply the same split: `build`/`release`/
`free` main-actor, `evaluate` `nonisolated`. `ParallelGroup.evaluate` uses
`concurrentPerform` over children — confirm the child `evaluate` calls remain
`nonisolated` end-to-end (no hop).
4. **Engine call sites.** `SynthesisEngine.processBlock` → `rootGroup.evaluate`
runs on the RT thread and must reach `evaluate` with no actor hop. Verify the
whole RT call chain (`processBlock` → `Group.evaluate` →
`synth.evaluate` → `Generator.calculatedSamples`) is `nonisolated`. The
engine itself is not an actor; ensure nothing forces a `MainActor.assumeIsolated`
or `await` onto the RT path (that would be a correctness/perf regression — a
hard fail for this phase).
5. **Other in-core conformers.** Audit the conformers that implement
`Synthesizer` directly rather than via `SynthesizerBase` (e.g. `VoicePool`,
AUv3 `LyrebirdAudioUnit` / `LyrebirdAUVoicePoolBinding`, any others surfaced
by `grep ": Synthesizer"`). Each needs the same `evaluate`-nonisolated split.
AUv3 is the riskiest (its render block is already a separate isolation
domain) — give it explicit attention.
6. **Language-mode decision.** Determine whether the core `LyrebirdSynth` target
should move to `.swiftLanguageMode(.v6)` (so the isolation is baked into the
module's binary interface and propagates to consumers regardless of their
mode) or stay `.v5` with explicit annotations. Prefer keeping `.v5` if
explicit `@MainActor`/`nonisolated` annotations suffice — a full v6 migration
of the whole module is a much larger lift and out of scope unless required to
make the consumer experience clean. **Spike this first** — it determines the
size of the rest of the phase.
7. **`LyrebirdUI`.** Currently `.v5` to dodge SwiftUI/AppKit actor diagnostics.
`@UIParam` lives here. Confirm the isolation split doesn't force a `.v6`
migration of `LyrebirdUI`; if `@UIParam`-bearing synths need anything, capture
it.
**Acceptance criteria (all three must pass with NO consumer-side concurrency
annotations):**
- **Core:** `swift test --no-parallel` green; `(cd LiveCompile && swift test
--no-parallel)` 34/34. RT path verified to have no actor hop (inspect, and
confirm no perf regression on the core synthesis benchmark).
- **Quartet** (local-path ref): builds + runs; its `SynthesizerBase` subclasses
carry no `nonisolated`/`@preconcurrency`. Remove any such annotations Quartet
currently has and confirm it still builds.
- **Test** (remote gitea ref, Xcode-26 `MainActor` default): the plain
`final class ToneSynth: SynthesizerBase { override func build() {…} }` builds
and runs with zero annotations. Revert the `@preconcurrency` /
`nonisolated override init` / `nonisolated override func build` that
Claude-in-Xcode added.
- A **regression fixture**: an SPM consumer target built with
`-default-isolation MainActor` + `.swiftLanguageMode(.v6)` (the repro from
the Phase-201 investigation) compiles an unannotated `SynthesizerBase`
subclass. Keep this as a committed smoke test so the guarantee doesn't silently
regress.
**Risks / watch-items.**
- `nonisolated(unsafe)` is a promise to the compiler — the `/lyrebird_review`
RT-safety pass must explicitly bless the two properties it lands on, citing the
add-barrier. Do not broaden it beyond `parameterTable` + `outputGenerators`
without re-justifying.
- If the protocol-level `@MainActor` forces awaits onto any existing internal
call site that currently runs sync on a background queue (routines, NRT batch),
that's in-scope to fix — those are language-side and can be `@MainActor` or
explicitly hopped, but must not touch the RT path.
- Docs: once landed, update `GettingStarted.md` / `INSTALLATION_AND_USAGE.md` to
show the clean zero-annotation subclass as *the* pattern, and drop the
interim "use `nonisolated final class`" guidance if it was added.
**Branch:** `phase-201-mainactor-isolation` off `main`. Standard phase
checklist + `/lyrebird_review` before merge. After merge, re-snapshot to gitea
and re-tag (the gitea 1.0.0 is unreleased, so it can absorb this).
**Investigation notes (from the session that wrote this plan — don't re-run these).**
*Exact failure (reproduced).* Consumer error under Xcode 26 MainActor default:
```
error: main actor-isolated instance method 'build()' has different actor isolation
from nonisolated overridden declaration
error: main actor-isolated initializer 'init()' has different actor isolation
from nonisolated overridden declaration
```
Source: `SynthesizerBase.build()` / `init()` are nonisolated (core is Swift 5
mode); consumer's project default makes the *subclass's* override `@MainActor`;
override-vs-base isolation mismatch.
*Reproduction recipe (use verbatim as the Phase 201 regression fixture).* A
throwaway SPM consumer at `/tmp`, depending on the package via local path:
```swift
// Package.swift target settings that reproduce Xcode 26's new-project default:
swiftSettings: [
.swiftLanguageMode(.v6),
.unsafeFlags(["-default-isolation", "MainActor"]),
]
```
```swift
// Sources/App/main.swift — the unannotated subclass that MUST compile post-201:
import LyrebirdSynth
final class ToneSynth: SynthesizerBase {
override func build() { output(bus: 0, source: OscSin.Audio(freq: 440) * 0.2) }
}
let s = ToneSynth(); print("ok \(s)")
```
Note: `.defaultIsolation(MainActor.self)` in the manifest is **unavailable** in
this SwiftPM toolchain (`error: 'defaultIsolation' is unavailable`) — must use
the raw `-default-isolation MainActor` unsafeFlag as above.
*Approaches already tried and RULED OUT (don't repeat):*
1. `nonisolated` on base `init()` + `build()` — **fails.** Consumer's override
still gets `@MainActor` from its own project default; mismatch persists. (The
error even confirms the base is "nonisolated" — proving the problem is the
consumer side, not the base.)
2. `nonisolated` on the **class** declaration (`open nonisolated class
SynthesizerBase`) — **fails to compile core**: `'nonisolated' is not
supported on properties with property wrappers` (the `@LiveParam`/`@UIParam`
stored properties). Whole-class `nonisolated` is a dead end.
3. `nonisolated` on the **protocol requirement** (`Synthesizer.build`) + base —
**fails the same way** as (1).
4. `@MainActor` on the class + `nonisolated final func evaluate(...)` — **right
direction, but surfaced the real work**: 9 errors, all from `evaluate()`
reading `parameterTable` and `outputGenerators` from a nonisolated context
while the class is MainActor (`#ConformanceIsolation` + "main actor-isolated
property can not be referenced from a nonisolated context"). This is exactly
why the plan lands `nonisolated(unsafe)` on those **two** properties — they
are the entire RT-read surface of `evaluate()`. Nothing else in the class is
read on the RT thread.
*Verified-working interim (NOT what we ship, but proves the seam):* the consumer
single-annotation form `nonisolated final class ToneSynth: SynthesizerBase { … }`
compiles cleanly (`Build complete`). Confirms one annotation on the *type* is
enough — Phase 201's job is to move that necessity into the core so the consumer
needs zero.
*RT-read surface (confirmed by reading `evaluate()`):* `evaluate(graph:count:)`
references exactly `parameterTable` (immutable `let`) and `outputGenerators`
(`var`, written in `build()` on main, read on RT). No other stored property is
touched on the RT thread. The `nonisolated(unsafe)` blast radius is precisely
these two.
### Phase 104 — AUv3 Plugin Export
Ship a `SynthesizerBase` subclass as an AudioUnit v3 (.appex) plugin loadable
by Logic, GarageBand, Ableton (AUv3-wrapped via Bridge), Loopy Pro, AUM,
and other AUv3 hosts on macOS and iOS. Closes a major distribution gap: today
Lyrebird synths can only run inside a Lyrebird app. After 104 they can ship
as drop-in instruments / effects in any DAW.
**Background.** AUv3 is Apple's modern Audio Unit format — sandboxed app-
extensions hosted in the DAW's process via a remote-audio-unit interface.
Required for iOS plugin distribution (AUv2 doesn't exist on iOS). Replaces
AUv2 on macOS (still allowed but discouraged for new development). Lyrebird
currently uses the AudioUnit *consumer* C API in `CoreAudioDriver` /
`iOSAudioDriver` to pull samples from hardware — Phase 104 inverts the
relationship: Lyrebird becomes an AudioUnit *producer* that hosts pull from.
**Phase split.** This is a large lift. Split into three sub-phases that can
ship independently:
| Sub-phase | Scope | Status |
|-----------|-------|--------|
| 104a | Wrapper infrastructure: `AUv3Driver`, `LyrebirdAudioUnit` (`AUAudioUnit` subclass), parameter-tree mapping, buffer adapter, ring-buffer block-size adapter. Pure Swift, in `Sources/Lyrebird/`. Headless — no Xcode artefact yet. | ✓ shipped — see `docs/01-completed-working-order.md` |
| 104b | Example Xcode AUv3 project under `Demos/LyrebirdAUv3Demo/` with host app shell + extension target; `auval` validation; ships one example synth ("LyrebirdFM") as a working AUv3 instrument. | ✓ shipped — see `docs/01-completed-working-order.md` |
| 104c | MIDI render block (kAudioUnitType_MusicDevice — note on/off → Lyrebird voice pool), advanced parameter ramping (AUAudioUnit's per-sample parameter automation), preset save/restore, view controller (minimal SwiftUI). | ✓ shipped — see `docs/01-completed-working-order.md` |
All three Phase 104 sub-phases are now shipped. See
`docs/01-completed-working-order.md` for the writeups.
---
### Phase 113 — Pan4 family refactor (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`)
✓ shipped — see `docs/01-completed-working-order.md` for the full writeup.
Reshapes the 4-speaker panning family around an `open class Pan4` base that
holds the shared infrastructure (4-row output buffer, `_mulAdd`,
`outputChannelCount = 4`, named channel aliases). Four concrete subclasses
provide the user-facing generators with two coordinate systems (polar /
cartesian) crossed with two distance modes (none / full SpatialDistance-style
shaping).
**Why now.** The original Phase 113 work (planned as PanXY + PanXYDistance
only) duplicated the 4-corner equal-power gain math against the existing
`Pan4`. Mid-phase the scope expanded to:
1. Drop elevation from `Pan4` — the original "elevation" parameter was just
a second planar axis, not real elevation, and made the API ambiguous.
2. Give the family a polar interface (`PanAz` / `PanAzDistance`) alongside
the cartesian one for sound-positioning workflows that think in
`(angle, radius)` instead of `(x, y)`.
3. Single-source the equal-power gain math so all four subclasses share one
implementation.
**Design.**
| Subclass | Coordinates | Distance modelling |
|----------|-------------|--------------------|
| `PanAz` | polar — `@LiveParam azimuth: Double` (radians) | none (position fixed to unit-square boundary) |
| `PanAzDistance` | polar — `azimuth` + `distance` + `velocity` (all `any ValidGeneratorInput`) | 1/d amp + air-absorption LP + Doppler past `\|distance\| = 1` |
| `PanXY` | cartesian — `@LiveParam x`, `@LiveParam y` ∈ `[-1, 1]` | none |
| `PanXYDistance` | cartesian — `x`, `y` + `velocity` (all `any ValidGeneratorInput`) | Chebyshev metric: 1/d amp + air-absorption LP + Doppler past `max(\|x\|, \|y\|) = 1` |
Shared module-internal helpers (`Sources/Lyrebird/Generators/Panning/Pan4Helpers.swift`):
- `azimuthToSquareBoundary(_ az: Double) -> (x, y)` — projects azimuth
radians onto the unit-square boundary via `1 / max(|sin|, |cos|)` scaling
so the trajectory hits speaker corners at `±π/4` and `±3π/4` (rather than
the inscribed unit circle, which would leave corners unreachable from
azimuth alone).
- `writeEqualPowerSquarePanSample(into:sampleIndex:source:x:y:)` — clamps
`(x, y)` to `[-1, 1]²`, computes the standard four-corner equal-power
gains via `(±+1)·π/4` angles, and writes `source × gain` into the four
`_result` rows at the given index. Power invariant
`LF² + RF² + RR² + LR² = 1` for any clamped position.
Both helpers `@inline(__always) internal`; call cost vanishes after the
optimiser. NaN / subnormal-cancellation guards in
`azimuthToSquareBoundary` collapse degenerate inputs to `(0, 0)`.
Distance shaping (`PanAzDistance` + `PanXYDistance`) reuses the
`SpatialDistanceConstants.swift` module-internal constants
(`spatialDistanceMinReadRate`, `spatialDistanceMaxReadRate`,
`spatialDistanceInitialDelaySamples`, `spatialDistanceMinDelaySamples`,
`spatialDistanceMinCutoffHz`, `spatialDistanceMaxCutoffFraction`,
`spatialDistanceTwoPi`) — promoted out of `SpatialDistance.swift` so the
distance generators share one source of truth. The amplitude / LP /
Doppler pipeline applies to the mono signal **once** before panning
(single one-pole LP + single variable-rate delay line) to avoid
per-channel phase decorrelation artifacts; distance from the listener is
a single scalar.
**Migration / breaking changes.**
- Old `Pan4(input:).azimuth` / `.elevation` (each `@LiveParam` in
`[-1, 1]`) API is removed. The azimuth-only behaviour now lives in
`PanAz` with proper radian semantics (`0` = front centre,
`±π/4` / `±3π/4` for corners, wraps modulo `2π`).
- `Pan4` itself is no longer instantiable as a useful generator — it is
the open base class. Bare `Pan4(mul:add:)` produces a silent zero-fill
output. The doc comment warns against this.
- All existing tests using the old `Pan4` API (`PanningTests.swift` Pan4
suite, `Pan4ParameterRampingTests.swift`, the `Pan4` alias section of
`ChannelSelectTests.swift`) migrated to `PanAz` with corresponding
radian-based corner / edge expectations.
**Files changed.**
New:
- `Sources/Lyrebird/Generators/Panning/Pan4Helpers.swift`
- `Sources/Lyrebird/Generators/Panning/PanAz.swift`
- `Sources/Lyrebird/Generators/Panning/PanAzDistance.swift`
- `Sources/Lyrebird/Generators/Panning/PanXY.swift` (initial Phase 113 pass; refactored to subclass `Pan4`)
- `Sources/Lyrebird/Generators/Panning/PanXYDistance.swift` (initial Phase 113 pass; refactored to subclass `Pan4`)
- `Sources/Lyrebird/Generators/Modulation/SpatialDistanceConstants.swift`
- `Tests/LyrebirdTests/PanXYTests.swift`
- `Tests/LyrebirdTests/PanXYParameterRampingTests.swift`
- `Tests/LyrebirdTests/PanXYDistanceTests.swift`
- `Tests/LyrebirdTests/PanAzDistanceTests.swift`
Modified:
- `Sources/Lyrebird/Generators/Panning/Pan4.swift` (leaf class → `open` base)
- `Sources/Lyrebird/Generators/Modulation/SpatialDistance.swift` (constants extracted)
- `Tests/LyrebirdTests/PanningTests.swift` (Pan4 suite rewritten as PanAz)
- `Tests/LyrebirdTests/ChannelSelectTests.swift` (Pan4 alias → PanAz)
- `Tests/LyrebirdTests/PanAzParameterRampingTests.swift` (renamed from `Pan4ParameterRampingTests.swift` via `git mv`)
- `docs/stdlib/generators.md`, `docs/stdlib/multichannel.md`,
`Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md`
**Verification.**
- `swift build` clean.
- `swift test --filter PanAz --filter PanXY` — 58 tests across 6 suites.
- `swift test` — 3544 tests in 409 suites pass.
- `lyrebird_review_agent` two review cycles. First (initial PanXY /
PanXYDistance work with the old leaf Pan4 still on the elevation API)
caught four blocking findings: dead `_referenceDistance` stored property,
dead `_sampleRate` stored property, two `@Suite` in one file, and
`try? outsideEng.start()` swallowing a second-engine start failure. All
resolved before re-review. The Pan4-family refactor (this entry) passed
clean on the first sweep — vtable dispatch through the `AudioGenerator`
protocol witness verified correct for `_computeSamples` overrides;
`is any Generator` classification confined to `init`; helper inlining
clean; channel-alias inheritance through `extension Pan4` correctly
propagates to every subclass.
---
### Phases 142–147 — Live-compile scratch view (`LyrebirdScratchView` + `LyrebirdScratchDemo`)
Live-coding path for Lyrebird via dylib hot-swap. Replaces the dead
`swift package repl` (removed from current Swift toolchain). User writes a
Swift snippet in a `NSTextView`-backed editor, ⌘↩ shells out to `swiftc
-emit-library`, the resulting dylib is `dlopen`'d and its entry symbol
called with a pointer to the live `SynthesisEngine`. macOS-only v1 (iOS
can't shell out to swiftc).
**Why renumbered.** Originally scoped as phases 135–140 in
`memory/project_live_compile_phases.md` (planned 2026-05-12). Phases
135–141 got consumed by unrelated drive-by work (SC reference scrub,
DocC build instructions, Xcode-project scaffolder templates, denormal-
flush macro, NoteController template, Sendable-warning cleanup) before
the scratch-view work started. Renumbered here to 142–147 — same scope,
same naming, same split.
**Naming locked.**
- SwiftUI view: `LyrebirdScratchView` (lives in `Sources/LyrebirdUI/LiveCompile/`).
- Sample app: `LyrebirdScratchDemo` (under `Demos/LyrebirdScratchDemo/`).
- New SPM target: `LyrebirdLiveCompile` (`Sources/LyrebirdLiveCompile/`)
— keeps swiftc shell-out + `dlopen` surface out of the core RT
`Lyrebird` module.
- Snippet entry symbol: `lyrebird_snippet_entry` (`@_cdecl`).
**Why not the alternatives** (don't re-litigate):
- `swift package repl` — removed from current Swift toolchain.
- Xcode Playgrounds — user tested; audio did not work.
- Embedded Swift interpreter — no such thing; SwiftSyntax parses but
does not execute.
**Phase split** (each on its own branch off `main` per the standard
phase-branch workflow):
| Sub-phase | Scope |
|-----------|-------|
| 142 ✓ | `LiveCompiler` core: `swiftc -emit-library -module-name LBSnippet_<uuid> ...` shell-out, dylib write to a temp dir, `dlopen` + `dlsym(lyrebird_snippet_entry)`. No UI, no engine binding. Returns a callable function pointer + a `LoadedSnippet` handle (kept alive for the lifetime of the process — dylib unload is unsafe while live `Synth` instances reference dylib types). **Merged to main.** |
| 143 ✓ | `SnippetHarness` + `SnippetContext` + `LiveSession`: tiny Swift preamble wrapped around the user's snippet body that imports `Lyrebird`, declares `@_cdecl("lyrebird_snippet_entry")`, and exposes `engine: SynthesisEngine` (+ helpers TBD per open question 4). `LiveSession` owns the `SynthesisEngine` and tracks every `Synth` started by the current snippet so re-evaluation can `free` them. **Merged to main.** |
| 144 ✓ | Diagnostics: parse `swiftc` stderr → structured `Diagnostic` (file/line/column/severity/message). Offset the line numbers back from the harness preamble to the user's snippet coordinates so error reports point to the row the user actually typed. **Merged to main.** |
| 145 ✓ | `LyrebirdScratchView` SwiftUI (`#if os(macOS)`) in `LyrebirdUI` — `NSTextView`-backed editor, ⌘↩ compile-and-run, ⌘⇧↩ additive compile-and-run, scrollable diagnostics list, status row. **Merged to main.** Async compile + line-gutter / syntax highlighting deferred to Phase 147. |
| 146 ✓ | `LyrebirdScratchDemo` Xcode project under `Demos/`, registered in `Lyrebird.xcworkspace`. Demo `.app` cannot be sandboxed (App Sandbox blocks shell-out + `dlopen`); hardened-runtime likely needs `Disable Library Validation` entitlement for unsigned dylib loading. **Merged to main.** |
| 147 ✓ | Polish v1 — async compile (swiftc on background `Task.detached`, real `isCompiling` state, Run buttons disable while compiling), line-number gutter (`ScratchLineNumberRuler` NSRulerView subclass), snippet open/save (`NSOpenPanel`/`NSSavePanel`, ⌘O/⌘S/⌘⇧S). Syntax highlighting + multi-snippet tabs deferred to a later phase. **Merged to main.** |
**Open questions to resolve before Phase 142 starts.**
1. **Sandboxing.** Demo `.app` cannot be sandboxed. Confirm OK for
v1 (not for Mac App Store; fine for direct distribution).
2. **Hardened runtime.** `Disable Library Validation` entitlement
likely needed for `dlopen` on unsigned dylibs. Test early in 146.
3. **Re-evaluation semantics.** ⌘↩ removes the prior snippet's tracked
synths first; ⌘⇧↩ is additive. Confirm.
4. **Snippet body API surface.** Just `engine`, or also helpers like
`play(_:)` / `stop(_:)`? Lean minimal for v1.
**Non-goals (don't scope-creep).**
- Recreating the SuperCollider interpreter pattern.
- iOS support v1.
- AOT-style autocomplete / IDE-equivalent symbol resolution.
- Hot-**unload** of dylibs — types in a dylib are referenced by live
`Synth` instances. Unload = crash. Leak them by design; new snippet =
new dylib.
---
### Phases 182–190 — Pattern + Demand catalogue expansion
Expand the language-side `Pattern<T>` and RT-side `Demand*` catalogues with
SuperCollider-style data-generation and composition primitives (no event-binding
/ synth-spawning patterns — Lyrebird wires Generators directly). Plan covers
nine sequential phases. Full design + rationale: plan file
`/Users/josh/.claude/plans/let-s-plan-more-pattern-quirky-wilkinson.md`.
**Phase 182** — Pattern facade refactor + Demand* rename. ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Phase 183** — Atomic numeric Pattern sources (`series`, `geometric`,
`uniformRandom`, `brownian`, `gaussian`, `cauchy`, `beta`). ✓ shipped;
see `docs/01-completed-working-order.md` for the full writeup.
**Phase 184** — Discrete-pool Pattern sources + closure escape hatch
(`shuffle`, `nonRepeatingRandom`, `weightedRandom`, `closure`). ✓ shipped;
see `docs/01-completed-working-order.md` for the full writeup.
**Phase 185** — Length/range Pattern modifiers (`repeating`, `limit`,
`drop`, `stutter`). ✓ shipped; see `docs/01-completed-working-order.md`
for the full writeup.
**Phase 186** — Multi-pattern composition (`switching`, `concatenate`,
`roundRobin`, `tuple`, `interleave`). ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Phase 187** — Map/filter/transform Pattern catalogue (`map`, `filter`,
`reject`, and `where T == Double` numeric transforms — `accumulate`,
`difference`, `wrap`, `clip`, `round`, `smooth`). ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup. Closes the
Pattern-side of the 183-187 sweep.
**Phase 188** — Atomic numeric `Demand*` (`DemandSeries`,
`DemandGeometric`, `DemandUniformRandom`, `DemandBrownian`) built as
thin wrappers around the Phase 183 Pattern engines. ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Phase 189** — Discrete-pool `Demand*` (`DemandShuffle`,
`DemandNonRepeatingRandom`, `DemandWeightedRandom`) built as thin
wrappers around the Phase 184 Pattern engines parameterised over
`T=Double`. ✓ shipped; see `docs/01-completed-working-order.md` for
the full writeup.
**Phase 190** — Composition `Demand*` (`DemandStutter`, `DemandSwitch`,
`DemandConcatenate`) composing other `DemandGenerator` instances
directly (no Pattern-engine wrap). ✓ shipped; see
`docs/01-completed-working-order.md` for the full writeup.
**Closes the 182-190 Pattern + Demand catalogue expansion.**
---
### Longer-term — Deferred
| Phase | Title | Source ref | Complexity |
|-------|-------|-----------|-----------|
| 96b | Ableton Link Sync | 9.2 | High |
#### Phase 96b — Ableton Link *(deferred)*
Ableton Link SDK (open source, Apache 2.0) integration for peer-to-peer beat sync over
LAN/WiFi. `LyrebirdClock` follows Link session tempo and beat phase. Stub:
`docs/roadmap/ableton-link.md`. SDK vendoring effort estimate 5–8 days (asio +
Link headers, C++ SwiftPM target, abl_link FFI shim, Bonjour entitlements,
manual 2-device test bench). Phase 96a (MIDI Clock follow) and Phase 95
(Scanned Synthesis) are complete on `main`.
---
### Beat-Timeline / Time-Signature group (Phases 224–229)
Goal: let authors place notes at explicit beat positions on a part timeline and
auto-fill the rests (the `VoiceGenerator.from((1.0, Note…), (5.0, Note…))`
request), with a real time-signature model underneath (compound, complex/
additive, anacrusis, mid-piece meter changes, eventual polymeter).
Design decisions (locked with Josh):
- **One internal truth** = 0-based quarter-note beats (matches `ScoreEvent.beat`,
tuplet math, engine). All musician-friendly addressing resolves down to it.
- **`beatGrouping` is the primitive.** A `TimeSignature` carries a partition of
the numerator into beats in denominator-note units. Auto-inferred, but
explicitly overridable: `6/8` defaults compound `[3,3]` but can be made simple
`[1,1,1,1,1,1]` (slow 6/8); additive `8/8` as `[3,3,2]` gives a 3+3+2 pulse.
`isCompound` = "any group > 1". No special-casing — compound math falls out of
the grouping data.
- **Meter scope:** `Score.meterMap` is the global default; `Part.meterMap?` is an
all-or-nothing override (nil = inherit; non-nil = a *complete* replacement map).
A part can NOT patch a segment of the score map. `MeterMap` itself is segmented
`[(startBar, TimeSignature)]`.
- **Anacrusis:** `anacrusis: Fraction` (pickup length in quarters). Quarter `0.0`
= pickup start; first full barline at `anacrusis`; pickup = bar 0 (`implicit`);
bar 1 = first complete measure. Existing 1-based `TempoChange`/`Ending` measure
refs stay bar ≥ 1 (pickup excluded).
- **Overlap policy:** default traps loud + signals — throws a descriptive
`TimelineError.overlap(at:previousEndsAt:incoming:)` (catchable, also routable
to `LyrebirdMessageCenter`). Not a silent fix.
- **Polymeter:** allow in the model from Phase 224 (cheap — the placement/`flatten`
path is meter-map-driven, gets polymeter free); defer the hard *notation*
(per-part non-aligning barlines, per-part encoder measure loop) to Phase 229.
No retrofit — staged fill-in, not a rewrite.
#### Phase 224 — `TimeSignature` + `MeterMap` model ✓ *(complete — see `01-completed-working-order.md`)*
#### Phase 225 — `ScoreTimeline.fill` (quarter-beat addressing) + shared rest-fill ✓ *(complete — see `01-completed-working-order.md`)*
#### Phase 226 — `BeatPosition` (musical addressing) + meter-aware resolver ✓ *(complete — see `01-completed-working-order.md`)*
#### Phase 227 — Overlap policies + multi-voice timelines ✓ *(complete — see `01-completed-working-order.md`)*
#### Phase 228 — Homometric mid-piece meter changes (encoder) ✓ *(complete — see `01-completed-working-order.md`)*
#### Phase 228b — Parser meter round-trip + per-measure beams ✓ *(complete — see `01-completed-working-order.md`)*
#### Phase 228c — Anacrusis notation + round-trip ✓ *(complete — see `01-completed-working-order.md`)*
#### Phase 228.5 — Drop phase-number references from code/docs ✓ *(complete)*
- Swept `Phase NNN` references from all source comments, doc-comments, `.docc`
prose, `@Suite` strings, and test file/type/function names (59 files). Renamed
`Phase60ScatterCollectionTests`/`Phase57NoiseTests`/`Phase201IsolationGuardTests`.
- New CLAUDE.md hard rule **"No phase numbers in code or docs"** (under Swift
Code Style Rules → review-flagged) enforces it for code-writing + review agents
going forward. DSP term "phase" exempt.
#### Phase 229 — Polymeter notation ✓ *(complete — see `01-completed-working-order.md`)*
Per-part meter already rendered correctly once the encoder went per-part for
mid-piece meter changes (`part.meterMap ?? score.meterMap`, parts encode
independently) — so this was tests + docs + ScoreDemo material samples, not a
structural lift. **The beat-timeline / time-signature group (223–229) is
complete.**
New work beyond this group is scoped from the **Deferred / Future** and **Not
planned** lists below as demand appears.
### Longer-term — Not planned
#### Phase 96b — Ableton Link *(not planned)*
Ableton Link SDK integration for peer-to-peer beat sync over LAN/WiFi was
scoped but will not be built. MIDI Clock follow (Phase 96a, complete on `main`)
is the supported external-transport path. Revisit only if real demand appears;
the SDK-vendoring cost (C++ SwiftPM target, abl_link FFI shim, Bonjour
entitlements, 2-device test bench) is not justified otherwise.
---