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

fix: preserve sprite alpha variation semantics (#4654)

[._.]/ Adam Eivy1dd755ce2bfa
diff --git a/server/lib/README.md b/server/lib/README.md
index dccbb5951f..f44f52b3e4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -163,7 +163,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
-| `borderKey.js` | Sharp-free image primitives shared by sprites and image-to-3D: statistics median, subsampled border-band sampling, solid-border coverage detection, and meaningful-alpha checks. |
+| `borderKey.js` | Sharp-free image primitives shared by sprites and image-to-3D: statistics median, subsampled border-band sampling, solid-border coverage detection, and alpha meaningfulness/variation checks. |
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `loadAllResult` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. `loadAll` silently drops corrupt records; `loadAllResult()` → `{ records, failedIds }` keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. |
| `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. |
diff --git a/server/lib/borderKey.js b/server/lib/borderKey.js
index 44272156e5..33d7d5cc9c 100644
--- a/server/lib/borderKey.js
+++ b/server/lib/borderKey.js
@@ -93,3 +93,13 @@ export function hasMeaningfulAlpha(data, alphaThreshold = 250) {
}
return false;
}
+
+/** Whether an RGBA buffer's alpha channel varies between pixels. */
+export function hasAlphaVariation(data) {
+ if (data.length < 4) return false;
+ const first = data[3];
+ for (let i = 7; i < data.length; i += 4) {
+ if (data[i] !== first) return true;
+ }
+ return false;
+}
diff --git a/server/lib/borderKey.test.js b/server/lib/borderKey.test.js
index 85978d7010..388f8fd6d5 100644
--- a/server/lib/borderKey.test.js
+++ b/server/lib/borderKey.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
detectSolidBorderColor,
+ hasAlphaVariation,
hasMeaningfulAlpha,
median,
sampleBorderKey,
@@ -44,4 +45,9 @@ describe('borderKey', () => {
expect(hasMeaningfulAlpha(almostOpaque.data, 255)).toBe(true);
expect(hasMeaningfulAlpha(makeFrame(2, 1, () => [0, 0, 0, 255]).data)).toBe(false);
});
+
+ it('keeps uniform near-opaque alpha out of the variation path', () => {
+ expect(hasAlphaVariation(makeFrame(2, 1, () => [0, 0, 0, 254]).data)).toBe(false);
+ expect(hasAlphaVariation(makeFrame(2, 1, (x) => [0, 0, 0, x ? 255 : 254]).data)).toBe(true);
+ });
});
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
index 0228785ff8..cbf574822c 100644
--- a/server/services/sprites/walkPostprocess.js
+++ b/server/services/sprites/walkPostprocess.js
@@ -24,7 +24,7 @@ import { join } from 'path';
import { readdir, writeFile } from 'fs/promises';
import { createHash } from 'crypto';
import {
- hasMeaningfulAlpha,
+ hasAlphaVariation,
median,
sampleBorderKey as sampleBorderKeyShared,
} from '../../lib/borderKey.js';
@@ -128,7 +128,7 @@ export const sha256Buffer = (buf) => createHash('sha256').update(buf).digest('he
export async function decodeTransparentSpriteSource(src, split, keyHex) {
const frame = await decodeRgbaFrame(src);
const { data } = frame;
- if (hasMeaningfulAlpha(data, 255)) return despillKeyFrame(frame, split);
+ if (hasAlphaVariation(data)) return despillKeyFrame(frame, split);
const measured = sampleBorderKey(frame);
validateMeasuredKey(measured, split, keyHex);
return despillKeyFrame(recoverAlphaFrame(frame, measured, split), split);
diff --git a/server/services/sprites/walkPostprocess.test.js b/server/services/sprites/walkPostprocess.test.js
index 8dc6921d22..5ec17119e0 100644
--- a/server/services/sprites/walkPostprocess.test.js
+++ b/server/services/sprites/walkPostprocess.test.js
@@ -16,7 +16,8 @@ import {
recoverAlphaFrame, despillKeyFrame, imageDistance, selectCycleIndices, selectAmbientLoopIndices,
alphaBbox, rootX, robustBottomRow, alignFrames, packStrip, validateFrames, buildContrastSheet,
rootBandForManifest, ROOT_BAND_TORSO, ROOT_BAND_HIP, ALIGN_OP_TORSO_X,
- prepareWalkAnchorChromaInput, WALK_PHASES, WALK_CELL_SIZE, WALK_FRAME_COUNT,
+ decodeTransparentSpriteSource, prepareWalkAnchorChromaInput,
+ WALK_PHASES, WALK_CELL_SIZE, WALK_FRAME_COUNT,
} from './walkPostprocess.js';
import { keyChannelSplit } from './chromaKey.js';
@@ -95,6 +96,27 @@ describe('sampleBorderKey / validateMeasuredKey', () => {
});
});
+describe('decodeTransparentSpriteSource', () => {
+ it('recovers a uniform near-opaque chroma matte', async () => {
+ const width = 20; const height = 20;
+ const rgba = Buffer.alloc(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const i = (y * width + x) * 4;
+ const [r, g, b] = x >= 5 && x < 15 && y >= 5 && y < 15
+ ? [30, 110, 60]
+ : [255, 0, 255];
+ rgba[i] = r; rgba[i + 1] = g; rgba[i + 2] = b; rgba[i + 3] = 254;
+ }
+ }
+ const source = join(TEST_ROOT, 'uniform-near-opaque.png');
+ await sharp(rgba, { raw: { width, height, channels: 4 } }).png().toFile(source);
+ const result = await decodeTransparentSpriteSource(source, MAGENTA, '#FF00FF');
+ expect(result.data[3]).toBe(0);
+ expect(result.data[(10 * width + 10) * 4 + 3]).toBe(255);
+ });
+});
+
describe('longestUsableSpan', () => {
it('finds the longest contiguous run of usable frames', () => {
// A leading black intro frame + a trailing one, good frames between.