# SPRINT v0.1.46 - NEXT
## Kimi: Fix MIDI Arrangement Blocker + Rhythm Repair

**Owner:** Kimi via OpenCode  
**Reviewer:** Codex (orquestador)  
**Date:** 2026-04-04  
**Mode:** Remote Script fix + manual repair of open project `song.als`  
**Prerequisite:** Ableton Live restart required after code changes

---

## 0. Handoff from v0.1.45

### What Kimi accomplished
- 11 audio clips added to arrangement (tracks 12 and 11)
- 3 session clips created on HARMONY_PIANO_MIDI with Am-F-G-C chord content
- Honest reporting: did not claim false completion

### What remains broken
- **HARMONY_PIANO_MIDI** has 0 arrangement clips — the core sprint goal was not met
- Drum coverage: 40.4% (target ≥ 55%)
- Trailing gaps: AUDIO TOP LOOP 168-356 beats, AUDIO PERC ALT 176-356 beats
- Longest harmonic gap: 339 beats
- Longest drum gap: 188 beats

### Root cause of the blocker (Codex analysis)

The MIDI arrangement clip creation fails because `_record_session_clip_to_arrangement` uses
`time.sleep()` inside the Live Remote Script thread. This is the critical mistake:

```python
# abletonmcp_init.py lines 1423-1426
clip_slot.fire()
time.sleep(0.12)          # ← blocks the Remote Script thread
self._start_playback()
time.sleep(record_seconds) # ← blocks for several seconds
```

The Live API runs on a cooperative thread model. Sleeping inside the Remote Script thread
freezes the entire Live API event loop, so playback never actually starts, the session clip
never records into arrangement, and `_locate_arrangement_clip` returns nothing after polling.

`track.create_clip(start_time, length)` in `_create_arrangement_clip` also fails because
Live 12 does not expose `create_clip` on MIDI tracks in arrangement — only on audio tracks
via `create_audio_clip`. The `hasattr` check returns `False` for MIDI tracks, sending
control directly to the broken sleeping fallback.

---

## 1. Sprint Goal

Two deliverables, in order of priority:

1. **Fix the Remote Script** so MIDI arrangement clips can be created reliably
2. **Use the fix immediately** to populate HARMONY_PIANO_MIDI and finish rhythm repairs

Both must be validated in the live open project before the sprint is declared done.

---

## 2. Technical Task — Fix MIDI Arrangement Clip Creation

### T0. Understand what is available in Live 12

Before writing any fix, Kimi must confirm which Live API methods exist on the active track.
Use the MCP diagnostic tool or a short inspection block to answer:

```python
# Check via a get_track_info call or a live log inspection
# Does the MIDI track have: create_clip? arrangement_clips? clips?
```

The relevant log lines from v0.1.45 would be `[ARR_DEBUG]` entries — check these in
`C:\Users\ren\AppData\Roaming\Ableton\Live 12.0.15\Preferences\Log.txt`.

### T1. Implement a working MIDI arrangement clip path

**File to edit:** `abletonmcp_init.py`  
**Function:** `_create_arrangement_clip` (line ~1462)

**Strategy: use `schedule_message` instead of `time.sleep`**

Live's Remote Script API provides `self.schedule_message(delay_ticks, callback)`.
This is the correct async mechanism. However, because our server uses a socket/request model
(not a fire-and-forget model), a true async schedule is awkward to return from.

**Recommended fix: abandon the record-based approach for MIDI clips.**

Instead, use the Live MIDI clip insertion via the `clip_slots` + `arrangement_record` API
if available, or use the `Live.Song.Song` arrangement API directly.

The correct Live 12 path for inserting a MIDI clip into an arrangement is:

```python
# Option A: Live.Song.Song.create_midi_clip (if available in your build)
clip = self._song.create_midi_clip(track, start_time, length)

# Option B: force arrangement record via song-level API
# self._song.arrangement_record  (write a mini clip without playback sleep)

# Option C: use the track's clip_slots[0].create_clip then copy notes,
#           then use self._song.duplicate_clip_to_arrangement or equivalent
```

If none of these work, the safe minimal fix for v0.1.46 is:

**Remove the `time.sleep()` calls from `_record_session_clip_to_arrangement` and replace
with a `schedule_message`-based deferred check**, turning it into a two-step operation:
1. Fire the session clip + start playback in step 1
2. Return immediately with status `pending`
3. Let the caller poll `_locate_arrangement_clip` after a real delay outside Live thread

For this sprint, the pragmatic minimum is:

