entangled-worlds-orbiters-shared 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ /** A cancel handle from `armAt`; returns true iff it cancelled an armed-but-unoccurred event. */
2
+ export type CancelHandle = () => boolean;
3
+ /**
4
+ * The neutral backend contract the Transport depends on. No Tone/AudioContext type leaks through the
5
+ * transport's public surface (design doc §0 D1).
6
+ */
7
+ export interface ClockBackend {
8
+ /** Current audio time in seconds. */
9
+ nowSec(): number;
10
+ /** Arm an audio event at a precise future audio time. Returns a cancel handle. */
11
+ armAt(audioTimeSec: number, payload: unknown): CancelHandle;
12
+ }
13
+ interface ArmedRecord {
14
+ audioTimeSec: number;
15
+ payload: unknown;
16
+ armedAtNowSec: number;
17
+ cancelled: boolean;
18
+ occurred: boolean;
19
+ }
20
+ /**
21
+ * Headless, fully deterministic backend. Time only moves when the test advances it (no wall-clock
22
+ * flakiness). Records arms + occurrences for assertions, and actually OCCURS armed events when virtual
23
+ * time passes their target — so tests can prove cancellation, not just callback invocation.
24
+ */
25
+ export declare class VirtualClockBackend implements ClockBackend {
26
+ private _now;
27
+ readonly armed: ArmedRecord[];
28
+ readonly occurrences: Array<{
29
+ audioTimeSec: number;
30
+ payload: unknown;
31
+ }>;
32
+ constructor(startSec?: number);
33
+ nowSec(): number;
34
+ /** Arm an audio event at a precise future audio time. Returns a cancel handle (true if it cancelled). */
35
+ armAt(audioTimeSec: number, payload: unknown): CancelHandle;
36
+ /** Advance virtual audio time. Marks armed events occurred (for cancellation assertions only — the
37
+ * Transport, not the backend, fires them). A cancelled event never occurs. */
38
+ advance(dtSec: number, jitterSec?: number): number;
39
+ /** Events armed at least `leadSec` before their target (proof of look-ahead). */
40
+ armedAheadBy(leadSec: number): ArmedRecord[];
41
+ /** Count of events that actually occurred (not cancelled) — the audible truth. */
42
+ get occurredCount(): number;
43
+ }
44
+ export {};
@@ -0,0 +1,70 @@
1
+ // ClockBackend — the neutral audio-anchored time source the transport depends on.
2
+ //
3
+ // The shared package depends ONLY on this interface. Production injects an AudioContext/Tone-backed
4
+ // implementation; headless tests inject a VirtualClockBackend. No Tone/AudioContext type ever leaks
5
+ // through the transport's public surface (design doc §0 D1).
6
+ //
7
+ // The contract distinguishes ARMING from OCCURRENCE:
8
+ // - `armAt(audioTimeSec, payload)` schedules an audio event AHEAD and returns a CANCEL handle. This
9
+ // is the ONLY thing a real backend must do — wire `node.start(audioTimeSec)` here. The backend is
10
+ // pure audio I/O; it does NOT drive the transport's event lifecycle.
11
+ // - the TRANSPORT self-detects occurrence in its tick (when its audio clock passes `armedTarget`)
12
+ // and runs the per-event fire/reset itself — so a real backend never needs a JS timer to call back.
13
+ // - cancelling before occurrence prevents the sound (pause/seek/rate/loop change cancels armed-but-
14
+ // unplayed audio). Cancelling after occurrence is a no-op.
15
+ /**
16
+ * Headless, fully deterministic backend. Time only moves when the test advances it (no wall-clock
17
+ * flakiness). Records arms + occurrences for assertions, and actually OCCURS armed events when virtual
18
+ * time passes their target — so tests can prove cancellation, not just callback invocation.
19
+ */
20
+ export class VirtualClockBackend {
21
+ _now;
22
+ armed;
23
+ occurrences;
24
+ constructor(startSec = 0) {
25
+ this._now = startSec;
26
+ this.armed = [];
27
+ this.occurrences = [];
28
+ }
29
+ nowSec() {
30
+ return this._now;
31
+ }
32
+ /** Arm an audio event at a precise future audio time. Returns a cancel handle (true if it cancelled). */
33
+ armAt(audioTimeSec, payload) {
34
+ const rec = {
35
+ audioTimeSec,
36
+ payload,
37
+ armedAtNowSec: this._now,
38
+ cancelled: false,
39
+ occurred: false,
40
+ };
41
+ this.armed.push(rec);
42
+ return () => {
43
+ if (rec.occurred || rec.cancelled)
44
+ return false;
45
+ rec.cancelled = true;
46
+ return true;
47
+ };
48
+ }
49
+ /** Advance virtual audio time. Marks armed events occurred (for cancellation assertions only — the
50
+ * Transport, not the backend, fires them). A cancelled event never occurs. */
51
+ advance(dtSec, jitterSec = 0) {
52
+ const step = Math.max(0, dtSec + jitterSec);
53
+ this._now += step;
54
+ for (const r of this.armed) {
55
+ if (!r.cancelled && !r.occurred && r.audioTimeSec <= this._now + 1e-12) {
56
+ r.occurred = true;
57
+ this.occurrences.push(r);
58
+ }
59
+ }
60
+ return this._now;
61
+ }
62
+ /** Events armed at least `leadSec` before their target (proof of look-ahead). */
63
+ armedAheadBy(leadSec) {
64
+ return this.armed.filter((a) => a.audioTimeSec - a.armedAtNowSec >= leadSec - 1e-9);
65
+ }
66
+ /** Count of events that actually occurred (not cancelled) — the audible truth. */
67
+ get occurredCount() {
68
+ return this.occurrences.length;
69
+ }
70
+ }
@@ -0,0 +1,85 @@
1
+ import type { ClockBackend } from './ClockBackend.js';
2
+ export interface LoopSec {
3
+ startSec: number;
4
+ endSec: number;
5
+ }
6
+ export type PlayState = 'playing' | 'paused';
7
+ /** The event handed to `schedule`. `fire` runs at occurrence with (audioTimeSec, atSec). */
8
+ export interface EventSpec {
9
+ atSec: number;
10
+ fire: (audioTimeSec: number, atSec: number) => void;
11
+ payload?: unknown;
12
+ }
13
+ export interface TransportSnapshot {
14
+ playState: PlayState;
15
+ positionSec: number;
16
+ rate: number;
17
+ loop: LoopSec | null;
18
+ }
19
+ export interface AnchoredState {
20
+ playState: PlayState;
21
+ positionSec: number;
22
+ rate?: number;
23
+ anchorAudioSec?: number;
24
+ loop?: LoopSec | null;
25
+ }
26
+ export interface ScheduleStateMeta {
27
+ term?: number;
28
+ seq?: number;
29
+ onApply?: (() => void) | null;
30
+ }
31
+ /** Structural shape of a musical projection — typed here so `./clock` never imports `./clock/musical`. */
32
+ export interface MusicalProjectionLike {
33
+ musicalAt(positionSec: number): unknown;
34
+ }
35
+ export interface TransportOptions {
36
+ lookaheadSec?: number;
37
+ }
38
+ export declare class Transport {
39
+ backend: ClockBackend;
40
+ lookaheadSec: number;
41
+ private _playing;
42
+ private _rate;
43
+ private _anchorBackend;
44
+ private _anchorPos;
45
+ private _events;
46
+ private _nextId;
47
+ private _frameReaders;
48
+ private _loop;
49
+ private _projection;
50
+ private _pending;
51
+ constructor(backend: ClockBackend, opts?: TransportOptions);
52
+ positionSec(): number;
53
+ private _reanchor;
54
+ play(): void;
55
+ pause(): void;
56
+ seekSec(sec: number): void;
57
+ setRate(rate: number): void;
58
+ get rate(): number;
59
+ get playing(): boolean;
60
+ setLoopSec(loop: LoopSec | null): void;
61
+ get loopEnabled(): boolean;
62
+ schedule(spec: EventSpec): number;
63
+ unschedule(id: number): void;
64
+ onTick(cb: (positionSec: number) => void): () => void;
65
+ /** Cancel armed-but-unoccurred audio and clear arm state (does NOT replay already-fired events). */
66
+ private _cancelArmed;
67
+ /** Re-open fired events so they can occur again — only after a POSITION/topology change (seek/loop). */
68
+ private _reopenEvents;
69
+ private _eventLoops;
70
+ /** Transport-seconds distance to an event's NEXT occurrence from `pos` (null = won't occur). */
71
+ private _nextDist;
72
+ setProjection(projection: MusicalProjectionLike | null): void;
73
+ musicalPosition(): unknown;
74
+ applyAnchoredState(s: AnchoredState): void;
75
+ /** Arm an anchored state (with optional control) to apply when audio time reaches `atAudioSec`. */
76
+ scheduleStateChange(atAudioSec: number, state: AnchoredState, meta?: ScheduleStateMeta): void;
77
+ /** Drop pending changes older than a freshly-applied (term,seq) — supersession (Codex fix #4). */
78
+ dropPendingOlderThan(term: number, seq: number): void;
79
+ private _drainPending;
80
+ tick(): void;
81
+ /** Fire armed events whose audio time has arrived, and reset them for re-arm (loop) / mark done. */
82
+ private _detectOccurrences;
83
+ private _maybeWrapLoop;
84
+ snapshot(): TransportSnapshot;
85
+ }
@@ -0,0 +1,268 @@
1
+ // Transport — the seconds-first clock + look-ahead scheduler (design doc §0 D1/D3, §2).
2
+ //
3
+ // Canonical position is SECONDS, derived from the injected ClockBackend's audio time. The musical
4
+ // grid is an OPTIONAL projection (setProjection); with none, the transport is a pure time machine.
5
+ //
6
+ // Scheduling discipline (rewritten after Codex review):
7
+ // - Events are ARMED ahead of their deadline via backend.armAt -> they OCCUR at the precise audio
8
+ // time. An armed event is cancelable; any disruption (pause/seek/rate/loop change) cancels armed-
9
+ // but-unoccurred events so stale audio never plays, then re-arms from the new position.
10
+ // - The look-ahead window is scaled by rate (audio-time, not transport-time).
11
+ // - Looping is handled by computing each event's NEXT occurrence distance (wrapping across the loop
12
+ // boundary), so events just after loopStart are armed during the pre-wrap look-ahead.
13
+ const EPS = 1e-9;
14
+ export class Transport {
15
+ backend;
16
+ lookaheadSec;
17
+ _playing;
18
+ _rate;
19
+ _anchorBackend;
20
+ _anchorPos;
21
+ _events;
22
+ _nextId;
23
+ _frameReaders;
24
+ _loop;
25
+ _projection;
26
+ _pending;
27
+ constructor(backend, opts = {}) {
28
+ this.backend = backend;
29
+ this.lookaheadSec = opts.lookaheadSec ?? 0.1;
30
+ this._playing = false;
31
+ this._rate = 1;
32
+ this._anchorBackend = backend.nowSec();
33
+ this._anchorPos = 0;
34
+ this._events = new Map();
35
+ this._nextId = 1;
36
+ this._frameReaders = new Set();
37
+ this._loop = null;
38
+ this._projection = null;
39
+ this._pending = [];
40
+ }
41
+ // ---- position (seconds is canonical) ------------------------------------------------
42
+ positionSec() {
43
+ if (!this._playing)
44
+ return this._anchorPos;
45
+ return this._anchorPos + (this.backend.nowSec() - this._anchorBackend) * this._rate;
46
+ }
47
+ _reanchor(atPos = this.positionSec()) {
48
+ this._anchorPos = atPos;
49
+ this._anchorBackend = this.backend.nowSec();
50
+ }
51
+ // ---- transport ops ------------------------------------------------------------------
52
+ play() {
53
+ if (this._playing)
54
+ return;
55
+ this._reanchor(this._anchorPos);
56
+ this._playing = true;
57
+ }
58
+ pause() {
59
+ if (!this._playing)
60
+ return;
61
+ this._anchorPos = this.positionSec();
62
+ this._playing = false;
63
+ this._cancelArmed(); // armed future audio must not sound during pause; re-armed on resume
64
+ }
65
+ seekSec(sec) {
66
+ this._reanchor(Math.max(0, sec));
67
+ this._cancelArmed();
68
+ this._reopenEvents(); // a seek MOVES position -> fired events may replay
69
+ }
70
+ setRate(rate) {
71
+ if (rate <= 0)
72
+ throw new Error('rate must be > 0');
73
+ this._reanchor();
74
+ this._rate = rate;
75
+ this._cancelArmed(); // window/audio-time changed -> re-arm pending events (NOT replay fired ones)
76
+ }
77
+ get rate() {
78
+ return this._rate;
79
+ }
80
+ get playing() {
81
+ return this._playing;
82
+ }
83
+ setLoopSec(loop) {
84
+ this._loop = loop ? { startSec: loop.startSec, endSec: loop.endSec } : null;
85
+ this._cancelArmed();
86
+ this._reopenEvents(); // loop topology changed -> events may re-enter/leave the loop window
87
+ }
88
+ get loopEnabled() {
89
+ return this._loop != null;
90
+ }
91
+ // ---- scheduling ---------------------------------------------------------------------
92
+ schedule(spec) {
93
+ const id = this._nextId++;
94
+ this._events.set(id, {
95
+ atSec: spec.atSec,
96
+ fire: spec.fire,
97
+ payload: spec.payload ?? null,
98
+ armedTarget: null,
99
+ handle: null,
100
+ done: false,
101
+ lastOccurredTarget: null,
102
+ });
103
+ return id;
104
+ }
105
+ unschedule(id) {
106
+ const ev = this._events.get(id);
107
+ if (ev && ev.handle)
108
+ ev.handle();
109
+ this._events.delete(id);
110
+ }
111
+ onTick(cb) {
112
+ this._frameReaders.add(cb);
113
+ return () => this._frameReaders.delete(cb);
114
+ }
115
+ /** Cancel armed-but-unoccurred audio and clear arm state (does NOT replay already-fired events). */
116
+ _cancelArmed() {
117
+ // An event whose audio time has ALREADY passed has sounded (osc.start fired) — settle its fire()
118
+ // before we cancel, else a pause/seek/rate/loop change right after the beat would drop the visual
119
+ // flash / lifecycle for a sound the listener already heard (Codex review).
120
+ this._detectOccurrences(this.backend.nowSec());
121
+ for (const ev of this._events.values()) {
122
+ if (ev.handle)
123
+ ev.handle();
124
+ ev.handle = null;
125
+ ev.armedTarget = null;
126
+ }
127
+ }
128
+ /** Re-open fired events so they can occur again — only after a POSITION/topology change (seek/loop). */
129
+ _reopenEvents() {
130
+ for (const ev of this._events.values()) {
131
+ ev.done = false;
132
+ ev.lastOccurredTarget = null;
133
+ }
134
+ }
135
+ _eventLoops(ev) {
136
+ if (!this._loop)
137
+ return false;
138
+ const { startSec, endSec } = this._loop;
139
+ return ev.atSec >= startSec - EPS && ev.atSec < endSec - EPS;
140
+ }
141
+ /** Transport-seconds distance to an event's NEXT occurrence from `pos` (null = won't occur). */
142
+ _nextDist(ev, pos) {
143
+ if (this._loop) {
144
+ const { startSec, endSec } = this._loop;
145
+ const len = endSec - startSec;
146
+ if (len > 0 && ev.atSec >= startSec - EPS && ev.atSec < endSec - EPS) {
147
+ let d = ev.atSec - pos;
148
+ if (d < -EPS)
149
+ d += len; // wrapped into the next pass
150
+ return d;
151
+ }
152
+ }
153
+ const d = ev.atSec - pos;
154
+ return d >= -EPS ? d : null; // non-loop: a passed event won't fire again until a seek
155
+ }
156
+ // ---- optional musical overlay -------------------------------------------------------
157
+ setProjection(projection) {
158
+ this._projection = projection;
159
+ }
160
+ musicalPosition() {
161
+ return this._projection ? this._projection.musicalAt(this.positionSec()) : null;
162
+ }
163
+ // ---- sync apply (Inc 3) -------------------------------------------------------------
164
+ applyAnchoredState(s) {
165
+ this._playing = s.playState === 'playing';
166
+ if (s.rate != null)
167
+ this._rate = s.rate;
168
+ this._anchorPos = s.positionSec;
169
+ this._anchorBackend = s.anchorAudioSec ?? this.backend.nowSec();
170
+ if (s.loop !== undefined)
171
+ this._loop = s.loop ? { ...s.loop } : null;
172
+ this._cancelArmed();
173
+ this._reopenEvents(); // anchored apply repositions the timeline -> events re-evaluate
174
+ }
175
+ /** Arm an anchored state (with optional control) to apply when audio time reaches `atAudioSec`. */
176
+ scheduleStateChange(atAudioSec, state, meta = {}) {
177
+ this._pending.push({
178
+ atAudioSec,
179
+ state,
180
+ term: meta.term ?? 0,
181
+ seq: meta.seq ?? 0,
182
+ onApply: meta.onApply ?? null,
183
+ });
184
+ this._pending.sort((a, b) => a.atAudioSec - b.atAudioSec);
185
+ }
186
+ /** Drop pending changes older than a freshly-applied (term,seq) — supersession (Codex fix #4). */
187
+ dropPendingOlderThan(term, seq) {
188
+ this._pending = this._pending.filter((p) => !(p.term < term || (p.term === term && p.seq < seq)));
189
+ }
190
+ _drainPending() {
191
+ const now = this.backend.nowSec();
192
+ while (this._pending.length && this._pending[0].atAudioSec <= now + EPS) {
193
+ const p = this._pending.shift();
194
+ this.applyAnchoredState({ ...p.state, anchorAudioSec: p.state.anchorAudioSec ?? now });
195
+ if (p.onApply)
196
+ p.onApply(); // control rides WITH the state, applied atomically here (fix #5)
197
+ }
198
+ }
199
+ // ---- the pump -----------------------------------------------------------------------
200
+ tick() {
201
+ this._drainPending();
202
+ if (this._playing) {
203
+ const now = this.backend.nowSec();
204
+ this._detectOccurrences(now); // fire events whose audio time has passed (Transport owns this)
205
+ this._maybeWrapLoop();
206
+ const pos = this.positionSec();
207
+ for (const ev of this._events.values()) {
208
+ if (ev.done || ev.armedTarget != null)
209
+ continue;
210
+ const d = this._nextDist(ev, pos);
211
+ if (d == null)
212
+ continue;
213
+ const audioDist = d / this._rate; // look-ahead is in AUDIO time (rate-scaled)
214
+ if (audioDist <= this.lookaheadSec + EPS) {
215
+ const audioTime = now + audioDist;
216
+ // a loop event at/near the boundary must not re-arm for the instant it just fired.
217
+ // The dedupe window must stay below half a loop period, else ultra-short loops starve.
218
+ const period = this._loop ? (this._loop.endSec - this._loop.startSec) / this._rate : Infinity;
219
+ const dedupeEps = Math.min(1e-6, 0.4 * period);
220
+ if (ev.lastOccurredTarget != null && audioTime <= ev.lastOccurredTarget + dedupeEps)
221
+ continue;
222
+ ev.armedTarget = audioTime;
223
+ // armed AHEAD: a real backend schedules node.start(audioTime) here, using `data` for the sound.
224
+ ev.handle = this.backend.armAt(audioTime, { atSec: ev.atSec, data: ev.payload });
225
+ }
226
+ }
227
+ }
228
+ const p = this.positionSec();
229
+ for (const r of this._frameReaders)
230
+ r(p);
231
+ }
232
+ /** Fire armed events whose audio time has arrived, and reset them for re-arm (loop) / mark done. */
233
+ _detectOccurrences(now) {
234
+ for (const ev of this._events.values()) {
235
+ if (ev.armedTarget == null || now < ev.armedTarget - EPS)
236
+ continue;
237
+ const at = ev.armedTarget;
238
+ ev.armedTarget = null;
239
+ ev.handle = null; // the scheduled audio already plays at `at`; nothing to cancel
240
+ ev.lastOccurredTarget = at;
241
+ if (!this._eventLoops(ev))
242
+ ev.done = true; // non-loop fires once; loop re-arms next pass
243
+ ev.fire(at, ev.atSec);
244
+ }
245
+ }
246
+ _maybeWrapLoop() {
247
+ if (!this._loop)
248
+ return;
249
+ const { startSec, endSec } = this._loop;
250
+ const len = endSec - startSec;
251
+ if (len <= 0)
252
+ return;
253
+ const pos = this.positionSec();
254
+ if (pos < endSec - EPS)
255
+ return;
256
+ const overshoot = (pos - startSec) % len;
257
+ this._reanchor(startSec + overshoot); // armed events keep their absolute audio times across the wrap
258
+ }
259
+ // ---- snapshot -----------------------------------------------------------------------
260
+ snapshot() {
261
+ return {
262
+ playState: this._playing ? 'playing' : 'paused',
263
+ positionSec: this.positionSec(),
264
+ rate: this._rate,
265
+ loop: this._loop ? { ...this._loop } : null,
266
+ };
267
+ }
268
+ }
@@ -0,0 +1,84 @@
1
+ /** Easing function: maps a normalized fraction in [0,1] to an eased fraction. */
2
+ export type EaseFn = (x: number) => number;
3
+ export declare const Ease: {
4
+ linear: EaseFn;
5
+ smooth: EaseFn;
6
+ };
7
+ /** A single curve keyframe: a time key `t` (seconds or beats) and its value. */
8
+ export interface Keyframe {
9
+ t: number;
10
+ value: number;
11
+ }
12
+ export type TimeMode = 'absolute-seconds' | 'beat-locked';
13
+ /**
14
+ * Structural shape of a musical projection — typed here so `./clock/curves` never imports
15
+ * `./clock/musical`. A beat-locked curve only needs seconds <-> beats conversion.
16
+ */
17
+ export interface ProjectionLike {
18
+ secondsToBeats(positionSec: number): number;
19
+ }
20
+ export interface CurveTrackSpec {
21
+ keyframes: Keyframe[];
22
+ timeMode?: TimeMode;
23
+ projection?: ProjectionLike | null;
24
+ ease?: EaseFn;
25
+ outputIntent?: unknown;
26
+ }
27
+ export declare class CurveTrack {
28
+ keyframes: Keyframe[];
29
+ timeMode: TimeMode;
30
+ projection: ProjectionLike | null;
31
+ ease: EaseFn;
32
+ outputIntent: unknown;
33
+ constructor(spec: CurveTrackSpec);
34
+ /** The track's own time key for a given clock position. */
35
+ _key(positionSec: number): number;
36
+ sample(positionSec: number): number;
37
+ }
38
+ /**
39
+ * Structural shape of the transport a GestureRecorder/Orchestrator subscribes to — typed here so
40
+ * `./clock/curves` never imports `./clock/musical`. Mirrors the subset of `./Transport.js` used.
41
+ */
42
+ export interface TransportLike {
43
+ positionSec(): number;
44
+ onTick(cb: (positionSec: number) => void): () => void;
45
+ schedule(spec: {
46
+ atSec: number;
47
+ fire: (audioTimeSec: number, atSec: number) => void;
48
+ }): number;
49
+ }
50
+ export interface GestureRecorderOptions {
51
+ timeMode?: TimeMode;
52
+ projection?: ProjectionLike | null;
53
+ }
54
+ /**
55
+ * GestureRecorder — captures live input samples stamped with the transport position, producing a
56
+ * CurveTrack. Free gestures stamp seconds; musical gestures stamp beats (so they tempo-rebase).
57
+ * (design doc §4a: today gestures are applied live & never recorded against musical time.)
58
+ */
59
+ export declare class GestureRecorder {
60
+ transport: TransportLike;
61
+ timeMode: TimeMode;
62
+ projection: ProjectionLike | null;
63
+ keyframes: Keyframe[];
64
+ constructor(transport: TransportLike, { timeMode, projection }?: GestureRecorderOptions);
65
+ /** Stamp a value at the current transport position. */
66
+ capture(value: number): void;
67
+ toTrack(ease?: EaseFn): CurveTrack;
68
+ }
69
+ /**
70
+ * Orchestrator — the thin layer that subscribes every domain to ONE transport (design doc §5):
71
+ * - audio: schedule(atSec, fire) -> armed ahead with precise audio time
72
+ * - visuals: onTick -> sample curves at the current position each frame (one shared reader)
73
+ */
74
+ export declare class Orchestrator {
75
+ transport: TransportLike;
76
+ curves: Map<string, CurveTrack>;
77
+ lastValues: Map<string, number>;
78
+ private _off;
79
+ constructor(transport: TransportLike);
80
+ addCurve(id: string, track: CurveTrack): void;
81
+ scheduleAudio(atSec: number, fire: (audioTimeSec: number, atSec: number) => void): number;
82
+ _readFrame(positionSec: number): void;
83
+ dispose(): void;
84
+ }
@@ -0,0 +1,115 @@
1
+ // CurveTrack — a time-addressable curve the orchestrator samples by position (design doc §0 D3, §4/§5).
2
+ //
3
+ // Two kinds, one interface:
4
+ // - 'absolute-seconds' : keyframes are { t: seconds, value } (free gestures, non-metric)
5
+ // - 'beat-locked' : keyframes are { t: beats, value } (musical; needs a projection)
6
+ // A beat-locked curve REFLOWS automatically when tempo changes — a peak authored "at beat 3" lands on
7
+ // beat 3 at any tempo. This is what lets recorded gestures and authored anime-style curves share the
8
+ // musical timeline. `sample(positionSec)` is pure: position in, value out — no internal timer.
9
+ export const Ease = {
10
+ linear: (x) => x,
11
+ smooth: (x) => x * x * (3 - 2 * x), // smoothstep
12
+ };
13
+ function lerp(a, b, t) {
14
+ return a + (b - a) * t;
15
+ }
16
+ export class CurveTrack {
17
+ keyframes;
18
+ timeMode;
19
+ projection;
20
+ ease;
21
+ outputIntent;
22
+ constructor(spec) {
23
+ this.keyframes = spec.keyframes.slice().sort((a, b) => a.t - b.t);
24
+ this.timeMode = spec.timeMode ?? 'absolute-seconds';
25
+ this.projection = spec.projection ?? null;
26
+ this.ease = spec.ease ?? Ease.linear;
27
+ this.outputIntent = spec.outputIntent ?? null;
28
+ if (this.timeMode === 'beat-locked' && !this.projection) {
29
+ throw new Error('beat-locked CurveTrack needs a MusicalProjection');
30
+ }
31
+ }
32
+ /** The track's own time key for a given clock position. */
33
+ _key(positionSec) {
34
+ return this.timeMode === 'beat-locked' ? this.projection.secondsToBeats(positionSec) : positionSec;
35
+ }
36
+ sample(positionSec) {
37
+ const k = this._key(positionSec);
38
+ const kf = this.keyframes;
39
+ if (k <= kf[0].t)
40
+ return kf[0].value;
41
+ if (k >= kf[kf.length - 1].t)
42
+ return kf[kf.length - 1].value;
43
+ let i = 0;
44
+ while (i < kf.length - 1 && kf[i + 1].t <= k)
45
+ i++;
46
+ const a = kf[i];
47
+ const b = kf[i + 1];
48
+ const frac = (k - a.t) / (b.t - a.t);
49
+ return lerp(a.value, b.value, this.ease(frac));
50
+ }
51
+ }
52
+ /**
53
+ * GestureRecorder — captures live input samples stamped with the transport position, producing a
54
+ * CurveTrack. Free gestures stamp seconds; musical gestures stamp beats (so they tempo-rebase).
55
+ * (design doc §4a: today gestures are applied live & never recorded against musical time.)
56
+ */
57
+ export class GestureRecorder {
58
+ transport;
59
+ timeMode;
60
+ projection;
61
+ keyframes;
62
+ constructor(transport, { timeMode = 'absolute-seconds', projection = null } = {}) {
63
+ this.transport = transport;
64
+ this.timeMode = timeMode;
65
+ // `_projection` is the transport's private musical overlay (read defensively — it is an
66
+ // implementation detail not part of the public TransportLike contract).
67
+ const carried = transport._projection;
68
+ this.projection = projection ?? carried ?? null;
69
+ // Fail fast: a beat-locked gesture must have a projection to stamp beats, else capture() would
70
+ // crash later with a cryptic null error (Codex review). Invalid config only — valid paths unchanged.
71
+ if (this.timeMode === 'beat-locked' && !this.projection) {
72
+ throw new Error('[GestureRecorder] timeMode "beat-locked" requires a projection (none provided or carried by the transport).');
73
+ }
74
+ this.keyframes = [];
75
+ }
76
+ /** Stamp a value at the current transport position. */
77
+ capture(value) {
78
+ const pos = this.transport.positionSec();
79
+ const t = this.timeMode === 'beat-locked' ? this.projection.secondsToBeats(pos) : pos;
80
+ this.keyframes.push({ t, value });
81
+ }
82
+ toTrack(ease) {
83
+ return new CurveTrack({ keyframes: this.keyframes, timeMode: this.timeMode, projection: this.projection, ease });
84
+ }
85
+ }
86
+ /**
87
+ * Orchestrator — the thin layer that subscribes every domain to ONE transport (design doc §5):
88
+ * - audio: schedule(atSec, fire) -> armed ahead with precise audio time
89
+ * - visuals: onTick -> sample curves at the current position each frame (one shared reader)
90
+ */
91
+ export class Orchestrator {
92
+ transport;
93
+ curves;
94
+ lastValues;
95
+ _off;
96
+ constructor(transport) {
97
+ this.transport = transport;
98
+ this.curves = new Map();
99
+ this._off = transport.onTick((positionSec) => this._readFrame(positionSec));
100
+ this.lastValues = new Map();
101
+ }
102
+ addCurve(id, track) {
103
+ this.curves.set(id, track);
104
+ }
105
+ scheduleAudio(atSec, fire) {
106
+ return this.transport.schedule({ atSec, fire });
107
+ }
108
+ _readFrame(positionSec) {
109
+ for (const [id, track] of this.curves)
110
+ this.lastValues.set(id, track.sample(positionSec));
111
+ }
112
+ dispose() {
113
+ this._off();
114
+ }
115
+ }
@@ -0,0 +1,4 @@
1
+ export { Transport } from './Transport.js';
2
+ export type { LoopSec, PlayState, EventSpec, TransportSnapshot, AnchoredState, ScheduleStateMeta, MusicalProjectionLike, TransportOptions, } from './Transport.js';
3
+ export { VirtualClockBackend } from './ClockBackend.js';
4
+ export type { ClockBackend, CancelHandle } from './ClockBackend.js';
@@ -0,0 +1,4 @@
1
+ // ./clock — the headless, framework-free time core: the seconds-first Transport + look-ahead
2
+ // scheduler and the neutral ClockBackend contract. No three, no react, no sync/musical/curves.
3
+ export { Transport } from './Transport.js';
4
+ export { VirtualClockBackend } from './ClockBackend.js';