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

add a music publish lane to the Game studio, symmetric with artwork

[._.]/ Adam Eivyfda2ea609e76
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7fb992e4a3..2fd9d15458 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,7 @@
- **Quota Burn is now its own page (`Dev Tools → Quota Burn`) driven by one programmatic loop.** It used to be a `quota-burn` entry in each managed app's `taskTypeOverrides`, which meant the schedule, the provider windows, and the burn prompt were duplicated per app — and two enabled apps ran two independent loops racing for the same window budget, even though quota belongs to the machine, not to any one repo. There is now ONE install-level loop inside PortOS reading one machine-local plan (`data/cos/quota-burn.json`), with a full config surface: master switch, poll interval, and per-provider-family reset window / reserve / dispatch cap / priority.
- **Each family runs an ORDERED list of burn jobs, each with its own type, model, and target** — so "have codex render every universe bible entry that has no image, and only then fall through to agent work" is expressible. Two job types ship: `agent-prompt` (the previous behavior — queue a CoS agent in a *named* managed app, so the work can still target any app) and `universe-bible-images`, a fully programmatic job that enqueues renders for bible entries whose `imageRefs[]` is empty, defaulting the render backend to the burning family's own image mode so a codex burn spends codex's image quota. A new job type is three server edits; the config form builds itself from the server's job catalog.
- The page states, per family, whether it will burn on the next tick and — when it won't — the exact gate that closed (`resets in 40h — outside the 24h window`, `dispatch cap reached (2/2)`, `62% left is at or below the 70% reserve`), evaluated by the same predicate the runner uses. Per-job pending counts, a run log that records skips *with reasons*, and manual "Evaluate now" / "Burn now" / per-job force-run controls are all on the page.
+- **Game studio music bindings can now publish into the game repo, symmetric with the artwork lane.** `POST /api/games/:id/music/:bindingId/publish` copies the bound track's library audio into the managed app repository with SHA-256 provenance, an occupied/diverged-destination guard behind an explicit overwrite acknowledgement, a mid-deploy refusal, and per-repo write serialization shared with the artwork lane (one queue, so artwork and music publishes into the same repo can't race). Music bindings gained an editable repo-relative `destinationPath` (`PATCH /api/games/:id/music/:bindingId`, defaulted from the rendered audio filename under `game/assets/music/` at bind time), the integrity preflight now reports published/pending state for music exactly as it does for artwork — without changing the manifest-input hash of destination-less legacy bindings, so upgrading alone can't flag an existing bundle stale — and the Assets tab's music rows grew destination editing, a Publish button, and an inline overwrite-consent flow.
## Fixed
diff --git a/client/src/components/games/GameBindings.jsx b/client/src/components/games/GameBindings.jsx
index 4fdd395be8..0cd3f5e6f7 100644
--- a/client/src/components/games/GameBindings.jsx
+++ b/client/src/components/games/GameBindings.jsx
@@ -138,6 +138,136 @@ function BindingRow({
);
}
+// Music rows mirror the artwork publish UX (editable repo destination, publish
+// behind saved details, published/pending pill) in the compact row layout the
+// music list uses. A destination-less binding (created before the publish lane
+// existed, or synced from an older peer) shows the editor with an empty input
+// and keeps Publish disabled until a destination is saved.
+function MusicBindingRow({
+ binding,
+ track,
+ health,
+ issue,
+ busy,
+ overwriteRequested,
+ onUpdate,
+ onPublish,
+ onUnbind,
+ onDismissOverwrite,
+}) {
+ const [destinationPath, setDestinationPath] = useState(binding.destinationPath || '');
+ useEffect(() => {
+ setDestinationPath(binding.destinationPath || '');
+ }, [binding]);
+ const dirty = destinationPath.trim() !== (binding.destinationPath || '');
+ const publicationCurrent = health?.publicationStatus === 'current';
+ const { Icon, className } = healthTone(health);
+ // Shown only when the preflight has no verdict for this track, so it must
+ // state what the RECORD says, not claim a verification result — "Audio
+ // ready" here would assert bytes nobody hashed. The server's message wins.
+ const message = health?.message || (track?.audioFilename ? 'Audio attached' : 'No audio yet');
+ const needsAttention = health?.status === 'blocked';
+ const explanation = missingHelp[issue?.code] || issue?.message;
+ return (
+ <li className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2">
+ <div className="flex min-h-[54px] items-start justify-between gap-2">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <Icon className={`h-3.5 w-3.5 shrink-0 ${className}`} aria-hidden="true" />
+ <div className="truncate text-sm font-medium text-white">{track?.title || binding.trackId}</div>
+ {binding.destinationPath ? (
+ <Pill tone={publicationCurrent ? 'success' : 'warning'} bordered={false}>
+ {publicationCurrent ? 'Published' : 'Publish pending'}
+ </Pill>
+ ) : null}
+ </div>
+ <div className="truncate text-xs text-gray-500" title={message}>{message}</div>
+ {needsAttention && explanation ? (
+ <p className="mt-1 text-xs leading-5 text-gray-400">{explanation}</p>
+ ) : null}
+ {needsAttention && track && !sourceIsMissing(issue) ? (
+ <Link
+ to={`/music/tracks/${encodeURIComponent(binding.trackId)}`}
+ className="mt-1 inline-flex min-h-[32px] items-center gap-1 text-xs font-medium text-port-accent hover:underline"
+ >
+ Open in Music
+ <ArrowUpRight className="h-3.5 w-3.5" aria-hidden="true" />
+ </Link>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ onClick={() => onUnbind(binding.id)}
+ disabled={busy}
+ className="min-h-[44px] min-w-[44px] shrink-0 rounded-lg p-2 text-gray-400 hover:text-port-error disabled:opacity-50"
+ aria-label={`Unbind ${track?.title || binding.trackId}`}
+ title="Unbind music track"
+ >
+ <Unlink className="h-4 w-4" aria-hidden="true" />
+ </button>
+ </div>
+ <div className="mt-2">
+ <label htmlFor={`music-dest-${binding.id}`} className="mb-1 block text-xs text-gray-400">Game destination</label>
+ <input
+ id={`music-dest-${binding.id}`}
+ value={destinationPath}
+ maxLength={500}
+ placeholder="game/assets/music/track.mp3"
+ onChange={(event) => setDestinationPath(event.target.value)}
+ className={`${inputClass} font-mono text-xs`}
+ />
+ </div>
+ <div className="mt-2 flex flex-wrap gap-2">
+ <button
+ type="button"
+ disabled={busy || !dirty || !destinationPath.trim()}
+ onClick={() => onUpdate(binding.id, { destinationPath: destinationPath.trim() })}
+ className="inline-flex min-h-[40px] items-center gap-2 rounded-lg border border-port-border px-3 text-xs font-medium text-gray-200 hover:border-port-accent/60 disabled:opacity-40"
+ >
+ <Save className="h-3.5 w-3.5" aria-hidden="true" />
+ Save destination
+ </button>
+ <button
+ type="button"
+ disabled={busy || dirty || !binding.destinationPath}
+ onClick={() => onPublish(binding.id)}
+ title={dirty
+ ? 'Save destination changes before publishing'
+ : (!binding.destinationPath ? 'Set a game destination before publishing' : undefined)}
+ className="inline-flex min-h-[40px] items-center gap-2 rounded-lg bg-port-accent px-3 text-xs font-semibold text-white disabled:opacity-40"
+ >
+ <Send className="h-3.5 w-3.5" aria-hidden="true" />
+ {publicationCurrent ? 'Republish' : 'Publish to game'}
+ </button>
+ </div>
+ {overwriteRequested ? (
+ <div className="mt-2 flex flex-wrap items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2">
+ <AlertTriangle className="h-4 w-4 shrink-0 text-amber-400" aria-hidden="true" />
+ <p className="min-w-0 flex-1 text-xs leading-5 text-amber-200">
+ {binding.destinationPath} contains bytes PortOS did not publish. Overwrite it?
+ </p>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => onPublish(binding.id, true)}
+ className="inline-flex min-h-[36px] items-center rounded-lg bg-amber-500/80 px-3 text-xs font-semibold text-black disabled:opacity-40"
+ >
+ Overwrite
+ </button>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={onDismissOverwrite}
+ className="inline-flex min-h-[36px] items-center rounded-lg border border-port-border px-3 text-xs text-gray-300 disabled:opacity-40"
+ >
+ Cancel
+ </button>
+ </div>
+ ) : null}
+ </li>
+ );
+}
+
function BindingSection({
title,
icon: Icon,
@@ -316,7 +446,11 @@ export default function GameBindings({
onBindSprite,
onUnbindSprite,
onBindMusic,
+ onUpdateMusic,
+ onPublishMusic,
onUnbindMusic,
+ musicOverwriteFor,
+ onDismissMusicOverwrite,
onBindArtwork,
onUpdateArtwork,
onPublishArtwork,
@@ -438,30 +572,21 @@ export default function GameBindings({
>
{game.musicBindings.length > 0 ? (
<ul className="max-h-72 space-y-2 overflow-y-auto pr-1">
- {game.musicBindings.map((binding) => {
- const track = trackMap.get(binding.trackId);
- const issue = musicIssues.get(binding.trackId);
- return (
- <BindingRow
- key={binding.id}
- label={track?.title || binding.trackId}
- // Shown only when the preflight has no verdict for this track,
- // so it must state what the RECORD says, not claim a
- // verification result — "Audio ready" here would assert bytes
- // nobody hashed. The server's own message wins when present.
- detail={track?.audioFilename ? 'Audio attached' : 'No audio yet'}
- health={musicIntegrity.get(binding.id)}
- issue={issue}
- manageTo={track && !sourceIsMissing(issue)
- ? `/music/tracks/${encodeURIComponent(binding.trackId)}`
- : null}
- manageLabel="Open in Music"
- disabled={busy}
- onUnbind={() => onUnbindMusic(binding.id)}
- unbindTitle="Unbind music track"
- />
- );
- })}
+ {game.musicBindings.map((binding) => (
+ <MusicBindingRow
+ key={binding.id}
+ binding={binding}
+ track={trackMap.get(binding.trackId)}
+ health={musicIntegrity.get(binding.id)}
+ issue={musicIssues.get(binding.trackId)}
+ busy={busy}
+ overwriteRequested={musicOverwriteFor === binding.id}
+ onUpdate={onUpdateMusic}
+ onPublish={onPublishMusic}
+ onUnbind={onUnbindMusic}
+ onDismissOverwrite={onDismissMusicOverwrite}
+ />
+ ))}
</ul>
) : null}
</BindingSection>
diff --git a/client/src/components/games/GameBindings.test.jsx b/client/src/components/games/GameBindings.test.jsx
index 8a8f12e920..5df82e1055 100644
--- a/client/src/components/games/GameBindings.test.jsx
+++ b/client/src/components/games/GameBindings.test.jsx
@@ -1,16 +1,24 @@
-import { render, screen, within } from '@testing-library/react';
+import { fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import GameBindings from './GameBindings.jsx';
const noop = vi.fn();
+const onUpdateMusic = vi.fn();
+const onPublishMusic = vi.fn();
+const onDismissMusicOverwrite = vi.fn();
-const renderBindings = () => render(
+const renderBindings = (props = {}) => render(
<MemoryRouter>
<GameBindings
game={{
spriteBindings: [{ spriteId: 'deleted-sprite' }],
- musicBindings: [{ id: 'binding-1', trackId: 'theme/one' }],
+ musicBindings: [{
+ id: 'binding-1',
+ trackId: 'theme/one',
+ destinationPath: 'game/assets/music/example-theme.ogg',
+ publication: null,
+ }],
artworkBindings: [{
id: 'artwork-1',
imageFilename: 'title.png',
@@ -74,16 +82,25 @@ const renderBindings = () => render(
onBindSprite={noop}
onUnbindSprite={noop}
onBindMusic={noop}
+ onUpdateMusic={onUpdateMusic}
+ onPublishMusic={onPublishMusic}
onUnbindMusic={noop}
+ musicOverwriteFor={null}
+ onDismissMusicOverwrite={onDismissMusicOverwrite}
onBindArtwork={noop}
onUpdateArtwork={noop}
onPublishArtwork={noop}
onUnbindArtwork={noop}
+ {...props}
/>
</MemoryRouter>,
);
+const musicSection = () => screen.getByRole('heading', { name: 'Music assets' }).closest('section');
+
describe('GameBindings', () => {
+ beforeEach(() => vi.clearAllMocks());
+
it('explains a missing source without trusting a stale catalog entry enough to link it', () => {
renderBindings();
@@ -108,10 +125,61 @@ describe('GameBindings', () => {
renderBindings();
expect(screen.getByRole('heading', { name: 'World & interface artwork' })).toBeInTheDocument();
expect(screen.getByRole('img', { name: 'Title Key Art preview' })).toHaveAttribute('src', '/data/images/title.png');
- expect(screen.getByText('Publish pending')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Publish to game' })).toBeEnabled();
+ const artworkSection = screen.getByRole('heading', { name: 'World & interface artwork' }).closest('section');
+ expect(within(artworkSection).getByText('Publish pending')).toBeInTheDocument();
+ expect(within(artworkSection).getByRole('button', { name: 'Publish to game' })).toBeEnabled();
expect(screen.getByRole('link', { name: 'Generate for this role' }))
.toHaveAttribute('href', expect.stringContaining('/media/image?prompt='));
expect(screen.getAllByRole('option', { name: 'Game logo' })).toHaveLength(2);
});
+
+ it('edits the music destination and keeps publishing behind the saved path', () => {
+ renderBindings();
+ const section = musicSection();
+ expect(within(section).getByText('Publish pending')).toBeInTheDocument();
+
+ const publish = within(section).getByRole('button', { name: 'Publish to game' });
+ expect(publish).toBeEnabled();
+ fireEvent.click(publish);
+ expect(onPublishMusic).toHaveBeenCalledWith('binding-1');
+
+ const destination = within(section).getByLabelText('Game destination');
+ expect(destination).toHaveValue('game/assets/music/example-theme.ogg');
+ fireEvent.change(destination, { target: { value: 'game/assets/audio/theme.ogg' } });
+ // A dirty destination gates the publish button — publishing must use the
+ // path the server has, not the one still sitting unsaved in the input.
+ expect(within(section).getByRole('button', { name: 'Publish to game' })).toBeDisabled();
+
+ fireEvent.click(within(section).getByRole('button', { name: 'Save destination' }));
+ expect(onUpdateMusic).toHaveBeenCalledWith('binding-1', { destinationPath: 'game/assets/audio/theme.ogg' });
+ });
+
+ it('escalates an occupied music destination to explicit overwrite consent', () => {
+ renderBindings({ musicOverwriteFor: 'binding-1' });
+ const section = musicSection();
+
+ expect(within(section).getByText(
+ 'game/assets/music/example-theme.ogg contains bytes PortOS did not publish. Overwrite it?',
+ )).toBeInTheDocument();
+ fireEvent.click(within(section).getByRole('button', { name: 'Overwrite' }));
+ expect(onPublishMusic).toHaveBeenCalledWith('binding-1', true);
+
+ fireEvent.click(within(section).getByRole('button', { name: 'Cancel' }));
+ expect(onDismissMusicOverwrite).toHaveBeenCalled();
+ });
+
+ it('keeps publish disabled for a binding with no destination yet', () => {
+ renderBindings({
+ game: {
+ spriteBindings: [],
+ musicBindings: [{ id: 'binding-legacy', trackId: 'theme/one', destinationPath: null, publication: null }],
+ artworkBindings: [],
+ },
+ integrity: null,
+ });
+ const section = musicSection();
+ expect(within(section).getByLabelText('Game destination')).toHaveValue('');
+ expect(within(section).getByRole('button', { name: 'Publish to game' })).toBeDisabled();
+ expect(within(section).queryByText('Publish pending')).not.toBeInTheDocument();
+ });
});
diff --git a/client/src/pages/Game.jsx b/client/src/pages/Game.jsx
index 2c2ce75658..36484bdf93 100644
--- a/client/src/pages/Game.jsx
+++ b/client/src/pages/Game.jsx
@@ -23,12 +23,14 @@ import {
listTracks,
launchNativeApp,
publishGameArtwork,
+ publishGameMusic,
requestGameFeedback,
startApp,
unbindGameArtwork,
unbindGameMusic,
unbindGameSprite,
updateGameArtwork,
+ updateGameMusic,
} from '../services/api.js';
import { timeAgo } from '../utils/formatters.js';
@@ -68,6 +70,9 @@ export default function Game() {
const [busy, setBusy] = useState('');
const [name, setName] = useState('');
const [appId, setAppId] = useState('');
+ // Music binding id whose publish hit a 409 PUBLISH_DEST_OCCUPIED — the row
+ // shows an inline overwrite consent instead of a dead-end error toast.
+ const [musicOverwrite, setMusicOverwrite] = useState(null);
const load = useCallback(async () => {
setLoading(true);
@@ -217,6 +222,35 @@ export default function Game() {
return true;
};
+ const publishMusic = async (bindingId, acknowledgeOverwrite = false) => {
+ setBusy(`music-publish-${bindingId}`);
+ let occupied = false;
+ const result = await publishGameMusic(
+ game.id,
+ bindingId,
+ acknowledgeOverwrite ? { acknowledgeOverwrite: true } : {},
+ silent,
+ ).catch((error) => {
+ occupied = error?.code === 'PUBLISH_DEST_OCCUPIED';
+ return null;
+ });
+ setBusy('');
+ if (!result?.game) {
+ if (occupied) {
+ setMusicOverwrite(bindingId);
+ return false;
+ }
+ toast.error('Music publish failed');
+ return false;
+ }
+ setMusicOverwrite(null);
+ replaceGame(result.game);
+ setCompileError('');
+ await refreshIntegrity();
+ toast.success(result.publication?.wrote ? 'Music published to the game' : 'Music is already current');
+ return true;
+ };
+
if (loading) {
return <div className="py-12 text-center text-sm text-gray-400">Loading Game studio…</div>;
}
@@ -309,7 +343,7 @@ export default function Game() {
// Binding actions are namespaced so a new non-binding action (compile,
// feedback, launch, …) doesn't have to be remembered in an exclusion list.
- const bindingBusy = /^(un)?bind-|^artwork-/.test(busy);
+ const bindingBusy = /^(un)?bind-|^artwork-|^music-/.test(busy);
return (
<div className="flex h-full min-h-0 flex-col">
<header className="flex shrink-0 flex-col justify-between gap-2 border-b border-port-border px-4 py-3 sm:flex-row sm:items-center">
@@ -379,6 +413,14 @@ export default function Game() {
onBindSprite={(spriteId) => mutate('bind-sprite', () => bindGameSprite(game.id, spriteId, silent), 'Sprite bound')}
onUnbindSprite={(spriteId) => mutate('unbind-sprite', () => unbindGameSprite(game.id, spriteId, silent), 'Sprite unbound')}
onBindMusic={(trackId) => mutate('bind-music', () => bindGameMusic(game.id, trackId, silent), 'Music bound')}
+ onUpdateMusic={(bindingId, patch) => mutate(
+ `music-update-${bindingId}`,
+ () => updateGameMusic(game.id, bindingId, patch, silent),
+ 'Music destination saved',
+ )}
+ onPublishMusic={publishMusic}
+ musicOverwriteFor={musicOverwrite}
+ onDismissMusicOverwrite={() => setMusicOverwrite(null)}
onUnbindMusic={(bindingId) => mutate('unbind-music', () => unbindGameMusic(game.id, bindingId, silent), 'Music unbound')}
onBindArtwork={(binding) => mutate(
'bind-artwork',
diff --git a/client/src/services/apiGames.js b/client/src/services/apiGames.js
index 146ada19c7..685c0d0ed2 100644
--- a/client/src/services/apiGames.js
+++ b/client/src/services/apiGames.js
@@ -37,11 +37,23 @@ export const bindGameMusic = (id, trackId, options = {}) => request(
{ method: 'POST', body: JSON.stringify({ trackId }), ...options },
);
+export const updateGameMusic = (id, bindingId, patch, options = {}) => request(
+ `/games/${encodeURIComponent(id)}/music/${encodeURIComponent(bindingId)}`,
+ { method: 'PATCH', body: JSON.stringify(patch), ...options },
+);
+
export const unbindGameMusic = (id, bindingId, options = {}) => request(
`/games/${encodeURIComponent(id)}/music/${encodeURIComponent(bindingId)}`,
{ method: 'DELETE', ...options },
);
+// Pass { acknowledgeOverwrite: true } after a 409 PUBLISH_DEST_OCCUPIED to
+// consent to replacing destination bytes PortOS never published.
+export const publishGameMusic = (id, bindingId, body = {}, options = {}) => request(
+ `/games/${encodeURIComponent(id)}/music/${encodeURIComponent(bindingId)}/publish`,
+ { method: 'POST', body: JSON.stringify(body), ...options },
+);
+
export const bindGameArtwork = (id, binding, options = {}) => request(
`/games/${encodeURIComponent(id)}/artwork`,
{ method: 'POST', body: JSON.stringify(binding), ...options },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 4af1c5324d..e1f8c3e8ca 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -339,10 +339,35 @@ export const gameSpriteBindingSchema = z.object({
spriteId: gameAssetIdSchema,
}).strict();
+// Repo-relative publish destination inside the managed app repository. The
+// extension gate is per-lane (PNG artwork vs library audio); the traversal
+// refinements are shared so the two lanes can't drift.
+const gameDestinationSchema = (extensionPattern, extensionMessage) => z.string()
+ .trim()
+ .min(1)
+ .max(500)
+ .regex(extensionPattern, extensionMessage)
+ .refine((value) => !value.startsWith('/') && !value.includes('\\'), 'must be a repo-relative path')
+ .refine((value) => !value.split('/').includes('..'), 'must not traverse outside the app repository');
+const gameMusicDestinationSchema = gameDestinationSchema(
+ /\.(?:mp3|wav|m4a|ogg|flac)$/i,
+ 'must end in a supported audio extension',
+);
+const gamePublishOptionsSchema = z.object({
+ acknowledgeOverwrite: z.boolean().optional(),
+}).strict();
+
export const gameMusicBindingSchema = z.object({
trackId: gameAssetIdSchema,
+ destinationPath: gameMusicDestinationSchema.optional(),
}).strict();
+export const gameMusicBindingUpdateSchema = z.object({
+ destinationPath: gameMusicDestinationSchema,
+}).strict();
+
+export const gameMusicPublishSchema = gamePublishOptionsSchema;
+
export const GAME_ARTWORK_ROLES = [
'title-key-art',
'game-logo',
@@ -357,13 +382,7 @@ const gameArtworkFilenameSchema = z.string()
.trim()
.regex(/^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i, 'must be a gallery PNG filename')
.max(255);
-const gameArtworkDestinationSchema = z.string()
- .trim()
- .min(1)
- .max(500)
- .regex(/\.png$/i, 'must end in .png')
- .refine((value) => !value.startsWith('/') && !value.includes('\\'), 'must be a repo-relative path')
- .refine((value) => !value.split('/').includes('..'), 'must not traverse outside the app repository');
+const gameArtworkDestinationSchema = gameDestinationSchema(/\.png$/i, 'must end in .png');
export const gameArtworkBindingSchema = z.object({
imageFilename: gameArtworkFilenameSchema,
@@ -380,9 +399,7 @@ export const gameArtworkBindingUpdateSchema = z.object({
message: 'at least one field is required',
});
-export const gameArtworkPublishSchema = z.object({
- acknowledgeOverwrite: z.boolean().optional(),
-}).strict();
+export const gameArtworkPublishSchema = gamePublishOptionsSchema;
export const gameFeedbackSchema = z.object({
providerId: z.string().trim().min(1).max(128),
diff --git a/server/routes/games.js b/server/routes/games.js
index f0a3c7f730..55c3948404 100644
--- a/server/routes/games.js
+++ b/server/routes/games.js
@@ -11,6 +11,8 @@ import {
gameArtworkPublishSchema,
gameFeedbackSchema,
gameMusicBindingSchema,
+ gameMusicBindingUpdateSchema,
+ gameMusicPublishSchema,
gameSpriteBindingSchema,
gameUpdateSchema,
isPaginationRequested,
@@ -28,12 +30,14 @@ import {
getGameIntegrity,
listGames,
publishGameArtwork,
+ publishGameMusic,
requestGameFeedback,
unbindMusic,
unbindArtwork,
unbindSprite,
updateArtwork,
updateGame,
+ updateMusic,
} from '../services/games/index.js';
const router = Router();
@@ -89,10 +93,20 @@ router.post('/:id/music', asyncHandler(async (req, res) => {
res.status(201).json(await bindMusic(req.params.id, binding));
}));
+router.patch('/:id/music/:bindingId', asyncHandler(async (req, res) => {
+ const patch = validateRequest(gameMusicBindingUpdateSchema, req.body);
+ res.json(await updateMusic(req.params.id, req.params.bindingId, patch));
+}));
+
router.delete('/:id/music/:bindingId', asyncHandler(async (req, res) => {
res.json(await unbindMusic(req.params.id, req.params.bindingId));
}));
+router.post('/:id/music/:bindingId/publish', asyncHandler(async (req, res) => {
+ const options = validateRequest(gameMusicPublishSchema, req.body || {});
+ res.json(await publishGameMusic(req.params.id, req.params.bindingId, options));
+}));
+
router.post('/:id/artwork', asyncHandler(async (req, res) => {
const binding = validateRequest(gameArtworkBindingSchema, req.body);
res.status(201).json(await bindArtwork(req.params.id, binding));
diff --git a/server/routes/games.test.js b/server/routes/games.test.js
index f132c956cd..3ca0d286df 100644
--- a/server/routes/games.test.js
+++ b/server/routes/games.test.js
@@ -14,12 +14,14 @@ vi.mock('../services/games/index.js', () => ({
getGameIntegrity: vi.fn(),
listGames: vi.fn(async () => []),
publishGameArtwork: vi.fn(),
+ publishGameMusic: vi.fn(),
requestGameFeedback: vi.fn(),
unbindMusic: vi.fn(),
unbindArtwork: vi.fn(),
unbindSprite: vi.fn(),
updateArtwork: vi.fn(),
updateGame: vi.fn(),
+ updateMusic: vi.fn(),
}));
import * as games from '../services/games/index.js';
@@ -154,6 +156,43 @@ describe('Game routes', () => {
expect(games.publishGameArtwork).toHaveBeenCalledWith('game-1', 'artwork-1', {});
});
+ it('retargets and publishes a bound music track', async () => {
+ const updated = { id: 'game-1', musicBindings: [{ id: 'music-1' }] };
+ games.updateMusic.mockResolvedValueOnce(updated);
+ const patchResponse = await request(makeApp())
+ .patch('/api/games/game-1/music/music-1')
+ .send({ destinationPath: 'game/assets/music/example-theme.ogg' });
+ expect(patchResponse.status).toBe(200);
+ expect(games.updateMusic).toHaveBeenCalledWith('game-1', 'music-1', {
+ destinationPath: 'game/assets/music/example-theme.ogg',
+ });
+
+ games.publishGameMusic.mockResolvedValueOnce({
+ game: updated,
+ publication: { bindingId: 'music-1', wrote: true },
+ });
+ const publishResponse = await request(makeApp())
+ .post('/api/games/game-1/music/music-1/publish')
+ .send({ acknowledgeOverwrite: true });
+ expect(publishResponse.status).toBe(200);
+ expect(games.publishGameMusic).toHaveBeenCalledWith('game-1', 'music-1', {
+ acknowledgeOverwrite: true,
+ });
+ });
+
+ it('rejects music destinations that escape the repository or are not audio', async () => {
+ const escape = await request(makeApp())
+ .patch('/api/games/game-1/music/music-1')
+ .send({ destinationPath: '../outside.mp3' });
+ expect(escape.status).toBe(400);
+
+ const wrongExtension = await request(makeApp())
+ .patch('/api/games/game-1/music/music-1')
+ .send({ destinationPath: 'game/assets/music/theme.png' });
+ expect(wrongExtension.status).toBe(400);
+ expect(games.updateMusic).not.toHaveBeenCalled();
+ });
+
it('accepts a game logo as managed interface artwork', async () => {
const binding = {
imageFilename: 'example-game-logo.png',
diff --git a/server/services/games/README.md b/server/services/games/README.md
index e3df6bd2fc..f0c79fcdc5 100644
--- a/server/services/games/README.md
+++ b/server/services/games/README.md
@@ -1,13 +1,15 @@
# Games
-The Game studio binds a managed app to reusable Sprite, Music, and gallery Artwork records, publishes artwork into the app repository, compiles immutable versioned asset manifests, and stores user-triggered AI review history.
+The Game studio binds a managed app to reusable Sprite, Music, and gallery Artwork records, publishes artwork and music into the app repository, compiles immutable versioned asset manifests, and stores user-triggered AI review history.
| File | Purpose |
|---|---|
| `store.js` | PostgreSQL/collectionStore dispatcher plus per-Game write serialization and manifest directory paths. |
| `db.js` | PostgreSQL leaf I/O for `games` JSONB records. |
| `records.js` | Game CRUD, managed-app validation, and sprite/music/artwork bind operations. |
-| `artwork.js` | Provenance-tracked, drift-guarded gallery-artwork publishing into managed app repositories. |
+| `publishCore.js` | Shared per-repo-serialized publish lane: path anchoring, occupied-destination guards, atomic writes, SHA-256 provenance stamps. |
+| `artwork.js` | Gallery-artwork publish lane over `publishCore.js`. |
+| `musicPublish.js` | Music-library audio publish lane over `publishCore.js`. |
| `compile.js` | Deterministic, idempotent asset-manifest compiler with SHA-256 references. |
| `integrity.js` | Bundle preflight, imported-runtime resolution, and current manifest/source hash verification. |
| `feedback.js` | Explicitly user-triggered provider/model/effort feedback and history persistence. |
diff --git a/server/services/games/artwork.js b/server/services/games/artwork.js
index f533816bbf..5213af2df0 100644
--- a/server/services/games/artwork.js
+++ b/server/services/games/artwork.js
@@ -1,136 +1,33 @@
/**
* Publish gallery artwork into a managed game's repository with provenance and
- * occupied/diverged-destination guards.
+ * occupied/diverged-destination guards (shared lane: publishCore.js).
*/
-import { createHash } from 'crypto';
-import { readFile, stat } from 'fs/promises';
-import { join, resolve } from 'path';
+import { join } from 'path';
import { ServerError } from '../../lib/errorHandler.js';
-import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
-import { atomicWrite, isPathInsideDir, PATHS } from '../../lib/fileUtils.js';
-import { getAppById } from '../apps.js';
-import { isDeploying } from '../appDeployer.js';
-import { getGame, mutateGame } from './records.js';
-
-const repoPublishTail = createKeyCachedQueue();
-const sha256Buffer = (buffer) => createHash('sha256').update(buffer).digest('hex');
-
-const anchorRepoPath = (repoRoot, relPath) => {
- const abs = resolve(repoRoot, relPath);
- if (abs === resolve(repoRoot)
- || relPath.startsWith('/')
- || relPath.includes('\\')
- || !isPathInsideDir(repoRoot, abs)) {
- throw new ServerError('Artwork destination must stay inside the managed app repository', {
- status: 400,
- code: 'INVALID_PUBLISH_PATH',
- });
- }
- return abs;
-};
-
-const readIfPresent = (path) => readFile(path).then(
- (buffer) => buffer,
- (error) => {
- if (error?.code === 'ENOENT') return null;
- throw error;
- },
-);
-
-export async function publishGameArtwork(
- gameId,
- bindingId,
- { acknowledgeOverwrite = false } = {},
-) {
- const game = await getGame(gameId);
- if (!game) throw new ServerError('Game not found', { status: 404, code: 'NOT_FOUND' });
- const binding = game.artworkBindings.find((entry) => entry.id === bindingId);
- if (!binding) throw new ServerError('Artwork binding not found', { status: 404, code: 'NOT_FOUND' });
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i.test(binding.imageFilename)) {
- throw new ServerError('The bound gallery artwork path is invalid', {
- status: 409,
- code: 'ARTWORK_PATH_INVALID',
- });
- }
-
- const app = await getAppById(game.appId);
- const repoStat = app?.repoPath ? await stat(app.repoPath).catch(() => null) : null;
- if (!app || !repoStat?.isDirectory()) {
- throw new ServerError('The bound managed app has no accessible repository', {
- status: 409,
- code: 'APP_REPO_MISSING',
- });
- }
-
- const sourcePath = join(PATHS.images, binding.imageFilename);
- const source = await readIfPresent(sourcePath);
- if (!source) {
- throw new ServerError('The bound gallery artwork is missing', {
- status: 409,
- code: 'ARTWORK_MISSING',
- });
- }
- const sourceSha256 = sha256Buffer(source);
- const repoRoot = resolve(app.repoPath);
-
- return repoPublishTail(repoRoot, async () => {
- if (isDeploying(app.repoPath)) {
- throw new ServerError(`App ${app.name || app.id} is deploying — retry when it finishes`, {
- status: 409,
- code: 'APP_DEPLOY_IN_PROGRESS',
- });
- }
- const destination = anchorRepoPath(repoRoot, binding.destinationPath);
- const existing = await readIfPresent(destination);
- const existingSha256 = existing ? sha256Buffer(existing) : null;
- const previous = binding.publication?.destinationPath === binding.destinationPath
- ? binding.publication
- : null;
- const occupiedByOtherBytes = existingSha256
- && existingSha256 !== sourceSha256
- && existingSha256 !== previous?.destinationSha256;
- if (occupiedByOtherBytes && !acknowledgeOverwrite) {
- throw new ServerError(
- `${binding.destinationPath} contains bytes PortOS did not publish — confirm the overwrite to replace it.`,
- { status: 409, code: 'PUBLISH_DEST_OCCUPIED' },
- );
- }
-
- const wrote = existingSha256 !== sourceSha256;
- if (wrote) await atomicWrite(destination, source);
- const publishedAt = new Date().toISOString();
- const updated = await mutateGame(gameId, (current) => {
- if (!current.artworkBindings.some((entry) => entry.id === bindingId)) {
- throw new ServerError('Artwork binding not found', { status: 404, code: 'NOT_FOUND' });
+import { PATHS } from '../../lib/fileUtils.js';
+import { publishGameBinding, readIfPresent } from './publishCore.js';
+
+export function publishGameArtwork(gameId, bindingId, { acknowledgeOverwrite = false } = {}) {
+ return publishGameBinding(gameId, bindingId, {
+ acknowledgeOverwrite,
+ bindingsKey: 'artworkBindings',
+ bindingNotFound: 'Artwork binding not found',
+ async resolveSourceBytes(binding) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i.test(binding.imageFilename)) {
+ throw new ServerError('The bound gallery artwork path is invalid', {
+ status: 409,
+ code: 'ARTWORK_PATH_INVALID',
+ });
+ }
+ const source = await readIfPresent(join(PATHS.images, binding.imageFilename));
+ if (!source) {
+ throw new ServerError('The bound gallery artwork is missing', {
+ status: 409,
+ code: 'ARTWORK_MISSING',
+ });
}
- return {
- ...current,
- artworkBindings: current.artworkBindings.map((entry) => (
- entry.id === bindingId
- ? {
- ...entry,
- publication: {
- sourceSha256,
- destinationSha256: sourceSha256,
- destinationPath: entry.destinationPath,
- publishedAt,
- },
- }
- : entry
- )),
- };
- });
- return {
- game: updated,
- publication: {
- bindingId,
- sourceSha256,
- destinationSha256: sourceSha256,
- destinationPath: binding.destinationPath,
- publishedAt,
- wrote,
- },
- };
+ return source;
+ },
});
}
diff --git a/server/services/games/index.js b/server/services/games/index.js
index 160b2bcf28..241b6a1b99 100644
--- a/server/services/games/index.js
+++ b/server/services/games/index.js
@@ -14,8 +14,10 @@ export {
unbindSprite,
updateArtwork,
updateGame,
+ updateMusic,
} from './records.js';
export { publishGameArtwork } from './artwork.js';
+export { publishGameMusic } from './musicPublish.js';
export { compileGameAssets } from './compile.js';
export {
BUNDLE_SCHEMA_VERSION,
diff --git a/server/services/games/integrity.js b/server/services/games/integrity.js
index f62db59acd..a0e7179bad 100644
--- a/server/services/games/integrity.js
+++ b/server/services/games/integrity.js
@@ -253,6 +253,14 @@ async function resolveMusic(binding) {
);
}
+ // Publish state mirrors the artwork lane — but only for bindings that HAVE a
+ // destination. The conditional spread is load-bearing: destination-less
+ // bindings (pre-publish records, older peers) keep the exact item shape they
+ // hashed before, so upgrading PortOS alone can't flip an existing bundle to
+ // "stale" for music that never opted into publishing.
+ const publicationCurrent = Boolean(binding.destinationPath)
+ && binding.publication?.sourceSha256 === audioSha256
+ && binding.publication?.destinationPath === binding.destinationPath;
return {
item: {
bindingId: binding.id,
@@ -260,12 +268,20 @@ async function resolveMusic(binding) {
title: track.title,
audioPath: `music/${track.audioFilename}`,
audioSha256,
+ ...(binding.destinationPath ? {
+ destinationPath: binding.destinationPath,
+ publishedSha256: publicationCurrent ? audioSha256 : null,
+ } : {}),
},
summary: {
...identity,
status: 'ready',
fileCount: 1,
- message: 'Audio ready',
+ ...(binding.destinationPath ? {
+ destinationPath: binding.destinationPath,
+ publicationStatus: publicationCurrent ? 'current' : 'pending',
+ message: publicationCurrent ? 'Audio verified · published' : 'Audio verified · publish pending',
+ } : { message: 'Audio ready' }),
},
};
}
diff --git a/server/services/games/integrity.test.js b/server/services/games/integrity.test.js
index 56a1d6f1bd..911dab9e92 100644
--- a/server/services/games/integrity.test.js
+++ b/server/services/games/integrity.test.js
@@ -189,6 +189,45 @@ describe('Game bundle integrity', () => {
expect(current.verifiedFileCount).toBe(1);
});
+ it('reports music publish state without disturbing destination-less bindings', async () => {
+ state.game.spriteBindings = [];
+
+ // A binding with no destination (pre-publish record, or an older peer)
+ // keeps the exact manifest-item shape it always hashed — an upgrade alone
+ // must not flip an existing bundle to "stale".
+ const legacy = await resolveGameAssets(state.game);
+ expect(legacy.music[0]).not.toHaveProperty('destinationPath');
+ expect(legacy.music[0]).not.toHaveProperty('publishedSha256');
+ expect(legacy.summaries.music[0]).toMatchObject({ status: 'ready', message: 'Audio ready' });
+ expect(legacy.summaries.music[0].publicationStatus).toBeUndefined();
+
+ state.game.musicBindings = [{
+ id: 'music-1',
+ trackId: 'theme',
+ destinationPath: 'game/assets/music/example-theme.ogg',
+ publication: null,
+ }];
+ const pending = await resolveGameAssets(state.game);
+ expect(pending.music[0]).toMatchObject({
+ destinationPath: 'game/assets/music/example-theme.ogg',
+ publishedSha256: null,
+ });
+ expect(pending.summaries.music[0]).toMatchObject({
+ publicationStatus: 'pending',
+ message: 'Audio verified · publish pending',
+ });
+
+ state.game.musicBindings[0].publication = {
+ sourceSha256: 'music-sha',
+ destinationSha256: 'music-sha',
+ destinationPath: 'game/assets/music/example-theme.ogg',
+ publishedAt: '2026-01-01T00:00:00.000Z',
+ };
+ const current = await resolveGameAssets(state.game);
+ expect(current.music[0].publishedSha256).toBe('music-sha');
+ expect(current.summaries.music[0].publicationStatus).toBe('current');
+ });
+
it('blocks missing gallery artwork without failing the whole preflight', async () => {
state.game.spriteBindings = [];
state.game.musicBindings = [];
diff --git a/server/services/games/musicPublish.js b/server/services/games/musicPublish.js
new file mode 100644
index 0000000000..6beb3541ac
--- /dev/null
+++ b/server/services/games/musicPublish.js
@@ -0,0 +1,56 @@
+/**
+ * Publish a bound music track's library audio into a managed game's repository
+ * with provenance and occupied/diverged-destination guards (shared lane:
+ * publishCore.js). The audio file resolves through the same music library the
+ * integrity preflight verifies, so a track the preflight blocks cannot publish.
+ */
+
+import { join } from 'path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS } from '../../lib/fileUtils.js';
+import { isSafeMusicFilename } from '../pipeline/musicLibrary.js';
+import { getTrack } from '../tracks/index.js';
+import { publishGameBinding, readIfPresent } from './publishCore.js';
+
+export function publishGameMusic(gameId, bindingId, { acknowledgeOverwrite = false } = {}) {
+ return publishGameBinding(gameId, bindingId, {
+ acknowledgeOverwrite,
+ bindingsKey: 'musicBindings',
+ bindingNotFound: 'Music binding not found',
+ async resolveSourceBytes(binding) {
+ if (!binding.destinationPath) {
+ throw new ServerError('Set a game destination for this track before publishing', {
+ status: 409,
+ code: 'MUSIC_DESTINATION_REQUIRED',
+ });
+ }
+ const track = await getTrack(binding.trackId);
+ if (!track) {
+ throw new ServerError(`Bound music track no longer exists: ${binding.trackId}`, {
+ status: 409,
+ code: 'TRACK_MISSING',
+ });
+ }
+ if (!track.audioFilename) {
+ throw new ServerError(`Render or upload audio for "${track.title}" before publishing`, {
+ status: 409,
+ code: 'TRACK_AUDIO_REQUIRED',
+ });
+ }
+ if (!isSafeMusicFilename(track.audioFilename)) {
+ throw new ServerError(`The rendered audio path for "${track.title}" is invalid`, {
+ status: 409,
+ code: 'TRACK_AUDIO_INTEGRITY_FAILED',
+ });
+ }
+ const source = await readIfPresent(join(PATHS.music, track.audioFilename));
+ if (!source) {
+ throw new ServerError(`The rendered audio for "${track.title}" is missing or unreadable`, {
+ status: 409,
+ code: 'TRACK_AUDIO_MISSING',
+ });
+ }
+ return source;
+ },
+ });
+}
diff --git a/server/services/games/musicPublish.test.js b/server/services/games/musicPublish.test.js
new file mode 100644
index 0000000000..2fe69a229b
--- /dev/null
+++ b/server/services/games/musicPublish.test.js
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({
+ game: null,
+ track: null,
+ source: Buffer.from('theme-audio-v1'),
+ destination: null,
+}));
+
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ if (path === '/library/example-theme.ogg') return state.source;
+ if (path === '/app/game/assets/music/example-theme.ogg' && state.destination) return state.destination;
+ throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' });
+ }),
+ stat: vi.fn(async () => ({ isDirectory: () => true })),
+}));
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { music: '/library' },
+ atomicWrite: vi.fn(async (path, bytes) => {
+ if (path === '/app/game/assets/music/example-theme.ogg') state.destination = Buffer.from(bytes);
+ }),
+ isPathInsideDir: vi.fn((dir, candidate) => candidate.startsWith(`${dir}/`)),
+}));
+
+vi.mock('../apps.js', () => ({
+ getAppById: vi.fn(async () => ({ id: 'app-1', name: 'Example App', repoPath: '/app' })),
+}));
+
+vi.mock('../appDeployer.js', () => ({ isDeploying: vi.fn(() => false) }));
+
+vi.mock('../tracks/index.js', () => ({
+ getTrack: vi.fn(async () => state.track),
+}));
+
+vi.mock('../pipeline/musicLibrary.js', () => ({
+ isSafeMusicFilename: vi.fn((name) => /^[^/\\]+\.(?:mp3|wav|m4a|ogg|flac)$/i.test(String(name || ''))),
+}));
+
+vi.mock('./records.js', () => ({
+ getGame: vi.fn(async () => state.game),
+ mutateGame: vi.fn(async (_id, mutator) => {
+ state.game = await mutator(state.game);
+ return state.game;
+ }),
+}));
+
+import { atomicWrite } from '../../lib/fileUtils.js';
+import { isDeploying } from '../appDeployer.js';
+import { publishGameMusic } from './musicPublish.js';
+
+const gameFixture = () => ({
+ id: 'game-1',
+ appId: 'app-1',
+ musicBindings: [{
+ id: 'music-1',
+ trackId: 'theme',
+ destinationPath: 'game/assets/music/example-theme.ogg',
+ publication: null,
+ }],
+});
+
+describe('publishGameMusic', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ state.game = gameFixture();
+ state.track = { id: 'theme', title: 'Example Theme', audioFilename: 'example-theme.ogg' };
+ state.source = Buffer.from('theme-audio-v1');
+ state.destination = null;
+ });
+
+ it('publishes library audio bytes and records provenance', async () => {
+ const result = await publishGameMusic('game-1', 'music-1');
+ expect(result.publication.wrote).toBe(true);
+ expect(state.destination).toEqual(state.source);
+ expect(state.game.musicBindings[0].publication).toMatchObject({
+ destinationPath: 'game/assets/music/example-theme.ogg',
+ sourceSha256: expect.stringMatching(/^[a-f0-9]{64}$/),
+ });
+ });
+
+ it('is a byte-preserving no-op when the destination is current', async () => {
+ state.destination = Buffer.from(state.source);
+ const result = await publishGameMusic('game-1', 'music-1');
+ expect(result.publication.wrote).toBe(false);
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('refuses to replace unmanaged destination bytes without acknowledgement', async () => {
+ state.destination = Buffer.from('hand-authored-game-audio');
+ await expect(publishGameMusic('game-1', 'music-1')).rejects.toMatchObject({
+ code: 'PUBLISH_DEST_OCCUPIED',
+ status: 409,
+ });
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('overwrites unmanaged destination bytes once acknowledged', async () => {
+ state.destination = Buffer.from('hand-authored-game-audio');
+ const result = await publishGameMusic('game-1', 'music-1', { acknowledgeOverwrite: true });
+ expect(result.publication.wrote).toBe(true);
+ expect(state.destination).toEqual(state.source);
+ });
+
+ it('requires a destination before publishing', async () => {
+ state.game.musicBindings[0].destinationPath = null;
+ await expect(publishGameMusic('game-1', 'music-1')).rejects.toMatchObject({
+ code: 'MUSIC_DESTINATION_REQUIRED',
+ status: 409,
+ });
+ });
+
+ it('refuses a track that has no rendered audio yet', async () => {
+ state.track = { id: 'theme', title: 'Example Theme' };
+ await expect(publishGameMusic('game-1', 'music-1')).rejects.toMatchObject({
+ code: 'TRACK_AUDIO_REQUIRED',
+ status: 409,
+ });
+ });
+
+ it('refuses to write while the bound app is deploying', async () => {
+ isDeploying.mockReturnValueOnce(true);
+ await expect(publishGameMusic('game-1', 'music-1')).rejects.toMatchObject({
+ code: 'APP_DEPLOY_IN_PROGRESS',
+ status: 409,
+ });
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/games/publishCore.js b/server/services/games/publishCore.js
new file mode 100644
index 0000000000..0fc11782d2
--- /dev/null
+++ b/server/services/games/publishCore.js
@@ -0,0 +1,131 @@
+/**
+ * Shared managed-repo publish lane for game asset bindings.
+ *
+ * Every lane (artwork, music) resolves its own source bytes; this core owns
+ * everything the lanes must not drift on: the repo lookup, the path anchor,
+ * the occupied/diverged-destination guard behind an explicit overwrite
+ * acknowledgement, the mid-deploy refusal, the atomic write, and the SHA-256
+ * provenance stamp on the published binding. One queue serializes ALL game
+ * publishes per repository, so an artwork and a music publish into the same
+ * repo run one-after-another rather than racing.
+ */
+
+import { createHash } from 'crypto';
+import { readFile, stat } from 'fs/promises';
+import { resolve } from 'path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
+import { atomicWrite, isPathInsideDir } from '../../lib/fileUtils.js';
+import { getAppById } from '../apps.js';
+import { isDeploying } from '../appDeployer.js';
+import { getGame, mutateGame } from './records.js';
+
+const repoPublishTail = createKeyCachedQueue();
+const sha256Buffer = (buffer) => createHash('sha256').update(buffer).digest('hex');
+
+const anchorRepoPath = (repoRoot, relPath) => {
+ const abs = resolve(repoRoot, relPath);
+ if (abs === resolve(repoRoot)
+ || relPath.startsWith('/')
+ || relPath.includes('\\')
+ || !isPathInsideDir(repoRoot, abs)) {
+ throw new ServerError('Publish destination must stay inside the managed app repository', {
+ status: 400,
+ code: 'INVALID_PUBLISH_PATH',
+ });
+ }
+ return abs;
+};
+
+export const readIfPresent = (path) => readFile(path).then(
+ (buffer) => buffer,
+ (error) => {
+ if (error?.code === 'ENOENT') return null;
+ throw error;
+ },
+);
+
+export async function publishGameBinding(gameId, bindingId, {
+ acknowledgeOverwrite = false,
+ bindingsKey,
+ bindingNotFound,
+ resolveSourceBytes,
+}) {
+ const game = await getGame(gameId);
+ if (!game) throw new ServerError('Game not found', { status: 404, code: 'NOT_FOUND' });
+ const binding = (game[bindingsKey] || []).find((entry) => entry.id === bindingId);
+ if (!binding) throw new ServerError(bindingNotFound, { status: 404, code: 'NOT_FOUND' });
+
+ const source = await resolveSourceBytes(binding);
+ const sourceSha256 = sha256Buffer(source);
+
+ const app = await getAppById(game.appId);
+ const repoStat = app?.repoPath ? await stat(app.repoPath).catch(() => null) : null;
+ if (!app || !repoStat?.isDirectory()) {
+ throw new ServerError('The bound managed app has no accessible repository', {
+ status: 409,
+ code: 'APP_REPO_MISSING',
+ });
+ }
+ const repoRoot = resolve(app.repoPath);
+
+ return repoPublishTail(repoRoot, async () => {
+ if (isDeploying(app.repoPath)) {
+ throw new ServerError(`App ${app.name || app.id} is deploying — retry when it finishes`, {
+ status: 409,
+ code: 'APP_DEPLOY_IN_PROGRESS',
+ });
+ }
+ const destination = anchorRepoPath(repoRoot, binding.destinationPath);
+ const existing = await readIfPresent(destination);
+ const existingSha256 = existing ? sha256Buffer(existing) : null;
+ const previous = binding.publication?.destinationPath === binding.destinationPath
+ ? binding.publication
+ : null;
+ const occupiedByOtherBytes = existingSha256
+ && existingSha256 !== sourceSha256
+ && existingSha256 !== previous?.destinationSha256;
+ if (occupiedByOtherBytes && !acknowledgeOverwrite) {
+ throw new ServerError(
+ `${binding.destinationPath} contains bytes PortOS did not publish — confirm the overwrite to replace it.`,
+ { status: 409, code: 'PUBLISH_DEST_OCCUPIED' },
+ );
+ }
+
+ const wrote = existingSha256 !== sourceSha256;
+ if (wrote) await atomicWrite(destination, source);
+ const publishedAt = new Date().toISOString();
+ const updated = await mutateGame(gameId, (current) => {
+ if (!(current[bindingsKey] || []).some((entry) => entry.id === bindingId)) {
+ throw new ServerError(bindingNotFound, { status: 404, code: 'NOT_FOUND' });
+ }
+ return {
+ ...current,
+ [bindingsKey]: current[bindingsKey].map((entry) => (
+ entry.id === bindingId
+ ? {
+ ...entry,
+ publication: {
+ sourceSha256,
+ destinationSha256: sourceSha256,
+ destinationPath: entry.destinationPath,
+ publishedAt,
+ },
+ }
+ : entry
+ )),
+ };
+ });
+ return {
+ game: updated,
+ publication: {
+ bindingId,
+ sourceSha256,
+ destinationSha256: sourceSha256,
+ destinationPath: binding.destinationPath,
+ publishedAt,
+ wrote,
+ },
+ };
+ });
+}
diff --git a/server/services/games/records.js b/server/services/games/records.js
index 35d4a86282..234c4871c2 100644
--- a/server/services/games/records.js
+++ b/server/services/games/records.js
@@ -7,6 +7,7 @@ import { join } from 'path';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, pathExists } from '../../lib/fileUtils.js';
import { getAppById } from '../apps.js';
+import { isSafeMusicFilename } from '../pipeline/musicLibrary.js';
import { getRecord as getSpriteRecord } from '../sprites/records.js';
import { getTrack } from '../tracks/index.js';
import {
@@ -25,7 +26,7 @@ const objectArray = (value) =>
const boundedHistory = (value) => objectArray(value).slice(-HISTORY_LIMIT);
const isSafeArtworkFilename = (value) =>
typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i.test(value);
-const sanitizeArtworkPublication = (value) => {
+const sanitizePublication = (value) => {
if (!value || typeof value !== 'object') return null;
if (typeof value.sourceSha256 !== 'string'
|| typeof value.destinationSha256 !== 'string'
@@ -52,7 +53,23 @@ const sanitizeArtworkBinding = (binding) => {
role: binding.role,
destinationPath: binding.destinationPath,
boundAt: typeof binding.boundAt === 'string' ? binding.boundAt : new Date().toISOString(),
- publication: sanitizeArtworkPublication(binding.publication),
+ publication: sanitizePublication(binding.publication),
+ };
+};
+const sanitizeMusicBinding = (binding) => {
+ if (!binding || typeof binding !== 'object') return null;
+ if (typeof binding.id !== 'string' || typeof binding.trackId !== 'string') return null;
+ return {
+ id: binding.id,
+ trackId: binding.trackId,
+ // Optional: bindings created before the music publish lane (and bindings
+ // synced from older peers) carry no destination — they stay bindable and
+ // compilable, and gain a destination via PATCH before publishing.
+ destinationPath: typeof binding.destinationPath === 'string' && binding.destinationPath
+ ? binding.destinationPath
+ : null,
+ boundAt: typeof binding.boundAt === 'string' ? binding.boundAt : new Date().toISOString(),
+ publication: sanitizePublication(binding.publication),
};
};
@@ -67,8 +84,7 @@ export function sanitizeGame(raw) {
appId: raw.appId,
name,
spriteBindings: objectArray(raw.spriteBindings).filter((binding) => typeof binding.spriteId === 'string'),
- musicBindings: objectArray(raw.musicBindings).filter((binding) =>
- typeof binding.id === 'string' && typeof binding.trackId === 'string'),
+ musicBindings: objectArray(raw.musicBindings).map(sanitizeMusicBinding).filter(Boolean),
artworkBindings: objectArray(raw.artworkBindings).map(sanitizeArtworkBinding).filter(Boolean),
compiledManifest: raw.compiledManifest && typeof raw.compiledManifest === 'object'
? raw.compiledManifest
@@ -191,9 +207,15 @@ export async function unbindSprite(id, spriteId) {
});
}
-export async function bindMusic(id, { trackId }) {
+export async function bindMusic(id, { trackId, destinationPath }) {
const track = await getTrack(trackId);
if (!track) throw new ServerError('Music track not found', { status: 400, code: 'INVALID_TRACK' });
+ // Default the publish destination from the rendered audio when it exists and
+ // carries a safe library filename; a track bound before its audio renders
+ // gets a destination via PATCH (mirroring the artwork lane's editable path).
+ const defaultDestination = isSafeMusicFilename(track.audioFilename)
+ ? `game/assets/music/${track.audioFilename}`
+ : null;
return mutateGame(id, (current) => {
if (current.musicBindings.some((binding) => binding.trackId === trackId)) {
throw new ServerError('Music track is already bound to this game', { status: 409, code: 'ALREADY_BOUND' });
@@ -203,12 +225,28 @@ export async function bindMusic(id, { trackId }) {
musicBindings: [...current.musicBindings, {
id: `music-${randomUUID()}`,
trackId,
+ destinationPath: destinationPath || defaultDestination,
boundAt: new Date().toISOString(),
+ publication: null,
}],
};
});
}
+export async function updateMusic(id, bindingId, patch) {
+ return mutateGame(id, (current) => {
+ if (!current.musicBindings.some((binding) => binding.id === bindingId)) {
+ throw new ServerError('Music binding not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ return {
+ ...current,
+ musicBindings: current.musicBindings.map((binding) => (
+ binding.id === bindingId ? { ...binding, ...patch } : binding
+ )),
+ };
+ });
+}
+
export async function unbindMusic(id, bindingId) {
return mutateGame(id, (current) => {
if (!current.musicBindings.some((binding) => binding.id === bindingId)) {