```python
# In _record_session_clip_to_arrangement, replace:
time.sleep(record_seconds)
# With:
# Return a "pending" dict and expose a separate poll tool
# OR: use very short sleeps in a loop with schedule_message between polls
```

**The absolute minimum acceptable fix:**

Remove dead sleeping and replace the verify loop approach with a Live-thread-safe
alternative. Even if we cannot fully schedule it, reducing the sleep from `record_seconds`
(which can be 10+ seconds) to 0 and relying on a post-call `get_track_info` to confirm
materialization is better than blocking the thread.

### T2. Compile and verify before using

After every change to `abletonmcp_init.py`:

```powershell
python -m py_compile "C:\ProgramData\Ableton\Live 12 Suite\Resources\MIDI Remote Scripts\abletonmcp_init.py"
```

Then request an Ableton Live restart from the user. This is **mandatory** because
`abletonmcp_init.py` is loaded at startup by Live's Remote Script engine.

After restart, run:

```powershell
Get-Content "C:\Users\ren\AppData\Roaming\Ableton\Live 12.0.15\Preferences\Log.txt" -Tail 60
```

Confirm no Python errors in the log before calling any MCP tools.

---

## 3. Project Repair Tasks

These tasks only start after T1 + T2 are verified working.

### T3. Populate HARMONY_PIANO_MIDI in Arrangement

The 3 session clips from v0.1.45 are already on track 15 with Am-F-G-C content.
Use the now-working `duplicate_clip_to_arrangement` or `create_arrangement_clip` to
place them in the arrangement at positions that fill harmonic holes.

Minimum target positions (in beats, based on v0.1.45 audit):
- 0-16 (intro harmonic anchor)
- 32-48 (pre-drop fill)
- 64-80 (drop A support)
- 128-144 (break harmonic)
- 192-208 (drop B support)
- 256-272 (build out)
- 320-336 (outro anchor)

Do not stop at 2-3 clips. The track needs real coverage across ≥ 60% of the song.

If `duplicate_clip_to_arrangement` still fails after T1, use `create_arrangement_clip`
+ `add_notes_to_arrangement_clip` directly for each position. Log every call and result.

### T4. Fill trailing rhythm gaps

Continue the audio repair started in v0.1.45.

Remaining gaps to fill:

