Documentation comes from this release commit, without inheriting newer content. Commit: 371ee4692c.
Adaptive Tempo — rules, contract and wiring
Source: Adaptive Tempo for Piano Simulation App PDF (2026-10-16), replaced on 2026-10-21 by the
pause-driven, tap-windowed model (requirements + design "v2"). The earlier bar-line model (v1),
the pause snap and their struggle / lag-drift / severe-step / ceiling-memory machinery are gone —
there is one model, and this file is its reference. Read it before touching code.
1. Goal
Fewer wait-mode pauses so the song keeps playing smoothly. A hidden per-play tempo multiplier m
slows the song when the player pauses and recovers when they play cleanly. Slowing down buys the
player time to tap on time; after every change they get a settle-in window before being judged again.
2. The model
Counts are in judged taps, not bars or seconds. A tap is a judged note that is not Late/Wait
(late judgement, or the note needed an auto-pause) and not a miss: only taps fill a watch window
and feed the lag median.
- Pause → instant slow-down.
onAutoPause(called once per stop, before the waiting note is judged) dropsmbyslowStep(0.15), clamped tomMin, and starts a fresh watch window. - Second slow-down, after a gap. A pause with at least
secondSlowGap(3) taps since the last slow-down slows once more. Fewer taps → held (hold:gap). At most two slow-downs per allowance. - Safety stop. After two slow-downs, pauses hold (
hold:safety, reported once) until a watch window completes without a pause, which re-arms both. - Warm-up / end freeze. No change before
warmupTaps(8) judged notes (hold:warmup) or in the lastendFreezeBars(2) bars (hold:endOfSong). Windows are not evaluated in the end freeze. - Lag gate. A pause does not slow down a player whose median tap offset is earlier than
−(60000 / songBpm) / slowLagGateSubdivisionms (hold:lagEarly): slowing an early player is the wrong fix. The gate is a beat subdivision (6 → ≈ −250 ms at 40 BPM, −83 ms at 120, −37 ms at 270), derived from the song's original BPM;mnever feeds into it. The median is over the lastlagWindow(8) taps; with fewer thanlagMinSamples(4) it is unknown and never blocks. The pause still spoils its window. - Watch window.
window(8) taps. A window with a pause holds and resets the streak (hold:pauseInWindow). A clean window re-arms the slow-downs; with at leastperfectShare(0.75) Perfect / Perfect+ it passes (hold:stayPassuntil the streak is long enough), otherwise the tempo stays and the streak resets (hold:stayGreat). - Speed-up.
speedUpWindows(2) passing windows in a row, withmbelow the ceiling, queue aspeedUpStep(0.15) speed-up. It is decided insideonNoteJudged(no return value) and returned by the nextonTick, starting at that tick (speed:windows); a pause before then voids it. - Floor / ceiling holds name the state once (
hold:floor,hold:ceiling); every later pause / window in the same state is still a decision, recorded as a neutralhold(R7.3).
Timing judgment and the reflect zone
The policy never measures time itself: the host judges every tap against the original-BPM windows
(Timing tab: 60000 / (bpm × subdivision)) and feeds the policy a grade. The
zone below the hit line is the reflect zone: the Perfect / Great windows mirrored to the late side,
× pauseZoneScale, so wait mode does not call a slightly late tap a pause.
Example at 120 BPM, quarter notes, pauseZoneScale 1:
With pauseZoneScale 0 the reflect zone is off: any freeze is a pause at once. The song freezes at the
line when a note is unpressed; the tap that ends the freeze is judged by how long it took.
How each grade counts in the policy:
The offset the lag median sees is real ms including any time the song sat frozen. Not built (deferred
in the requirements): grading a pause by how long the wait was, and a separate Late grade.
Reason codes
<kind>:<why> — slow:pause, speed:windows, hold: warmup · endOfSong · gap · safety ·
lagEarly · floor · ceiling · pauseInWindow · stayPass · stayGreat · and a bare hold,
plus clamp:config (a config change moved m into the band) and force:devtool. Every pause and
every window boundary is a trace entry (R7.3); only the reason of a state-entry hold (floor,
safety, ceiling) is not repeated while the state lasts — the repeat is a bare hold.
3. Decisions kept from the original design
- Wait-mode and scoring stay exactly as today. The policy treats "this note needed an
auto-pause" as the Late/Wait signal regardless of how the engine grades the resume tap. No change
to
resolveAutoPauseResumeJudgement,perfectLateor stars. (The resume graces it reads are fixed wall-clock times — 0.5 s Perfect, 1.2 s Late — never scaled by BPM orm.) - Real-ms windows: a window of W ms is
W/1000 × ticksPerSecond × mticks. BPM scaling stays as it is today (bpmScale, default 1 =60000 / (bpm × sub)— see the Timing tab), andmmust never feedcomputeSongBpm. - Ramp is time-domain (progress = elapsed playing time / ramp duration, so a pause freezes it
for free). Smoothstep integrates in closed form: ticks advanced over progress
p=tps × T × (m0·p + (m1−m0)(p³ − p⁴/2)), withT = (endTick − startTick) / (tps × (m0+m1)/2); the tick→time inversion is numeric. - Recorded backing is muted (short fade) while
m < 0.995; the SoundFont melody/rhythm tracks follow the ramp. No native code, no time-stretch. - Active only when wait-mode auto-pause is enabled, the remote flag is on, and the mode is normal song gameplay. OFF for Learn, tutorial, auto-play and any mode without auto-pause.
- Everything is JS/TS + worklets. No change under
modules/piano-audio-engine/ios/or any native dependency — the prebuilt runtime (bun runtime:start --latest) must keep working. - Policy thresholds live in a valibot-validated Remote Config object, with an
enabledswitch (default OFF). The fullmtrace is logged per play for tuning.
4. Interface contract
Units: linear song ticks everywhere (see packages/rhythm-engine/src/timeline/linearize.ts); the
policy is pure and clock-free.
AdaptiveTempoConfig (every number; counts are taps, nothing but the lag gate is a duration). The
Spec name column is the key in the v2 requirements / design (R5, design §3); the Export JSON of the
DevTool uses the repo key.
sanitizeAdaptiveTempoConfig keeps mMin in [0.5, 1] and mMax in [mMin, 1] (both on the 0.001 grid the
multiplier lives on), steps at least 0.01, perfectShare and the five score numbers in [0, 1], counts
whole numbers capped at 64, lagMinSamples in [1, lagWindow], and drops non-finite values.
forceMultiplier is kept in [0.5, 1].
5. How it is wired
- Active only when the flag is on (Remote Config, or the dev override in a development build) AND
wait-mode auto-pause is on AND the run is a normal song. Decided once per play, when the controller
is built (
useAdaptiveTempo); flipping the flag mid-play waits for the next play. Learn, the tutorial and the labs never mount a provider, so they run atm = 1exactly as before. - Inactive costs nothing: no adaptive callbacks → no per-step tempo publish; windows use
m = 1. - Per play:
createAdaptiveTempo({ barTicks, endTick, ticksPerSecond, songBpm }, config)withsongBpm= the chart's authored BPM at song time 0;adapter.reset()+controller.resetTempo()on start and on teardown. - Events (
events.ts,adapter.ts):onTap→NoteJudgedEvent(tooEarly→early; offset in real ms =(tapTick − noteTick) / (ticksPerSecond × m) × 1000, plus the wall-clock time the song sat frozen when the tap resumed a pause;neededAutoPause= the tap resumed a pause). A claim-less press (wrong key, or a right key on a tile not on screen yet) is a stray tap attached to the next judged note; a right key on a visible tile before the Early window is a judgedearlynote.onMiss→ onemissper unclaimed note.onAutoPause(tick)→policy.onAutoPauseonce the freeze outlasts the pause zone (at once withpauseZoneScale: 0); an instant step it answers with goes straight tocontroller.applyTempoRampwhile the song is still stopped.onStep(tick)→policy.onTick(tick)before the notes of that step are judged; a returned speed-up goes tocontroller.applyTempoRamp. Every tick and multiplier the adapter sees is the LANE's (useAdaptiveTempovisualClock: the tick on screen, mirrored by the rhythm engine), the same clock taps and misses are judged against — not the audio clock (piano.md — Gameplay clock). - Pause zone (
pauseZoneScale, read by the adapter): the Perfect+Great zone mirrored below the hit line. A freeze counts as a pause only when nothing was pressed forgreatMs × pauseZoneScale; a tap inside the zone is judged as a normal (late) Perfect / Great. - Hot path: plain closures over refs; the hook never sets React state. The only React commits are the dev HUD leaf (≈4 Hz, development builds only).
- Render side:
TempoMultiplierContext←tempoMultiplierSvandTempoMultiplierFloorContext← the policy floor (hold-beam atlas bake height) wrapPlayScreenGameplayGroupwhile active. - Recorded backing: while
m < 0.995(BACKING_TEMPO_HOLD_BELOW)BackingScheduleTracksoft-pauses the recording and ignores auto-pause/resume; back at original speed it seeks to the song tick and restarts it. A recording withoutseekis left playing. SoundFont melody/rhythm lanes follow the ramp.
6. Config, flag and profiles
Remote Config key adaptive_tempo (JSON string). The console's thresholds are switched OFF for now
(ADAPTIVE_TEMPO_RC_THRESHOLDS_ENABLED = false in src/features/piano/adaptive-tempo/setup.ts): the
numbers come from the app's defaults and, where tuning is honoured, the DevTool's live tuning, so the
model can be tuned in one place on the DevTool and the app. The enabled switch still works (default off: nothing runs until the console sets true), and
the DevTool reports no Remote Config overrides. Flip the constant to let the console's thresholds apply
again.
enabled— default false; the console value overrides it, sotrueswitches adaptive tempo on.profile— only"default"exists. A retired name ("damped") is read as"default", and a key the policy no longer has (speedBigStep,slowStruggle, …) is ignored, so an old console value keeps working.- any other key — one
AdaptiveTempoConfigthreshold (flat, optional numbers). Ignored while the console's thresholds are off; laid over the profile and sanitized when they are on.
Dev override (development builds and builds with EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1; a store build
ignores it): tap the HUD pill on the play screen to cycle rc → off → default (persisted in MMKV
adaptive-tempo-dev, effective from the next play); env EXPO_PUBLIC_RC_ADAPTIVE_TEMPO=1|default|0;
e2e builds: EXPO_PUBLIC_E2E=1 + EXPO_PUBLIC_E2E_ADAPTIVE_TEMPO=1 forces it on.
Desktop DevTool (docs/devtool.md, protocol v13): the Adaptive
tempo tab shows ON/OFF and why, the live m, the stats and decisions of the current / last play, the
numbers in force, a change log, a Play report and sliders for every threshold. Its simulator runs the
REAL policy against a model player on a synthetic song or a real chart (lib/adaptive-sim.ts), and
scripts/tune-adaptive-tempo.ts searches the v2 numbers against 8 player scenarios (lib/adaptive-scenarios.ts).
DevTool presets (one click replaces the whole tuning; measured on 5 real charts + 2 long songs × 8 scenarios × 8 unseen seeds — each is a trade-off, the default stays the best overall):
Dev HUD: AT <profile> m <live>→<target> <last decision reason> [dev: <mode>, tap to cycle]; hidden
in release builds. The trace is logged in development builds as [adaptive-tempo] … decision … lines and
one … summary … line per play.
7. Verification and what is not done
- Unit tests:
packages/rhythm-engine/tests/adaptive-tempo.test.ts(R1–R4, lag gate, BPM scaling, one-time reasons),src/features/piano/adaptive-tempo/__tests__/, the DevTool'stests/adaptive-*.test.ts. - Not validated: the lag gate and the numbers above are untuned starting points; the playtest replay
(
tools/replay_v2.py) lives outside this repo and was not run. A replay of recorded taps cannot validate the lag gate anyway (recorded taps do not react to tempo) — it needs a closed-loop playtest. - Deep recovery is slow. Climbing from the floor takes about two windows per 0.15 step. Levers:
speedUpWindows: 1with a 12-tap window (the DevTool's Quick recovery preset) or a biggerspeedUpStep. - Every pause costs a slow-down, so a player who blanks often is held low; the simulator shows it.
- Cost on the JS thread (bun, warmed; Hermes is several times slower):
onStep≈ 0.2–0.5 µs,onTap≈ 4 µs — the policy is not the load. The DevTool telemetry is:barLog.getBars()≈ 240 µs per rebuild (96 bars) and a full state push ≈ 1 ms / 66 KB (384 notes, 96 bars), only in a development build or one with the desktop tools compiled in. The per-bar / per-note tables are therefore refreshed at 1 Hz (the live gauge stays at 4 Hz). - What reaches audio: a slow-down lands while the sequencer is paused (wait mode), so only the tick → time mapping changes. A speed-up (or a DevTool force / band clamp) lands while it runs:
RhythmSequencer.changeTempohard-stops the voices queued inside the 0.15 s lookahead and re-issues them on the new mapping. The recorded backing is soft-paused belowm = 0.995and re-seeked and restarted when the tempo is back at it, so a play that keeps probing 0.9 ↔ 1.0 restarts the backing each time. Draggingfloor/ceilingpast the livemin the DevTool re-ramps per step. - Deviations from the v2 requirements / design documents (decided, not oversights):
- v1 (
barLine) andsnapare gone, so R8.2, the Constraints aboutpauseMode: 'barLine'and design §1 ("a third mode next to snap and barLine") no longer apply: there is one model and nopauseMode. - Design §2.4 lets
resetfall back to a 120 BPM beat; R6a.5 forbids a silent default. R6a.5 wins: a play without a validsongBpmthrows. The BPM is given when the policy is built for a play (one per play), not toreset(). - Config keys follow the spec (
mMin,mMax,lagWindow,rampBars,endFreezeBars) and addlagMinSamples,pauseZoneScale(the "reflect zone"). The informational struggle scoreS(and its five numbers) was dropped. tools/replay_v2.pyand the playtest CSVs are not in this repo, so R8.3 (replay comparison) was not run.
- v1 (
- No analytics event for the play summary: the trace is development-build logs plus the DevTool tab.
- Not play-tested on device / simulator by the author. Native code untouched.
- Song-segment clips are not phase-corrected for bars. Mid-song time-signature changes are lost at
serialization (
ChartJsonkeeps the first one). Ad "played seconds" count song time, which is shorter than wall time while slowed. - Quality bar: repo rules apply (see
AGENTS.md). Maestro / simulator e2e (bun run e2e:*) is never run by an agent; flows08–10andscripts/e2e-adaptive-tempo-*.tswere updated for this model but not run.
8. Playing it by hand (iOS simulator)
bun runtime:start --latest(the prebuilt Debug simulator app; no native step). Metro serves this branch's JS.- Open any normal song (not the tutorial, not AUTO). Tap the pill at the top right until it reads
dev: default; start the song again (settings apply to the next play). - Wait-mode is on by default: after the warm-up (8 notes) let a tile reach the line and leave it.
mdrops by 0.15 at once (slow:pause) and tiles spread further apart; the recorded backing mutes. - Play cleanly: after two clean windows (16 taps)
mramps up 0.15 (speed:windows) and the backing returns in sync. A pause right after a slow-down is held for 3 taps (hold:gap). - Score / stars / combo are as they would be without it; timing windows feel the same in real time; the
Metro console prints the
[adaptive-tempo]lines and a summary on leaving. - Not active (the pill says why) in: the tutorial song, AUTO play, Learn.