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: make migration 024 imageRefs back-fill idempotent

[._.]/ Adam Eivyfd9402378d61
diff --git a/scripts/migrations/024-lock-canon-and-variations.js b/scripts/migrations/024-lock-canon-and-variations.js
index 6b53341160..077058b60a 100644
--- a/scripts/migrations/024-lock-canon-and-variations.js
+++ b/scripts/migrations/024-lock-canon-and-variations.js
@@ -89,17 +89,37 @@ const ensureIdOnVariation = (entry, prefix) => {
return { ...entry, id: `${prefix}${randomUUID()}` };
};
-const appendUniqueRef = (entry, filename) => {
- if (!entry || typeof entry !== 'object' || !filename) return { entry, added: false };
- const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
- if (refs.includes(filename)) return { entry, added: false };
- const next = [...refs, filename];
- const capped = next.length > IMAGE_REFS_PER_ENTRY_MAX
- ? next.slice(-IMAGE_REFS_PER_ENTRY_MAX)
- : next;
- return { entry: { ...entry, imageRefs: capped }, added: true };
+// Merge candidate filenames (in deterministic job-file order) with the
+// variation's existing imageRefs, dedupe, and apply the cap exactly once.
+// Candidates lead the combined list so that on a rerun the dedup order is
+// driven by the (deterministic) jobs file, not by where previous runs
+// happened to leave imageRefs after capping — that arrangement is the
+// idempotency contract: same jobs + same existing imageRefs ⇒ same output.
+//
+// A per-job append+cap loop would NOT be idempotent when a variation has
+// more than IMAGE_REFS_PER_ENTRY_MAX matching historical jobs: the first
+// run prunes older filenames out of imageRefs[], the second run sees them
+// as missing, re-appends and re-rotates, and reports changes every run.
+const mergeAndCap = (existing, candidates) => {
+ const seen = new Set();
+ const out = [];
+ for (const f of candidates) {
+ if (typeof f !== 'string' || !f || seen.has(f)) continue;
+ seen.add(f);
+ out.push(f);
+ }
+ for (const f of existing) {
+ if (typeof f !== 'string' || !f || seen.has(f)) continue;
+ seen.add(f);
+ out.push(f);
+ }
+ return out.length > IMAGE_REFS_PER_ENTRY_MAX
+ ? out.slice(-IMAGE_REFS_PER_ENTRY_MAX)
+ : out;
};
+const sameRefs = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
+
export default {
async up({ rootDir }) {
const universesPath = join(rootDir, 'data', 'universe-builder.json');
@@ -192,6 +212,10 @@ export default {
}
}
+ // Pass 1: gather candidate filenames per variation in deterministic
+ // job-file order (dedup so a job that emitted the same filename twice
+ // doesn't double-count).
+ const candidatesByKey = new Map();
for (const job of jobs) {
if (!job || job.kind !== 'image' || job.status !== 'completed') continue;
const tag = job.params?.universeRun;
@@ -201,18 +225,31 @@ export default {
const category = normalizeCategoryKey(tag.category);
const label = labelKey(tag.label);
if (!universeId || !category || !label) continue;
- const hit = variationIndex.get(`${universeId}|${category}|${label}`);
- if (!hit) continue;
+ const key = `${universeId}|${category}|${label}`;
+ if (!variationIndex.has(key)) continue;
+ let arr = candidatesByKey.get(key);
+ if (!arr) { arr = []; candidatesByKey.set(key, arr); }
+ if (!arr.includes(filename)) arr.push(filename);
+ }
+
+ // Pass 2: merge each variation's full candidate set with its existing
+ // imageRefs in one shot, so the cap is applied to the merged whole
+ // (idempotency — see mergeAndCap comment).
+ for (const [key, candidates] of candidatesByKey) {
+ const hit = variationIndex.get(key);
const bucket = hit.universe.categories[hit.bucketKey];
const variations = Array.isArray(bucket.variations) ? bucket.variations : [];
const current = variations[hit.idx];
- const { entry: nextEntry, added } = appendUniqueRef(current, filename);
- if (added) {
- variations[hit.idx] = nextEntry;
- bucket.variations = variations;
- hit.universe.categories[hit.bucketKey] = bucket;
- appendedRefs += 1;
- }
+ const existing = Array.isArray(current?.imageRefs) ? current.imageRefs : [];
+ const merged = mergeAndCap(existing, candidates);
+ if (sameRefs(merged, existing)) continue;
+ const existingSet = new Set(existing);
+ let addedCount = 0;
+ for (const f of merged) if (!existingSet.has(f)) addedCount += 1;
+ variations[hit.idx] = { ...current, imageRefs: merged };
+ bucket.variations = variations;
+ hit.universe.categories[hit.bucketKey] = bucket;
+ appendedRefs += addedCount;
}
}
diff --git a/scripts/migrations/024-lock-canon-and-variations.test.js b/scripts/migrations/024-lock-canon-and-variations.test.js
index 6f5643312b..295a983ec7 100644
--- a/scripts/migrations/024-lock-canon-and-variations.test.js
+++ b/scripts/migrations/024-lock-canon-and-variations.test.js
@@ -202,6 +202,52 @@ describe('migration 024 — lock canon + variations, back-fill thumbnails', () =
expect(second.mintedVariationIds).toBe(0);
});
+ it('is idempotent across reruns when a variation has MORE than the imageRefs cap of completed jobs', async () => {
+ // Regression: the previous per-job append-and-cap loop pruned older
+ // filenames out of imageRefs[] during the first run, then the second run
+ // saw them as missing, re-appended them, rotated the list, and reported
+ // changes on every rerun. The merge-then-cap approach computes the same
+ // deterministic capped window each run regardless of where the prior run
+ // left imageRefs.
+ const variationLabel = 'Heavy Renderer';
+ const totalJobs = 18; // > IMAGE_REFS_PER_ENTRY_MAX (12)
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-1',
+ categories: {
+ landscapes: {
+ variations: [{ id: 'var-1', label: variationLabel, prompt: 'a' }],
+ },
+ },
+ },
+ ],
+ });
+ const jobs = Array.from({ length: totalJobs }, (_, i) => ({
+ id: `job-${i}`,
+ kind: 'image',
+ status: 'completed',
+ params: { universeRun: { universeId: 'u-1', category: 'landscapes', label: variationLabel } },
+ result: { filename: `render-${String(i).padStart(3, '0')}.png` },
+ }));
+ writeJson(jobsPath, { jobs });
+
+ const first = await migration.up({ rootDir });
+ expect(first.appendedRefs).toBe(12);
+ const afterFirst = readJson(universesPath);
+ const firstRefs = afterFirst.universes[0].categories.landscapes.variations[0].imageRefs;
+ expect(firstRefs).toHaveLength(12);
+ // Last-12-wins window: jobs 6..17 in file order.
+ expect(firstRefs[0]).toBe('render-006.png');
+ expect(firstRefs[11]).toBe('render-017.png');
+
+ const second = await migration.up({ rootDir });
+ expect(second.appendedRefs).toBe(0);
+ const afterSecond = readJson(universesPath);
+ expect(afterSecond.universes[0].categories.landscapes.variations[0].imageRefs)
+ .toEqual(firstRefs);
+ });
+
it('returns `no-universes` when the data file is missing', async () => {
// Skip writing universesPath — the loader should bail.
const result = await migration.up({ rootDir });