Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(fix) Loop seam keeps notes sounding; loop recording: Overdub or Replace (#29) (#96)

Egor Khindikaynen3ed5d73ad03f
diff --git a/.specify/bugs/loop-seam-note-cut/assessment.md b/.specify/bugs/loop-seam-note-cut/assessment.md
new file mode 100644
index 00000000..6c549445
--- /dev/null
+++ b/.specify/bugs/loop-seam-note-cut/assessment.md
@@ -0,0 +1,96 @@
+# Bug Assessment: Held notes and release tails cut at the loop seam; notes recorded across it shrink
+
+- **Slug**: loop-seam-note-cut
+- **Created**: 2026-10-16
+- **Source**: https://github.com/nota-daw/nota/issues/29 (host: github.com, policy: allowlisted)
+- **Verdict**: valid
+- **Severity**: medium
+
+## Report (verbatim or summarized)
+
+Issue #29 (reported on 0.52.1, Windows x64, label `bug`). Title: "Recording when playing MIDI & it loops a bar suddenly stops while holding a key if it loops the bar during the hold, and recording live midi on loop 1 bar with same melody punched in on repeat makes it stack overlay at different timings (perhaps a toggle for this)".
+
+> if u hold a key down and it loops it suddenly stops
+
+Comment from the reporter:
+
+> It Basically Just Stops The Audio Like Say I Have An String It Lasts A Long Duration After Being Played, But It Cuts Off On Loop If U Are Looping Something
+
+**Scope of this assessment**: held live notes and release tails cut at the loop seam, plus the length of a note recorded across the seam. The report's other half is that overdub passes stack notes, and it asks for an Overdub/Replace toggle. That half is expected behaviour today and a feature request. It is **out of scope** here and goes through `/speckit-specify`.
+
+## Symptom
+
+With the transport loop on, every sounding voice on Arrangement-driven instrument tracks is hard-cut when the playhead wraps from the loop end to the loop start. That includes a key the player is still holding and the release tail of a long pad or string. Expected: a held key keeps sounding, and tails ring out naturally. A note that ends at the loop end gets a normal note-off and releases.
+
+While loop-recording in the Arrangement, a key pressed before the seam and released after it is stored as a 0.1-beat stub at its start position. A routed (MIDI-from-track) note gets the same treatment, with its length clamped to 0 and then 0.1. Expected: the recorded note keeps the part that was played.
+
+## Reproduction
+
+1. New project, add an instrument track with a sustaining built-in (e.g. Volt pad with long release) and arm it.
+2. Turn the transport loop on over 1 bar (beats 0–4) and press Play (or Record).
+3. Press and hold a key around beat 3.5 and keep holding past the loop end.
+ **Observed**: the note goes silent at the wrap. **Expected**: it keeps sounding until released.
+4. Release a short note just before the loop end on a long-release patch.
+ **Observed**: the tail is cut at the wrap (only the ~1.5 ms declick fade remains). **Expected**: the tail rings into the next pass.
+5. With Record on, hold a key from ~beat 3.5 across the wrap and release at ~beat 0.5 of the next pass, then stop.
+ **Observed**: the take holds a 0.1-beat note at 3.5. **Expected**: see Open Questions (split vs. truncate), but not a 0.1-beat stub.
+
+Step 4 also applies to clip playback without recording: any clip note whose release crosses the loop end is cut.
+
+## Suspected Code Paths
+
+- `src/native/nota.engine/src/Engine_Render.cpp:1077-1084` (`flushArrangementVoices` lambda) — calls `instrument->allNotesOff()` and `md->reset()` on every non-Session instrument track.
+- `src/native/nota.engine/src/Engine_Render.cpp:1101-1107` (loop wrap in `processBlock`) — calls `flushArrangementVoices()` on every wrap. This is the cut.
+- `src/native/nota.engine/src/VoltSynth.h:266`, `OperatorSynth.h:194`, `Keys.h:327`, `RhythmMachine.h:493` — built-in `allNotesOff()` sets `v.active = false`, so the voice is removed with no release stage. That is why the tails vanish.
+- `src/native/nota.engine/pluginhost/PluginHost.cpp:705` — hosted plugins get CC123 All Notes Off. It also kills the live-held key, though most plugins release rather than cut.
+- `src/native/nota.engine/src/Arpeggiator.h:131` — `reset()` clears `held_`/`physDown_`, so an arp on the track also forgets a key the player is still holding at the seam.
+- `src/native/nota.engine/src/Engine_Render.cpp:609-648` (`gatherInstrumentNotes`) — clip note-offs are emitted only when `offS` falls inside the current block. A clip note running past the loop end never gets its off in that pass. The flush exists to cover this, so removing the flush needs a replacement off.
+- `src/native/nota.engine/src/Engine_Render.cpp:513-522` (`drainLiveMidi`) — `len = nowBeat - pendingStart_`. The wrap fix (`len += slotLen`) is only applied for Session slots (`if (slot && len < 0.0)`). An Arrangement-loop note across the seam gets a negative length.
+- `src/native/nota.engine/src/Engine_Render.cpp:296` (`collectRecorded`) — `n.lengthBeats = r.lengthBeats > 0.0 ? r.lengthBeats : 0.1`, which turns the negative length into the 0.1-beat stub.
+- `src/native/nota.engine/src/Engine_Render.cpp:580-590` (`captureRoutedNotes`) — the same problem for routed notes: `std::max(0.0, beat - recRoutedStart_)` gives 0, which becomes 0.1.
+- `src/native/nota.engine/src/Engine_Render.cpp:545-556` (`captureLiveExpr`) — expression offsets have the same Session-only wrap handling, so MPE curves on a cross-seam note go out of range.
+- `src/native/nota.engine/src/Engine_Render.cpp:430-450` (`publishHeldSnapshot`) — the #56 held-note preview reports `pendingStart_` from the previous pass, so after a wrap the preview note's start is later than "now".
+
+## Root Cause Hypothesis
+
+The loop wrap reuses the stop/seek "flush stuck voices" path. That path hard-kills every voice on Arrangement tracks, so a clip note running past the loop end can't hang. It doesn't tell clip-owned voices from live-input voices. And because the built-ins' `allNotesOff()` deactivates voices outright, release tails go too. Separately, the live and routed capture compute note length as `now - start` on the unwrapped beat clock, and only the Session-slot path corrects for the wrap. In the Arrangement loop, a cross-seam note gets a negative length, which `collectRecorded` replaces with 0.1. Confidence: **high** (all three effects follow directly from the cited lines).
+
+## Proposed Remediation
+
+**Preferred**:
+
+1. *Release clip notes at the seam instead of flushing the instrument.* On a loop wrap, stop calling `flushArrangementVoices()`. Set a flag for the first segment after the wrap. In `gatherInstrumentNotes`, while the flag is set, emit a note-off at offset 0 for every clip note that was sounding at the loop end (`onS < loopEndS && offS > loopEndS`, after the clip-end clamp; inactive clips included, as for normal offs). These offs go through the track's MIDI FX chain like any other event, so the arp, chord, transpose and similar devices map them correctly. They also reach routed destinations, and instruments play their release stage. Note chase already retriggers notes spanning the loop start, and `midiEvLess` sorts offs before ons at the same offset, so a note spanning the whole loop still re-articulates as it does today. Live events are untouched, so a held key keeps sounding. Drop the `md->reset()` on wrap so the arp keeps live-held keys (see Open Questions on arp phase). Keep `flushArrangementVoices()` for stop and seek, which this report doesn't cover.
+2. *Split recorded notes at the seam.* In `processBlock`, when a wrap happens while recording into the Arrangement (no `recordSlotPlayer_`), handle every `pendingActive_` pitch and every `recRoutedActive_` pitch the same way. Push a `RecordedNote` from its start to `loopEnd`, then restart it at `loopStart` with the same velocity. The continuation becomes its own note when the key is released, and the held-note preview stays correct. As a safety net, `collectRecorded`/`drainLiveMidi` no longer turn a negative length into 0.1. Clamp to the loop end instead, though with step 2 that should no longer happen. `captureLiveExpr` follows the restarted `pendingStart_` automatically.
+
+**Alternatives**:
+- *Per-track "clip-sounding" ledger at the instrument input (post-FX)*, flushed with `noteOff` per pitch at the seam. It's exact with respect to what the instrument received, but after the MIDI FX the engine can't tell clip notes from live ones. It also adds state per track. The pre-FX synthetic offs are simpler and stateless.
+- *Add `Instrument::releaseAll()` (soft) and re-press the live-held keys after the wrap.* It's simple, but every held key re-attacks on each pass, which is audible and wrong for pads.
+- *Recording: truncate at the loop end* instead of splitting. It's one note and simpler, but the part played after the wrap is lost. See Open Questions.
+
+**Files likely to change**:
+- `src/native/nota.engine/src/Engine_Render.cpp` (wrap handling in `processBlock`, `gatherInstrumentNotes`, `drainLiveMidi`, `captureRoutedNotes`, `collectRecorded`)
+- `src/native/nota.engine/src/Engine.h` (seam flag / loop-end sample for the post-wrap segment)
+- `tests/Nota.SmokeTest/LiveRecordTests.cs` (new cases), possibly a loop-playback case in `tests/Nota.SmokeTest/Program.cs`
+- `CHANGELOG.md` ([Unreleased] → Fixed)
+
+**Tests to add or update** (smoke test, `RenderOffline` with a 1-bar loop at 120 BPM):
+- *Held key survives the seam*: arm a long-sustain built-in, loop 0–4, `NoteOn` at beat 3.5, render past the wrap. RMS in the window just after the wrap stays above a floor (not silence).
+- *Release tail survives the seam*: a long-release patch, a clip note 3.0–3.9. Energy right after the wrap is non-zero and decays (tail present).
+- *Clip note crossing the loop end does not hang*: a clip note 3.0–6.0 in a 0–4 loop on a sustain patch. Once the next pass has no note at that pitch, the instrument's voice count (or RMS) falls back to 0.
+- *Recorded note across the seam*: Record, `NoteOn` at 3.5, release at 0.5 of the next pass. The take holds a note at 3.5 of ~0.5 beats and a note at 0.0 of ~0.5 beats. There must be no 0.1-beat stub. Run the routed variant the same way (`Routed()` pattern).
+- *Session slot behaviour unchanged*: the existing `SessionSlot()` test still passes.
+
+## Risks & Considerations
+
+- **Hanging notes**: the hard flush is the current guarantee against stuck notes on the wrap. The replacement offs have to cover every clip note crossing the loop end. That includes clips trimmed or deactivated mid-pass, and notes whose start is before the clip (#56 pickups). Stop and seek keep the hard flush as a backstop.
+- **MIDI FX with internal state** (arp, note length, random): without `reset()` on the wrap, an arp keeps its step position across the seam instead of restarting at step 1 each pass. This could change how existing loops sound, so see Open Questions. Note-length FX that schedule their own offs keep working because they see the synthetic offs.
+- **Same pitch held live and ending in a clip at the seam**: the synthetic off for the clip note also releases the live voice. This is an edge case and matches how a normal clip note-off behaves today.
+- **Hosted plugins** now get individual note-offs instead of CC123 at every seam. That's better behaviour, but VST/AU instruments should be spot-checked.
+- **Audio thread rules**: everything stays allocation-free (fixed arrays and flags). No locks.
+- **Declick**: the seam fade (`Engine_Render.cpp:1141-1157`) still applies. With tails surviving, the fade is now an audible notch on sustained material, though at ~1.5 ms it's probably inaudible. Keep it for audio clips.
+
+## Open Questions
+
+- [NEEDS CLARIFICATION: A note held across the loop seam while recording. Split it into "start→loop end" plus "loop start→release" (proposed), or truncate it at the loop end?]
+- [NEEDS CLARIFICATION: Should a track's arpeggiator still restart its pattern at step 1 on every loop pass (today's behaviour via `reset()`)? If so, use a phase restart (`midiCommand(1)`-style) that keeps held keys instead of the full `reset()`.]
+- [NEEDS CLARIFICATION: Should stopping the transport also let tails ring out (release) instead of hard-cutting? Same mechanism, but not part of this report.]
diff --git a/.specify/bugs/loop-seam-note-cut/fix.md b/.specify/bugs/loop-seam-note-cut/fix.md
new file mode 100644
index 00000000..78c9983f
--- /dev/null
+++ b/.specify/bugs/loop-seam-note-cut/fix.md
@@ -0,0 +1,85 @@
+# Bug Fix: Held notes and release tails cut at the loop seam; notes recorded across it shrink
+
+- **Slug**: loop-seam-note-cut
+- **Fixed**: 2026-10-16
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+The loop wrap no longer hard-flushes every Arrangement instrument (`allNotesOff` + MIDI FX `reset`).
+In the first segment after the wrap, the engine sends a note-off for each clip note that was still
+sounding at the loop end, so live-held keys keep sounding and instruments play their release. MIDI FX
+with transport-beat state (Arp, Note Length) shift that state by −loop length, so they carry on
+across the seam. While recording into the Arrangement, a note held across the seam (live or routed)
+is split into "start → loop end" and "loop start → release".
+
+## Decisions (user, 2026-10-16 — resolving the assessment's Open Questions)
+
+- A note held across the seam while recording is **split into two** notes.
+- The arpeggiator **continues its pattern from the same position** across the seam (no restart, held keys kept).
+- Stop and seek **keep the hard flush**. Tails on stop are out of scope.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/native/nota.engine/src/Engine_Render.cpp` | modified | Wrap: no `flushArrangementVoices()`. It records the pre-wrap playhead (`seamEndSamples_`), calls `onLoopWrap()` and sets `seamOffs_` for the next segment. `gatherInstrumentNotes` emits offset-0 note-offs for clip notes with `onS < seamEnd ≤ offS`. New `Engine::onLoopWrap()` handles MIDI FX `timeJump` and the recording split. |
+| `src/native/nota.engine/src/Engine.h` | modified | `seamOffs_`, `seamEndSamples_`, `onLoopWrap()` declaration. |
+| `src/native/nota.engine/src/MidiDevice.h` | modified | New `virtual void timeJump(double deltaBeats)` (default no-op). The `reset()` comment no longer lists the loop wrap. |
+| `src/native/nota.engine/src/Arpeggiator.h` | modified | `timeJump`: shifts `arpBeat_`, `phaseRef_`, and the pending on/off beats. |
+| `src/native/nota.engine/src/MidiNoteLength.h` | modified | `timeJump`: shifts `intBeat_`, the pending offs, the sounding and held note beats. |
+| `tests/Nota.SmokeTest/LoopSeamTests.cs` | added test | Six seam cases (see below). |
+| `tests/Nota.SmokeTest/Program.cs` | modified | Runs `LoopSeamTests` in the full run and under `--live-record`. |
+| `CHANGELOG.md` | modified | `[Unreleased] → Fixed` entry. |
+
+## Diff Highlights
+
+```cpp
+// processBlock, at the wrap
+seamEndSamples_ = transport_.playheadSamples();
+transport_.wrapToLoopStart();
+if (spb > 0.0) onLoopWrap(g, transport_.loopStartSamples() / spb, seamEndSamples_ / spb);
+seamOffs_ = true;
+chase = true;
+
+// gatherInstrumentNotes: release what was still sounding at the loop end (offs sort before chase ons)
+if (seamOffs_ && onS < seamEndSamples_ && offS >= seamEndSamples_ && n < 1024)
+ evs[n++] = {0, false, note.pitch, 0.0f};
+
+// onLoopWrap: split a note held across the seam while recording
+const double head = loopEndBeat - start;
+if (head >= kMinHead) recorded_.push(RecordedNote{pitch, start, head, vel});
+start = loopStartBeat;
+```
+
+## Tests Added or Updated
+
+`tests/Nota.SmokeTest/LoopSeamTests.cs` (1-bar loop 0–4 at 120 BPM, offline render):
+- `HeldKey`: a live key held across the wrap keeps its level after the wrap.
+- `ReleaseTail`: a clip note ending at 3.9 on a long-release Synth is still audible right after the wrap.
+- `ClipNoteAcrossEnd`: a clip note from 3.0 to 6.0 releases at the seam, and the next pass is silent (no hanging note). This is the regression guard for removing the flush.
+- `Arpeggiator`: an Arp on the track keeps playing a key held across the wrap.
+- `RecordAcrossSeam`: a key held from 3.5 to 0.5 of the next pass is stored as `3.5+0.5` and `0.0+0.5`.
+- `RoutedAcrossSeam`: the same for MIDI routed in from another track.
+
+## Local Verification
+
+- `cmake --build src/native/nota.engine/build` and `dotnet build tests/Nota.SmokeTest -c Release` → OK.
+- **Without the fix** (engine sources reverted, rebuilt): five of the six seam tests FAIL, while `ClipNoteAcrossEnd` passes. The failures: held key `0.0288 → 0.0000`, tail `0.0000`, arp `0.0222 → 0.0000`, and a recorded note of `3.51+0.10` (the stub from the report).
+- **With the fix**: `dotnet run --project tests/Nota.SmokeTest -c Release` → `SMOKE TEST PASSED`, 3483 PASS / 0 FAIL, all six seam tests pass, including the existing `loop seam declicked` check.
+- The full `scripts/build.sh` (universal arm64+x86_64 build) was not run. Only the existing native build directory and the smoke test were.
+- Not checked by ear in the app, and not with hosted VST/AU instruments.
+
+## Deviations from Assessment
+
+- **Scope expansion: MIDI FX `timeJump`.** The assessment proposed dropping `md->reset()` on the wrap. While implementing, two problems turned up. The Arpeggiator and Note Length keep pattern phase and pending offs in absolute transport beats. Without a shift, pending events would wait a whole pass, and a Note-retriggered arp would go silent after the wrap (`k < 0`). So I added `MidiDevice::timeJump(deltaBeats)`, implemented in `Arpeggiator.h` and `MidiNoteLength.h`. Chord, Scale, Random and Velocity run on their own sample clock or are stateless, so they only needed to stop being reset.
+- **Short heads are dropped.** A key pressed less than 1/64 beat before the seam (the block-quantisation sliver, or a player anticipating the downbeat) is not split. The whole note moves to the loop start instead.
+- **No change to the 0.1-beat fallback** in `collectRecorded`. With the split in place, Arrangement-loop notes no longer reach it with a negative length, so the extra clamp from the assessment wasn't needed.
+
+## Follow-ups
+
+- Spot-check with a hosted VST/AU instrument. Plugins now get individual note-offs at the seam instead of CC123.
+- Drum one-shots (Rhythm, Drum Rack) are no longer cut at the seam, so their tails ring into the next pass. This is intended, but worth a listen.
+- The Overdub/Replace loop-record toggle from #29 is a separate feature (`/speckit-specify`; proposed as a task card).
+- User docs: no page describes the old cut behaviour, so I left nota-docs alone. Re-check during `/release` audit.
diff --git a/.specify/bugs/loop-seam-note-cut/test.md b/.specify/bugs/loop-seam-note-cut/test.md
new file mode 100644
index 00000000..5880966c
--- /dev/null
+++ b/.specify/bugs/loop-seam-note-cut/test.md
@@ -0,0 +1,78 @@
+# Bug Verification: Held notes and release tails cut at the loop seam; notes recorded across it shrink
+
+- **Slug**: loop-seam-note-cut
+- **Tested**: 2026-10-16
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified
+
+## Summary
+
+The assessment's reproduction steps 3–5 were run through the engine (offline render, the same
+`processBlock` path the audio callback uses). Without the fix the symptoms reproduce. With it they
+are gone on Synth, Volt, Keys and Operator, across one and several wraps, while recording live and
+routed MIDI, and with the Arp (every retrigger mode) and Note Length on the track. The full build and
+smoke suite pass with no regressions. Nobody listened in the running app, and no hosted VST/AU
+instrument was tested.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction (pre-fix) | Engine sources reverted, rebuilt, smoke run | fail (as expected) | 5 of 6 seam tests FAIL: held key `0.0288 → 0.0000`, tail `0.0000`, arp `0.0222 → 0.0000`, recorded `3.51+0.10` (the stub from the report). Run during `/speckit-bug-fix`. |
+| Reproduction (post-fix), steps 3–5 | `tests/Nota.SmokeTest/LoopSeamTests.cs` (Synth) | pass | See excerpts. |
+| Reproduction (post-fix), on other instruments | Throwaway harness `/tmp/seam-verify` (outside the repo): Volt, Keys, Operator | pass | Held key across the seam on all three. Volt release tail across the seam matches a no-loop baseline exactly. |
+| Edge cases | Same harness | pass | A key held across 3 wraps keeps sounding, and Stop still silences it (hard flush kept). Arp with Retrig Off / Note / Beat carries on across the seam with nothing hanging after release. Note Length FX: nothing hangs. A key recorded across one seam gives 2 notes. |
+| Full build + regression suite | `scripts/build.sh` | pass | Universal `x86_64 arm64` dylib, managed build, `SMOKE TEST PASSED`, 3483 PASS / 0 FAIL, including the existing `loop seam declicked` check. |
+| Lint / type-check | — | not-run | The project has no separate lint step. The C++ and C# compiles in `build.sh` passed. |
+| In-app listening (Windows, the reporter's platform) | — | not-run | Needs a person at the keyboard. Engine-level checks cover the same code path. |
+| Hosted VST/AU instrument | — | not-run | No plugin available headless. Plugins now get per-note offs at the seam instead of CC123. |
+
+## Output Excerpts
+
+`scripts/build.sh`:
+```
+Architectures in the fat file: src/native/nota.engine/build/libnota_engine.dylib are: x86_64 arm64
+-- loop seam --
+ [PASS] loop seam: a held key keeps sounding after the wrap (rms 0,0288 → 0,0288, pos 0,27)
+ [PASS] loop seam: a release tail rings on after the wrap (rms 0,0247, pos 0,01)
+ [PASS] loop seam: a clip note crossing the loop end releases, no hanging note (rms 0,0229 → 0,000000)
+ [PASS] loop seam: the arpeggiator carries on with a key held across the wrap (rms 0,0222 → 0,0220)
+ [PASS] loop seam: a note recorded across the wrap is split at the loop end (0,00+0,51, 3,51+0,49)
+ [PASS] loop seam: a routed note recorded across the wrap is split at the loop end (0,00+0,51, 3,51+0,49)
+SMOKE TEST PASSED
+```
+
+Harness (`/tmp/seam-verify`):
+```
+PASS held key across seam [Volt]: rms 0,0628 -> 0,0377, pos 0,22
+PASS held key across seam [Keys]: rms 0,1609 -> 0,1367, pos 0,22
+PASS held key across seam [Operator]: rms 0,0799 -> 0,0768, pos 0,22
+PASS release tail across seam [Volt]: rms at end 0,0544, just after wrap 0,04866, pos 0,04
+PASS held key across 3 wraps, stop flushes [Volt]: rms after 3 wraps 0,0587, after stop 0,000000
+PASS arp retrig=0 across seam: rms 0,0567 -> 0,0654, after release 0,000000
+PASS arp retrig=1 across seam: rms 0,0665 -> 0,0654, after release 0,000000
+PASS arp retrig=2 across seam: rms 0,0567 -> 0,0654, after release 0,000000
+PASS note length FX across seam: rms 0,0492 -> 0,0000, after release+4.5 beats 0,000000
+PASS record across seam [Volt]: 64: [0,00+0,51, 3,51+0,49] 67: [0,00+4,00, 0,00+2,52, 1,51+2,49]
+INFO volt tail loop=False release=0,8: rms 45-100 ms after note-off 0,04866
+INFO volt tail loop=True release=0,8: rms 45-100 ms after note-off 0,04866
+```
+
+Notes on reading the harness:
+- The first tail run measured 0 because Volt's default amp release is under ~45 ms, and the no-loop baseline also measures 0. With the release raised (param 39), the looped and unlooped tails are identical.
+- In the record case, key 67 was held from 1.5 for 9 beats, so it crossed two seams. It came out as 3 notes, two of them stacked at 0.0. That is overdub, which is out of scope here (the Overdub/Replace feature).
+- Note Length's "after" is 0 because its default length ends the note before the seam. The check is that nothing hangs.
+
+## Residual Risks
+
+- Not listened to in the app, and not on Windows (the reporter's platform). The engine path is platform-independent.
+- Hosted VST/AU instruments were not exercised. They now get individual note-offs at the seam instead of CC123.
+- Drum one-shots and long tails now ring into the next pass rather than being cut. This is intended, but it changes the sound of existing loops.
+- A key and a clip note on the same pitch: the clip note's seam off also releases the live voice. This matches a normal clip note-off.
+
+## Recommendation
+
+Close the engine side of nota-daw/nota#29 (the cut notes and tails, and the shrunken recorded
+note) once someone has listened in the app with a long pad and an Arp on a 1-bar loop. The
+issue's other half, the Overdub/Replace toggle, stays open as a separate feature.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9749c7e1..6fd1f808 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,13 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Fixed
+- **Notes no longer cut off at the loop seam** (nota-daw/nota#29): when the loop jumps
+ back to its start, a key you're holding keeps sounding and release tails (pads, strings)
+ ring out. Before, every voice was cut at the seam. A clip note running past the loop end
+ now releases there, and an arpeggiator keeps its pattern and held keys going across the
+ seam instead of starting over. Recording in a loop, a note held across the seam is stored
+ as two notes, one up to the loop end and one from the loop start. Before, it was saved
+ as a short blip.
- **Undo covers device knobs** (nota-daw/nota#30): turning a knob, flipping a switch or
typing a value on an effect, a MIDI effect, an instrument or a plug-in is now one undo
step, in order with note and clip edits — before, ⌘Z skipped it and undid the edit before.
@@ -34,6 +41,14 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
moves them into the project file on the next save.
### Added
+- **Loop recording: Overdub or Replace** (nota-daw/nota#29): when you record MIDI in a loop,
+ choose whether each pass adds to the take (**Overdub**, as before) or replaces it
+ (**Replace**). In Replace mode, the first note you play on a new pass clears the earlier
+ passes, so playing a phrase again until it's right leaves only the latest take instead of
+ stacked copies. A pass you don't play on keeps the take, and notes that were already in the
+ clip stay. Switch with the Overdub / Replace cell next to Loop in the transport,
+ ⌘⇧R / Ctrl+Shift+R, or the Transport menu. A switch applies from the next pass, and Nota
+ remembers your choice. MCP: `set_loop_record_mode`, and `get_transport` reports the mode.
- **MCP `list_sections` and `set_sections`**: read and replace the arrangement's sections.
- **See MIDI notes while you record** (nota-daw/nota#56): a note now shows up in the take
the moment the key goes down and grows with the playhead while the key is held, instead
diff --git a/FEATURES.md b/FEATURES.md
index a5390ec4..af732581 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -80,7 +80,9 @@ JUCE module; the engine core is JUCE-free.
power of two), grid and quantization.
- **Tap tempo**: a TAP cell beside the BPM (and *Tap Tempo* in the command palette) sets the
tempo from tapped beats — mean of the last eight gaps, restarts on a pace change or a 3 s pause.
-- **Loop region** (on/off and range; Cmd/Ctrl+L loops the selection).
+- **Loop region** (on/off and range; Cmd/Ctrl+L loops the selection). Notes held across the
+ loop seam keep sounding and release tails ring into the next pass; an arpeggiator keeps its
+ pattern going across the seam.
- **Metronome** and **count-in** before recording (notes played on the count-in are recorded).
- **Transport shortcuts** (Space play/stop, Enter stop, R/M/A, clip copy-paste, typing
notes, undo/redo) work in detached windows too.
@@ -272,6 +274,12 @@ track count and closes with Escape.
routed ("MIDI In") input. Notes played on the count-in and keys already held when
recording starts are recorded where they started: the take's clip begins earlier to hold
them (at 1.1 the part before the song start is kept beyond the clip's left edge).
+- **Loop recording: Overdub / Replace** — with the loop on, **Overdub** adds every pass to the
+ MIDI take; **Replace** keeps only the latest pass you play on (a silent pass keeps the take,
+ notes already in the clip stay). Switched by the cell next to Loop in the transport,
+ Cmd/Ctrl+Shift+R or the Transport menu; applies from the next pass; remembered between
+ sessions. A note held across the loop seam is recorded as two notes, up to the loop end
+ and on from the loop start.
- **MPE (per-note expression)** — an MPE controller's notes each carry their own pitch
bend, pressure and slide (CC74): channels 2–16 are per-note (lower zone, ±48 semitones by
default; the controller's MPE Configuration and bend-range messages are honoured), channel 1
@@ -1056,7 +1064,8 @@ or Claude Code) write music directly in the open Nota project. Enable it in Pref
appears in the UI immediately.
Coverage:
-- **Transport**: play/stop, tempo, time signature, loop, metronome.
+- **Transport**: play/stop, tempo, time signature, loop, metronome, loop record mode
+ (`set_loop_record_mode`; `get_transport` reports it).
- **Project**: `get_overview` (a full snapshot); the arrangement's sections
(`list_sections`, `set_sections`); version history — `list_versions` (with what
each changed), `save_version` with a note, `switch_version`, `annotate_version` (name, note,
diff --git a/specs/018-loop-record-replace/checklists/requirements.md b/specs/018-loop-record-replace/checklists/requirements.md
new file mode 100644
index 00000000..42204616
--- /dev/null
+++ b/specs/018-loop-record-replace/checklists/requirements.md
@@ -0,0 +1,35 @@
+# Specification Quality Checklist: Loop record mode — Overdub / Replace
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-16
+**Feature**: [spec.md](../spec.md)
+
+## Content Quality
+
+- [x] No implementation details (languages, frameworks, APIs)
+- [x] Focused on user value and business needs
+- [x] Written for non-technical stakeholders
+- [x] All mandatory sections completed
+
+## Requirement Completeness
+
+- [x] No [NEEDS CLARIFICATION] markers remain
+- [x] Requirements are testable and unambiguous
+- [x] Success criteria are measurable
+- [x] Success criteria are technology-agnostic (no implementation details)
+- [x] All acceptance scenarios are defined
+- [x] Edge cases are identified
+- [x] Scope is clearly bounded
+- [x] Dependencies and assumptions identified
+
+## Feature Readiness
+
+- [x] All functional requirements have clear acceptance criteria
+- [x] User scenarios cover primary flows
+- [x] Feature meets measurable outcomes defined in Success Criteria
+- [x] No implementation details leak into specification
+
+## Notes
+
+- Q1–Q3 answered 2026-10-16 (see spec § Clarifications). All items pass.
+- The Nota Context section names code areas by design (template requirement). That is not counted as an implementation leak.
diff --git a/specs/018-loop-record-replace/contracts/c-abi.md b/specs/018-loop-record-replace/contracts/c-abi.md
new file mode 100644
index 00000000..b2a4f40a
--- /dev/null
+++ b/specs/018-loop-record-replace/contracts/c-abi.md
@@ -0,0 +1,27 @@
+# Contract: C ABI — loop record mode
+
+Added to `src/native/nota.engine/include/nota/nota_engine.h`, next to the count-in calls:
+
+```c
+/* Loop record mode for MIDI recorded into the Arrangement with the loop on:
+ * 0 = overdub (every pass adds to the take), 1 = replace (the first new note of a
+ * pass removes what earlier passes of this take recorded). App preference; takes
+ * effect from the next pass. Session slot recording is unaffected. */
+NOTA_API NotaResult nota_transport_set_loop_record_mode(NotaEngine* engine, int32_t mode);
+NOTA_API int32_t nota_transport_loop_record_mode(const NotaEngine* engine);
+```
+
+- `mode` outside {0, 1} → `NOTA_ERR_INVALID_ARG`. A null engine → `NOTA_ERR_INVALID_ARG` (setter) or 0 (getter).
+- Thread: any non-audio thread. Lock-free (an atomic store).
+
+Managed mirror (`IAudioEngine` / `NotaEngine`):
+
+```csharp
+void SetLoopRecordMode(bool replace);
+bool LoopRecordReplace { get; }
+```
+
+MCP (`TransportTools`):
+
+- `get_transport` → `TransportState` gains `bool LoopRecordReplace`.
+- `set_loop_record_mode(bool replace)`: sets the mode. The UI toggle and the persisted preference follow it.
diff --git a/specs/018-loop-record-replace/contracts/ui.md b/specs/018-loop-record-replace/contracts/ui.md
new file mode 100644
index 00000000..1a90978b
--- /dev/null
+++ b/specs/018-loop-record-replace/contracts/ui.md
@@ -0,0 +1,7 @@
+# Contract: UI — loop record mode
+
+- **Transport console**: a `cell` ToggleButton right after the Loop cell, inside the same recess. It shows the label **Overdub** when off and **Replace** when on. It uses the accent colour only when on (Studio: the accent is for what is chosen and non-default). Tooltip: "Loop recording: Overdub adds every pass · Replace keeps the latest pass (⌘⇧R)". Bound to `Transport.LoopRecordReplace`.
+- **Command**: `transport.loopRecordMode`, "Loop record: overdub / replace", category Transport, shortcut **⌘⇧R** (Ctrl+Shift+R on Windows/Linux through the existing mapping). It appears in the command palette and in Preferences → Shortcuts (nota-shortcuts skill).
+- **Menu**: Transport → "Loop record: overdub / replace" (sentence case per the design-token check), next to Loop, bound to the same command.
+- **Persistence**: `Settings.Current.LoopRecordReplace` is written on every change and restored at startup before the engine is used, the same way as `CountInBars`.
+- The control is enabled at all times. It does not change appearance with loop on or off, so the choice stays visible.
diff --git a/specs/018-loop-record-replace/data-model.md b/specs/018-loop-record-replace/data-model.md
new file mode 100644
index 00000000..f601cbe4
--- /dev/null
+++ b/specs/018-loop-record-replace/data-model.md
@@ -0,0 +1,39 @@
+# Data Model: Loop record mode — Overdub / Replace
+
+## LoopRecordMode (app preference)
+
+| Field | Type | Default | Notes |
+|-------|------|---------|-------|
+| `LoopRecordReplace` | bool | `false` (Overdub) | In `Settings` (app preferences, like `CountInBars`). Not saved in the project. |
+
+Engine mirror: `std::atomic<bool> loopRecordReplace_`. It is written on the message thread and latched by the audio thread at take start and at each wrap (`passReplace_`).
+
+## Pass (audio thread, per take)
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `recordPass_` | int32 | 0 at take start. +1 on each loop wrap while an Arrangement MIDI take records. |
+| `passReplace_` | bool | The mode latched for the current pass. |
+| `passTriggered_` | bool | A fresh note-on already fired the replace in this pass. |
+| `replaceUpTo_` | atomic int32 | Notes with `pass <` this value are to be removed. Monotonic within a take, published with release semantics. |
+
+## RecordedNote (audio → message queue)
+
+Gains `int32_t pass`: the pass in which the note (or its post-seam continuation) started.
+
+## Take bookkeeping (message thread)
+
+`takeNotes_`: a list of `{pitch, absStartBeat, pass}` for every note this take appended to the record clip. Cleared at take start. `appliedReplaceUpTo_` holds the last `replaceUpTo_` that was applied.
+
+### State transitions (one Arrangement MIDI take, loop on)
+
+```
+take start: pass=0, latch mode, replaceUpTo=0
+wrap: pass+=1, latch mode, triggered=false
+fresh note-on (record track / routed) && latched Replace && !triggered && pass>0:
+ replaceUpTo=pass (release), triggered=true
+Poll: read replaceUpTo (acquire) → drain queue → append → if replaceUpTo>applied:
+ remove takeNotes with pass<replaceUpTo from the clip, applied=replaceUpTo
+```
+
+Validation: Replace never touches notes that are absent from `takeNotes_` (FR-005). A pass without a fresh note-on never sets `replaceUpTo_` (FR-004).
diff --git a/specs/018-loop-record-replace/plan.md b/specs/018-loop-record-replace/plan.md
new file mode 100644
index 00000000..f8fdb2ef
--- /dev/null
+++ b/specs/018-loop-record-replace/plan.md
@@ -0,0 +1,112 @@
+# Implementation Plan: Loop record mode — Overdub / Replace
+
+**Branch**: `fix/loop-seam-note-cut` | **Date**: 2026-10-16 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `/specs/018-loop-record-replace/spec.md`
+
+## Summary
+
+Add an app-wide loop record mode, Overdub (the default, today's behaviour) or Replace, for MIDI
+recorded into the Arrangement with the loop on. The audio thread numbers the passes of a take at
+each loop wrap, tags every recorded note with its pass, and on the first fresh note of a new pass in
+Replace mode publishes "replace everything before this pass". The message thread then removes this
+take's earlier-pass notes from the record clip within the same undo step. The mode is switched by a
+transport toggle next to Loop, ⌘⇧R, a menu item and an MCP tool, and persists as an app preference.
+Design details: [research.md](research.md).
+
+## Nota: Read Before Planning
+
+Consult the matching source of truth before designing:
+
+- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): the AR rules table is binding (AR-4 lock-free queue, AR-5 immutable snapshots, AR-6 audio-thread restrictions, AR-7 pure C ABI, AR-9 `Transport` is the only source of musical time).
+- **UI work** → [`DESIGN.md`](../../DESIGN.md) (Studio design language) and the `nota-design` skill.
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md): licensing, dependency policy, PR expectations.
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 (Application, Infrastructure, Presentation, App, Mcp)
+
+**Primary Dependencies**: None new (Avalonia already used)
+
+**Storage**: App settings (`Settings.LoopRecordReplace`). Not stored in the project file.
+
+**Audio-Thread Impact**: Small and allocation-free. An `int pass` field on `RecordedNote` (fixed-size SPSC ring). A pass counter, a latched mode flag and a "triggered" flag as plain members. One atomic int (`replaceUpTo_`, release store) set at most once per pass. The mode crosses in as an atomic bool written by the message thread. Clip edits stay on the message thread via immutable snapshots (AR-5). No locks, no I/O (AR-6).
+
+**Testing**: `tests/Nota.SmokeTest` (new `LoopRecordModeTests.cs`, offline render through the C ABI), `scripts/build.sh`
+
+**Target Platform**: macOS, Windows, Linux desktop
+
+**Project Type**: Desktop app (native engine + managed UI)
+
+**Performance Goals**: The replace is visible within one UI tick (~33 ms) of the triggering key press. No audio glitch (SC-005).
+
+**Constraints**: AR-4/5/6/7. The take stays one undo step.
+
+**Scale/Scope**: Arrangement MIDI loop recording only. Session slots and audio punch are unchanged.
+
+## Constitution Check
+
+| Principle | Status |
+|-----------|--------|
+| I. Real-time audio safety | ✅ The audio thread only touches fixed-size state and atomics. Clip mutation happens on the message thread through a snapshot republish. |
+| II. Boundary discipline | ✅ Two new C ABI functions in `nota_engine.h` (contracts/c-abi.md). No JUCE. |
+| III. Licensing hygiene | ✅ The one new file (`LoopRecordModeTests.cs`) gets the SPDX header. No dependencies. |
+| IV. Verification gate | ✅ New smoke group covers every acceptance scenario (quickstart.md). `scripts/build.sh` must pass. |
+| V. One logical change per PR | ⚠️ It shares a branch with the seam bug fix at the user's request ("close the issue in one go"). Separate commits keep the two reviewable. |
+| VI. Docs in sync | ✅ CHANGELOG `[Unreleased] → Added`. nota-features, nota-shortcuts (⌘⇧R) and nota-docs (recording page) are planned in tasks. |
+| VII. Spec-first | ✅ Spec, clarifications, plan, tasks. |
+| VIII. Safety rules not weakened | ✅ |
+
+Post-design re-check: unchanged, all gates pass. The V deviation is recorded under Complexity Tracking.
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/018-loop-record-replace/
+├── plan.md
+├── research.md
+├── data-model.md
+├── quickstart.md
+├── contracts/
+│ ├── c-abi.md
+│ └── ui.md
+├── checklists/requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code (repository root)
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # + set/get loop record mode
+└── src/
+ ├── Engine.h # RecordedNote.pass; pass/replace state; takeNotes_
+ ├── Engine_Render.cpp # onLoopWrap: pass++ & latch; drainLiveMidi/captureRoutedNotes: tag pass, trigger; collectRecorded: apply replace
+ ├── Engine_Recording.cpp # setRecording: reset pass state, clear takeNotes_
+ └── nota_engine_core.cpp # ABI shims
+src/managed/
+├── Nota.Application/
+│ ├── Engine/IAudioEngine.cs # SetLoopRecordMode / LoopRecordReplace
+│ ├── Settings.cs # LoopRecordReplace (default false)
+│ └── Palette/CommandCatalog.cs # transport.loopRecordMode, ⌘⇧R
+├── Nota.Infrastructure/Interop/ # NativeMethods + NotaEngine wrappers
+├── Nota.Presentation/ViewModels/TransportViewModel.cs # LoopRecordReplace property → engine
+├── Nota.App/
+│ ├── MainWindow.axaml # transport cell + menu item
+│ ├── MainWindow.axaml.cs # restore from settings, persist on change
+│ └── MainWindow.Commands.cs # bind the command
+└── Nota.Mcp/Tools/TransportTools.cs # get_transport field, set_loop_record_mode
+tests/Nota.SmokeTest/
+├── LoopRecordModeTests.cs # new
+└── Program.cs # register group
+```
+
+**Structure Decision**: Follow the existing count-in path end to end (engine atomic → C ABI → `IAudioEngine` → `TransportViewModel` → `Settings` and the transport console), plus pass bookkeeping in the existing recording path.
+
+## Complexity Tracking
+
+| Violation | Why Needed | Simpler Alternative Rejected Because |
+|-----------|------------|-------------------------------------|
+| Two logical changes on one branch (seam fix + this feature) | The user asked to close nota-daw/nota#29 in one branch | Two branches would split one issue across PRs, against the user's request. Mitigation: separate commits. |
diff --git a/specs/018-loop-record-replace/quickstart.md b/specs/018-loop-record-replace/quickstart.md
new file mode 100644
index 00000000..ed7da2f7
--- /dev/null
+++ b/specs/018-loop-record-replace/quickstart.md
@@ -0,0 +1,27 @@
+# Quickstart: validate loop record mode
+
+## Automated (PR gate)
+
+```bash
+scripts/build.sh
+```
+
+The `-- loop record mode --` smoke group in `tests/Nota.SmokeTest/LoopRecordModeTests.cs` drives the engine through the C ABI on a 1-bar loop at 120 BPM:
+
+| Scenario | Expected |
+|----------|----------|
+| Overdub, a different pitch on each of 3 passes | All 3 pitches in the take (SC-002) |
+| Replace, the same phrase on 5 passes with jittered timing | Exactly one phrase's notes (SC-001) |
+| Replace, play on pass 1, silent pass 2, stop | Pass-1 notes kept (FR-004) |
+| Replace, recording into a clip with existing notes | The existing notes are kept (FR-005) |
+| Replace, a note held across the seam, then a fresh note | The head is removed with the old pass; the continuation and the fresh note stay |
+| Switch Overdub → Replace mid-pass | Takes effect from the next pass (FR-007) |
+| Replace, routed MIDI | Same as live |
+| Mode get/set through the ABI, invalid value | Round-trips; 2 → `NOTA_ERR_INVALID_ARG` |
+
+## Manual (in the app)
+
+1. Loop one bar, arm a Volt track, click **Overdub** in the transport so it reads **Replace** (or press ⌘⇧R).
+2. Record and play a phrase three times, varying the timing, then stop. The clip holds one phrase.
+3. Press ⌘⇧R (it reads **Overdub**), record kick, snare and hats on three passes. All three stay.
+4. Quit and relaunch. The mode is as you left it.
diff --git a/specs/018-loop-record-replace/research.md b/specs/018-loop-record-replace/research.md
new file mode 100644
index 00000000..2fbd6c6f
--- /dev/null
+++ b/specs/018-loop-record-replace/research.md
@@ -0,0 +1,43 @@
+# Research: Loop record mode — Overdub / Replace
+
+## R1 — Where a "pass" is known
+
+- **Decision**: The audio thread counts passes. `Engine::onLoopWrap` (added by the seam fix) increments `recordPass_` while an Arrangement MIDI take is recording. Every `RecordedNote` carries the `pass` it started in.
+- **Rationale**: The wrap happens on the audio thread, block-accurately, and `onLoopWrap` already splits held notes there. The head of a split note keeps the old pass, and the continuation (restarted at the loop start) gets the new pass. That is exactly spec AS-1.3.
+- **Alternatives**: Derive the pass on the message thread from note start beats plus the loop length. Rejected: a pass is a time span, not a beat range (beats repeat every pass), so start beats cannot tell passes apart.
+
+## R2 — What triggers a replace
+
+- **Decision**: The trigger is a *fresh* note-on of the take (live keyboard on the record track, or routed MIDI captured into it) whose pass is greater than the last replaced pass, while the pass's latched mode is Replace. It sets `replaceUpTo_` (an atomic with release semantics) to that pass. The continuation of a note held across the seam is not a fresh note-on, so it does not trigger.
+- **Rationale**: Clarification Q1 says whole earlier passes are removed at the first note of the new pass. FR-004 says a silent pass removes nothing. If a held continuation triggered the replace, holding a final chord over the seam would wipe the pass that chord belongs to.
+- **Alternatives**: Trigger on the first *released* note. Rejected because the removal would lag the press by the note's length, and FR-010 wants the take view to update as you play.
+
+## R3 — Mode switch timing
+
+- **Decision**: The message thread writes the mode to an atomic (`loopRecordReplace_`). The audio thread latches it into `passReplace_` at take start and at every wrap. Triggers use the latched value.
+- **Rationale**: FR-007 says a switch applies from the next pass. Latching at the wrap gives that with one relaxed load per wrap.
+
+## R4 — Removing earlier passes on the message thread
+
+- **Decision**: `collectRecorded` (message thread, `Poll`) first loads `replaceUpTo_` with acquire semantics, then drains `recorded_`, so every note of an earlier pass that was pushed before the trigger is already in the batch. It appends the batch. Then, if `replaceUpTo_` has grown, it removes from the take clip each note recorded by this take with `pass < replaceUpTo_`, and drops any late arrival with `pass < replaceUpTo_`. The take's notes are tracked in a message-thread list `takeNotes_` of `{pitch, absStartBeat, pass}`. Clip notes are matched by pitch and absolute start (ε = 1e-6 beat), so the matching survives the clip's left edge moving (count-in pickups) and other notes being reordered.
+- **Rationale**: FR-005 says notes in the clip before the take must stay. Matching by identity (not by index) keeps those notes untouched. The edit goes through the same `republishWithTrackRaw` as the growing take, so the whole take stays one undo step (spec edge case) and stays AR-5 compliant: an immutable snapshot published from the message thread.
+- **Alternatives**: A parallel per-index pass array. Rejected because it is fragile when the clip shifts or the user edits notes during recording.
+
+## R5 — Held-note preview
+
+- **Decision**: No change to the snapshot ABI. The preview shows held (pending) notes, and those always belong to the current pass. The replaced notes disappear when the next `Poll` republishes the clip, at most one UI tick (~33 ms) after the trigger.
+
+## R6 — Scope boundaries
+
+- Session slot recording (`recordSlotPlayer_` set) never counts passes and never replaces (spec edge case).
+- Loop off: there are no wraps, so `recordPass_` stays 0 and nothing is ever replaced.
+- Audio loop punch is unchanged.
+
+## R7 — UI and shortcut
+
+- **Decision**: A `cell` ToggleButton in the transport console, right after the Loop cell, labelled **Overdub** / **Replace** (sentence case, per DESIGN.md). The accent shows only while it reads Replace, since Overdub is the default resting state. A new command `transport.loopRecordMode`, "Loop record: overdub / replace", bound to **⌘⇧R** (free in `CommandCatalog`: ⌘R is Record, and the shift variant reads as "record mode"). A menu item goes under Transport next to Loop and Metronome. The setting persists as `Settings.LoopRecordReplace` (bool, default false), mirroring `CountInBars`.
+- **Alternatives**: The right-click menu on Record (Q3 option B) and menu-only (Q3 option C) were rejected by the user.
+
+## R8 — MCP
+
+- **Decision**: `get_transport` gains `LoopRecordReplace`. A new tool `set_loop_record_mode(replace: bool)` sets the engine and the app setting through the same transport view-model path the UI uses (FR-012).
diff --git a/specs/018-loop-record-replace/spec.md b/specs/018-loop-record-replace/spec.md
new file mode 100644
index 00000000..5e9f0b77
--- /dev/null
+++ b/specs/018-loop-record-replace/spec.md
@@ -0,0 +1,154 @@
+# Feature Specification: Loop record mode — Overdub / Replace
+
+**Feature Branch**: `fix/loop-seam-note-cut`
+
+**Created**: 2026-10-16
+
+**Status**: Clarified
+
+**Input**: User description: "Loop-record mode toggle, Overdub / Replace (nota-daw/nota#29, the second half of the issue). Today, when MIDI is recorded with the Arrangement transport loop on, every pass overdubs into the same take, so playing the same phrase on each pass stacks the notes at slightly different timings. Add a loop-record mode: Overdub (today's behaviour: each pass adds to the take) and Replace (each new pass replaces what earlier passes of this take recorded in the loop region, so only the latest pass remains). It should be quick to switch: the reporter asks for "a shortcut or an easy button" because some people want overdub. The seam bug (notes cut at the loop seam, a note held across the seam) is already fixed on this branch (.specify/bugs/loop-seam-note-cut) and is out of scope."
+
+## Nota Context *(fill in — drives plan and tasks)*
+
+**Feature area** *(pick the main one)*:
+
+- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table
+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation
+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)
+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:
+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),
+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR
+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),
+[`FEATURES.md`](../../FEATURES.md).
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Re-record a loop until it's right (Priority: P1)
+
+A player loops one bar and records MIDI. They play the phrase, don't like it, and play it again on
+the next pass, and again, until it's right. In Replace mode, each new pass that they actually play
+on takes the place of what earlier passes of this take recorded. When they stop, the take holds
+only the latest pass, not several near-identical phrases stacked a few milliseconds apart.
+
+**Why this priority**: This is the reported problem (#29). Without it, looping a bar to practise
+and record a part leaves a smeared, doubled take that has to be cleaned up by hand.
+
+**Independent Test**: Turn on the loop over 1 bar, choose Replace, and record. Play the same
+4-note phrase on three passes with slightly different timing, then stop. The take contains exactly
+the 4 notes of the last pass.
+
+**Acceptance Scenarios**:
+
+1. **Given** Replace mode, a 1-bar loop and Record on, **When** the player plays a phrase on pass 1 and a different phrase on pass 2, **Then** after stopping the take contains only the pass-2 notes.
+2. **Given** Replace mode, **When** the player plays on pass 1 and plays nothing on pass 2, **Then** pass 1's notes remain (a silent pass does not wipe the take).
+3. **Given** Replace mode and a note held across the loop seam (split into two notes by the seam fix), **When** the player then plays on the following pass, **Then** the split note is treated consistently: the continuation that started the new pass belongs to that pass.
+
+---
+
+### User Story 2 - Keep overdubbing when that's the intent (Priority: P1)
+
+A player builds a drum pattern on a loop: kick on pass 1, snare on pass 2, hats on pass 3. In
+Overdub mode every pass adds to the take, exactly as today.
+
+**Why this priority**: The reporter stresses that some people rely on overdubbing. Changing the
+behaviour without a way back would break their workflow.
+
+**Independent Test**: Choose Overdub, loop 1 bar, and record a different pitch on each of three
+passes. After stopping, the take holds all three.
+
+**Acceptance Scenarios**:
+
+1. **Given** Overdub mode, **When** the player records on three passes, **Then** the take holds every note from every pass (today's behaviour, unchanged).
+
+---
+
+### User Story 3 - Switch quickly, even while recording (Priority: P2)
+
+The player switches between Overdub and Replace with one click or a keyboard shortcut, without
+opening Preferences. The current mode is visible near the transport, and the choice is remembered
+next time.
+
+**Why this priority**: The reporter asked for "a shortcut or an easy button". If the mode is buried,
+people won't find it or will forget which one is on.
+
+**Independent Test**: Press the shortcut. The visible mode indicator flips, and the next recorded
+pass follows the new mode. Restart the app and the mode is the same.
+
+**Acceptance Scenarios**:
+
+1. **Given** the app is open, **When** the player presses the loop-record-mode shortcut or clicks the control, **Then** the mode toggles and the control shows the new mode.
+2. **Given** a take is being recorded in a loop, **When** the player switches the mode, **Then** the switch applies from the next pass on. Notes already recorded are not touched at the moment of switching.
+3. **Given** the player chose a mode, **When** they quit and reopen Nota, **Then** the same mode is active.
+
+### Edge Cases
+
+- Loop off: the mode has no effect, and recording is linear as today.
+- Session slot recording: it has its own overdub-into-slot behaviour and is out of scope. The mode applies to Arrangement loop recording only.
+- Recording into an existing clip that already holds notes inside the loop: Replace only removes notes recorded by earlier passes of the current take. Notes that were in the clip before Record was pressed are kept (the existing record-onto-a-clip rules apply).
+- Pickup notes played on the count-in before the loop start belong to the first pass.
+- Routed MIDI ("MIDI In" from another track) follows the same mode as the live keyboard.
+- Undo after a take recorded in Replace mode undoes the whole take in one step, as today. Replaced passes are not recoverable one by one.
+- Switching the mode while the loop is off, or while not recording, just changes the setting.
+
+## Clarifications
+
+### Session 2026-10-16
+
+- Q: What does a new pass replace in Replace mode? → A: The whole earlier passes of this take, removed at the first note of the new pass. A pass with no notes changes nothing.
+- Q: Default mode on a new install? → A: Overdub (today's behaviour).
+- Q: Where is the mode switched? → A: A toggle in the transport console next to Loop (always visible), plus a menu item and a keyboard shortcut.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: Nota MUST offer a loop record mode with two values, **Overdub** and **Replace**, that applies to MIDI recorded into the Arrangement while the transport loop is on.
+- **FR-002**: In **Overdub**, every pass MUST add its notes to the take (today's behaviour).
+- **FR-003**: In **Replace**, a new pass on which the player plays at least one note MUST remove the notes that earlier passes of the same take recorded inside the loop region, so the take ends with only the latest played pass. The removal happens at the first note of the new pass and covers whole earlier passes, not just the time range played.
+- **FR-004**: A pass on which the player plays no notes MUST NOT remove anything.
+- **FR-005**: Replace MUST NOT remove notes that were in the clip before the take started, and MUST NOT touch other tracks or clips.
+- **FR-006**: The player MUST be able to switch the mode with a single visible control near the transport and with a keyboard shortcut, while stopped, playing or recording. The control is a small Overdub/Replace toggle in the transport console next to Loop, always visible, plus a menu item and a shortcut.
+- **FR-007**: A switch made while recording MUST take effect from the next pass and MUST NOT alter notes already recorded.
+- **FR-008**: The current mode MUST be visible at a glance, and MUST persist across app restarts as an app preference, like count-in.
+- **FR-009**: The default mode for a new install MUST be **Overdub** (today's behaviour).
+- **FR-010**: The live preview of held notes (the growing note while a key is down) MUST stay consistent with the mode. In Replace, the replaced notes disappear from the take view when they are removed.
+- **FR-011**: The shortcut and control MUST appear in Preferences → Shortcuts and in the app's menu next to Loop and Metronome.
+- **FR-012**: The mode MUST be readable and settable by MCP tools that already control the transport, so agents see the same state.
+
+### Key Entities
+
+- **Loop record mode**: An app preference with two values (Overdub, Replace) that controls how successive loop passes of one MIDI take combine.
+- **Pass**: One trip of the playhead through the loop region during a take. Notes are attributed to the pass in which they start. A note held across the seam has its continuation attributed to the new pass.
+- **Take**: The MIDI recorded between pressing Record and stopping. It is one undo step.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: In Replace mode, after recording the same phrase on 5 passes of a 1-bar loop, the take contains exactly the note count of one phrase (0 duplicates), compared with 5× today.
+- **SC-002**: In Overdub mode, the recorded result is identical to today's for the same input (no behaviour change for overdub users).
+- **SC-003**: Switching the mode takes one action (one click or one key press) from any state, with no dialog.
+- **SC-004**: The mode survives an app restart in 100% of cases.
+- **SC-005**: No audible glitch or dropout when a pass replaces earlier notes. The audio keeps playing without a gap at the moment of replacement.
+
+## Assumptions
+
+- The issue reporter's "toggle" means a two-state mode, not take lanes or comping (multiple stored takes per pass). Take lanes are out of scope.
+- The mode is a global app preference, not stored per project or per track, mirroring count-in.
+- Audio recording in a loop (loop punch) already keeps only the latest pass and is unchanged.
+- The seam fix on this branch (notes split at the seam, voices not cut) is in place and is relied on.
+- Session slot recording keeps its own overdub behaviour.
+
+## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*
+
+- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)
+- [x] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned
+- [x] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5)
+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`
+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`
+- [x] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)
+- [x] UI change → follows `DESIGN.md` (Studio design language)
diff --git a/specs/018-loop-record-replace/tasks.md b/specs/018-loop-record-replace/tasks.md
new file mode 100644
index 00000000..e72bc8cc
--- /dev/null
+++ b/specs/018-loop-record-replace/tasks.md
@@ -0,0 +1,122 @@
+---
+description: "Tasks for loop record mode — Overdub / Replace"
+---
+
+# Tasks: Loop record mode — Overdub / Replace
+
+**Input**: Design documents from `/specs/018-loop-record-replace/`
+
+**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/, quickstart.md
+
+**Tests**: Included. Constitution IV requires the smoke test to cover any engine behaviour change.
+
+**Organization**: Grouped by user story. US1 (Replace) and US2 (Overdub unchanged) share the engine foundation. US3 is the switch, persistence and surfaces.
+
+## Format: `[ID] [P?] [Story] Description`
+
+## Phase 1: Setup
+
+- [X] T001 Create `tests/Nota.SmokeTest/LoopRecordModeTests.cs` with the two-line SPDX header, a `Run()` that yields the groups below, and the helpers copied from `LoopSeamTests.cs` (`Beats`, `Looped`, `Notes`). Register it as `-- loop record mode --` in `tests/Nota.SmokeTest/Program.cs`, both in the full run (after loop seam) and in the `--live-record` block.
+
+---
+
+## Phase 2: Foundational (engine + ABI)
+
+**⚠️ Blocks US1–US3**
+
+- [X] T002 Add `int32_t pass` to `RecordedNote` in `src/native/nota.engine/src/Engine.h`. Update every construction site in `src/native/nota.engine/src/Engine_Render.cpp` (`drainLiveMidi`, `captureRoutedNotes`, `onLoopWrap`'s split lambda) to pass `recordPass_`. In `onLoopWrap` the head gets the old pass and the continuation the new one.
+- [X] T003 Add the mode and pass state to `src/native/nota.engine/src/Engine.h`: `std::atomic<bool> loopRecordReplace_{false}` with `setLoopRecordReplace(bool)` / `loopRecordReplace()`, audio-thread `int32_t recordPass_ = 0; bool passReplace_ = false; bool passTriggered_ = false;`, `std::atomic<int32_t> replaceUpTo_{0}`, and message-thread `struct TakeNote { int32_t pitch; double absStart; int32_t pass; }; std::vector<TakeNote> takeNotes_; int32_t appliedReplaceUpTo_ = 0;`.
+- [X] T004 Reset the pass state on the audio thread when a take starts. In `drainLiveMidi` (`src/native/nota.engine/src/Engine_Render.cpp`), on `takeStarted` set `recordPass_ = 0`, `passTriggered_ = false`, `passReplace_ = loopRecordReplace_.load(relaxed)`, `replaceUpTo_.store(0, release)`. In `Engine::setRecording(true)` (`src/native/nota.engine/src/Engine_Recording.cpp`) clear `takeNotes_` and set `appliedReplaceUpTo_ = 0` before `recording_` goes true.
+- [X] T005 In `Engine::onLoopWrap` (`src/native/nota.engine/src/Engine_Render.cpp`), for an Arrangement take only (recording, no `recordSlotPlayer_`), after the split: `++recordPass_`, `passTriggered_ = false`, `passReplace_ = loopRecordReplace_.load(relaxed)`.
+- [X] T006 [P] Add the C ABI per `specs/018-loop-record-replace/contracts/c-abi.md`. Declare `nota_transport_set_loop_record_mode` and `nota_transport_loop_record_mode` in `src/native/nota.engine/include/nota/nota_engine.h` next to the count-in calls, and implement them in `src/native/nota.engine/src/nota_engine_core.cpp` ("mode outside {0, 1} → NOTA_ERR_INVALID_ARG").
+- [X] T007 [P] Add the managed mirror. `SetLoopRecordMode(bool replace)` and `bool LoopRecordReplace { get; }` go in `src/managed/Nota.Application/Engine/IAudioEngine.cs`. P/Invokes go in `src/managed/Nota.Infrastructure/Interop/NativeMethods.cs`, and wrappers in `src/managed/Nota.Infrastructure/Interop/NotaEngine.cs`. Implement it in any other `IAudioEngine` implementers or fakes (grep `SetCountIn(` to find them).
+
+**Checkpoint**: Builds. Recording behaves exactly as before (no trigger yet).
+
+---
+
+## Phase 3: User Story 1 — Re-record a loop until it's right (P1) 🎯 MVP
+
+**Goal**: In Replace, the first fresh note of a new pass removes this take's earlier passes.
+
+**Independent test**: quickstart.md rows "Replace, same phrase on 5 passes", "silent pass", "existing clip notes", "held across seam", "routed".
+
+- [X] T008 [US1] Trigger on the audio thread (`src/native/nota.engine/src/Engine_Render.cpp`). In `drainLiveMidi`, where a recorded live note-on sets `pendingActive_`, and in `captureRoutedNotes` on a routed note-on, when `!recordSlotPlayer_` and `passReplace_ && !passTriggered_ && recordPass_ > 0`: `replaceUpTo_.store(recordPass_, release); passTriggered_ = true;`. The seam continuation in `onLoopWrap` must not trigger.
+- [X] T009 [US1] Apply on the message thread in `collectRecorded` (`src/native/nota.engine/src/Engine_Render.cpp`). Load `replaceUpTo_` with acquire **before** draining `recorded_`. In the Arrangement branch, skip batch notes with `pass < replaceUpTo` and push `{pitch, absStart, pass}` to `takeNotes_` for each appended note. Then, if `replaceUpTo > appliedReplaceUpTo_`, erase from `clip.notes` every note matching a `takeNotes_` entry with `pass < replaceUpTo` (same pitch, `|clip.startBeat + n.startBeat − absStart| < 1e-6`), drop those entries, and set `appliedReplaceUpTo_`. Also handle a batch that is empty but has a pending replace (don't early-return before applying), and publish via `republishWithTrackRaw` (same undo step). Session-slot branch: unchanged.
+- [X] T010 [US1] Smoke tests in `tests/Nota.SmokeTest/LoopRecordModeTests.cs` (mode set via the new ABI, 1-bar loop at 120 BPM):
+ - (a) Replace, the same 4-note phrase on 5 passes with ±0.03-beat jitter → exactly 4 notes, all from the last pass.
+ - (b) Replace, play on pass 1, nothing on pass 2, stop → pass-1 notes kept.
+ - (c) Replace into an existing clip that holds a note at beat 2.0 → that note survives.
+ - (d) Replace, hold a key 3.5 → seam → 0.5, then a fresh note at 1.0 on the same pass → the head `3.5+0.5` is gone, while `0.0+0.5` and the fresh note stay. A further fresh note on the next pass removes them.
+ - (e) Replace with routed MIDI (`SetTrackMidiSource` + `TrackNoteOn` on the source) → same result as (a) with 3 passes.
+
+**Checkpoint**: US1 works headless.
+
+---
+
+## Phase 4: User Story 2 — Keep overdubbing (P1)
+
+**Goal**: Overdub is unchanged and is the default.
+
+- [X] T011 [US2] Smoke tests in `tests/Nota.SmokeTest/LoopRecordModeTests.cs`:
+ - (f) default mode on a fresh engine reads overdub (`LoopRecordReplace == false`).
+ - (g) Overdub, a different pitch on each of 3 passes → all 3 pitches present.
+ - (h) the ABI round-trip works, and an invalid mode (2) returns an error (call the `NativeMethods` entry directly, or check that the wrapper throws).
+
+---
+
+## Phase 5: User Story 3 — Switch quickly, even while recording (P2)
+
+**Goal**: One click or ⌘⇧R toggles the mode. The mode is visible, persisted and reachable from MCP. A mid-take switch applies from the next pass.
+
+- [X] T012 [US3] Smoke test (i) in `tests/Nota.SmokeTest/LoopRecordModeTests.cs`: start in Overdub, play on pass 1, switch to Replace during pass 2 after playing a note in it, play on pass 3. Expected: pass-1 and pass-2 notes are removed only at pass 3's first note, and the pass-2 note did not trigger a replace when played.
+- [X] T013 [P] [US3] Add `public bool LoopRecordReplace { get; set; }` (default `false`) to `src/managed/Nota.Application/Settings.cs`, next to `CountInBars`, with a doc comment.
+- [X] T014 [US3] Add `[ObservableProperty] private bool _loopRecordReplace;` to `src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs`, with `partial void OnLoopRecordReplaceChanged(bool value) => _engine.SetLoopRecordMode(value);` and a `ToggleLoopRecordMode` relay command. Also add a `LoopRecordModeText` ("Overdub"/"Replace") if the cell needs a bound label.
+- [X] T015 [US3] Restore and persist in `src/managed/Nota.App/MainWindow.axaml.cs`: set `vm.Transport.LoopRecordReplace = vm.Settings.Current.LoopRecordReplace` where `CountInBars` is restored (~line 347), and write it back plus save on change (subscribe to `PropertyChanged`, the same way other transport preferences are saved; find how `Settings` is saved).
+- [X] T016 [US3] Add the transport console cell to `src/managed/Nota.App/MainWindow.axaml` right after the Loop cell, per `specs/018-loop-record-replace/contracts/ui.md`: a `ToggleButton Classes="cell"` bound to `Transport.LoopRecordReplace`, labelled Overdub/Replace, with the tooltip from the contract. Follow DESIGN.md / the nota-design skill. Add a separator if the Loop group uses one.
+- [X] T017 [US3] Add the command `C("transport.loopRecordMode", "Loop record: overdub / replace", "Transport", "⌘⇧R", "overdub replace take pass")` to `src/managed/Nota.Application/Palette/CommandCatalog.cs`. Bind it in `src/managed/Nota.App/MainWindow.Commands.cs` (`B("transport.loopRecordMode", ...)` toggling `Transport.LoopRecordReplace`). Check that ⌘⇧R is not handled elsewhere in `src/managed/Nota.App/MainWindow.Input.cs`.
+- [X] T018 [US3] Add the menu item `<NativeMenuItem Header="Loop Record: Replace" app:Commands.Id="transport.loopRecordMode"/>` under Transport in `src/managed/Nota.App/MainWindow.axaml`, next to Loop and Metronome, with a check state if other toggle items show one.
+- [X] T019 [P] [US3] MCP in `src/managed/Nota.Mcp/Tools/TransportTools.cs`: add `bool LoopRecordReplace` to `TransportState` / `get_transport`, and add a `set_loop_record_mode(bool replace)` tool. Route it through the same state the UI uses (view-model or engine plus settings) so the toggle reflects it. Update any MCP tool listing or test that enumerates tools (grep `set_metronome` in `tests/`).
+
+**Checkpoint**: The UI toggle, shortcut, menu, MCP and persistence all work.
+
+---
+
+## Phase 6: Polish & cross-cutting
+
+- [X] T020 Add a `CHANGELOG.md` `[Unreleased] → Added` entry: "Loop recording: Overdub or Replace (nota-daw/nota#29)".
+- [X] T021 Run the nota-shortcuts skill (Preferences → Shortcuts list gains ⌘⇧R), the nota-features skill (FEATURES.md), and the nota-docs skill (recording page, EN + RU).
+- [X] T022 Run `scripts/build.sh`. It must pass, including the new `-- loop record mode --` group.
+- [X] T023 Verify the UI headless or in the app per the "Nota UI verify recipe" memory: the transport cell renders in both states in Studio Dark and Light, and ⌘⇧R toggles it.
+- [X] T024 Re-check the Nota Compliance Checklist in `specs/018-loop-record-replace/spec.md` and run `/speckit-converge`.
+- [X] T025 Commit on `fix/loop-seam-note-cut` as `Egor Khindikaynen <[email protected]>`, with no Co-Authored-By, separately from the seam-fix commit.
+
+## Dependencies
+
+- T001 → T010–T012 (test file).
+- T002–T005 (engine state) → T008–T009 → T010.
+- T006 → T007 → T010–T019 (tests and the app use the ABI).
+- US1 (T008–T010) and US2 (T011) are independent once Phase 2 is done.
+- US3 UI (T013–T018) depends only on T007. T012 depends on T008–T009.
+- Polish depends on everything.
+
+## Parallel opportunities
+
+- T006 ∥ T002–T005 (different files). T007 after T006.
+- T013 ∥ T019 ∥ T017 (different files) once T007 is done.
+
+## Implementation strategy
+
+MVP = Phase 2 + US1 (Replace works headless and is tested). Then US2 (guard rails), then US3 (surfaces), then polish. One commit at the end, per the user's workflow.
+
+## Implementation notes (2026-10-16)
+
+- T011 (h): the managed wrapper takes a `bool`, so a test cannot pass an out-of-range mode. The C ABI rejects modes outside {0, 1}, as the code shows. The smoke test covers the default and the set/get round-trip.
+- T016 / T018: the toggle label sizes to the longer word ("Overdub") so the transport bar doesn't shift between states. The menu item reads **Loop record: overdub / replace**, a plain command, because the design-token check requires sentence case. It is not a check item. The cell also joins the transport's narrow-width shed order (`MainWindow.TransportFit.cs`), and is shed before Loop.
+- T019: MCP sets the engine directly, as `set_metronome` does. `TransportViewModel.Tick` follows the engine's mode, so the toggle and the saved preference update either way.
+- T023: verified headless (`/tmp/loopmodeharness`). Clicking the toggle, ⌘⇧R, and the MCP/engine path all update the engine, the VM, the label and the saved preference. Plain ⌘R still records. The cell is 58 px in both states. Screenshots were taken in Studio Dark and Light, and the setting survived a restart. The Shortcuts pane lists ⌘⇧R.
+
+## Phase 7: Convergence
+
+- [X] T026 When `collectRecorded` (src/native/nota.engine/src/Engine_Render.cpp) removes earlier-pass notes in Replace mode, release their voices: queue an audio-thread command (AR-4, allocation-free) carrying the record track id and the removed pitches. In the next block, before rendering, inject note-offs for those pitches into that track's MIDI (through its MIDI FX, like the seam offs), skipping any pitch the player is holding live on that track right now. Do not route it through `trackNoteOff`, which would end a note being recorded. Per SC-005 / FR-003 (contradicts).
+- [X] T027 Add a smoke test to tests/Nota.SmokeTest/LoopRecordModeTests.cs: Replace, a long note on pass 0 (0.1 → 3.6), polled so it plays back on pass 1, then a fresh note on pass 1 while it sounds → after release, a pass with no notes in the take is silent (rms < 1e-4). Run the same scenario in Overdub as a control: it still sounds. Per SC-005 / Constitution IV (missing).
diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.cs
index 7a228339..546f866c 100644
--- a/src/managed/Nota.App/MainWindow.Commands.cs
+++ b/src/managed/Nota.App/MainWindow.Commands.cs
@@ -94,6 +94,7 @@ public partial class MainWindow
B("transport.record", () => OnMenuRecord(this, e));
B("transport.loop", () => OnMenuLoop(this, e));
B("transport.metronome", () => OnMenuMetronome(this, e));
+ B("transport.loopRecordMode", () => { if (_vm is not null) _vm.Transport.LoopRecordReplace = !_vm.Transport.LoopRecordReplace; });
B("transport.tapTempo", TapTempoBeat);
// ---- Track
diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.cs
index a973ee5a..32096398 100644
--- a/src/managed/Nota.App/MainWindow.Input.cs
+++ b/src/managed/Nota.App/MainWindow.Input.cs
@@ -194,6 +194,13 @@ public partial class MainWindow
e.Handled = true; // an auto-repeat is swallowed, not passed on to the menu
return;
}
+ // ⌘⇧R / ⌃⇧R: loop record mode, Overdub ↔ Replace.
+ if (mod && e.Key == Key.R && (e.KeyModifiers & KeyModifiers.Shift) != 0 && (e.KeyModifiers & KeyModifiers.Alt) == 0)
+ {
+ if (_heldKeys.Add(e.Key)) _commands.Run("transport.loopRecordMode");
+ e.Handled = true;
+ return;
+ }
if (plainMod && e.Key == Key.M)
{
if (_heldKeys.Add(e.Key)) _commands.Run("transport.metronome");
diff --git a/src/managed/Nota.App/MainWindow.TransportFit.cs b/src/managed/Nota.App/MainWindow.TransportFit.cs
index 3969ade8..d9a9e837 100644
--- a/src/managed/Nota.App/MainWindow.TransportFit.cs
+++ b/src/managed/Nota.App/MainWindow.TransportFit.cs
@@ -36,6 +36,7 @@ public partial class MainWindow
new Control[] { RemotePanel }, // MIDI learn (the panel goes with its last chip)
new Control[] { SnapChip }, // the grid; snapping itself stays switchable
new Control[] { SnapToggle }, // hold Alt to drag freely
+ new Control[] { LoopRecordCell }, // ⌘⇧R / Transport menu
new Control[] { LoopSep, LoopCell }, // ⌘L; the range stays visible on the ruler
new Control[] { MasterWell }, // the master strip is in the mixer
};
diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axaml
index d43f0c0d..6ee1aa77 100644
--- a/src/managed/Nota.App/MainWindow.axaml
+++ b/src/managed/Nota.App/MainWindow.axaml
@@ -98,6 +98,7 @@
<NativeMenuItem Header="Play / stop" app:Commands.Id="transport.playStop"/>
<NativeMenuItem Header="Record" app:Commands.Id="transport.record"/>
<NativeMenuItem Header="Loop" app:Commands.Id="transport.loop"/>
+ <NativeMenuItem Header="Loop record: overdub / replace" app:Commands.Id="transport.loopRecordMode"/>
<NativeMenuItem Header="Metronome" app:Commands.Id="transport.metronome"/>
</NativeMenu>
</NativeMenuItem.Menu>
@@ -216,6 +217,18 @@
Foreground="{Binding $parent[ToggleButton].Foreground}"/>
</StackPanel>
</ToggleButton>
+ <!-- Loop record mode: Overdub (rests neutral) or Replace (lit, the non-default choice) -->
+ <ToggleButton x:Name="LoopRecordCell" Classes="cell" Height="22" IsChecked="{Binding Transport.LoopRecordReplace}"
+ ToolTip.Tip="Loop recording: Overdub adds every pass · Replace keeps the latest pass (⌘⇧R)">
+ <Panel>
+ <!-- Sizer: the cell keeps the longer label's width in both states, so the bar doesn't shift -->
+ <TextBlock Classes="CellLabel" Text="Overdub" Opacity="0" VerticalAlignment="Center"/>
+ <TextBlock Classes="CellLabel" Text="Overdub" VerticalAlignment="Center" HorizontalAlignment="Center"
+ IsVisible="{Binding !Transport.LoopRecordReplace}" Foreground="{Binding $parent[ToggleButton].Foreground}"/>
+ <TextBlock Classes="CellLabel" Text="Replace" VerticalAlignment="Center" HorizontalAlignment="Center"
+ IsVisible="{Binding Transport.LoopRecordReplace}" Foreground="{Binding $parent[ToggleButton].Foreground}"/>
+ </Panel>
+ </ToggleButton>
</StackPanel>
</Border>
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index b2045e98..d3610b5a 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -345,6 +345,15 @@ public partial class MainWindow : Window
Timeline.ClipLabels = (ClipLabelMode)Math.Clamp(vm.Settings.Current.ArrangementClipLabels, 0, 2);
Timeline.ShowSections = vm.Settings.Current.ArrangementShowSections;
vm.Transport.CountInBars = Math.Clamp(vm.Settings.Current.CountInBars, 0, 4);
+ vm.Transport.LoopRecordReplace = vm.Settings.Current.LoopRecordReplace;
+ vm.Transport.PropertyChanged += (_, e) =>
+ {
+ // The loop record mode is an app preference: every switch (toggle, ⌘⇧R, menu, MCP) persists.
+ if (e.PropertyName != nameof(vm.Transport.LoopRecordReplace)
+ || vm.Settings.Current.LoopRecordReplace == vm.Transport.LoopRecordReplace) return;
+ vm.Settings.Current.LoopRecordReplace = vm.Transport.LoopRecordReplace;
+ vm.Settings.Save();
+ };
Timeline.Waveform = (WaveformStyle)Math.Clamp(vm.Settings.Current.ArrangementWaveform, 0, 1);
InitSnapGrid();
// Settings → Appearance can switch the waveform style while the arrangement is open.
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index bc811c9c..72c0bbf1 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -1100,6 +1100,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("⌘R", "Record"),
("⌘M", "Metronome"),
("⌘L", "Loop on / off · loop the selected clips or time range"),
+ ("⌘⇧R", "Loop recording: Overdub (every pass adds) / Replace (keep the latest pass)"),
}),
("Arrangement & editing", new[]
{
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index af4bf649..66737c68 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -31,6 +31,11 @@ public interface IAudioEngine : IDisposable
void SetCountIn(int bars);
/// <summary>Beats of count-in still to click (0 = not counting in).</summary>
double CountInBeats { get; }
+ /// <summary>Loop record mode for MIDI recorded into the Arrangement with the loop on:
+ /// false = overdub (every pass adds to the take), true = replace (the first new note of a
+ /// pass removes what earlier passes of the take recorded). Applies from the next pass.</summary>
+ void SetLoopRecordMode(bool replace);
+ bool LoopRecordReplace { get; }
void StopTransport();
void SetBpm(double bpm);
double Bpm { get; }
diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.cs
index fca5bfa7..748f1a94 100644
--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs
+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs
@@ -71,6 +71,7 @@ public static class CommandCatalog
C("transport.record", "Record", "Transport", "⌘R", "arm capture"),
C("transport.loop", "Toggle loop", "Transport", "⌘L", "cycle repeat"),
C("transport.metronome", "Metronome", "Transport", "⌘M", "click"),
+ C("transport.loopRecordMode", "Loop record: overdub / replace", "Transport", "⌘⇧R", "overdub replace take pass loop record"),
C("transport.tapTempo", "Tap tempo", "Transport", "", "bpm beat tap"),
// ---- Track ------------------------------------------------------------------------
diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.cs
index b8eb083c..49478f65 100644
--- a/src/managed/Nota.Application/Settings.cs
+++ b/src/managed/Nota.Application/Settings.cs
@@ -55,6 +55,10 @@ public sealed class Settings
/// <summary>Bars of metronome count-in before Play / Record from stop (0 = off). Set from
/// the metronome button's right-click menu.</summary>
public int CountInBars { get; set; }
+ /// <summary>Loop record mode (#29): false = Overdub (every loop pass adds to the MIDI take),
+ /// true = Replace (a new pass you play on replaces the earlier ones). Set from the transport
+ /// toggle next to Loop, ⌘⇧R, or the Transport menu.</summary>
+ public bool LoopRecordReplace { get; set; }
/// <summary>Run the built-in MCP server so an AI (Claude Desktop / Claude Code) can drive the
/// live app. Off by default; loopback-only. Toggled in Preferences.</summary>
public bool McpEnabled { get; set; }
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index 5659516c..8ee026d9 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -81,6 +81,12 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_transport_count_in_beats")]
internal static partial double CountInBeats(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_transport_set_loop_record_mode")]
+ internal static partial NotaResult SetLoopRecordMode(IntPtr engine, int mode);
+
+ [LibraryImport(Lib, EntryPoint = "nota_transport_loop_record_mode")]
+ internal static partial int LoopRecordMode(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_transport_set_metronome")]
internal static partial NotaResult SetMetronome(IntPtr engine, int enabled);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index cb4bb3af..9ce8d44b 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -80,6 +80,8 @@ public sealed partial class NotaEngine : IAudioEngine
public void PlayWithCountIn() { ThrowIfDisposed(); Check(NativeMethods.TransportPlayCountIn(_handle)); }
public void SetCountIn(int bars) { ThrowIfDisposed(); Check(NativeMethods.SetCountIn(_handle, Math.Max(0, bars))); }
public double CountInBeats { get { ThrowIfDisposed(); return NativeMethods.CountInBeats(_handle); } }
+ public void SetLoopRecordMode(bool replace) { ThrowIfDisposed(); Check(NativeMethods.SetLoopRecordMode(_handle, replace ? 1 : 0)); }
+ public bool LoopRecordReplace { get { ThrowIfDisposed(); return NativeMethods.LoopRecordMode(_handle) == 1; } }
public void StopTransport() { ThrowIfDisposed(); Check(NativeMethods.TransportStop(_handle)); }
public void SetBpm(double bpm) { ThrowIfDisposed(); Check(NativeMethods.SetBpm(_handle, bpm)); }
public double Bpm { get { ThrowIfDisposed(); return NativeMethods.TransportBpm(_handle); } }
diff --git a/src/managed/Nota.Mcp/Tools/TransportTools.cs b/src/managed/Nota.Mcp/Tools/TransportTools.cs
index b06f12ce..75dce6ea 100644
--- a/src/managed/Nota.Mcp/Tools/TransportTools.cs
+++ b/src/managed/Nota.Mcp/Tools/TransportTools.cs
@@ -13,11 +13,12 @@ namespace Nota.Mcp.Tools;
public sealed class TransportTools(IAudioEngine engine, IEngineDispatch dispatch, IArrangementRefresh refresh)
: EngineTools(engine, dispatch, refresh)
{
- public sealed record TransportState(bool Playing, double PositionBeats, double Bpm, bool LoopEnabled, double LoopStart, double LoopEnd);
+ public sealed record TransportState(bool Playing, double PositionBeats, double Bpm, bool LoopEnabled, double LoopStart, double LoopEnd,
+ bool LoopRecordReplace);
- [McpServerTool(Name = "get_transport"), Description("Current transport state: playing, playhead position (beats), tempo (BPM), and loop region.")]
+ [McpServerTool(Name = "get_transport"), Description("Current transport state: playing, playhead position (beats), tempo (BPM), loop region, and loop record mode (LoopRecordReplace: false = overdub, true = replace).")]
public Task<TransportState> GetTransport()
- => Read(() => new TransportState(E.IsPlaying, E.PositionBeats, E.Bpm, E.LoopEnabled, E.LoopStart, E.LoopEnd));
+ => Read(() => new TransportState(E.IsPlaying, E.PositionBeats, E.Bpm, E.LoopEnabled, E.LoopStart, E.LoopEnd, E.LoopRecordReplace));
[McpServerTool(Name = "play"), Description("Start playback from the current playhead position.")]
public Task Play() => Mutate(() => E.Play());
@@ -39,6 +40,9 @@ public sealed class TransportTools(IAudioEngine engine, IEngineDispatch dispatch
public Task SetLoop([Description("Loop on/off")] bool enabled, [Description("Loop start beat")] double startBeat, [Description("Loop end beat")] double endBeat)
=> Mutate(() => E.SetLoop(enabled, Math.Max(0, startBeat), Math.Max(startBeat, endBeat)));
+ [McpServerTool(Name = "set_loop_record_mode"), Description("Loop record mode for MIDI recorded with the loop on: replace=false overdubs (every pass adds to the take), replace=true keeps only the latest pass you play on. Applies from the next pass; an app preference.")]
+ public Task SetLoopRecordMode([Description("true = replace, false = overdub")] bool replace) => Mutate(() => E.SetLoopRecordMode(replace));
+
[McpServerTool(Name = "set_metronome"), Description("Turn the metronome click on or off.")]
public Task SetMetronome([Description("Metronome on/off")] bool enabled) => Mutate(() => E.SetMetronome(enabled));
diff --git a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs
index d6d94d76..cd0e4910 100644
--- a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs
@@ -38,6 +38,9 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
/// <summary>The count-in is clicking (the transport hasn't rolled yet).</summary>
[ObservableProperty] private bool _isCountingIn;
[ObservableProperty] private bool _loopOn;
+ /// <summary>Loop record mode: false = Overdub, true = Replace (the first new note of a loop
+ /// pass replaces what earlier passes of the take recorded).</summary>
+ [ObservableProperty] private bool _loopRecordReplace;
[ObservableProperty] private string _loopRangeText = "1.1–5.1";
[ObservableProperty] private bool _recordOn;
/// <summary>Which clock the position readout is showing, printed under it so the
@@ -76,6 +79,7 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
}
partial void OnMetronomeOnChanged(bool value) => _engine.SetMetronome(value);
partial void OnCountInBarsChanged(int value) => _engine.SetCountIn(value);
+ partial void OnLoopRecordReplaceChanged(bool value) => _engine.SetLoopRecordMode(value);
partial void OnLoopOnChanged(bool value)
{
@@ -193,6 +197,9 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
if (IsCountingIn != wasCounting) PositionUnitText = IsCountingIn ? "count-in" : ShowTimeDisplay ? "time" : "bars";
IsPlaying = _engine.IsPlaying || IsCountingIn; // the Play button lights from the first click
PlayLabel = IsPlaying ? "■ Stop" : "▶ Play";
+ // The loop record mode can also be set from outside the UI (MCP): follow the engine.
+ bool replace = _engine.LoopRecordReplace;
+ if (replace != LoopRecordReplace) LoopRecordReplace = replace;
}
/// <summary>The count-in as negative bars counting up to the start: −2.1 … −2.4, −1.1 … −1.4.</summary>
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index fa23e51b..ddc7f501 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -458,6 +458,12 @@ NOTA_API NotaResult nota_transport_stop(NotaEngine* engine);
NOTA_API NotaResult nota_transport_play_count_in(NotaEngine* engine);
NOTA_API NotaResult nota_transport_set_count_in(NotaEngine* engine, int32_t bars);
NOTA_API double nota_transport_count_in_beats(const NotaEngine* engine);
+/* Loop record mode for MIDI recorded into the Arrangement with the loop on:
+ * 0 = overdub (every pass adds to the take), 1 = replace (the first new note of a
+ * pass removes what earlier passes of this take recorded). App preference; takes
+ * effect from the next pass. Session slot recording is unaffected. */
+NOTA_API NotaResult nota_transport_set_loop_record_mode(NotaEngine* engine, int32_t mode);
+NOTA_API int32_t nota_transport_loop_record_mode(const NotaEngine* engine);
NOTA_API NotaResult nota_transport_set_bpm(NotaEngine* engine, double bpm);
NOTA_API double nota_transport_bpm(const NotaEngine* engine);
NOTA_API NotaResult nota_transport_set_time_signature(NotaEngine* engine, int32_t num, int32_t denom);
diff --git a/src/native/nota.engine/src/Arpeggiator.h b/src/native/nota.engine/src/Arpeggiator.h
index cd37270a..fd059ca7 100644
--- a/src/native/nota.engine/src/Arpeggiator.h
+++ b/src/native/nota.engine/src/Arpeggiator.h
@@ -133,6 +133,13 @@ public:
curLp_.store(-1, std::memory_order_relaxed); curK_.store(-1, std::memory_order_relaxed);
heldLive_.store(0, std::memory_order_relaxed);
}
+ // Loop wrap: the pattern continues from where it was — phase and pending events move
+ // with the transport's beat clock.
+ void timeJump(double d) override {
+ arpBeat_ += d; phaseRef_ += d;
+ for (int i = 0; i < nOns_; ++i) { onBuf_[i].onBeat += d; onBuf_[i].offBeat += d; }
+ for (int i = 0; i < nOffs_; ++i) offBuf_[i].beat += d;
+ }
// Editor commands: 1 = restart the pattern (step 1) at the next block.
void midiCommand(int32_t cmd) override { if (cmd == 1) restartReq_.store(true, std::memory_order_relaxed); }
diff --git a/src/native/nota.engine/src/CommandQueue.h b/src/native/nota.engine/src/CommandQueue.h
index 59e7c811..8b11c924 100644
--- a/src/native/nota.engine/src/CommandQueue.h
+++ b/src/native/nota.engine/src/CommandQueue.h
@@ -33,6 +33,9 @@ enum class CommandType : uint32_t {
SetLoop,
SetMetronome,
Seek,
+ // Loop record replace (#29): release a pitch on a track — a note just removed from the take
+ // may still be sounding (played back from an earlier pass). i0 = track id, i1 = pitch.
+ ReleaseNote,
};
struct Command {
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index a000a23e..ee39548e 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -51,7 +51,9 @@ struct MidiEvent { bool on; int32_t pitch; float velocity; int32_t trackId = -1;
using MidiQueue = SpscRingBuffer<MidiEvent, 1024>;
// Recorded note (audio -> message), lock-free up-queue. startBeat is absolute.
-struct RecordedNote { int32_t pitch; double startBeat; double lengthBeats; float velocity; };
+// pass: the loop pass of the take the note started in (0 without a loop; a note held across
+// the loop seam is split, its continuation starting the next pass) — loop record mode (#29).
+struct RecordedNote { int32_t pitch; double startBeat; double lengthBeats; float velocity; int32_t pass = 0; };
using RecordedQueue = SpscRingBuffer<RecordedNote, 1024>;
// A recorded note's expression sample (audio -> message): the note is identified by its pitch
// and start (as its RecordedNote will carry them), `beat` is the offset from that start.
@@ -304,6 +306,11 @@ public:
// (transportPlayCountIn) and a Record from stop use it — exports / freezes / session
// launches roll immediately. The clicks sound whether or not the metronome is on.
void setCountInBars(int32_t bars) { countInBars_.store(std::clamp(bars, 0, 8), std::memory_order_relaxed); }
+ // Loop record mode (#29): false = overdub (every loop pass adds to the take), true = replace
+ // (the first fresh note of a pass removes what earlier passes of this take recorded).
+ // Arrangement MIDI takes only; latched by the audio thread at take start and at each wrap.
+ void setLoopRecordReplace(bool on) { loopRecordReplace_.store(on, std::memory_order_relaxed); }
+ bool loopRecordReplace() const { return loopRecordReplace_.load(std::memory_order_relaxed); }
int32_t countInBars() const { return countInBars_.load(std::memory_order_relaxed); }
void transportPlayCountIn();
// Beats of count-in still to click (0 = not counting in). UI poll.
@@ -1352,6 +1359,20 @@ private:
// session-only jam. Read on the audio thread to gate arrangement clip content per track.
std::atomic<bool> arrangementActive_{false};
std::atomic<int32_t> countInBars_{0}; // count-in length setting (bars)
+ std::atomic<bool> loopRecordReplace_{false}; // loop record mode setting (true = replace)
+ // Loop record passes (audio thread): the take's current pass, the mode latched for it, and
+ // whether a fresh note already fired its replace. replaceUpTo_ (audio → message, release):
+ // this take's notes from passes before it are to be removed (collectRecorded applies it).
+ int32_t recordPass_ = 0;
+ bool passReplace_ = false;
+ bool passTriggered_ = false;
+ std::atomic<int32_t> replaceUpTo_{0};
+ void triggerPassReplace(); // audio thread: a fresh recorded note-on in this pass
+ // The notes this take appended to its Arrangement clip (message thread), by identity so a
+ // replace removes exactly them — never notes the clip held before the take.
+ struct TakeNote { int32_t pitch; double absStart; int32_t pass; };
+ std::vector<TakeNote> takeNotes_;
+ int32_t appliedReplaceUpTo_ = 0;
std::atomic<double> uiCountIn_{0.0}; // beats of count-in left (UI mirror)
// False while a count-in runs: takes started from stop don't capture the clicks-only
// pre-roll (the hardware tap and the internal-resampling tap both honour it).
@@ -1430,6 +1451,16 @@ private:
bool seekedThisBlock_ = false; // a Seek command was drained this block (audio thread)
bool seekedWhileRolling_ = false; // ...and it arrived while the transport was rolling
bool chaseNotes_ = false; // this segment starts at a discontinuity: re-trigger held clip notes
+ // This segment starts right after a loop wrap: clip notes still sounding at the loop end
+ // (seamEndSamples_, the pre-wrap playhead) get their note-off here — a release, not a cut (#29).
+ bool seamOffs_ = false;
+ double seamEndSamples_ = 0.0;
+ void onLoopWrap(Graph* g, double loopStartBeat, double loopEndBeat); // processBlock, at the wrap
+ // Pitches to release on one track in the next segment (ReleaseNote command, audio thread):
+ // notes a loop record replace removed while they may be sounding. A key the player holds
+ // live is skipped.
+ int32_t releaseTrack_ = -1;
+ uint32_t releasePitches_[4] = {};
// session-slot recording target (M5-4). recordSessionScene_ >= 0 selects slot
// mode; recordSlotPlayer_/recordSlotLen_ are read on the audio thread to time
diff --git a/src/native/nota.engine/src/Engine_Recording.cpp b/src/native/nota.engine/src/Engine_Recording.cpp
index 311fcaf1..f6c722dd 100644
--- a/src/native/nota.engine/src/Engine_Recording.cpp
+++ b/src/native/nota.engine/src/Engine_Recording.cpp
@@ -297,6 +297,11 @@ void Engine::setRecording(bool on) {
republishWithTrack(recordTrackId_, nt);
}
recordClipIndex_ = idx;
+ // A fresh take for loop record replace: nothing recorded, nothing replaced yet (the
+ // audio thread also zeroes replaceUpTo_ when it sees the take start).
+ takeNotes_.clear();
+ appliedReplaceUpTo_ = 0;
+ replaceUpTo_.store(0, std::memory_order_relaxed);
recording_.store(true, std::memory_order_relaxed);
}
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index 8824b787..db156bbf 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -248,15 +248,20 @@ void Engine::poll() {
sampleAutomationWritesAt(transport_.uiPositionBeats());
}
+ // Loop record replace (#29): read the audio thread's mark before draining, so every note of
+ // an earlier pass queued ahead of it is in this batch.
+ const int32_t replaceUpTo = replaceUpTo_.load(std::memory_order_acquire);
RecordedNote rn;
std::vector<RecordedNote> batch;
while (recorded_.pop(rn)) batch.push_back(rn);
// Expression after the notes: a note's points were all queued before its note-off was.
collectRecordedExpr();
- if (batch.empty()) return;
+ const bool replacePending = replaceUpTo > appliedReplaceUpTo_ && recordSessionScene_ < 0;
+ if (batch.empty() && !replacePending) return;
// Session-slot recording (M5-4): notes are already loop-local; append into the slot.
if (recordSessionScene_ >= 0 && recordSessionTrackId_ > 0) {
+ if (batch.empty()) return;
auto st = findTrackAuthoring(recordSessionTrackId_);
if (!st || recordSessionScene_ >= static_cast<int32_t>(st->sessionSlots.size())) return;
auto nt = cloneTrack(*st);
@@ -280,6 +285,10 @@ void Engine::poll() {
auto nt = cloneTrack(*t);
MidiClip& clip = nt->midiClips[recordClipIndex_];
for (auto& r : batch) {
+ if (r.pass < replaceUpTo) { // its pass was already replaced: drop it (and its curves)
+ Note gone; attachRecordedExpr(gone, r.pitch, r.startBeat);
+ continue;
+ }
// A note that began before the take's clip (played on the count-in, or a key held
// when Record was pressed, #56) moves the clip's left edge back to it, keeping every
// note where it is. Clips can't start before 1.1, so a note older than that keeps
@@ -299,11 +308,33 @@ void Engine::poll() {
n.velocity = r.velocity;
attachRecordedExpr(n, r.pitch, r.startBeat);
clip.notes.push_back(n);
+ takeNotes_.push_back({ r.pitch, r.startBeat, r.pass });
// Grow the clip so freshly recorded notes fall inside it (gating in
// renderInstrumentRaw drops notes past lengthBeats).
const double end = n.startBeat + n.lengthBeats;
if (end > clip.lengthBeats) clip.lengthBeats = end;
}
+ // Replace: remove the notes this take recorded on earlier passes — matched by pitch and
+ // absolute start, so notes the clip held before the take (or the user drew) stay.
+ if (replacePending) {
+ auto& notes = clip.notes;
+ for (size_t i = 0; i < notes.size();) {
+ const double abs = clip.startBeat + notes[i].startBeat;
+ auto it = std::find_if(takeNotes_.begin(), takeNotes_.end(), [&](const TakeNote& k) {
+ return k.pass < replaceUpTo && k.pitch == notes[i].pitch && std::fabs(k.absStart - abs) < 1e-6;
+ });
+ if (it == takeNotes_.end()) { ++i; continue; }
+ takeNotes_.erase(it);
+ // It may be sounding right now (an earlier pass playing back): release its voice.
+ Command c; c.type = CommandType::ReleaseNote; c.i0 = recordTrackId_; c.i1 = notes[i].pitch;
+ commands_.push(c);
+ notes.erase(notes.begin() + static_cast<std::ptrdiff_t>(i));
+ }
+ takeNotes_.erase(std::remove_if(takeNotes_.begin(), takeNotes_.end(),
+ [&](const TakeNote& k) { return k.pass < replaceUpTo; }),
+ takeNotes_.end());
+ appliedReplaceUpTo_ = replaceUpTo;
+ }
republishWithTrackRaw(recordTrackId_, nt); // grows the live take, not a new undo step
}
@@ -416,6 +447,12 @@ void Engine::drainCommands() {
case CommandType::SetTimeSignature: transport_.setTimeSignature(c.i0, c.i1); break;
case CommandType::SetLoop: transport_.setLoop(c.i0 != 0, c.d0, c.d1); break;
case CommandType::SetMetronome: transport_.setMetronome(c.i0 != 0); break;
+ case CommandType::ReleaseNote:
+ if (c.i1 >= 0 && c.i1 < 128) {
+ if (releaseTrack_ != c.i0) { releaseTrack_ = c.i0; for (auto& w : releasePitches_) w = 0; }
+ releasePitches_[c.i1 >> 5] |= 1u << (c.i1 & 31);
+ }
+ break;
case CommandType::Seek:
seekedWhileRolling_ |= transport_.isPlaying(); // a jump mid-playback, not Stop→Seek→Play
transport_.seekBeats(c.d0); seekedThisBlock_ = true; break;
@@ -473,6 +510,12 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {
routedSeedPending_ = takeStarted && !slot; // routed notes held now join the take (captureRoutedNotes)
if (rec != prevRecording_)
for (int i = 0; i < 128; ++i) { pendingActive_[i] = false; recRoutedActive_[i] = false; }
+ if (takeStarted) { // a new take: pass 0, the loop record mode as set now
+ recordPass_ = 0;
+ passTriggered_ = false;
+ passReplace_ = loopRecordReplace_.load(std::memory_order_relaxed);
+ replaceUpTo_.store(0, std::memory_order_release);
+ }
prevRecording_ = rec;
// Every live event plays at offset 0 and the render sorts offs ahead of ons at one
// offset, so a pitch's on and off landing in the same block (a quick tap, a finger
@@ -514,10 +557,11 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {
pendingActive_[e.pitch] = true;
pendingStart_[e.pitch] = nowBeat;
pendingVel_[e.pitch] = e.velocity;
+ if (!slot) triggerPassReplace();
} else if (pendingActive_[e.pitch]) {
double len = nowBeat - pendingStart_[e.pitch];
if (slot && len < 0.0) len += slotLen; // wrapped past the loop end
- RecordedNote rn{e.pitch, pendingStart_[e.pitch], len, pendingVel_[e.pitch]};
+ RecordedNote rn{e.pitch, pendingStart_[e.pitch], len, pendingVel_[e.pitch], recordPass_};
recorded_.push(rn);
pendingActive_[e.pitch] = false;
}
@@ -585,8 +629,9 @@ void Engine::captureRoutedNotes(const MidiEv* evs, int n, double blockStart, dou
recRoutedActive_[p] = true;
recRoutedStart_[p] = beat;
recRoutedVel_[p] = evs[k].vel;
+ if (!recordSlotPlayer_.load(std::memory_order_relaxed)) triggerPassReplace();
} else if (recRoutedActive_[p]) {
- recorded_.push(RecordedNote{p, recRoutedStart_[p], std::max(0.0, beat - recRoutedStart_[p]), recRoutedVel_[p]});
+ recorded_.push(RecordedNote{p, recRoutedStart_[p], std::max(0.0, beat - recRoutedStart_[p]), recRoutedVel_[p], recordPass_});
recRoutedActive_[p] = false;
}
}
@@ -633,6 +678,10 @@ int Engine::gatherInstrumentNotes(Track& t, MidiEv* evs, int n, int32_t frames,
if (hasVel) vel *= std::clamp(clip.velocityEnvelope.valueAt(note.startBeat), 0.0f, 1.0f);
if (clipActive && onS >= blockStart && onS < blockStart + frames && n < 1024)
evs[n++] = {static_cast<int32_t>(onS - blockStart), true, note.pitch, vel, static_cast<float>((offS - onS) / spb)};
+ // Loop seam: a note still sounding at the loop end releases here, ahead of any
+ // chase re-trigger at the same offset (offs sort first).
+ if (seamOffs_ && onS < seamEndSamples_ && offS >= seamEndSamples_ && n < 1024)
+ evs[n++] = {0, false, note.pitch, 0.0f};
// Chase: a note already held at the jump point starts sounding right here.
if (chaseNotes_ && clipActive && onS < blockStart && offS > blockStart && n < 1024)
evs[n++] = {0, true, note.pitch, vel};
@@ -645,6 +694,14 @@ int Engine::gatherInstrumentNotes(Track& t, MidiEv* evs, int n, int32_t frames,
}
}
}
+ // Notes a loop record replace removed from this track's take: release them (once), unless
+ // the player is holding that key live.
+ if (t.id() == releaseTrack_) {
+ for (int p = 0; p < 128 && n < 1024; ++p)
+ if ((releasePitches_[p >> 5] >> (p & 31)) & 1u && !liveDown_[p]) evs[n++] = {0, false, p, 0.0f};
+ for (auto& w : releasePitches_) w = 0;
+ releaseTrack_ = -1;
+ }
// Live notes reach a track when it's armed, or when it's the audition target
// (so clicking a rack/drum pad plays it without arming/recording).
// A track-addressed event (Nota Remote) plays only its own track.
@@ -1063,6 +1120,42 @@ static inline bool sessionActiveOf(const Track& t) {
return t.sessionPlayer && t.sessionPlayer->playing.load(std::memory_order_relaxed) >= 0;
}
+// The transport loop just wrapped (audio thread, #29). MIDI FX keep their pattern and pending
+// offs across the seam instead of being reset. A take recording into the Arrangement splits each
+// note held across the seam: the part played so far ends at the loop end, and the note carries
+// on from the loop start (a key pressed just before the seam — a head under 1/64 beat — moves
+// to the loop start whole). A Session slot take times notes on its own loop clock: untouched.
+void Engine::onLoopWrap(Graph* g, double loopStartBeat, double loopEndBeat) {
+ const double jump = loopStartBeat - loopEndBeat;
+ if (g) for (auto& tptr : g->tracks)
+ if (tptr && tptr->instrument && !sessionActiveOf(*tptr))
+ for (auto& md : tptr->midiEffects) if (md) md->timeJump(jump);
+
+ if (!recording_.load(std::memory_order_relaxed) || recordSlotPlayer_.load(std::memory_order_acquire)) return;
+ constexpr double kMinHead = 1.0 / 64.0;
+ auto split = [&](int32_t pitch, double& start, float vel) {
+ const double head = loopEndBeat - start;
+ if (head >= kMinHead) recorded_.push(RecordedNote{pitch, start, head, vel, recordPass_});
+ start = loopStartBeat;
+ };
+ for (int p = 0; p < 128; ++p) if (pendingActive_[p]) split(p, pendingStart_[p], pendingVel_[p]);
+ for (int p = 0; p < 128; ++p) if (recRoutedActive_[p]) split(p, recRoutedStart_[p], recRoutedVel_[p]);
+ // A new pass of the take: the continuations above belong to it (they don't trigger a
+ // replace — only a fresh note does), and it takes the loop record mode set right now.
+ ++recordPass_;
+ passTriggered_ = false;
+ passReplace_ = loopRecordReplace_.load(std::memory_order_relaxed);
+}
+
+// Replace mode: the first fresh note of a pass after the first removes the take's earlier
+// passes. Published once per pass; collectRecorded reads it before draining recorded_, so every
+// earlier-pass note queued before it is in hand.
+void Engine::triggerPassReplace() {
+ if (!passReplace_ || passTriggered_ || recordPass_ <= 0) return;
+ passTriggered_ = true;
+ replaceUpTo_.store(recordPass_, std::memory_order_release);
+}
+
void Engine::processBlock(float* out, int32_t numFrames) {
drainCommands();
for (int32_t i = 0; i < numFrames * 2; ++i) out[i] = 0.0f;
@@ -1102,8 +1195,12 @@ void Engine::processBlock(float* out, int32_t numFrames) {
while (done < numFrames) {
if (playing && transport_.isLooping()
&& transport_.playheadSamples() >= transport_.loopEndSamples() - 0.5) {
+ // No voice flush here: clip notes crossing the loop end get note-offs in the next
+ // segment (seamOffs_), so live-held keys keep sounding and tails ring out (#29).
+ seamEndSamples_ = transport_.playheadSamples();
transport_.wrapToLoopStart();
- flushArrangementVoices();
+ if (spb > 0.0) onLoopWrap(g, transport_.loopStartSamples() / spb, seamEndSamples_ / spb);
+ seamOffs_ = true;
chase = true;
if (nLoopSeams < 16) loopSeams[nLoopSeams++] = done; // declick this seam below
}
@@ -1120,7 +1217,7 @@ void Engine::processBlock(float* out, int32_t numFrames) {
const double segStart = transport_.playheadSamples();
chaseNotes_ = chase;
if (g && sr > 0.0) mixGraph(g, out + done * 2, seg, segStart, playing, spb);
- chaseNotes_ = chase = false;
+ chaseNotes_ = chase = seamOffs_ = false;
bool countInDone = false;
if (playing) renderMetronome(out + done * 2, seg, segStart);
else if (countInActive_) countInDone = renderCountIn(out + done * 2, seg, spb);
diff --git a/src/native/nota.engine/src/MidiDevice.h b/src/native/nota.engine/src/MidiDevice.h
index b7f066dd..d450b5d1 100644
--- a/src/native/nota.engine/src/MidiDevice.h
+++ b/src/native/nota.engine/src/MidiDevice.h
@@ -46,10 +46,15 @@ public:
int32_t frames, double beatStart, double spb, bool playing) = 0;
// Flush all live state (held notes, pending offs, phase) WITHOUT touching params.
- // Called at transport stop / loop wrap / session slot switch, alongside the
+ // Called at transport stop / seek / session slot switch, alongside the
// instrument's allNotesOff, to avoid ghost/stuck notes across clock changes.
virtual void reset() {}
+ // The transport loop wrapped: beatStart jumps by deltaBeats (−loop length) while time
+ // runs on. A device keeping state in transport beats (pending offs, pattern phase) shifts
+ // it by deltaBeats so it carries on across the seam — held keys and all (#29).
+ virtual void timeJump(double /*deltaBeats*/) {}
+
// Built-in identity (0 = Arpeggiator), or -1 for a future hosted MIDI plugin.
virtual int32_t midiKind() const { return -1; }
virtual const char* displayName() const { return "MidiDevice"; }
diff --git a/src/native/nota.engine/src/MidiNoteLength.h b/src/native/nota.engine/src/MidiNoteLength.h
index 756f9791..30e4f8d9 100644
--- a/src/native/nota.engine/src/MidiNoteLength.h
+++ b/src/native/nota.engine/src/MidiNoteLength.h
@@ -77,6 +77,12 @@ public:
float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(v, std::memory_order_relaxed); }
void reset() override { nPending_ = 0; nHeld_ = 0; nSound_ = 0; intBeat_ = 0.0; sounding_.store(0, std::memory_order_relaxed); }
+ void timeJump(double d) override { // loop wrap: scheduled offs keep their real time
+ intBeat_ += d;
+ for (int i = 0; i < nPending_; ++i) { pending_[i].on += d; pending_[i].off += d; }
+ for (int i = 0; i < nSound_; ++i) sound_[i].on += d;
+ for (int i = 0; i < nHeld_; ++i) held_[i].onBeat += d;
+ }
// Editor / MCP telemetry: [0] last input pitch, [1] its velocity 0..1, [2] its held length
// (beats, −1 = still held), [3] last finished output pitch, [4] its actual length (beats),
diff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cpp
index f2fa31b6..f502c169 100644
--- a/src/native/nota.engine/src/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/nota_engine_core.cpp
@@ -122,6 +122,13 @@ NotaResult nota_transport_set_count_in(NotaEngine* e, int32_t bars) {
double nota_transport_count_in_beats(const NotaEngine* e) {
return e ? CENG(e)->countInBeatsRemaining() : 0.0;
}
+NotaResult nota_transport_set_loop_record_mode(NotaEngine* e, int32_t mode) {
+ if (!e || mode < 0 || mode > 1) return NOTA_ERR_INVALID_ARG;
+ ENG(e)->setLoopRecordReplace(mode == 1); return NOTA_OK;
+}
+int32_t nota_transport_loop_record_mode(const NotaEngine* e) {
+ return e && CENG(e)->loopRecordReplace() ? 1 : 0;
+}
NotaResult nota_transport_stop(NotaEngine* e) {
if (!e) return NOTA_ERR_INVALID_ARG; ENG(e)->transportStop(); return NOTA_OK;
}
diff --git a/tests/Nota.SmokeTest/LoopRecordModeTests.cs b/tests/Nota.SmokeTest/LoopRecordModeTests.cs
new file mode 100644
index 00000000..24814f04
--- /dev/null
+++ b/tests/Nota.SmokeTest/LoopRecordModeTests.cs
@@ -0,0 +1,248 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Loop record mode (#29, specs/018-loop-record-replace): with the transport loop on, Overdub adds
+// every pass to the MIDI take; Replace lets the first fresh note of a pass remove what earlier
+// passes of the take recorded — a silent pass removes nothing, notes the clip held before the
+// take stay, and a mode switch applies from the next pass.
+
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class LoopRecordModeTests
+{
+ private const double Sr = 48000.0;
+ private const double Spb = Sr * 60.0 / 120.0; // frames per beat at 120 BPM
+ private const int Chunk = 256;
+ private static readonly double[] PhraseAt = { 0.0, 1.0, 2.0, 3.0 };
+ private static readonly int[] PhrasePitch = { 60, 62, 64, 65 };
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ foreach (var r in Defaults()) yield return r;
+ foreach (var r in Overdub()) yield return r;
+ foreach (var r in ReplaceLatestPass()) yield return r;
+ foreach (var r in SilentPass()) yield return r;
+ foreach (var r in ExistingNotes()) yield return r;
+ foreach (var r in HeldAcrossSeam()) yield return r;
+ foreach (var r in Routed()) yield return r;
+ foreach (var r in SwitchMidTake()) yield return r;
+ foreach (var r in ReplacedNoteReleases()) yield return r;
+ }
+
+ // A take on a 1-bar loop (beats 0–4), timed on an absolute clock: pass k spans [4k, 4k+4).
+ private sealed class Rig : IDisposable
+ {
+ public readonly NotaEngine E = new();
+ public readonly int Track, Source = -1;
+ private long _frames;
+
+ public Rig(bool replace, bool routed = false)
+ {
+ E.SetBpm(120);
+ E.SetMetronome(false);
+ E.SetCountIn(0);
+ Track = E.AddInstrumentTrack();
+ E.SetTrackBuiltinInstrument(Track, 0);
+ if (routed)
+ {
+ Source = E.AddInstrumentTrack();
+ E.SetTrackBuiltinInstrument(Source, 0);
+ E.SetTrackMidiSource(Track, Source);
+ }
+ E.SetTrackArmed(Track, true);
+ E.SetLoop(true, 0.0, 4.0);
+ E.SetLoopRecordMode(replace);
+ E.StopTransport();
+ E.Seek(0.0);
+ E.RenderOffline(new float[Chunk * 2], Chunk, Sr);
+ }
+
+ public void Record() { E.SetRecording(true); _frames = 0; }
+
+ // Render up to an absolute beat of the take (beat 0 = Record pressed).
+ public float To(double beat)
+ {
+ var b = new float[Chunk * 2];
+ long target = (long)Math.Round(beat * Spb);
+ double sq = 0; long n = 0;
+ while (_frames < target)
+ {
+ E.RenderOffline(b, Chunk, Sr); _frames += Chunk;
+ foreach (var v in b) { sq += v * (double)v; n++; }
+ }
+ return n > 0 ? (float)Math.Sqrt(sq / n) : 0f;
+ }
+
+ public void On(int pitch) { if (Source >= 0) E.TrackNoteOn(Source, pitch, 0.8f); else E.NoteOn(pitch, 0.8f); }
+ public void Off(int pitch) { if (Source >= 0) E.TrackNoteOff(Source, pitch); else E.NoteOff(pitch); }
+
+ public void Note(int pitch, double at, double len = 0.25) { To(at); On(pitch); To(at + len); Off(pitch); }
+
+ // The 4-note phrase on pass k, shifted by `jitter` beats.
+ public void Phrase(int pass, double jitter = 0.0)
+ {
+ for (int i = 0; i < PhraseAt.Length; i++) Note(PhrasePitch[i], 4.0 * pass + PhraseAt[i] + 0.1 + jitter);
+ }
+
+ public void Stop() { E.Poll(); E.SetRecording(false); E.Poll(); }
+
+ // (absolute start in the loop, pitch) of every note on the record track, sorted by start.
+ public List<(double At, int Pitch)> Notes()
+ {
+ E.Poll();
+ var all = new List<(double, int)>();
+ for (int c = 0; c < 64 && E.TryGetClipInfo(Track, c, out var ci); c++)
+ foreach (var n in E.GetClipNotes(Track, c)) all.Add((ci.StartBeat + n.StartBeat, n.Pitch));
+ return all.OrderBy(x => x.Item1).ThenBy(x => x.Item2).ToList();
+ }
+
+ public void Dispose() => E.Dispose();
+ }
+
+ private static string Show(List<(double At, int Pitch)> n) => string.Join(", ", n.Select(x => $"{x.Pitch}@{x.At:F2}"));
+ private static bool Near(double a, double b, double tol = 0.05) => Math.Abs(a - b) <= tol;
+
+ private static IEnumerable<(bool, string)> Defaults()
+ {
+ using var e = new NotaEngine();
+ bool def = e.LoopRecordReplace;
+ e.SetLoopRecordMode(true);
+ bool on = e.LoopRecordReplace;
+ e.SetLoopRecordMode(false);
+ yield return (!def && on && !e.LoopRecordReplace, $"loop record mode: overdub by default, set/get round-trips ({def}/{on}/{e.LoopRecordReplace})");
+ }
+
+ // Overdub: a different pitch on each of three passes — all three stay (today's behaviour).
+ private static IEnumerable<(bool, string)> Overdub()
+ {
+ using var r = new Rig(replace: false);
+ r.Record();
+ r.Note(60, 0.5); r.Note(62, 4.5); r.Note(64, 8.5);
+ r.To(12.2);
+ r.Stop();
+ var n = r.Notes();
+ yield return (n.Count == 3 && n.Select(x => x.Pitch).OrderBy(p => p).SequenceEqual(new[] { 60, 62, 64 }),
+ $"loop record overdub: every pass adds to the take ({Show(n)})");
+ }
+
+ // Replace: the same phrase on 5 passes with jittered timing leaves exactly one phrase, the last.
+ private static IEnumerable<(bool, string)> ReplaceLatestPass()
+ {
+ using var r = new Rig(replace: true);
+ r.Record();
+ double[] jit = { 0.03, -0.03, 0.02, -0.02, 0.01 };
+ for (int p = 0; p < 5; p++) r.Phrase(p, jit[p]);
+ r.To(20.2);
+ r.Stop();
+ var n = r.Notes();
+ bool last = n.Count == 4 && n.Select((x, i) => Near(x.At, PhraseAt[i] + 0.1 + jit[4], 0.02) && x.Pitch == PhrasePitch[i]).All(b => b);
+ yield return (last, $"loop record replace: 5 passes of a phrase leave only the last one ({Show(n)})");
+ }
+
+ // Replace: a pass with no notes removes nothing.
+ private static IEnumerable<(bool, string)> SilentPass()
+ {
+ using var r = new Rig(replace: true);
+ r.Record();
+ r.Phrase(0);
+ r.To(8.2); // pass 1: silent
+ r.Stop();
+ var n = r.Notes();
+ yield return (n.Count == 4, $"loop record replace: a silent pass keeps the take ({Show(n)})");
+ }
+
+ // Replace: notes the clip held before the take stay.
+ private static IEnumerable<(bool, string)> ExistingNotes()
+ {
+ using var r = new Rig(replace: true);
+ r.E.AddMidiClip(r.Track, 0.0, 4.0);
+ r.E.SetClipNotes(r.Track, 0, new[] { new NotaNote(48, 2.5, 0.5, 0.8f) });
+ r.Record();
+ r.Phrase(0); r.Phrase(1); r.Phrase(2);
+ r.To(12.2);
+ r.Stop();
+ var n = r.Notes();
+ bool kept = n.Count(x => x.Pitch == 48 && Near(x.At, 2.5, 1e-6)) == 1;
+ yield return (kept && n.Count == 5, $"loop record replace: notes in the clip before the take stay ({Show(n)})");
+ }
+
+ // Replace with a note held across the seam: its continuation belongs to the new pass and
+ // doesn't trigger a replace; the next fresh note removes the old pass (with the head).
+ private static IEnumerable<(bool, string)> HeldAcrossSeam()
+ {
+ using var r = new Rig(replace: true);
+ r.Record();
+ r.To(3.5); r.On(67); r.To(4.5); r.Off(67); // 67: 3.5 → seam → 0.5
+ r.To(4.8);
+ var mid = r.Notes();
+ bool bothHalves = mid.Count(x => x.Pitch == 67) == 2;
+ r.Note(69, 5.0); // fresh note on pass 1
+ r.To(6.0);
+ var after = r.Notes();
+ bool headGone = after.Count == 2 && after.Any(x => x.Pitch == 67 && Near(x.At, 0.0)) && after.Any(x => x.Pitch == 69 && Near(x.At, 1.0));
+ r.Note(71, 9.0); // fresh note on pass 2
+ r.To(10.0);
+ r.Stop();
+ var end = r.Notes();
+ yield return (bothHalves, $"loop record replace: a note held across the seam doesn't trigger a replace ({Show(mid)})");
+ yield return (headGone, $"loop record replace: the next fresh note removes the old pass, the continuation stays ({Show(after)})");
+ yield return (end.Count == 1 && end[0].Pitch == 71, $"loop record replace: a further pass replaces that one too ({Show(end)})");
+ }
+
+ // Routed MIDI ("MIDI In" from another track) follows the mode like the keyboard.
+ private static IEnumerable<(bool, string)> Routed()
+ {
+ using var r = new Rig(replace: true, routed: true);
+ r.Record();
+ r.Phrase(0, 0.02); r.Phrase(1, -0.02); r.Phrase(2);
+ r.To(12.2);
+ r.Stop();
+ var n = r.Notes();
+ bool last = n.Count == 4 && n.Select((x, i) => Near(x.At, PhraseAt[i] + 0.1, 0.02)).All(b => b);
+ yield return (last, $"loop record replace: routed MIDI keeps only the last pass ({Show(n)})");
+ }
+
+ // A switch mid-take applies from the next pass: the pass it was made on keeps overdubbing.
+ private static IEnumerable<(bool, string)> SwitchMidTake()
+ {
+ using var r = new Rig(replace: false);
+ r.Record();
+ r.Note(60, 0.5);
+ r.Note(62, 4.5);
+ r.To(5.0);
+ r.E.SetLoopRecordMode(true);
+ r.Note(64, 6.0); // same pass as the switch: still overdub
+ r.To(7.9);
+ var mid = r.Notes();
+ r.Note(65, 8.5); // next pass: the replace fires
+ r.To(9.5);
+ r.Stop();
+ var end = r.Notes();
+ yield return (mid.Count == 3, $"loop record mode: a switch mid-pass doesn't replace on that pass ({Show(mid)})");
+ yield return (end.Count == 1 && end[0].Pitch == 65, $"loop record mode: the switch applies from the next pass ({Show(end)})");
+ }
+
+ // A replaced note that is sounding (played back from an earlier pass) is released, not left
+ // hanging: Overdub as the control keeps sounding; Replace goes quiet once the new note ends.
+ private static IEnumerable<(bool, string)> ReplacedNoteReleases()
+ {
+ float Run(bool replace)
+ {
+ using var r = new Rig(replace);
+ r.Record();
+ r.To(0.1); r.On(60); r.To(3.6); r.Off(60);
+ r.To(3.7); r.E.Poll(); // in the take before pass 1 plays it back
+ r.To(4.5); r.On(62); r.To(4.7); r.Off(62); // fresh note while 60 sounds
+ r.To(4.8); r.E.Poll();
+ r.To(5.2);
+ float rest = r.To(7.5); // 62 is done; only 60 could still sound
+ r.Stop();
+ return rest;
+ }
+ float overdub = Run(false), replace = Run(true);
+ yield return (overdub > 1e-3 && replace < 1e-4,
+ $"loop record replace: a replaced note that is sounding is released, not left hanging (overdub {overdub:F4}, replace {replace:F6})");
+ }
+}
diff --git a/tests/Nota.SmokeTest/LoopSeamTests.cs b/tests/Nota.SmokeTest/LoopSeamTests.cs
new file mode 100644
index 00000000..13052624
--- /dev/null
+++ b/tests/Nota.SmokeTest/LoopSeamTests.cs
@@ -0,0 +1,191 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The transport loop's seam (#29, .specify/bugs/loop-seam-note-cut): when the playhead wraps, a
+// key held live keeps sounding, a release tail rings on, a clip note crossing the loop end
+// still releases, an arpeggiator carries on with the held keys, and a note recorded across the
+// seam is stored as two notes — up to the loop end, and on from the loop start.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class LoopSeamTests
+{
+ private const double Sr = 48000.0;
+ private const double Spb = Sr * 60.0 / 120.0; // frames per beat at 120 BPM
+ private const int Chunk = 256;
+ private const int SynthRelease = 4; // Synth param index (normalized, exp 2 ms … 3 s)
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ foreach (var r in HeldKey()) yield return r;
+ foreach (var r in ReleaseTail()) yield return r;
+ foreach (var r in ClipNoteAcrossEnd()) yield return r;
+ foreach (var r in Arpeggiator()) yield return r;
+ foreach (var r in RecordAcrossSeam()) yield return r;
+ foreach (var r in RoutedAcrossSeam()) yield return r;
+ }
+
+ private static float Beats(NotaEngine e, double beats)
+ {
+ var b = new float[Chunk * 2];
+ int frames = (int)Math.Round(beats * Spb);
+ double sq = 0; int n = 0;
+ for (int done = 0; done < frames; done += Chunk)
+ {
+ e.RenderOffline(b, Chunk, Sr);
+ foreach (var v in b) { sq += v * (double)v; n++; }
+ }
+ return n > 0 ? (float)Math.Sqrt(sq / n) : 0f;
+ }
+
+ // An armed Synth track with a 1-bar loop (beats 0–4), stopped at 0.
+ private static NotaEngine Looped(out int track)
+ {
+ var e = new NotaEngine();
+ e.SetBpm(120);
+ e.SetMetronome(false);
+ e.SetCountIn(0);
+ track = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(track, 0);
+ e.SetTrackArmed(track, true);
+ e.SetLoop(true, 0.0, 4.0);
+ e.StopTransport();
+ e.Seek(0.0);
+ e.RenderOffline(new float[Chunk * 2], Chunk, Sr);
+ return e;
+ }
+
+ private static bool Near(double a, double b, double tol = 0.05) => Math.Abs(a - b) <= tol;
+
+ private static List<double[]> Notes(NotaEngine e, int track, int pitch)
+ {
+ var all = new List<double[]>();
+ for (int c = 0; c < 64 && e.TryGetClipInfo(track, c, out var ci); c++)
+ foreach (var n in e.GetClipNotes(track, c))
+ if (n.Pitch == pitch) all.Add(new[] { ci.StartBeat + n.StartBeat, n.LengthBeats });
+ return all.OrderBy(x => x[0]).ToList();
+ }
+
+ // A key held across the wrap keeps sounding.
+ private static IEnumerable<(bool, string)> HeldKey()
+ {
+ using var e = Looped(out _);
+ e.Play();
+ Beats(e, 3.0);
+ e.NoteOn(60, 0.8f);
+ float before = Beats(e, 0.75); // to ~3.75
+ Beats(e, 0.5); // across the seam, to ~0.25
+ double pos = e.PositionBeats;
+ float after = Beats(e, 0.5);
+ e.NoteOff(60);
+ e.StopTransport();
+ yield return (pos < 1.0 && before > 1e-3 && after > before * 0.5,
+ $"loop seam: a held key keeps sounding after the wrap (rms {before:F4} → {after:F4}, pos {pos:F2})");
+ }
+
+ // A note released just before the loop end rings out its release tail into the next pass.
+ private static IEnumerable<(bool, string)> ReleaseTail()
+ {
+ using var e = Looped(out int t);
+ e.PluginParamSet(t, -1, SynthRelease, 0.8f); // ~0.7 s ≈ 1.4 beats at 120 BPM
+ e.AddMidiClip(t, 0.0, 4.0);
+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 3.0, 0.9, 0.9f) });
+ e.Seek(2.0);
+ Beats(e, 0.01);
+ e.Play();
+ Beats(e, 2.0); // past the seam at 4.0, to ~0.0
+ double pos = e.PositionBeats;
+ float tail = Beats(e, 0.25);
+ e.StopTransport();
+ yield return (pos < 1.0 && tail > 1e-3,
+ $"loop seam: a release tail rings on after the wrap (rms {tail:F4}, pos {pos:F2})");
+ }
+
+ // A clip note running past the loop end is released at the seam: nothing hangs.
+ private static IEnumerable<(bool, string)> ClipNoteAcrossEnd()
+ {
+ using var e = Looped(out int t);
+ e.AddMidiClip(t, 0.0, 8.0);
+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 3.0, 3.0, 0.9f) }); // 3.0 → 6.0
+ e.Seek(2.5);
+ Beats(e, 0.01);
+ e.Play();
+ float sounding = Beats(e, 1.0); // the note sounds from 3.0
+ Beats(e, 1.0); // across the seam, to ~0.5
+ float after = Beats(e, 1.0); // 0.5 → 1.5: no note in the loop there
+ e.StopTransport();
+ yield return (sounding > 1e-3 && after < 1e-4,
+ $"loop seam: a clip note crossing the loop end releases, no hanging note (rms {sounding:F4} → {after:F6})");
+ }
+
+ // An arpeggiator keeps arpeggiating a key held across the wrap (no pattern reset).
+ private static IEnumerable<(bool, string)> Arpeggiator()
+ {
+ using var e = Looped(out int t);
+ e.AddMidiEffect(t, 0); // Nota Arp
+ e.Play();
+ Beats(e, 3.0);
+ e.NoteOn(60, 0.8f);
+ float before = Beats(e, 0.9);
+ Beats(e, 0.3); // across the seam
+ float after = Beats(e, 1.0);
+ e.NoteOff(60);
+ e.StopTransport();
+ yield return (before > 1e-3 && after > before * 0.5,
+ $"loop seam: the arpeggiator carries on with a key held across the wrap (rms {before:F4} → {after:F4})");
+ }
+
+ // A key held across the seam while recording is stored as two notes: 3.5 → 4.0 and 0.0 → 0.5.
+ private static IEnumerable<(bool, string)> RecordAcrossSeam()
+ {
+ using var e = Looped(out int t);
+ e.SetRecording(true);
+ Beats(e, 3.5);
+ e.NoteOn(64, 0.7f);
+ Beats(e, 1.0); // across the seam, to ~0.5
+ e.NoteOff(64);
+ Beats(e, 0.2);
+ e.Poll();
+ e.SetRecording(false);
+ e.Poll();
+ var n = Notes(e, t, 64);
+ string got = string.Join(", ", n.Select(x => $"{x[0]:F2}+{x[1]:F2}"));
+ yield return (n.Count == 2 && Near(n[0][0], 0.0) && Near(n[0][1], 0.5) && Near(n[1][0], 3.5) && Near(n[1][1], 0.5),
+ $"loop seam: a note recorded across the wrap is split at the loop end ({got})");
+ }
+
+ // The same for MIDI routed in from another track.
+ private static IEnumerable<(bool, string)> RoutedAcrossSeam()
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ e.SetMetronome(false);
+ e.SetCountIn(0);
+ int dst = e.AddInstrumentTrack();
+ int src = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(dst, 0);
+ e.SetTrackBuiltinInstrument(src, 0);
+ e.SetTrackMidiSource(dst, src);
+ e.SetTrackArmed(dst, true);
+ e.SetLoop(true, 0.0, 4.0);
+ e.StopTransport();
+ e.Seek(0.0);
+ e.RenderOffline(new float[Chunk * 2], Chunk, Sr);
+ e.SetRecording(true);
+ Beats(e, 3.5);
+ e.TrackNoteOn(src, 71, 0.8f);
+ Beats(e, 1.0);
+ e.TrackNoteOff(src, 71);
+ Beats(e, 0.2);
+ e.Poll();
+ e.SetRecording(false);
+ e.Poll();
+ var n = Notes(e, dst, 71);
+ string got = string.Join(", ", n.Select(x => $"{x[0]:F2}+{x[1]:F2}"));
+ yield return (n.Count == 2 && Near(n[0][0], 0.0) && Near(n[0][1], 0.5) && Near(n[1][0], 3.5) && Near(n[1][1], 0.5),
+ $"loop seam: a routed note recorded across the wrap is split at the loop end ({got})");
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 4c4c80fd..80043d36 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -365,6 +365,10 @@ if (args.Length >= 1 && args[0] == "--live-record")
{
Console.WriteLine("-- live midi recording --");
foreach (var (ok, label) in LiveRecordTests.Run()) Check(ok, label);
+ Console.WriteLine("-- loop seam --");
+ foreach (var (ok, label) in LoopSeamTests.Run()) Check(ok, label);
+ Console.WriteLine("-- loop record mode --");
+ foreach (var (ok, label) in LoopRecordModeTests.Run()) Check(ok, label);
Console.WriteLine(failures == 0 ? "LIVE RECORD PASSED" : $"LIVE RECORD FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
@@ -14643,6 +14647,10 @@ Console.WriteLine("-- mpe: per-note expression --");
foreach (var (ok, label) in MpeTests.Run()) Check(ok, label);
Console.WriteLine("-- live midi recording --");
foreach (var (ok, label) in LiveRecordTests.Run()) Check(ok, label);
+Console.WriteLine("-- loop seam --");
+foreach (var (ok, label) in LoopSeamTests.Run()) Check(ok, label);
+Console.WriteLine("-- loop record mode --");
+foreach (var (ok, label) in LoopRecordModeTests.Run()) Check(ok, label);
Console.WriteLine("-- nota keys --");
foreach (var (ok, label) in KeysTests.Run()) Check(ok, label);
Console.WriteLine("-- nota mosaic --");