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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
verify every bound game asset by hash before a bundle can launch
[._.]/ Adam Eivy042811e9c65c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 54a3ee94df..a4cab57b16 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -23,6 +23,7 @@## Game- **[issue-3177] Added a Game studio for assembling managed-app asset bundles.** Create a Game workspace, bind reusable Sprite records and Music tracks, compile an immutable versioned manifest with SHA-256 asset references, and request persisted AI feedback with any configured provider, model, and supported effort. The new `/game/:id` workspace is reachable from Create, Cmd+K, and voice navigation.+- **Game workspaces now stay compact and verify assets before launch.** Bundle, Assets, and Feedback live in separate deep-linkable tabs; large sprite sets use a dense contained grid; imported prop atlases participate in bundles; and a preflight names every missing, stale, or hash-mismatched asset. A game can be started from its workspace only after the current manifest and all bound asset bytes pass verification.## Quota burndiff --git a/client/src/components/games/GameBindings.jsx b/client/src/components/games/GameBindings.jsxindex f32dbd07e4..100f7ce347 100644--- a/client/src/components/games/GameBindings.jsx+++ b/client/src/components/games/GameBindings.jsx@@ -1,9 +1,46 @@import { useMemo, useState } from 'react';-import { Music2, PersonStanding, Plus, Unlink } from 'lucide-react';+import { AlertTriangle, CheckCircle2, Music2, PersonStanding, Plus, Unlink } from 'lucide-react';+import Pill from '../ui/Pill.jsx';const selectClass = 'w-full min-h-[44px] rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white';const actionClass = 'inline-flex min-h-[44px] items-center justify-center gap-2 rounded-lg bg-port-accent px-3 py-2 text-sm font-medium text-white disabled:opacity-50';+// Anything the preflight didn't mark `ready` — including an asset it hasn't+// reported on yet — reads as needing attention. Sprites and music share the+// mapping so a new status can't render one way in one list and another in the+// other.+const HEALTH_TONES = {+ ready: { Icon: CheckCircle2, className: 'text-emerald-400' },+ blocked: { Icon: AlertTriangle, className: 'text-amber-400' },+};+const healthTone = (health) => HEALTH_TONES[health?.status] || HEALTH_TONES.blocked;++function BindingRow({ label, detail, health, disabled, onUnbind, unbindTitle }) {+ const { Icon, className } = healthTone(health);+ const message = health?.message || detail;+ return (+ <li className="flex min-h-[54px] items-center justify-between gap-2 rounded-lg border border-port-border bg-port-bg/50 px-3 py-1.5">+ <div className="min-w-0">+ <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">{label}</div>+ </div>+ <div className="truncate text-xs text-gray-500" title={message}>{message}</div>+ </div>+ <button+ type="button"+ onClick={onUnbind}+ disabled={disabled}+ className="min-h-[44px] min-w-[44px] rounded-lg p-2 text-gray-400 hover:text-port-error disabled:opacity-50"+ aria-label={`Unbind ${label}`}+ title={unbindTitle}+ >+ <Unlink className="h-4 w-4" aria-hidden="true" />+ </button>+ </li>+ );+}+function BindingSection({title,icon: Icon,@@ -13,6 +50,7 @@ function BindingSection({onValueChange,onAdd,addLabel,+ count,disabled,children,}) {@@ -22,6 +60,7 @@ function BindingSection({<div className="mb-3 flex items-center gap-2"><Icon className="h-5 w-5 text-port-accent" aria-hidden="true" /><h2 className="font-semibold text-white">{title}</h2>+ <Pill tone="muted" bordered={false}>{count}</Pill></div><div className="mb-4 flex flex-col gap-2 sm:flex-row"><div className="min-w-0 flex-1">@@ -60,6 +99,7 @@ export default function GameBindings({game,sprites,tracks,+ integrity,busy,onBindSprite,onUnbindSprite,@@ -70,6 +110,12 @@ export default function GameBindings({const [trackId, setTrackId] = useState('');const spriteMap = useMemo(() => new Map(sprites.map((sprite) => [sprite.id, sprite])), [sprites]);const trackMap = useMemo(() => new Map(tracks.map((track) => [track.id, track])), [tracks]);+ const spriteIntegrity = useMemo(() => new Map(+ (integrity?.assets?.sprites || []).map((asset) => [asset.assetId, asset]),+ ), [integrity]);+ const musicIntegrity = useMemo(() => new Map(+ (integrity?.assets?.music || []).map((asset) => [asset.bindingId, asset]),+ ), [integrity]);const boundSpriteIds = new Set(game.spriteBindings.map((binding) => binding.spriteId));const boundTrackIds = new Set(game.musicBindings.map((binding) => binding.trackId));const availableSprites = sprites@@ -99,29 +145,23 @@ export default function GameBindings({onValueChange={setSpriteId}onAdd={addSprite}addLabel="Sprite record"+ count={game.spriteBindings.length}disabled={busy}>{game.spriteBindings.length > 0 ? (- <ul className="space-y-2">+ <ul className="grid max-h-72 gap-2 overflow-y-auto pr-1 sm:grid-cols-2">{game.spriteBindings.map((binding) => {const sprite = spriteMap.get(binding.spriteId);return (- <li key={binding.spriteId} className="flex items-center justify-between gap-3 rounded-lg border border-port-border bg-port-bg/50 px-3 py-2">- <div className="min-w-0">- <div className="truncate text-sm font-medium text-white">{sprite?.name || binding.spriteId}</div>- <div className="text-xs text-gray-500">{sprite ? `${sprite.kind} · ${sprite.status}` : 'Record unavailable'}</div>- </div>- <button- type="button"- onClick={() => onUnbindSprite(binding.spriteId)}- disabled={busy}- className="min-h-[44px] min-w-[44px] rounded-lg p-2 text-gray-400 hover:text-port-error disabled:opacity-50"- aria-label={`Unbind ${sprite?.name || binding.spriteId}`}- title="Unbind sprite"- >- <Unlink className="h-4 w-4" aria-hidden="true" />- </button>- </li>+ <BindingRow+ key={binding.spriteId}+ label={sprite?.name || binding.spriteId}+ detail={sprite ? `${sprite.kind} · ${sprite.status}` : 'Record unavailable'}+ health={spriteIntegrity.get(binding.spriteId)}+ disabled={busy}+ onUnbind={() => onUnbindSprite(binding.spriteId)}+ unbindTitle="Unbind sprite"+ />);})}</ul>@@ -137,29 +177,23 @@ export default function GameBindings({onValueChange={setTrackId}onAdd={addMusic}addLabel="Music track"+ count={game.musicBindings.length}disabled={busy}>{game.musicBindings.length > 0 ? (- <ul className="space-y-2">+ <ul className="max-h-72 space-y-2 overflow-y-auto pr-1">{game.musicBindings.map((binding) => {const track = trackMap.get(binding.trackId);return (- <li key={binding.id} className="flex items-center justify-between gap-3 rounded-lg border border-port-border bg-port-bg/50 px-3 py-2">- <div className="min-w-0">- <div className="truncate text-sm font-medium text-white">{track?.title || binding.trackId}</div>- <div className="text-xs text-gray-500">{track?.audioFilename ? 'Audio ready' : 'Audio render required'}</div>- </div>- <button- type="button"- onClick={() => onUnbindMusic(binding.id)}- disabled={busy}- className="min-h-[44px] min-w-[44px] 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>- </li>+ <BindingRow+ key={binding.id}+ label={track?.title || binding.trackId}+ detail={track?.audioFilename ? 'Audio ready' : 'Audio render required'}+ health={musicIntegrity.get(binding.id)}+ disabled={busy}+ onUnbind={() => onUnbindMusic(binding.id)}+ unbindTitle="Unbind music track"+ />);})}</ul>diff --git a/client/src/components/games/GameCompilePanel.jsx b/client/src/components/games/GameCompilePanel.jsxindex 2e33d97c9f..b67e47db80 100644--- a/client/src/components/games/GameCompilePanel.jsx+++ b/client/src/components/games/GameCompilePanel.jsx@@ -1,8 +1,53 @@-import { Boxes, RefreshCw } from 'lucide-react';+import {+ AlertTriangle,+ Boxes,+ CheckCircle2,+ CircleDashed,+ Play,+ RefreshCw,+ ShieldCheck,+} from 'lucide-react';+import Banner from '../ui/Banner.jsx';import { formatDateShort } from '../../utils/formatters.js';-export default function GameCompilePanel({ game, compiling, onCompile }) {+const statusStyle = {+ current: {+ icon: CheckCircle2,+ label: 'Verified',+ className: 'border-port-success/30 bg-port-success/10 text-port-success',+ },+ stale: {+ icon: RefreshCw,+ label: 'Needs rebuild',+ className: 'border-port-warning/30 bg-port-warning/10 text-port-warning',+ },+ corrupt: {+ icon: AlertTriangle,+ label: 'Integrity failed',+ className: 'border-port-error/30 bg-port-error/10 text-port-error',+ },+ missing: {+ icon: CircleDashed,+ label: 'Not built',+ className: 'border-port-border bg-port-bg/60 text-gray-400',+ },+};++export default function GameCompilePanel({+ game,+ integrity,+ loadingIntegrity,+ compiling,+ launching,+ compileError,+ onCompile,+ onLaunch,+}) {const current = game.compiledManifest;+ const bundleStatus = statusStyle[integrity?.bundle?.status] || statusStyle.missing;+ const StatusIcon = bundleStatus.icon;+ const blocked = integrity && !integrity.readyToCompile;+ const issues = integrity?.issues || [];return (<section className="rounded-xl border border-port-border bg-port-card p-4"><div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-start">@@ -12,34 +57,91 @@ export default function GameCompilePanel({ game, compiling, onCompile }) {<h2 className="font-semibold text-white">Game asset bundle</h2></div><p className="mt-1 text-sm text-gray-400">- Compile immutable sprite-atlas and music references into a deterministic manifest.+ Build a deterministic manifest and verify every bound source file by SHA-256.</p></div>- <button- type="button"- onClick={onCompile}- disabled={compiling}- className="inline-flex min-h-[44px] items-center justify-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white disabled:opacity-50"- >- <RefreshCw className={`h-4 w-4 ${compiling ? 'animate-spin' : ''}`} aria-hidden="true" />- {current ? 'Recompile' : 'Compile bundle'}- </button>+ <div className="flex flex-col gap-2 sm:flex-row">+ <button+ type="button"+ onClick={onCompile}+ disabled={compiling || loadingIntegrity || blocked}+ className="inline-flex min-h-[44px] items-center justify-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white disabled:opacity-50"+ title={blocked ? 'Resolve the asset integrity blockers first' : undefined}+ >+ <RefreshCw className={`h-4 w-4 ${compiling ? 'animate-spin' : ''}`} aria-hidden="true" />+ {compiling ? 'Verifying…' : current ? 'Rebuild & verify' : 'Build & verify'}+ </button>+ <button+ type="button"+ onClick={onLaunch}+ disabled={launching || !integrity?.canLaunch}+ className="inline-flex min-h-[44px] items-center justify-center gap-2 rounded-lg border border-emerald-500/40 bg-emerald-500/10 px-4 py-2 text-sm font-medium text-emerald-300 hover:bg-emerald-500/20 disabled:cursor-not-allowed disabled:opacity-40"+ title={!integrity?.canLaunch ? 'Build a current, verified bundle before starting the game' : undefined}+ >+ <Play className="h-4 w-4" aria-hidden="true" />+ {launching ? 'Starting…' : 'Start game'}+ </button>+ </div></div>+ <div className="mt-4 grid gap-3 sm:grid-cols-3">+ <div className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-sm ${bundleStatus.className}`}>+ <StatusIcon className={`h-4 w-4 shrink-0 ${loadingIntegrity ? 'animate-spin' : ''}`} aria-hidden="true" />+ <div>+ <div className="text-xs opacity-70">Bundle</div>+ <div className="font-medium">{loadingIntegrity ? 'Checking…' : bundleStatus.label}</div>+ </div>+ </div>+ <div className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-sm">+ <div className="text-xs text-gray-500">Sprite readiness</div>+ <div className="font-medium text-white">+ {integrity ? `${integrity.counts.spriteReady} / ${integrity.counts.spriteTotal}` : '—'}+ </div>+ </div>+ <div className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-sm">+ <div className="text-xs text-gray-500">Verified files</div>+ <div className="font-medium text-white">{integrity?.counts?.verifiedFiles ?? '—'}</div>+ </div>+ </div>++ {issues.length > 0 && (+ <Banner+ tone="warning"+ size="md"+ icon={AlertTriangle}+ title={`${issues.length} ${issues.length === 1 ? 'asset needs' : 'assets need'} attention`}+ className="mt-4"+ >+ <ul className="mt-2 grid gap-1 sm:grid-cols-2">+ {issues.map((item) => (+ <li key={`${item.assetType}-${item.assetId}`} className="truncate" title={item.message}>+ <span className="font-medium">{item.name}</span>: {item.message}+ </li>+ ))}+ </ul>+ </Banner>+ )}++ {compileError && (+ <Banner tone="error" size="md" role="alert" className="mt-4">{compileError}</Banner>+ )}+{current ? (<dl className="mt-4 grid gap-3 rounded-lg border border-port-border bg-port-bg/50 p-3 text-sm sm:grid-cols-2 lg:grid-cols-4"><div><dt className="text-xs text-gray-500">Version</dt><dd className="text-white">v{current.version}</dd></div><div><dt className="text-xs text-gray-500">Sprites</dt><dd className="text-white">{current.spriteCount}</dd></div><div><dt className="text-xs text-gray-500">Music</dt><dd className="text-white">{current.musicCount}</dd></div><div><dt className="text-xs text-gray-500">Built</dt><dd className="text-white">{formatDateShort(current.builtAt)}</dd></div>+ <div><dt className="text-xs text-gray-500">Verified files</dt><dd className="text-white">{current.verifiedFileCount ?? '—'}</dd></div><div className="min-w-0 sm:col-span-2 lg:col-span-4"><dt className="text-xs text-gray-500">Manifest</dt><dd className="truncate font-mono text-xs text-gray-300" title={current.manifestPath}>{current.manifestPath}</dd></div></dl>- ) : (- <p className="mt-4 rounded-lg border border-dashed border-port-border p-4 text-sm text-gray-500">- No bundle compiled yet. Bound sprites need a current runtime atlas and bound tracks need audio.+ ) : blocked ? null : (+ <p className="mt-4 flex items-center gap-2 rounded-lg border border-dashed border-port-border p-4 text-sm text-gray-500">+ <ShieldCheck className="h-4 w-4" aria-hidden="true" />+ Ready to build a hash-verified bundle.</p>)}</section>diff --git a/client/src/components/games/GameCompilePanel.test.jsx b/client/src/components/games/GameCompilePanel.test.jsxnew file mode 100644index 0000000000..4a5411531d--- /dev/null+++ b/client/src/components/games/GameCompilePanel.test.jsx@@ -0,0 +1,75 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';+import GameCompilePanel from './GameCompilePanel.jsx';++const game = {+ compiledManifest: null,+};++describe('GameCompilePanel', () => {+ it('surfaces integrity blockers and gates build and launch', () => {+ render(+ <GameCompilePanel+ game={game}+ integrity={{+ readyToCompile: false,+ canLaunch: false,+ bundle: { status: 'missing' },+ issues: [{+ assetType: 'sprite',+ assetId: 'draft-hero',+ name: 'Draft Hero',+ message: 'Runtime atlas required',+ }],+ counts: {+ spriteReady: 2,+ spriteTotal: 3,+ verifiedFiles: 5,+ },+ }}+ onCompile={() => {}}+ onLaunch={() => {}}+ />,+ );++ expect(screen.getByText('2 / 3')).toBeInTheDocument();+ expect(screen.getByText('Draft Hero')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Build & verify' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Start game' })).toBeDisabled();+ });++ it('allows a verified bundle to launch', () => {+ const onLaunch = vi.fn();+ render(+ <GameCompilePanel+ game={{+ compiledManifest: {+ version: 2,+ spriteCount: 1,+ musicCount: 1,+ verifiedFileCount: 3,+ builtAt: '2026-07-28T12:00:00.000Z',+ manifestPath: 'manifests/game-assets-v2.json',+ },+ }}+ integrity={{+ readyToCompile: true,+ canLaunch: true,+ bundle: { status: 'current' },+ issues: [],+ counts: {+ spriteReady: 1,+ spriteTotal: 1,+ verifiedFiles: 3,+ },+ }}+ onCompile={() => {}}+ onLaunch={onLaunch}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Start game' }));+ expect(onLaunch).toHaveBeenCalledOnce();+ expect(screen.getByText('Verified')).toBeInTheDocument();+ });+});diff --git a/client/src/pages/Game.jsx b/client/src/pages/Game.jsxindex 6a7f3e010a..763b304a24 100644--- a/client/src/pages/Game.jsx+++ b/client/src/pages/Game.jsx@@ -1,11 +1,13 @@import { useCallback, useEffect, useMemo, useState } from 'react';-import { ArrowLeft, Gamepad2, Plus } from 'lucide-react';+import { ArrowLeft, Boxes, Gamepad2, Images, MessageSquare, Plus } from 'lucide-react';import { Link, useNavigate, useParams } from 'react-router-dom';import toast from '../components/ui/Toast';import AppContextPicker from '../components/AppContextPicker.jsx';import GameBindings from '../components/games/GameBindings.jsx';import GameCompilePanel from '../components/games/GameCompilePanel.jsx';import GameFeedback from '../components/games/GameFeedback.jsx';+import TabPills from '../components/ui/TabPills.jsx';+import useDrawerTab from '../hooks/useDrawerTab.js';import {bindGameMusic,bindGameSprite,@@ -13,24 +15,42 @@ import {createGame,getApps,getGame,+ getGameIntegrity,listGames,listSpriteRecords,listTracks,+ launchNativeApp,requestGameFeedback,+ startApp,unbindGameMusic,unbindGameSprite,} from '../services/api.js';import { timeAgo } from '../utils/formatters.js';const silent = { silent: true };+const DETAIL_TABS = [+ { id: 'bundle', label: 'Bundle', icon: Boxes },+ {+ id: 'assets',+ label: 'Assets',+ icon: Images,+ count: (game) => game.spriteBindings.length + game.musicBindings.length,+ },+ { id: 'feedback', label: 'Feedback', icon: MessageSquare, count: (game) => game.feedbackHistory.length },+];+const DETAIL_TAB_IDS = DETAIL_TABS.map((tab) => tab.id);export default function Game() {const { id } = useParams();const navigate = useNavigate();+ const [activeTab, setActiveTab] = useDrawerTab('gameTab', 'bundle', DETAIL_TAB_IDS);const [games, setGames] = useState([]);const [apps, setApps] = useState([]);const [sprites, setSprites] = useState([]);const [tracks, setTracks] = useState([]);+ const [integrity, setIntegrity] = useState(null);+ const [integrityLoading, setIntegrityLoading] = useState(false);+ const [compileError, setCompileError] = useState('');const [loading, setLoading] = useState(true);const [busy, setBusy] = useState('');const [name, setName] = useState('');@@ -58,6 +78,20 @@ export default function Game() {useEffect(() => { load(); }, [load]);+ const refreshIntegrity = useCallback(async () => {+ if (!id) {+ setIntegrity(null);+ return;+ }+ setIntegrityLoading(true);+ setIntegrity(await getGameIntegrity(id, silent).catch(() => null));+ setIntegrityLoading(false);+ }, [id]);++ useEffect(() => {+ refreshIntegrity();+ }, [refreshIntegrity]);+const game = useMemo(() => games.find((entry) => entry.id === id) || null, [games, id]);const app = apps.find((entry) => entry.id === game?.appId);const replaceGame = (updated) => setGames((current) =>@@ -82,18 +116,43 @@ export default function Game() {setBusy('');if (!updated) { toast.error('Game update failed'); return false; }replaceGame(updated);+ setCompileError('');+ await refreshIntegrity();if (successMessage) toast.success(successMessage);return true;};const compile = async () => {setBusy('compile');- const result = await compileGameAssets(game.id, silent).catch(() => null);+ setCompileError('');+ let message = '';+ const result = await compileGameAssets(game.id, silent)+ .catch((error) => { message = error?.message || 'Bundle compilation failed'; return null; });const refreshed = result ? await getGame(game.id, silent).catch(() => null) : null;+ await refreshIntegrity();setBusy('');- if (!result || !refreshed) { toast.error('Bundle compilation failed'); return; }+ if (!refreshed) {+ setCompileError(message || 'Bundle compilation failed');+ return;+ }replaceGame(refreshed);- toast.success(result.created ? `Compiled bundle v${result.version}` : `Bundle v${result.version} is already current`);+ toast.success(result.created+ ? `Built and verified bundle v${result.version}`+ : `Bundle v${result.version} is already verified`);+ };++ const launch = async () => {+ if (!app || !integrity?.canLaunch) return;+ setBusy('launch');+ const result = await (app.nativeLaunch+ ? launchNativeApp(app.id, silent)+ : startApp(app.id, silent)).catch(() => null);+ setBusy('');+ if (!result?.success) {+ toast.error('Game launch failed');+ return;+ }+ toast.success(app.nativeLaunch?.label || 'Game started');};const feedback = async (payload) => {@@ -196,35 +255,76 @@ export default function Game() {);}- const bindingBusy = Boolean(busy && busy !== 'compile' && busy !== 'feedback');+ // 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-/.test(busy);return (<div className="mx-auto max-w-6xl space-y-4">- <header>- <Link to="/game" className="mb-2 inline-flex min-h-[44px] items-center gap-2 text-sm text-gray-400 hover:text-white">- <ArrowLeft className="h-4 w-4" aria-hidden="true" />- All Games- </Link>- <div className="flex items-center gap-3">- <Gamepad2 className="h-7 w-7 text-port-accent" aria-hidden="true" />- <div>- <h1 className="text-2xl font-bold text-white">{game.name}</h1>- <p className="text-sm text-gray-400">{app?.name || 'Managed app unavailable'}</p>+ <header className="flex flex-col justify-between gap-2 sm:flex-row sm:items-end">+ <div>+ <Link to="/game" className="mb-2 inline-flex min-h-[44px] items-center gap-2 text-sm text-gray-400 hover:text-white">+ <ArrowLeft className="h-4 w-4" aria-hidden="true" />+ All Games+ </Link>+ <div className="flex items-center gap-3">+ <Gamepad2 className="h-7 w-7 text-port-accent" aria-hidden="true" />+ <div>+ <h1 className="text-2xl font-bold text-white">{game.name}</h1>+ <p className="text-sm text-gray-400">{app?.name || 'Managed app unavailable'}</p>+ </div></div></div>+ <div className="flex items-center gap-2 text-xs text-gray-400">+ <span>{game.spriteBindings.length} sprites</span>+ <span aria-hidden="true">·</span>+ <span>{game.musicBindings.length} {game.musicBindings.length === 1 ? 'music track' : 'music tracks'}</span>+ </div></header>- <GameBindings- game={game}- sprites={sprites}- tracks={tracks}- busy={bindingBusy}- 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')}- onUnbindMusic={(bindingId) => mutate('unbind-music', () => unbindGameMusic(game.id, bindingId, silent), 'Music unbound')}+ <TabPills+ tabs={DETAIL_TABS.map((tab) => ({ ...tab, count: tab.count?.(game) }))}+ activeTab={activeTab}+ onChange={setActiveTab}+ ariaLabel="Game workspace sections"+ controlsIdPrefix="game-panel"+ mobileDropdown+ mobileSelectId="game-section"/>- <GameCompilePanel game={game} compiling={busy === 'compile'} onCompile={compile} />- <GameFeedback history={game.feedbackHistory} submitting={busy === 'feedback'} onSubmit={feedback} />++ {activeTab === 'bundle' && (+ <div id="game-panel-bundle" role="tabpanel" aria-labelledby="tab-bundle">+ <GameCompilePanel+ game={game}+ integrity={integrity}+ loadingIntegrity={integrityLoading}+ compiling={busy === 'compile'}+ launching={busy === 'launch'}+ compileError={compileError}+ onCompile={compile}+ onLaunch={launch}+ />+ </div>+ )}+ {activeTab === 'assets' && (+ <div id="game-panel-assets" role="tabpanel" aria-labelledby="tab-assets">+ <GameBindings+ game={game}+ sprites={sprites}+ tracks={tracks}+ integrity={integrity}+ busy={bindingBusy}+ 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')}+ onUnbindMusic={(bindingId) => mutate('unbind-music', () => unbindGameMusic(game.id, bindingId, silent), 'Music unbound')}+ />+ </div>+ )}+ {activeTab === 'feedback' && (+ <div id="game-panel-feedback" role="tabpanel" aria-labelledby="tab-feedback">+ <GameFeedback history={game.feedbackHistory} submitting={busy === 'feedback'} onSubmit={feedback} />+ </div>+ )}</div>);}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 10bc8b27cc..de5f953c57 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -95,7 +95,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiMediaJobs.js` | Media generation job tracking. || `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). |-| `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation, and AI feedback history. |+| `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation/integrity preflight, and AI feedback history. || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. || `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, and deletion. |diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex a9d6276a14..198c0e1051 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -47,7 +47,8 @@ export const launchNativeApp = (id, options = {}) =>request(`/apps/${id}/native-launch`, { method: 'POST', ...options });export const getNativeLaunchStatus = (id, options = {}) =>request(`/apps/${id}/native-launch/status`, options);-export const startApp = (id) => request(`/apps/${id}/start`, { method: 'POST' });+export const startApp = (id, options = {}) =>+ request(`/apps/${id}/start`, { method: 'POST', ...options });export const stopApp = (id) => request(`/apps/${id}/stop`, { method: 'POST' });export const restartApp = (id) => request(`/apps/${id}/restart`, { method: 'POST' });export const upgradeAppTls = (id, body) => request(`/apps/${id}/upgrade-tls`, {diff --git a/client/src/services/apiGames.js b/client/src/services/apiGames.jsindex 5e3e71cdcb..bc0f441760 100644--- a/client/src/services/apiGames.js+++ b/client/src/services/apiGames.js@@ -2,6 +2,8 @@ import { request } from './apiCore.js';export const listGames = (options = {}) => request('/games', options);export const getGame = (id, options = {}) => request(`/games/${encodeURIComponent(id)}`, options);+export const getGameIntegrity = (id, options = {}) =>+ request(`/games/${encodeURIComponent(id)}/integrity`, options);export const createGame = (body, options = {}) => request('/games', {method: 'POST',diff --git a/client/src/services/apiGames.test.js b/client/src/services/apiGames.test.jsindex 733b9d7f86..bef1039512 100644--- a/client/src/services/apiGames.test.js+++ b/client/src/services/apiGames.test.js@@ -44,4 +44,9 @@ describe('apiGames', () => {await api.compileGameAssets('game-1');expect(request).toHaveBeenCalledWith('/games/game-1/compile', { method: 'POST' });});++ it('loads the integrity preflight silently', async () => {+ await api.getGameIntegrity('game/1', { silent: true });+ expect(request).toHaveBeenCalledWith('/games/game%2F1/integrity', { silent: true });+ });});diff --git a/server/lib/README.md b/server/lib/README.mdindex 4df171bfd3..64d44d2df0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -133,7 +133,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Also the slashdo loaders: `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals (PortOS inlines these into CoS prompts WITHOUT running slashdo's installer), with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Most paths/file work goes through here. |+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Also the slashdo loaders: `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals (PortOS inlines these into CoS prompts WITHOUT running slashdo's installer), with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Most paths/file work goes through here. || `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex ac8ba8bd48..66e37cf81b 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -1746,6 +1746,9 @@ export async function dirSize(path) {return kb * 1024;}+/** SHA-256 a string or Buffer as hex — `sha256File`'s in-memory twin. */+export const sha256Text = (value) => createHash('sha256').update(value).digest('hex');+/*** SHA-256 a file as hex. One-shot read under 512 KB; streams above so multi-GB* videos don't blow heap. Threshold matches `server/services/backup.js`'sdiff --git a/server/routes/games.js b/server/routes/games.jsindex 9add3a171b..7e54cda349 100644--- a/server/routes/games.js+++ b/server/routes/games.js@@ -19,6 +19,7 @@ import {createGame,deleteGame,getGame,+ getGameIntegrity,listGames,requestGameFeedback,unbindMusic,@@ -43,6 +44,12 @@ router.get('/:id', asyncHandler(async (req, res) => {res.json(game);}));+router.get('/:id/integrity', asyncHandler(async (req, res) => {+ const integrity = await getGameIntegrity(req.params.id);+ if (!integrity) throw new ServerError('Game not found', { status: 404, code: 'NOT_FOUND' });+ res.json(integrity);+}));+router.patch('/:id', asyncHandler(async (req, res) => {const patch = validateRequest(gameUpdateSchema, req.body);res.json(await updateGame(req.params.id, patch));diff --git a/server/routes/games.test.js b/server/routes/games.test.jsindex fcc98a8500..d4a6864b55 100644--- a/server/routes/games.test.js+++ b/server/routes/games.test.js@@ -10,6 +10,7 @@ vi.mock('../services/games/index.js', () => ({createGame: vi.fn(),deleteGame: vi.fn(),getGame: vi.fn(),+ getGameIntegrity: vi.fn(),listGames: vi.fn(async () => []),requestGameFeedback: vi.fn(),unbindMusic: vi.fn(),@@ -55,6 +56,17 @@ describe('Game routes', () => {expect(response.body).toEqual({ version: 2, created: true });});+ it('returns bundle integrity preflight details', async () => {+ games.getGameIntegrity.mockResolvedValueOnce({+ readyToCompile: false,+ issues: [{ code: 'SPRITE_ATLAS_REQUIRED' }],+ });+ const response = await request(makeApp()).get('/api/games/game-1/integrity');+ expect(response.status).toBe(200);+ expect(response.body.readyToCompile).toBe(false);+ expect(games.getGameIntegrity).toHaveBeenCalledWith('game-1');+ });+it('passes explicit provider, model, effort, and prompt to feedback', async () => {games.requestGameFeedback.mockResolvedValueOnce({feedback: { id: 'feedback-1', text: 'Add a victory cue.' },diff --git a/server/services/games/README.md b/server/services/games/README.mdindex 833dc2914b..cf8558f2b5 100644--- a/server/services/games/README.md+++ b/server/services/games/README.md@@ -8,5 +8,6 @@ The Game studio binds a managed app to reusable Sprite and Music records, compil| `db.js` | PostgreSQL leaf I/O for `games` JSONB records. || `records.js` | Game CRUD, managed-app validation, and sprite/music bind/unbind operations. || `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. || `index.js` | Public Game service barrel. |diff --git a/server/services/games/compile.js b/server/services/games/compile.jsindex ed4aa914e8..8eb768c7ba 100644--- a/server/services/games/compile.js+++ b/server/services/games/compile.js@@ -6,75 +6,15 @@* without writing a new version.*/-import { createHash } from 'crypto';import { join } from 'path';import { ServerError } from '../../lib/errorHandler.js';-import { atomicWrite, pathExists, PATHS, sha256File } from '../../lib/fileUtils.js';+import { atomicWrite, pathExists, sha256File, sha256Text } from '../../lib/fileUtils.js';import { canonicalStringify } from '../../lib/objects.js';import { getAppById } from '../apps.js';-import { statMusicTrack } from '../pipeline/musicLibrary.js';-import { getAtlasState } from '../sprites/atlas.js';-import { getRecord as getSpriteRecord } from '../sprites/records.js';-import { getTrack } from '../tracks/index.js';import { GAME_HISTORY_LIMIT, sanitizeGame } from './records.js';+import { resolveGameAssets } from './integrity.js';import { gameRecordDir, isValidGameId, queueGameWrite, readRaw, writeRaw } from './store.js';-const sha256Text = (value) => createHash('sha256').update(value).digest('hex');--async function resolveSprite(binding) {- const [record, atlas] = await Promise.all([- getSpriteRecord(binding.spriteId),- getAtlasState(binding.spriteId),- ]);- if (!record) {- throw new ServerError(`Bound sprite no longer exists: ${binding.spriteId}`, {- status: 409,- code: 'SPRITE_MISSING',- });- }- if (!atlas.current?.atlasPath || !atlas.current?.atlasSha256- || !atlas.current?.manifestPath || !atlas.current?.manifestSha256) {- throw new ServerError(`Compile an atlas for "${record.name}" before building the game bundle`, {- status: 409,- code: 'SPRITE_ATLAS_REQUIRED',- });- }- return {- spriteId: record.id,- name: record.name,- kind: record.kind,- atlasVersion: atlas.current.version,- atlasPath: `sprites/${record.id}/${atlas.current.atlasPath}`,- atlasSha256: atlas.current.atlasSha256,- manifestPath: `sprites/${record.id}/${atlas.current.manifestPath}`,- manifestSha256: atlas.current.manifestSha256,- geometry: atlas.current.geometry,- };-}--async function resolveMusic(binding) {- 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 || !(await statMusicTrack(track.audioFilename))) {- throw new ServerError(`Render or upload audio for "${track.title}" before building the game bundle`, {- status: 409,- code: 'TRACK_AUDIO_REQUIRED',- });- }- return {- bindingId: binding.id,- trackId: track.id,- title: track.title,- audioPath: `music/${track.audioFilename}`,- audioSha256: await sha256File(join(PATHS.music, track.audioFilename)),- };-}-const manifestPathFor = (version) => `manifests/game-assets-v${version}.json`;export async function compileGameAssets(id) {@@ -88,16 +28,16 @@ export async function compileGameAssets(id) {const app = await getAppById(game.appId);if (!app) throw new ServerError('The bound managed app no longer exists', { status: 409, code: 'APP_MISSING' });- const [sprites, music] = await Promise.all([- Promise.all([...game.spriteBindings]- .sort((a, b) => a.spriteId.localeCompare(b.spriteId))- .map(resolveSprite)),- Promise.all([...game.musicBindings]- .sort((a, b) => a.trackId.localeCompare(b.trackId) || a.id.localeCompare(b.id))- .map(resolveMusic)),- ]);- const inputs = { schemaVersion: 1, gameId: game.id, appId: game.appId, sprites, music };- const inputSha256 = sha256Text(canonicalStringify(inputs));+ const resolved = await resolveGameAssets(game);+ if (resolved.issues.length > 0) {+ const first = resolved.issues[0];+ throw new ServerError(first.message, {+ status: 409,+ code: first.code,+ context: { issues: resolved.issues },+ });+ }+ const { sprites, music, inputSha256, schemaVersion, verifiedFileCount } = resolved;const current = game.compiledManifest;const currentPath = current?.manifestPath? join(gameRecordDir(id), current.manifestPath)@@ -115,7 +55,7 @@ export async function compileGameAssets(id) {Number.isInteger(entry.version) ? entry.version : 0)) + 1;const builtAt = new Date().toISOString();const manifest = {- schemaVersion: 1,+ schemaVersion,kind: 'portos-game-assets',game: { id: game.id, name: game.name, appId: game.appId },version,@@ -127,7 +67,7 @@ export async function compileGameAssets(id) {const manifestPath = manifestPathFor(version);await atomicWrite(join(gameRecordDir(id), manifestPath), serialized);const pointer = {- schemaVersion: 1,+ schemaVersion,version,builtAt,manifestPath,@@ -135,6 +75,7 @@ export async function compileGameAssets(id) {inputSha256,spriteCount: sprites.length,musicCount: music.length,+ verifiedFileCount,};const next = sanitizeGame({...game,diff --git a/server/services/games/compile.test.js b/server/services/games/compile.test.jsindex abb0803cac..16e98b9cc4 100644--- a/server/services/games/compile.test.js+++ b/server/services/games/compile.test.js@@ -20,9 +20,17 @@ vi.mock('./store.js', () => ({vi.mock('../../lib/fileUtils.js', () => ({PATHS: { music: '/tmp/music' },atomicWrite: vi.fn(async () => { state.manifestExists = true; }),- pathExists: vi.fn(async () => state.manifestExists),- sha256File: vi.fn(async (path) =>- path.includes('/manifests/') ? state.manifestSha256 : 'audio-sha'),+ pathExists: vi.fn(async (path) =>+ path.includes('/manifests/') ? state.manifestExists : true),+ readJSONFile: vi.fn(async () => null),+ sha256Text: vi.fn((value) => `text-sha:${String(value).length}`),+ sha256File: vi.fn(async (path) => {+ if (path.includes('/manifests/')) return state.manifestSha256;+ const spriteId = path.match(/\/sprites\/([^/]+)\//)?.[1];+ if (path.endsWith('.png')) return `atlas-${spriteId}`;+ if (path.endsWith('.json')) return `manifest-${spriteId}`;+ return 'audio-sha';+ }),}));vi.mock('../apps.js', () => ({@@ -47,6 +55,15 @@ vi.mock('../sprites/atlas.js', () => ({})),}));+vi.mock('../sprites/paths.js', () => ({+ listRuntimeAtlasAssets: vi.fn(async () => []),+ safeResolveSpriteAssetPath: vi.fn((id, path) => `/tmp/sprites/${id}/${path}`),+}));++vi.mock('../sprites/recordsLogic.js', () => ({+ isValidSpriteId: vi.fn(() => true),+}));+vi.mock('../tracks/index.js', () => ({getTrack: vi.fn(async (id) => ({ id, title: `Track ${id}`, audioFilename: `${id}.ogg` })),}));diff --git a/server/services/games/index.js b/server/services/games/index.jsindex 39ea316ae3..17cc5c5b66 100644--- a/server/services/games/index.js+++ b/server/services/games/index.js@@ -13,6 +13,11 @@ export {updateGame,} from './records.js';export { compileGameAssets } from './compile.js';+export {+ BUNDLE_SCHEMA_VERSION,+ getGameIntegrity,+ resolveGameAssets,+} from './integrity.js';export { requestGameFeedback } from './feedback.js';export {_resetGamesBackend,diff --git a/server/services/games/integrity.js b/server/services/games/integrity.jsnew file mode 100644index 0000000000..657c5f9e53--- /dev/null+++ b/server/services/games/integrity.js@@ -0,0 +1,344 @@+/**+ * Game bundle preflight and integrity verification.+ *+ * Resolves every bound asset to immutable, hash-pinned bytes. Native sprite+ * records use their current runtime-atlas pointer; imported prop/object+ * records use the runtime files already imported under atlas/. Character+ * references without a compiled atlas remain explicit blockers rather than+ * disappearing from a supposedly complete bundle.+ */++import { join } from 'path';+import {+ PATHS,+ readJSONFile,+ sha256File,+ sha256Text,+} from '../../lib/fileUtils.js';+import { canonicalStringify } from '../../lib/objects.js';+import { getAppById } from '../apps.js';+import { statMusicTrack } from '../pipeline/musicLibrary.js';+import { getAtlasState } from '../sprites/atlas.js';+import {+ listRuntimeAtlasAssets,+ safeResolveSpriteAssetPath,+} from '../sprites/paths.js';+import { getRecord as getSpriteRecord } from '../sprites/records.js';+import { isValidSpriteId } from '../sprites/recordsLogic.js';+import { getTrack } from '../tracks/index.js';+import { getGame } from './records.js';+import { gameRecordDir } from './store.js';++export const BUNDLE_SCHEMA_VERSION = 2;++const issue = (assetType, assetId, name, code, message) => ({+ assetType,+ assetId,+ name,+ code,+ message,+});++/**+ * A resolver's failure result. Every blocked asset carries both an `issue` for+ * the blocker list and a matching `summary` row for the per-asset UI, built+ * from the same values here so the two can't drift — `shortMessage` is the+ * badge text when the full blocker sentence is too long for a row.+ */+const blocked = (assetType, identity, code, message, shortMessage = message) => ({+ problem: issue(assetType, identity.assetId, identity.name, code, message),+ summary: { ...identity, status: 'blocked', message: shortMessage },+});++const hashIfPresent = (path) => sha256File(path).catch(() => null);++async function resolveRuntimeAtlas(record, current) {+ const identity = { assetId: record.id, name: record.name, kind: record.kind };+ const required = [+ current?.atlasPath,+ current?.atlasSha256,+ current?.manifestPath,+ current?.manifestSha256,+ ];+ if (required.some((value) => typeof value !== 'string' || !value)) return null;++ const paths = [+ safeResolveSpriteAssetPath(record.id, current.atlasPath),+ safeResolveSpriteAssetPath(record.id, current.manifestPath),+ ];+ if (paths.some((path) => !path)) {+ return blocked(+ 'sprite',+ identity,+ 'SPRITE_ATLAS_INTEGRITY_FAILED',+ `The runtime atlas paths for "${record.name}" are invalid`,+ 'Runtime atlas path invalid',+ );+ }++ const [atlasSha256, manifestSha256] = await Promise.all(paths.map(hashIfPresent));+ if (atlasSha256 !== current.atlasSha256 || manifestSha256 !== current.manifestSha256) {+ return blocked(+ 'sprite',+ identity,+ 'SPRITE_ATLAS_INTEGRITY_FAILED',+ `The runtime atlas for "${record.name}" is missing or does not match its recorded hash`,+ 'Runtime atlas integrity failed',+ );+ }++ return {+ item: {+ spriteId: record.id,+ name: record.name,+ kind: record.kind,+ sourceType: 'runtime-atlas',+ atlasVersion: current.version,+ atlasPath: `sprites/${record.id}/${current.atlasPath}`,+ atlasSha256,+ manifestPath: `sprites/${record.id}/${current.manifestPath}`,+ manifestSha256,+ geometry: current.geometry,+ },+ summary: {+ ...identity,+ status: 'ready',+ sourceType: 'runtime-atlas',+ // The atlas sheet plus its manifest — the two files hashed above.+ fileCount: paths.length,+ message: `Runtime atlas v${current.version}`,+ },+ };+}++async function resolveImportedAssets(record) {+ const identity = { assetId: record.id, name: record.name, kind: record.kind };+ const runtimeAssets = await listRuntimeAtlasAssets(record.id);+ if (runtimeAssets.length === 0) return null;++ const assets = await Promise.all(runtimeAssets.map(async (asset) => ({+ path: `sprites/${record.id}/${asset.path}`,+ sha256: await hashIfPresent(safeResolveSpriteAssetPath(record.id, asset.path)),+ sizeBytes: asset.size,+ })));+ if (assets.some((asset) => !asset.sha256)) {+ return blocked(+ 'sprite',+ identity,+ 'SPRITE_ATLAS_INTEGRITY_FAILED',+ `An imported runtime asset for "${record.name}" is missing or unreadable`,+ 'Imported asset integrity failed',+ );+ }++ return {+ item: {+ spriteId: record.id,+ name: record.name,+ kind: record.kind,+ sourceType: 'imported-assets',+ assets,+ },+ summary: {+ ...identity,+ status: 'ready',+ sourceType: 'imported-assets',+ fileCount: assets.length,+ message: `${assets.length} imported runtime ${assets.length === 1 ? 'file' : 'files'}`,+ },+ };+}++async function resolveSprite(binding) {+ // The atlas pointer is keyed on the same id as the record, so both reads can+ // start together — a missing record wastes one cheap pointer read rather than+ // serializing two round trips for every bound sprite on every preflight. The+ // id guard keeps a corrupt binding a SPRITE_MISSING row instead of a 400 out+ // of `spriteDir`.+ const [record, atlas] = await Promise.all([+ getSpriteRecord(binding.spriteId),+ isValidSpriteId(binding.spriteId) ? getAtlasState(binding.spriteId) : { current: null },+ ]);+ if (!record) {+ return blocked(+ 'sprite',+ { assetId: binding.spriteId, name: binding.spriteId },+ 'SPRITE_MISSING',+ `Bound sprite no longer exists: ${binding.spriteId}`,+ );+ }+ const identity = { assetId: record.id, name: record.name, kind: record.kind };++ const runtime = await resolveRuntimeAtlas(record, atlas.current);+ if (runtime) return runtime;++ const imported = await resolveImportedAssets(record);+ if (imported) return imported;++ return blocked(+ 'sprite',+ identity,+ 'SPRITE_ATLAS_REQUIRED',+ `Compile or import a runtime atlas for "${record.name}" before building the game bundle`,+ 'Runtime atlas required',+ );+}++async function resolveMusic(binding) {+ const track = await getTrack(binding.trackId);+ if (!track) {+ return blocked(+ 'music',+ { assetId: binding.trackId, bindingId: binding.id, name: binding.trackId },+ 'TRACK_MISSING',+ `Bound music track no longer exists: ${binding.trackId}`,+ );+ }+ const identity = { assetId: track.id, bindingId: binding.id, name: track.title };++ if (!track.audioFilename || !(await statMusicTrack(track.audioFilename))) {+ return blocked(+ 'music',+ identity,+ 'TRACK_AUDIO_REQUIRED',+ `Render or upload audio for "${track.title}" before building the game bundle`,+ 'Audio render required',+ );+ }++ const audioSha256 = await hashIfPresent(join(PATHS.music, track.audioFilename));+ if (!audioSha256) {+ return blocked(+ 'music',+ identity,+ 'TRACK_AUDIO_INTEGRITY_FAILED',+ `The rendered audio for "${track.title}" is missing or unreadable`,+ 'Audio integrity failed',+ );+ }++ return {+ item: {+ bindingId: binding.id,+ trackId: track.id,+ title: track.title,+ audioPath: `music/${track.audioFilename}`,+ audioSha256,+ },+ summary: {+ ...identity,+ status: 'ready',+ fileCount: 1,+ message: 'Audio ready',+ },+ };+}++export async function resolveGameAssets(game) {+ const [spriteResults, musicResults] = await Promise.all([+ Promise.all([...game.spriteBindings]+ .sort((a, b) => a.spriteId.localeCompare(b.spriteId))+ .map(resolveSprite)),+ Promise.all([...game.musicBindings]+ .sort((a, b) => a.trackId.localeCompare(b.trackId) || a.id.localeCompare(b.id))+ .map(resolveMusic)),+ ]);+ const issues = [...spriteResults, ...musicResults]+ .map((result) => result.problem)+ .filter(Boolean);+ const sprites = spriteResults.map((result) => result.item).filter(Boolean);+ const music = musicResults.map((result) => result.item).filter(Boolean);+ const summaries = {+ sprites: spriteResults.map((result) => result.summary),+ music: musicResults.map((result) => result.summary),+ };+ const inputs = {+ schemaVersion: BUNDLE_SCHEMA_VERSION,+ gameId: game.id,+ appId: game.appId,+ sprites,+ music,+ };+ return {+ schemaVersion: BUNDLE_SCHEMA_VERSION,+ sprites,+ music,+ issues,+ inputSha256: sha256Text(canonicalStringify(inputs)),+ summaries,+ // "How many files does this asset contribute" is answered once, by the+ // resolver that hashed them. The compiled manifest pointer and the+ // preflight both read this, so a new source type can't make the two+ // numbers disagree on screen.+ verifiedFileCount: [...summaries.sprites, ...summaries.music]+ .reduce((sum, asset) => sum + (asset.fileCount || 0), 0),+ };+}++async function inspectCurrentBundle(game, resolved) {+ const current = game.compiledManifest;+ if (!current) return { status: 'missing', message: 'No bundle has been built yet' };+ const corrupt = {+ status: 'corrupt',+ message: 'The current bundle manifest is missing or failed integrity verification',+ };+ if (!current.manifestPath) return corrupt;+ const path = join(gameRecordDir(game.id), current.manifestPath);+ const [actualSha256, manifest] = await Promise.all([+ hashIfPresent(path),+ readJSONFile(path, null, { logError: false }),+ ]);+ if (!actualSha256+ || actualSha256 !== current.manifestSha256+ || manifest?.kind !== 'portos-game-assets'+ || manifest?.game?.id !== game.id+ || manifest?.version !== current.version) {+ return corrupt;+ }+ if (current.inputSha256 !== resolved.inputSha256 || resolved.issues.length > 0) {+ return {+ status: 'stale',+ message: 'Bound assets changed after this bundle was built',+ };+ }+ return {+ status: 'current',+ message: 'Bundle manifest and every bound asset hash are verified',+ };+}++export async function getGameIntegrity(id) {+ const game = await getGame(id);+ if (!game) return null;+ // The app lookup is independent of the hashing sweep — don't make it wait.+ const [app, resolved] = await Promise.all([+ getAppById(game.appId),+ resolveGameAssets(game),+ ]);+ if (!app) {+ resolved.issues.push(issue(+ 'app',+ game.appId,+ game.name,+ 'APP_MISSING',+ 'The bound managed app no longer exists',+ ));+ }+ const bundle = await inspectCurrentBundle(game, resolved);+ const readyToCompile = resolved.issues.length === 0 && Boolean(app);+ return {+ schemaVersion: BUNDLE_SCHEMA_VERSION,+ readyToCompile,+ canLaunch: readyToCompile && bundle.status === 'current',+ bundle,+ issues: resolved.issues,+ assets: resolved.summaries,+ counts: {+ spriteReady: resolved.sprites.length,+ spriteTotal: game.spriteBindings.length,+ musicReady: resolved.music.length,+ musicTotal: game.musicBindings.length,+ verifiedFiles: resolved.verifiedFileCount,+ },+ };+}diff --git a/server/services/games/integrity.test.js b/server/services/games/integrity.test.jsnew file mode 100644index 0000000000..cff92b404a--- /dev/null+++ b/server/services/games/integrity.test.js@@ -0,0 +1,156 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({+ game: null,+ records: {},+ atlases: {},+ assets: {},+ manifest: null,+}));++vi.mock('./records.js', () => ({+ getGame: vi.fn(async () => state.game),+}));++vi.mock('./store.js', () => ({+ gameRecordDir: (id) => `/tmp/games/${id}`,+}));++vi.mock('../apps.js', () => ({+ getAppById: vi.fn(async () => ({ id: 'app-1', name: 'Example App' })),+}));++vi.mock('../sprites/records.js', () => ({+ getRecord: vi.fn(async (id) => state.records[id] || null),+}));++vi.mock('../sprites/atlas.js', () => ({+ getAtlasState: vi.fn(async (id) => ({+ current: state.atlases[id] || null,+ publications: [],+ })),+}));++vi.mock('../sprites/paths.js', () => ({+ listRuntimeAtlasAssets: vi.fn(async (id) => state.assets[id] || []),+ safeResolveSpriteAssetPath: vi.fn((id, path) => `/tmp/sprites/${id}/${path}`),+}));++vi.mock('../sprites/recordsLogic.js', () => ({+ isValidSpriteId: vi.fn(() => true),+}));++vi.mock('../tracks/index.js', () => ({+ getTrack: vi.fn(async (id) => ({+ id,+ title: 'Example Theme',+ audioFilename: 'example-theme.ogg',+ })),+}));++vi.mock('../pipeline/musicLibrary.js', () => ({+ statMusicTrack: vi.fn(async () => ({ sizeBytes: 128 })),+}));++vi.mock('../../lib/fileUtils.js', () => ({+ PATHS: { music: '/tmp/music' },+ readJSONFile: vi.fn(async () => state.manifest),+ sha256Text: vi.fn((value) => `text-sha:${String(value).length}`),+ sha256File: vi.fn(async (path) => {+ if (path.includes('/games/')) return 'bundle-sha';+ if (path.endsWith('native.png')) return 'native-atlas-sha';+ if (path.endsWith('native.json')) return 'native-manifest-sha';+ if (path.endsWith('props.png')) return 'props-sha';+ if (path.endsWith('.ogg')) return 'music-sha';+ return null;+ }),+}));++import { getGameIntegrity, resolveGameAssets } from './integrity.js';++const baseGame = () => ({+ id: 'game-1',+ appId: 'app-1',+ name: 'Example Game',+ spriteBindings: [+ { spriteId: 'native' },+ { spriteId: 'props' },+ { spriteId: 'draft-character' },+ ],+ musicBindings: [{ id: 'music-1', trackId: 'theme' }],+ compiledManifest: null,+});++describe('Game bundle integrity', () => {+ beforeEach(() => {+ state.game = baseGame();+ state.records = {+ native: { id: 'native', name: 'Native Hero', kind: 'character' },+ props: { id: 'props', name: 'Imported Props', kind: 'props' },+ 'draft-character': { id: 'draft-character', name: 'Draft Character', kind: 'character' },+ };+ state.atlases = {+ native: {+ version: 4,+ atlasPath: 'runtime/v4/native.png',+ atlasSha256: 'native-atlas-sha',+ manifestPath: 'runtime/v4/native.json',+ manifestSha256: 'native-manifest-sha',+ geometry: { cellSize: 96 },+ },+ };+ state.assets = {+ props: [{ path: 'atlas/props.png', size: 512 }],+ };+ state.manifest = null;+ });++ it('accepts native and imported runtime assets while preserving draft blockers', async () => {+ const resolved = await resolveGameAssets(state.game);+ expect(resolved.sprites.map((sprite) => [sprite.spriteId, sprite.sourceType])).toEqual([+ ['native', 'runtime-atlas'],+ ['props', 'imported-assets'],+ ]);+ expect(resolved.music).toHaveLength(1);+ expect(resolved.issues).toEqual([+ expect.objectContaining({+ assetId: 'draft-character',+ code: 'SPRITE_ATLAS_REQUIRED',+ }),+ ]);+ expect(resolved.summaries.sprites).toEqual(expect.arrayContaining([+ expect.objectContaining({ assetId: 'props', status: 'ready', fileCount: 1 }),+ expect.objectContaining({ assetId: 'draft-character', status: 'blocked' }),+ ]));+ });++ it('marks a complete hash-matching manifest current and launchable', async () => {+ state.game.spriteBindings = state.game.spriteBindings.filter(+ (binding) => binding.spriteId !== 'draft-character',+ );+ const resolved = await resolveGameAssets(state.game);+ state.game.compiledManifest = {+ version: 3,+ manifestPath: 'manifests/game-assets-v3.json',+ manifestSha256: 'bundle-sha',+ inputSha256: resolved.inputSha256,+ };+ state.manifest = {+ kind: 'portos-game-assets',+ game: { id: 'game-1' },+ version: 3,+ };++ const integrity = await getGameIntegrity('game-1');+ expect(integrity.bundle.status).toBe('current');+ expect(integrity.readyToCompile).toBe(true);+ expect(integrity.canLaunch).toBe(true);+ expect(integrity.counts).toMatchObject({+ spriteReady: 2,+ spriteTotal: 2,+ musicReady: 1,+ musicTotal: 1,+ verifiedFiles: 4,+ });+ });+});diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.jsindex 1266556130..570cdb3b22 100644--- a/server/services/sprites/paths.js+++ b/server/services/sprites/paths.js@@ -75,6 +75,14 @@ export function toRecordRelativeAssetPath(recordId, rawPath) {return rel;}+// The confinement check itself, shared by the throwing gate below and the+// non-throwing `safeResolveSpriteAssetPath` so the two can never disagree on+// what counts as an escape.+const confineToRecordDir = (dir, relPath) => {+ const abs = resolve(dir, relPath);+ return abs === dir || isPathInsideDir(dir, abs) ? abs : null;+};+/*** Resolve a relative asset path inside a record's directory, refusing any* path that escapes it (`..`, absolute paths).@@ -84,8 +92,8 @@ export function resolveSpriteAssetPath(recordId, relPath) {if (typeof relPath !== 'string' || !relPath) {throw new ServerError('Missing asset path', { status: 400, code: 'INVALID_ASSET_PATH' });}- const abs = resolve(dir, relPath);- if (abs !== dir && !isPathInsideDir(dir, abs)) {+ const abs = confineToRecordDir(dir, relPath);+ if (!abs) {throw new ServerError(`Asset path escapes sprite directory: ${relPath}`, { status: 400, code: 'INVALID_ASSET_PATH' });}return abs;@@ -267,9 +275,16 @@ export function __resetSpriteMetadataCache() {* run in parallel. A record with no directory yet returns []. A non-image* carries no image fields at all; an image sharp can't read carries* `imageError: true` — see `readImageMetadata`.+ *+ * Options narrow the walk for consumers that don't need the whole record:+ * - `subdir` — descend only this record-relative directory (paths stay+ * record-relative, so callers see the same shape either way)+ * - `metadata` — set false to skip the sharp header probe entirely. The+ * asset browser wants dimensions; a caller that only needs bytes and sizes+ * should not pay a probe per image on every call.*/-export async function listSpriteAssets(recordId) {- const dir = spriteDir(recordId);+export async function listSpriteAssets(recordId, { subdir = '', metadata = true } = {}) {+ const dir = subdir ? join(spriteDir(recordId), subdir) : spriteDir(recordId);const out = [];async function walk(current, relPrefix) {let entries;@@ -287,12 +302,42 @@ export async function listSpriteAssets(recordId) {} else if (entry.isFile()) {const abs = join(current, entry.name);const s = await stat(abs);- const meta = await readImageMetadata(abs, s);+ const meta = metadata ? await readImageMetadata(abs, s) : null;out.push({ path: rel, size: s.size, mtime: s.mtimeMs, ...meta });}}));}- await walk(dir, '');+ await walk(dir, subdir);out.sort((a, b) => a.path.localeCompare(b.path));return out;}++/**+ * The runtime-ready files a record contributes to a game asset bundle:+ * everything under `atlas/` with a loadable extension. Named here rather than+ * in the games bundler because this module owns the on-disk layout — imported+ * prop/object families land in `atlas/` via `importer.js` `importPropsFamily`,+ * and that anchor has already moved once (migration 202).+ *+ * The extension filter is narrower than what the importer copies (it also+ * brings `.md` docs across) and wider than what PortOS itself emits, so a+ * hand-placed sheet in another image format still bundles.+ */+export const IMPORTED_ATLAS_DIR = 'atlas';+const RUNTIME_ASSET_EXT = /\.(?:png|gif|webp|jpe?g|json)$/i;++export async function listRuntimeAtlasAssets(recordId) {+ const assets = await listSpriteAssets(recordId, { subdir: IMPORTED_ATLAS_DIR, metadata: false });+ return assets.filter((asset) => RUNTIME_ASSET_EXT.test(asset.path));+}++/**+ * `resolveSpriteAssetPath` for callers that want a bad path to be a data row+ * rather than a 400 — preflight/verification sweeps report a broken pointer as+ * a blocked asset instead of failing the whole request. Returns null for a+ * non-slug id, an empty path, or anything that escapes the record dir.+ */+export function safeResolveSpriteAssetPath(recordId, relPath) {+ if (!isValidSpriteId(recordId) || typeof relPath !== 'string' || !relPath) return null;+ return confineToRecordDir(join(PATHS.sprites, recordId), relPath);+}