**AUDIO TOP LOOP (track 12):**
- Beats 168-224: 56-beat trailing void — add 7 × 8-beat clips
- Beats 232-288: partial — add as needed
- Use samples from: `libreria\reggaeton\perc loop\`

**AUDIO PERC ALT (track 11):**
- Beats 176-288: 112-beat trailing void — add 7 × 16-beat clips
- Use same sample pool

Sample paths confirmed working from v0.1.45:
```
C:\ProgramData\Ableton\Live 12 Suite\Resources\MIDI Remote Scripts\libreria\reggaeton\perc loop\! (extra I oneshot) perc 1.wav
C:\ProgramData\Ableton\Live 12 Suite\Resources\MIDI Remote Scripts\libreria\reggaeton\perc loop\! (extra I oneshot) perc 2.wav
C:\ProgramData\Ableton\Live 12 Suite\Resources\MIDI Remote Scripts\libreria\reggaeton\perc loop\! (extra I oneshot) perc 3.wav
C:\ProgramData\Ableton\Live 12 Suite\Resources\MIDI Remote Scripts\libreria\reggaeton\perc loop\! (extra I oneshot) perc 4.wav
C:\ProgramData\Ableton\Live 12 Suite\Resources\MIDI Remote Scripts\libreria\reggaeton\perc loop\! (extra I oneshot) perc 5.wav
```

Note: perc 1 is the most reliable. Use perc 2-5 for variation, not as primary.

### T5. Audit after all edits

Run `audit_project_coherence()` and `get_track_info` for tracks 11, 12, and 15 after all edits.

Target metrics post-sprint:
- `longest_harmonic_gap < 64 beats`
- `longest_drum_gap < 64 beats` (relaxed from 32, which is more realistic given current state)
- `harmonic_coverage_ratio >= 0.70` (must reflect MIDI backbone, not just audio tracks)
- `drum_coverage_ratio >= 0.55`

---

## 4. Track State Reference (from v0.1.45 + PROJECT_AUDIT)

| Track | Index | Type | Current state |
|-------|-------|------|---------------|
| AUDIO PERC ALT | 11 | Audio | 12 clips, trailing gap 176-288 |
| AUDIO TOP LOOP | 12 | Audio | 13 clips, trailing gap 168-288 |
| AUDIO SYNTH LOOP | 13 | Audio | some coverage, intro/outro absent |
| AUDIO SYNTH PEAK | 14 | Audio | short accent clips only |
| HARMONY_PIANO_MIDI | 15 | MIDI | 0 arrangement clips, 3 session clips |

Song tempo: **95 BPM**  
Song key: **A minor**  
Total arrangement length: ~416 seconds / ~356+ beats  
Track count: 16 regular + 4 returns

---

## 5. Required Workflow

1. Read Ableton log from v0.1.45 — look for `[ARR_DEBUG]` entries to confirm what the
   Live API actually returned when `create_clip` was called
2. Edit `abletonmcp_init.py` with the fix
3. Compile and confirm clean
4. Tell the user to restart Ableton Live
5. After restart: reconnect MCP and verify with `get_session_info`
6. Confirm session clip still exists on track 15 (they may survive restart)
7. Perform T3 + T4
8. Run T5 audit
9. Write validation report

---

## 6. Acceptance Criteria

Sprint passes only if ALL of these are true:

- [ ] `abletonmcp_init.py` compiles cleanly before restart
- [ ] MCP connects after restart (confirmed via `get_session_info`)
- [ ] `create_arrangement_clip` or `duplicate_clip_to_arrangement` succeeds for at least
      one MIDI clip on track 15 (verified via `get_track_info` showing `arrangement_clip_count >= 1`)
- [ ] HARMONY_PIANO_MIDI has ≥ 5 arrangement clips by end of sprint
- [ ] Trailing gaps on tracks 11 and 12 are materially reduced (not just first few beats)
- [ ] `audit_project_coherence()` shows improvement from v0.1.45 baseline
- [ ] Exact MCP calls and results are logged in the validation report

---

## 7. Automatic Failure Conditions

Fail the sprint if any of these are true:

- Report claims MIDI clips were created but `get_track_info(track_index=15)` shows
  `arrangement_clip_count: 0`
- The fix to `abletonmcp_init.py` was not compiled before restart
- The sprint was completed without requesting a Live restart after editing the Remote Script
- Only session clips were created and arrangement remained empty
- The sleeping sleep fix was "fixed" by making sleeps shorter without removing the
  fundamental blocker (blocking the Live thread)
- Validation report cites v0.1.45 audit data instead of fresh live MCP calls

---

## 8. Restart Policy

**Ableton restart is required** after changes to `abletonmcp_init.py`.

Kimi must:
1. Stop OpenCode / MCP
2. Tell the user: "Please restart Ableton Live now"
3. Wait for confirmation
4. Then restart OpenCode and reconnect

Do not attempt MCP calls between code change and Live restart.

---

## 9. If the MIDI fix fails completely

If after genuine attempts the Live API still cannot create MIDI arrangement clips,
do not waste the sprint. Switch to this fallback plan:

1. Document exactly what was tried and what error was returned
2. Add a clear `[KNOWN_BLOCKER]` entry to `docs/KNOWN_ISSUES.md`
3. Pivot to maximum audio repair on tracks 11, 12, 13, 14
4. Use `create_arrangement_audio_pattern` to fill as many gaps as possible
5. Focus the remaining session clips on harmonic audio support instead of MIDI

This is honest partial success, not failure — as long as you document it clearly.

---

## 10. Deliverables

Required files:

- `docs/SPRINT_v0.1.46_VALIDATION_REPORT.md`

Required content:
- What fix was applied (exact diff or description of changed lines in `abletonmcp_init.py`)
- Compile result
- Confirmation of Ableton restart
- Fresh `get_session_info` + `get_track_info` calls post-restart
- Exact MCP calls used for arrangement edits
- Before/after `get_track_info` for tracks 11, 12, 15
- `audit_project_coherence()` result
- Clear list of remaining open issues

---

## 11. Open Issues Carried from v0.1.45

| Priority | Issue | Assigned |
|----------|-------|----------|
| P0 | MIDI arrangement clip creation blocked by Remote Script thread sleeping | Kimi (this sprint) |
| P1 | AUDIO TOP LOOP trailing gap 168-356 beats | Kimi (this sprint) |
| P1 | AUDIO PERC ALT trailing gap 176-356 beats | Kimi (this sprint) |
| P2 | 24 mirrored section pairs (visual repetition) | Future sprint |
| P2 | HARMONY_PIANO_MIDI Wavetable device may need re-voicing | Future sprint |
| P3 | Drum coverage still at 40% (kick/clap/hat islands) | Future sprint |
