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

address review (claude): legacy-import gate, publish evidence + baseline fixes

[._.]/ Adam Eivy1098a33542c7
diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsx
index fdad6aa7a8..ec973b5820 100644
--- a/client/src/components/sprites/PublishWorkflow.jsx
+++ b/client/src/components/sprites/PublishWorkflow.jsx
@@ -35,12 +35,15 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
// 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).
+ // Re-seed the form when the server-side binding changes (save round-trip)
+ // — and drop any pending confirmation: consent given for one destination
+ // must never carry over to a different binding.
useEffect(() => {
setAppId(saved?.appId || '');
setDestPath(saved?.atlasDestPath || '');
setCodePath(saved?.codeBinding?.path || '');
setResourcePath(saved?.codeBinding?.resourcePath || '');
+ setConfirmStage(null);
}, [saved?.appId, saved?.atlasDestPath, saved?.codeBinding?.path, saved?.codeBinding?.resourcePath]);
const [compile, compiling] = useAsyncAction(async () => {
@@ -64,8 +67,9 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
return result;
}, { errorMessage: 'Could not save the publish binding' });
+ // The confirm row stays mounted while the request is in flight (so the
+ // "Publishing…" label is actually visible) and clears on completion.
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
@@ -74,10 +78,17 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
setConfirmStage('overwrite');
return null;
}
+ setConfirmStage(null);
throw err;
});
if (result) {
- toast.success(result.published ? `Atlas v${result.publication.version} published` : 'Destination already up to date');
+ setConfirmStage(null);
+ const rewriteNote = result.codeBinding?.rewritten || result.publication?.codeBinding?.rewritten
+ ? ' — code binding rewritten to the new resource path'
+ : '';
+ toast.success(result.published
+ ? `Atlas v${result.publication.version} published${rewriteNote}`
+ : `Destination already up to date${rewriteNote}`);
onChanged?.();
}
return result;
@@ -85,13 +96,35 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
if (!finalized) return null;
+ // Phase-1 imported walk sets carry source-pipeline paths and no packaged
+ // frames — the server refuses to recompile them (LEGACY_IMPORTED_WALK_SET).
+ // Show why instead of offering a button that always fails.
+ if (walk.walkSet.selectionPath?.startsWith('art-source/')) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-1">
+ <h3 className="text-sm font-medium text-gray-200 flex items-center gap-2">
+ <Package size={16} className="text-port-accent" /> Runtime Atlas
+ </h3>
+ <p className="text-xs text-gray-500">
+ This walk set was imported from the source pipeline, which kept its packaged frames —
+ PortOS cannot recompile it. The imported runtime atlases remain in the asset library
+ below; to compile and publish from PortOS, run the walk workflow on a new character.
+ </p>
+ </div>
+ );
+ }
+
const bindingDirty = (saved?.appId || '') !== appId
|| (saved?.atlasDestPath || '') !== destPath.trim()
|| (saved?.codeBinding?.path || '') !== codePath.trim()
|| (saved?.codeBinding?.resourcePath || '') !== resourcePath.trim();
// Publish reads the SAVED binding server-side — gate on it, and hold while
- // a binding save is in flight so a click can't race the PUT.
- const canPublish = Boolean(saved?.appId && saved?.atlasDestPath) && !bindingDirty && !savingBinding && !publishing;
+ // a binding save is in flight so a click can't race the PUT. The confirm
+ // row uses bindingSettled (not canPublish) so it stays mounted while the
+ // publish itself is in flight, but disappears the moment the binding is
+ // edited — consent never carries across a binding change.
+ const bindingSettled = Boolean(saved?.appId && saved?.atlasDestPath) && !bindingDirty && !savingBinding;
+ const canPublish = bindingSettled && !publishing;
const boundApp = apps.find((a) => a.id === saved?.appId);
const destLabel = `${boundApp?.name || saved?.appId}: ${saved?.atlasDestPath}`;
@@ -166,21 +199,21 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
</button>
)}
</div>
- {confirmStage === 'publish' && (
+ {confirmStage === 'publish' && bindingSettled && (
<InlineConfirmRow
question={`Replace ${destLabel}?`}
confirmText={publishing ? 'Publishing…' : 'Publish'}
tone="warning"
- onConfirm={() => publish(false)}
+ onConfirm={() => { if (!publishing) publish(false); }}
onCancel={() => setConfirmStage(null)}
/>
)}
- {confirmStage === 'overwrite' && (
+ {confirmStage === 'overwrite' && bindingSettled && (
<InlineConfirmRow
question={`${destLabel} already contains an atlas PortOS did not publish. Overwrite it?`}
confirmText={publishing ? 'Publishing…' : 'Overwrite'}
tone="error"
- onConfirm={() => publish(true)}
+ onConfirm={() => { if (!publishing) publish(true); }}
onCancel={() => setConfirmStage(null)}
/>
)}
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 3d02572be0..a6e48b0859 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -29,7 +29,9 @@ import {
atomicWrite, ensureDir, pathExists, readJSONFile, tryReadFile,
} from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { spriteDir, RUNTIME_POINTER_REL, RUNTIME_PUBLICATIONS_REL } from './paths.js';
+import {
+ spriteDir, resolveSpriteAssetPath, 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';
@@ -153,18 +155,20 @@ async function normalizeCellFrame(source, scale, label, geometry) {
* reference set's anchors. Returns everything the compiler consumes.
*/
export async function validateForCompile(recordId) {
- const dir = spriteDir(recordId);
// 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).
+ // provably the pixels verified (no re-read between check and use). Paths
+ // come from server-owned manifests but still route through the record-dir
+ // confinement gate (resolveSpriteAssetPath) per the paths.js contract.
const readVerified = async (relPath, expectedSha, label) => {
- const bytes = await readFile(join(dir, relPath)).catch(() => null);
+ const bytes = await readFile(resolveSpriteAssetPath(recordId, relPath)).catch(() => null);
if (!bytes || sha256Buffer(bytes) !== expectedSha) {
throw compileError(`${label} no longer matches its recorded sha256`);
}
return bytes;
};
+ const dir = spriteDir(recordId);
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');
@@ -178,6 +182,21 @@ export async function validateForCompile(recordId) {
throw compileError('Walk set manifest is not a finalized eight-direction walk set');
}
if (walkSet.characterId !== recordId) throw compileError('Walk set characterId mismatch');
+ // Phase-1 imported walk sets are copied verbatim from the source pipeline:
+ // their paths are repo-root (`art-source/sprites/<id>/…`) and — decisively —
+ // the packaged per-frame PNGs were never imported (the importer skips
+ // frames/ to minimize copies). Recompiling them here is structurally
+ // impossible; say so plainly instead of a misleading tamper error. Their
+ // already-published runtime atlases were imported and remain browsable.
+ const legacyPrefix = 'art-source/';
+ if (
+ typeof walkSet.selectionPath === 'string' && walkSet.selectionPath.startsWith(legacyPrefix)
+ ) {
+ throw new ServerError(
+ 'This walk set was imported from the source pipeline — its packaged frames were not imported, so PortOS cannot recompile it. Imported runtime atlases remain available in the asset library; to compile here, run the walk workflow on a new character.',
+ { status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },
+ );
+ }
if (JSON.stringify(walkSet.directionOrder) !== JSON.stringify(SPRITE_DIRECTIONS)) {
throw compileError('Walk set direction order does not match the runtime contract');
}
@@ -362,9 +381,15 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
// 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.
+ // Both idempotent early-returns require the pointed-at atlas file to still
+ // exist — otherwise a deleted runtime/vN PNG would loop forever ("recompile"
+ // → pointer returned untouched → still missing); falling through re-writes
+ // the same version (nextAtlasVersion only counts versions whose PNG exists).
const current = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null);
+ const currentAtlasOnDisk = current ? await pathExists(join(dir, current.atlasPath)) : false;
if (
current
+ && currentAtlasOnDisk
&& current.walkSetSha256 === validated.walkSetSha256
&& current.geometry?.cellSize === geometry.cellSize
&& JSON.stringify(current.geometry?.pivot) === JSON.stringify(geometry.pivot)
@@ -391,7 +416,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
.toBuffer();
const atlasSha256 = sha256Buffer(atlasBuffer);
- if (current && current.walkSetSha256 === validated.walkSetSha256 && current.atlasSha256 === atlasSha256) {
+ if (current && currentAtlasOnDisk && current.walkSetSha256 === validated.walkSetSha256 && current.atlasSha256 === atlasSha256) {
return { ...current, created: false };
}
@@ -404,6 +429,32 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
await ensureDir(join(dir, versionRel));
await writeImmutable(join(dir, atlasRel), atlasBuffer);
+ // Self-heal: when re-writing a version whose PNG was deleted, the version's
+ // manifest usually survives — reuse it verbatim when it vouches for these
+ // exact atlas bytes, since a freshly-built one would differ only in
+ // createdAt and trip the immutable-write refusal.
+ const manifestAbs = join(dir, manifestRel);
+ const survivingManifest = await readJSONFile(manifestAbs, null);
+ if (survivingManifest?.atlasSha256 === atlasSha256) {
+ const survivingBuffer = await readFile(manifestAbs);
+ const pointer = {
+ schemaVersion: 1,
+ kind: 'runtime-atlas-selection',
+ characterId: recordId,
+ version,
+ atlasPath: atlasRel,
+ atlasSha256,
+ manifestPath: manifestRel,
+ manifestSha256: sha256Buffer(survivingBuffer),
+ walkSetSha256: validated.walkSetSha256,
+ geometry: survivingManifest.geometry,
+ compiledAt: survivingManifest.createdAt,
+ };
+ await atomicWrite(join(dir, RUNTIME_POINTER_REL), pointer);
+ console.log(`🧩 sprite atlas re-materialized for ${recordId} → v${version}`);
+ return { ...pointer, created: true };
+ }
+
const manifest = {
schemaVersion: 1,
kind: 'reviewed-walk-set-runtime-atlas',
@@ -448,7 +499,7 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
})),
};
const manifestBuffer = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
- await writeImmutable(join(dir, manifestRel), manifestBuffer);
+ await writeImmutable(manifestAbs, manifestBuffer);
const pointer = {
schemaVersion: 1,
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index e57d5067e1..b89b752184 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -250,6 +250,24 @@ describe('compileAtlas', () => {
expect(meta.height).toBe(64 * 8);
});
+ it('refuses an imported legacy walk set with an explicit code (not a tamper error)', async () => {
+ const id = await finalizedCharacter();
+ const setAbs = join(TEST_ROOT, 'sprites', id, `walk/${id}-walk-set-v1.json`);
+ const walkSet = JSON.parse(await readFile(setAbs, 'utf8'));
+ walkSet.selectionPath = `art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`;
+ await writeFile(setAbs, JSON.stringify(walkSet));
+ await expect(compileAtlas(id)).rejects.toMatchObject({ status: 409, code: 'LEGACY_IMPORTED_WALK_SET' });
+ });
+
+ it('self-heals a deleted versioned atlas instead of returning a dangling pointer', async () => {
+ const id = await finalizedCharacter();
+ const first = await compileAtlas(id);
+ rmSync(join(TEST_ROOT, 'sprites', id, first.atlasPath));
+ const again = await compileAtlas(id);
+ expect(again.version).toBe(first.version); // re-writes the same version, not a new one
+ expect(await readFile(join(TEST_ROOT, 'sprites', id, first.atlasPath))).toBeTruthy();
+ });
+
it('rejects geometry whose content bounds cannot fit the cell', async () => {
const id = await finalizedCharacter();
await expect(compileAtlas(id, { geometry: { cellSize: 64, targetMaxWidth: 64 } }))
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index 36022cdd76..a850439444 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -31,11 +31,12 @@ import { ServerError } from '../../lib/errorHandler.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { getAppById } from '../apps.js';
import { isDeploying } from '../appDeployer.js';
-import { spriteDir, RUNTIME_PUBLICATIONS_REL } from './paths.js';
+import { spriteDir, RUNTIME_POINTER_REL, 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';
+import { sha256Buffer } from './walkPostprocess.js';
// Per-repo serialization: keyed by the resolved repoPath (matching
// appDeployer's `deployingApps` key), so two app records pointing at the
@@ -159,7 +160,20 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
}
const { app, repoRoot } = await requireAppRepo(binding.appId, 409);
- const compiled = await compileAtlasInTail(recordId);
+ const dir = spriteDir(recordId);
+ // Reuse the current pointer's geometry so publish ships the atlas the user
+ // compiled and previewed — a bare default-geometry recompile would silently
+ // discard a custom-geometry compile and flip the pointer back to defaults.
+ const pointer = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null);
+ const geometryOverride = pointer?.geometry
+ ? {
+ cellSize: pointer.geometry.cellSize,
+ pivot: pointer.geometry.pivot,
+ targetMaxHeight: pointer.geometry.targetMaxHeight,
+ targetMaxWidth: pointer.geometry.targetMaxWidth,
+ }
+ : undefined;
+ const compiled = await compileAtlasInTail(recordId, { geometry: geometryOverride });
return repoPublishTail(resolve(repoRoot), async () => {
// Don't mutate a tree a deploy is currently building from — appDeployer
@@ -168,22 +182,64 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
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 atlasBuffer = await readFile(join(dir, compiled.atlasPath)).catch(() => null);
+ if (!atlasBuffer) {
+ throw new ServerError('Compiled atlas file is missing on disk — recompile before publishing', { status: 422, code: 'ATLAS_OUTPUT_MISSING' });
+ }
+ // The only path that writes outside data/ ships exactly the bytes the
+ // evidence chain vouched for — never a tampered runtime/vN file.
+ if (sha256Buffer(atlasBuffer) !== compiled.atlasSha256) {
+ throw new ServerError('Compiled atlas bytes no longer match their recorded sha256 — recompile before publishing', { status: 422, code: 'ATLAS_OUTPUT_TAMPERED' });
+ }
const publications = await readJSONFile(join(dir, RUNTIME_PUBLICATIONS_REL), []);
const previous = [...publications].reverse().find(
(p) => p.appId === binding.appId && p.atlasDestPath === binding.atlasDestPath,
);
+ // The code-binding baseline follows the FILE, not the destination — a
+ // destination move changes atlasDestPath, and the rewrite exists exactly
+ // for that case, so a dest-keyed lookup would never find the old
+ // resource path to rewrite from.
+ const previousForCode = binding.codeBinding
+ ? [...publications].reverse().find(
+ (p) => p.appId === binding.appId && p.codeBinding?.path === binding.codeBinding.path,
+ )
+ : null;
+
+ const recordPublication = async (extra) => {
+ const publication = {
+ publishedAt: new Date().toISOString(),
+ characterId: recordId,
+ version: compiled.version,
+ atlasPath: compiled.atlasPath,
+ atlasSha256: compiled.atlasSha256,
+ appId: binding.appId,
+ appName: app.name || null,
+ atlasDestPath: binding.atlasDestPath,
+ ...extra,
+ };
+ publications.push(publication);
+ await atomicWrite(join(dir, RUNTIME_PUBLICATIONS_REL), publications);
+ return publication;
+ };
const destSha256 = (await pathExists(destAbs)) ? await sha256File(destAbs) : null;
if (destSha256 === compiled.atlasSha256) {
// Verify the code binding even on a no-op so drift never hides.
const codeBinding = binding.codeBinding
- ? await applyCodeBinding(repoRoot, binding.codeBinding, previous?.codeBinding?.resourcePath)
+ ? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath)
: null;
- return { published: false, upToDate: true, compiled, codeBinding };
+ // The destination already holds the current bytes, but two sub-cases
+ // still mutate durable state and must be recorded: a code-binding
+ // rewrite just changed the game's source, and a first-ever publish
+ // finding its own bytes needs a history baseline (otherwise the next
+ // changed-atlas publish reads the dest as foreign and 409s OCCUPIED).
+ let publication = null;
+ if ((codeBinding?.rewritten || !previous)) {
+ publication = await recordPublication({ destPreviousSha256: destSha256, codeBinding, upToDateBaseline: true });
+ }
+ return { published: false, upToDate: true, compiled, codeBinding, publication };
}
if (previous && destSha256 !== null && destSha256 !== previous.atlasSha256) {
throw new ServerError(
@@ -204,25 +260,12 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
// Verify/rewrite the code binding BEFORE replacing the atlas so a drifted
// binding aborts the publish with the game repo untouched.
const codeBinding = binding.codeBinding
- ? await applyCodeBinding(repoRoot, binding.codeBinding, previous?.codeBinding?.resourcePath)
+ ? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath)
: null;
await atomicWrite(destAbs, atlasBuffer);
- const publication = {
- publishedAt: new Date().toISOString(),
- characterId: recordId,
- version: compiled.version,
- atlasPath: compiled.atlasPath,
- atlasSha256: compiled.atlasSha256,
- appId: binding.appId,
- appName: app.name || null,
- atlasDestPath: binding.atlasDestPath,
- destPreviousSha256: destSha256,
- codeBinding,
- };
- publications.push(publication);
- await atomicWrite(join(dir, RUNTIME_PUBLICATIONS_REL), publications);
+ const publication = await recordPublication({ destPreviousSha256: destSha256, codeBinding });
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 c8d2049344..7c57d51a7c 100644
--- a/server/services/sprites/publish.test.js
+++ b/server/services/sprites/publish.test.js
@@ -215,28 +215,87 @@ describe('publishAtlas', () => {
expect((await readFile(join(APP_REPO, BINDING.atlasDestPath))).toString()).toBe('atlas-png-bytes-v1');
});
- it('rewrites an occurrence-guarded moved resource path', async () => {
+ it('rewrites the code binding on a real destination move (baseline follows the file, not the dest)', async () => {
const { id } = await characterWithAtlas();
- const oldResource = 'res://assets/sprites/hero/old-atlas.png';
- const newResource = 'res://assets/sprites/hero/hero-atlas.png';
+ const oldResource = 'res://assets/sprites/hero/old-name.png';
+ const newResource = 'res://assets/sprites/hero/new-name.png';
await mkdir(join(APP_REPO, 'src'), { recursive: true });
await writeFile(join(APP_REPO, 'src/Hero.cs'), `var atlas = load("${oldResource}");\n`);
- // Simulate a previous publish that recorded the old resource path.
await setPublishBinding(id, {
- ...BINDING,
+ appId: 'game-app',
+ atlasDestPath: 'assets/sprites/hero/old-name.png',
codeBinding: { path: 'src/Hero.cs', resourcePath: oldResource },
});
await publishAtlas(id);
- // Destination moved: same dest bytes, new resource path in the binding.
+ // Real move: atlasDestPath AND resourcePath both change. The code-binding
+ // baseline must be found via the file (appId + codeBinding.path), because
+ // no publication exists for the NEW destination yet.
await setPublishBinding(id, {
- ...BINDING,
+ appId: 'game-app',
+ atlasDestPath: 'assets/sprites/hero/new-name.png',
codeBinding: { path: 'src/Hero.cs', resourcePath: newResource },
});
const result = await publishAtlas(id);
- expect(result.published).toBe(false); // dest bytes unchanged — binding-only fix
- expect(result.codeBinding).toMatchObject({ rewritten: true, previousResourcePath: oldResource });
+ expect(result.published).toBe(true);
+ expect(result.publication.codeBinding).toMatchObject({ rewritten: true, previousResourcePath: oldResource });
expect(await readFile(join(APP_REPO, 'src/Hero.cs'), 'utf8')).toContain(newResource);
});
+
+ it('records a publication when an up-to-date publish rewrites the code binding', async () => {
+ const { id } = await characterWithAtlas();
+ const oldResource = 'res://assets/sprites/hero/old-atlas.png';
+ const newResource = 'res://assets/sprites/hero/hero-atlas.png';
+ await mkdir(join(APP_REPO, 'src'), { recursive: true });
+ await writeFile(join(APP_REPO, 'src/Hero.cs'), `var atlas = load("${oldResource}");\n`);
+ await setPublishBinding(id, { ...BINDING, codeBinding: { path: 'src/Hero.cs', resourcePath: oldResource } });
+ await publishAtlas(id);
+
+ // Same dest bytes, new resource path → binding-only fix, but the game
+ // source WAS mutated, so history must say so.
+ await setPublishBinding(id, { ...BINDING, codeBinding: { path: 'src/Hero.cs', resourcePath: newResource } });
+ const result = await publishAtlas(id);
+ expect(result.published).toBe(false);
+ expect(result.codeBinding).toMatchObject({ rewritten: true, previousResourcePath: oldResource });
+ expect(result.publication).toMatchObject({ upToDateBaseline: true });
+ const history = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runtime/publications.json'), 'utf8'));
+ expect(history).toHaveLength(2);
+ // The recorded baseline lets a THIRD publish see the current resource path.
+ const third = await publishAtlas(id);
+ expect(third.published).toBe(false);
+ expect(third.codeBinding).toMatchObject({ rewritten: false });
+ });
+
+ it('seeds a history baseline when the first publish finds its own bytes already at the destination', 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), atlasBytes);
+
+ const first = await publishAtlas(id);
+ expect(first.upToDate).toBe(true);
+ expect(first.publication).toMatchObject({ upToDateBaseline: true });
+
+ // A later changed atlas now reads as DIVERGED-checkable, not OCCUPIED.
+ const nextBytes = 'atlas-png-bytes-v2';
+ const nextRel = `runtime/v2/${id}-animation-atlas-v2.png`;
+ await mkdir(join(TEST_ROOT, 'sprites', id, 'runtime/v2'), { recursive: true });
+ await writeFile(join(TEST_ROOT, 'sprites', id, nextRel), nextBytes);
+ compileAtlasInTail.mockResolvedValue({
+ created: true, version: 2, atlasPath: nextRel, atlasSha256: sha256(Buffer.from(nextBytes)),
+ });
+ const second = await publishAtlas(id);
+ expect(second.published).toBe(true);
+ });
+
+ it('refuses to ship a tampered or missing compiled atlas file', async () => {
+ const { id, atlasRel } = await characterWithAtlas();
+ await setPublishBinding(id, BINDING);
+ await writeFile(join(TEST_ROOT, 'sprites', id, atlasRel), 'tampered-after-compile');
+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 422, code: 'ATLAS_OUTPUT_TAMPERED' });
+ rmSync(join(TEST_ROOT, 'sprites', id, atlasRel));
+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 422, code: 'ATLAS_OUTPUT_MISSING' });
+ expect(await readFile(join(APP_REPO, BINDING.atlasDestPath)).catch(() => null)).toBeNull();
+ });
});