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: announce a retired model pin when a catalog refresh rots it (#7328)

[._.]/ Adam Eivyaf28f604acea
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 4af4fbd161..d341e2c635 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -537,7 +537,13 @@ describe('deferred imports stay deferred (#6156)', () => {
// heavy subtree, and the split REMOVES one for the browser, which is its point:
// `localProviderRuntime` reaches `opencodeConfig.js` → `zod` to resolve
// ENDPOINTS, a question no picker asks. Raise by exactly that delta.
-const MAX_STATIC_INSTANTIATIONS = 104398;
+// #7328 raised this by a further 2: the retired-pin notifier's new suite and the
+// module it statically imports, lib/mirrorParity.js (dependency-free), for the
+// bootstrap source contract. Both the notifier and the audit behind it are
+// reached through `await import()`, so neither is in that closure — and
+// bootstrap.js gaining a static import of the notifier cost nothing, because no
+// server test file statically reaches bootstrap.js.
+const MAX_STATIC_INSTANTIATIONS = 104400;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 9dd82a9f97..aac4d45d3a 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -96,6 +96,7 @@ import { startSpotifyScheduler } from './spotifyScheduler.js';
import { startYoutubeScheduler } from './youtubeScheduler.js';
import { reconcileStackerNewsSchedulers } from './stackerNewsScheduler.js';
import { onProvidersSaved as onProvidersSavedForGraph } from './providerGraph.js';
+import { reportRetiredModelPins } from './modelPinAuditNotifier.js';
import { startBrainScheduler } from './brainScheduler.js';
import { startActivityDigestScheduler } from './activityDigestScheduler.js';
import { startTwinEnrichmentScheduler } from './twinEnrichmentScheduler.js';
@@ -277,7 +278,15 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD
// providers.json — an old client's PATCH, a model refresh, a delete.
// Injected rather than imported by the toolkit, which stays
// self-contained. A no-op until the database phase enables the graph.
- onProvidersSaved: () => onProvidersSavedForGraph(),
+ //
+ // The same write is also the moment a catalog refresh retires a model a
+ // stored pin names, so it re-runs the derive-on-read pin audit and logs
+ // the pins that NEWLY went stale (#7328). allSettled, not all: neither
+ // consumer may skip or fail the other.
+ onProvidersSaved: () => Promise.allSettled([
+ onProvidersSavedForGraph(),
+ reportRetiredModelPins(),
+ ]),
// Keep the fallback chain off providers whose CLI is not installed on
// this host (#4611), so a run falls through to the next candidate instead
// of dying at spawn time. Sync by contract: it reads the runtime probe's
diff --git a/server/services/modelPinAuditNotifier.js b/server/services/modelPinAuditNotifier.js
new file mode 100644
index 0000000000..e107e9720d
--- /dev/null
+++ b/server/services/modelPinAuditNotifier.js
@@ -0,0 +1,110 @@
+/**
+ * Announce a retired model pin at the moment it becomes observable (#7328).
+ *
+ * `modelPinAudit.js` derives the stale set on READ, which is the right rule —
+ * it catches pins that rotted before it shipped and needs nothing persisted.
+ * What derive-on-read cannot do is tell anybody: without this, a pin stays
+ * quietly broken until the user happens to open Settings → Providers.
+ *
+ * A catalog refresh is that moment, so this runs from the toolkit's
+ * `onProvidersSaved` host extension point (wired in `bootstrap.js`) and logs.
+ * It is a TRIGGER for the existing audit, never a second source of truth: no
+ * membership rule lives here, no stale set is persisted, and nothing is written
+ * inside `server/lib/aiToolkit/` (its AGENTS.md forbids that).
+ *
+ * **Transition only.** `providers.json` is written by a refresh, a legacy
+ * `PATCH /api/providers/:id`, a migration and a boot seed alike, so an install
+ * carrying one rotted pin would narrate on every one of them forever. The ids
+ * reported last time are held in process memory and re-announced only when a
+ * pin that was NOT stale then is stale now. Nothing is persisted — a restart
+ * re-announcing once is the accepted cost of keeping this off disk and off the
+ * federation layer.
+ */
+
+/**
+ * The pin ids reported by the last SUCCESSFUL audit.
+ *
+ * Only a successful audit may replace this. A failed one that wrote an empty
+ * set here would forget what it had already announced, so the next successful
+ * audit would re-announce a pin the user was told about — the exact narration
+ * loop this module exists to prevent.
+ */
+let lastReportedStaleIds = new Set();
+
+/**
+ * At most one audit runs, and at most one more is queued behind it.
+ *
+ * `saveProviders` AWAITS this hook, so every audit sits on the latency of the
+ * write that triggered it — and provider writes arrive in bursts: the harness
+ * catalog sync saves one provider at a time, the graph's import does the same,
+ * and the graph's own projection write re-enters this hook from inside a pass
+ * it latches itself out of. Each of those saves would otherwise pay a full
+ * audit whose answer depends only on the FINAL state, so all but the last is
+ * wasted. Coalescing bounds a burst of N writes at two audits.
+ *
+ * A queued caller gets the in-flight promise. That cannot cycle back on itself:
+ * the audit only READS the pin stores, and never writes `providers.json`.
+ */
+let running = null;
+let queued = false;
+
+/** Test seam: forget what was reported so the next audit announces again. */
+export function resetStaleModelPinReport() {
+ lastReportedStaleIds = new Set();
+ running = null;
+ queued = false;
+}
+
+/**
+ * Deferred so the audit's own import closure — and the pin stores behind it —
+ * stays out of the boot closure `bootstrap.js` pays for. Memoizes the PROMISE
+ * rather than the module, matching `modelPinAudit.js`'s own loaders: concurrent
+ * `import()` calls of a mocked module can let one caller escape the mock unless
+ * they share a single in-flight promise.
+ */
+let auditModule = null;
+const loadAuditModule = () => (auditModule ||= import('./modelPinAudit.js'));
+
+async function reportOnce() {
+ const { auditModelPins } = await loadAuditModule();
+ const { pins } = await auditModelPins();
+ const staleIds = new Set(pins.map((pin) => pin.id));
+ // A pin that was already stale last time is not news. Only a pin that has
+ // newly rotted earns a line, so the normal state (nothing stale, or the same
+ // stale set as before) is silent.
+ const newlyStale = [...staleIds].filter((id) => !lastReportedStaleIds.has(id));
+ // Assign the full set, not just the new ids: a pin the user clears drops out
+ // here, so rotting again later announces again.
+ lastReportedStaleIds = staleIds;
+ if (newlyStale.length === 0) return;
+ console.log(`⚠️ ${newlyStale.length} of ${staleIds.size} stored model pin(s) now name a retired model`
+ + ' — review Settings → Providers');
+}
+
+async function drain() {
+ do {
+ queued = false;
+ // The hook is non-fatal by contract: the `providers.json` write has already
+ // landed, and its callers include boot warmups and schedulers with no
+ // Express `next(err)` to bubble to. Log and continue, leaving
+ // `lastReportedStaleIds` untouched so the next audit still announces.
+ await reportOnce().catch((error) => {
+ console.error(`❌ Model pin audit after provider save failed: ${error.message}`);
+ });
+ } while (queued);
+ running = null;
+}
+
+/**
+ * Audit the stored model pins and log any that newly went stale. Never rejects.
+ *
+ * @returns {Promise<void>}
+ */
+export function reportRetiredModelPins() {
+ if (running) {
+ queued = true;
+ return running;
+ }
+ running = drain();
+ return running;
+}
diff --git a/server/services/modelPinAuditNotifier.test.js b/server/services/modelPinAuditNotifier.test.js
new file mode 100644
index 0000000000..6464544c81
--- /dev/null
+++ b/server/services/modelPinAuditNotifier.test.js
@@ -0,0 +1,158 @@
+/**
+ * Retired-pin announcement on a catalog refresh (#7328).
+ *
+ * The regressions these uniquely catch: an install with one rotted pin
+ * re-narrating on every `providers.json` write (there is no other transition
+ * tracker), a throwing audit turning a landed provider save into a failure, and
+ * the bootstrap hook losing one of its two consumers when the other is edited.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+import { stripCommentsAndNormalize } from '../lib/mirrorParity.js';
+
+vi.mock('./modelPinAudit.js', () => ({ auditModelPins: vi.fn() }));
+
+const { auditModelPins } = await import('./modelPinAudit.js');
+const {
+ reportRetiredModelPins, resetStaleModelPinReport,
+} = await import('./modelPinAuditNotifier.js');
+
+const audited = (...ids) => ({ pins: ids.map((id) => ({ id })), providers: {} });
+
+let logged;
+let errored;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ resetStaleModelPinReport();
+ logged = vi.spyOn(console, 'log').mockImplementation(() => {});
+ errored = vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ logged.mockRestore();
+ errored.mockRestore();
+});
+
+describe('reportRetiredModelPins', () => {
+ it('announces once, naming how many pins went stale', async () => {
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model', 'task:brain-sync'));
+
+ await reportRetiredModelPins();
+
+ expect(logged).toHaveBeenCalledTimes(1);
+ expect(logged.mock.calls[0][0]).toContain('2 of 2 stored model pin(s)');
+ // Single-line, and never a dump of the pin array (AGENTS.md logging rule).
+ expect(logged.mock.calls[0][0]).not.toContain('\n');
+ expect(logged.mock.calls[0][0]).not.toContain('settings:imageGen.agy.model');
+ });
+
+ it('stays silent on a later refresh that finds the SAME stale set', async () => {
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model'));
+
+ await reportRetiredModelPins();
+ logged.mockClear();
+ await reportRetiredModelPins();
+ await reportRetiredModelPins();
+
+ expect(logged).not.toHaveBeenCalled();
+ });
+
+ it('stays silent on every refresh when nothing is stale', async () => {
+ auditModelPins.mockResolvedValue(audited());
+
+ await reportRetiredModelPins();
+ await reportRetiredModelPins();
+
+ expect(logged).not.toHaveBeenCalled();
+ });
+
+ it('announces only the pin that NEWLY rotted, alongside the running total', async () => {
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model'));
+ await reportRetiredModelPins();
+ logged.mockClear();
+
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model', 'task:brain-sync'));
+ await reportRetiredModelPins();
+
+ expect(logged).toHaveBeenCalledTimes(1);
+ expect(logged.mock.calls[0][0]).toContain('1 of 2 stored model pin(s)');
+ });
+
+ it('announces again after the user clears a pin that later rots a second time', async () => {
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model'));
+ await reportRetiredModelPins();
+
+ // Cleared back to inherit — it drops out of the stale set entirely.
+ auditModelPins.mockResolvedValue(audited());
+ await reportRetiredModelPins();
+ logged.mockClear();
+
+ // Re-pinned, and rotted again: this is news, not the set we already reported.
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model'));
+ await reportRetiredModelPins();
+
+ expect(logged).toHaveBeenCalledTimes(1);
+ });
+
+ it('never rejects when the audit throws, and does not forget what it announced', async () => {
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model'));
+ await reportRetiredModelPins();
+ logged.mockClear();
+
+ auditModelPins.mockRejectedValue(new Error('settings store unreadable'));
+ await expect(reportRetiredModelPins()).resolves.toBeUndefined();
+ expect(errored.mock.calls[0][0]).toContain('settings store unreadable');
+
+ // The failure must leave the reported set alone. Clearing it here would make
+ // the very next audit re-announce a pin the user was already told about.
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model'));
+ await reportRetiredModelPins();
+
+ expect(logged).not.toHaveBeenCalled();
+ });
+
+ it('coalesces a burst of provider saves into two audits, not one per save', async () => {
+ // saveProviders AWAITS this hook, and provider writes arrive in bursts (the
+ // harness catalog sync saves one provider at a time). Every audit but the
+ // last reads state that is already superseded.
+ let release;
+ auditModelPins.mockReturnValueOnce(new Promise((resolve) => { release = resolve; }));
+ auditModelPins.mockResolvedValue(audited('settings:imageGen.agy.model'));
+
+ const burst = Promise.all([
+ reportRetiredModelPins(), reportRetiredModelPins(),
+ reportRetiredModelPins(), reportRetiredModelPins(),
+ ]);
+ await Promise.resolve();
+ expect(auditModelPins).toHaveBeenCalledTimes(1);
+
+ release(audited());
+ await burst;
+
+ // One in flight plus one covering everything that landed behind it.
+ expect(auditModelPins).toHaveBeenCalledTimes(2);
+ // And the final state is what got reported, not the superseded first read.
+ expect(logged).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('bootstrap wiring', () => {
+ // `createToolkit` has no unit harness — building it arms the whole toolkit —
+ // so the fact the audit depends on is asserted against the source.
+ const SRC = stripCommentsAndNormalize(
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'bootstrap.js'), 'utf-8'),
+ );
+
+ it('runs the pin audit from the providers-saved hook alongside the graph reconcile', () => {
+ const hook = SRC.slice(SRC.indexOf('onProvidersSaved:'));
+ const consumers = hook.slice(0, hook.indexOf(']'));
+ expect(consumers).toContain('onProvidersSavedForGraph()');
+ expect(consumers).toContain('reportRetiredModelPins()');
+ // allSettled, not all: one consumer rejecting must not skip or fail the other.
+ expect(consumers).toContain('Promise.allSettled');
+ });
+});