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): normalize alpha thresholds across PNG depths

[._.]/ Adam Eivy89e49d49d22a
diff --git a/server/lib/README.md b/server/lib/README.md
index 40dc1e1663..c47c48e88b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -175,7 +175,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
| `fileWriteQueue.js` | Serialize read-modify-write cycles so they don't interleave. `createFileWriteQueue()` → single-tail `queue(fn)` for one shared file; `createRecordWriteQueue(assertId?)` → id-keyed `queueRecordWrite(id, fn)` where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for `collectionStore.queueRecordWrite` parity); `createKeyedFileWriteQueue()` → `queueKeyedWrite(key, fn)` that collapses the pipeline stage stores' hand-rolled `Map` + per-key `createFileWriteQueue` factory (falsy keys → shared `'__unknown__'` tail; self-pruning via `createKeyCachedQueue`). |
| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |
-| `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`). Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). |
+| `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`), except when a non-opaque alpha channel carries a substantial silhouette itself. Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). |
| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
diff --git a/server/lib/imageFrameStats.js b/server/lib/imageFrameStats.js
index 6b7f5bcbe9..e43fd823f7 100644
--- a/server/lib/imageFrameStats.js
+++ b/server/lib/imageFrameStats.js
@@ -55,13 +55,14 @@ export const MIN_JUDGEABLE_PIXELS = 256;
// Match NEAR_EMPTY_ENTROPY_FLOOR's roughly 0.5% signal floor for alpha-only
// silhouettes. Both visible and transparent coverage must clear this floor;
// a couple of transparent holes in an otherwise flat opaque sheet are not a
-// meaningful silhouette.
-export const ALPHA_COVERAGE_FLOOR = 255 * 0.005;
+// meaningful silhouette. Keep this unitless because Sharp reports 16-bit PNG
+// channel stats on a 0-65535 scale.
+export const ALPHA_COVERAGE_FRACTION_FLOOR = 0.005;
// A silhouette needs a substantial minority of the alpha distribution to be
// present, not merely one-pixel speckle. This is the binary-mask stdev for a
// 5% minority and keeps alpha noise from rescuing a flat colour fill.
-export const ALPHA_SILHOUETTE_STDEV_FLOOR = 255 * Math.sqrt(0.05 * 0.95);
+export const ALPHA_SILHOUETTE_STDEV_FRACTION_FLOOR = Math.sqrt(0.05 * 0.95);
export const FRAME_REASON = {
SOLID_FILL: 'solid-fill',
@@ -130,13 +131,16 @@ export async function describeFrameStats(input) {
// alpha variance is content, unlike a fully opaque alpha channel, which is
// just the normal PNG case and must not rescue a flat fill.
const alpha = metadata.hasAlpha ? perChannel[perChannel.length - 1] : null;
+ const alphaMax = metadata.depth === 'ushort' ? 65535 : 255;
+ const alphaMeanFraction = alpha ? alpha.mean / alphaMax : 0;
+ const alphaStdevFraction = alpha ? alpha.stdev / alphaMax : 0;
const alphaCarriesContent = Boolean(
alpha
&& !stats.isOpaque
&& alpha.max > alpha.min
- && alpha.stdev >= ALPHA_SILHOUETTE_STDEV_FLOOR
- && alpha.mean >= ALPHA_COVERAGE_FLOOR
- && alpha.mean <= 255 - ALPHA_COVERAGE_FLOOR,
+ && alphaStdevFraction >= ALPHA_SILHOUETTE_STDEV_FRACTION_FLOOR
+ && alphaMeanFraction >= ALPHA_COVERAGE_FRACTION_FLOOR
+ && alphaMeanFraction <= 1 - ALPHA_COVERAGE_FRACTION_FLOOR,
);
// Only the colour channels decide "flat" — a fully-OPAQUE alpha channel is
diff --git a/server/lib/imageFrameStats.test.js b/server/lib/imageFrameStats.test.js
index 7c99ddc505..6efdedcb77 100644
--- a/server/lib/imageFrameStats.test.js
+++ b/server/lib/imageFrameStats.test.js
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest';
import sharp from 'sharp';
+import { deflateSync } from 'zlib';
+import { crc32 } from './zipWriter.js';
import {
describeFrameStats,
isDegenerateFrame,
@@ -28,6 +30,46 @@ const fromPixels = (fill, { channels = 3, width = SIDE, height = SIDE } = {}) =>
return sharp(raw, { raw: { width, height, channels } }).png().toBuffer();
};
+const pngChunk = (typeName, data) => {
+ const type = Buffer.from(typeName);
+ const chunk = Buffer.alloc(12 + data.length);
+ chunk.writeUInt32BE(data.length, 0);
+ type.copy(chunk, 4);
+ data.copy(chunk, 8);
+ chunk.writeUInt32BE(crc32(Buffer.concat([type, data])), 8 + data.length);
+ return chunk;
+};
+
+// Sharp's test fixtures are 8-bit by default; this keeps the depth-aware
+// sentinel covered without committing a binary asset.
+const rgba16Png = (alphaAt) => {
+ const width = SIDE;
+ const height = SIDE;
+ const rowBytes = 1 + width * 4 * 2;
+ const raw = Buffer.alloc(height * rowBytes);
+ for (let y = 0; y < height; y++) {
+ const row = y * rowBytes;
+ for (let x = 0; x < width; x++) {
+ const pixel = row + 1 + x * 8;
+ raw.writeUInt16BE(0, pixel);
+ raw.writeUInt16BE(0, pixel + 2);
+ raw.writeUInt16BE(0, pixel + 4);
+ raw.writeUInt16BE(alphaAt(x, y), pixel + 6);
+ }
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 16;
+ ihdr[9] = 6;
+ return Buffer.concat([
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
+ pngChunk('IHDR', ihdr),
+ pngChunk('IDAT', deflateSync(raw)),
+ pngChunk('IEND', Buffer.alloc(0)),
+ ]);
+};
+
describe('describeFrameStats', () => {
it('rejects a solid black frame as a flat fill', async () => {
const stats = await describeFrameStats(await solid({ r: 0, g: 0, b: 0 }));
@@ -129,6 +171,21 @@ describe('describeFrameStats', () => {
expect(stats.reason).toBe(FRAME_REASON.SOLID_FILL);
});
+ it('ACCEPTS a 16-bit alpha silhouette', async () => {
+ const stats = await describeFrameStats(await rgba16Png((x, y) => (
+ x >= 20 && x < 44 && y >= 20 && y < 44 ? 65535 : 0
+ )));
+ expect(stats.ok).toBe(true);
+ });
+
+ it('rejects a sparse 16-bit alpha frame', async () => {
+ const stats = await describeFrameStats(await rgba16Png((x, y) => (
+ x === 0 && y < 12 ? 65535 : 0
+ )));
+ expect(stats.ok).toBe(false);
+ expect(stats.reason).toBe(FRAME_REASON.SOLID_FILL);
+ });
+
it('rejects a near-empty frame whose single stray pixel leaves entropy at the floor', async () => {
const buf = await fromPixels((x, y) => (x === 0 && y === 0 ? [255, 255, 255] : [0, 0, 0]));
const stats = await describeFrameStats(buf);