bugfixes, better MusicXML support and 1.1.0
This commit is contained in:
@@ -4750,14 +4750,14 @@ needed no change — system-realtime status bytes still route through
|
||||
the `(status & 0xF0) == 0xF0 ? 0x1 : 0x2` test.
|
||||
|
||||
**Docs.** `docs/tooling/midi-clock-sync.md` is the user-facing
|
||||
guide; `docs/roadmap/ableton-link.md` stubs Phase 96b.
|
||||
guide. Phase 96b (Ableton Link) is not planned.
|
||||
|
||||
**3122 tests at completion** (was 3108 on `main` after inter-phase
|
||||
ramps; +13 follower tests + 1 `.continue` round-trip).
|
||||
|
||||
### Phase 96b — Ableton Link
|
||||
|
||||
Deferred. Stub at `docs/roadmap/ableton-link.md`.
|
||||
Not planned. MIDI Clock follow (Phase 96a) is the supported external-transport path.
|
||||
|
||||
---
|
||||
|
||||
@@ -9928,3 +9928,663 @@ which the runtime check resolves.
|
||||
|
||||
**Branch:** `phase-203-livecompile-swift6` off `main`. Standard checklist +
|
||||
`/lyrebird_review` before merge.
|
||||
|
||||
---
|
||||
|
||||
## 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 204 — Score / MusicXML demo + templates
|
||||
|
||||
Code-first starting point for authoring notated scores and exporting MusicXML.
|
||||
Three surfaces, all driven by the existing `Score` DSL + `Score+MusicXMLEncode`
|
||||
round-trip (no new core API):
|
||||
|
||||
1. **`Demos/LyrebirdScoreDemo/`** — nested SwiftPM package + `.xcodeproj`, mirrors
|
||||
`LyrebirdNRTDemo`'s offline-render model. `ScoreDemo` builds a two-part 8-bar
|
||||
`Score` exercising every DSL node (Note/Rest/Chord/Tuplet, all dynamics, all
|
||||
articulations), writes `~/Desktop/LyrebirdScoreDemo.musicxml`, round-trips it
|
||||
(`Score.fromMusicXML`), then schedules one self-freeing `ScoreVoice`
|
||||
(`OscSawtooth` + `EnvelopeGen.Control(doneAction: .freeNode)`) per `ScoreEvent`
|
||||
against an `NRTDriver` and renders `~/Desktop/LyrebirdScoreDemo.caf`. Added to
|
||||
`Lyrebird.xcworkspace`.
|
||||
2. **CLI project template** `lyrebird new <name> --template score`
|
||||
(`ProjectTemplate.score`, SPM-only) — emits a single-file NRT-render flavor of
|
||||
the demo via `mainSwiftScore(name:)`.
|
||||
3. **Xcode file template** `LyrebirdScore.xctemplate` — `func make<Name>() -> Score`
|
||||
factory (Tier 2, SortOrder 26), auto-discovered by `TemplateInstaller`.
|
||||
|
||||
Key API used (all pre-existing): `Pitch.frequency: Double?`, `ScoreEvent.isRest`,
|
||||
`Score.allEvents` / `.totalBeats`, `NoteDuration.dotted(_:)`,
|
||||
`score.toMusicXMLString()` / `.toMusicXMLData()` / `Score.fromMusicXML(data:)`.
|
||||
|
||||
Note: `Score.allEvents` excludes rests (rests only advance the flatten cursor), so
|
||||
scheduled voice count == sounding-note count.
|
||||
|
||||
Swift 6 isolation: emitted SPM `main.swift` top-level entry is main-actor-isolated
|
||||
by default, so the scaffold template schedules `@MainActor` `SynthesizerBase` voices
|
||||
and calls `@MainActor` `engine.schedule` directly from top-level with no
|
||||
`MainActor.assumeIsolated` wrapper — verified to compile + run (sibling
|
||||
`LyrebirdNRTDemo` does the same).
|
||||
|
||||
Verification: `swift test --no-parallel` 4214/4214; scaffolded `--template score`
|
||||
project built + ran end-to-end (valid MusicXML 4.0, round-trip 12→12, 5.5 s `.caf`);
|
||||
`LyrebirdScore.xctemplate` validates parse + build OK. One `/lyrebird_review` cycle:
|
||||
architecture agent's `@MainActor` "won't compile" finding rejected as empirically
|
||||
false; two magic-number findings fixed (ScoreDemo pan/amp constants). Pre-existing
|
||||
unrelated `LyrebirdTask.xctemplate` validation failure flagged separately.
|
||||
|
||||
---
|
||||
|
||||
### Pitch / Scale Theory Toolkit (Phases T1–T6)
|
||||
|
||||
A spelling-aware music-theory layer: intervals, scales/modes, pitch collections
|
||||
(cells / 12-tone rows), and diatonic vs chromatic transposition — all preserving
|
||||
**correct enharmonic spelling** (transposing `A` up an augmented 2nd gives `B♯`,
|
||||
NOT `C♮`).
|
||||
|
||||
**Foundation already in place** (do not re-implement): `Letter` (C–B,
|
||||
`rootSemitone`, `CaseIterable`), `Accidental` (9-step grid double-flat…double-
|
||||
sharp + quarter-tones, `semitones: Double`), `NoteName(Letter, Accidental)`
|
||||
(spelling-preserving, `semitones`, full static-let factories `.cSharp`/`.eFlat`/…),
|
||||
`Pitch` (`.midi`/`.freq`/`.named(NoteName, Int)`, `midiNote`, `frequency`). The
|
||||
letter carries the octave; the accidental never changes the octave (`C♭4` is
|
||||
octave 4). This is what makes correct spelling possible.
|
||||
|
||||
**Layout:** new `Sources/Lyrebird/Score/Theory/` subfolder, one public type per
|
||||
file. All pure value types — `Sendable`, `Hashable`, explicit type annotations,
|
||||
no force unwraps, no magic numbers (interval tables as named constants). Pure
|
||||
language-side; no RT/engine involvement. Everything outputs `NoteName`/`Pitch`
|
||||
so results drop straight into the Score DSL (`Note(.named(...))`). Tests: one
|
||||
`@Suite` per type; encode every worked example below; add a MusicXML round-trip
|
||||
test on a transposed phrase to confirm spellings survive export.
|
||||
|
||||
Dependency order: **T1 → T2 → T3 → (T4, T5, T6)**.
|
||||
|
||||
---
|
||||
|
||||
**Phase T1 — `Interval` + spelling-correct transposition** (the keystone; covers
|
||||
items b and f). Everything else spells through this.
|
||||
|
||||
- `Theory/Interval.swift`: `struct Interval` = `number: Int` (diatonic interval
|
||||
number ≥ 1; 1 = unison, 2 = second, … 8 = octave, 9 = ninth — compound allowed)
|
||||
+ `quality: IntervalQuality`. Computed `diatonicSteps = number - 1` (letter
|
||||
distance) and `semitones: Int` (derived from number+quality via the
|
||||
perfect/major reference table). Validity rule: perfect qualities only on
|
||||
unison/4th/5th/octave; major/minor only on 2nd/3rd/6th/7th; diminished/
|
||||
augmented on any. Static conveniences: `.unison`, `.minorSecond`,
|
||||
`.majorSecond`, `.augmentedSecond`, `.minorThird`, `.majorThird`,
|
||||
`.perfectFourth`, `.augmentedFourth`, `.diminishedFifth`, `.perfectFifth`,
|
||||
`.minorSixth`, `.majorSixth`, `.minorSeventh`, `.majorSeventh`, `.octave`, …
|
||||
Plus `static func between(_ a: NoteName, _ b: NoteName) -> Interval` (analyze
|
||||
the spelled interval between two names — needed by T6).
|
||||
- `Theory/IntervalQuality.swift`: `.diminished(Int)` / `.minor` / `.perfect` /
|
||||
`.major` / `.augmented(Int)` (the `Int` = degree, for doubly-dim/aug).
|
||||
- `Theory/IntervalDirection.swift`: `.up` / `.down`.
|
||||
- Transposition (`Theory/NoteName+Transpose.swift`, `Pitch+Transpose.swift`):
|
||||
- `NoteName.transposed(by: Interval, _ dir: IntervalDirection = .up) -> NoteName`.
|
||||
**Algorithm**: advance the letter by ±`diatonicSteps` (mod 7); compute the
|
||||
natural semitone gap to the new letter; pick the accidental that makes the
|
||||
actual semitone distance equal `interval.semitones`. Out-of-range result
|
||||
(beyond double-sharp/flat) → decide: `throws` or return the best
|
||||
representable enharmonic (document).
|
||||
- `Pitch.transposed(by:_:) -> Pitch`: for `.named`, transpose the `NoteName`
|
||||
and adjust the octave by the letter wrap (+ compound octaves); for
|
||||
`.midi`/`.freq`, shift by `interval.semitones` numerically (spelling lost —
|
||||
document).
|
||||
- **Tests (worked examples — must pass):** A +aug2↑ = B♯ (not C); C +M3↑ = E,
|
||||
E +M3↑ = G♯; C +m3↑ = E♭; B +P4↑ = E; F♯ +m3↓ = D♯; C♭ +M2↑ = D♭.
|
||||
|
||||
---
|
||||
|
||||
**Phase T2 — `Scale`** (items a, a1).
|
||||
|
||||
- `Theory/Scale.swift`: `struct Scale` = `tonic: NoteName` + `degrees: [NoteName]`
|
||||
(spelled pitch-classes, `degrees[0] == tonic`, one entry per scale degree).
|
||||
- `init(tonic:intervals: [Interval])` — degrees = `tonic.transposed(by:)` each
|
||||
interval (designated; guarantees correct per-degree spelling).
|
||||
- `init(tonic:degrees: [NoteName])` and `init(tonic:pitches: [Pitch])` — treat
|
||||
an arbitrary pitch set as a scale (item a).
|
||||
- Queries: `contains(_:) -> Bool`; `degree(of: NoteName) -> ScaleDegree?`
|
||||
(`ScaleDegree = (index: Int, alteration: Int)` so chromatic non-scale pitches
|
||||
map as nearest degree + chromatic alteration); `noteName(atDegree: Int)
|
||||
-> NoteName` (wraps mod count); `pitch(atDegree:octave:) -> Pitch`.
|
||||
- `Theory/ScaleDegree.swift`: `struct ScaleDegree { index: Int; alteration: Int }`.
|
||||
- Convenience factories (item a1), each from a tonic + interval pattern:
|
||||
modes `.major`/`.ionian`, `.dorian`, `.phrygian`, `.lydian`, `.mixolydian`,
|
||||
`.aeolian`/`.naturalMinor`, `.locrian`; `.harmonicMinor`, `.melodicMinor`;
|
||||
symmetric `.wholeTone`, `.chromatic`, `.octatonicHalfWhole`,
|
||||
`.octatonicWholeHalf`, `.augmentedScale`; `.majorPentatonic`,
|
||||
`.minorPentatonic`, `.blues`.
|
||||
- **Spelling note:** 7-note diatonic scales use 7 distinct letters (one per
|
||||
degree) — the interval pattern guarantees the letter progression (D major →
|
||||
D E F♯ G A B C♯). Symmetric scales (6/8/12 notes) have no one-letter-per-degree
|
||||
mapping; each factory must define a **canonical spelling** per tonic (e.g.
|
||||
whole-tone C = C D E F♯ G♯ A♯; document the sharps-up / flats-down choice).
|
||||
|
||||
---
|
||||
|
||||
**Phase T3 — `PitchCollection`** (item c).
|
||||
|
||||
- `Theory/PitchCollection.swift`: `struct PitchCollection` = `pitches: [Pitch]`
|
||||
(ordered — melodic cell, atonal cell, or 12-tone row), optional
|
||||
`referenceScale: Scale?` (used by T6).
|
||||
- Spelled ops: `retrograde`; `transposedChromatic(by: Interval, _ dir:)` (item f,
|
||||
via T1 on every pitch); `inverted(around: Pitch)` (pitch inversion preserving
|
||||
spelling); `octaveReduced` (to pitch-classes).
|
||||
- 12-tone row ops (when 12 distinct pitch-classes): `prime`, `inversion (I)`,
|
||||
`retrograde (R)`, `retrogradeInversion (RI)`, `transposed(_ n)` (Tn),
|
||||
`transposedInversion(_ n)` (TnI), `matrix() -> [[NoteName]]` (12×12) — spelling
|
||||
via T1.
|
||||
- Optional atonal set-theory helpers (pitch-class integers, spelling-agnostic):
|
||||
normal form, prime form, interval-class vector — keep separate from the spelled
|
||||
ops (could be a T3b sub-phase).
|
||||
|
||||
---
|
||||
|
||||
**Phase T4 — Diatonic (modal) transposition** (item e). Transpose a collection by
|
||||
SCALE DEGREES within a scale, staying in the scale, correct spelling.
|
||||
|
||||
- `Scale.transposeDiatonic(_ c: PitchCollection, byDegrees n: Int)
|
||||
-> PitchCollection`: each pitch → `degree(of:)`, `index += n`, wrap octave,
|
||||
re-spell via `noteName(atDegree:)`; carry chromatic alteration through for
|
||||
non-scale pitches.
|
||||
- **Test:** C-D-E up a third (n = +2) in C major → **E-F-G** (NOT E-F♯-G♯). Plus
|
||||
down + octave-wrap cases.
|
||||
|
||||
---
|
||||
|
||||
**Phase T5 — Chromatic transposition of collections** (item f). Mostly falls out
|
||||
of T1 + T3.
|
||||
|
||||
- `PitchCollection.transposedChromatic(by: Interval, _ dir:)` applies the
|
||||
spelling-correct interval to every pitch.
|
||||
- **Test:** C-D-E up a major third → **E-F♯-G♯**. Pair it with the T4 test on the
|
||||
same input to lock the modal-vs-chromatic distinction. (May fold into T3; kept
|
||||
explicit to pin the contrast.)
|
||||
|
||||
---
|
||||
|
||||
**Phase T6 — Scale-to-scale mapping** (item d). Map a collection from an original
|
||||
scale to a target scale by degree, correct spelling.
|
||||
|
||||
- `PitchCollection.mapped(from original: Scale, to target: Scale)
|
||||
-> PitchCollection`: each pitch → `original.degree(of:)` →
|
||||
`target.noteName(atDegree:)`, carrying alteration + octave.
|
||||
- **Test:** C-E-G assigned to C major → mapped to D major = **D-F♯-A**; mapped to
|
||||
E♭ major = **E♭-G-B♭**.
|
||||
- Decide + document degree-count-mismatch policy (e.g. pentatonic → heptatonic):
|
||||
map-by-index with wrap, or error.
|
||||
|
||||
**Open decisions to settle during implementation:** out-of-range spelling
|
||||
(beyond 𝄫/𝄪); compound-interval octave bookkeeping; quarter-tone interaction
|
||||
(intervals are 12-TET — define or exclude quarter-tone accidentals in
|
||||
transposition); degree-count mismatch in T6.
|
||||
|
||||
---
|
||||
|
||||
### Phase 222 — `LyrebirdPaths` filesystem conveniences
|
||||
|
||||
New `LyrebirdPaths` namespace (`Sources/Lyrebird/Utilities/`, new subfolder) of
|
||||
filesystem-location helpers, motivated by the `score` template hardcoding
|
||||
`URL(fileURLWithPath: "score.musicxml")` — which drops files in the launch
|
||||
directory (DerivedData under Xcode), not the project.
|
||||
|
||||
- `projectRoot(from:marker:) -> URL?` — walks up from the **caller's** source
|
||||
file (default-argument `#filePath` expands at the call site, not in the
|
||||
library) to the directory containing `Package.swift`. `marker` matches by
|
||||
exact filename, or — when dot-prefixed (`.xcodeproj`) — by path extension
|
||||
against directory contents, so it finds `MyApp.xcodeproj` (private
|
||||
`directory(_:contains:)` helper). Dev-time only — path reflects the build
|
||||
machine; docs steer shipped apps to `documents` / `applicationSupport`.
|
||||
- Sandbox-standard accessors: `documents` / `applicationSupport` / `caches`
|
||||
(via private `searchPath`, fallback `temporary`), `temporary` / `home` /
|
||||
`currentWorkingDirectory`, plus macOS-only `desktop -> URL?`.
|
||||
- `score` template generator (`ProjectScaffolder.mainSwiftScore`) now writes
|
||||
both outputs via `projectRoot() ?? currentWorkingDirectory`.
|
||||
- Docs: new **File output locations** section in `INSTALLATION_AND_USAGE.md`
|
||||
(same session also added the `score` template row, a Score-features section,
|
||||
and `LyrebirdScoreDemo` to the demo table); `Utilities/` added to the
|
||||
CLAUDE.md folder list.
|
||||
- Tests: `LyrebirdPathsTests` (6 cases). Full suite `swift test --no-parallel`
|
||||
4516/4516.
|
||||
|
||||
One `/lyrebird_review` cycle — clean, no blocking. The caveman sweep's one risk
|
||||
(docs said pass `.xcodeproj` but matching was exact-name) fixed by adding the
|
||||
extension-suffix match + a 6th test. Number bumped from 221 (taken by the
|
||||
mid-voice clef-changes phase).
|
||||
|
||||
---
|
||||
|
||||
## Phase 224 — `TimeSignature` + `MeterMap` model
|
||||
|
||||
Foundation for the beat-timeline group (Phases 224–229). **Model-only — no
|
||||
notation behavior change.** Full suite 4544/4544 (+18).
|
||||
|
||||
- New `TimeSignature` value type: `numerator`, `denominator`, `beatGrouping: [Int]`
|
||||
(sum == numerator), derived `measureQuarters: Fraction`, `isCompound`,
|
||||
`pulsesPerBar`, `tuple`. Constructors: `(n, d)` auto-grouping (compound default
|
||||
when `d ∈ {8,16}`, `n % 3 == 0`, `n > 3`), `(n, d, grouping:)` explicit override
|
||||
(slow-6/8-simple `[1,1,1,1,1,1]` and additive 3+3+2 `[3,3,2]`), `(_ tuple:)`
|
||||
back-compat. Named statics (`.fourFour`, `.threeFour`, `.twoFour`, `.cutTime`,
|
||||
`.sixEightCompound`, `.sixEightSimple`, `.nineEight`, `.twelveEight`).
|
||||
- New `MeterMap` type: segmented `[Segment(startBar:_:)]` (sorted, first must be
|
||||
bar 1, unique startBars) + `anacrusis: Fraction` (pickup quarters). `timeSignature(atBar:)`
|
||||
lookup (last segment with `startBar <= bar`; pickup bar 0 → initial), `initial`,
|
||||
`isConstant`, single-constant convenience init.
|
||||
- Wired `Score.meterMap` (defaults to single-segment map from `timeSignature`;
|
||||
explicit map drives the back-compat tuple from `initial`) + `Part.meterMap?`
|
||||
(all-or-nothing polymeter override, nil = inherit). **Model only** — encoder
|
||||
still renders against the bar-1 signature.
|
||||
- Refactored the encoder's inline `Fraction(num: ts.0*4, den: ts.1)` to
|
||||
`TimeSignature(ts).measureQuarters` (bit-identical output).
|
||||
- Design decisions (locked with Josh): grouping is the primitive (compound NOT
|
||||
auto-only — explicitly overridable; complex/additive expressible); meter scope
|
||||
= score-global default + all-or-nothing part override; anacrusis = bar 0
|
||||
implicit; polymeter allowed in the model now, notation deferred to Phase 229.
|
||||
- One `/lyrebird_review` cycle: 3 blocking fixed (ScorePart.init `/// - Parameters:`
|
||||
block; MeterMap `anacrusis >= .zero`; `timeSignature(atBar:)` early-return) + 1
|
||||
non-blocking (Score tuple precondition guarded `if meterMap == nil`). Caveman LGTM.
|
||||
- Tests: `TimeSignatureTests` (13), `MeterMapTests` (5).
|
||||
|
||||
---
|
||||
|
||||
## Phase 225 — `ScoreTimeline.fill` + shared rest-fill helper
|
||||
|
||||
The core beat-timeline feature: place `ScoreElement`s at explicit 0-based
|
||||
quarter-note beats; auto-fill the rests. Full suite 4558/4558 (+14).
|
||||
|
||||
- `ScoreTimeline` (caseless `public enum`): `fill([(beat:Double, element:ScoreElement)])`,
|
||||
variadic `from(...)`, dict `fill([Double: ScoreElement])` — all `throws`.
|
||||
0-based quarter addressing (beat 0.0 = part start). Sorts (stable); leading rest
|
||||
when the first element starts after 0. Usage: `let lead = try ScoreTimeline.from(...)`
|
||||
then `Part("lead") { lead }` (builders are non-throwing).
|
||||
- `ScoreTimelineError`: `.overlap(atBeat:previousEndsAtBeat:elementDescription:)`
|
||||
thrown when an element starts before the running cursor (monophonic per call —
|
||||
loud signal, not a silent fix) + `.negativeBeat`.
|
||||
- Shared generic `fillRests<P: Comparable & AdditiveArithmetic>(sorted:duration:makeRest:onOverlap:transform:)`
|
||||
(gap → rest, `< cursor` → onOverlap, `==` → no rest, cursor `= position + duration`).
|
||||
`scoreElementBeatSpan` (Fraction; recursive tuplet `× normal/actual`, wedge
|
||||
transparent, voice/grace/clefChange zero). `noteDurationFraction` / `fractionFromBeats`.
|
||||
- **Dedup**: routed all THREE gap-fill sites through `fillRests` — `ScoreTimeline`
|
||||
(Fraction, throwing overlap), `MusicXMLParser` voice reconstruction (Fraction,
|
||||
no-op overlap, `zeroVoice` transform), `MIDIFile+Score` event→element (P=Double,
|
||||
preserves `.beats` representation + lossy-monophonic SMF behavior). `Fraction`
|
||||
gained `AdditiveArithmetic` (+ `-=`) so the generic spans both cursors with no
|
||||
cross-conversion.
|
||||
- Consolidated the triplicated `2^20` denominator into `Fraction.beatApproxDenominator`.
|
||||
- One `/lyrebird_review` cycle: 2 blocking fixed (tuplet-advance test; constant
|
||||
consolidation) + 2 non-blocking (DocC link; wedge/zero-span tests). Caveman LGTM.
|
||||
Parser round-trip + SMF bridge 281/281 unchanged (refactor behavior-identical).
|
||||
- Tests: `ScoreTimelineTests` (14).
|
||||
|
||||
---
|
||||
|
||||
## Phase 226 — `BeatPosition` musical addressing + meter-aware resolver
|
||||
|
||||
Musician-friendly positions resolved to absolute quarter beats via a `MeterMap`.
|
||||
Addressing only — anacrusis *notation* deferred to Phase 228. Full suite 4579/4579.
|
||||
|
||||
- `BeatPosition` (`public struct` + private `Kind` enum + static factory funcs —
|
||||
`.bar(_:beat:)` and `.bar(_:division:)` differ only by label, which enum cases
|
||||
can't, so static funcs): `.quarters(Double)`/`.quarters(Fraction)` (0-based,
|
||||
meter-free, Fraction exact), `.beat(Double)` (flat 1-based felt beat, continuous
|
||||
across bars, constant-initial-meter + anacrusis-free), `.bar(Int, beat:)` (felt
|
||||
beat, meter-aware), `.bar(Int, division:)` (denominator-note granular).
|
||||
`resolve(in: MeterMap) -> Fraction` honors anacrusis (bar 0 = pickup) + mid-piece
|
||||
meter accumulation. Out-of-range felt beat traps.
|
||||
- **`beat` = the conducted/felt pulse** (Josh): 4/4 → quarter, compound 6/8 → dotted-
|
||||
quarter, additive 3+3+2 → [dotted-q, dotted-q, q]. `beat 1` = downbeat in every
|
||||
meter. The finer notated note-value (eighth in 6/8) is the granular `division`.
|
||||
- **Naming alignment**: two layers of "beat" — absolute timeline = quarter
|
||||
(`ScoreEvent.beat`, `bpm`, `NoteDuration`, untouched) vs meter/addressing = felt
|
||||
beat. Aligned the meter layer: `pulsesPerBar`→`beatsPerBar`, `pulseOnsetsQuarters`
|
||||
→`beatOnsetsQuarters`, `pulseLengthsQuarters`→`beatLengthsQuarters`,
|
||||
`beatUnitQuarters`→`divisionQuarters` (the denominator-note unit). Cross-layer
|
||||
overload accepted; bridge documented at `resolve()`.
|
||||
- `MeterMap.barStartQuarters(_:)`; `TimeSignature.divisionQuarters` / `beatOnsetsQuarters`
|
||||
/ `beatLengthsQuarters`. `ScoreTimeline` meter-aware overloads `fill([(BeatPosition,
|
||||
element)], meter:)` + `from(..., meter: = .fourFour)` via shared `fillResolved` core.
|
||||
- One `/lyrebird_review` cycle: one blocking — out-of-range felt beat silently
|
||||
misplaced → `precondition` trap (consistent with Tuplet/Voice/MeterMap). Caveman LGTM.
|
||||
- Tests: `BeatPositionTests` (19) + 4 `ScoreTimeline` meter overload tests.
|
||||
|
||||
---
|
||||
|
||||
## Phase 227 — `ScoreTimeline` overlap policies + multi-voice timelines
|
||||
|
||||
Extends `ScoreTimeline` beyond single-voice-trap. Full suite 4586/4586.
|
||||
|
||||
- `ScoreTimelineOverlap` (`public enum`): `.trap` (default — throw) / `.truncatePrevious`
|
||||
(shorten the previous note/chord/rest to end at the overlapping element's start;
|
||||
tuplet/voice/wedge/grace/clef and same-start throw). Added as `overlap:` to every
|
||||
single-voice `fill`/`from`/dict overload (Double + BeatPosition).
|
||||
- `fillVoices([(beat/BeatPosition, voice, element)])` — explicit voice numbers; each
|
||||
voice filled independently (intra-voice overlap traps), wrapped in `.voice(v, …)`
|
||||
ascending → multi-voice `Part`. `voice < 1` throws `ScoreTimelineError.invalidVoice`.
|
||||
- `fillAutoVoiced([(beat/BeatPosition, element)])` — greedy first-fit overlap
|
||||
distribution into voices 1…N (the `.toNewVoice` behavior); non-overlapping → one
|
||||
`.voice(1, …)`.
|
||||
- Private cores `fillCore(_:overlap:)` / `fillVoicesCore` / `autoVoiceCore` + shared
|
||||
`stableSorted` / `absoluteItems` / `resolvedItems` / `truncateOverlaps` /
|
||||
`withTruncatedDuration` (rebuilds note/chord/rest preserving all fields). Public
|
||||
overloads resolve once to `[(Fraction, element)]` then funnel through the cores.
|
||||
- One `/lyrebird_review` cycle: 2 blocking — `voice<1` precondition→throw
|
||||
(`invalidVoice`); missing BeatPosition-overload tests added. Caveman LGTM (chained
|
||||
truncation, field preservation, greedy auto-voice, strict-`<` consistency verified).
|
||||
- Tests: +7 `ScoreTimelineTests` (28 total).
|
||||
|
||||
---
|
||||
|
||||
## Phase 228 — Homometric mid-piece meter changes (encoder)
|
||||
|
||||
MusicXML encoder consumes `score.meterMap` (per-part `part.meterMap ?? score.meterMap`)
|
||||
instead of a single timeSignature tuple. **Constant-meter output byte-identical.**
|
||||
ENCODER-ONLY — parser round-trip + anacrusis deferred to 228b. Full suite 4595/4595.
|
||||
|
||||
- `encodePart` / `encodeVoiceSequence` / `openMeasure`: `timeSignature` tuple param
|
||||
replaced by `meterMap: MeterMap`.
|
||||
- Per-measure capacity: `remaining` resets to `meterMap.timeSignature(atBar: N).measureQuarters`
|
||||
in both the multi-voice loop (`thisMeasureCapacity`) and `encodeVoiceSequence`
|
||||
(recompute after `measureIndex += 1`). Dependent computations (wholeMeasureRest,
|
||||
pad-rest, `<backup>` divisions) use the per-bar value.
|
||||
- `openMeasure` emits `<time>` at measure 1 and at any later bar where
|
||||
`timeSignature(atBar:N) != timeSignature(atBar:N-1)` — a bare `<attributes><time>…</time></attributes>`.
|
||||
- `measureCount(atoms:meterMap:)` walks bars subtracting variable capacities.
|
||||
- Byte-identical guarantee for single-segment maps verified provably by both review agents.
|
||||
- One `/lyrebird_review` cycle: NO BLOCKING (both LGTM). Implemented by `lyrebird_language_agent`,
|
||||
verified by tests + review.
|
||||
- Known limitations → 228b: parser still first-`<time>`-wins (lossy round-trip),
|
||||
anacrusis ignored, `annotateBeams` uses bar-1 capacity for all bars.
|
||||
- Tests: `MusicXMLMeterChangeTests` (6).
|
||||
|
||||
---
|
||||
|
||||
## Phase 228b — Parser meter round-trip + per-measure beams
|
||||
|
||||
Closes the Phase 228 lossy round-trip for mid-piece meter changes. Full suite 4600/4600.
|
||||
|
||||
- Parser (`MusicXMLParser`): reads EVERY `<time>` from the first part (per-block
|
||||
`pendingTimeBeatCount`/`pendingTimeBeatType` accumulators, committed on `</time>`
|
||||
to `parsedMeterByMeasure[measure]` first-wins, `isFirstPart`-gated). `parsedScore()`
|
||||
builds a `MeterMap` (sort by bar, guarantee a bar-1 segment, dedupe consecutive
|
||||
equal signatures), passed to both `Score` constructions. First `<time>` still sets
|
||||
the back-compat tuple. Single `<time>` → single-segment map → byte-identical model.
|
||||
- Encoder (`annotateBeams(atoms:meterMap:)`): bar counter resets `tempRemaining` to
|
||||
`meterMap.timeSignature(atBar: bar).measureQuarters` at each barline. Constant-meter
|
||||
beams byte-identical.
|
||||
- Caveat (documented + tested): MusicXML standard `<time>` carries no beat grouping,
|
||||
so round-trip preserves num/den but re-infers the default grouping (6/8-simple → [3,3]).
|
||||
- One `/lyrebird_review` cycle: NO BLOCKING (both LGTM) — byte-identity, MeterMap-build
|
||||
precondition safety, no off-by-one, grouping-caveat-documented all verified.
|
||||
- Tests: `firstTimeSignatureWinsOnMultiTimeDocument` → `midPieceTimeSignatureParsesIntoMeterMap`;
|
||||
new `MusicXMLMeterRoundTripTests` (5).
|
||||
|
||||
---
|
||||
|
||||
## Phase 228c — Anacrusis (pickup) notation + round-trip
|
||||
|
||||
Encoder emits the pickup as `<measure number="0" implicit="yes">` (capacity =
|
||||
`meterMap.anacrusis`); full bars stay 1-based. No-anacrusis output byte-identical.
|
||||
Full suite 4611/4611.
|
||||
|
||||
- `measureCapacity(forMeasure:meterMap:)` (measure 0 → anacrusis, n≥1 → per-bar);
|
||||
`measureCount` subtracts anacrusis before the full-bar walk (pickup-only → 0).
|
||||
- `openMeasure` gains `implicit: Bool`; else-branch `<time>`-on-change gains a
|
||||
`prevBar >= 1` guard (bar 1 after a pickup doesn't re-emit the initial `<time>`).
|
||||
- Both measure loops prepend measure 0; `annotateBeams` starts at bar 0 (pickup
|
||||
window) when `anacrusis > 0` so the full bar after resets to beat 0.
|
||||
- Parser reads `<measure implicit="yes">`, pre-decrements the counter so the pickup
|
||||
is measure 0 (full bars 1..N, existing 1-based maps intact), and recovers
|
||||
`anacrusis = Fraction(pickupCursorDivisions, divisions)`. The pickup `<time>`
|
||||
maps to MeterMap key 1 (no bar-0 segment → no precondition trap).
|
||||
- One `/lyrebird_review` cycle: 2 blocking (beam pickup-window accounting + a
|
||||
missing pickup-beaming test) + 1 non-blocking (doc comment) all fixed. Both LGTM.
|
||||
- Tests: `MusicXMLAnacrusisTests` (11).
|
||||
|
||||
The meter-notation layer (mid-piece changes + anacrusis) is complete except
|
||||
polymeter; per-part barlines already work via `part.meterMap ?? score.meterMap`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 229 — Polymeter notation
|
||||
|
||||
Per-part meter maps already rendered correctly (the encoder went per-part for
|
||||
mid-piece meter changes: `part.meterMap ?? score.meterMap`, parts encode
|
||||
independently in `score-partwise`), so this was tests + docs + demo, not a
|
||||
structural lift. **Closes the beat-timeline / time-signature group (223–229).**
|
||||
Full suite 4615/4615; ScoreDemo xcodebuild SUCCEEDED.
|
||||
|
||||
- `MusicXMLPolymeterTests` (4): each part uses its own meter + bar count; no
|
||||
cross-part `<time>` leak; per-part mid-piece meter change; per-part anacrusis.
|
||||
- ScoreSystem.docc: new "Meter and time signatures" + "Polymeter" + "Beat
|
||||
timelines" section (the 224–229 group was previously undocumented there).
|
||||
- Caveats documented: score-level repeats/tempo/key are measure-indexed (align by
|
||||
measure number, not absolute beat under polymeter); round-trip reads meter
|
||||
score-globally (first part), so per-part overrides are export-faithful but do
|
||||
not survive `fromMusicXML`.
|
||||
- Corrected stale "later phase" doc-comments on `Score`/`ScorePart`/`MeterMap`.
|
||||
- ScoreDemo: `timeline` (ScoreTimeline + BeatPosition), `autovoice`
|
||||
(fillAutoVoiced), `polymeter` (own 3/4 MeterMap) parts + a makeScore() menu of
|
||||
all material-creation approaches.
|
||||
- One `/lyrebird_review` cycle: 1 blocking (stale `MeterMap` doc-comment) + caveman
|
||||
LGTM; all docc claims + caveats verified against code.
|
||||
|
||||
### Beat-timeline / time-signature group (223–229) — summary
|
||||
|
||||
223 `Generate`/`PatternNotes` algorithmic generators · 224 `TimeSignature`+`MeterMap`
|
||||
model · 225 `ScoreTimeline.fill` + shared `fillRests` · 226 `BeatPosition` musical
|
||||
addressing (`beat` = felt pulse) · 227 overlap policies + multi-voice · 228 mid-piece
|
||||
meter-change encoder · 228b parser meter round-trip · 228c anacrusis · 228.5 phase-ref
|
||||
cleanup + CLAUDE.md rule · 229 polymeter. The Score system now places notes at
|
||||
explicit/musical beats with rest auto-fill, addresses beats across simple/compound/
|
||||
additive meters, handles overlaps + multi-voice, and renders mid-piece meter changes,
|
||||
anacrusis, and polymeter — all MusicXML-export-faithful.
|
||||
|
||||
Reference in New Issue
Block a user