v1.0.11 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: cc3dd17e61.

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.

ItemRule
Rangem in mMin 0.50 … mMax 1.00 — the band is 0.50–1.00 and a config cannot leave it. Never faster than the original tempo (mMax is capped at 1, no ceiling memory)
Startm = mMax (1.00 unless the ceiling is lower), all logs cleared on every play / restart / retry. Nothing carries over
Slow-downA wait-mode pause drops m instantly, in the pause itself (no ramp — the song is frozen, so the jump is never heard)
Speed-upDecided when a watch window fills, ramped over rampBars bars (smoothstep)
ScrollConstant px/sec; notes spread further apart when slower (y = (noteTick − tick) / (ticksPerPixel × m))
AudioSoundFont only, pitch unchanged. Recorded backing is NOT stretched (§5)
WindowsReal ms, based on the ORIGINAL song BPM, never on m
Player-facingInvisible. No effect on score or stars

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) drops m by slowStep (0.15), clamped to mMin, 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 last endFreezeBars (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) / slowLagGateSubdivision ms (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; m never feeds into it. The median is over the last lagWindow (8) taps; with fewer than lagMinSamples (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 least perfectShare (0.75) Perfect / Perfect+ it passes (hold:stayPass until the streak is long enough), otherwise the tempo stays and the streak resets (hold:stayGreat).
  • Speed-up. speedUpWindows (2) passing windows in a row, with m below the ceiling, queue a speedUpStep (0.15) speed-up. It is decided inside onNoteJudged (no return value) and returned by the next onTick, 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 neutral hold (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:

Zone (vs the hit line)WindowWhat it is
Perfect+±31 msPerfect
Perfect±250 msPerfect (late side = late Perfect, from the reflect zone)
Great±500 msGreat (late side = late Great)
Early−1000 … −500 msone-sided, before the line
Late = pauselater than +500 ms (Great × pauseZoneScale)the song freezes and onAutoPause is called once

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:

GradeA tap (fills a window, moves the lag median)Counts as Perfect for perfectShare
Perfect+ / Perfect / late Perfectyesyes
Great / late Greatyesno
Earlyyesno
Late = pause (neededAutoPause) or lateno (a pause, not a tap)no
missnono

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

  1. 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, perfectLate or stars. (The resume graces it reads are fixed wall-clock times — 0.5 s Perfect, 1.2 s Late — never scaled by BPM or m.)
  2. Real-ms windows: a window of W ms is W/1000 × ticksPerSecond × m ticks. BPM scaling stays as it is today (bpmScale, default 1 = 60000 / (bpm × sub) — see the Timing tab), and m must never feed computeSongBpm.
  3. 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)), with T = (endTick − startTick) / (tps × (m0+m1)/2); the tick→time inversion is numeric.
  4. Recorded backing is muted (short fade) while m < 0.995; the SoundFont melody/rhythm tracks follow the ramp. No native code, no time-stretch.
  5. 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.
  6. 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.
  7. Policy thresholds live in a valibot-validated Remote Config object, with an enabled switch (default OFF). The full m trace 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.

// packages/rhythm-engine/src/adaptive-tempo/types.ts
export interface TempoRamp { startTick; endTick; m0; m1 }   // endTick === startTick: instant step
export interface AdaptiveTempoChart { barTicks; endTick; ticksPerSecond; songBpm }  // songBpm required
export const DEFAULT_ADAPTIVE_TEMPO_CONFIG: AdaptiveTempoConfig;
export function createAdaptiveTempo(chart, config?): AdaptiveTempo;   // throws without a valid songBpm
interface AdaptiveTempo {
  onNoteJudged(e: NoteJudgedEvent): void;
  onAutoPause(tick): TempoRamp | null;     // instant slow-down, or null (held)
  onTick(tick): TempoRamp | null;          // a queued speed-up; bar lines decide nothing
  getRecentPauseCount(): number;           // pauses within the last `window` judged notes
  getTargetMultiplier(); getTrace(); getSignals(); getConfig();
  updateConfig(cfg); clampToBand(tick, frozen?); forceMultiplier(m, tick, frozen?); reset();
}

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.

Repo keySpec nameDefaultMeaning
mMinmMin0.5lowest multiplier (the band is 0.50–1.00)
mMaxmMax1highest multiplier (≤ 1, the original BPM); a play starts here, so a ceiling below 1 starts below 1.0
slowStepslowStep0.15instant step per pause
secondSlowGapsecondSlowGap3taps before a second slow-down
slowLagGateSubdivisionslowLagGateSubdivision6lag gate = −beat ÷ n (untuned start)
lagWindowlagWindow8taps the lag median is taken over
lagMinSamples(not in the spec)4fewer taps than this: lag unknown, the gate never blocks (kept from the bar-line model; one early tap must not block a slow-down)
windowwindow8taps per watch window
perfectShareperfectShare0.75Perfect share for a passing window
speedUpWindowsspeedUpWindows2passing windows in a row to speed up
speedUpStepspeedUpStep0.15speed-up step
rampBarsrampBars1bars a speed-up ramps over
warmupTapswarmupTaps8judged notes before any change
endFreezeBarsendFreezeBars2frozen last bars
pauseZoneScale(the "reflect zone" of R1; no number in the spec)1host-side: late-zone size, 0 = off (any freeze is a pause at once); the policy never reads it

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

PieceWhere
Pure policy, config sanitizerpackages/rhythm-engine/src/adaptive-tempo/ (createAdaptiveTempo, computeBarTicksForChart, resolveAdaptiveTempoConfig)
Ramp-aware clock / schedulerTransport.setRamp, RhythmSequencer.applyTempoRamp, PlayController.applyTempoRamp / getTempoMultiplier / resetTempo, useRhythmEngine → tempoMultiplierSv, onStep, onAutoPause, onStrayTap, onTap(res, TapInfo)
Recorded-backing holdBackingScheduleTrack (rhythm-engine)
Real-ms windows + tempo-scaled scrolljudgement-window-scaling.ts, components/tempo-scroll.ts, tempo-multiplier-context.ts
Host wiringsrc/features/piano/adaptive-tempo/ (useAdaptiveTempo, adapter, bar-log, events, setup, dev-store, hud-store, log, e2e-switch), components/AdaptiveTempoDevHud.tsx, PlayScreenBody, useMagicJudgement
Remote Configadaptive_tempo in src/core/config/ (schema, defaults, RC_KEY_MAP, selectAdaptiveTempoRc)
  • 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 at m = 1 exactly 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) with songBpm = 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 judged early note. onMiss → one miss per unclaimed note. onAutoPause(tick) → policy.onAutoPause once the freeze outlasts the pause zone (at once with pauseZoneScale: 0); an instant step it answers with goes straight to controller.applyTempoRamp while the song is still stopped. onStep(tick) → policy.onTick(tick) before the notes of that step are judged; a returned speed-up goes to controller.applyTempoRamp. Every tick and multiplier the adapter sees is the LANE's (useAdaptiveTempo visualClock: 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 for greatMs × 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 ← tempoMultiplierSv and TempoMultiplierFloorContext ← the policy floor (hold-beam atlas bake height) wrap PlayScreenGameplayGroup while active.
  • Recorded backing: while m < 0.995 (BACKING_TEMPO_HOLD_BELOW) BackingScheduleTrack soft-pauses the recording and ignores auto-pause/resume; back at original speed it seeks to the song tick and restarts it. A recording without seek is 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": true, "profile": "default", "speedUpWindows": 1 }
  • enabled — default false; the console value overrides it, so true switches 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 AdaptiveTempoConfig threshold (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):

