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

feat([issue-1214]): GC orphan staged init/reference upload images in data/image-refs

[._.]/ Adam Eivy1c4ecffa9915
diff --git a/server/index.js b/server/index.js
index e7fa2902c3..9c999d4d47 100644
--- a/server/index.js
+++ b/server/index.js
@@ -155,6 +155,7 @@ import { recoverStuckClassifications } from './services/brain.js';
import { recoverStuckAnalyses } from './services/writersRoom/evaluator.js';
import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';
import { startOrphanShellGc } from './services/importerOrphanGc.js';
+import { startImageRefsGc } from './services/imageRefsGc.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
import { initDrillCache } from './services/meatspacePostDrillCache.js';
import { createAIToolkit } from './lib/aiToolkit/index.js';
@@ -572,6 +573,9 @@ startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot sched
// Periodically GC orphan zero-issue/zero-canon importer shells left by an
// abandoned analyze (issue #727).
startOrphanShellGc();
+// Periodically GC orphan staged init/reference upload images that pile up in
+// data/image-refs on every i2i/edit render and are never cleaned up (issue #1214).
+startImageRefsGc();
// Warm the catalog user-type registry from the user-type store (Postgres as of
// #1001; the settings.json slice under the escape hatch) before any catalog
// request can land, so user-defined types validate + mint ids immediately on
diff --git a/server/services/imageRefsGc.js b/server/services/imageRefsGc.js
new file mode 100644
index 0000000000..e6e75c7f4c
--- /dev/null
+++ b/server/services/imageRefsGc.js
@@ -0,0 +1,179 @@
+/**
+ * Staged-upload image-refs GC (issue #1214)
+ *
+ * Init/reference uploads for i2i / edit renders are staged into
+ * `data/image-refs` with a fresh UUID name (`init-<uuid>.png` / `ref-<uuid>.png`)
+ * on EVERY render (`imageGen/prepareParams.js`). They are never cleaned up, so
+ * `data/image-refs` grows without bound for any user who does repeated
+ * edit-from-upload renders. (Migration 085 relocated these out of the gallery
+ * dir, fixing the visible duplicate-card bug, but the unbounded accumulation
+ * was left silent rather than solved.)
+ *
+ * This periodic sweep deletes `init-`/`ref-`-prefixed files in `data/image-refs`
+ * that are BOTH:
+ * (a) not referenced by any gallery sidecar's `initImageFilename` /
+ * `referenceImageFilenames` basenames, AND
+ * (b) older than a grace window.
+ *
+ * Why BOTH gates (not either):
+ * - The reference check alone is unsafe — the codex backend does NOT record an
+ * `initImageFilename` in its sidecar, so a still-wanted init upload behind a
+ * codex render would look unreferenced. The age gate is the backstop: a file
+ * younger than the window is spared regardless, covering codex lineage and
+ * renders still in flight (the staged file exists before its sidecar is
+ * written).
+ * - The age check alone is unsafe — a long-lived gallery image that still
+ * points at an old init upload would lose its lineage source. The reference
+ * check protects those: any basename a kept sidecar names is never swept,
+ * no matter how old.
+ *
+ * Conservative by construction: only the `init-<uuid>` / `ref-<uuid>` staged
+ * pattern is a candidate (the same discriminator migration 085 uses). Character
+ * reference sheets (`universe-…`, `sheet-…`) and any other file in the dir are
+ * never matched.
+ *
+ * Runs OUTSIDE the Express request lifecycle (a `setInterval` from index.js),
+ * so this module wraps its sweep in try/catch and logs single-line per the repo
+ * logging convention — an uncaught throw here would crash the process.
+ */
+
+import { readdir, stat, unlink } from 'fs/promises';
+import { join, basename } from 'path';
+import { existsSync } from 'fs';
+import { PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
+
+// `init-<uuid>` / `ref-<uuid>` with a decodable image extension — the exact
+// staged-upload discriminator migration 085 uses. The UUID shape is loose on
+// purpose (any hex/dash run) so files staged by older builds are still caught.
+const STAGED_UPLOAD_RE = /^(?:init|ref)-[0-9a-f-]+\.(?:png|jpe?g|webp)$/i;
+
+// Grace window before an unreferenced staged upload is eligible for deletion.
+// Measured against the file's mtime. Generous on purpose: the cost of a stale
+// upload lingering an extra week is trivial next to deleting an init/reference
+// source a render (e.g. a sidecar-less codex edit) still depends on.
+export const ORPHAN_REF_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
+
+// How often the sweep runs once started. These files are cheap to leave around,
+// so a slow cadence is fine — daily keeps `data/image-refs` bounded without churn.
+const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
+
+let sweepTimer = null;
+let initialSweepTimer = null;
+
+/**
+ * Scan every gallery sidecar and collect the set of `data/image-refs` basenames
+ * any kept image still references (`initImageFilename` + `referenceImageFilenames`).
+ * A basename in this set is never swept regardless of age.
+ *
+ * Reads the `*.metadata.json` sidecars directly rather than going through
+ * `listGallery()` so the dir is injectable for tests and we don't pay for the
+ * full gallery sort/shape we don't need here.
+ */
+export async function collectReferencedRefBasenames(imagesDir = PATHS.images) {
+ const referenced = new Set();
+ if (!existsSync(imagesDir)) return referenced;
+ const entries = await readdir(imagesDir).catch(() => []);
+ for (const name of entries) {
+ if (!name.endsWith('.metadata.json')) continue;
+ const raw = await tryReadFile(join(imagesDir, name));
+ if (raw == null) continue;
+ const meta = safeJSONParse(raw, {});
+ if (typeof meta.initImageFilename === 'string' && meta.initImageFilename) {
+ referenced.add(basename(meta.initImageFilename));
+ }
+ if (Array.isArray(meta.referenceImageFilenames)) {
+ for (const f of meta.referenceImageFilenames) {
+ if (typeof f === 'string' && f) referenced.add(basename(f));
+ }
+ }
+ }
+ return referenced;
+}
+
+/**
+ * One GC pass. Pure-ish: takes `now` so tests can pin the clock, plus optional
+ * dir overrides. A staged-upload file is deleted only when it is NOT referenced
+ * by any gallery sidecar AND its mtime is older than `maxAgeMs`.
+ *
+ * Returns `{ deleted, keptReferenced, keptYoung }` counts.
+ */
+export async function sweepOrphanRefImages({
+ now = Date.now(),
+ maxAgeMs = ORPHAN_REF_MAX_AGE_MS,
+ refsDir = PATHS.imageRefs,
+ imagesDir = PATHS.images,
+} = {}) {
+ if (!existsSync(refsDir)) return { deleted: 0, keptReferenced: 0, keptYoung: 0 };
+
+ const entries = await readdir(refsDir, { withFileTypes: true }).catch(() => []);
+ const candidates = entries
+ .filter((e) => e.isFile() && STAGED_UPLOAD_RE.test(e.name))
+ .map((e) => e.name);
+ if (candidates.length === 0) return { deleted: 0, keptReferenced: 0, keptYoung: 0 };
+
+ const referenced = await collectReferencedRefBasenames(imagesDir);
+
+ let deleted = 0;
+ let keptReferenced = 0;
+ let keptYoung = 0;
+ for (const name of candidates) {
+ // A basename a kept gallery sidecar still names is lineage we must keep,
+ // regardless of age.
+ if (referenced.has(name)) {
+ keptReferenced += 1;
+ continue;
+ }
+ // mtime backstop — spare anything younger than the grace window so a
+ // sidecar-less codex render or an in-flight render isn't swept early. A
+ // stat failure means the file vanished under us; skip it silently.
+ const info = await stat(join(refsDir, name)).catch(() => null);
+ if (!info) continue;
+ if (now - info.mtimeMs < maxAgeMs) {
+ keptYoung += 1;
+ continue;
+ }
+ await unlink(join(refsDir, name)).catch(() => {});
+ deleted += 1;
+ }
+
+ return { deleted, keptReferenced, keptYoung };
+}
+
+/**
+ * Start the periodic sweep. Fires once on a short delay after boot (so a long
+ * grace window doesn't mean accumulation waits a full day after a restart) then
+ * on SWEEP_INTERVAL_MS. Idempotent — a second call is a no-op.
+ */
+export function startImageRefsGc() {
+ if (sweepTimer) return;
+
+ const runSweep = () => {
+ sweepOrphanRefImages()
+ .then(({ deleted }) => {
+ if (deleted > 0) {
+ console.log(`🧹 Image-refs GC: removed ${deleted} orphan staged upload(s)`);
+ }
+ })
+ .catch((err) => console.error(`❌ Image-refs GC sweep failed: ${err.message}`));
+ };
+
+ // Initial pass ~5 min after boot — off the startup hot path, but soon enough
+ // that a restart doesn't reset the cleanup clock. Keep the handle so
+ // stopImageRefsGc() can cancel it if shutdown lands inside the window.
+ initialSweepTimer = setTimeout(() => { initialSweepTimer = null; runSweep(); }, 5 * 60 * 1000);
+ initialSweepTimer.unref?.();
+ sweepTimer = setInterval(runSweep, SWEEP_INTERVAL_MS);
+ sweepTimer.unref?.();
+}
+
+/** Stop the periodic sweep (used by tests / graceful shutdown). */
+export function stopImageRefsGc() {
+ if (initialSweepTimer) {
+ clearTimeout(initialSweepTimer);
+ initialSweepTimer = null;
+ }
+ if (sweepTimer) {
+ clearInterval(sweepTimer);
+ sweepTimer = null;
+ }
+}
diff --git a/server/services/imageRefsGc.test.js b/server/services/imageRefsGc.test.js
new file mode 100644
index 0000000000..e992e546b4
--- /dev/null
+++ b/server/services/imageRefsGc.test.js
@@ -0,0 +1,146 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdir, writeFile, rm, utimes, readdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import {
+ sweepOrphanRefImages,
+ collectReferencedRefBasenames,
+ ORPHAN_REF_MAX_AGE_MS,
+} from './imageRefsGc.js';
+
+// Pin a clock so age math is deterministic.
+const NOW = Date.parse('2026-06-12T00:00:00Z');
+const OLD = NOW - ORPHAN_REF_MAX_AGE_MS - 60_000; // just past the grace window
+const YOUNG = NOW - 60_000; // 1 min old — inside the window
+
+let root;
+let refsDir;
+let imagesDir;
+
+// Write a staged-upload file with a controlled mtime.
+async function stageRef(name, mtimeMs = OLD) {
+ const p = join(refsDir, name);
+ await writeFile(p, 'x');
+ const secs = mtimeMs / 1000;
+ await utimes(p, secs, secs);
+}
+
+// Write a gallery sidecar that references the given init/reference basenames.
+async function sidecar(jobId, { init = null, refs = [] } = {}) {
+ await writeFile(
+ join(imagesDir, `${jobId}.metadata.json`),
+ JSON.stringify({ id: jobId, initImageFilename: init, referenceImageFilenames: refs }),
+ );
+}
+
+beforeEach(async () => {
+ root = join(tmpdir(), `portos-imagerefsgc-${process.pid}-${Math.floor(NOW)}-${Math.random().toString(36).slice(2)}`);
+ refsDir = join(root, 'image-refs');
+ imagesDir = join(root, 'images');
+ await mkdir(refsDir, { recursive: true });
+ await mkdir(imagesDir, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+});
+
+describe('collectReferencedRefBasenames', () => {
+ it('collects init + reference basenames from every sidecar, deduped', async () => {
+ await sidecar('job1', { init: 'init-aaa.png', refs: ['ref-bbb.png', 'ref-ccc.png'] });
+ await sidecar('job2', { init: 'init-aaa.png' }); // duplicate init across renders
+ const set = await collectReferencedRefBasenames(imagesDir);
+ expect([...set].sort()).toEqual(['init-aaa.png', 'ref-bbb.png', 'ref-ccc.png']);
+ });
+
+ it('normalizes any path to a basename and tolerates absent/empty fields', async () => {
+ await sidecar('job1', { init: '/abs/path/init-ddd.png', refs: [] });
+ await sidecar('job2', {}); // both fields null/empty
+ await writeFile(join(imagesDir, 'job3.metadata.json'), '{ not json'); // tolerated
+ const set = await collectReferencedRefBasenames(imagesDir);
+ expect([...set]).toEqual(['init-ddd.png']);
+ });
+
+ it('returns an empty set when the images dir is missing', async () => {
+ const set = await collectReferencedRefBasenames(join(root, 'does-not-exist'));
+ expect(set.size).toBe(0);
+ });
+});
+
+describe('sweepOrphanRefImages', () => {
+ // Staged uploads are always named from randomUUID(), so the discriminator
+ // is hex+dash only — fixtures use UUID-shaped names to match real files.
+ const ORPHAN_A = 'init-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.png';
+ const ORPHAN_B = 'ref-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.png';
+ const KEPT_INIT = 'init-cccccccc-3333-4333-8333-cccccccccccc.png';
+ const KEPT_REF = 'ref-dddddddd-4444-4444-8444-dddddddddddd.png';
+ const YOUNG_INIT = 'init-eeeeeeee-5555-4555-8555-eeeeeeeeeeee.png';
+
+ it('deletes old, unreferenced staged uploads', async () => {
+ await stageRef(ORPHAN_A, OLD);
+ await stageRef(ORPHAN_B, OLD);
+ const res = await sweepOrphanRefImages({ now: NOW, refsDir, imagesDir });
+ expect(res.deleted).toBe(2);
+ expect(existsSync(join(refsDir, ORPHAN_A))).toBe(false);
+ expect(existsSync(join(refsDir, ORPHAN_B))).toBe(false);
+ });
+
+ it('keeps a file still referenced by a gallery sidecar, even when old', async () => {
+ await stageRef(KEPT_INIT, OLD);
+ await sidecar('job1', { init: KEPT_INIT });
+ const res = await sweepOrphanRefImages({ now: NOW, refsDir, imagesDir });
+ expect(res).toMatchObject({ deleted: 0, keptReferenced: 1 });
+ expect(existsSync(join(refsDir, KEPT_INIT))).toBe(true);
+ });
+
+ it('keeps a referenced file named only in referenceImageFilenames', async () => {
+ await stageRef(KEPT_REF, OLD);
+ await sidecar('job1', { refs: [KEPT_REF] });
+ const res = await sweepOrphanRefImages({ now: NOW, refsDir, imagesDir });
+ expect(res.deleted).toBe(0);
+ expect(res.keptReferenced).toBe(1);
+ });
+
+ it('spares a young unreferenced file (codex / in-flight backstop)', async () => {
+ await stageRef(YOUNG_INIT, YOUNG);
+ const res = await sweepOrphanRefImages({ now: NOW, refsDir, imagesDir });
+ expect(res).toMatchObject({ deleted: 0, keptYoung: 1 });
+ expect(existsSync(join(refsDir, YOUNG_INIT))).toBe(true);
+ });
+
+ it('never touches non-staged files (character sheets, others)', async () => {
+ await stageRef('universe-14590a09-chr-cb8e-blueprint-aaa.png', OLD);
+ await stageRef('sheet-something.png', OLD);
+ await stageRef('random.png', OLD);
+ const res = await sweepOrphanRefImages({ now: NOW, refsDir, imagesDir });
+ expect(res.deleted).toBe(0);
+ const remaining = await readdir(refsDir);
+ expect(remaining.sort()).toEqual([
+ 'random.png',
+ 'sheet-something.png',
+ 'universe-14590a09-chr-cb8e-blueprint-aaa.png',
+ ]);
+ });
+
+ it('handles a mixed dir: deletes only old+unreferenced staged uploads', async () => {
+ await stageRef(ORPHAN_A, OLD); // delete
+ await stageRef(KEPT_REF, OLD); // keep (referenced)
+ await stageRef(YOUNG_INIT, YOUNG); // keep (young)
+ await stageRef('universe-x-blueprint.png', OLD); // keep (not staged pattern)
+ await sidecar('job1', { refs: [KEPT_REF] });
+ const res = await sweepOrphanRefImages({ now: NOW, refsDir, imagesDir });
+ expect(res).toEqual({ deleted: 1, keptReferenced: 1, keptYoung: 1 });
+ expect(existsSync(join(refsDir, ORPHAN_A))).toBe(false);
+ expect(existsSync(join(refsDir, KEPT_REF))).toBe(true);
+ expect(existsSync(join(refsDir, YOUNG_INIT))).toBe(true);
+ expect(existsSync(join(refsDir, 'universe-x-blueprint.png'))).toBe(true);
+ });
+
+ it('is a no-op when the refs dir is missing or empty', async () => {
+ const missing = await sweepOrphanRefImages({ now: NOW, refsDir: join(root, 'nope'), imagesDir });
+ expect(missing).toEqual({ deleted: 0, keptReferenced: 0, keptYoung: 0 });
+ const empty = await sweepOrphanRefImages({ now: NOW, refsDir, imagesDir });
+ expect(empty).toEqual({ deleted: 0, keptReferenced: 0, keptYoung: 0 });
+ });
+});