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
fix([med-migration-scripts-migrations-014-attribute]): stop migration 014 from writing 'unknown' as a phantom annotation author
[._.]/ Adam Eivyeb7f2d1d3bf9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0f369b75cc..8e056d4c5b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -52,6 +52,8 @@- **[med-pipeline-server-services-pipeline-arcplanner] `sanitizeSeasonList` now warns when LLM-emitted seasons collide on id.** `server/lib/storyArc.js#sanitizeSeasonList` dedupes by id with last-write-wins (Map.set overwrite) on every series persist. Two LLM-emitted seasons sharing an id were silently dropped before persist while child issues kept their `seasonId` pointers — leaving the issues attached to the surviving season under the colliding id, which is rarely what an arc-resolve LLM rewrite intended. The helper now tracks colliding ids during the loop and emits a single `console.warn` listing the offending ids (counting both total overwrites and distinct colliding ids) so the responsible run is grep-able in logs. Behavior is preserved (LWW still wins, no throw); the warning is the new signal. Four tests added to `storyArc.test.js` cover the warn, the unique no-warn baseline, the multi-id collision listing, and the same-id-3+-times listing (deduped via Set).+- **[med-migration-scripts-migrations-014-attribute] Migration 014 no longer writes `'unknown'` as a phantom annotation author.** When the migration runner fires before `ensureSelf()` on a fresh install (the order in `server/index.js` — migrations at startup, identity later), `instances.json` is absent and the old fallback `instances?.self?.instanceId || 'unknown'` stamped the literal string `'unknown'` into every legacy annotation entry forever (`setAnnotation` refuses to write under `'unknown'` and `annotationsSync.flushAll` refuses to export it, so those notes became unrecoverable / unexportable). `scripts/migrations/014-attribute-existing-annotations.js` now lazy-creates the local identity inline (same shape as `ensureSelf()` — `randomUUID()` + `os.hostname()`) and writes it to `data/instances.json` before reading. Read-side belt-and-suspenders: `mediaAnnotations.readAll()` heals any pre-existing `authors.unknown` bucket by re-keying it to the real `localInstanceId` (in-memory only; the first subsequent `setAnnotation` persists the clean shape via the normal write path). When a real local entry already exists alongside an unknown phantom, the real entry wins and the phantom is dropped. Tests in `scripts/migrations/014-attribute-existing-annotations.test.js` and `server/services/mediaAnnotations.test.js`.+- **HF token banner no longer surfaces in Codex / External mode.** The `needsHfTokenGate` predicate in `client/src/pages/ImageGen.jsx` checked `currentModel?.requiresHfToken && !isFlux2Model` but forgot to also require `isLocalMode`. A user who'd selected a gated mflux model (e.g. FLUX.1-dev) and later switched the backend chip to Codex saw the "Flux 1 Dev is a gated model — paste your HF token" banner over the Codex form, even though Codex uses gpt-image-2 and never touches HuggingFace. The gate now requires `isLocalMode` first, matching the FLUX.2 install/status block right below it.- **v2.1.0 review residue — small-fixes bundle (11 items).** Universe Builder render registration moves before the enqueue loop so the worker can't race past run registration and lose per-image emit coalescing; `seasonCoverSchema` gained `.passthrough()` so a full-series round-trip echoing server-built render fields no longer 400s; `volumePdf.js` sort now uses `arcPosition || number || id` with `?? Infinity` so null-arcPosition issues sink to the end instead of interleaving via the `number` fallback; series PATCH `console.warn`s when legacy `characters` / `settings` / `objects` are stripped so stale-tab POSTs are observable; `promptRunner.js` cwd guard now treats empty-string overrides as absent (matches `tuiPromptRunner`); `loops.js` no longer misclassifies an `onComplete({success:true})` throw as `iteration:error`; dead `|| series.characters` fallback removed from `textStages.js`; `migrateSeriesCanon.js` defers the orphan-series universe-link write until after the canon patch lands so a crash window doesn't leave the series stripped + universe empty; importer warns when arc-extract returns empty `summary` + `logline` before falling back to a synthetic value; `ansiStrip.js` adds a `\x1B(?![@-_\[\]])` second-pass strip so chunks like `\x1B\x1B[31m` no longer leak an orphan escape byte.diff --git a/PLAN.md b/PLAN.mdindex 83922f9248..18e8b7bbd2 100644--- a/PLAN.md+++ b/PLAN.md@@ -30,7 +30,6 @@ _Nothing currently parked — pick the next item from the Backlog._### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)-- [ ] [med-migration-scripts-migrations-014-attribute] **[MED][MIGRATION]** `scripts/migrations/014-attribute-existing-annotations.js:43` — if migrations run before first server boot, `instances?.self?.instanceId || 'unknown'` writes the literal `'unknown'` as a phantom peer forever. Defer the migration to first server boot via `ensureSelf()`, or reconcile `unknown`→real id on read.- [ ] [med-pipeline-server-services-pipeline-arcplanner-2] **[MED][PIPELINE]** `server/services/pipeline/arcPlanner.js:929-942` — `buildSeasonRemap` Pass 3 (positional fallback) silently invents wrong mappings when the LLM structurally reshapes the arc. Log a warning when Pass 3 fires; consider only firing when unmatched count ≤ 1.- [ ] [med-pipeline-server-routes-pipeline-js-1416-1452] **[MED][PIPELINE]** `server/routes/pipeline.js:1416, 1452, 470-472, 498-500` — cover render routes always overwrite `script` with the resolved value (treats absent vs empty-string identically). Only update `script` from render when the request body actually carried the field, OR drop script writes from render routes entirely (blur-save owns the field).- [ ] [med-sharing-server-services-sharing-version-js] **[MED][SHARING]** `server/services/sharing/version.js` — `SHARING_SCHEMA_VERSION` not bumped despite series-schema canon-field removal. Cross-peer share-bucket import from a pre-B.4 install silently loses series-side canon. Either bump the version (force refusal) or mirror migration logic in the importer for legacy canon fields.diff --git a/scripts/migrations/014-attribute-existing-annotations.js b/scripts/migrations/014-attribute-existing-annotations.jsindex 2a7816cd84..830bf5887f 100644--- a/scripts/migrations/014-attribute-existing-annotations.js+++ b/scripts/migrations/014-attribute-existing-annotations.js@@ -9,16 +9,21 @@* (once exported) appear attributed on peers' machines. Idempotent: any entry* that already has an `authors` field is left alone.*- * Reads identity from data/instances.json (self.instanceId / self.name).- * Falls back to a deterministic placeholder if instances.json is missing —- * the multi-author service still works with a `'unknown'` author entry, and- * the placeholder gets overwritten the first time the user edits the note- * (setAnnotation always stamps with the real instanceId).+ * Identity comes from data/instances.json (self.instanceId / self.name). If+ * `self` is missing — possible on a brand-new install where the migration+ * runner fires before `ensureSelf()` in server boot — we lazy-create the+ * identity here using the same shape `ensureSelf()` uses (`crypto.randomUUID()`+ * + `os.hostname()`) and persist it. Without this, the migration would write+ * the literal `'unknown'` as a phantom author forever — `setAnnotation` refuses+ * to write under `'unknown'`, and `annotationsSync.flushAll` refuses to export+ * it, so the user's pre-multi-author notes would become unrecoverable.*/import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';+import os from 'os';+import crypto from 'crypto';async function readJsonOr(path, fallback) {if (!existsSync(path)) return fallback;@@ -27,6 +32,24 @@ async function readJsonOr(path, fallback) {return JSON.parse(raw);}+// Self-contained ensureSelf: matches `server/services/instances.js`+// (`{ instanceId: randomUUID(), name: hostname() }`) but avoids importing the+// service so this migration doesn't drag in peer-relay/event-emitter modules+// at migration-runner time (which can also run via the `npm run migrations`+// CLI with no server lifecycle).+async function ensureSelfIdentity(instancesPath) {+ const data = await readJsonOr(instancesPath, { self: null, peers: [] });+ if (data?.self?.instanceId) return data.self;+ const self = { instanceId: crypto.randomUUID(), name: os.hostname() };+ const next = {+ self,+ peers: Array.isArray(data?.peers) ? data.peers : [],+ };+ await writeFile(instancesPath, JSON.stringify(next, null, 2));+ console.log(`🌐 migration 014: created instance identity ${self.name} (${self.instanceId})`);+ return self;+}+export default {async up({ rootDir }) {const annotationsPath = join(rootDir, 'data', 'media-annotations.json');@@ -39,9 +62,9 @@ export default {: {};const instancesPath = join(rootDir, 'data', 'instances.json');- const instances = await readJsonOr(instancesPath, { self: null });- const instanceId = instances?.self?.instanceId || 'unknown';- const authorName = instances?.self?.name || '';+ const self = await ensureSelfIdentity(instancesPath);+ const instanceId = self.instanceId;+ const authorName = self.name || '';let migrated = 0;let alreadyCurrent = 0;diff --git a/scripts/migrations/014-attribute-existing-annotations.test.js b/scripts/migrations/014-attribute-existing-annotations.test.jsnew file mode 100644index 0000000000..3ca87d366f--- /dev/null+++ b/scripts/migrations/014-attribute-existing-annotations.test.js@@ -0,0 +1,157 @@+/**+ * Test for migration 014 — wrap legacy single-author annotations into the+ * multi-author shape, and crucially: lazy-create the local instance identity+ * if it's missing so we never write the literal `'unknown'` as a phantom+ * author key.+ *+ * Picked up by server/vitest.config.js's `../scripts/migrations/**\/*.test.js`+ * glob.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './014-attribute-existing-annotations.js';++describe('migration 014 — attribute existing annotations', () => {+ let rootDir;+ let dataDir;+ let annotationsPath;+ let instancesPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-014-'));+ dataDir = join(rootDir, 'data');+ mkdirSync(dataDir, { recursive: true });+ annotationsPath = join(dataDir, 'media-annotations.json');+ instancesPath = join(dataDir, 'instances.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ const writeAnnotations = (annotations) => {+ writeFileSync(annotationsPath, JSON.stringify({ annotations }, null, 2));+ };+ const readAnnotations = () => JSON.parse(readFileSync(annotationsPath, 'utf-8')).annotations;+ const writeInstances = (data) => {+ writeFileSync(instancesPath, JSON.stringify(data, null, 2));+ };+ const readInstances = () => JSON.parse(readFileSync(instancesPath, 'utf-8'));++ it('no-ops cleanly when media-annotations.json is missing', async () => {+ expect(existsSync(annotationsPath)).toBe(false);+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ changed: false, reason: 'no-annotations-file' });+ expect(existsSync(annotationsPath)).toBe(false);+ // Must NOT touch instances.json when there's nothing to migrate — a stale+ // install with no legacy notes shouldn't gain a phantom identity here.+ expect(existsSync(instancesPath)).toBe(false);+ });++ it('attributes legacy entries to existing self when instances.json has one', async () => {+ writeInstances({+ self: { instanceId: 'real-uuid-1234', name: 'workstation' },+ peers: [],+ });+ writeAnnotations({+ 'image:foo.png': { starred: true, note: 'love it', updatedAt: '2025-01-01T00:00:00.000Z' },+ });+ const result = await migration.up({ rootDir });+ expect(result).toMatchObject({ changed: true, migrated: 1 });+ const out = readAnnotations();+ expect(out['image:foo.png'].authors).toEqual({+ 'real-uuid-1234': {+ authorName: 'workstation',+ starred: true,+ note: 'love it',+ updatedAt: '2025-01-01T00:00:00.000Z',+ },+ });+ });++ it('lazy-creates self identity when instances.json is missing — never writes "unknown"', async () => {+ expect(existsSync(instancesPath)).toBe(false);+ writeAnnotations({+ 'image:foo.png': { starred: true, note: 'old note', updatedAt: '2025-01-01T00:00:00.000Z' },+ });+ await migration.up({ rootDir });++ // instances.json must now exist with a real uuid (never "unknown") and a+ // hostname-shaped name.+ expect(existsSync(instancesPath)).toBe(true);+ const instances = readInstances();+ expect(instances.self).toBeTruthy();+ expect(instances.self.instanceId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);+ expect(instances.self.instanceId).not.toBe('unknown');+ expect(typeof instances.self.name).toBe('string');+ expect(instances.self.name.length).toBeGreaterThan(0);++ // The annotation must be attributed to the freshly-created identity, not "unknown".+ const out = readAnnotations();+ const authorKeys = Object.keys(out['image:foo.png'].authors);+ expect(authorKeys).toEqual([instances.self.instanceId]);+ expect(authorKeys).not.toContain('unknown');+ });++ it('lazy-creates self identity when instances.json exists but self is null', async () => {+ writeInstances({ self: null, peers: [{ id: 'peer-1', name: 'preserved' }] });+ writeAnnotations({+ 'image:foo.png': { starred: true, updatedAt: '2025-01-01T00:00:00.000Z' },+ });+ await migration.up({ rootDir });++ const instances = readInstances();+ expect(instances.self.instanceId).not.toBe('unknown');+ // Preserves the pre-existing peers list rather than blowing it away.+ expect(instances.peers).toEqual([{ id: 'peer-1', name: 'preserved' }]);++ const out = readAnnotations();+ expect(Object.keys(out['image:foo.png'].authors)).toContain(instances.self.instanceId);+ });++ it('leaves entries already in multi-author shape untouched (idempotent)', async () => {+ writeInstances({+ self: { instanceId: 'real-uuid', name: 'host' },+ peers: [],+ });+ writeAnnotations({+ 'image:already-current.png': {+ authors: {+ 'real-uuid': { authorName: 'host', starred: true, note: '', updatedAt: '2026-01-01T00:00:00.000Z' },+ },+ },+ });+ const before = readFileSync(annotationsPath, 'utf-8');+ const result = await migration.up({ rootDir });+ expect(result).toMatchObject({ changed: false, alreadyCurrent: 1 });+ const after = readFileSync(annotationsPath, 'utf-8');+ expect(after).toBe(before); // bit-for-bit unchanged+ });++ it('skips legacy entries that are empty (neither starred nor note)', async () => {+ writeInstances({ self: { instanceId: 'real-uuid', name: 'host' }, peers: [] });+ writeAnnotations({+ 'image:hollow.png': { starred: false, note: '', updatedAt: '2026-01-01T00:00:00.000Z' },+ 'image:keep.png': { starred: true, updatedAt: '2026-01-01T00:00:00.000Z' },+ });+ await migration.up({ rootDir });+ const out = readAnnotations();+ expect(out['image:hollow.png']).toBeUndefined();+ expect(out['image:keep.png']).toBeDefined();+ });++ it('is idempotent — re-running over already-migrated data is a no-op', async () => {+ writeInstances({ self: { instanceId: 'real-uuid', name: 'host' }, peers: [] });+ writeAnnotations({+ 'image:foo.png': { starred: true, updatedAt: '2025-01-01T00:00:00.000Z' },+ });+ await migration.up({ rootDir });+ const afterFirst = readFileSync(annotationsPath, 'utf-8');+ await migration.up({ rootDir });+ const afterSecond = readFileSync(annotationsPath, 'utf-8');+ expect(afterSecond).toBe(afterFirst);+ });+});diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.jsindex c3ebcb8dca..4be1bc21a1 100644--- a/server/services/mediaAnnotations.js+++ b/server/services/mediaAnnotations.js@@ -84,6 +84,15 @@ async function readAll() {resolveLocalAuthorName().catch(() => ''),]);const liftCtx = { localInstanceId, defaultAuthorName };+ // Heal-on-read: migration 014 wrote the literal `'unknown'` as an author key+ // when it ran before `ensureSelf()` had created the local identity. Re-key+ // those entries to the real `localInstanceId` so they project as the user's+ // own annotation and become exportable again (annotationsSync.flushAll+ // refuses to ship payloads with instanceId `'unknown'`). The heal is in-+ // memory only — the first subsequent `setAnnotation` for the key persists+ // the clean shape via the normal write path. Skip the heal when we still+ // don't have a real local identity, otherwise we'd just rename the phantom.+ const healUnknownAuthor = localInstanceId && localInstanceId !== 'unknown';const out = {};for (const [key, value] of Object.entries(annotations)) {if (!isValidKey(key)) continue;@@ -93,7 +102,18 @@ async function readAll() {for (const [instanceId, sub] of Object.entries(lifted.authors)) {if (typeof instanceId !== 'string' || !instanceId) continue;const sane = sanitizeAuthorEntry(sub);- if (sane) authors[instanceId] = sane;+ if (!sane) continue;+ if (instanceId === 'unknown' && healUnknownAuthor) {+ // Prefer a real local entry already present — it's the source of truth;+ // the unknown bucket is the phantom that needs to be dropped.+ if (!authors[localInstanceId]) {+ authors[localInstanceId] = sane.authorName+ ? sane+ : { ...sane, authorName: defaultAuthorName };+ }+ continue;+ }+ authors[instanceId] = sane;}if (Object.keys(authors).length > 0) out[key] = { authors };}diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.jsindex cd186226a9..2495f5a185 100644--- a/server/services/mediaAnnotations.test.js+++ b/server/services/mediaAnnotations.test.js@@ -245,6 +245,46 @@ describe('mediaAnnotations service (multi-author)', () => {expect(storedMs).toBeLessThanOrEqual(afterMerge);});+ it('heals authors.unknown → local instanceId on read (post-migration-014 phantom)', async () => {+ // Migration 014 wrote `'unknown'` as a phantom author key when it ran+ // before ensureSelf() created the local identity. readAll() must re-key+ // those into the real localInstanceId so they project as the user's own+ // (otherwise setAnnotation refuses to merge with them and the sharing+ // export silently drops them).+ fileStore.set(STATE_PATH, {+ annotations: {+ 'image:phantom.png': {+ authors: {+ unknown: { authorName: 'pre-id-host', starred: true, note: 'pre-id', updatedAt: '2026-01-01T00:00:00.000Z' },+ },+ },+ },+ });+ const all = await svc.listAnnotations();+ expect(all['image:phantom.png'].own).toMatchObject({ starred: true, note: 'pre-id' });+ expect(all['image:phantom.png'].others).toEqual([]);+ const mine = await svc.listLocalAuthorAnnotations();+ expect(mine['image:phantom.png']).toBeDefined();+ });++ it('heals authors.unknown but prefers an existing real local entry when both are present', async () => {+ // If a real local entry already exists, that's the source of truth — the+ // unknown phantom must be dropped, not merged or favored.+ fileStore.set(STATE_PATH, {+ annotations: {+ 'image:both.png': {+ authors: {+ unknown: { authorName: 'old-host', starred: true, note: 'phantom', updatedAt: '2026-01-01T00:00:00.000Z' },+ [LOCAL_INSTANCE]: { authorName: 'Local User', starred: false, note: 'real', updatedAt: '2026-02-01T00:00:00.000Z' },+ },+ },+ },+ });+ const all = await svc.listAnnotations();+ expect(all['image:both.png'].own).toMatchObject({ note: 'real', starred: false });+ expect(all['image:both.png'].others).toEqual([]); // unknown bucket dropped, not exposed as a peer+ });+it('legacy single-author entries are lifted into the local author bucket on read', async () => {fileStore.set(STATE_PATH, {annotations: {