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
audit per-record imageModelId pins for retired models (#7326)
[._.]/ Adam Eivyead026447bfb
diff --git a/client/src/components/providers/RetiredModelPinsPanel.test.jsx b/client/src/components/providers/RetiredModelPinsPanel.test.jsxindex 45314bbdde..dcc707fae2 100644--- a/client/src/components/providers/RetiredModelPinsPanel.test.jsx+++ b/client/src/components/providers/RetiredModelPinsPanel.test.jsx@@ -68,6 +68,34 @@ describe('RetiredModelPinsPanel', () => {expect(await screen.findByText('Universe Bible & canon renders — model:')).toBeTruthy();});+ it('names a per-record pin by the record, and links to that record', async () => {+ // A record pin (#7326) has no client-side registry to compose a name from —+ // the record's own name is the name — so the panel falls through to the+ // server's label rather than printing the pin kind.+ api.getModelPinWarnings.mockResolvedValue({+ pins: [{+ id: 'record:universe:u-1',+ kind: 'record',+ family: 'universe',+ recordId: 'u-1',+ mode: 'agy',+ providerId: 'antigravity-cli',+ model: 'gemini-3.5-flash-low',+ label: 'Example Universe · universe render model',+ location: 'Universes → Render',+ href: '/universes/u-1?tab=render',+ }],+ providers: STALE.providers,+ });+ renderPanel();++ expect(await screen.findByText('Example Universe · universe render model:')).toBeTruthy();+ expect(screen.getByText(/Universes → Render/)).toBeTruthy();+ expect(screen.getByRole('link', { name: 'Open setting' })).toHaveAttribute(+ 'href', '/universes/u-1?tab=render',+ );+ });+it('renders nothing on a healthy install', async () => {api.getModelPinWarnings.mockResolvedValue({ pins: [], providers: {} });const { container } = renderPanel();diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex a36b65811d..86e4f4ce15 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -547,7 +547,19 @@ describe('deferred imports stay deferred (#6156)', () => {// the sweep, lib/agentSentinel.js and the fileUtils chain those two already// share with the rest of the suite. No new edge into a heavy subtree — a new// test file simply costs its own closure once.-const MAX_STATIC_INSTANTIATIONS = 104480;+// #7326 extends the audit to the per-record `imageModelId` pins: +7 on top of+// that (104,487), raised by exactly the delta the way #7327 did. All 7 is the two new+// suites' OWN closures — modelPinRecords.test.js and modelPinRecords.db.test.js+// each reach `services/modelPinRecords.js` plus its three light leaves (db.js,+// renderTargets.js, runtimeEnv.js). Neither statically imports a record service:+// the DB suite seeds and reads with raw SQL and lets `clearRecordPin` pull+// decks.js the way production does, which is worth ~41 on its own. The production+// change adds NO import to any module — the collector sits behind the same+// memoized call-site `await import()` as the audit's other three stores, and the+// mode -> provider map stays in modelPinAudit.js rather than moving to a shared+// leaf, which would have cost ~54 (one more file in the static closure of every+// suite reaching routes/providers.js).+const MAX_STATIC_INSTANTIATIONS = 104487;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/services/modelPinAudit.js b/server/services/modelPinAudit.jsindex 0e28deeda0..19b80268d5 100644--- a/server/services/modelPinAudit.js+++ b/server/services/modelPinAudit.js@@ -53,10 +53,12 @@ let appsModule = null;let notificationsModule = null;let providersModule = null;let taskScheduleModule = null;+let recordPinsModule = null;const loadAppsModule = () => (appsModule ||= import('./apps.js'));const loadNotificationsModule = () => (notificationsModule ||= import('./notifications.js'));const loadProvidersModule = () => (providersModule ||= import('./providers.js'));const loadTaskScheduleModule = () => (taskScheduleModule ||= import('./taskSchedule.js'));+const loadRecordPinsModule = () => (recordPinsModule ||= import('./modelPinRecords.js'));/*** Which provider record serves each cloud image-gen mode that can carry a pin.@@ -77,6 +79,18 @@ const PINNED_IMAGE_MODES = Object.freeze({[IMAGE_GEN_MODE.CODEX]: { providerId: CODEX_CLI_ID, label: 'Codex CLI' },});+/**+ * The provider record that serves `mode`, or null when `mode` names no pinnable+ * cloud backend.+ *+ * Every collector reading a `imageMode`/`imageModel` PAIR goes through this,+ * and `local` answering null is the point: the same model field holds a LOCAL+ * DIFFUSION CHECKPOINT id when the surface renders locally, and that is not a+ * CLI catalog entry to reconcile against. Judging one would report a working+ * local pin as retired and offer a button to delete it.+ */+const pinnedModeProviderId = (mode) => (typeof mode === 'string' && PINNED_IMAGE_MODES[mode]?.providerId) || null;+/** Exported for the coverage guard above — not a runtime dependency. */export const PINNED_IMAGE_MODE_IDS = Object.freeze(Object.keys(PINNED_IMAGE_MODES));export { MODEL_OVERRIDE_CAPABLE_MODES };@@ -126,7 +140,7 @@ function collectRenderDefaultPins({ settings }) {return pinIf({id: `settings:renderDefaults.${target}.imageModel`,target,- providerId: mode ? PINNED_IMAGE_MODES[mode]?.providerId : null,+ providerId: pinnedModeProviderId(mode),model: normalizeRenderPinValue(entry?.imageModel),label: `${target} render model`,location: 'Settings → Media Gen → Render Defaults',@@ -230,6 +244,32 @@ const PIN_SOURCES = Object.freeze([return updateAppTaskTypeOverride(pin.appId, pin.taskType, { model: null });},},+ // Per-record `imageModelId` pins (#7326) — universes, series, sprite records,+ // decks and music-video projects. ONE row rather than five: they share a+ // storage shape, so `modelPinRecords.js` handles them with one query per+ // family and dispatches the clear on `pin.family`. Last in the table because+ // the panel reads install-wide pins first — a setting that mis-points every+ // surface should be the row the user sees above one record's own choice.+ //+ // The record module finds the stored pairs and stops there; `pinnedModeProviderId`+ // is applied HERE, exactly as `collectRenderDefaultPins` applies it, so the+ // "a `local` pin names a diffusion checkpoint, not a CLI model" gate has one+ // definition. It also keeps the mode map out of a module this one reaches+ // through a deferred import — importing it back would close a cycle, and a+ // shared leaf would put another file in the static closure of every suite+ // that reaches `routes/providers.js`.+ {+ kind: 'record',+ collect: async () => {+ const { collectRecordPins } = await loadRecordPinsModule();+ const stored = await collectRecordPins();+ return stored.flatMap((pin) => pinIf({ ...pin, providerId: pinnedModeProviderId(pin.mode) }));+ },+ clear: async (pin) => {+ const { clearRecordPin } = await loadRecordPinsModule();+ return clearRecordPin(pin);+ },+ },]);/**diff --git a/server/services/modelPinAudit.test.js b/server/services/modelPinAudit.test.jsindex 51ff54a8c1..5be6d587a0 100644--- a/server/services/modelPinAudit.test.js+++ b/server/services/modelPinAudit.test.js@@ -8,12 +8,18 @@ vi.mock('./apps.js', () => ({getActiveApps: vi.fn(),updateAppTaskTypeOverride: vi.fn(),}));+// The per-record source (#7326) owns its own SQL and is covered in+// modelPinRecords.test.js; here it stands in for 'a source that yields pins',+// so the registry wiring — reconciliation, ordering, clear dispatch — is what+// these assertions are about.+vi.mock('./modelPinRecords.js', () => ({ collectRecordPins: vi.fn(), clearRecordPin: vi.fn() }));const { listProviders } = await import('./providers.js');const { removeByMetadata } = await import('./notifications.js');const { getSettings, updateSettingsWith } = await import('./settings.js');const { loadSchedule, updateTaskInterval } = await import('./taskSchedule.js');const { getActiveApps, updateAppTaskTypeOverride } = await import('./apps.js');+const { collectRecordPins, clearRecordPin } = await import('./modelPinRecords.js');const {auditModelPins, clearModelPin, MODEL_OVERRIDE_CAPABLE_MODES, PINNED_IMAGE_MODE_IDS,} = await import('./modelPinAudit.js');@@ -37,6 +43,20 @@ beforeEach(() => {loadSchedule.mockResolvedValue({ tasks: {} });getActiveApps.mockResolvedValue([]);removeByMetadata.mockResolvedValue({ success: true, removed: 0 });+ collectRecordPins.mockResolvedValue([]);+});++// One record's stored render pin, as the record source reports it.+const recordPin = (overrides = {}) => ({+ id: 'record:universe:u-1',+ family: 'universe',+ recordId: 'u-1',+ mode: 'agy',+ model: 'gemini-3.5-flash-low',+ label: 'Neon Dusk · universe render model',+ location: 'Universes → Render',+ href: '/universes/u-1?tab=render',+ ...overrides,});describe('image-gen pin coverage', () => {@@ -233,5 +253,76 @@ describe('clearModelPin', () => {expect(updateSettingsWith).not.toHaveBeenCalled();expect(updateTaskInterval).not.toHaveBeenCalled();expect(updateAppTaskTypeOverride).not.toHaveBeenCalled();+ expect(clearRecordPin).not.toHaveBeenCalled();+ });+});++describe('per-record pins (#7326)', () => {+ it('reports a retired record pin with its deep link and what the provider now offers', async () => {+ collectRecordPins.mockResolvedValue([recordPin()]);++ const { pins, providers } = await auditModelPins();++ expect(pins).toHaveLength(1);+ expect(pins[0]).toMatchObject({+ id: 'record:universe:u-1',+ kind: 'record',+ model: 'gemini-3.5-flash-low',+ label: 'Neon Dusk · universe render model',+ href: '/universes/u-1?tab=render',+ });+ expect(providers['antigravity-cli'].available).toEqual(['gemini-3.6-flash']);+ });++ it.each([+ ['a local diffusion checkpoint', 'local', 'sdxl-base'],+ ['the auto sentinel', 'auto', 'gemini-3.5-flash-low'],+ ['no mode at all', null, 'gemini-3.5-flash-low'],+ ])('drops a record pin whose mode names %s — its provider is not a CLI catalog', async (_case, mode, model) => {+ // The false positive this gate exists to prevent: a working LOCAL pin+ // reported as retired, with a one-click button offering to delete it.+ collectRecordPins.mockResolvedValue([recordPin({ mode, model })]);++ expect((await auditModelPins()).pins).toEqual([]);+ });++ it('leaves a record pinned to a model the provider still lists alone', async () => {+ collectRecordPins.mockResolvedValue([recordPin({ model: 'gemini-3.6-flash-high' })]);++ expect((await auditModelPins()).pins).toEqual([]);+ });++ it('orders record pins after the install-wide ones', async () => {+ // A setting that mis-points every surface outranks one record's own choice.+ getSettings.mockResolvedValue(settingsWith({+ imageGen: { agy: { enabled: true, model: 'gemini-3.5-flash-low' } },+ }));+ collectRecordPins.mockResolvedValue([recordPin()]);++ expect((await auditModelPins()).pins.map((pin) => pin.id))+ .toEqual(['settings:imageGen.agy.model', 'record:universe:u-1']);+ });++ it('keeps the rest of the audit when the record scan throws', async () => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});+ getSettings.mockResolvedValue(settingsWith({+ imageGen: { agy: { enabled: true, model: 'gemini-3.5-flash-low' } },+ }));+ collectRecordPins.mockRejectedValue(new Error('database is down'));++ expect((await auditModelPins()).pins.map((pin) => pin.id)).toEqual(['settings:imageGen.agy.model']);+ expect(logged).toHaveBeenCalledWith(expect.stringContaining('record'));+ logged.mockRestore();+ });++ it('clears a record pin through the record writer, carrying the family it belongs to', async () => {+ collectRecordPins.mockResolvedValue([recordPin()]);++ await expect(clearModelPin('record:universe:u-1')).resolves.toEqual({+ cleared: true, id: 'record:universe:u-1',+ });+ expect(clearRecordPin).toHaveBeenCalledWith(expect.objectContaining({ family: 'universe', recordId: 'u-1' }));+ // The model field alone — nothing here may write a mode or a provider.+ expect(updateSettingsWith).not.toHaveBeenCalled();});});diff --git a/server/services/modelPinRecords.db.test.js b/server/services/modelPinRecords.db.test.jsnew file mode 100644index 0000000000..0140dbc5fe--- /dev/null+++ b/server/services/modelPinRecords.db.test.js@@ -0,0 +1,135 @@+/**+ * Per-record retired-model-pin scan against real PostgreSQL (#7326).+ *+ * modelPinRecords.test.js pins the collector's behavior with `lib/db.js`+ * mocked; what only a real database can answer is whether the SQL itself is+ * right — that every family's table and JSON column exist and are spelled+ * correctly, that the filter excludes unpinned and tombstoned rows, and that a+ * clear lands as an absent model beside an untouched `imageMode`.+ *+ * Seeds and reads back through raw SQL, and reaches each record service only+ * the way production does — through the lazy `import()` inside `clearRecordPin`.+ * A static `import` of one here would put that service's whole subtree in this+ * file's closure, which the suite-wide budget in lib/importScoping.test.js+ * charges for (see the "Import scoping" section of server/AGENTS.md).+ *+ * Runs only against portos_test.+ */+import { afterAll, beforeEach, describe, expect, it } from 'vitest';+import { checkHealth, close, ensureSchema, query } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';+import { RECORD_PIN_FAMILIES, clearRecordPin, collectRecordPins } from './modelPinRecords.js';++const health = await checkHealth().catch((error) => ({ connected: false, error: error.message }));+const ready = requireDbOrSkip('services/modelPinRecords.db.test', health.connected, health.error);+if (ready) await ensureSchema();++// Every family keyed by name, so a case seeds by the same id the collector reports.+const byFamily = Object.fromEntries(RECORD_PIN_FAMILIES.map((family) => [family.family, family]));++// The id column is TEXT everywhere but decks, which key on UUID — the seeded+// ids below follow suit, and cleanup has to cast to match.+const DECK_ID = '00000000-7326-4000-8000-00000000000d';+const SEEDED = {+ universe: 'pin-audit-universe',+ series: 'pin-audit-series',+ sprite: 'pin-audit-sprite',+ musicVideo: 'pin-audit-music-video',+ deck: DECK_ID,+};++// `deck_cards` cascade from the deck row, so one delete per table is enough.+const cleanup = async () => {+ for (const [family, id] of Object.entries(SEEDED)) {+ const { table } = byFamily[family];+ const cast = family === 'deck' ? '::uuid' : '::text';+ await query(`DELETE FROM ${table} WHERE id = $1${cast}`, [id]);+ }+};++// Columns a family's DDL requires beyond the id/document/deleted trio every one+// of them shares — a mirrored `name` where the list query needs one, plus the+// deck's NOT NULL `kind`. Anything absent keeps its DDL default.+const REQUIRED_COLUMNS = {+ universe: { name: 'Pin Audit' },+ series: { name: 'Pin Audit' },+ sprite: {},+ musicVideo: {},+ deck: { name: 'Pin Audit', kind: 'playing' },+};++/**+ * Seed one family's row carrying `document` as its stored record. One seeder+ * serves all five because they differ only in the map above.+ */+const seed = async (family, { id = SEEDED[family], document = {}, deleted = false } = {}) => {+ const { table, json } = byFamily[family];+ const required = REQUIRED_COLUMNS[family];+ const columns = ['id', ...Object.keys(required), json, 'deleted'];+ const values = [id, ...Object.values(required), JSON.stringify(document), deleted];+ await query(+ `INSERT INTO ${table} (${columns.join(', ')})+ VALUES (${columns.map((_, i) => `$${i + 1}`).join(', ')})`,+ values,+ );+};++// The stored pair as the RESOLVERS read it: `->>` yields SQL NULL for an absent+// key and for a JSON null alike, which is the point — each family's clear lands+// one shape or the other (decks write `imageModelId: null`; the series/universe+// sanitizers drop the key outright) and both mean the same thing to+// `recordRenderPin`, to this module's own scan filter, and to every enqueue site.+const storedPin = async (family) => {+ const { table, json } = byFamily[family];+ const { rows } = await query(+ `SELECT ${json} ->> 'imageMode' AS mode, ${json} ->> 'imageModelId' AS model+ FROM ${table} WHERE id = $1${family === 'deck' ? '::uuid' : '::text'}`,+ [SEEDED[family]],+ );+ return rows[0];+};++// Only the ids this suite seeded — portos_test is shared with 46 other suites,+// and asserting on the whole scan would couple this file to their cleanup.+const SEEDED_PIN_IDS = new Set(Object.entries(SEEDED).map(([family, id]) => `record:${family}:${id}`));+const pinIds = async () => (await collectRecordPins())+ .map((pin) => pin.id)+ .filter((id) => SEEDED_PIN_IDS.has(id));+const cloudPin = { imageMode: 'codex', imageModelId: 'gpt-4o' };++beforeEach(async () => { if (ready) await cleanup(); });+afterAll(async () => {+ if (ready) await cleanup();+ await close();+});++describe.skipIf(!ready)('per-record model-pin scan', () => {+ it('reads the pin out of every family\'s own table and column', async () => {+ // A table or JSON column renamed out from under a family fails HERE, rather+ // than as a section of the audit that is silently empty on a real install.+ for (const family of Object.keys(SEEDED)) await seed(family, { document: cloudPin });++ expect((await pinIds()).sort()).toEqual([...SEEDED_PIN_IDS].sort());+ });++ it('returns only rows that carry a pin and are still live', async () => {+ await seed('universe', { document: cloudPin });+ await seed('series', { document: { name: 'Unpinned' } });+ await seed('sprite', { document: { name: 'Mode only', imageMode: 'codex' } });+ await seed('deck', { document: cloudPin, deleted: true });++ expect(await pinIds()).toEqual([`record:universe:${SEEDED.universe}`]);+ });++ it('clears a pin back to inherit and leaves the backend choice intact', async () => {+ await seed('deck', { document: cloudPin });++ const [pin] = await collectRecordPins();+ await clearRecordPin(pin);++ // Back to inherit, with the backend choice untouched — `imageMode` is a+ // separate decision the user did not ask to undo.+ expect(await storedPin('deck')).toEqual({ mode: 'codex', model: null });+ expect(await pinIds()).toEqual([]);+ });+});diff --git a/server/services/modelPinRecords.js b/server/services/modelPinRecords.jsnew file mode 100644index 0000000000..dc9264b71c--- /dev/null+++ b/server/services/modelPinRecords.js@@ -0,0 +1,242 @@+/**+ * Per-record retired-model-pin source (#7326).+ *+ * The install-wide pins (`settings.imageGen`, `settings.renderDefaults`, the+ * scheduled-task pins) were covered by #7324. The pins stored ON A RECORD —+ * the flat `imageMode` / `imageModelId` pair #3231 Phase 3 put on universes,+ * series, sprite records, decks and music-video projects — rot exactly the same+ * way and were not: they name a model the vendor retired, and nobody learns+ * until that record's next render dies with a raw vendor error.+ *+ * This module is the collect + clear half of ONE `PIN_SOURCES` row+ * (`kind: 'record'`), not one row per store: every family stores the same+ * normalized pair in the same place (a JSONB document column beside a+ * soft-delete flag), so they differ only in the facts `RECORD_PIN_FAMILIES` names+ * — table, JSON column, how to read a name, where the pin is edited, and how to+ * clear one. Adding a sixth family is one row there.+ *+ * **Three rules this source exists to honor.**+ *+ * 1. **Report the record's own `imageMode` beside its model.** Every descriptor+ * carries the mode UNJUDGED; `modelPinAudit.js` resolves it through the same+ * `pinnedModeProviderId` its settings collectors use, and a mode that names+ * no cloud backend drops the pin there. That is what keeps a LOCAL pin out of+ * the audit: the same `imageModelId` field holds a local diffusion checkpoint+ * id when the record renders locally, and reconciling one against a CLI+ * catalog reports a working pin as retired.+ * 2. **Never read a whole record table.** The audit is derive-on-read, so the+ * query projects four scalars and filters on `imageModelId IS NOT NULL` in+ * the database. A pinned record is rare, so what comes back is a handful of+ * rows — not every universe's JSONB document hydrated through its service.+ * 3. **Clearing writes the MODEL field only.** Each family's own update+ * function applies the key-present-with-null clear (the absent-vs-empty+ * convention in root AGENTS.md) and leaves the sibling `imageMode` alone —+ * the backend choice is a separate decision the user did not ask to undo.+ *+ * Two record families that also persist an `imageModelId` are deliberately+ * ABSENT, because neither can produce an auditable pin: a pipeline issue's+ * gen-config clears the field for every mode but `local`+ * (`pipeline/issuesShared.js`), and a creative commission surfaces it only under+ * a `local` image backend (`commissionForm.js` → `modelModes: ['local']`). The+ * audit's mode gate would filter both to nothing; a row for them would be dead+ * weight that still cost a query.+ *+ * Reached from `modelPinAudit.js` through a DEFERRED import: the clear half+ * loads a record service, and those drag heavy subtrees the audit's own module+ * comment explains it must not pay for at import time.+ */++import { isTestDatabase, query } from '../lib/db.js';+import { recordRenderPin } from '../lib/renderTargets.js';+import { isTestRunner } from '../lib/runtimeEnv.js';++/**+ * One row per record family carrying the #3231 Phase 3 render pin.+ *+ * `nameSql` differs because some families mirror `name` as a column for their+ * list query and some leave it in the document; `json` differs because decks+ * name their document column `definition`. Everything else about the five is+ * identical, which is why they share one collector.+ *+ * `clear` imports its service lazily and per family, so clearing a deck pin does+ * not also instantiate the universe builder's closure.+ */+export const RECORD_PIN_FAMILIES = Object.freeze([+ {+ family: 'universe',+ table: 'universes',+ json: 'data',+ nameSql: 'name',+ noun: 'universe',+ location: 'Universes → Render',+ href: (id) => `/universes/${encodeURIComponent(id)}?tab=render`,+ clear: async (recordId) => {+ const { updateUniverse } = await import('./universeBuilder/crud.js');+ return updateUniverse(recordId, { imageModelId: null });+ },+ },+ {+ family: 'series',+ table: 'pipeline_series',+ json: 'data',+ nameSql: 'name',+ noun: 'series',+ location: 'Series Pipeline → Series settings',+ href: (id) => `/pipeline/series/${encodeURIComponent(id)}`,+ clear: async (recordId) => {+ const { updateSeries } = await import('./pipeline/series.js');+ return updateSeries(recordId, { imageModelId: null });+ },+ },+ {+ family: 'sprite',+ table: 'sprite_records',+ json: 'data',+ nameSql: "data ->> 'name'",+ noun: 'sprite record',+ location: 'Sprites → Reference',+ href: (id) => `/sprites/${encodeURIComponent(id)}`,+ clear: async (recordId) => {+ const { updateRecord } = await import('./sprites/records.js');+ return updateRecord(recordId, { imageModelId: null });+ },+ },+ {+ family: 'deck',+ table: 'decks',+ json: 'definition',+ nameSql: 'name',+ noun: 'deck',+ location: 'Decks → Render',+ href: (id) => `/decks/${encodeURIComponent(id)}`,+ clear: async (recordId) => {+ const { updateDeck } = await import('./decks.js');+ return updateDeck(recordId, { imageModelId: null });+ },+ },+ {+ family: 'musicVideo',+ table: 'music_video_projects',+ json: 'data',+ nameSql: "data ->> 'name'",+ noun: 'music video',+ location: 'Music Video → Project toolbar',+ href: (id) => `/music-video/${encodeURIComponent(id)}`,+ clear: async (recordId) => {+ const { updateProject } = await import('./musicVideo/projects.js');+ return updateProject(recordId, { imageModelId: null });+ },+ },+]);++/**+ * The pinned-rows query for one family.+ *+ * `id::text` because decks key on UUID and every other family on TEXT — the pin+ * id this builds is a string either way, and a UUID that reached the clear path+ * as a pg UUID object would not match it back.+ *+ * The `IS NOT NULL` filter is what keeps rule 2: `->>` yields SQL NULL for both+ * an absent key and a JSON null, so the database returns only rows that actually+ * carry a pin. No index serves the expression today and none is added — the+ * filter's value here is that a scan returns a handful of four-scalar rows+ * instead of every document in the table, which is the cost this endpoint was+ * asked to avoid.+ *+ * @param {{table: string, json: string, nameSql: string}} family+ * @returns {string}+ */+export function pinnedRowsSql({ table, json, nameSql }) {+ return `SELECT id::text AS id,+ ${nameSql} AS name,+ ${json} ->> 'imageMode' AS image_mode,+ ${json} ->> 'imageModelId' AS image_model_id+ FROM ${table}+ WHERE ${json} ->> 'imageModelId' IS NOT NULL+ AND deleted = FALSE`;+}++/**+ * One pin descriptor from a queried row, or null when the row carries no pin.+ *+ * Normalizes through `recordRenderPin` rather than re-deriving: that is the ONE+ * rule for what counts as a stored pin (trim, the `'auto'` sentinel and blanks+ * collapse to null, the model id capped at the persisted length), and the+ * enqueue sites already read the pair through it.+ *+ * @param {{family: object, row: object}} args+ * @returns {object|null}+ */+function recordPinDescriptor({ family, row }) {+ const pin = recordRenderPin({ imageMode: row?.image_mode, imageModelId: row?.image_model_id });+ const recordId = typeof row?.id === 'string' ? row.id : '';+ if (!pin.modelId || !recordId) return null;+ const name = typeof row.name === 'string' && row.name.trim() ? row.name.trim() : recordId;+ return {+ id: `record:${family.family}:${recordId}`,+ family: family.family,+ recordId,+ mode: pin.mode,+ model: pin.modelId,+ label: `${name} · ${family.noun} render model`,+ location: family.location,+ href: family.href(recordId),+ };+}++/**+ * May this process scan the record tables?+ *+ * The SAME condition `checkHealth` refuses to connect under — the test runner+ * pointed at a database that is not a designated `*_test` one. Reads are allowed+ * through `assertWriteAllowed`, so without this the ordinary server suite would+ * silently query the developer's LIVE `portos` every time a test touched the+ * audit, and a machine with no Postgres would log a failed scan per family per+ * call. Reusing the two exported predicates rather than re-deriving the rule+ * keeps this gate from drifting away from the one in `lib/db.js`.+ *+ * `npm run test:db` points PGDATABASE at `portos_test`, so the DB-backed suite+ * runs the real query; production is not a test runner at all and is unaffected.+ */+const scanAllowed = () => !isTestRunner() || isTestDatabase();++/**+ * Every per-record pin across the families above, in `RECORD_PIN_FAMILIES`+ * order so the panel's rows stay stable between reads.+ *+ * One family's query failing must not take the other four down with it — an+ * unreachable table is a missing section, not a failed audit. (`modelPinAudit`+ * catches at the SOURCE level, which would drop all five together.)+ *+ * @returns {Promise<Array<object>>}+ */+export async function collectRecordPins() {+ if (!scanAllowed()) return [];+ const perFamily = await Promise.all(RECORD_PIN_FAMILIES.map(async (family) => {+ const result = await query(pinnedRowsSql(family)).catch((error) => {+ console.error(`❌ Record model-pin scan of ${family.table} failed: ${error.message}`);+ return null;+ });+ return (result?.rows || [])+ .map((row) => recordPinDescriptor({ family, row }))+ .filter(Boolean);+ }));+ return perFamily.flat();+}++/**+ * Clear ONE per-record pin back to "inherit".+ *+ * Goes through the family's own update function rather than an UPDATE against+ * the JSONB column: that is what keeps the record's sanitizer, LWW clock and+ * peer-sync fan-out in the loop, and a direct write would leave every service+ * still holding the old value in its cache.+ *+ * @param {{family?: string, recordId?: string}} pin+ * @returns {Promise<unknown>}+ */+export async function clearRecordPin(pin) {+ const family = RECORD_PIN_FAMILIES.find((entry) => entry.family === pin?.family);+ if (!family) throw new Error(`Unknown record pin family: ${pin?.family}`);+ return family.clear(pin.recordId);+}diff --git a/server/services/modelPinRecords.test.js b/server/services/modelPinRecords.test.jsnew file mode 100644index 0000000000..d22662f550--- /dev/null+++ b/server/services/modelPinRecords.test.js@@ -0,0 +1,140 @@+/**+ * Per-record retired-model-pin source (#7326) — the collector's contract with+ * the audit: which stored pins it surfaces, which it must NOT, and that a clear+ * touches only the model field.+ *+ * `lib/db.js` is mocked so the query text and the rows it returns are both+ * observable, which is what lets the mode gate and the "don't read whole+ * tables" rule be asserted at all. The SQL is exercised against real Postgres+ * in modelPinRecords.db.test.js.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/db.js', () => ({ query: vi.fn(), isTestDatabase: () => true }));+vi.mock('./universeBuilder/crud.js', () => ({ updateUniverse: vi.fn() }));+vi.mock('./pipeline/series.js', () => ({ updateSeries: vi.fn() }));+vi.mock('./sprites/records.js', () => ({ updateRecord: vi.fn() }));+vi.mock('./decks.js', () => ({ updateDeck: vi.fn() }));+vi.mock('./musicVideo/projects.js', () => ({ updateProject: vi.fn() }));++const { query } = await import('../lib/db.js');+const { updateUniverse } = await import('./universeBuilder/crud.js');+const { updateSeries } = await import('./pipeline/series.js');+const { updateRecord } = await import('./sprites/records.js');+const { updateDeck } = await import('./decks.js');+const { updateProject } = await import('./musicVideo/projects.js');+const {+ RECORD_PIN_FAMILIES, clearRecordPin, collectRecordPins, pinnedRowsSql,+} = await import('./modelPinRecords.js');++const familyOf = (name) => RECORD_PIN_FAMILIES.find((entry) => entry.family === name);++// Answer one family's scan with `rows`; every other family scans empty.+const rowsFor = (family, rows) => {+ query.mockImplementation(async (sql) => (+ sql.includes(` FROM ${familyOf(family).table}\n`) ? { rows } : { rows: [] }+ ));+};++beforeEach(() => {+ vi.clearAllMocks();+ query.mockResolvedValue({ rows: [] });+});++describe('collectRecordPins', () => {+ it('surfaces a stored pin with its mode, its model, and a deep link to the record', async () => {+ rowsFor('universe', [{ id: 'u-1', name: 'Neon Dusk', image_mode: 'agy', image_model_id: 'gemini-3.5-flash-low' }]);++ expect(await collectRecordPins()).toEqual([{+ id: 'record:universe:u-1',+ family: 'universe',+ recordId: 'u-1',+ mode: 'agy',+ model: 'gemini-3.5-flash-low',+ label: 'Neon Dusk · universe render model',+ location: 'Universes → Render',+ href: '/universes/u-1?tab=render',+ }]);+ });++ it('reports the mode unjudged, so the audit can apply its one gate', async () => {+ // A LOCAL pin names a diffusion checkpoint, not a CLI model, and 'auto'/absent+ // names no backend at all — modelPinAudit drops all three through+ // pinnedModeProviderId. This source must therefore SAY which mode it found+ // rather than silently keeping or discarding the row.+ rowsFor('series', [+ { id: 's-1', name: 'Local', image_mode: 'local', image_model_id: 'sdxl-base' },+ { id: 's-2', name: 'Auto', image_mode: 'auto', image_model_id: 'gpt-5-codex' },+ { id: 's-3', name: 'No mode', image_mode: null, image_model_id: 'gpt-5-codex' },+ ]);++ expect((await collectRecordPins()).map((pin) => pin.mode)).toEqual(['local', null, null]);+ });++ it('treats a blank or auto model id as no pin at all', async () => {+ rowsFor('sprite', [+ { id: 'sp-1', name: 'Blank', image_mode: 'codex', image_model_id: ' ' },+ { id: 'sp-2', name: 'Sentinel', image_mode: 'codex', image_model_id: 'auto' },+ ]);++ expect(await collectRecordPins()).toEqual([]);+ });++ it('falls back to the record id when the row carries no usable name', async () => {+ rowsFor('musicVideo', [{ id: 'mv-1', name: ' ', image_mode: 'codex', image_model_id: 'gpt-5-codex' }]);++ const [pin] = await collectRecordPins();+ expect(pin.label).toBe('mv-1 · music video render model');+ expect(pin.href).toBe('/music-video/mv-1');+ });++ it('keeps scanning the other families when one table fails', async () => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});+ query.mockImplementation(async (sql) => {+ if (sql.includes(' FROM universes\n')) throw new Error('relation does not exist');+ if (sql.includes(' FROM decks\n')) return { rows: [{ id: 'd-9', name: 'Playing', image_mode: 'codex', image_model_id: 'gpt-5-codex' }] };+ return { rows: [] };+ });++ expect(await collectRecordPins()).toHaveLength(1);+ expect(logged).toHaveBeenCalledWith(expect.stringContaining('universes'));+ logged.mockRestore();+ });++ it('scans every family exactly once per audit', async () => {+ await collectRecordPins();+ expect(query).toHaveBeenCalledTimes(RECORD_PIN_FAMILIES.length);+ });+});++describe('pinnedRowsSql', () => {+ // The audit is derive-on-read: it must not hydrate every record in a table to+ // answer one request. Each family's query filters IN THE DATABASE and projects+ // four scalars — never the record document.+ it.each(RECORD_PIN_FAMILIES)('filters $family to pinned, live rows without selecting the document', (family) => {+ const sql = pinnedRowsSql(family);+ expect(sql).toContain(`${family.json} ->> 'imageModelId' IS NOT NULL`);+ expect(sql).toContain('deleted = FALSE');+ expect(sql).not.toMatch(new RegExp(`SELECT[^;]*\\b${family.json}\\b\\s*(,|\\n\\s*FROM)`));+ expect(sql).not.toContain('SELECT *');+ });+});++describe('clearRecordPin', () => {+ // The sibling `imageMode` is a separate choice the user did not ask to undo —+ // every family's clear sends the model key ALONE.+ it.each([+ ['universe', () => updateUniverse],+ ['series', () => updateSeries],+ ['sprite', () => updateRecord],+ ['deck', () => updateDeck],+ ['musicVideo', () => updateProject],+ ])('clears only the model field of a %s record', async (family, update) => {+ await clearRecordPin({ family, recordId: 'r-1' });+ expect(update()).toHaveBeenCalledWith('r-1', { imageModelId: null });+ });++ it('rejects a pin naming a family that does not exist', async () => {+ await expect(clearRecordPin({ family: 'nope', recordId: 'r-1' })).rejects.toThrow(/Unknown record pin family/);+ });+});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex f85bebecb9..c22b911020 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -45,6 +45,7 @@ export const DB_TEST_INCLUDE = ['routes/mindToolRecipes.db.test.js','routes/decks.db.test.js','services/decksSync.db.test.js',+ 'services/modelPinRecords.db.test.js','scripts/run-db-migrations.test.js',];