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

refactor([issue-2911]): apply quality-pass findings to the chiptune feature

[._.]/ Adam Eivy8f91ba723232
diff --git a/server/lib/chiptuneRender.js b/server/lib/chiptuneRender.js
index 5a5725bdf2..6ec1ff49c1 100644
--- a/server/lib/chiptuneRender.js
+++ b/server/lib/chiptuneRender.js
@@ -72,14 +72,16 @@ export function renderScoreToPcm(score, { sampleRate = CHIPTUNE_SAMPLE_RATE } =
const lfsr = makeLfsr();
let held = 0;
let heldFor = Infinity; // force a fresh LFSR value on the first sample
+ // Sweep constants are per-preset, not per-sample — hoist out of the loop.
+ const k = preset.kind === 'sweep' ? Math.log(preset.toHz / preset.fromHz) / preset.decaySec : 0;
+ const fromOverK = k ? preset.fromHz / k : 0;
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);
+ const phase = fromOverK * (Math.exp(k * t) - 1);
s = Math.sin(2 * Math.PI * phase);
} else {
if (heldFor >= preset.updateEvery) { held = lfsr(); heldFor = 0; }
diff --git a/server/lib/chiptuneScore.js b/server/lib/chiptuneScore.js
index 42d02544d8..d7e8a90091 100644
--- a/server/lib/chiptuneScore.js
+++ b/server/lib/chiptuneScore.js
@@ -106,8 +106,9 @@ export const chiptuneScoreSchema = z.object({
}
}
}
- const stepsPerBar = score.beatsPerBar * score.stepsPerBeat;
- const totalSteps = score.order.reduce((sum, name) => sum + (score.patterns[name]?.bars || 0) * stepsPerBar, 0);
+ // The order loop above already returned on any unknown pattern, so the
+ // shared step math is safe to reuse here (one formula, not two).
+ const totalSteps = scoreTotalSteps(score);
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})` });
}
diff --git a/server/services/chiptune.js b/server/services/chiptune.js
index 1544fcba19..67ce26caa7 100644
--- a/server/services/chiptune.js
+++ b/server/services/chiptune.js
@@ -14,17 +14,17 @@
* 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 { unlink, stat } from 'fs/promises';
+import { join, resolve, isAbsolute } from 'path';
import { randomUUID } from 'crypto';
import { ServerError } from '../lib/errorHandler.js';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, atomicWrite, isPathInsideDir } 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';
+import { getAppById, PORTOS_APP_ID } from './apps.js';
export const DEFAULT_PUBLISH_SUBDIR = 'game/assets/music';
@@ -120,9 +120,8 @@ export async function generateChiptuneScore({ trackId, prompt, providerId, model
// 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));
+ await atomicWrite(wavPath, renderScoreToWav(score)); // ensureDir + temp-rename
const bin = await findFfmpeg();
if (!bin) return `${basename}.wav`;
const oggPath = join(dir, `${basename}.ogg`);
@@ -189,6 +188,12 @@ export async function publishChiptuneTrack({ trackId, appId, subdir, slug }) {
if (!app || !app.repoPath) {
throw new ServerError('Managed app not found (or it has no repo path)', { status: 404, code: 'CHIPTUNE_APP_NOT_FOUND' });
}
+ // Enforce the publishable-target policy server-side (the panel's app filter
+ // is just a mirror of this rule): never write generated assets into PortOS's
+ // own working tree, and archived apps aren't valid destinations.
+ if (app.id === PORTOS_APP_ID || app.archived) {
+ throw new ServerError('That app is not a publishable target', { status: 400, code: 'CHIPTUNE_APP_NOT_PUBLISHABLE' });
+ }
const repoRoot = resolve(app.repoPath);
const repoStat = await stat(repoRoot).catch(() => null);
if (!repoStat?.isDirectory()) {
@@ -201,23 +206,24 @@ export async function publishChiptuneTrack({ trackId, appId, subdir, slug }) {
assertSafeSubdir(rawSubdir);
const cleanSubdir = rawSubdir.replace(/\/+$/g, '');
const targetDir = resolve(repoRoot, cleanSubdir);
- if (targetDir !== repoRoot && !targetDir.startsWith(repoRoot + sep)) {
+ if (targetDir !== repoRoot && !isPathInsideDir(repoRoot, targetDir)) {
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`);
+ await atomicWrite(join(targetDir, scoreFilename), `${JSON.stringify(score, null, 2)}\n`);
const rel = (f) => (cleanSubdir ? `${cleanSubdir}/${f}` : f);
+ const isOgg = audioFilename.endsWith('.ogg');
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')
+ format: isOgg ? 'ogg' : 'wav',
+ note: isOgg
? '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
index 5bdd1ea8ae..14e1218382 100644
--- a/server/services/chiptune.test.js
+++ b/server/services/chiptune.test.js
@@ -28,6 +28,7 @@ vi.mock('../lib/promptRunner.js', () => ({
vi.mock('./apps.js', () => ({
getAppById: vi.fn(),
+ PORTOS_APP_ID: 'portos-default',
}));
// No ffmpeg in tests — the render path keeps the deterministic WAV output.
@@ -174,6 +175,16 @@ describe('publishChiptuneTrack', () => {
.rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_FOUND' });
});
+ it('refuses PortOS itself and archived apps as publish targets', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
+ apps.getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS', repoPath: '/tmp' });
+ await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'portos-default' }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_PUBLISHABLE' });
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: '/tmp', archived: true });
+ await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' }))
+ .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_PUBLISHABLE' });
+ });
+
it('rejects traversal and absolute subdirs before touching the filesystem', async () => {
tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
const repo = await makeTmp('chiptune-repo-');