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): assert the sidecar destination before mutating the game source

[._.]/ Adam Eivy8c5a851c0e78
diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsx
index ecc6c409e2..6d4991413a 100644
--- a/client/src/components/sprites/PublishWorkflow.jsx
+++ b/client/src/components/sprites/PublishWorkflow.jsx
@@ -32,8 +32,11 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
const [codePath, setCodePath] = useState(saved?.codeBinding?.path || '');
const [resourcePath, setResourcePath] = useState(saved?.codeBinding?.resourcePath || '');
// null → idle; 'publish' → normal confirm; 'overwrite' → the server
- // refused with PUBLISH_DEST_OCCUPIED and needs explicit consent.
+ // refused with PUBLISH_DEST_OCCUPIED / PUBLISH_LAYOUT_OCCUPIED and needs
+ // explicit consent. occupiedFile names which file the consent is about, so
+ // the question doesn't say "atlas" when the blocker is the layout sidecar.
const [confirmStage, setConfirmStage] = useState(null);
+ const [occupiedFile, setOccupiedFile] = useState('atlas');
// Re-seed the form when the server-side binding changes (save round-trip)
// — and drop any pending confirmation: consent given for one destination
@@ -72,9 +75,11 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
const [publish, publishing] = useAsyncAction(async (acknowledgeOverwrite) => {
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') {
+ // The destination holds an atlas — or a layout sidecar — PortOS never
+ // published. Escalate to an explicit overwrite consent instead of
+ // toasting a dead end the UI offers no way to act on.
+ if (err?.code === 'PUBLISH_DEST_OCCUPIED' || err?.code === 'PUBLISH_LAYOUT_OCCUPIED') {
+ setOccupiedFile(err.code === 'PUBLISH_LAYOUT_OCCUPIED' ? 'layout' : 'atlas');
setConfirmStage('overwrite');
return null;
}
@@ -211,7 +216,9 @@ export default function PublishWorkflow({ record, walk, atlas, onChanged }) {
)}
{confirmStage === 'overwrite' && bindingSettled && (
<InlineConfirmRow
- question={`${destLabel} already contains an atlas PortOS did not publish. Overwrite it?`}
+ question={occupiedFile === 'layout'
+ ? `${destLabel} already has a layout sidecar PortOS did not write. Overwrite it?`
+ : `${destLabel} already contains an atlas PortOS did not publish. Overwrite it?`}
confirmText={publishing ? 'Publishing…' : 'Overwrite'}
tone="error"
onConfirm={() => { if (!publishing) publish(true); }}
diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.md
index 568075e8b4..21b0cf8471 100644
--- a/docs/features/sprite-export-contract.md
+++ b/docs/features/sprite-export-contract.md
@@ -12,7 +12,7 @@ The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell
|---|---|
| Cell size | 96 × 96 px (overridable per compile; the published geometry is whatever was compiled) |
| Pivot | `(48, 88)` — silhouette centered on x, feet on the y ground line |
-| Rows | 8, in `directionOrder`: S, SE, E, NE, N, NW, W, SW |
+| Rows | 8, in `directionOrder`: `south`, `south-east`, `east`, `north-east`, `north`, `north-west`, `west`, `south-west` |
| Columns | `idle` at 0, the N walk phases from 1, `scanner` last |
| N (walk frame count) | authorable, 6–16 (`walkBounds.js`); historically always 8 |
@@ -41,7 +41,7 @@ Nothing else crosses. The compile manifest, the run provenance, the trims, and t
"sourceAtlasSha256": "…",
"cellSize": 96,
"rows": 8,
- "rowOrder": ["S", "SE", "E", "NE", "N", "NW", "W", "SW"],
+ "rowOrder": ["south", "south-east", "east", "north-east", "north", "north-west", "west", "south-west"],
"columns": ["idle", "left-contact", "…", "right-up", "scanner"],
"columnCount": 10,
"tracks": {
@@ -60,7 +60,7 @@ Consumer guidance:
- **Resolve columns by name, not by constant.** `tracks` gives each animation track a column span, so a walk of any length — and any future track (a four-frame scanner action, a three-frame ambient loop) — is additive rather than a breaking re-read. `columns` is the flat list for anything that wants raw names.
- **Verify before you trust.** `sourceAtlasSha256` identifies the atlas the layout describes. The sidecar is written *before* the PNG on each publish, so a partially-completed publish is detectable (hash mismatch) rather than silent.
- **The sidecar carries no timestamp** — identical geometry produces byte-identical content, so an unchanged republish rewrites nothing.
-- The sidecar shares the PNG's per-repo write serialization and destination guards; an atlas whose sidecar was deleted gets it back on the next publish, and a file at that path PortOS didn't write (no `kind: portos-sprite-atlas-layout`) is never replaced without an explicit overwrite acknowledgment.
+- The sidecar shares the PNG's per-repo write serialization and its occupied-destination guard: an atlas whose sidecar was deleted gets it back on the next publish, and a file at that path PortOS didn't write (no `kind: portos-sprite-atlas-layout`, or not valid JSON at all) is never replaced without an explicit overwrite acknowledgment. It has no *divergence* guard — unlike the PNG, a PortOS-written sidecar someone hand-edited is simply regenerated, since it is derived data.
## Playback speed belongs to the consuming app
@@ -79,7 +79,7 @@ Two mechanisms guard that:
- **`publishBinding.runtimeContract`** (optional): `{ walkFrameCount, cellSize?, columnCount? }` — the grid the app was built against. Set it via `PUT /api/sprites/:id/publish-binding`. Publishing an atlas whose compiled geometry disagrees fails with a **409** naming both the actual and expected numbers and both resolutions (change the app's constant, or reprocess the walk set). A binding with no contract publishes unchecked, exactly as before the field existed.
- **The sidecar**, so an app that reads it can fail loudly on its own terms instead of relying on PortOS to have been asked.
-`runtimeContract` follows absent-vs-null semantics: a saved binding that omits the key inherits the stored contract (the publish form doesn't edit it), while an explicit `null` clears it.
+`runtimeContract` follows absent-vs-null semantics: a saved binding that omits the key inherits the stored contract (the publish form doesn't edit it), while an explicit `null` clears it. The inheritance is scoped to the same `appId` — re-pointing a character at a different app drops the old app's contract rather than holding the new one to it.
**A frame-count change is therefore a two-repo change.** Reprocess the walk set to the new count, update the app's frame-count constant *and* the distance/timing math derived from it, and update the contract — in whichever order, but neither half ships alone.
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index 1f2e253024..6fc4fa7667 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -151,12 +151,18 @@ export async function validatePublishBinding(binding) {
* publish form saves appId/dest/codeBinding only, and a form save must not
* silently drop the contract an app declared through the API. Pass
* `runtimeContract: null` to clear it, or `binding: null` to clear everything.
+ *
+ * The inheritance is scoped to the SAME app — a contract describes the grid one
+ * particular app was built against, so carrying it across a re-point would make
+ * every publish to the new app 409 against an expectation that app never
+ * declared (and, with no UI for the field, leave no way out).
*/
export async function setPublishBinding(recordId, binding) {
const record = await requireCharacter(recordId);
const validated = await validatePublishBinding(binding);
- if (validated && binding.runtimeContract === undefined) {
- validated.runtimeContract = record.publishBinding?.runtimeContract ?? null;
+ const stored = record.publishBinding;
+ if (validated && binding.runtimeContract === undefined && validated.appId === stored?.appId) {
+ validated.runtimeContract = stored.runtimeContract ?? null;
}
return updateRecord(recordId, { publishBinding: validated });
}
@@ -269,28 +275,33 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
// as the PNG, so the pair is never interleaved with another publish into
// the same checkout.
const layoutAbs = anchorRepoPath(repoRoot, layoutDestPath, 'atlas layout sidecar');
- // Write it only when the content actually differs, so a republish that
- // changes nothing stays a genuine no-op. Returns whether the repo was
- // mutated — an atlas already at the destination but MISSING its sidecar
- // still gets one, so the two can never be permanently out of step.
- //
+ const existingLayout = await readFile(layoutAbs).catch(() => null);
+ const layoutUpToDate = Boolean(existingLayout?.equals(layoutBuffer));
// Occupied-destination guard, mirroring the atlas's: PortOS owns files it
// stamped with its own `kind`, and will regenerate one freely, but a JSON
// file it never wrote sitting at that path is somebody else's — replacing
// it needs the same explicit acknowledgment replacing a foreign atlas does.
- const writeLayoutSidecar = async () => {
- const existing = await readFile(layoutAbs).catch(() => null);
- if (existing?.equals(layoutBuffer)) return false;
- // A malformed/non-JSON file at that path counts as foreign too — parse
- // failure must not become a 500, and must not license an overwrite.
- if (existing
- && safeJSONParse(existing.toString('utf8'))?.kind !== ATLAS_LAYOUT_KIND
- && !acknowledgeOverwrite) {
+ // A malformed/non-JSON file counts as foreign too: a parse failure must
+ // not become a 500, and must not license an overwrite.
+ //
+ // Split from the write and asserted BEFORE applyCodeBinding, which mutates
+ // the game's source file — a refusal after that rewrite would leave the
+ // source pointing at an atlas this publish then declined to write.
+ const assertLayoutDestWritable = () => {
+ if (layoutUpToDate || acknowledgeOverwrite || !existingLayout) return;
+ if (safeJSONParse(existingLayout.toString('utf8'))?.kind !== ATLAS_LAYOUT_KIND) {
throw new ServerError(
`${layoutDestPath} already exists and was not written by PortOS — confirm the overwrite to replace it.`,
{ status: 409, code: 'PUBLISH_LAYOUT_OCCUPIED' },
);
}
+ };
+ // Write only when the content actually differs, so a republish that changes
+ // nothing stays a genuine no-op. Returns whether the repo was mutated — an
+ // atlas already at the destination but MISSING its sidecar still gets one,
+ // so the two can never be permanently out of step.
+ const writeLayoutSidecar = async () => {
+ if (layoutUpToDate) return false;
await atomicWrite(layoutAbs, layoutBuffer);
return true;
};
@@ -337,6 +348,7 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
const destSha256 = (await pathExists(destAbs)) ? await sha256File(destAbs) : null;
if (destSha256 === compiled.atlasSha256) {
+ assertLayoutDestWritable();
// Verify the code binding even on a no-op so drift never hides.
const codeBinding = binding.codeBinding
? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath)
@@ -378,7 +390,9 @@ 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.
+ // binding aborts the publish with the game repo untouched — and assert the
+ // sidecar destination first, since that rewrite is itself a mutation.
+ assertLayoutDestWritable();
const codeBinding = binding.codeBinding
? await applyCodeBinding(repoRoot, binding.codeBinding, previousForCode?.codeBinding?.resourcePath)
: null;
diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.js
index 33dcc7113d..dad3c8ae19 100644
--- a/server/services/sprites/publish.test.js
+++ b/server/services/sprites/publish.test.js
@@ -29,9 +29,12 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
return actual;
});
-const getAppById = vi.fn(async (id) => (id === 'game-app'
- ? { id: 'game-app', name: 'Example Game', repoPath: APP_REPO }
- : null));
+const OTHER_APP_REPO = join(TEST_ROOT, 'other-game-repo');
+const APPS = {
+ 'game-app': { id: 'game-app', name: 'Example Game', repoPath: APP_REPO },
+ 'other-app': { id: 'other-app', name: 'Other Example Game', repoPath: OTHER_APP_REPO },
+};
+const getAppById = vi.fn(async (id) => APPS[id] || null);
vi.mock('../apps.js', () => ({ getAppById: (...args) => getAppById(...args) }));
const isDeploying = vi.fn(() => false);
@@ -49,7 +52,7 @@ const { walkPhaseLabels } = await import('./walkBounds.js');
let seq = 0;
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
-const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
+const { SPRITE_DIRECTIONS: DIRECTIONS } = await import('./prompts.js');
// The geometry block a real compile writes into the runtime pointer — the
// publish path reads it for the contract guard and the layout sidecar.
@@ -93,7 +96,9 @@ beforeEach(async () => {
compileAtlasInTail.mockReset();
rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
rmSync(APP_REPO, { recursive: true, force: true });
+ rmSync(OTHER_APP_REPO, { recursive: true, force: true });
await mkdir(APP_REPO, { recursive: true });
+ await mkdir(OTHER_APP_REPO, { recursive: true });
});
afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
@@ -170,6 +175,16 @@ describe('validatePublishBinding / setPublishBinding', () => {
const cleared = await setPublishBinding(id, { ...BINDING, runtimeContract: null });
expect(cleared.publishBinding.runtimeContract).toBeNull();
});
+
+ it('does not carry a contract across a re-point to a different app', async () => {
+ const { id } = await characterWithAtlas();
+ await setPublishBinding(id, { ...BINDING, runtimeContract: { walkFrameCount: 8 } });
+ // The contract describes the grid ONE app was built against — holding a
+ // different app to it would 409 every publish against an expectation it
+ // never declared.
+ const repointed = await setPublishBinding(id, { ...BINDING, appId: 'other-app' });
+ expect(repointed.publishBinding.runtimeContract).toBeNull();
+ });
});
describe('publishAtlas', () => {
@@ -517,6 +532,31 @@ describe('layout sidecar (#2982)', () => {
expect((await readSidecar(BINDING.atlasDestPath)).kind).toBe('portos-sprite-atlas-layout');
});
+ it('refuses an occupied sidecar BEFORE rewriting the game source', async () => {
+ const { id } = await characterWithAtlas();
+ const oldResource = 'res://assets/sprites/hero/old-name.png';
+ const newResource = 'res://assets/sprites/hero/hero-atlas.png';
+ await mkdir(join(APP_REPO, 'src'), { recursive: true });
+ const sourceBefore = `var atlas = load("${oldResource}");\n`;
+ await writeFile(join(APP_REPO, 'src/Hero.cs'), sourceBefore);
+ // A pending code-binding REWRITE (the previous publish recorded the old
+ // resource path) plus a foreign sidecar at the destination.
+ await setPublishBinding(id, {
+ appId: 'game-app',
+ atlasDestPath: 'assets/sprites/hero/old-name.png',
+ codeBinding: { path: 'src/Hero.cs', resourcePath: oldResource },
+ });
+ await publishAtlas(id);
+ await setPublishBinding(id, { ...BINDING, codeBinding: { path: 'src/Hero.cs', resourcePath: newResource } });
+ await writeFile(join(APP_REPO, sidecarPath(BINDING.atlasDestPath)), 'not even json');
+
+ await expect(publishAtlas(id)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_LAYOUT_OCCUPIED' });
+ // The refusal must land before applyCodeBinding mutates the game source —
+ // otherwise the source points at an atlas this publish declined to write.
+ expect(await readFile(join(APP_REPO, 'src/Hero.cs'), 'utf8')).toBe(sourceBefore);
+ expect(await readFile(join(APP_REPO, BINDING.atlasDestPath)).catch(() => null)).toBeNull();
+ });
+
it('refuses to publish an atlas whose geometry carries no column layout', async () => {
const { id } = await characterWithAtlas('atlas-png-bytes-nogeo', undefined);
compileAtlasInTail.mockResolvedValue({