Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2911]): prompt-based looping chiptune scores in the Music studio

[._.]/ Adam Eivy68f690f1de23
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f963f0f88d..58e5d774ba 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## Music studio
+
+- **[issue-2911] Compose looping 8-bit game music from a prompt** — the Track editor gains a "Chiptune score" generation mode alongside the on-device audio models: describe the music, pick any configured AI provider/model, and it composes a structured NES-style score (two pulse channels, triangle bass, noise drums) that plays as a seamless loop right in the browser. Revise it conversationally ("more drums", "make it spookier") or start fresh, render takes into the track's regular render history as audio loops, and publish straight into a managed game app's repo (default `game/assets/music/`) as a game-ready OGG plus its editable score source — so a Godot game can drop the loop in as background music. The provider pin and publish target are remembered between sessions.
+
## Sprite Manager
- **[issue-2895] Media Gen gains a Sprites section (phase 1: library + import)** — a new Sprites tab lists your game-sprite characters and prop atlas families, browses each one's locked reference set, walk-cycle strips, and published atlas versions (with pixel-perfect previews), and imports the approved production assets from an existing sprite-pipeline checkout in one click. Only final/approved artifacts import — rejected candidates and raw video intermediates stay behind — and every file the source manifests hash-pin is verified on the way in. Reachable from ⌘K and voice ("take me to sprites"). Generation (reference → anchors → walk videos → publish-to-game) lands in the follow-up phases.
diff --git a/client/src/components/music/ChiptunePanel.jsx b/client/src/components/music/ChiptunePanel.jsx
new file mode 100644
index 0000000000..e837feebe5
--- /dev/null
+++ b/client/src/components/music/ChiptunePanel.jsx
@@ -0,0 +1,329 @@
+/**
+ * ChiptunePanel (#2911) — prompt-based looping 8-bit score generation for the
+ * Track editor. The user picks any configured AI provider/model, describes the
+ * music, and gets a structured chiptune score persisted on the track. The
+ * score previews as a seamless in-browser loop (chiptunePlayback.js), renders
+ * into the track's history as an OGG loop, and publishes into a managed app's
+ * repo (default `game/assets/music/`) as game-ready assets.
+ *
+ * Sibling of MusicGenPanel (the diffusion engines) — TracksManager toggles
+ * between the two. Provider/model + publish prefs persist in
+ * `settings.music.chiptune` so the next session starts where this one left off.
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Loader2, Wand2, Play, Square, Disc3, Gamepad2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import useProviderModels from '../../hooks/useProviderModels';
+import ProviderModelSelector from '../ProviderModelSelector';
+import { buildChiptuneSchedule, createChiptunePlayer } from '../../lib/chiptunePlayback.js';
+import {
+ generateTrackChiptune, renderTrackChiptune, publishTrackChiptune,
+ getApps, getSettings, updateSettings,
+} from '../../services/api';
+
+const slugify = (s) => String(s || '').toLowerCase().trim().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);
+const DEFAULT_SUBDIR = 'game/assets/music';
+
+export default function ChiptunePanel({ track, onTrackUpdate }) {
+ const [prompt, setPrompt] = useState(track?.chiptunePrompt || '');
+ const [fresh, setFresh] = useState(false);
+ const [generating, setGenerating] = useState(false);
+ const [rendering, setRendering] = useState(false);
+ const [publishing, setPublishing] = useState(false);
+ const [playing, setPlaying] = useState(false);
+ const [publishOpen, setPublishOpen] = useState(false);
+ const [apps, setApps] = useState([]);
+ const [publishAppId, setPublishAppId] = useState('');
+ const [publishSubdir, setPublishSubdir] = useState(DEFAULT_SUBDIR);
+ const [publishSlug, setPublishSlug] = useState('');
+ const [publishedFiles, setPublishedFiles] = useState(null);
+ const musicSettingsRef = useRef({});
+ const mountedRef = useRef(true);
+ useEffect(() => () => { mountedRef.current = false; }, []);
+
+ const {
+ providers, selectedProviderId, selectedModel, availableModels,
+ setSelectedProviderId, setSelectedModel,
+ } = useProviderModels({ silent: true });
+
+ const score = track?.chiptuneScore || null;
+ // The player re-reads this ref on every play, so a regeneration is heard
+ // without rebuilding the player instance.
+ const scoreRef = useRef(score);
+ scoreRef.current = score;
+ const playerRef = useRef(null);
+ if (!playerRef.current) {
+ playerRef.current = createChiptunePlayer(() => scoreRef.current);
+ }
+
+ // Stop playback when the selected track changes or the panel unmounts.
+ useEffect(() => () => { playerRef.current?.stop(); setPlaying(false); }, [track?.id]);
+
+ // Reseed the prompt + publish slug from the newly-selected track.
+ useEffect(() => {
+ setPrompt(track?.chiptunePrompt || '');
+ setFresh(false);
+ setPublishedFiles(null);
+ setPublishSlug(slugify(track?.title));
+ }, [track?.id]);
+
+ // Load saved prefs (provider pin + publish target) once. The provider pin is
+ // applied when the provider list has loaded; a stale saved id degrades to the
+ // hook's default selection.
+ useEffect(() => {
+ getSettings({ silent: true }).then((settings) => {
+ if (!mountedRef.current) return;
+ const music = settings?.music || {};
+ musicSettingsRef.current = music;
+ const saved = music.chiptune || {};
+ if (saved.providerId) setSelectedProviderId(saved.providerId);
+ if (saved.model) setSelectedModel(saved.model);
+ if (saved.publishAppId) setPublishAppId(saved.publishAppId);
+ if (saved.publishSubdir) setPublishSubdir(saved.publishSubdir);
+ }).catch(() => {});
+ }, []);
+
+ const summary = useMemo(() => {
+ if (!score) return null;
+ const { totalSec } = buildChiptuneSchedule(score);
+ return {
+ title: score.title || 'Untitled loop',
+ bpm: score.bpm,
+ patterns: Object.keys(score.patterns || {}).length,
+ order: (score.order || []).join(' '),
+ seconds: Math.round(totalSec * 10) / 10,
+ };
+ }, [score]);
+
+ const persistChiptunePrefs = (patch) => {
+ const music = musicSettingsRef.current;
+ const next = { ...music, chiptune: { ...(music.chiptune || {}), ...patch } };
+ musicSettingsRef.current = next;
+ updateSettings({ music: next }, { silent: true }).catch(() => {});
+ };
+
+ const handleGenerate = async () => {
+ if (!track?.id) { toast.error('Save the track first, then generate'); return; }
+ if (!prompt.trim()) { toast.error('Describe the music first'); return; }
+ if (!selectedProviderId) { toast.error('Pick an AI provider first'); return; }
+ setGenerating(true);
+ const res = await generateTrackChiptune(track.id, {
+ prompt: prompt.trim(),
+ providerId: selectedProviderId,
+ model: selectedModel || undefined,
+ ...(fresh ? { fresh: true } : {}),
+ }, { silent: true }).catch((err) => { toast.error(err.message || 'Generation failed'); return null; });
+ if (!mountedRef.current) return;
+ setGenerating(false);
+ if (res?.track) {
+ onTrackUpdate?.(res.track);
+ setFresh(false);
+ persistChiptunePrefs({ providerId: selectedProviderId, model: selectedModel || '' });
+ toast.success(score ? 'Score revised' : 'Score composed');
+ }
+ };
+
+ const togglePlay = async () => {
+ if (playerRef.current.isPlaying()) {
+ playerRef.current.stop();
+ setPlaying(false);
+ return;
+ }
+ setPlaying(true);
+ await playerRef.current.play();
+ if (mountedRef.current && !playerRef.current.isPlaying()) setPlaying(false);
+ };
+
+ const handleRender = async () => {
+ if (playerRef.current.isPlaying()) { playerRef.current.stop(); setPlaying(false); }
+ setRendering(true);
+ const res = await renderTrackChiptune(track.id, { silent: true })
+ .catch((err) => { toast.error(err.message || 'Render failed'); return null; });
+ if (!mountedRef.current) return;
+ setRendering(false);
+ if (res?.track) {
+ onTrackUpdate?.(res.track);
+ toast.success(`Loop rendered (${res.durationSec}s)`);
+ }
+ };
+
+ const openPublish = async () => {
+ setPublishedFiles(null);
+ if (!publishOpen && apps.length === 0) {
+ const list = await getApps({ silent: true }).catch(() => []);
+ if (!mountedRef.current) return;
+ // Publishable targets are managed apps with a repo on disk — PortOS
+ // itself is excluded (its repo is not a game asset destination).
+ setApps((Array.isArray(list) ? list : []).filter((a) => a.repoPath && a.id !== 'portos-default' && !a.archived));
+ }
+ setPublishOpen((o) => !o);
+ };
+
+ const handlePublish = async () => {
+ if (!publishAppId) { toast.error('Pick a target app first'); return; }
+ setPublishing(true);
+ const res = await publishTrackChiptune(track.id, {
+ appId: publishAppId,
+ subdir: publishSubdir.trim() || undefined,
+ slug: publishSlug.trim() || undefined,
+ }, { silent: true }).catch((err) => { toast.error(err.message || 'Publish failed'); return null; });
+ if (!mountedRef.current) return;
+ setPublishing(false);
+ if (res) {
+ setPublishedFiles(res);
+ persistChiptunePrefs({ publishAppId, publishSubdir: publishSubdir.trim() || DEFAULT_SUBDIR });
+ toast.success(`Published to ${res.appName}`);
+ }
+ };
+
+ const canGenerate = !!track?.id && !!prompt.trim() && !!selectedProviderId && !generating;
+
+ return (
+ <div className="space-y-2 border border-port-border rounded-lg p-3 bg-port-bg/40">
+ <div className="flex items-center gap-2 text-sm text-gray-300">
+ <Gamepad2 size={14} className="text-port-accent" /> Chiptune score — looping 8-bit background music
+ </div>
+
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Describe the music</span>
+ <textarea
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ rows={2}
+ maxLength={8000}
+ placeholder="Upbeat farm-chores theme — bouncy melody, walking bass, light hats, loops every 20s."
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ />
+ </label>
+
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={setSelectedProviderId}
+ onModelChange={setSelectedModel}
+ label="AI provider"
+ layout="row"
+ />
+
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={handleGenerate}
+ disabled={!canGenerate}
+ title={!track?.id ? 'Save the track first' : !prompt.trim() ? 'Describe the music first' : score && !fresh ? 'Revise the current score' : 'Compose a new score'}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ >
+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
+ {generating ? 'Composing…' : score && !fresh ? 'Revise score' : 'Compose score'}
+ </button>
+ {score ? (
+ <label className="inline-flex items-center gap-1.5 text-xs text-gray-400">
+ <input type="checkbox" checked={fresh} onChange={(e) => setFresh(e.target.checked)} />
+ Start fresh (ignore current score)
+ </label>
+ ) : null}
+ </div>
+
+ {summary ? (
+ <div className="space-y-2 pt-2 border-t border-port-border/60">
+ <div className="text-xs text-gray-400">
+ <span className="text-white">{summary.title}</span>
+ {' — '}{summary.bpm} BPM · {summary.patterns} pattern{summary.patterns === 1 ? '' : 's'} · order {summary.order} · ~{summary.seconds}s loop
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={togglePlay}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
+ >
+ {playing ? <Square size={14} /> : <Play size={14} />}
+ {playing ? 'Stop' : 'Preview loop'}
+ </button>
+ <button
+ type="button"
+ onClick={handleRender}
+ disabled={rendering}
+ title="Render the loop to audio and add it to this track's renders"
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
+ >
+ {rendering ? <Loader2 size={14} className="animate-spin" /> : <Disc3 size={14} />}
+ {rendering ? 'Rendering…' : 'Render take'}
+ </button>
+ <button
+ type="button"
+ onClick={openPublish}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
+ >
+ <Gamepad2 size={14} /> Publish to app…
+ </button>
+ </div>
+
+ {publishOpen ? (
+ <div className="space-y-2 border border-port-border rounded-lg p-2 bg-port-bg">
+ {apps.length === 0 ? (
+ <p className="text-xs text-gray-500">No managed apps with a repo path — add the game app under Apps first.</p>
+ ) : (
+ <>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Target app</span>
+ <select
+ value={publishAppId}
+ onChange={(e) => setPublishAppId(e.target.value)}
+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
+ >
+ <option value="">— pick an app —</option>
+ {apps.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
+ </select>
+ </label>
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Filename slug</span>
+ <input
+ value={publishSlug}
+ onChange={(e) => setPublishSlug(e.target.value)}
+ placeholder={slugify(track?.title) || 'track'}
+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
+ />
+ </label>
+ </div>
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Folder inside the app repo</span>
+ <input
+ value={publishSubdir}
+ onChange={(e) => setPublishSubdir(e.target.value)}
+ placeholder={DEFAULT_SUBDIR}
+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
+ />
+ </label>
+ <button
+ type="button"
+ onClick={handlePublish}
+ disabled={publishing || !publishAppId}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ >
+ {publishing ? <Loader2 size={14} className="animate-spin" /> : <Gamepad2 size={14} />}
+ {publishing ? 'Publishing…' : 'Publish loop'}
+ </button>
+ </>
+ )}
+ {publishedFiles ? (
+ <div className="text-[11px] text-gray-400 space-y-0.5">
+ <p className="text-port-success">Published to {publishedFiles.appName}:</p>
+ {publishedFiles.files.map((f) => <p key={f} className="font-mono truncate">{f}</p>)}
+ <p>{publishedFiles.note}</p>
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ ) : (
+ <p className="text-[11px] text-gray-500">
+ No score yet — describe the vibe and compose. The score previews as a seamless loop, renders to audio, and publishes straight into a managed game app.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index 1f6e6cb222..87c8f637c2 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -19,6 +19,7 @@ import toast from '../ui/Toast';
import { formatTimecode } from '../../utils/formatters';
import ArtistPicker from './ArtistPicker';
import MusicGenPanel from './MusicGenPanel';
+import ChiptunePanel from './ChiptunePanel';
import TrackRenderCard from './TrackRenderCard';
import TrackRenderModal from './TrackRenderModal';
import MidiVisualization from '../songs/MidiVisualization.jsx';
@@ -80,6 +81,10 @@ export default function TracksManager() {
// Music Video projects, for the MIDI read-through: MuScriptor transcriptions
// are stored on the MV project that links a track, not on the track itself.
const [mvProjects, setMvProjects] = useState([]);
+ // Which generator the editor shows: the on-device audio models or the
+ // LLM-composed chiptune score (#2911). Seeded per selection below — a track
+ // that already carries a score opens on the chiptune panel.
+ const [genMode, setGenMode] = useState('audio');
const remixNonceRef = useRef(0);
const fileInputRef = useRef(null);
// Mirrors `selectedId` so async audio handlers can detect a selection change
@@ -142,6 +147,7 @@ export default function TracksManager() {
resetTrackViewState();
if (isCreate) setForm(emptyForm());
else if (selected) setForm(formFromTrack(selected));
+ setGenMode(selected?.chiptuneScore ? 'chiptune' : 'audio');
}, [selectionKey, isCreate, selected, loading]);
const upsertLocal = (track) => {
@@ -291,6 +297,9 @@ export default function TracksManager() {
// model/duration, and close the modal so the panel is in view.
const remixRender = (render) => {
setModalRender(null);
+ // A chiptune take remixes in the chiptune panel; everything else seeds the
+ // audio-model panel below.
+ setGenMode(render.engine === 'chiptune' ? 'chiptune' : 'audio');
setForm((f) => ({
...f,
...(render.prompt ? { prompt: render.prompt } : {}),
@@ -410,27 +419,53 @@ export default function TracksManager() {
/>
</Field>
- {/* On-device generation — available once the track is saved (the
- server attaches the audio + metadata to the persisted track).
- Uses the CURRENT prompt/lyrics in the form; `remix` seeds the
- engine/model/duration from a past take. */}
+ {/* Generation — available once the track is saved (the server
+ attaches the audio + metadata to the persisted track). Two
+ modes: the on-device audio models (MusicGen/AudioLDM2/ACE-Step)
+ and the LLM-composed looping chiptune score (#2911). */}
{persisted ? (
- <MusicGenPanel
- track={persisted}
- prompt={form.prompt}
- lyrics={form.lyrics}
- remix={remix}
- onGenerated={(updated) => {
- upsertLocal(updated); // list update is id-keyed → always safe
- // Merge ONLY the server-set generation fields into the open
- // form (the active audio pointer mirrors onto the form) so any
- // UNSAVED edits the user made to title/artist/album/prompt/
- // lyrics before clicking Generate survive.
- if (selectedIdRef.current === updated.id) {
- setForm((f) => ({ ...f, audioFilename: updated.audioFilename || '' }));
- }
- }}
- />
+ <div className="space-y-2">
+ <div className="inline-flex rounded-lg border border-port-border overflow-hidden text-sm" role="group" aria-label="Generation mode">
+ {[['audio', 'Audio model'], ['chiptune', 'Chiptune score']].map(([mode, label]) => (
+ <button
+ key={mode}
+ type="button"
+ onClick={() => setGenMode(mode)}
+ className={`px-3 py-1.5 ${genMode === mode ? 'bg-port-accent/20 text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ {genMode === 'chiptune' ? (
+ <ChiptunePanel
+ track={persisted}
+ onTrackUpdate={(updated) => {
+ upsertLocal(updated); // list update is id-keyed → always safe
+ if (selectedIdRef.current === updated.id) {
+ setForm((f) => ({ ...f, audioFilename: updated.audioFilename || f.audioFilename }));
+ }
+ }}
+ />
+ ) : (
+ <MusicGenPanel
+ track={persisted}
+ prompt={form.prompt}
+ lyrics={form.lyrics}
+ remix={remix}
+ onGenerated={(updated) => {
+ upsertLocal(updated); // list update is id-keyed → always safe
+ // Merge ONLY the server-set generation fields into the open
+ // form (the active audio pointer mirrors onto the form) so any
+ // UNSAVED edits the user made to title/artist/album/prompt/
+ // lyrics before clicking Generate survive.
+ if (selectedIdRef.current === updated.id) {
+ setForm((f) => ({ ...f, audioFilename: updated.audioFilename || '' }));
+ }
+ }}
+ />
+ )}
+ </div>
) : null}
{/* Render history — every generated/uploaded take as a card. The
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 5e57dcffb5..8b253c6a98 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -116,6 +116,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
| `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. |
| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. |
+| `chiptunePlayback.js` | Looping WebAudio preview for LLM-generated chiptune scores (#2911) — `buildChiptuneSchedule(score)` (pure pattern/order → absolute-time flatten, MIRRORS `server/lib/chiptuneScore.js` timing semantics), `parseChiptunePitch("C5")` → MIDI, and `createChiptunePlayer(getScore, { onLoop })` — a seamless-loop player over `createLookaheadTransport` (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums). No React — `ChiptunePanel` drives it. |
| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |
| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
diff --git a/client/src/lib/chiptunePlayback.js b/client/src/lib/chiptunePlayback.js
new file mode 100644
index 0000000000..3b1f225f65
--- /dev/null
+++ b/client/src/lib/chiptunePlayback.js
@@ -0,0 +1,226 @@
+// Chiptune score preview (#2911) — turns a track's LLM-generated chiptune
+// score into a seamlessly LOOPING WebAudio preview. Companion to the offline
+// renderer (server/lib/chiptuneRender.js): same score contract, same timing
+// semantics (MIRRORS server/lib/chiptuneScore.js buildScoreEvents — keep the
+// two in lockstep), synthesized live with OscillatorNodes + a noise buffer
+// instead of offline PCM.
+//
+// No third-party audio library — built on the shared lookahead transport
+// (lookaheadTransport.js, #2493) like the other synth players. The schedule
+// build is a pure function (unit-tested without Web Audio); the player loops
+// by re-basing its cursor each time it exhausts the event list, so the loop
+// boundary is sample-scheduler-exact rather than "restart on a timer".
+
+import { getAudioContext as ctx } from './audioContext.js';
+import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';
+import { midiToFreq, makeSafeCall } from './scorePlayback.js';
+
+const { SCHEDULE_AHEAD } = SYNTH_TIMING;
+const safeCall = makeSafeCall('chiptune playback');
+
+// --- Pure schedule build (mirrors server buildScoreEvents) ------------------
+
+const PITCH_CLASS = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
+const PITCH_RE = /^([A-Ga-g])(#{1,2}|b{1,2})?(-?\d)$/;
+export const CHIPTUNE_NOISE_PRESETS = ['kick', 'snare', 'hat', 'open-hat'];
+
+// MIDI number for a scientific-pitch STRING ("C4" = 60), or null. Differs from
+// scorePlayback.pitchToMidi, which takes a parsed { letter, accidental, octave }.
+export function parseChiptunePitch(pitch) {
+ const m = PITCH_RE.exec(String(pitch || '').trim());
+ if (!m) return null;
+ const shift = m[2] ? (m[2][0] === '#' ? m[2].length : -m[2].length) : 0;
+ return (Number(m[3]) + 1) * 12 + PITCH_CLASS[m[1].toUpperCase()] + shift;
+}
+
+/**
+ * Flatten a chiptune score into absolute-time events + the exact loop length.
+ * Same drop/clamp semantics as the server: notes starting past their pattern
+ * are dropped, overhang is clamped, unresolvable pitches drop just that note.
+ */
+export function buildChiptuneSchedule(score) {
+ if (
+ !score || !Array.isArray(score.channels) || !Array.isArray(score.order)
+ || !(score.bpm > 0) || !(score.stepsPerBeat > 0) || !(score.beatsPerBar > 0)
+ ) {
+ return { events: [], stepSec: 0, totalSec: 0 };
+ }
+ const stepSec = 60 / (score.bpm * score.stepsPerBeat);
+ const channelsById = new Map(score.channels.map((c) => [c.id, c]));
+ const events = [];
+ let baseStep = 0;
+ for (const name of score.order) {
+ const pattern = score.patterns?.[name];
+ if (!pattern) continue;
+ const steps = pattern.bars * score.beatsPerBar * score.stepsPerBeat;
+ for (const [channelId, notes] of Object.entries(pattern.notes || {})) {
+ const channel = channelsById.get(channelId);
+ if (!channel || !Array.isArray(notes)) continue;
+ for (const note of notes) {
+ if (note.step >= steps) continue;
+ const lenSteps = Math.min(note.len, steps - note.step);
+ const isNoise = channel.wave === 'noise';
+ const noise = isNoise ? (CHIPTUNE_NOISE_PRESETS.includes(note.pitch) ? note.pitch : null) : null;
+ const freq = isNoise ? null : midiToFreq(parseChiptunePitch(note.pitch));
+ if (isNoise ? !noise : !freq) continue;
+ events.push({
+ wave: channel.wave,
+ duty: channel.duty ?? 0.5,
+ gain: channel.gain ?? 0.5,
+ freq,
+ noise,
+ startSec: (baseStep + note.step) * stepSec,
+ durSec: lenSteps * stepSec,
+ vel: note.vel ?? 0.8,
+ });
+ }
+ }
+ baseStep += steps;
+ }
+ events.sort((a, b) => a.startSec - b.startSec);
+ return { events, stepSec, totalSec: baseStep * stepSec };
+}
+
+// --- WebAudio voices --------------------------------------------------------
+
+const VOICE_PEAK = 0.22; // per-voice headroom so four channels don't clip
+
+// Band-limited pulse wave for non-50% duty cycles (a 'square' OscillatorNode
+// is fixed at 50%). Fourier series of a pulse: a_n ∝ sin(nπ·duty)/n.
+const pulseWave = (c, duty) => {
+ const N = 32;
+ const real = new Float32Array(N);
+ const imag = new Float32Array(N);
+ for (let n = 1; n < N; n += 1) {
+ imag[n] = (2 / (n * Math.PI)) * Math.sin(n * Math.PI * duty);
+ }
+ return c.createPeriodicWave(real, imag, { disableNormalization: false });
+};
+
+// Shared white-noise buffer (1s, reused by every noise voice via offset 0 —
+// the LFSR aesthetic matters less in preview than in the deterministic render).
+let noiseBuffer = null;
+const getNoiseBuffer = (c) => {
+ if (!noiseBuffer || noiseBuffer.sampleRate !== c.sampleRate) {
+ noiseBuffer = c.createBuffer(1, c.sampleRate, c.sampleRate);
+ const data = noiseBuffer.getChannelData(0);
+ for (let i = 0; i < data.length; i += 1) data[i] = Math.random() * 2 - 1;
+ }
+ return noiseBuffer;
+};
+
+const NOISE_VOICES = {
+ kick: { decaySec: 0.11 },
+ snare: { decaySec: 0.12, rate: 0.45 },
+ hat: { decaySec: 0.04, rate: 1 },
+ 'open-hat': { decaySec: 0.2, rate: 1 },
+};
+
+// Schedule one chiptune voice; returns { osc, gain } for transport teardown
+// (an AudioBufferSourceNode satisfies the same start/stop/onended surface).
+function scheduleChipVoice(c, ev, startAt, destination, waveCache) {
+ const gain = c.createGain();
+ const peak = Math.max(0.0002, VOICE_PEAK * ev.gain * ev.vel);
+ const end = startAt + ev.durSec;
+ let osc;
+
+ if (ev.noise) {
+ const preset = NOISE_VOICES[ev.noise];
+ if (ev.noise === 'kick') {
+ // Classic chiptune kick: a fast descending sine sweep, not noise.
+ osc = c.createOscillator();
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(160, startAt);
+ osc.frequency.exponentialRampToValueAtTime(45, startAt + preset.decaySec);
+ } else {
+ osc = c.createBufferSource();
+ osc.buffer = getNoiseBuffer(c);
+ osc.loop = true;
+ osc.playbackRate.value = preset.rate;
+ }
+ gain.gain.setValueAtTime(peak, startAt);
+ gain.gain.exponentialRampToValueAtTime(0.0001, Math.min(end, startAt + preset.decaySec * 4));
+ } else {
+ osc = c.createOscillator();
+ if (ev.wave === 'triangle') osc.type = 'triangle';
+ else if (ev.duty === 0.5) osc.type = 'square';
+ else {
+ const key = ev.duty.toFixed(3);
+ if (!waveCache.has(key)) waveCache.set(key, pulseWave(c, ev.duty));
+ osc.setPeriodicWave(waveCache.get(key));
+ }
+ osc.frequency.setValueAtTime(ev.freq, startAt);
+ const attack = Math.min(0.008, ev.durSec * 0.25);
+ const release = Math.min(0.05, ev.durSec * 0.3);
+ gain.gain.setValueAtTime(0.0001, startAt);
+ gain.gain.exponentialRampToValueAtTime(peak, startAt + attack);
+ gain.gain.setValueAtTime(peak, Math.max(startAt + attack, end - release));
+ gain.gain.exponentialRampToValueAtTime(0.0001, end);
+ }
+
+ osc.connect(gain).connect(destination);
+ osc.start(startAt);
+ osc.stop(end + 0.02);
+ return { osc, gain };
+}
+
+// --- Player -----------------------------------------------------------------
+
+/**
+ * Looping chiptune preview player over the shared lookahead transport.
+ * `getScore` is re-read on every play() so the preview always sounds the
+ * freshest generation. Loops until stop() — `getTotalSec` is Infinity and the
+ * cursor re-bases itself each pass, so the loop boundary is scheduler-exact.
+ *
+ * @param {() => object|null} getScore — returns the current score (or null)
+ * @param {{ onLoop?: (loopCount:number) => void }} [callbacks]
+ * @returns {{ play, stop, isPlaying }}
+ */
+export function createChiptunePlayer(getScore, { onLoop } = {}) {
+ let schedule = null;
+ let master = null;
+ let waveCache = new Map();
+ let cursor = { idx: 0, loopStartSec: 0, loops: 0 };
+
+ const transport = createLookaheadTransport({
+ getTotalSec: () => Infinity,
+ prepare: () => {
+ const built = buildChiptuneSchedule(getScore());
+ if (!built.events.length || built.totalSec <= 0) return false;
+ schedule = built;
+ const c = ctx();
+ master = c.createGain();
+ master.gain.value = 1;
+ master.connect(c.destination);
+ waveCache = new Map();
+ cursor = { idx: 0, loopStartSec: 0, loops: 0 };
+ return true;
+ },
+ scheduleWindow: (now, startTime, track) => {
+ if (!schedule || !master) return;
+ const horizon = now + SCHEDULE_AHEAD;
+ // Hand every event due inside the window to the audio clock; when the
+ // list is exhausted, re-base onto the next loop pass and keep going.
+ for (;;) {
+ if (cursor.idx >= schedule.events.length) {
+ cursor.idx = 0;
+ cursor.loopStartSec += schedule.totalSec;
+ cursor.loops += 1;
+ safeCall(onLoop, cursor.loops);
+ }
+ const ev = schedule.events[cursor.idx];
+ const at = startTime + cursor.loopStartSec + ev.startSec;
+ if (at >= horizon) break;
+ cursor.idx += 1;
+ if (at < now - 0.01) continue; // already past (first tick after a stall)
+ track(scheduleChipVoice(ctx(), ev, at, master, waveCache));
+ }
+ },
+ seekCursors: () => { cursor = { idx: 0, loopStartSec: 0, loops: 0 }; },
+ onTeardown: () => {
+ if (master) { try { master.disconnect(); } catch { /* already gone */ } master = null; }
+ },
+ });
+
+ return { play: transport.play, stop: transport.stop, isPlaying: transport.isPlaying };
+}
diff --git a/client/src/lib/chiptunePlayback.test.js b/client/src/lib/chiptunePlayback.test.js
new file mode 100644
index 0000000000..72a011b787
--- /dev/null
+++ b/client/src/lib/chiptunePlayback.test.js
@@ -0,0 +1,74 @@
+// Pure-schedule tests for the chiptune preview (#2911). Only the Web-Audio-free
+// exports are exercised (buildChiptuneSchedule / parseChiptunePitch); the
+// timing semantics here MUST agree with server/lib/chiptuneScore.test.js —
+// the two flatteners are mirrors of the same contract.
+import { describe, expect, it } from 'vitest';
+import { buildChiptuneSchedule, parseChiptunePitch } from './chiptunePlayback.js';
+
+const score = () => ({
+ version: 1,
+ bpm: 120,
+ stepsPerBeat: 4,
+ beatsPerBar: 4,
+ channels: [
+ { id: 'pulse1', wave: 'square', duty: 0.25, gain: 0.5 },
+ { id: 'noise', wave: 'noise', gain: 0.3 },
+ ],
+ patterns: {
+ A: {
+ bars: 1,
+ notes: {
+ pulse1: [{ step: 0, pitch: 'C5', len: 4, vel: 0.9 }],
+ noise: [{ step: 8, pitch: 'snare', len: 1 }],
+ },
+ },
+ },
+ order: ['A', 'A'],
+});
+
+describe('parseChiptunePitch', () => {
+ it('parses scientific pitch strings to MIDI', () => {
+ expect(parseChiptunePitch('C4')).toBe(60);
+ expect(parseChiptunePitch('A4')).toBe(69);
+ expect(parseChiptunePitch('F#3')).toBe(54);
+ expect(parseChiptunePitch('Bb2')).toBe(46);
+ expect(parseChiptunePitch('snare')).toBeNull();
+ expect(parseChiptunePitch('')).toBeNull();
+ });
+});
+
+describe('buildChiptuneSchedule', () => {
+ it('mirrors the server flatten: step-exact timing, back-to-back order', () => {
+ const { events, stepSec, totalSec } = buildChiptuneSchedule(score());
+ expect(stepSec).toBeCloseTo(0.125);
+ expect(totalSec).toBeCloseTo(4); // 2 × 16 steps × 0.125s
+ const tones = events.filter((e) => e.freq);
+ expect(tones.map((e) => e.startSec)).toEqual([0, 2]);
+ expect(tones[0].durSec).toBeCloseTo(0.5);
+ expect(tones[0].duty).toBe(0.25);
+ const drums = events.filter((e) => e.noise);
+ expect(drums.map((e) => e.noise)).toEqual(['snare', 'snare']);
+ expect(drums[0].startSec).toBeCloseTo(1);
+ });
+
+ it('drops out-of-pattern notes, clamps overhang, skips unresolvable pitches', () => {
+ const s = score();
+ s.patterns.A.notes.pulse1 = [
+ { step: 20, pitch: 'C5', len: 2 }, // past the 16-step pattern → dropped
+ { step: 14, pitch: 'D5', len: 8 }, // overhang → clamped to 2 steps
+ { step: 2, pitch: 'xyz', len: 2 }, // unparseable → dropped
+ ];
+ s.patterns.A.notes.noise = [{ step: 0, pitch: 'C2', len: 1 }]; // not a preset → dropped
+ const { events } = buildChiptuneSchedule(s);
+ expect(events.filter((e) => e.noise)).toHaveLength(0);
+ const tones = events.filter((e) => e.freq);
+ expect(tones).toHaveLength(2); // the clamped D5, once per order entry
+ expect(tones[0].durSec).toBeCloseTo(0.25);
+ });
+
+ it('degrades to an empty schedule on a missing/garbage score', () => {
+ expect(buildChiptuneSchedule(null).events).toEqual([]);
+ expect(buildChiptuneSchedule({}).events).toEqual([]);
+ expect(buildChiptuneSchedule({ channels: [], order: [] }).totalSec).toBe(0);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 1e0021649a..0fad646460 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -84,6 +84,7 @@ export * from './voiceLabel.js';
export * from './audioContext.js';
export * from './cityPlaybackFrame.js';
export * from './canvasRoll.js';
+export * from './chiptunePlayback.js';
export * from './chordShapes.js';
export * from './colorMatch.js';
export * from './editorialChecks.js';
diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.js
index d87dd14bea..387deaff78 100644
--- a/client/src/services/apiTracks.js
+++ b/client/src/services/apiTracks.js
@@ -86,6 +86,30 @@ export const uploadTrackAudio = (id, formData, requestOptions = {}) => request(`
...requestOptions,
});
+// --- Chiptune scores (#2911) — prompt-based looping 8-bit background music.
+
+// Generate (or iterate on) the track's chiptune score with an AI provider.
+// `body`: { prompt, providerId?, model?, fresh? }.
+export const generateTrackChiptune = (id, body, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/chiptune/generate`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...requestOptions,
+});
+
+// Render the current score into the shared music library as a looping take.
+export const renderTrackChiptune = (id, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/chiptune/render`, {
+ method: 'POST',
+ ...requestOptions,
+});
+
+// Publish the current score into a managed app's repo (OGG + score JSON).
+// `body`: { appId, subdir?, slug? }.
+export const publishTrackChiptune = (id, body, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/chiptune/publish`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...requestOptions,
+});
+
// Mirror server caps in server/services/tracks/logic.js — bump both sides.
export const TRACK_TITLE_MAX = 200;
export const TRACK_LYRICS_MAX = 20000;
diff --git a/server/lib/README.md b/server/lib/README.md
index be667e216c..6946ad0659 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -220,6 +220,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `appResolver.js` | Fuzzy-match a spoken/typed phrase to a managed app (`{ id, name }`). Tiered exact → prefix → substring, used by voice tools that target a specific app. |
| `capabilityMap.js` | Pure row builders for the Capability Map (per-integration status tiers + rollup); fed by `routes/capabilities.js`. |
+| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
+| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, pitch math (`pitchToMidi`/`midiToFreq`), and `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
| `civitai.js` | Civitai URL parsing + API client. |
| `huggingfaceLora.js` | HuggingFace LoRA import helpers: parse HF ref → `{repo,revision}`, fetch `/api/models` metadata, pick the `.safetensors`, detect the video-LoRA family (`ltx-video`), build the sidecar + `resolve` download URL. The HF analogue of `civitai.js` for video LoRAs. Pure. |
| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. |
diff --git a/server/lib/chiptuneRender.js b/server/lib/chiptuneRender.js
new file mode 100644
index 0000000000..5a5725bdf2
--- /dev/null
+++ b/server/lib/chiptuneRender.js
@@ -0,0 +1,138 @@
+/**
+ * Chiptune offline renderer (#2911) — deterministic score → PCM → WAV, pure
+ * Node (no audio deps). The OGG encode happens in services/chiptune.js via the
+ * system ffmpeg; this module never shells out, so the same score always
+ * produces byte-identical PCM (unit-tested by hash).
+ *
+ * Synthesis mirrors the client preview (client/src/lib/chiptunePlayback.js):
+ * naive square (with duty) / triangle oscillators — aliasing is part of the
+ * 8-bit aesthetic — plus an NES-style 15-bit LFSR noise lane with four drum
+ * presets. Every note's envelope (attack/sustain/release) lives inside the
+ * note's own duration, so nothing rings past the loop boundary and the loop
+ * is seamless by construction.
+ */
+
+import { buildScoreEvents } from './chiptuneScore.js';
+
+export const CHIPTUNE_SAMPLE_RATE = 44100;
+
+// Keep the sum of four channels inside [-1, 1] without pumping: per-voice
+// headroom plus a hard clamp (deterministic, unlike a compressor).
+const MASTER_GAIN = 0.55;
+const ATTACK_SEC = 0.005;
+
+// Drum presets for the noise lane. `updateEvery` is how many output samples
+// each LFSR value holds (bigger = darker noise); `decaySec` shapes the hit.
+// The kick is a descending sine sweep — the classic chiptune trick — not noise.
+const NOISE_PRESETS = {
+ kick: { kind: 'sweep', fromHz: 160, toHz: 45, decaySec: 0.11 },
+ snare: { kind: 'noise', updateEvery: 4, decaySec: 0.12 },
+ hat: { kind: 'noise', updateEvery: 1, decaySec: 0.04 },
+ 'open-hat': { kind: 'noise', updateEvery: 1, decaySec: 0.2 },
+};
+
+// NES-style 15-bit LFSR (taps 0 and 1). Re-seeded per note so a note's noise
+// is independent of render order — determinism without shared mutable state.
+function makeLfsr() {
+ let reg = 0x7fff;
+ return () => {
+ const bit = (reg ^ (reg >> 1)) & 1;
+ reg = (reg >> 1) | (bit << 14);
+ return (reg & 1) ? 1 : -1;
+ };
+}
+
+function oscSample(wave, duty, phase) {
+ const p = phase - Math.floor(phase);
+ if (wave === 'square') return p < duty ? 1 : -1;
+ // Triangle: 0 → 1 → −1 → 0 across one period.
+ if (p < 0.25) return 4 * p;
+ if (p < 0.75) return 2 - 4 * p;
+ return 4 * p - 4;
+}
+
+/**
+ * Render a validated score to mono Float32 PCM. Sample count is
+ * round(totalSec · sampleRate) — whole-loop exact for seamless looping.
+ */
+export function renderScoreToPcm(score, { sampleRate = CHIPTUNE_SAMPLE_RATE } = {}) {
+ const { events, totalSec } = buildScoreEvents(score);
+ const totalSamples = Math.max(1, Math.round(totalSec * sampleRate));
+ const out = new Float32Array(totalSamples);
+
+ for (const ev of events) {
+ const start = Math.floor(ev.startSec * sampleRate);
+ const end = Math.min(totalSamples, Math.round((ev.startSec + ev.durSec) * sampleRate));
+ const durSamples = end - start;
+ if (durSamples <= 0) continue;
+ const peak = MASTER_GAIN * ev.gain * ev.vel;
+
+ if (ev.noise) {
+ const preset = NOISE_PRESETS[ev.noise];
+ const lfsr = makeLfsr();
+ let held = 0;
+ let heldFor = Infinity; // force a fresh LFSR value on the first sample
+ for (let i = 0; i < durSamples; i += 1) {
+ const t = i / sampleRate;
+ const env = Math.exp(-t / preset.decaySec) * (t < ATTACK_SEC ? t / ATTACK_SEC : 1);
+ let s;
+ if (preset.kind === 'sweep') {
+ // Exponential pitch sweep integrated in closed form keeps phase smooth.
+ const k = Math.log(preset.toHz / preset.fromHz) / preset.decaySec;
+ const phase = (preset.fromHz / k) * (Math.exp(k * t) - 1);
+ s = Math.sin(2 * Math.PI * phase);
+ } else {
+ if (heldFor >= preset.updateEvery) { held = lfsr(); heldFor = 0; }
+ heldFor += 1;
+ s = held;
+ }
+ out[start + i] += s * env * peak;
+ }
+ } else {
+ const attack = Math.min(ATTACK_SEC, ev.durSec * 0.25);
+ const release = Math.min(0.05, ev.durSec * 0.3);
+ const durSec = durSamples / sampleRate;
+ for (let i = 0; i < durSamples; i += 1) {
+ const t = i / sampleRate;
+ let env = 1;
+ if (t < attack) env = t / attack;
+ else if (t > durSec - release) env = Math.max(0, (durSec - t) / release);
+ out[start + i] += oscSample(ev.wave, ev.duty, t * ev.freq) * env * peak;
+ }
+ }
+ }
+
+ for (let i = 0; i < totalSamples; i += 1) {
+ if (out[i] > 1) out[i] = 1;
+ else if (out[i] < -1) out[i] = -1;
+ }
+ return out;
+}
+
+/** Encode mono Float32 PCM as a 16-bit little-endian WAV file buffer. */
+export function pcmToWavBuffer(pcm, { sampleRate = CHIPTUNE_SAMPLE_RATE } = {}) {
+ const dataBytes = pcm.length * 2;
+ const buf = Buffer.alloc(44 + dataBytes);
+ buf.write('RIFF', 0);
+ buf.writeUInt32LE(36 + dataBytes, 4);
+ buf.write('WAVE', 8);
+ buf.write('fmt ', 12);
+ buf.writeUInt32LE(16, 16); // fmt chunk size
+ buf.writeUInt16LE(1, 20); // PCM
+ buf.writeUInt16LE(1, 22); // mono
+ buf.writeUInt32LE(sampleRate, 24);
+ buf.writeUInt32LE(sampleRate * 2, 28); // byte rate
+ buf.writeUInt16LE(2, 32); // block align
+ buf.writeUInt16LE(16, 34); // bits per sample
+ buf.write('data', 36);
+ buf.writeUInt32LE(dataBytes, 40);
+ for (let i = 0; i < pcm.length; i += 1) {
+ buf.writeInt16LE(Math.round(pcm[i] * 32767), 44 + i * 2);
+ }
+ return buf;
+}
+
+/** Render a validated score straight to a WAV buffer. */
+export function renderScoreToWav(score, options = {}) {
+ return pcmToWavBuffer(renderScoreToPcm(score, options), options);
+}
diff --git a/server/lib/chiptuneRender.test.js b/server/lib/chiptuneRender.test.js
new file mode 100644
index 0000000000..f9d9b7a9c9
--- /dev/null
+++ b/server/lib/chiptuneRender.test.js
@@ -0,0 +1,88 @@
+import { createHash } from 'crypto';
+import { describe, expect, it } from 'vitest';
+import { renderScoreToPcm, pcmToWavBuffer, renderScoreToWav, CHIPTUNE_SAMPLE_RATE } from './chiptuneRender.js';
+
+// 120 BPM, 4 steps/beat, 1 bar of 4/4 → 16 steps · 0.125s = 2s loop.
+const score = () => ({
+ version: 1,
+ bpm: 120,
+ stepsPerBeat: 4,
+ beatsPerBar: 4,
+ channels: [
+ { id: 'pulse1', wave: 'square', duty: 0.25, gain: 0.5 },
+ { id: 'triangle', wave: 'triangle', gain: 0.6 },
+ { id: 'noise', wave: 'noise', gain: 0.4 },
+ ],
+ patterns: {
+ A: {
+ bars: 1,
+ notes: {
+ pulse1: [{ step: 0, pitch: 'C5', len: 8, vel: 0.9 }],
+ triangle: [{ step: 0, pitch: 'C3', len: 16 }],
+ noise: [
+ { step: 0, pitch: 'kick', len: 2 },
+ { step: 4, pitch: 'snare', len: 2 },
+ { step: 8, pitch: 'hat', len: 1 },
+ { step: 12, pitch: 'open-hat', len: 4 },
+ ],
+ },
+ },
+ },
+ order: ['A'],
+});
+
+describe('renderScoreToPcm', () => {
+ it('produces a loop-exact sample count', () => {
+ const pcm = renderScoreToPcm(score());
+ expect(pcm.length).toBe(Math.round(2 * CHIPTUNE_SAMPLE_RATE));
+ });
+
+ it('is deterministic — the same score renders byte-identical PCM', () => {
+ const a = renderScoreToPcm(score());
+ const b = renderScoreToPcm(score());
+ const hash = (arr) => createHash('sha256').update(Buffer.from(arr.buffer)).digest('hex');
+ expect(hash(a)).toBe(hash(b));
+ });
+
+ it('actually produces sound, bounded to [-1, 1]', () => {
+ const pcm = renderScoreToPcm(score());
+ let peak = 0;
+ for (const s of pcm) {
+ peak = Math.max(peak, Math.abs(s));
+ expect(s).toBeGreaterThanOrEqual(-1);
+ expect(s).toBeLessThanOrEqual(1);
+ }
+ expect(peak).toBeGreaterThan(0.1);
+ });
+
+ it('note envelopes stay inside the note — the loop boundary is silent-safe', () => {
+ // The last audible event (open-hat) ends at step 16 = the loop end; nothing
+ // may write past the buffer, and the final samples should be decaying, not
+ // clipped mid-waveform at full scale.
+ const pcm = renderScoreToPcm(score());
+ const tail = Math.abs(pcm[pcm.length - 1]);
+ expect(tail).toBeLessThan(0.2);
+ });
+});
+
+describe('pcmToWavBuffer', () => {
+ it('writes a well-formed 16-bit mono WAV header', () => {
+ const pcm = new Float32Array([0, 0.5, -0.5, 1]);
+ const wav = pcmToWavBuffer(pcm, { sampleRate: 44100 });
+ expect(wav.toString('ascii', 0, 4)).toBe('RIFF');
+ expect(wav.toString('ascii', 8, 12)).toBe('WAVE');
+ expect(wav.readUInt16LE(22)).toBe(1); // mono
+ expect(wav.readUInt32LE(24)).toBe(44100); // sample rate
+ expect(wav.readUInt16LE(34)).toBe(16); // bit depth
+ expect(wav.readUInt32LE(40)).toBe(pcm.length * 2);
+ expect(wav.length).toBe(44 + pcm.length * 2);
+ expect(wav.readInt16LE(44 + 6)).toBe(32767); // 1.0 → full scale
+ });
+});
+
+describe('renderScoreToWav', () => {
+ it('renders a complete WAV whose data length matches the loop', () => {
+ const wav = renderScoreToWav(score());
+ expect(wav.readUInt32LE(40)).toBe(Math.round(2 * CHIPTUNE_SAMPLE_RATE) * 2);
+ });
+});
diff --git a/server/lib/chiptuneScore.js b/server/lib/chiptuneScore.js
new file mode 100644
index 0000000000..42d02544d8
--- /dev/null
+++ b/server/lib/chiptuneScore.js
@@ -0,0 +1,205 @@
+/**
+ * Chiptune score contract (#2911) — the versioned JSON shape an LLM emits for
+ * a looping 8-bit background-music score, plus the pure math that turns it
+ * into absolute-time note events.
+ *
+ * One score = NES-style channels (two pulse waves, a triangle bass, a noise
+ * drum lane), a bank of named patterns, and an `order` list that sequences
+ * patterns into one seamless loop. Loop length is whole-pattern by
+ * construction: total steps = sum of the ordered patterns' steps, so the
+ * render/preview can loop sample-exactly with no tail math.
+ *
+ * Consumed by:
+ * - server/lib/chiptuneRender.js — offline PCM/WAV render (deterministic)
+ * - server/services/chiptune.js — LLM generation (responseSchema) + publish
+ * - server/services/tracks/logic.js — track sanitizer (sanitizeChiptuneScore)
+ * - client/src/lib/chiptunePlayback.js — WebAudio preview (MIRRORS
+ * buildScoreEvents' timing semantics; keep the two in lockstep)
+ */
+
+import { z } from 'zod';
+
+export const CHIPTUNE_SCORE_VERSION = 1;
+
+// Bounds — shared by the Zod schema, the LLM prompt contract, and the tests.
+export const CHIPTUNE_LIMITS = Object.freeze({
+ BPM_MIN: 40,
+ BPM_MAX: 240,
+ STEPS_PER_BEAT_MAX: 8,
+ BEATS_PER_BAR_MAX: 12,
+ BARS_PER_PATTERN_MAX: 16,
+ PATTERNS_MAX: 8,
+ ORDER_MAX: 32,
+ NOTES_PER_CHANNEL_MAX: 512,
+ TOTAL_STEPS_MAX: 8192,
+ TITLE_MAX: 120,
+});
+
+// The fixed channel palette. `wave` is constrained per id so the LLM can't
+// put a noise lane on a pulse channel (the renderer keys drum presets off it).
+export const CHIPTUNE_CHANNEL_IDS = Object.freeze(['pulse1', 'pulse2', 'triangle', 'noise']);
+export const CHIPTUNE_NOISE_PRESETS = Object.freeze(['kick', 'snare', 'hat', 'open-hat']);
+
+const patternNameField = z.string().regex(/^[A-Za-z0-9_-]{1,16}$/);
+
+const noteSchema = z.object({
+ step: z.number().int().min(0).max(CHIPTUNE_LIMITS.TOTAL_STEPS_MAX),
+ // Tonal channels: scientific pitch ("C4", "F#3", "Bb2"). Noise channel: a
+ // drum preset name (kick/snare/hat/open-hat). Validated leniently here (the
+ // event builder drops what it can't resolve) so one odd note can't reject a
+ // whole otherwise-good generation.
+ pitch: z.string().trim().min(1).max(12),
+ len: z.number().int().min(1).max(CHIPTUNE_LIMITS.TOTAL_STEPS_MAX),
+ vel: z.number().min(0).max(1).optional(),
+});
+
+const channelSchema = z.object({
+ id: z.enum(CHIPTUNE_CHANNEL_IDS),
+ wave: z.enum(['square', 'triangle', 'noise']),
+ duty: z.number().min(0.05).max(0.95).optional(),
+ gain: z.number().min(0).max(1).optional(),
+});
+
+const patternSchema = z.object({
+ bars: z.number().int().min(1).max(CHIPTUNE_LIMITS.BARS_PER_PATTERN_MAX),
+ // Keys are plain strings here (zod 4 treats enum-keyed records as
+ // exhaustive); the superRefine below rejects keys that aren't declared
+ // channel ids, which also gives a better error message.
+ notes: z.record(
+ z.string().max(16),
+ z.array(noteSchema).max(CHIPTUNE_LIMITS.NOTES_PER_CHANNEL_MAX),
+ ),
+});
+
+export const chiptuneScoreSchema = z.object({
+ version: z.literal(CHIPTUNE_SCORE_VERSION),
+ title: z.string().trim().max(CHIPTUNE_LIMITS.TITLE_MAX).optional(),
+ bpm: z.number().min(CHIPTUNE_LIMITS.BPM_MIN).max(CHIPTUNE_LIMITS.BPM_MAX),
+ stepsPerBeat: z.number().int().min(1).max(CHIPTUNE_LIMITS.STEPS_PER_BEAT_MAX),
+ beatsPerBar: z.number().int().min(1).max(CHIPTUNE_LIMITS.BEATS_PER_BAR_MAX),
+ channels: z.array(channelSchema).min(1).max(CHIPTUNE_CHANNEL_IDS.length),
+ patterns: z.record(patternNameField, patternSchema)
+ .refine((p) => {
+ const n = Object.keys(p).length;
+ return n >= 1 && n <= CHIPTUNE_LIMITS.PATTERNS_MAX;
+ }, { message: `patterns must contain 1–${CHIPTUNE_LIMITS.PATTERNS_MAX} entries` }),
+ order: z.array(patternNameField).min(1).max(CHIPTUNE_LIMITS.ORDER_MAX),
+}).superRefine((score, ctx) => {
+ const channelIds = new Set(score.channels.map((c) => c.id));
+ if (channelIds.size !== score.channels.length) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['channels'], message: 'channel ids must be unique' });
+ }
+ for (const name of score.order) {
+ if (!score.patterns[name]) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['order'], message: `order references unknown pattern "${name}"` });
+ return;
+ }
+ }
+ for (const [name, pattern] of Object.entries(score.patterns)) {
+ for (const channelId of Object.keys(pattern.notes || {})) {
+ if (!channelIds.has(channelId)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['patterns', name, 'notes'],
+ message: `pattern "${name}" writes to undeclared channel "${channelId}"`,
+ });
+ }
+ }
+ }
+ const stepsPerBar = score.beatsPerBar * score.stepsPerBeat;
+ const totalSteps = score.order.reduce((sum, name) => sum + (score.patterns[name]?.bars || 0) * stepsPerBar, 0);
+ if (totalSteps > CHIPTUNE_LIMITS.TOTAL_STEPS_MAX) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['order'], message: `loop is too long (${totalSteps} steps > ${CHIPTUNE_LIMITS.TOTAL_STEPS_MAX})` });
+ }
+});
+
+/**
+ * Validate an untrusted value into a canonical score, or null. Used by the
+ * track sanitizer (absent/invalid → null = "no score", per the sentinel rule).
+ */
+export function sanitizeChiptuneScore(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const parsed = chiptuneScoreSchema.safeParse(raw);
+ return parsed.success ? parsed.data : null;
+}
+
+// --- Pitch → frequency (mirrors client/src/lib/scorePlayback.js math) -------
+const PITCH_CLASS = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
+const PITCH_RE = /^([A-Ga-g])(#{1,2}|b{1,2})?(-?\d)$/;
+
+/** MIDI number for a scientific-pitch string ("C4" = 60, "A4" = 69), or null. */
+export function pitchToMidi(pitch) {
+ const m = PITCH_RE.exec(String(pitch || '').trim());
+ if (!m) return null;
+ const pc = PITCH_CLASS[m[1].toUpperCase()];
+ const shift = m[2] ? (m[2][0] === '#' ? m[2].length : -m[2].length) : 0;
+ const octave = Number(m[3]);
+ return (octave + 1) * 12 + pc + shift;
+}
+
+/** Frequency (Hz) for a MIDI note number, A4 (69) = 440. */
+export const midiToFreq = (midi) => (Number.isFinite(midi) ? 440 * Math.pow(2, (midi - 69) / 12) : null);
+
+/** Seconds per sequencer step. */
+export const scoreStepSec = (score) => 60 / (score.bpm * score.stepsPerBeat);
+
+/** Steps in one pattern. */
+export const patternSteps = (score, pattern) => pattern.bars * score.beatsPerBar * score.stepsPerBeat;
+
+/** Total loop length in steps (the order walk). */
+export function scoreTotalSteps(score) {
+ return score.order.reduce((sum, name) => sum + patternSteps(score, score.patterns[name]), 0);
+}
+
+/** Total loop length in seconds — whole-step exact, so loops are seamless. */
+export const scoreDurationSec = (score) => scoreTotalSteps(score) * scoreStepSec(score);
+
+/**
+ * Flatten a validated score into absolute-time events, one per sounding note:
+ * { channelId, wave, duty, gain, freq|null, noise|null, startSec, durSec, vel }
+ *
+ * Timing semantics (MIRRORED by client/src/lib/chiptunePlayback.js — keep in
+ * lockstep): the order walk lays patterns back to back; a note sounds at
+ * (patternBase + step) · stepSec for len · stepSec seconds. Notes that start
+ * past their pattern's end are dropped; notes that overhang it are clamped so
+ * nothing bleeds past the loop boundary (loop-safe by construction). A tonal
+ * pitch that doesn't parse (or an unknown noise preset) drops just that note.
+ */
+export function buildScoreEvents(score) {
+ const stepSec = scoreStepSec(score);
+ const channelsById = new Map(score.channels.map((c) => [c.id, c]));
+ const events = [];
+ let baseStep = 0;
+ for (const name of score.order) {
+ const pattern = score.patterns[name];
+ const steps = patternSteps(score, pattern);
+ for (const [channelId, notes] of Object.entries(pattern.notes || {})) {
+ const channel = channelsById.get(channelId);
+ if (!channel) continue;
+ for (const note of notes) {
+ if (note.step >= steps) continue;
+ const lenSteps = Math.min(note.len, steps - note.step);
+ const isNoise = channel.wave === 'noise';
+ const noise = isNoise
+ ? (CHIPTUNE_NOISE_PRESETS.includes(note.pitch) ? note.pitch : null)
+ : null;
+ const freq = isNoise ? null : midiToFreq(pitchToMidi(note.pitch));
+ if (isNoise ? !noise : !freq) continue;
+ events.push({
+ channelId,
+ wave: channel.wave,
+ duty: channel.duty ?? 0.5,
+ gain: channel.gain ?? 0.5,
+ freq,
+ noise,
+ startSec: (baseStep + note.step) * stepSec,
+ durSec: lenSteps * stepSec,
+ vel: note.vel ?? 0.8,
+ });
+ }
+ }
+ baseStep += steps;
+ }
+ events.sort((a, b) => a.startSec - b.startSec);
+ return { events, stepSec, totalSteps: baseStep, totalSec: baseStep * stepSec };
+}
diff --git a/server/lib/chiptuneScore.test.js b/server/lib/chiptuneScore.test.js
new file mode 100644
index 0000000000..50b8ef6228
--- /dev/null
+++ b/server/lib/chiptuneScore.test.js
@@ -0,0 +1,143 @@
+import { describe, expect, it } from 'vitest';
+import {
+ chiptuneScoreSchema, sanitizeChiptuneScore, pitchToMidi, midiToFreq,
+ buildScoreEvents, scoreDurationSec, scoreTotalSteps, CHIPTUNE_LIMITS,
+} from './chiptuneScore.js';
+
+// A minimal valid score: 1 bar of 4/4 at 120 BPM, 4 steps/beat → 16 steps,
+// stepSec = 60/(120·4) = 0.125s, loop = 2s.
+const validScore = () => ({
+ version: 1,
+ title: 'Test loop',
+ bpm: 120,
+ stepsPerBeat: 4,
+ beatsPerBar: 4,
+ channels: [
+ { id: 'pulse1', wave: 'square', duty: 0.5, gain: 0.5 },
+ { id: 'triangle', wave: 'triangle', gain: 0.6 },
+ { id: 'noise', wave: 'noise', gain: 0.3 },
+ ],
+ patterns: {
+ A: {
+ bars: 1,
+ notes: {
+ pulse1: [{ step: 0, pitch: 'C5', len: 4, vel: 0.8 }, { step: 8, pitch: 'E5', len: 4 }],
+ triangle: [{ step: 0, pitch: 'C3', len: 16 }],
+ noise: [{ step: 0, pitch: 'kick', len: 1 }, { step: 8, pitch: 'snare', len: 1 }],
+ },
+ },
+ },
+ order: ['A'],
+});
+
+describe('chiptuneScoreSchema', () => {
+ it('accepts a valid score', () => {
+ expect(chiptuneScoreSchema.safeParse(validScore()).success).toBe(true);
+ });
+
+ it('rejects an order entry referencing an unknown pattern', () => {
+ const score = validScore();
+ score.order = ['A', 'B'];
+ expect(chiptuneScoreSchema.safeParse(score).success).toBe(false);
+ });
+
+ it('rejects notes on an undeclared channel', () => {
+ const score = validScore();
+ score.patterns.A.notes.pulse2 = [{ step: 0, pitch: 'G4', len: 2 }];
+ expect(chiptuneScoreSchema.safeParse(score).success).toBe(false);
+ });
+
+ it('rejects duplicate channel ids', () => {
+ const score = validScore();
+ score.channels.push({ id: 'pulse1', wave: 'square' });
+ expect(chiptuneScoreSchema.safeParse(score).success).toBe(false);
+ });
+
+ it('rejects a loop that exceeds the total-step cap', () => {
+ const score = validScore();
+ score.patterns.A.bars = 16; // 256 steps per order entry
+ score.order = Array(CHIPTUNE_LIMITS.ORDER_MAX).fill('A'); // 8192... exactly at cap
+ expect(chiptuneScoreSchema.safeParse(score).success).toBe(true);
+ score.stepsPerBeat = 5; // push past the cap
+ expect(chiptuneScoreSchema.safeParse(score).success).toBe(false);
+ });
+
+ it('rejects a wrong version and non-integer steps', () => {
+ expect(chiptuneScoreSchema.safeParse({ ...validScore(), version: 2 }).success).toBe(false);
+ const score = validScore();
+ score.patterns.A.notes.pulse1[0].step = 1.5;
+ expect(chiptuneScoreSchema.safeParse(score).success).toBe(false);
+ });
+});
+
+describe('sanitizeChiptuneScore', () => {
+ it('returns the canonical score for valid input and null otherwise', () => {
+ expect(sanitizeChiptuneScore(validScore())).toMatchObject({ bpm: 120 });
+ expect(sanitizeChiptuneScore(null)).toBeNull();
+ expect(sanitizeChiptuneScore('nope')).toBeNull();
+ expect(sanitizeChiptuneScore({ version: 1 })).toBeNull();
+ });
+});
+
+describe('pitch math', () => {
+ it('parses scientific pitch to MIDI', () => {
+ expect(pitchToMidi('C4')).toBe(60);
+ expect(pitchToMidi('A4')).toBe(69);
+ expect(pitchToMidi('F#3')).toBe(54);
+ expect(pitchToMidi('Bb2')).toBe(46);
+ expect(pitchToMidi('kick')).toBeNull();
+ expect(pitchToMidi('')).toBeNull();
+ });
+
+ it('converts MIDI to frequency (A4 = 440)', () => {
+ expect(midiToFreq(69)).toBeCloseTo(440);
+ expect(midiToFreq(57)).toBeCloseTo(220);
+ expect(midiToFreq(null)).toBeNull();
+ });
+});
+
+describe('buildScoreEvents', () => {
+ it('lays patterns back to back with step-exact timing', () => {
+ const score = validScore();
+ score.order = ['A', 'A'];
+ const { events, stepSec, totalSteps, totalSec } = buildScoreEvents(score);
+ expect(stepSec).toBeCloseTo(0.125);
+ expect(totalSteps).toBe(32);
+ expect(totalSec).toBeCloseTo(4);
+ // The second loop of the melody starts one pattern (2s) after the first.
+ const c5s = events.filter((e) => e.channelId === 'pulse1' && Math.abs(e.freq - midiToFreq(72)) < 1e-6);
+ expect(c5s.map((e) => e.startSec)).toEqual([0, 2]);
+ expect(c5s[0].durSec).toBeCloseTo(0.5);
+ });
+
+ it('drops out-of-pattern notes and clamps overhang to the pattern end', () => {
+ const score = validScore();
+ score.patterns.A.notes.pulse1 = [
+ { step: 20, pitch: 'C5', len: 2 }, // starts past the 16-step pattern → dropped
+ { step: 14, pitch: 'D5', len: 8 }, // overhangs → clamped to 2 steps
+ ];
+ const { events } = buildScoreEvents(score);
+ const pulse = events.filter((e) => e.channelId === 'pulse1');
+ expect(pulse).toHaveLength(1);
+ expect(pulse[0].durSec).toBeCloseTo(2 * 0.125);
+ });
+
+ it('drops unparseable tonal pitches and unknown noise presets, keeps the rest', () => {
+ const score = validScore();
+ score.patterns.A.notes.pulse1 = [{ step: 0, pitch: 'H9x', len: 2 }, { step: 4, pitch: 'G4', len: 2 }];
+ score.patterns.A.notes.noise = [{ step: 0, pitch: 'C2', len: 1 }, { step: 2, pitch: 'hat', len: 1 }];
+ const { events } = buildScoreEvents(score);
+ expect(events.filter((e) => e.channelId === 'pulse1')).toHaveLength(1);
+ const noise = events.filter((e) => e.channelId === 'noise');
+ expect(noise).toHaveLength(1);
+ expect(noise[0].noise).toBe('hat');
+ });
+
+ it('scoreDurationSec / scoreTotalSteps agree with the event flatten', () => {
+ const score = validScore();
+ score.order = ['A', 'A', 'A'];
+ expect(scoreTotalSteps(score)).toBe(48);
+ expect(scoreDurationSec(score)).toBeCloseTo(6);
+ expect(buildScoreEvents(score).totalSec).toBeCloseTo(scoreDurationSec(score));
+ });
+});
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 015c0325d7..0bc7efa047 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -89,7 +89,12 @@ const MEDIA_COLLECTION_SCALAR_FIELDS = Object.freeze(['name', 'description', 'co
// (local and remote both differ from a base computed without renders). Excluding
// it from the hash keeps base-hash compatibility; render-only divergences are
// LWW-ordered by `updatedAt` regardless, and renders stays restorable (below).
-const HASH_EXCLUDED_FIELDS = Object.freeze({ issue: ['number'], track: ['renders'] });
+// track: renders (server-managed take history) and the additive chiptune
+// fields (#2911) stay out of the content hash — an older peer's copy simply
+// lacks the keys, and including them would leave mixed-version peers with a
+// permanent base-hash mismatch (the churn the wire comments warn about).
+// Score changes still propagate via the whole-record LWW merge (updatedAt).
+const HASH_EXCLUDED_FIELDS = Object.freeze({ issue: ['number'], track: ['renders', 'chiptuneScore', 'chiptunePrompt'] });
/**
* sha256 of the canonical content projection. Reuses sanitizeRecordForWire +
diff --git a/server/lib/index.js b/server/lib/index.js
index 8baa0b5870..d020186149 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -195,6 +195,8 @@ export * from './songCraftRef.js';
// === Domain utilities ===
export * from './appResolver.js';
export * from './capabilityMap.js';
+export * from './chiptuneRender.js';
+export * from './chiptuneScore.js';
export * from './civitai.js';
export * from './huggingfaceLora.js';
export * from './huggingfaceModel.js';
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 51105a2f2a..92445d23c8 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -564,6 +564,17 @@ export const autofixerSettingsSchema = featureProviderConfigSchema.extend({
verifyCommand: z.preprocess(emptyToUndefined, z.string().max(500).optional()),
});
+// Music settings slice (#2911). `chiptune` remembers the Track editor's last
+// chiptune generation provider/model pin plus the publish preferences (target
+// managed app + subdir inside its repo). Reuses the shared feature-provider
+// shape so an empty-string picker value normalizes to unset.
+export const musicSettingsSchema = z.object({
+ chiptune: featureProviderConfigSchema.extend({
+ publishAppId: z.preprocess(emptyToUndefined, z.string().max(120).optional()),
+ publishSubdir: z.preprocess(emptyToUndefined, z.string().max(200).optional()),
+ }).partial().optional(),
+});
+
// Creative Director settings slice. Each LLM-backed stage can pin its own
// provider/model instead of inheriting the system default. `evaluation` is a
// direct vision API call (blank = auto-pick a local vision model, else fall
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 8a73d1d41b..b94f2422fc 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -10,7 +10,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -139,6 +139,10 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.creativeDirector !== undefined) {
validateRequest(creativeDirectorSettingsSchema.partial(), req.body.creativeDirector);
}
+ // Music studio slice (#2911) — the chiptune provider pin + publish prefs.
+ if (req.body?.music !== undefined) {
+ validateRequest(musicSettingsSchema.partial(), req.body.music);
+ }
// Home location ({ lat, lon }) read by the weather_now voice tool. The schema
// already makes both fields optional + nullable (clearing falls back to the
// tool default), and the refine enforces both-or-neither — so validate the
diff --git a/server/routes/tracks.js b/server/routes/tracks.js
index 9536632056..6aaf1ab364 100644
--- a/server/routes/tracks.js
+++ b/server/routes/tracks.js
@@ -39,6 +39,7 @@ import {
import {
startYoutubeImport, attachImportSseClient, cancelYoutubeImport, YOUTUBE_URL_RE,
} from '../services/trackYoutubeImport.js';
+import { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack } from '../services/chiptune.js';
const router = Router();
@@ -259,6 +260,45 @@ router.delete('/:id/audio', asyncHandler(async (req, res) => {
res.json({ track: await tracks.updateTrack(req.params.id, { audioFilename: '' }) });
}));
+// --- Chiptune scores (#2911) — prompt-based looping 8-bit background music.
+// Generation is synchronous (a single LLM call, seconds) and strictly
+// user-triggered from the Track editor, per the AI-provider usage policy.
+
+const chiptuneGenerateSchema = z.object({
+ prompt: z.string().trim().min(1, 'prompt is required').max(tracks.PROMPT_MAX),
+ providerId: z.string().trim().max(120).optional(),
+ model: z.string().trim().max(120).optional(),
+ // true = ignore the track's existing score and compose from scratch
+ // (default is to iterate on it when one exists).
+ fresh: z.boolean().optional(),
+});
+
+const chiptunePublishSchema = z.object({
+ appId: z.string().trim().min(1).max(120),
+ subdir: z.string().trim().max(200).optional(),
+ slug: z.string().trim().max(64).optional(),
+});
+
+// Generate (or iterate on) the track's chiptune score with an AI provider.
+router.post('/:id/chiptune/generate', asyncHandler(async (req, res) => {
+ await requireTrack(req.params.id);
+ const body = validateRequest(chiptuneGenerateSchema, req.body ?? {});
+ res.json(await generateChiptuneScore({ trackId: req.params.id, ...body }));
+}));
+
+// Render the current score into the shared music library as a looping take.
+router.post('/:id/chiptune/render', asyncHandler(async (req, res) => {
+ await requireTrack(req.params.id);
+ res.json(await renderChiptuneTrack({ trackId: req.params.id }));
+}));
+
+// Publish the current score into a managed app's repo (OGG + score JSON).
+router.post('/:id/chiptune/publish', asyncHandler(async (req, res) => {
+ await requireTrack(req.params.id);
+ const body = validateRequest(chiptunePublishSchema, req.body ?? {});
+ res.json(await publishChiptuneTrack({ trackId: req.params.id, ...body }));
+}));
+
// Make a past render the active one (re-point the player + gen-metadata badges
// at it). The user-authored prompt/lyrics are left untouched — they drive the
// NEXT generation, independent of which take is selected for playback.
diff --git a/server/services/chiptune.js b/server/services/chiptune.js
new file mode 100644
index 0000000000..1544fcba19
--- /dev/null
+++ b/server/services/chiptune.js
@@ -0,0 +1,224 @@
+/**
+ * Chiptune score service (#2911) — LLM generation, offline render into the
+ * shared music library, and publish into a managed app's repo.
+ *
+ * generateChiptuneScore — prompt + any configured AI provider/model →
+ * validated score JSON persisted on the track (`chiptuneScore` +
+ * `chiptunePrompt`). User-triggered only (no cold-bootstrap LLM calls).
+ * renderChiptuneTrack — score → WAV (lib/chiptuneRender) → OGG via the
+ * system ffmpeg when available (WAV fallback otherwise), landed in the
+ * shared music library and appended to the track's render history.
+ * publishChiptuneTrack — render the CURRENT score straight into a managed
+ * app's repoPath (default `game/assets/music/`) as `<slug>.ogg` +
+ * `<slug>.score.json`, path-safety anchored to the app's repo. The game
+ * repo owns its own git — we only write files.
+ */
+
+import { mkdir, writeFile, unlink, stat } from 'fs/promises';
+import { join, resolve, sep, isAbsolute } from 'path';
+import { randomUUID } from 'crypto';
+import { ServerError } from '../lib/errorHandler.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { findFfmpeg, runFfmpegProcess } from '../lib/ffmpeg.js';
+import { chiptuneScoreSchema, CHIPTUNE_LIMITS, CHIPTUNE_NOISE_PRESETS, scoreDurationSec } from '../lib/chiptuneScore.js';
+import { renderScoreToWav } from '../lib/chiptuneRender.js';
+import { resolveProviderAndModel, assertProvider, runPromptThroughProvider } from '../lib/promptRunner.js';
+import * as tracks from './tracks/index.js';
+import { getAppById } from './apps.js';
+
+export const DEFAULT_PUBLISH_SUBDIR = 'game/assets/music';
+
+const requireTrack = async (trackId) => {
+ const track = await tracks.getTrack(trackId);
+ if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ return track;
+};
+
+const requireScore = (track) => {
+ if (!track.chiptuneScore) {
+ throw new ServerError('This track has no chiptune score yet — generate one first', {
+ status: 400, code: 'CHIPTUNE_NO_SCORE',
+ });
+ }
+ return track.chiptuneScore;
+};
+
+/** The generation contract sent to the LLM. Exported for tests. */
+export function buildChiptunePrompt({ prompt, currentScore }) {
+ const iterate = currentScore
+ ? `\nCURRENT SCORE (revise this per the request above — keep what works, change what's asked):\n${JSON.stringify(currentScore)}\n`
+ : '';
+ return `You are a chiptune composer writing a seamlessly LOOPING 8-bit background-music score for a game.
+
+MUSIC REQUEST: ${prompt}
+${iterate}
+Return ONLY a JSON object (no prose, no code fence) in exactly this shape:
+{
+ "version": 1,
+ "title": "<short title>",
+ "bpm": <number ${CHIPTUNE_LIMITS.BPM_MIN}-${CHIPTUNE_LIMITS.BPM_MAX}>,
+ "stepsPerBeat": <int 1-${CHIPTUNE_LIMITS.STEPS_PER_BEAT_MAX}, 4 = sixteenth notes>,
+ "beatsPerBar": <int 1-${CHIPTUNE_LIMITS.BEATS_PER_BAR_MAX}, usually 4>,
+ "channels": [
+ {"id": "pulse1", "wave": "square", "duty": 0.5, "gain": 0.5},
+ {"id": "pulse2", "wave": "square", "duty": 0.25, "gain": 0.4},
+ {"id": "triangle", "wave": "triangle", "gain": 0.55},
+ {"id": "noise", "wave": "noise", "gain": 0.35}
+ ],
+ "patterns": {
+ "A": {"bars": <int 1-${CHIPTUNE_LIMITS.BARS_PER_PATTERN_MAX}>, "notes": {
+ "pulse1": [{"step": 0, "pitch": "C5", "len": 2, "vel": 0.8}, ...],
+ "noise": [{"step": 0, "pitch": "kick", "len": 1}, ...]
+ }}
+ },
+ "order": ["A", "A", "B", "A"]
+}
+
+Rules:
+- pulse1 carries melody, pulse2 harmony/counter-melody, triangle the bassline, noise the drums.
+- Tonal pitches are scientific notation ("C5", "F#3", "Bb2"). Noise pitches are ONLY: ${CHIPTUNE_NOISE_PRESETS.join(', ')}.
+- "step" is the note's onset within its pattern (0-indexed, stepsPerBeat × beatsPerBar × bars steps per pattern); "len" is its length in steps. Notes must fit inside their pattern.
+- 1-${CHIPTUNE_LIMITS.PATTERNS_MAX} patterns, order length 1-${CHIPTUNE_LIMITS.ORDER_MAX}. Aim for a 15-40 second loop that ends back where it starts musically (the playback loops the whole order seamlessly).
+- Write real music: a memorable melody, movement in the bass, drums that groove. Vary velocity for feel.`;
+}
+
+/**
+ * Generate (or iterate on) a track's chiptune score with the chosen provider.
+ * When the track already has a score and `fresh` is not set, the current score
+ * is included so the LLM revises rather than starting over.
+ */
+export async function generateChiptuneScore({ trackId, prompt, providerId, model, fresh = false }) {
+ const track = await requireTrack(trackId);
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, {
+ message: 'No AI provider available for chiptune generation',
+ code: 'CHIPTUNE_NO_PROVIDER',
+ });
+
+ const currentScore = fresh ? null : track.chiptuneScore;
+ const run = await runPromptThroughProvider({
+ provider,
+ prompt: buildChiptunePrompt({ prompt, currentScore }),
+ source: 'chiptune-score',
+ model: selectedModel ?? undefined,
+ responseSchema: chiptuneScoreSchema,
+ });
+
+ // The runner validated/coerced the response against the schema; a failure
+ // here means the runner contract broke — surface it rather than persisting.
+ const parsed = chiptuneScoreSchema.safeParse(JSON.parse(run.text));
+ if (!parsed.success) {
+ throw new ServerError('Chiptune response failed schema validation after runner coercion', {
+ status: 502, code: 'CHIPTUNE_BAD_RESPONSE',
+ });
+ }
+
+ const updated = await tracks.updateTrack(trackId, { chiptuneScore: parsed.data, chiptunePrompt: prompt });
+ return { track: updated, providerId: run.provider?.id || provider.id, model: run.model ?? selectedModel ?? null };
+}
+
+// Render the score to an audio file in `dir` as `<basename>.ogg` (via ffmpeg)
+// or `<basename>.wav` when ffmpeg isn't installed. Returns the filename used.
+async function renderScoreToFile(score, dir, basename) {
+ await mkdir(dir, { recursive: true });
+ const wavPath = join(dir, `${basename}.wav`);
+ await writeFile(wavPath, renderScoreToWav(score));
+ const bin = await findFfmpeg();
+ if (!bin) return `${basename}.wav`;
+ const oggPath = join(dir, `${basename}.ogg`);
+ const result = await runFfmpegProcess({ bin, args: ['-y', '-i', wavPath, '-c:a', 'libvorbis', '-q:a', '5', oggPath] });
+ if (!result.ok) {
+ console.error(`❌ Chiptune OGG encode failed (keeping WAV): ${result.reason}`);
+ return `${basename}.wav`;
+ }
+ await unlink(wavPath).catch(() => {});
+ return `${basename}.ogg`;
+}
+
+/**
+ * Render the track's current score into the shared music library and append
+ * it to the render history (same contract as the diffusion generate route).
+ */
+export async function renderChiptuneTrack({ trackId }) {
+ const track = await requireTrack(trackId);
+ const score = requireScore(track);
+ const filename = await renderScoreToFile(score, PATHS.music, `music-${randomUUID()}`);
+ const durationSec = Math.max(1, Math.round(scoreDurationSec(score)));
+
+ // Re-read so the append lands on the freshest history (musicGen route pattern).
+ const current = (await tracks.getTrack(trackId)) ?? track;
+ const { renders } = tracks.buildRenderAppend(current, {
+ audioFilename: filename,
+ prompt: track.chiptunePrompt,
+ engine: 'chiptune',
+ durationSec,
+ });
+ const updated = await tracks.updateTrack(trackId, {
+ audioFilename: filename,
+ engine: 'chiptune',
+ modelId: '',
+ durationSec,
+ renders,
+ });
+ return { track: updated, filename, durationSec };
+}
+
+const SLUG_RE = /[^a-z0-9-]+/g;
+const slugify = (s) => String(s || '').toLowerCase().trim().replace(SLUG_RE, '-').replace(/^-+|-+$/g, '').slice(0, 64);
+
+// A publish subdir must stay inside the app repo: relative, no traversal, no
+// backslashes (Windows-style separators would dodge the segment check).
+function assertSafeSubdir(subdir) {
+ if (isAbsolute(subdir) || subdir.includes('\\') || subdir.split('/').some((seg) => seg === '..')) {
+ throw new ServerError('Publish subdir must be a relative path inside the app repo', {
+ status: 400, code: 'CHIPTUNE_BAD_SUBDIR',
+ });
+ }
+}
+
+/**
+ * Render the track's current score directly into a managed app's repo:
+ * `<repoPath>/<subdir>/<slug>.ogg` + `<slug>.score.json` (the editable source
+ * travels with the audio). Path-safety anchored to the app's repoPath.
+ */
+export async function publishChiptuneTrack({ trackId, appId, subdir, slug }) {
+ const track = await requireTrack(trackId);
+ const score = requireScore(track);
+
+ const app = await getAppById(appId);
+ if (!app || !app.repoPath) {
+ throw new ServerError('Managed app not found (or it has no repo path)', { status: 404, code: 'CHIPTUNE_APP_NOT_FOUND' });
+ }
+ const repoRoot = resolve(app.repoPath);
+ const repoStat = await stat(repoRoot).catch(() => null);
+ if (!repoStat?.isDirectory()) {
+ throw new ServerError(`App repo path does not exist: ${app.repoPath}`, { status: 400, code: 'CHIPTUNE_APP_REPO_MISSING' });
+ }
+
+ // Validate the RAW subdir before any normalization — stripping a leading
+ // slash first would launder an absolute path into a relative-looking one.
+ const rawSubdir = subdir || DEFAULT_PUBLISH_SUBDIR;
+ assertSafeSubdir(rawSubdir);
+ const cleanSubdir = rawSubdir.replace(/\/+$/g, '');
+ const targetDir = resolve(repoRoot, cleanSubdir);
+ if (targetDir !== repoRoot && !targetDir.startsWith(repoRoot + sep)) {
+ throw new ServerError('Publish target escapes the app repo', { status: 400, code: 'CHIPTUNE_BAD_SUBDIR' });
+ }
+
+ const name = slugify(slug) || slugify(track.title) || 'track';
+ const audioFilename = await renderScoreToFile(score, targetDir, name);
+ const scoreFilename = `${name}.score.json`;
+ await writeFile(join(targetDir, scoreFilename), `${JSON.stringify(score, null, 2)}\n`);
+
+ const rel = (f) => (cleanSubdir ? `${cleanSubdir}/${f}` : f);
+ console.log(`🎮 Published chiptune "${name}" to app ${app.name} (${rel(audioFilename)})`);
+ return {
+ appId: app.id,
+ appName: app.name,
+ files: [rel(audioFilename), rel(scoreFilename)],
+ format: audioFilename.endsWith('.ogg') ? 'ogg' : 'wav',
+ note: audioFilename.endsWith('.ogg')
+ ? 'Godot auto-imports the OGG; enable "Loop" in its import settings for seamless background playback.'
+ : 'ffmpeg was not found, so the loop was published as WAV. Install ffmpeg for OGG output.',
+ };
+}
diff --git a/server/services/chiptune.test.js b/server/services/chiptune.test.js
new file mode 100644
index 0000000000..5bdd1ea8ae
--- /dev/null
+++ b/server/services/chiptune.test.js
@@ -0,0 +1,217 @@
+import { mkdtemp, readFile, readdir, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const tmpRoots = [];
+const makeTmp = async (prefix) => {
+ const dir = await mkdtemp(join(tmpdir(), prefix));
+ tmpRoots.push(dir);
+ return dir;
+};
+const musicDir = await makeTmp('chiptune-music-');
+
+vi.mock('./tracks/index.js', () => ({
+ getTrack: vi.fn(),
+ updateTrack: vi.fn(),
+ buildRenderAppend: vi.fn((track, input) => {
+ const render = { id: 'render-test', ...input, createdAt: '2026-01-01T00:00:00.000Z' };
+ return { render, renders: [...(track?.renders || []), render] };
+ }),
+}));
+
+vi.mock('../lib/promptRunner.js', () => ({
+ resolveProviderAndModel: vi.fn(),
+ assertProvider: vi.fn(),
+ runPromptThroughProvider: vi.fn(),
+}));
+
+vi.mock('./apps.js', () => ({
+ getAppById: vi.fn(),
+}));
+
+// No ffmpeg in tests — the render path keeps the deterministic WAV output.
+vi.mock('../lib/ffmpeg.js', () => ({
+ findFfmpeg: vi.fn().mockResolvedValue(null),
+ runFfmpegProcess: vi.fn(),
+}));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, music: musicDir } };
+});
+
+const tracks = await import('./tracks/index.js');
+const promptRunner = await import('../lib/promptRunner.js');
+const apps = await import('./apps.js');
+const { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack, buildChiptunePrompt } = await import('./chiptune.js');
+
+const validScore = () => ({
+ version: 1,
+ bpm: 120,
+ stepsPerBeat: 4,
+ beatsPerBar: 4,
+ channels: [{ id: 'pulse1', wave: 'square', duty: 0.5, gain: 0.5 }],
+ patterns: { A: { bars: 1, notes: { pulse1: [{ step: 0, pitch: 'C5', len: 4 }] } } },
+ order: ['A'],
+});
+
+const baseTrack = (extra = {}) => ({
+ id: 'track-1', title: 'Farm Theme', renders: [], chiptuneScore: null, chiptunePrompt: '', ...extra,
+});
+
+afterAll(async () => {
+ await Promise.all(tmpRoots.map((dir) => rm(dir, { recursive: true, force: true })));
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ promptRunner.resolveProviderAndModel.mockResolvedValue({
+ provider: { id: 'prov-1', type: 'api' }, selectedModel: 'model-x',
+ });
+ tracks.updateTrack.mockImplementation(async (id, patch) => ({ ...baseTrack(), ...patch }));
+});
+
+describe('generateChiptuneScore', () => {
+ it('runs the provider with the score schema and persists the validated score', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack());
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify(validScore()), provider: { id: 'prov-1' }, model: 'model-x',
+ });
+
+ const result = await generateChiptuneScore({ trackId: 'track-1', prompt: 'upbeat farm theme', providerId: 'prov-1', model: 'model-x' });
+
+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({
+ provider: { id: 'prov-1', type: 'api' },
+ source: 'chiptune-score',
+ model: 'model-x',
+ responseSchema: expect.anything(),
+ }));
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', {
+ chiptuneScore: expect.objectContaining({ bpm: 120 }),
+ chiptunePrompt: 'upbeat farm theme',
+ });
+ expect(result.providerId).toBe('prov-1');
+ expect(result.model).toBe('model-x');
+ });
+
+ it('iterates on an existing score by default and starts fresh when asked', async () => {
+ const existing = validScore();
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: existing }));
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(validScore()), provider: { id: 'prov-1' }, model: null });
+
+ await generateChiptuneScore({ trackId: 'track-1', prompt: 'faster' });
+ expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).toContain('CURRENT SCORE');
+
+ await generateChiptuneScore({ trackId: 'track-1', prompt: 'faster', fresh: true });
+ expect(promptRunner.runPromptThroughProvider.mock.calls[1][0].prompt).not.toContain('CURRENT SCORE');
+ });
+
+ it('rejects a response that fails schema validation after the runner', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack());
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify({ version: 1 }), provider: { id: 'prov-1' } });
+ await expect(generateChiptuneScore({ trackId: 'track-1', prompt: 'x' }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_BAD_RESPONSE' });
+ expect(tracks.updateTrack).not.toHaveBeenCalled();
+ });
+
+ it('404s on an unknown track', async () => {
+ tracks.getTrack.mockResolvedValue(null);
+ await expect(generateChiptuneScore({ trackId: 'nope', prompt: 'x' }))
+ .rejects.toMatchObject({ status: 404 });
+ });
+});
+
+describe('buildChiptunePrompt', () => {
+ it('embeds the request and, when iterating, the current score JSON', () => {
+ const fresh = buildChiptunePrompt({ prompt: 'spooky cave theme', currentScore: null });
+ expect(fresh).toContain('spooky cave theme');
+ expect(fresh).not.toContain('CURRENT SCORE');
+ const iterate = buildChiptunePrompt({ prompt: 'more drums', currentScore: validScore() });
+ expect(iterate).toContain('CURRENT SCORE');
+ expect(iterate).toContain('"order":["A"]');
+ });
+});
+
+describe('renderChiptuneTrack', () => {
+ it('400s when the track has no score', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack());
+ await expect(renderChiptuneTrack({ trackId: 'track-1' }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_NO_SCORE' });
+ });
+
+ it('renders a WAV into the music library and appends a chiptune render', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore(), chiptunePrompt: 'farm loop' }));
+
+ const result = await renderChiptuneTrack({ trackId: 'track-1' });
+
+ expect(result.filename).toMatch(/^music-.+\.wav$/);
+ const files = await readdir(musicDir);
+ expect(files).toContain(result.filename);
+ expect(result.durationSec).toBe(2); // 16 steps · 0.125s = 2s
+ expect(tracks.buildRenderAppend).toHaveBeenCalledWith(expect.objectContaining({ id: 'track-1' }), {
+ audioFilename: result.filename,
+ prompt: 'farm loop',
+ engine: 'chiptune',
+ durationSec: result.durationSec,
+ });
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({
+ audioFilename: result.filename,
+ engine: 'chiptune',
+ modelId: '',
+ }));
+ });
+});
+
+describe('publishChiptuneTrack', () => {
+ it('404s when the app is unknown or has no repoPath', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
+ apps.getAppById.mockResolvedValue(null);
+ await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'nope' }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_FOUND' });
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: '' });
+ await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_FOUND' });
+ });
+
+ it('rejects traversal and absolute subdirs before touching the filesystem', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
+ const repo = await makeTmp('chiptune-repo-');
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });
+ for (const subdir of ['../outside', 'a/../../b', '/etc', 'a\\..\\b']) {
+ await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1', subdir }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
+ }
+ });
+
+ it('400s when the repo path does not exist on disk', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: '/nonexistent/path/for/test' });
+ await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_APP_REPO_MISSING' });
+ });
+
+ it('writes the audio + score JSON under the default subdir with a slugged name', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
+ const repo = await makeTmp('chiptune-repo-');
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });
+
+ const result = await publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' });
+
+ expect(result.files).toEqual(['game/assets/music/farm-theme.wav', 'game/assets/music/farm-theme.score.json']);
+ expect(result.format).toBe('wav'); // ffmpeg mocked away → WAV fallback
+ const published = JSON.parse(await readFile(join(repo, 'game/assets/music/farm-theme.score.json'), 'utf8'));
+ expect(published.bpm).toBe(120);
+ const audio = await readFile(join(repo, 'game/assets/music/farm-theme.wav'));
+ expect(audio.toString('ascii', 0, 4)).toBe('RIFF');
+ });
+
+ it('honors a custom subdir and slug', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
+ const repo = await makeTmp('chiptune-repo-');
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });
+
+ const result = await publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1', subdir: 'assets/bgm', slug: 'Overworld Theme!' });
+ expect(result.files[0]).toBe('assets/bgm/overworld-theme.wav');
+ });
+});
diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.js
index d826ce453a..c150e5a8ee 100644
--- a/server/services/tracks/logic.js
+++ b/server/services/tracks/logic.js
@@ -37,6 +37,7 @@
*/
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
+import { sanitizeChiptuneScore } from '../../lib/chiptuneScore.js';
export const TRACK_ID_RE = /^track-[A-Za-z0-9-]{1,64}$/;
@@ -171,6 +172,11 @@ export function sanitizeTrack(raw) {
durationSec,
audioFilename,
renders,
+ // Chiptune score (#2911): null = no score; an invalid stored/synced value
+ // also normalizes to null (sentinel rule — absent and invalid collapse to
+ // "no score", never to a half-valid object the renderer would trip on).
+ chiptuneScore: sanitizeChiptuneScore(raw.chiptuneScore),
+ chiptunePrompt: trimTo(raw.chiptunePrompt, PROMPT_MAX),
createdAt,
updatedAt,
deleted,
@@ -268,6 +274,7 @@ export function deleteRenderPatch(current, renderId) {
// generic create/patch route schemas omit it so a client can't inject history.
const PATCHABLE = [
'title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders',
+ 'chiptuneScore', 'chiptunePrompt',
];
/**
diff --git a/server/services/tracks/logic.test.js b/server/services/tracks/logic.test.js
index 18770acc33..52c7d5269e 100644
--- a/server/services/tracks/logic.test.js
+++ b/server/services/tracks/logic.test.js
@@ -174,4 +174,31 @@ describe('tracks logic', () => {
expect(trackAudioFilename('sub/dir.mp3')).toBeNull();
});
});
+
+ describe('chiptune fields (#2911)', () => {
+ const score = {
+ version: 1, bpm: 120, stepsPerBeat: 4, beatsPerBar: 4,
+ channels: [{ id: 'pulse1', wave: 'square' }],
+ patterns: { A: { bars: 1, notes: { pulse1: [{ step: 0, pitch: 'C5', len: 4 }] } } },
+ order: ['A'],
+ };
+
+ it('sanitizes a valid score, nulls an invalid one, keeps the prompt', () => {
+ const track = sanitizeTrack({ id: 'track-1', title: 'X', chiptuneScore: score, chiptunePrompt: 'farm loop' });
+ expect(track.chiptuneScore).toMatchObject({ bpm: 120 });
+ expect(track.chiptunePrompt).toBe('farm loop');
+ const bad = sanitizeTrack({ id: 'track-1', title: 'X', chiptuneScore: { version: 99 } });
+ expect(bad.chiptuneScore).toBeNull();
+ });
+
+ it('is patchable — absent preserves, present overwrites', () => {
+ const base = sanitizeTrack({ id: 'track-1', title: 'X', chiptuneScore: score, chiptunePrompt: 'v1' });
+ const untouched = applyTrackPatch(base, { title: 'Y' });
+ expect(untouched.chiptuneScore).toMatchObject({ bpm: 120 });
+ expect(untouched.chiptunePrompt).toBe('v1');
+ const cleared = applyTrackPatch(base, { chiptuneScore: null, chiptunePrompt: '' });
+ expect(cleared.chiptuneScore).toBeNull();
+ expect(cleared.chiptunePrompt).toBe('');
+ });
+ });
});