PresetNumbersEffect (vs default)
Defaultnonebest total cost
Quick recoveryspeedUpWindows 1, window 12time too slow ≈ −⅓, ends nearer the player's level; ≈ +18 % pauses; same cost
Smooth (gradual)slowStep 0.05, secondSlowGap 4, speedUpWindows 3, speedUpStep 0.05, perfectShare 0.85biggest 4-bar drop 0.30 → ≈ 0.10, direction changes ≈ −70 %; ≈ 2× the pauses (it stays above the player's level longer)
ProtectiveslowStep 0.2, secondSlowGap 4, speedUpWindows 3, speedUpStep 0.1≈ −30 % pauses, rarely above the player's level; stays slower and drops harder

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's tests/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: 1 with a 12-tap window (the DevTool's Quick recovery preset) or a bigger speedUpStep.
  • 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.changeTempo hard-stops the voices queued inside the 0.15 s lookahead and re-issues them on the new mapping. The recorded backing is soft-paused below m = 0.995 and 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. Dragging floor / ceiling past the live m in the DevTool re-ramps per step.
  • Deviations from the v2 requirements / design documents (decided, not oversights):
    1. v1 (barLine) and snap are gone, so R8.2, the Constraints about pauseMode: 'barLine' and design §1 ("a third mode next to snap and barLine") no longer apply: there is one model and no pauseMode.
    2. Design §2.4 lets reset fall back to a 120 BPM beat; R6a.5 forbids a silent default. R6a.5 wins: a play without a valid songBpm throws. The BPM is given when the policy is built for a play (one per play), not to reset().
    3. Config keys follow the spec (mMin, mMax, lagWindow, rampBars, endFreezeBars) and add lagMinSamples, pauseZoneScale (the "reflect zone"). The informational struggle score S (and its five numbers) was dropped.
    4. tools/replay_v2.py and the playtest CSVs are not in this repo, so R8.3 (replay comparison) was not run.
  • 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 (ChartJson keeps 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; flows 08–10 and scripts/e2e-adaptive-tempo-*.ts were updated for this model but not run.

8. Playing it by hand (iOS simulator)

  1. bun runtime:start --latest (the prebuilt Debug simulator app; no native step). Metro serves this branch's JS.
  2. 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).
  3. Wait-mode is on by default: after the warm-up (8 notes) let a tile reach the line and leave it. m drops by 0.15 at once (slow:pause) and tiles spread further apart; the recorded backing mutes.
  4. Play cleanly: after two clean windows (16 taps) m ramps 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).
  5. 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.
  6. Not active (the pill says why) in: the tutorial song, AUTO play, Learn.