v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -11088,3 +11088,177 @@ Swept what the guards could not see. Each item below was measured, not assumed.
|
||||
rot that no API change caused (`theory.md`'s `.freeEnclosing` was already dead — that needed
|
||||
the phase 238 sweep), and for short common member names the candidate list is long enough that
|
||||
the reviewer must qualify by owning type. It narrows where to look; it does not decide.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-1 — Re-eval readiness signal (ReevalState)
|
||||
|
||||
First step of the LiveCompile / Scratch improvement group (LC-1…LC-8; roadmap in `docs/00-working-order.md`). Lives entirely in the macOS-only `LiveCompile/` sub-package — host-side tooling, nothing on the RT audio thread.
|
||||
|
||||
**The signal.** New `public enum ReevalState` (`LiveCompile/Sources/LyrebirdLiveCompileUI/ReevalState.swift`): `.empty` / `.clean` / `.dirty` / `.compiling` / `.failed(diagnosticCount:)`, plus `canEvaluate: Bool` (false only for `.empty` / `.compiling`). Answers "can I re-evaluate, and would it change anything?" — distinct from the free-text `statusMessage`.
|
||||
|
||||
**Model wiring** (`LyrebirdScratchModel`): `@Published private(set) var reevalState`; `lastEvaluatedText` baseline captured on each successful run. `text.didSet` recomputes to `.dirty`/`.empty`/`.clean` on edit (no-op while compiling — the run owns the state until it resolves). `run(additive:)` drives `.dirty` → `.compiling` → `.clean` (or `.dirty` if the buffer was edited mid-compile) / `.failed`. `clearTracked()` and `load(from:)` drop the baseline (nothing the buffer produced is still playing) so the buffer reads `.dirty` again. `didSet` correctly does not fire for the `init` assignment, so `reevalState` is seeded explicitly in `init`.
|
||||
|
||||
**UI** (`LyrebirdScratchView`): a colored dot + label + tooltip in the status bar bound to `reevalState`. `LyrebirdScratchMenuController` conforms to `NSMenuItemValidation` and disables the Run / Run Additive commands when `canEvaluate` is false (compiling or empty) — the readiness signal drives the actual UI gating. Corrected the stale "v1 synchronous, freezes UI" claim in `LiveCoding.md` (the off-main `compileAndRunAsync` path already ships) and the false "Run buttons disable" doc (no buttons existed; runs are menu-driven) in both `LiveCoding.md` and the view docstring; documented the readiness signal.
|
||||
|
||||
**Compile-env fix (folded in).** `LiveSession.makeSwiftcArgs` only discovered Clang module maps at Xcode's `GeneratedModuleMaps` location, so a snippet's `import LyrebirdSynth` failed with `missing required module 'LyrebirdC'` under a plain `swift build` / `swift test` layout (the C target's map lives at `<buildDir>/<Target>.build/module.modulemap`). New `discoverSPMModuleMaps` surfaces that location (umbrella-header path is absolute, so the map alone resolves the module). Fixed the 12 compile-round-trip tests that were red under bare `swift test` and makes live-compiled snippets work outside Xcode.
|
||||
|
||||
**Tests:** LiveCompile sub-package 47/47 (`swift test --no-parallel`). 3 `ReevalState` enum + 9 `LyrebirdScratchModel` transition + 1 `discoverSPMModuleMaps` fixture test. Main package unaffected (5497/5497).
|
||||
|
||||
**Review:** two agents (`lyrebird_review_agent` + caveman sweep), no RT/correctness blockers (host tooling). Findings resolved: named the badge-spacing constant (no magic numbers); wired real menu-item gating to make the doc claim true; tightened the run-outcome tests to assert `.clean` directly once the module-map fix made compiles reliable; added the `discoverSPMModuleMaps` unit test.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-2 — Bare-graph play ergonomics (ClosureSynthesizer)
|
||||
|
||||
Second step of the LiveCompile / Scratch group (roadmap in `docs/00-working-order.md`). Time-to-first-sound: play a generator graph without declaring a `SynthesizerBase` subclass and overriding `build()`.
|
||||
|
||||
**Core type.** New `public final class ClosureSynthesizer: SynthesizerBase` (`Sources/Lyrebird/Synthesizer/ClosureSynthesizer.swift`) — supplies its output graph from an `@escaping () -> any ValidGeneratorInput` closure instead of a `build()` override. The closure runs inside `build()`, once per instance, on the main thread at `engine.add` time (`rebuildGraph()` → `build()`; `evaluate()` never re-runs it). A multi-channel source fans across consecutive buses from `bus` (default `0`), exactly like `output(bus:source:)`. No `@LiveParam` slots — reach for a named subclass once a voice needs live-controllable parameters. Reusable everywhere (demos, tests, one-off voices), not just scratch:
|
||||
|
||||
```swift
|
||||
try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
|
||||
```
|
||||
|
||||
**Snippet surface.** `SnippetContext` gains `play(bus:_:)` — a `@MainActor` forwarder wrapping the closure in a `ClosureSynthesizer` and routing through the existing `play(_:)` so it is tracked for cleanup on the next non-additive re-evaluation. Scratch `defaultPlaceholder` rewritten to lead with the one-liner (`context.play { Pan2(input: OscSin.Audio(freq: 440, mul: 0.15), pan: 0) }`) — no subclass boilerplate.
|
||||
|
||||
**Docs:** `docs/protocols/synthesizer.md` gains a "ClosureSynthesizer — a graph without a subclass" section (bus fan-out, once-per-`build()` execution, graph-copy-per-instance guidance).
|
||||
|
||||
**Tests:** 5 core (`ClosureSynthesizerTests` — bus-zero write, `bus:` selection, closure-runs-once-per-instance-at-add, bare-oscillator produces audio, multi-channel fan-out) + 1 LiveCompile (`closurePlayAddsAndTracksBareGraph`, round-trips the `play { }` form through the real swiftc pipeline). Main package 5502/5502; LiveCompile sub-package 48/48. Guards green: `check-swift6-consumer.sh` (zero-annotation consumer guarantee holds despite the new public subclass), `check-docc.sh` (0 warnings), `check-doc-snippets.sh` (543).
|
||||
|
||||
**Review:** two agents, no blocking findings (host/non-RT + a pure `SynthesizerBase` subclass); caveman sweep LGTM. The only `check-doc-impact.sh` "no doc reference" entry was `ClosureSynthesizer.outputBus`, a `private let` — internal, no doc obligation.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-3 — Named slots (Pdef-style hot-swap)
|
||||
|
||||
Third step of the LiveCompile / Scratch group (roadmap in `docs/00-working-order.md`). Entirely in the macOS-only `LiveCompile/` sub-package — no core `Lyrebird` module changes; nothing on the RT audio thread.
|
||||
|
||||
**The idiom.** `context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }` installs a voice under a name. Re-running that slot definition **replaces just that voice in place** — the new voice starts before the old is removed (brief overlap, no gap) — while every other slot keeps playing. Unlike anonymous `context.play`, a slotted voice is **not** torn down by the next non-additive (⌘↩) run, which is what lets you edit and re-evaluate one voice at a time (the SC `Pdef` mental model).
|
||||
|
||||
**Model.** `LiveSession` gains a name→synth map `slottedSynths`, guarded by the existing `trackingLock`, kept SEPARATE from the anonymous `trackedSynths` so slots survive a non-additive clear: internal `assignSlot(_:synth:)` (post-add hook — called after `engine.add` succeeds; swaps the dict under the lock, then `engine.remove`s the previous synth outside the lock; the removed synth is a *different* instance, so the "one processBlock between remove and re-add of the same instance" constraint does not apply), plus public `clearSlot(_:)` / `clearSlots()` / `slotCount` / `slotNames`. `SnippetContext` gains `play(slot:_:)` (Synthesizer) and `play(slot:bus:_:)` (bare-graph closure via `ClosureSynthesizer`). `LyrebirdScratchModel.clearTracked()` is now a full reset (anonymous + slots) for the toolbar Clear Synths button; the non-additive run's internal `clearTracked` still clears anonymous only, so slots persist.
|
||||
|
||||
**Known gotcha (documented):** a slot definition you delete from the buffer and stop re-running is not auto-removed — clear it with `context.session.clearSlot("name")` / `clearSlots()`, or hit Clear Synths. Diffing which slots a run touched (to auto-prune) was judged not worth the complexity; deferred.
|
||||
|
||||
**Docs:** `LiveCoding.md` "Named slots (hot-swap)" section + lifetime table; `LYREBIRD_START_HERE.md` snippet-API list updated.
|
||||
|
||||
**Tests:** LiveCompile sub-package 54/54 (+6): 5 `LiveSession` (assign/replace-in-place keeps one voice, `clearSlot` named-only + no-op, `clearSlots` all, `clearTracked` leaves slots intact, end-to-end `play(slot:)` round-trip through real swiftc surviving a non-additive re-run) + 1 model (Clear Synths full-reset also clears slots). Main package untouched (5502).
|
||||
|
||||
**Review:** two agents; one blocking (a doc self-contradiction — the Clear Synths description in `LiveCoding.md` still said it called `LiveSession.clearTracked()` directly, contradicting the new Named slots section) + two non-blocking docs (the `@unchecked Sendable` proof didn't enumerate `slottedSynths`; stale `LYREBIRD_START_HERE.md` API list) — all fixed. Slot swap logic, lock discipline (`engine.remove` outside the lock, non-reentrant `NSLock` never double-acquired), and actor isolation verified clean; caveman sweep LGTM.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-4 — On-beat swap (quantized slot swaps, latency masking)
|
||||
|
||||
Fourth step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes; nothing on the RT thread. Depends on LC-1 (readiness state), LC-3 (named slots), and `LyrebirdClock`.
|
||||
|
||||
**The point.** A `swiftc` build finishes a few hundred ms after ⌘↩ — Swift has no in-process JIT, so that latency is a floor, not a bug to optimize away. LC-4 *hides* it: point the session at a clock and named-slot swaps land on the next musical boundary instead of whenever the compile finished. You edit the bass, hit ⌘↩, and the change drops on the downbeat.
|
||||
|
||||
**Mechanism.** New public `SwapQuantize` enum (`.immediate` / `.nextBeat` / `.nextBar(beatsPerBar:)`) with `targetBeat(clock:)`. `LiveSession` gains `swapClock` / `swapQuantize` config (settable, `trackingLock`-guarded) and `swapSlot(_:synth:)`: in quantized mode it computes the boundary `SampleTime` from a `LyrebirdClock` and calls `engine.schedule(new, at: t)` + schedules the old voice's removal at the same time — a glitch-free on-grid swap; immediate mode falls back to add-now (the LC-3 path). `pendingSwapBeat` is a self-clearing signal (nil once the clock passes the target or the config changes). `ReevalState` gains `.queued(untilBeat:)`, which the model shows after a scheduled swap and settles to `.clean` once the boundary passes (the view's heartbeat timer calls `refreshQueuedState`); purple badge.
|
||||
|
||||
**Orphan-safety (review-fixed).** Each slot occupant carries its scheduled add time (`SlotEntry`); every removal goes through `removeSlotOccupant`, which schedules the removal at `max(desired, addTime)` — never before the occupant's own add. The engine's per-block event sort is stable at equal times and the add is always enqueued first, so an add + removal on the same sample apply add-then-removal and the voice is always cleaned up. Without this, clearing a slot (or re-swapping earlier) before a scheduled add fired left a permanent orphan voice — the RT `remove` synchronously unbinds and no-ops the tree removal, then the later add lands unremovable. Regression test drives `processBlock` past the boundary and asserts `synthesizerCount == 0`.
|
||||
|
||||
**Tests:** LiveCompile 63/63 (+9 over LC-3): 4 `SwapQuantize.targetBeat`, `LiveSession` schedule/pending-beat/immediate-no-pending + the two node-tree tests (replace→one voice, clear-before-boundary→no orphan), 1 model queued-then-settles, `ReevalState.queued` canEvaluate. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents; **one blocking** (the orphan bug) + several correctness/doc issues (discarded remove Bool, phantom `pendingSwapBeat` after config change, "engine.add failed" message on the schedule path, stale `ReevalState` state-machine doc, a "LC-3" phase reference in shipped docs) — all fixed, with a discriminating regression test. Thread-safety (all swap state under `trackingLock`, `engine.remove` outside the lock), actor isolation, and `SwapQuantize` math verified clean; caveman sweep otherwise LGTM.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-5 — Module-cache prewarm (kill time-to-first-sound)
|
||||
|
||||
Fifth step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes; nothing on the RT thread. **Measurement-driven** (the whole point of doing the measurement first).
|
||||
|
||||
**What the numbers said.** A warm snippet compile is ~0.12 s; the cost is the **cold module cache** — building the precompiled module (`.pcm`) for the large `LyrebirdSynth` interface, ~2–3 s, paid once, landing on the user's first ⌘↩. Annotating snippet bindings shaved nothing at warm (0.11 vs 0.10 s), so the "auto-annotate" lever was dropped. Swift has no in-process JIT, so the cold build is a floor to *hide*, not optimize away.
|
||||
|
||||
**Fix — prewarm at session start.** `LiveCompiler.prewarm(extraSwiftcArgs:)` type-checks a trivial import-only snippet (building the `.pcm`) via the existing `runSwiftc`; `LiveSession.prewarm()` runs it on a detached `.utility` task, idempotent via `_prewarming`/`_prewarmed` under `trackingLock`, with the flag-building filesystem walk done *inside* the task (off the caller's thread). `isPrewarmed` reflects success only — a failed prewarm (missing toolchain) stays `false` and is retryable, never throws. `LyrebirdScratchView` triggers it from `onAppear` (deliberately not `LyrebirdScratchModel.init`, so constructing a model never shells swiftc). First ⌘↩ then hits a warm cache (~0.12 s) instead of ~2.2 s.
|
||||
|
||||
**Design landmine (found + reverted).** The first cut pinned a dedicated `-module-cache-path`. That **deterministically SIGSEGV'd** the sync-compile test: a freshly-built dedicated cache produces module metadata that diverges from the already-loaded `libLyrebirdLiveCompileDynamic`, turning the test bundle's benign ObjC class-duplication *warning* into a hard cast crash on `dlopen`. Confirmed it passes on `main`, isolated `-module-cache-path` as the trigger, reverted to swiftc's default shared cache (which measurement showed warms + persists). Prewarm and the real compile now share the default cache. The rationale is documented in `makeModuleResolutionArgs` and `LiveCoding.md`.
|
||||
|
||||
**Tests:** LiveCompile 67/67 (+4 over LC-4), stable across repeated runs (the crash was deterministic — now consistently clean). Two `LiveSession` prewarm tests (completes+flag, idempotent) plus two direct `LiveCompiler.prewarm` tests (success with real module-resolution args; throws when modules unresolvable) that bypass the session's error-swallowing wrapper. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents; no blocking correctness bugs, but several real issues fixed including nits (per request): flag-building fs-walk ran on the main thread (moved off), `isPrewarmed` flipped true even on failure (now success-only + retryable), two stale reverted-design doc references (`moduleCachePath` symbol link, `-module-cache-path` in a param doc), a stdout comment not covering `-typecheck`, and a test-quality gap (the session-level tests passed regardless of real success — added direct `LiveCompiler.prewarm` coverage). Prewarm lifecycle thread-safety and `[weak self]` verified clean.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-6 — Scratch editor syntax highlighting
|
||||
|
||||
Sixth step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes, nothing on the RT thread. Scope: **highlighting only**; code completion (a SourceKit-LSP path) is a much larger async effort, deliberately deferred.
|
||||
|
||||
**What.** The `NSTextView` scratch editor now colors Swift as you type — keywords + `@attributes` (pink), Capitalized-identifier types like `OscSin`/`Pan2` (purple), strings (red), numbers (blue), comments (green), via dynamic `NSColor.system*` that adapt to light/dark.
|
||||
|
||||
**How.** New `ScratchSwiftTokenizer` — a pure, dependency-free, UTF-16-correct lexer (nested `Kind`/`Token`) that classifies the colorable spans: line + nested-block comments, single- and triple-quoted strings with escapes, number literals (no range-operator over-capture, signed exponents), keywords, and Capitalized-identifier types. Approximate by design (a highlighter, not a parser). New `ScratchSyntaxHighlighter` paints those token colors onto an `NSTextStorage` — normalizes font/paragraph/label over the whole buffer first (so a paste or font change can't leave stray styling), then overlays per-token foreground colors; attribute-only, so the string and selection are untouched. `ScratchEditor` switched to `isRichText` (with `importsGraphics = false` so no attachment glyphs) and re-highlights on every edit.
|
||||
|
||||
**Tests:** LiveCompile 80/80 (+13 over LC-5). 11 `ScratchSwiftTokenizer` tests (keywords/types/plain, numbers incl. range-operator + signed exponent, strings incl. escapes, line/nested-block comments, attributes, UTF-16 offsets across an emoji, concurrency keywords, empty, **and the trailing-backslash-at-EOF crash regression**) + 2 `ScratchSyntaxHighlighter` render-wiring tests against a real `NSTextStorage` (correct per-token colors; re-apply normalizes away a stale keyword color). The tokenizer→color→storage path is verified; only NSTextView's pixel render isn't exercised headlessly. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents, and one found a **blocking crash** — the string escape handler advanced `i += 2` unconditionally, overrunning the UTF-16 offset table when a backslash was the buffer's last character (trap: "Index out of range"); since the editor re-tokenizes per keystroke, typing an opening quote + trailing backslash crashed the UI. Clamped both escape sites to `min(i + 2, count)` with a regression test. Plus nits fixed: named the `"""` delimiter-length constant, added the concurrency keywords, signed exponents, switched the internal-type DocC symbol link to a plain code span, pinned `importsGraphics = false`, and softened the perf claim.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-7 — Session reset valve + snippet-memory accounting
|
||||
|
||||
Seventh step of the LiveCompile / Scratch group. Entirely in the macOS-only `LiveCompile/` sub-package — no core changes, nothing on the RT thread. **Scope was deliberately reduced after an engineering finding** (confirmed with the maintainer).
|
||||
|
||||
**The finding — dlclose is unsafe, not just risky.** The roadmap wanted a refcount-gated `dlclose` behind a flag. Investigation: `dlopen` of a Swift snippet dylib registers its type metadata and protocol-conformance records into **process-global runtime caches**; `dlclose` unmaps the dylib without deregistering them, leaving those caches dangling → a crash on a later type operation, **even after every synth the snippet produced has been removed** (the refcount gate does not make it safe). A flag-gated `dlclose` would therefore knowingly ship a crash, so it was rejected rather than built. Reclaiming mapped snippet memory needs a process restart; the interpreted-graph path (LC-8) is the structural fix.
|
||||
|
||||
**Shipped (safe).** `LiveSession.resetAll()` — a panic/clear valve that removes every anonymous tracked synth (`clearTracked()`) and every named slot (`clearSlots()`) from the engine and clears the pending-swap signal, without tearing down the engine; the toolbar **Clear Synths** routes through it. `LiveSession.loadedSnippetCount` — thread-safe count of mapped snippet dylibs, for host observability (e.g. a "restart to reclaim memory" nudge after a long session). New `LiveCoding.md` "Snippet memory (the dylib leak)" section documenting the leak, why `dlclose` is unsafe, and `resetAll` as the valve.
|
||||
|
||||
**Tests:** LiveCompile 83/83 (+3 over LC-6): `resetAll` clears tracked + slots, `resetAll` clears a pending quantized swap, `loadedSnippetCount` grows per compile. Main package untouched (5502).
|
||||
|
||||
**Review:** two agents. Locking verified correct (`clearTracked`/`clearSlots` release `trackingLock` before `resetAll` re-acquires it — no re-entrancy/deadlock; `NSLock` non-reentrant), the pending-scheduled-swap interaction verified orphan-safe, and the doc's `dlclose`-unsafety claim confirmed accurate. One blocking (the `_pendingSwapBeat` clear was untested — added a test) + a doc caveat (concurrency precondition + non-atomic reset) fixed.
|
||||
|
||||
**Planned revisit (deferred).** At the end of the LiveCompile arc, come back for more user-facing memory choice/safety — e.g. surfacing `loadedSnippetCount` in the editor with a restart nudge past a threshold, and any additional guardrails. Tracked in `docs/00-working-order.md` Deferred / Future.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-8 — Interpreted Generator-graph DSL
|
||||
|
||||
Final step of the LiveCompile / Scratch group: a text-to-graph language that plays instantly with no `swiftc`, no dylib, no leak, and no sandbox-disable — the structural answer to LC-7's by-design snippet-dylib leak. The DSL layer (`LyrebirdGraphDSL`) is a cross-platform main-package target; only the editor integration is macOS-only.
|
||||
|
||||
**Code-gen first (8a).** No generator registry exists in Lyrebird (no runtime table, no reflection to call inits by name), so the DSL had to introduce one — generated, not hand-written. `Tools/DSLRegistryGen` is a separate SwiftPM package (swift-syntax stays out of the main build) that scans generator sources and emits `Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift`, driven by `scripts/generate-dsl-registry.sh` (`--report` / `--check` drift guard, compile-verify). `DSLBuiltin` (Sendable, `@Sendable make` closure) + `DSLBuiltinRegistry` (keyed by name + rate) + `DSLArgument` (coerces a bound `any ValidGeneratorInput` to the `Double`/`Int`/`Float`/buffer an init needs).
|
||||
|
||||
**Wider surface before the language.** `.Control`-rate variants emitted alongside audio (registry keyed by `(name, rate)`); resource kinds (buffer/bus/URL/closure) categorised so the parser was designed against the full surface. Final registry: **304 builtins** (165 audio + 121 control + 18 buffer).
|
||||
|
||||
**The language (8b + language surface).** `DSLLexer` → `DSLParser` (recursive descent, `*/` over `+-`, parens, unary minus, positional + labelled args, `name = expr` slot assignment, depth-capped at 128, constant-folds numeric subexpressions so numeric-literal-only params accept `-0.5`/`220*2`) → AST (`DSLExpr`/`DSLProgram`/`DSLSpan`) → `DSLGraphBuilder` (registry lookup, `+ - * /` → `BinaryOpGenerator` ops, duplicate-arg detection) → `DSLInterpreter.evaluate(_:resources:)` → `[DSLOutput]`. Explicit control-rate selection and buffer resources: `DSLValue` (`.signal | .buffer`), `DSLResourceResolver` (host name → `LyrebirdBuffer`), bare-identifier references (`PlayBuffer(buffer: kick)`), operators signal-only.
|
||||
|
||||
**Paste-compatibility.** The rate suffix is the *exact* Swift nested-class name — `OscSin.Control(freq: 4)`, not a lowercase `.control` or an SC-style `.kr` — so a DSL graph expression reads and constructs identically in the editor and in a Lyrebird `build()`; only the wrapping (`output(...)`, `let` slot) differs. (`.ar`/`.kr` was shipped, then corrected to `.audio`/`.control`, then to `.Audio`/`.Control` after maintainer feedback that a user shouldn't have to learn a spelling difference between environments.)
|
||||
|
||||
**Editor mode (8d).** A status-bar segmented toggle (`ScratchEvalMode`) switches the scratch buffer between the swiftc Swift-snippet path and the instant DSL path. `LiveSession.runGraphDSL(_:additive:resources:)` interprets the buffer and plays each `DSLOutput` through the **same** tracking + named-slot machinery as the Swift path (bare line → tracked anonymous synth; `name = …` → persistent hot-swap slot). The whole program is built **before** any engine mutation, so a malformed edit never drops the currently-playing graph; once valid, playback is best-effort per statement (a `.pendingQueueFull` on one statement is collected, not aborted — matching `SnippetContext.play`). `GraphDSLDiagnosticMapper` turns `DSLParseError`/`DSLBuildError` into the same `[Diagnostic]` the swiftc path emits (parse errors resolve a line/column from the span's char offset; build errors report at file scope). `LyrebirdScratchModel.switchMode(to:)` swaps the seed placeholder, clears diagnostics, and drops the run baseline.
|
||||
|
||||
**Linking (the crash paid for twice).** The DSL is compiled as a **local** `LyrebirdGraphDSLEmbedded` target in the LiveCompile sub-package, from the main package's shared sources via a git symlink (`LiveCompile/Sources/LyrebirdGraphDSLEmbedded` → `../../Sources/LyrebirdGraphDSL`, distinct module name), **not** consumed as a main-package product. Any `LyrebirdGraphDSL` product — static *or* dynamic — static-embeds a second copy of `LyrebirdSynth` into its dylib (a same-package target dependency is always embedded into a dynamic product; verified via `nm`), so both it and `libLyrebirdDynamic` register Lyrebird's ObjC classes → double registration → spurious cast failures + `SIGSEGV` under `swift test`. Only a cross-package boundary forces dynamic linking (the same mechanism that made the LiveCompile split necessary). Compiling the DSL as a local target lets its `import LyrebirdSynth` resolve cross-package to the one shared `libLyrebirdDynamic` (verified: 0 embedded `LyrebirdSynth` symbols in the LiveCompile dylib, `otool -L` shows the `libLyrebirdDynamic` dependency). Safe because the DSL is pure value types — it registers nothing with the ObjC runtime.
|
||||
|
||||
**Tests.** DSL suite grew across the sub-phases (lexer/parser/interpreter/registry/argument/resource); the editor phase added 22 (LiveCompile 86 → 108: `LiveSessionGraphDSLTests`, `GraphDSLDiagnosticMapperTests`, `ScratchModelGraphDSLTests`). Main package untouched (5563); registry `--check` clean.
|
||||
|
||||
**Review.** Two agents per sub-phase. Notable fixes: constant resolution silently broken (assigned before its `var` ran → wiped); designated-init selection dropped overloads (RBJBandPass lost `q:`); doubly-nested types got the wrong DSL name (`MouseX` not `X`); a stack-overflow on deep nesting (depth cap); a deterministic `PlayBuffer`-teardown `SIGTRAP` worked around by testing buffer resolution directly (underlying `LyrebirdBuffer` ARC race tracked separately). The editor phase's three blocking findings — `runGraphDSL` aborting the mutation loop on the first engine error (→ per-statement continue-on-error), a DSL build error rendering as the nonsensical `preamble:0:0` (→ `(file)`), and `switchMode` leaving stale diagnostics / a false `.clean` — were all fixed and re-reviewed clean.
|
||||
|
||||
**Deferred / out of scope.** Bus/URL/closure/demand builtins (routing is host-level via `ClosureSynthesizer`'s `Out`; closures are the Swift path). LC-6b SourceKit-LSP completion. LC-7 revisit (user-facing memory choice/safety). The `LyrebirdBuffer` teardown ARC race.
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-6b — Editor code completion (SourceKit-LSP)
|
||||
|
||||
The deferred half of LC-6: real Swift code completion in the live-coding editor, driven by the toolchain's `sourcekit-lsp`. macOS-only, all non-RT host tooling.
|
||||
|
||||
**Feasibility first.** The novel risk was whether `sourcekit-lsp` could resolve `LyrebirdSynth` symbols for an otherwise free-standing snippet file. Proven with a throwaway probe before any real code: driving the LSP handshake against a `compile_commands.json` built from the SPM build products, `OscSin.` completed to `Audio` / `Control` / `_Base`.
|
||||
|
||||
**`SourceKitLSPClient`** — a minimal LSP JSON-RPC client over stdio: `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, `textDocument/completion`. A background reader thread parses `Content-Length`-framed messages and completes `CheckedContinuation<Data, Error>`s stored in an `NSLock`-guarded pending map; requests carry `Data` (Sendable) and use sync lock helpers so no `NSLock` call sits in an `async` context. Per-request timeout via a task-group race; injectable timeout/arguments for testing.
|
||||
|
||||
**`SnippetCompletionService`** (actor) — maintains a temp workspace holding the snippet **wrapped** in the same `SnippetHarness` preamble the compiler uses, next to a `compile_commands.json` carrying the host `LiveSession`'s `-I` / module-map / link flags plus an explicit `-sdk` / `-target` (which a normal build infers but the LSP needs). The caret is mapped through the harness line offset (`wrappedLine = userLine + userBodyLineOffset - 1`). SDK lookup + file writes run inside the async `start()` (actor executor), never on the caller's main thread.
|
||||
|
||||
**Editor wiring** — the `ScratchEditor` Coordinator pre-fetches candidates asynchronously on `.` and serves them synchronously to `NSTextView`'s own completion window (arrows / return / esc / insertion for free). A generation counter drops superseded responses; a caret-equality guard drops ones whose insertion point moved. Swift-mode only — graph-DSL is interpreted and needs no compiler. Best-effort: any LSP failure yields no candidates, never an error. `editorLineAndUTF16Char` (the offset→(line, UTF-16 column) mapping, LSP's coordinate space) is extracted and unit-tested.
|
||||
|
||||
**Tests** — 120/120 LiveCompile. Integration tests spawn the real `sourcekit-lsp`: `OscSin.` → `Audio`/`Control`, `context.` → `play`/`engine`; graph-DSL mode returns nothing. Unit tests cover the position mapping and the client's timeout / launch-failure paths.
|
||||
|
||||
**Review.** Two rounds. The critical find: `request(...)`'s timeout path dropped the pending continuation without resuming it, so the task-group child stayed suspended and `request` hung forever — the exact wedged-server case the timeout exists to guard (`cancelAll()` does not wake a suspended continuation). Fixed by resuming-then-dropping under the lock (+ a regression test). Also fixed: a blocking `xcrun` shelled from `init` on the main actor (moved into async `start()`), a swallowed graceful `exit` on shutdown, and a missing request-generation guard.
|
||||
|
||||
**Follow-ups (optional).** A manual-invoke completion shortcut (⌥/⌃-driven; dropped from the MVP to avoid `NSEvent`-monitor isolation friction), and richer completion presentation (detail/kind in the popup — `NSTextView`'s built-in window shows plain strings only).
|
||||
|
||||
---
|
||||
|
||||
## Phase LC-7 revisit — snippet-memory UX (user-facing)
|
||||
|
||||
The deferred user-facing half of LC-7: make the by-design snippet-dylib leak visible and give the user a choice, without the unsafe `dlclose` (still rejected). LiveCompile-only, non-RT.
|
||||
|
||||
Each successful **Swift-mode** ⌘↩ maps one compiled snippet dylib that is never unloaded (`dlopen` registers Swift type metadata + conformance records into process-global caches that `dlclose` leaves dangling); Graph-DSL runs map none. `LyrebirdScratchModel` now mirrors `LiveSession.loadedSnippetCount` (refreshed at every site `trackedSynthCount` is — init, both run-path defers, `clearTracked`). A pure, unit-tested `snippetMemoryHint(count:threshold:)` returns a restart nudge past `snippetRestartThreshold` (50). The editor shows a **"snippets: N"** count in the engine bar (orange past the threshold) and an orange warning banner carrying the hint ("restart to reclaim, or use Graph DSL — no compile, no leak"). `Clear Synths` explicitly does *not* reclaim the dylibs and says so. It is a soft nudge, not a hard cap — the Graph DSL mode is the leak-free path the banner steers toward.
|
||||
|
||||
Review (pr_review_agent): no blocking issues; added one test exercising `clearTracked`'s mirror refresh. LiveCompile 127→128. Main untouched.
|
||||
|
||||
**LiveCompile arc complete: LC-1 … LC-8 + LC-6b + LC-7 revisit all shipped.**
|
||||
|
||||
Reference in New Issue
Block a user