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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (agy): never memoize an unmeasurable verdict
Adam Eivy17afc00e158a
diff --git a/server/lib/README.md b/server/lib/README.mdindex 772ced803d..64e59847db 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -247,7 +247,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`), 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). A **buffer** verdict is memoized on the sha256 of its bytes (#6004) — the probe costs ~4ms regardless of pixel count and the sprite compiler re-probes identical frames dozens of times per run; a **path** is never memoized (the file behind it can change), so hand it bytes you already read. `__resetFrameStatsCache()` drops the memo in tests. |+| `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). A **buffer** verdict is memoized on the sha256 of its bytes (#6004) — the probe costs ~4ms regardless of pixel count and the sprite compiler re-probes identical frames dozens of times per run; a **path** is never memoized (the file behind it can change), so hand it bytes you already read. `stats-unavailable` is never memoized either — that branch catches transient probe failures too, and pinning `ok: null` on valid bytes would disable the gate for them. `__resetFrameStatsCache()` drops the memo in tests. || `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.cache.test.js b/server/lib/imageFrameStats.cache.test.jsindex e9b9782690..abfea38e0d 100644--- a/server/lib/imageFrameStats.cache.test.js+++ b/server/lib/imageFrameStats.cache.test.js@@ -12,7 +12,7 @@* invisible in behavior and only shows up as CI wall time, so it is asserted* directly rather than left to a timing threshold.*/-import { describe, it, expect, beforeEach, vi } from 'vitest';+import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest';import { mkdtempSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -105,17 +105,40 @@ describe('describeFrameStats memo', () => {// actually re-measuring. Off for this test so the assertion is about OUR// memo — and note libvips' cache is per-process and short-lived, unlike an// hour-long path-keyed memo, which is why one is tolerable and the other- // would be a correctness bug.+ // would be a correctness bug. Restored from a teardown, not inline: a+ // failing assertion would otherwise leave libvips uncached for every later+ // test in this worker and leak the tmpdir.sharp.cache(false);+ onTestFinished(() => {+ sharp.cache(true);+ rmSync(dir, { recursive: true, force: true });+ });const degenerate = await describeFrameStats(framePath);writeFileSync(framePath, await gradientPng());const rewritten = await describeFrameStats(framePath);- sharp.cache(true);expect(degenerate.ok).toBe(false);expect(rewritten.ok).toBe(true);- rmSync(dir, { recursive: true, force: true });+ });++ it('re-probes an unmeasurable buffer instead of pinning `ok: null` on it', async () => {+ // `stats-unavailable` catches EVERY probe failure, including a transient+ // libvips one on bytes that are perfectly valid. Memoizing it would disable+ // the content gate for that frame until the TTL expired, so it is the one+ // verdict that must stay unmemoized — asserted by decode count, since the+ // returned verdict looks identical either way.+ const undecodable = Buffer.from('this is not an image');+ probe.calls = 0;++ const first = await describeFrameStats(undecodable);+ const decodesForFirst = probe.calls;+ const second = await describeFrameStats(undecodable);++ expect(first.ok).toBeNull();+ expect(first.reason).toBe(FRAME_REASON.STATS_UNAVAILABLE);+ expect(second).toEqual(first);+ expect(probe.calls).toBeGreaterThan(decodesForFirst);});it('hands out a copy, so a caller mutating a verdict cannot poison the memo', async () => {diff --git a/server/lib/imageFrameStats.js b/server/lib/imageFrameStats.jsindex dd44a19378..315c4a1901 100644--- a/server/lib/imageFrameStats.js+++ b/server/lib/imageFrameStats.js@@ -101,9 +101,14 @@ const result = (ok, reason, perChannel = null) => ({ ok, reason, perChannel });* Hashing is worth it on a miss too: sha256 runs at GB/s, an order of magnitude* under the decode it guards.*- * `null` (could-not-measure) verdicts are cached the same way: undecodable bytes- * stay undecodable, and re-warning once per unique bad buffer is the signal —- * re-warning per call is noise.+ * `stats-unavailable` is the one verdict NOT memoized. That branch catches every+ * failure the probe can raise, and not all of them are properties of the bytes:+ * a transient libvips failure (allocation spike, worker exhaustion) on a+ * perfectly valid frame would otherwise pin `ok: null` on it for the whole TTL+ * and silently disable the content gate for that frame. Re-probing an+ * undecodable buffer is the cheap side of that trade. `too-small-to-judge` IS+ * memoized — it is read off a SUCCESSFUL decode's metadata, so it is a property+ * of the bytes like any other verdict.*/const verdictCache = createBoundedStateMap({ maxSize: 2000, ttlMs: 60 * 60 * 1000 });@@ -125,7 +130,7 @@ export const __resetFrameStatsCache = () => verdictCache.clear();* @returns {Promise<{ ok: boolean|null, reason: string|null, perChannel: Array<{ mean: number, stdev: number, min: number, max: number }>|null }>}*/export async function describeFrameStats(input) {- const cacheKey = Buffer.isBuffer(input) && input.length+ const cacheKey = Buffer.isBuffer(input)? createHash('sha256').update(input).digest('hex'): null;if (cacheKey) {@@ -133,7 +138,9 @@ export async function describeFrameStats(input) {if (memo) return copyVerdict(memo);}const verdict = await measureFrameStats(input);- if (cacheKey) verdictCache.set(cacheKey, verdict);+ if (cacheKey && verdict.reason !== FRAME_REASON.STATS_UNAVAILABLE) {+ verdictCache.set(cacheKey, verdict);+ }return copyVerdict(verdict);}