Skip to content

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

refactor([issue-2898]): apply /simplify findings across the atlas compile + publish path

[._.]/ Adam Eivyccdb78bb0f05
diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsx
index c457614e8d..fdad6aa7a8 100644
--- a/client/src/components/sprites/PublishWorkflow.jsx
+++ b/client/src/components/sprites/PublishWorkflow.jsx
@@ -1,10 +1,14 @@
import { useEffect, useState } from 'react';
import { Package, Rocket, RefreshCw } from 'lucide-react';
+import toast from '../ui/Toast';
import {
compileSpriteAtlas, setSpritePublishBinding, publishSpriteAtlas,
} from '../../services/apiSprites.js';
-import { getApps } from '../../services/apiApps.js';
+import { useSidebarApps } from '../../hooks/useSidebarApps.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import AppContextPicker from '../AppContextPicker.jsx';
+import InlineConfirmRow from '../ui/InlineConfirmRow.jsx';
+import { FormField } from '../ui/FormField.jsx';
import { spriteAssetUrl } from './spriteAssets.js';
import { timeAgo } from '../../utils/formatters.js';
@@ -13,16 +17,8 @@ import { timeAgo } from '../../utils/formatters.js';
// and publish (atomic replace, divergence-refusing) into the game repo.
// Appears only once the walk set is finalized — the compile input.
-function Field({ label, children }) {
- return (
- <label className="block text-xs text-gray-400">
- <span className="block mb-1">{label}</span>
- {children}
- </label>
- );
-}
-
const inputClass = 'w-full px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200 focus:border-port-accent focus:outline-none';
+const fieldLabelClass = 'block text-xs text-gray-400 mb-1';
export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
const finalized = Boolean(walk?.walkSet);
@@ -30,19 +26,14 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
const publications = atlas?.publications || [];
const saved = record.publishBinding || null;
- const [apps, setApps] = useState([]);
+ const apps = useSidebarApps();
const [appId, setAppId] = useState(saved?.appId || '');
const [destPath, setDestPath] = useState(saved?.atlasDestPath || '');
const [codePath, setCodePath] = useState(saved?.codeBinding?.path || '');
const [resourcePath, setResourcePath] = useState(saved?.codeBinding?.resourcePath || '');
- const [confirming, setConfirming] = useState(false);
-
- useEffect(() => {
- if (!finalized) return;
- getApps({ silent: true })
- .then((list) => setApps((Array.isArray(list) ? list : []).filter((a) => !a.archived)))
- .catch(() => {});
- }, [finalized]);
+ // null → idle; 'publish' → normal confirm; 'overwrite' → the server
+ // refused with PUBLISH_DEST_OCCUPIED and needs explicit consent.
+ const [confirmStage, setConfirmStage] = useState(null);
// Re-seed the form when the server-side binding changes (save round-trip).
useEffect(() => {
@@ -59,7 +50,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
}, { errorMessage: 'Atlas compile failed' });
const [saveBinding, savingBinding] = useAsyncAction(async () => {
- const binding = appId && destPath
+ const binding = appId && destPath.trim()
? {
appId,
atlasDestPath: destPath.trim(),
@@ -73,10 +64,22 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
return result;
}, { errorMessage: 'Could not save the publish binding' });
- const [publish, publishing] = useAsyncAction(async () => {
- setConfirming(false);
- const result = await publishSpriteAtlas(record.id, { silent: true });
- onChanged?.();
+ const [publish, publishing] = useAsyncAction(async (acknowledgeOverwrite) => {
+ setConfirmStage(null);
+ const body = acknowledgeOverwrite ? { acknowledgeOverwrite: true } : {};
+ const result = await publishSpriteAtlas(record.id, body, { silent: true }).catch((err) => {
+ // The destination holds an atlas PortOS never published — escalate to
+ // an explicit overwrite consent instead of toasting a dead end.
+ if (err?.code === 'PUBLISH_DEST_OCCUPIED') {
+ setConfirmStage('overwrite');
+ return null;
+ }
+ throw err;
+ });
+ if (result) {
+ toast.success(result.published ? `Atlas v${result.publication.version} published` : 'Destination already up to date');
+ onChanged?.();
+ }
return result;
}, { errorMessage: 'Publish failed' });
@@ -90,6 +93,7 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
// a binding save is in flight so a click can't race the PUT.
const canPublish = Boolean(saved?.appId && saved?.atlasDestPath) && !bindingDirty && !savingBinding && !publishing;
const boundApp = apps.find((a) => a.id === saved?.appId);
+ const destLabel = `${boundApp?.name || saved?.appId}: ${saved?.atlasDestPath}`;
return (
<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
@@ -124,21 +128,24 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
<div className="flex-1 space-y-2 min-w-0">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
- <Field label="Managed app">
- <select value={appId} onChange={(e) => setAppId(e.target.value)} className={inputClass}>
- <option value="">— none —</option>
- {apps.map((app) => <option key={app.id} value={app.id}>{app.name}</option>)}
- </select>
- </Field>
- <Field label="Atlas destination (repo-relative .png)">
+ <AppContextPicker
+ apps={apps}
+ value={appId}
+ onChange={setAppId}
+ label="Managed app"
+ placeholder="— none —"
+ selectClassName={inputClass}
+ className="sm:col-span-2"
+ />
+ <FormField label="Atlas destination (repo-relative .png)" labelClassName={fieldLabelClass}>
<input value={destPath} onChange={(e) => setDestPath(e.target.value)} placeholder="assets/sprites/hero/hero-atlas.png" className={inputClass} />
- </Field>
- <Field label="Code binding file (optional)">
+ </FormField>
+ <FormField label="Code binding file (optional)" labelClassName={fieldLabelClass}>
<input value={codePath} onChange={(e) => setCodePath(e.target.value)} placeholder="src/Hero.cs" className={inputClass} />
- </Field>
- <Field label="Resource path in code (optional)">
+ </FormField>
+ <FormField label="Resource path in code (optional)" labelClassName={fieldLabelClass} className="sm:col-span-2">
<input value={resourcePath} onChange={(e) => setResourcePath(e.target.value)} placeholder="res://assets/sprites/hero/hero-atlas.png" className={inputClass} />
- </Field>
+ </FormField>
</div>
<div className="flex items-center gap-2 flex-wrap">
<button
@@ -148,27 +155,35 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
>
{savingBinding ? 'Saving…' : 'Save binding'}
</button>
- {!confirming ? (
+ {!confirmStage && (
<button
- onClick={() => setConfirming(true)}
+ onClick={() => setConfirmStage('publish')}
disabled={!canPublish}
title={bindingDirty ? 'Save the binding first' : undefined}
className="flex items-center gap-1 px-2 py-1 text-xs bg-port-accent/20 border border-port-accent rounded text-port-accent hover:bg-port-accent/30 disabled:opacity-50"
>
<Rocket size={12} /> Publish to app
</button>
- ) : (
- <span className="flex items-center gap-2 text-xs text-gray-300">
- Replace <code className="text-port-warning">{saved?.atlasDestPath}</code> in {boundApp?.name || saved?.appId}?
- <button onClick={publish} disabled={publishing} className="px-2 py-0.5 text-xs bg-port-error/20 border border-port-error rounded text-port-error hover:bg-port-error/30 disabled:opacity-50">
- {publishing ? 'Publishing…' : 'Confirm'}
- </button>
- <button onClick={() => setConfirming(false)} className="px-2 py-0.5 text-xs bg-port-bg border border-port-border rounded text-gray-400 hover:border-port-accent">
- Cancel
- </button>
- </span>
)}
</div>
+ {confirmStage === 'publish' && (
+ <InlineConfirmRow
+ question={`Replace ${destLabel}?`}
+ confirmText={publishing ? 'Publishing…' : 'Publish'}
+ tone="warning"
+ onConfirm={() => publish(false)}
+ onCancel={() => setConfirmStage(null)}
+ />
+ )}
+ {confirmStage === 'overwrite' && (
+ <InlineConfirmRow
+ question={`${destLabel} already contains an atlas PortOS did not publish. Overwrite it?`}
+ confirmText={publishing ? 'Publishing…' : 'Overwrite'}
+ tone="error"
+ onConfirm={() => publish(true)}
+ onCancel={() => setConfirmStage(null)}
+ />
+ )}
</div>
</div>
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index 060ff8427f..adf2779007 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -85,7 +85,9 @@ export const setSpritePublishBinding = (id, binding, options = {}) => request(`/
method: 'PUT', body: JSON.stringify({ binding }), ...options,
});
-// Publish the compiled atlas into the bound managed app's repo.
-export const publishSpriteAtlas = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}/atlas/publish`, {
- method: 'POST', body: JSON.stringify({}), ...options,
+// Publish the compiled atlas into the bound managed app's repo. Pass
+// { acknowledgeOverwrite: true } after a 409 PUBLISH_DEST_OCCUPIED to
+// consent to replacing a destination atlas PortOS never published.
+export const publishSpriteAtlas = (id, body = {}, options = {}) => request(`/sprites/${encodeURIComponent(id)}/atlas/publish`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index a4cdd4c23c..46d00e67c2 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -984,7 +984,9 @@ const spriteRepoRelativePath = z.string().min(1).max(1024)
export const spritePublishBindingSchema = z.object({
appId: z.string().min(1).max(200),
- atlasDestPath: spriteRepoRelativePath,
+ atlasDestPath: spriteRepoRelativePath.refine((p) => p.toLowerCase().endsWith('.png'), {
+ message: 'atlasDestPath must point at a .png atlas file',
+ }),
codeBinding: z.object({
path: spriteRepoRelativePath,
resourcePath: z.string().min(1).max(1024),
@@ -992,6 +994,12 @@ export const spritePublishBindingSchema = z.object({
}).nullable().optional(),
}).nullable();
+// acknowledgeOverwrite: explicit consent to replace a destination atlas
+// PortOS never published (409 PUBLISH_DEST_OCCUPIED otherwise).
+export const spriteAtlasPublishSchema = z.object({
+ acknowledgeOverwrite: z.boolean().optional(),
+});
+
// Optional per-compile geometry overrides (player default: 96px cells,
// pivot (48,88), 86×74 content bounds). Columns/rows are the fixed contract.
export const spriteAtlasCompileSchema = z.object({
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index 7102ecd65c..00777f4d9a 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -25,6 +25,7 @@ import {
spriteWalkTrimSchema,
spritePublishBindingSchema,
spriteAtlasCompileSchema,
+ spriteAtlasPublishSchema,
} from '../lib/validation.js';
import { z } from 'zod';
import { optionalUploadFields } from '../lib/multipart.js';
@@ -158,7 +159,8 @@ router.put('/:id/publish-binding', asyncHandler(async (req, res) => {
}));
router.post('/:id/atlas/publish', asyncHandler(async (req, res) => {
- res.json(await publishAtlas(req.params.id));
+ const body = validateRequest(spriteAtlasPublishSchema, req.body ?? {});
+ res.json(await publishAtlas(req.params.id, body));
}));
// Chroma-key changes route through patchSpriteRecord, which re-checks the
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 018d11cbe5..19cccdf3b5 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -337,13 +337,18 @@ describe('sprites routes', () => {
.send({ binding: { ...binding, atlasDestPath: '/abs.png' } })).status).toBe(400);
expect((await request(app).put('/api/sprites/pioneer/publish-binding')
.send({ binding: { ...binding, codeBinding: { path: 'src/Hero.cs', resourcePath: '' } } })).status).toBe(400);
+ expect((await request(app).put('/api/sprites/pioneer/publish-binding')
+ .send({ binding: { ...binding, atlasDestPath: 'assets/atlas.jpg' } })).status).toBe(400);
expect(publish.setPublishBinding).toHaveBeenCalledTimes(2);
});
- it('POST /:id/atlas/publish delegates to publishAtlas', async () => {
+ it('POST /:id/atlas/publish delegates to publishAtlas with the acknowledge flag', async () => {
const r = await request(app).post('/api/sprites/pioneer/atlas/publish').send({});
expect(r.status).toBe(200);
- expect(publish.publishAtlas).toHaveBeenCalledWith('pioneer');
+ expect(publish.publishAtlas).toHaveBeenCalledWith('pioneer', {});
expect(r.body.published).toBe(true);
+
+ await request(app).post('/api/sprites/pioneer/atlas/publish').send({ acknowledgeOverwrite: true });
+ expect(publish.publishAtlas).toHaveBeenLastCalledWith('pioneer', { acknowledgeOverwrite: true });
});
});
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index b6c3c46f75..3d02572be0 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -23,22 +23,22 @@
*/
import { join } from 'path';
-import { readdir } from 'fs/promises';
-import { createHash } from 'crypto';
+import { readdir, readFile } from 'fs/promises';
import sharp from 'sharp';
import {
- atomicWrite, ensureDir, pathExists, readJSONFile, sha256File, tryReadFile,
+ atomicWrite, ensureDir, pathExists, readJSONFile, tryReadFile,
} from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { spriteDir } from './paths.js';
+import { spriteDir, RUNTIME_POINTER_REL, RUNTIME_PUBLICATIONS_REL } from './paths.js';
import { requireCharacter, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS } from './prompts.js';
import { keyChannelSplit } from './chromaKey.js';
import {
WALK_PHASES, pyRound, pyRoundTo, median, decodeRgbaFrame, premultipliedResize,
sampleBorderKey, validateMeasuredKey, recoverAlphaFrame, despillKeyFrame,
+ alphaBbox, compositeOnto, sha256Buffer,
} from './walkPostprocess.js';
-import { withWalkWriteTail } from './walk.js';
+import { withWalkWriteTail, walkSetRelPath } from './walk.js';
// Player atlas contract (source pipeline runtime_publish.py): 96px cells,
// pivot (48,88) — silhouette centered on x=48, feet on the y=88 ground line —
@@ -62,46 +62,27 @@ const ALPHA_NOISE_FLOOR = 2;
const IDLE_HEIGHT_TOLERANCE = 2;
const RUNTIME_DIR = 'runtime';
-const CURRENT_POINTER = 'runtime/current.json';
const atlasStem = (recordId) => `${recordId}-animation-atlas`;
const compileError = (message, code = 'ATLAS_COMPILE_INVALID') =>
new ServerError(message, { status: 422, code });
-const sha256Buffer = (buffer) => createHash('sha256').update(buffer).digest('hex');
-
-/** Tight bbox of pixels with alpha > threshold; exclusive right/bottom. */
-function thresholdBbox(frame, threshold) {
- const { data, width, height } = frame;
- let left = width; let top = height; let right = -1; let bottom = -1;
- for (let y = 0; y < height; y++) {
- for (let x = 0; x < width; x++) {
- if (data[(y * width + x) * 4 + 3] > threshold) {
- if (x < left) left = x;
- if (x > right) right = x;
- if (y < top) top = y;
- if (y > bottom) bottom = y;
- }
- }
- }
- if (right < 0) return null;
- return { left, top, right: right + 1, bottom: bottom + 1 };
-}
-
function occupiedDimensions(frame, threshold, label) {
- const bounds = thresholdBbox(frame, threshold);
+ const bounds = alphaBbox(frame, threshold);
if (!bounds) throw compileError(`${label} has no visible pixels`);
return { width: bounds.right - bounds.left, height: bounds.bottom - bounds.top };
}
/**
- * Load a source image as a straight-alpha transparent frame. Already-keyed
- * sources (packaged walk frames) get a despill safety pass; opaque key-matte
- * sources (locked anchors) go through measured-key alpha recovery first —
- * the same treatment the walk postprocess gives its raw frames.
+ * Decode a validated source buffer as a straight-alpha transparent frame.
+ * Already-keyed sources (packaged walk frames) get a despill safety pass;
+ * opaque key-matte sources (locked anchors) go through measured-key alpha
+ * recovery first — the same treatment the walk postprocess gives its raw
+ * frames. Takes the in-memory bytes validateForCompile already hashed, so
+ * the pixels compiled are provably the pixels verified.
*/
-async function transparentSource(absPath, split, keyHex) {
- const frame = await decodeRgbaFrame(absPath);
+async function transparentSource(bytes, split, keyHex) {
+ const frame = await decodeRgbaFrame(bytes);
const { data } = frame;
let alphaMin = 255; let alphaMax = 0;
for (let i = 3; i < data.length; i += 4) {
@@ -131,7 +112,7 @@ async function normalizeCellFrame(source, scale, label, geometry) {
scaled.data[i - 3] = 0; scaled.data[i - 2] = 0; scaled.data[i - 1] = 0; scaled.data[i] = 0;
}
}
- const bounds = thresholdBbox(scaled, ALPHA_THRESHOLD);
+ const bounds = alphaBbox(scaled, ALPHA_THRESHOLD);
if (!bounds) throw compileError(`${label} has no visible pixels after scaling`);
const centerX = (bounds.left + bounds.right - 1) / 2;
const pasteX = pyRound(pivot[0] - centerX);
@@ -143,8 +124,11 @@ async function normalizeCellFrame(source, scale, label, geometry) {
throw compileError(`${label} touches the right or bottom runtime cell edge`);
}
const cell = { data: Buffer.alloc(cellSize * cellSize * 4), width: cellSize, height: cellSize };
- blitFrame(cell, scaled, pasteX, pasteY);
- const final = thresholdBbox(cell, ALPHA_THRESHOLD);
+ compositeOnto(cell, scaled, pasteX, pasteY);
+ // Port-faithful belt-and-braces: re-measure the composed cell and verify
+ // the feet really sit on the ground line (runtime_publish.py does the same
+ // final _bounds check rather than trusting the placement math).
+ const final = alphaBbox(cell, ALPHA_THRESHOLD);
if (!final || final.bottom - 1 !== pivot[1]) {
throw compileError(`${label} misses the runtime ground line y=${pivot[1]}`);
}
@@ -163,21 +147,6 @@ async function normalizeCellFrame(source, scale, label, geometry) {
};
}
-/** Copy a straight-alpha frame onto a transparent canvas (no overlap). */
-function blitFrame(canvas, frame, dx, dy) {
- for (let y = 0; y < frame.height; y++) {
- const ty = dy + y;
- if (ty < 0 || ty >= canvas.height) continue;
- for (let x = 0; x < frame.width; x++) {
- const tx = dx + x;
- if (tx < 0 || tx >= canvas.width) continue;
- const si = (y * frame.width + x) * 4;
- if (frame.data[si + 3] === 0) continue;
- frame.data.copy(canvas.data, (ty * canvas.width + tx) * 4, si, si + 4);
- }
- }
-}
-
/**
* Revalidate the full evidence chain: finalized walk set → selection →
* per-direction run manifests → packaged frame bytes, plus the locked
@@ -185,9 +154,26 @@ function blitFrame(canvas, frame, dx, dy) {
*/
export async function validateForCompile(recordId) {
const dir = spriteDir(recordId);
- const walkSetAbs = join(dir, `walk/${recordId}-walk-set-v1.json`);
- const walkSet = await readJSONFile(walkSetAbs, null);
- if (!walkSet) throw compileError('No finalized walk set — approve all 8 directions first', 'WALK_SET_REQUIRED');
+ // Every hashed input is read exactly once: verify the bytes in memory and
+ // hand those same bytes to the compiler, so the pixels compiled are
+ // provably the pixels verified (no re-read between check and use).
+ const readVerified = async (relPath, expectedSha, label) => {
+ const bytes = await readFile(join(dir, relPath)).catch(() => null);
+ if (!bytes || sha256Buffer(bytes) !== expectedSha) {
+ throw compileError(`${label} no longer matches its recorded sha256`);
+ }
+ return bytes;
+ };
+
+ const walkSetRel = walkSetRelPath(recordId);
+ const walkSetBytes = await readFile(join(dir, walkSetRel)).catch(() => null);
+ if (!walkSetBytes) throw compileError('No finalized walk set — approve all 8 directions first', 'WALK_SET_REQUIRED');
+ let walkSet;
+ try {
+ walkSet = JSON.parse(walkSetBytes);
+ } catch {
+ throw compileError('Walk set manifest is unreadable');
+ }
if (walkSet.kind !== 'finalized-eight-direction-walk-set' || walkSet.status !== 'final') {
throw compileError('Walk set manifest is not a finalized eight-direction walk set');
}
@@ -195,10 +181,7 @@ export async function validateForCompile(recordId) {
if (JSON.stringify(walkSet.directionOrder) !== JSON.stringify(SPRITE_DIRECTIONS)) {
throw compileError('Walk set direction order does not match the runtime contract');
}
- const selectionAbs = join(dir, walkSet.selectionPath);
- if ((await sha256File(selectionAbs)) !== walkSet.selectionSha256) {
- throw compileError('Walk selection file no longer matches its finalized sha256');
- }
+ await readVerified(walkSet.selectionPath, walkSet.selectionSha256, 'Walk selection file');
const referenceManifest = await loadManifest(recordId);
if (!referenceManifest || referenceManifest.status !== 'complete') {
@@ -213,22 +196,21 @@ export async function validateForCompile(recordId) {
if (!anchor || anchor.status !== 'locked' || !anchor.path) {
throw compileError(`Anchor for ${direction} is not locked`);
}
- const anchorAbs = join(dir, anchor.path);
- if ((await sha256File(anchorAbs)) !== anchor.sha256) {
- throw compileError(`Anchor for ${direction} no longer matches its locked sha256`);
- }
- anchors[direction] = { ...anchor, abs: anchorAbs };
+ const bytes = await readVerified(anchor.path, anchor.sha256, `Anchor for ${direction}`);
+ anchors[direction] = { ...anchor, bytes };
}
const runs = {};
for (const direction of SPRITE_DIRECTIONS) {
const entry = walkSet.directions?.[direction];
if (!entry || entry.status !== 'approved') throw compileError(`Direction ${direction} is not approved`);
- const manifestAbs = join(dir, entry.runManifest);
- if ((await sha256File(manifestAbs)) !== entry.runManifestSha256) {
- throw compileError(`Run manifest for ${direction} no longer matches its approved sha256`);
+ const manifestBytes = await readVerified(entry.runManifest, entry.runManifestSha256, `Run manifest for ${direction}`);
+ let manifest;
+ try {
+ manifest = JSON.parse(manifestBytes);
+ } catch {
+ manifest = null;
}
- const manifest = await readJSONFile(manifestAbs, null);
if (!manifest || manifest.direction !== direction) {
throw compileError(`Run manifest for ${direction} is unreadable or mislabeled`);
}
@@ -236,21 +218,20 @@ export async function validateForCompile(recordId) {
if (frames.length !== WALK_PHASES.length) {
throw compileError(`Direction ${direction} has ${frames.length} frames — expected ${WALK_PHASES.length}`);
}
+ const frameBytes = [];
for (let i = 0; i < frames.length; i++) {
if (frames[i].phase !== WALK_PHASES[i] || frames[i].outputIndex !== i) {
throw compileError(`Direction ${direction} frame ${i} is out of gait-phase order`);
}
- if ((await sha256File(join(dir, frames[i].path))) !== frames[i].sha256) {
- throw compileError(`Direction ${direction} frame ${frames[i].phase} no longer matches its packaged sha256`);
- }
+ frameBytes.push(await readVerified(frames[i].path, frames[i].sha256, `Direction ${direction} frame ${frames[i].phase}`));
}
- runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest };
+ runs[direction] = { runId: entry.runId, manifestPath: entry.runManifest, manifest, frameBytes };
}
return {
walkSet,
- walkSetPath: `walk/${recordId}-walk-set-v1.json`,
- walkSetSha256: await sha256File(walkSetAbs),
+ walkSetPath: walkSetRel,
+ walkSetSha256: sha256Buffer(walkSetBytes),
referenceManifest,
chromaKey,
anchors,
@@ -259,13 +240,12 @@ export async function validateForCompile(recordId) {
}
async function compileDirectionRow(recordId, direction, validated, geometry) {
- const dir = spriteDir(recordId);
const split = keyChannelSplit(validated.chromaKey);
- const { manifest, runId, manifestPath } = validated.runs[direction];
+ const { manifest, runId, manifestPath, frameBytes } = validated.runs[direction];
const walkSources = [];
- for (const frame of manifest.frames) {
- walkSources.push(await transparentSource(join(dir, frame.path), split, validated.chromaKey));
+ for (const bytes of frameBytes) {
+ walkSources.push(await transparentSource(bytes, split, validated.chromaKey));
}
const dims = walkSources.map((f, i) => occupiedDimensions(f, ALPHA_THRESHOLD, `${direction}-${WALK_PHASES[i]}`));
const directionScale = Math.min(
@@ -275,7 +255,7 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {
const cells = [];
const anchor = validated.anchors[direction];
- const idleSource = await transparentSource(anchor.abs, split, validated.chromaKey);
+ const idleSource = await transparentSource(anchor.bytes, split, validated.chromaKey);
const idleDims = occupiedDimensions(idleSource, SILHOUETTE_ALPHA_THRESHOLD, `${direction}-idle`);
const desiredIdleHeight = median(dims.map((d) => d.height)) * directionScale;
const idleScale = Math.min(desiredIdleHeight / idleDims.height, geometry.targetMaxWidth / idleDims.width);
@@ -297,9 +277,11 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {
cells.push({ column: frame.phase, ...normalized, sourcePath: frame.path, sourceSha256: frame.sha256 });
}
+ // Cell frames are read-only after normalization, so the scanner placeholder
+ // can share the idle cell's buffer outright.
cells.push({
column: 'scanner',
- cell: { ...idle.cell, data: Buffer.from(idle.cell.data) },
+ cell: idle.cell,
meta: idle.meta,
sourcePath: anchor.path,
sourceSha256: anchor.sha256,
@@ -375,6 +357,23 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
const validated = await validateForCompile(recordId);
const dir = spriteDir(recordId);
+ // Pre-pixel idempotency: the compile is deterministic, so an unchanged
+ // walk set + identical geometry means identical bytes by construction —
+ // skip the whole pixel pipeline. The evidence chain was still revalidated
+ // above; the post-encode sha comparison below stays as the fallback for a
+ // pointer whose geometry fields predate a shape change.
+ const current = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null);
+ if (
+ current
+ && current.walkSetSha256 === validated.walkSetSha256
+ && current.geometry?.cellSize === geometry.cellSize
+ && JSON.stringify(current.geometry?.pivot) === JSON.stringify(geometry.pivot)
+ && current.geometry?.targetMaxHeight === geometry.targetMaxHeight
+ && current.geometry?.targetMaxWidth === geometry.targetMaxWidth
+ ) {
+ return { ...current, created: false };
+ }
+
const rows = [];
for (const direction of SPRITE_DIRECTIONS) {
rows.push(await compileDirectionRow(recordId, direction, validated, geometry));
@@ -385,14 +384,13 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
const atlasHeight = cellSize * SPRITE_DIRECTIONS.length;
const atlas = { data: Buffer.alloc(atlasWidth * atlasHeight * 4), width: atlasWidth, height: atlasHeight };
for (let r = 0; r < rows.length; r++) {
- rows[r].cells.forEach((cell, c) => blitFrame(atlas, cell.cell, c * cellSize, r * cellSize));
+ rows[r].cells.forEach((cell, c) => compositeOnto(atlas, cell.cell, c * cellSize, r * cellSize));
}
const atlasBuffer = await sharp(atlas.data, { raw: { width: atlasWidth, height: atlasHeight, channels: 4 } })
.png()
.toBuffer();
const atlasSha256 = sha256Buffer(atlasBuffer);
- const current = await readJSONFile(join(dir, CURRENT_POINTER), null);
if (current && current.walkSetSha256 === validated.walkSetSha256 && current.atlasSha256 === atlasSha256) {
return { ...current, created: false };
}
@@ -465,7 +463,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
geometry: manifest.geometry,
compiledAt: manifest.createdAt,
};
- await atomicWrite(join(dir, CURRENT_POINTER), pointer);
+ await atomicWrite(join(dir, RUNTIME_POINTER_REL), pointer);
console.log(`🧩 sprite atlas compiled for ${recordId} → v${version}`);
return { ...pointer, created: true };
}
@@ -474,8 +472,8 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
export async function getAtlasState(recordId) {
const dir = spriteDir(recordId);
const [current, publications] = await Promise.all([
- readJSONFile(join(dir, CURRENT_POINTER), null),
- readJSONFile(join(dir, 'runtime/publications.json'), []),
+ readJSONFile(join(dir, RUNTIME_POINTER_REL), null),
+ readJSONFile(join(dir, RUNTIME_PUBLICATIONS_REL), []),
]);
return { current, publications: [...publications].reverse() };
}
diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.js
index e15ead65a6..aaebfa55ac 100644
--- a/server/services/sprites/paths.js
+++ b/server/services/sprites/paths.js
@@ -25,6 +25,12 @@ export function spriteDir(recordId) {
return join(PATHS.sprites, recordId);
}
+// Runtime-atlas layout (phase 4): the mutable current-selection pointer and
+// the append-only publish history, shared by atlas.js and publish.js so a
+// rename can't half-land.
+export const RUNTIME_POINTER_REL = 'runtime/current.json';
+export const RUNTIME_PUBLICATIONS_REL = 'runtime/publications.json';
+
/**
* Resolve a relative asset path inside a record's directory, refusing any
* path that escapes it (`..`, absolute paths).
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index db076ad467..36022cdd76 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -30,17 +30,18 @@ import {
import { ServerError } from '../../lib/errorHandler.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { getAppById } from '../apps.js';
-import { spriteDir } from './paths.js';
+import { isDeploying } from '../appDeployer.js';
+import { spriteDir, RUNTIME_PUBLICATIONS_REL } from './paths.js';
import { requireCharacter } from './reference.js';
import { updateRecord } from './records.js';
import { withWalkWriteTail } from './walk.js';
import { compileAtlasInTail } from './atlas.js';
-const PUBLICATIONS_REL = 'runtime/publications.json';
-
-// Per-app serialization: two records publishing into the same app repo queue
-// behind each other instead of interleaving reads/writes of the same tree.
-const appPublishTail = createKeyCachedQueue();
+// Per-repo serialization: keyed by the resolved repoPath (matching
+// appDeployer's `deployingApps` key), so two app records pointing at the
+// same checkout — or two characters publishing into one game — queue behind
+// each other instead of interleaving writes to the same tree.
+const repoPublishTail = createKeyCachedQueue();
const bindingError = (message, code) => new ServerError(message, { status: 400, code });
@@ -59,19 +60,27 @@ function anchorRepoPath(repoRoot, relPath, label) {
return abs;
}
+/**
+ * Resolve a binding's app and confirm its repoPath is a real directory.
+ * Shared by save-time validation (400) and publish time (409) so the two
+ * checks can't drift.
+ */
+async function requireAppRepo(appId, status) {
+ const app = await getAppById(appId);
+ if (!app) throw new ServerError(`Unknown app: ${appId}`, { status, code: 'UNKNOWN_APP' });
+ const repoStat = app.repoPath ? await stat(app.repoPath).catch(() => null) : null;
+ if (!repoStat?.isDirectory()) {
+ throw new ServerError(`App ${app.name || appId} has no accessible repoPath`, { status, code: 'APP_REPO_MISSING' });
+ }
+ return { app, repoRoot: app.repoPath };
+}
+
/** Validate a publishBinding shape (null clears it). */
export async function validatePublishBinding(binding) {
if (binding === null) return null;
const { appId, atlasDestPath, codeBinding } = binding;
- const app = await getAppById(appId);
- if (!app) throw bindingError(`Unknown app: ${appId}`, 'UNKNOWN_APP');
- if (!app.repoPath || !(await pathExists(app.repoPath))) {
- throw bindingError(`App ${app.name || appId} has no accessible repoPath`, 'APP_REPO_MISSING');
- }
+ const { app } = await requireAppRepo(appId, 400);
anchorRepoPath(app.repoPath, atlasDestPath, 'atlasDestPath');
- if (!atlasDestPath.toLowerCase().endsWith('.png')) {
- throw bindingError('atlasDestPath must point at a .png atlas file', 'INVALID_PUBLISH_PATH');
- }
if (codeBinding) {
anchorRepoPath(app.repoPath, codeBinding.path, 'codeBinding.path');
if (typeof codeBinding.resourcePath !== 'string' || !codeBinding.resourcePath.trim()) {
@@ -132,36 +141,38 @@ async function applyCodeBinding(repoRoot, codeBinding, previousResourcePath) {
/**
* Compile (idempotently) and publish the runtime atlas into the bound
- * managed app. Refuses without a binding, on a diverged destination, and on
- * code-binding drift. Idempotent: a destination already holding the current
- * atlas bytes records nothing and touches nothing.
+ * managed app. Refuses without a binding, on a diverged destination, on an
+ * occupied destination PortOS never published (unless explicitly
+ * acknowledged), and on code-binding drift. Idempotent: a destination
+ * already holding the current atlas bytes records nothing and touches
+ * nothing.
*/
-export function publishAtlas(recordId) {
- return withWalkWriteTail(recordId, () => publishAtlasImpl(recordId));
+export function publishAtlas(recordId, options = {}) {
+ return withWalkWriteTail(recordId, () => publishAtlasImpl(recordId, options));
}
-async function publishAtlasImpl(recordId) {
+async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {}) {
const record = await requireCharacter(recordId);
const binding = record.publishBinding;
if (!binding?.appId || !binding?.atlasDestPath) {
throw new ServerError('No publish binding configured — set the target app and atlas path first', { status: 409, code: 'PUBLISH_BINDING_REQUIRED' });
}
- const app = await getAppById(binding.appId);
- if (!app) throw new ServerError(`Bound app no longer exists: ${binding.appId}`, { status: 409, code: 'UNKNOWN_APP' });
- const repoRoot = app.repoPath;
- const repoStat = repoRoot ? await stat(repoRoot).catch(() => null) : null;
- if (!repoStat?.isDirectory()) {
- throw new ServerError(`App ${app.name || binding.appId} has no accessible repoPath`, { status: 409, code: 'APP_REPO_MISSING' });
- }
+ const { app, repoRoot } = await requireAppRepo(binding.appId, 409);
const compiled = await compileAtlasInTail(recordId);
- return appPublishTail(binding.appId, async () => {
+ return repoPublishTail(resolve(repoRoot), async () => {
+ // Don't mutate a tree a deploy is currently building from — appDeployer
+ // keys its lock by repoPath, so honor it here (the reverse direction —
+ // deploy checking publishes — isn't needed; publishes are sub-second).
+ if (isDeploying(repoRoot)) {
+ throw new ServerError(`App ${app.name || binding.appId} is deploying — retry when the deploy finishes`, { status: 409, code: 'APP_DEPLOY_IN_PROGRESS' });
+ }
const dir = spriteDir(recordId);
const destAbs = anchorRepoPath(repoRoot, binding.atlasDestPath, 'atlasDestPath');
const atlasBuffer = await readFile(join(dir, compiled.atlasPath));
- const publications = await readJSONFile(join(dir, PUBLICATIONS_REL), []);
+ const publications = await readJSONFile(join(dir, RUNTIME_PUBLICATIONS_REL), []);
const previous = [...publications].reverse().find(
(p) => p.appId === binding.appId && p.atlasDestPath === binding.atlasDestPath,
);
@@ -180,6 +191,15 @@ async function publishAtlasImpl(recordId) {
{ status: 409, code: 'PUBLISH_DEST_DIVERGED' },
);
}
+ // Never silently destroy bytes PortOS didn't write: a destination that
+ // already exists with no publication history needs an explicit overwrite
+ // acknowledgment from the caller.
+ if (!previous && destSha256 !== null && !acknowledgeOverwrite) {
+ throw new ServerError(
+ 'Destination already contains an atlas PortOS did not publish — confirm the overwrite to replace it.',
+ { status: 409, code: 'PUBLISH_DEST_OCCUPIED' },
+ );
+ }
// Verify/rewrite the code binding BEFORE replacing the atlas so a drifted
// binding aborts the publish with the game repo untouched.
@@ -202,7 +222,7 @@ async function publishAtlasImpl(recordId) {
codeBinding,
};
publications.push(publication);
- await atomicWrite(join(dir, PUBLICATIONS_REL), publications);
+ await atomicWrite(join(dir, RUNTIME_PUBLICATIONS_REL), publications);
console.log(`🚚 sprite atlas v${compiled.version} published for ${recordId} → ${app.name || binding.appId}:${binding.atlasDestPath}`);
return { published: true, publication, compiled };
});
diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.js
index b191e47422..c8d2049344 100644
--- a/server/services/sprites/publish.test.js
+++ b/server/services/sprites/publish.test.js
@@ -30,6 +30,9 @@ const getAppById = vi.fn(async (id) => (id === 'game-app'
: null));
vi.mock('../apps.js', () => ({ getAppById: (...args) => getAppById(...args) }));
+const isDeploying = vi.fn(() => false);
+vi.mock('../appDeployer.js', () => ({ isDeploying: (...args) => isDeploying(...args) }));
+
const compileAtlasInTail = vi.fn();
vi.mock('./atlas.js', () => ({
compileAtlasInTail: (...args) => compileAtlasInTail(...args),
@@ -61,6 +64,8 @@ const BINDING = { appId: 'game-app', atlasDestPath: 'assets/sprites/hero/hero-at
beforeEach(async () => {
getAppById.mockClear();
+ isDeploying.mockReset();
+ isDeploying.mockReturnValue(false);
compileAtlasInTail.mockReset();
rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
rmSync(APP_REPO, { recursive: true, force: true });
@@ -100,8 +105,7 @@ describe('validatePublishBinding / setPublishBinding', () => {
.rejects.toMatchObject({ code: 'INVALID_PUBLISH_PATH' });
await expect(validatePublishBinding({ ...BINDING, atlasDestPath: '/abs/path.png' }))
.rejects.toMatchObject({ code: 'INVALID_PUBLISH_PATH' });
- await expect(validatePublishBinding({ ...BINDING, atlasDestPath: 'assets/atlas.jpg' }))
- .rejects.toMatchObject({ code: 'INVALID_PUBLISH_PATH' });
+ // Non-.png destinations die at the route's Zod schema (spritePublishBindingSchema).
});
});
@@ -162,6 +166,28 @@ describe('publishAtlas', () => {
await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_DEST_DIVERGED' });
});
+ it('refuses an occupied destination it never published unless acknowledged', async () => {
+ const { id, atlasBytes } = await characterWithAtlas();
+ await setPublishBinding(id, BINDING);
+ await mkdir(join(APP_REPO, 'assets/sprites/hero'), { recursive: true });
+ await writeFile(join(APP_REPO, BINDING.atlasDestPath), 'hand-made-atlas-from-before-portos');
+
+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_DEST_OCCUPIED' });
+ // Explicit acknowledgment replaces it and records the prior sha.
+ const acked = await publishAtlas(id, { acknowledgeOverwrite: true });
+ expect(acked.published).toBe(true);
+ expect(acked.publication.destPreviousSha256).toBe(sha256(Buffer.from('hand-made-atlas-from-before-portos')));
+ expect((await readFile(join(APP_REPO, BINDING.atlasDestPath))).toString()).toBe(atlasBytes);
+ });
+
+ it('refuses to publish while the app is deploying', async () => {
+ const { id } = await characterWithAtlas();
+ await setPublishBinding(id, BINDING);
+ isDeploying.mockReturnValue(true);
+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'APP_DEPLOY_IN_PROGRESS' });
+ expect(isDeploying).toHaveBeenCalledWith(APP_REPO);
+ });
+
it('verifies the code binding by occurrence count and refuses drift', async () => {
const { id } = await characterWithAtlas();
const resource = 'res://assets/sprites/hero/hero-atlas.png';
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 9196b33620..5c7d76543c 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -38,7 +38,8 @@ import {
import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';
const selectionRelPath = (id) => `walk/${id}-walk-selection-v1.json`;
-const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;
+// Exported: atlas.js (phase 4) reads the finalized walk set as compile input.
+export const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;
const runRelPath = (runId) => `grok/${runId}`;
const RUN_RECORD_NAME = 'animation-run.json';
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
index 37d89a0022..7a22376f29 100644
--- a/server/services/sprites/walkPostprocess.js
+++ b/server/services/sprites/walkPostprocess.js
@@ -79,7 +79,7 @@ export function median(values) {
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
-const sha256Buffer = (buf) => createHash('sha256').update(buf).digest('hex');
+export const sha256Buffer = (buf) => createHash('sha256').update(buf).digest('hex');
/** Decode a PNG to a raw RGBA frame `{ data, width, height }`. */
export async function decodeRgbaFrame(src) {
@@ -320,13 +320,13 @@ export function selectCycleIndices(signatures) {
};
}
-/** Tight bbox of visible (alpha > 24) pixels; exclusive right/bottom. */
-export function alphaBbox(frame) {
+/** Tight bbox of visible (alpha > threshold) pixels; exclusive right/bottom. */
+export function alphaBbox(frame, threshold = BBOX_ALPHA_THRESHOLD) {
const { data, width, height } = frame;
let left = width; let top = height; let right = -1; let bottom = -1;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
- if (data[(y * width + x) * 4 + 3] > BBOX_ALPHA_THRESHOLD) {
+ if (data[(y * width + x) * 4 + 3] > threshold) {
if (x < left) left = x;
if (x > right) right = x;
if (y < top) top = y;
@@ -377,7 +377,7 @@ export async function premultipliedResize(frame, width, height) {
return { data, width, height };
}
-function compositeOnto(canvas, frame, dx, dy) {
+export function compositeOnto(canvas, frame, dx, dy) {
// Straight-alpha source-over; destinations may be clipped at canvas edges.
const { data, width, height } = frame;
for (let y = 0; y < height; y++) {