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
address review (codex): keep stale and ruled-out measurements out of every recommendation path (#4539)
[._.]/ Adam Eivy849699e6a936
diff --git a/server/lib/localModelAssessment.js b/server/lib/localModelAssessment.jsindex dbaf15d429..9d9bacadbe 100644--- a/server/lib/localModelAssessment.js+++ b/server/lib/localModelAssessment.js@@ -347,9 +347,21 @@ export function rankByIntent(assessments, intent = 'balanced') {});}- // Higher score first; ties broken by evidence coverage so a fully-measured- // model outranks one scored on a single axis, then by model id for stability.- ranked.sort((a, b) => (b.score - a.score) || (b.coverage - a.coverage) || String(a.modelId).localeCompare(String(b.modelId)));+ // FRESH evidence outranks stale evidence outright, before score is even+ // considered: a reading taken before a RAM upgrade or a backend update+ // describes a machine that no longer exists, so it must never be the top+ // recommendation — the same rule `reconcileFit` and the editorial recommender+ // apply. Stale rows stay in the list (labelled) rather than vanishing, because+ // this panel is where the user goes to see and re-run them.+ // Then: higher score first; ties broken by evidence coverage so a+ // fully-measured model outranks one scored on a single axis, then by model id+ // for stability.+ const isStale = (entry) => (entry.staleness?.stale ? 1 : 0);+ ranked.sort((a, b) =>+ (isStale(a) - isStale(b))+ || (b.score - a.score)+ || (b.coverage - a.coverage)+ || String(a.modelId).localeCompare(String(b.modelId)));return { intent: resolvedIntent, ranked, excluded };}diff --git a/server/lib/localModelAssessment.test.js b/server/lib/localModelAssessment.test.jsindex edc70fcd9c..2ab3baea4e 100644--- a/server/lib/localModelAssessment.test.js+++ b/server/lib/localModelAssessment.test.js@@ -423,3 +423,50 @@ describe('reconcileFit', () => {expect(reconcileFit(null, measurement)).toMatchObject({ fit: 'too-large', fitSource: 'measured', disagrees: false });});});++describe('rankByIntent staleness', () => {+ const assessment = (modelId, charsPerSecond, staleness) => ({+ backend: 'ollama',+ modelId,+ verdict: 'fits',+ params: '14B',+ residentGb: 8,+ environment: { memoryBudgetGb: 40 },+ performance: {+ meanCharsPerSecond: charsPerSecond,+ contextDegradation: 0.9,+ maxWorkingContextTokens: 4096,+ samplesRun: 2,+ samplesOk: 2,+ },+ staleness,+ });++ it('never lets a stale reading outrank a fresh one, however good its numbers', () => {+ const { ranked } = rankByIntent([+ assessment('stale-but-fast:14b', 240, { comparable: true, stale: true, changes: [{ field: 'totalMemoryGb', label: 'installed memory', from: 128, to: 32 }] }),+ assessment('fresh-but-slow:14b', 20, { comparable: true, stale: false, changes: [] }),+ ], 'fastest');+ expect(ranked.map((r) => r.modelId)).toEqual(['fresh-but-slow:14b', 'stale-but-fast:14b']);+ // Still listed, though — this panel is where the user re-runs it.+ expect(ranked[1].staleness.stale).toBe(true);+ });++ it('ranks on score alone when nothing is stale', () => {+ const { ranked } = rankByIntent([+ assessment('slow:14b', 20, { comparable: true, stale: false, changes: [] }),+ assessment('fast:14b', 240, { comparable: true, stale: false, changes: [] }),+ ], 'fastest');+ expect(ranked.map((r) => r.modelId)).toEqual(['fast:14b', 'slow:14b']);+ });++ it('treats a record with no staleness annotation as un-demoted', () => {+ // `staleness: null` means the caller never compared — that is not evidence+ // of staleness, so it must not push the entry down the list.+ const { ranked } = rankByIntent([+ assessment('unannotated:14b', 240, undefined),+ assessment('fresh:14b', 20, { comparable: true, stale: false, changes: [] }),+ ], 'fastest');+ expect(ranked[0].modelId).toBe('unannotated:14b');+ });+});diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex 379e1de673..041d3c27f5 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -1231,6 +1231,24 @@ export async function enrichCatalogWithVariants(catalog, { backend, systemMemoryreturn catalog}+// Does a stored measurement describe THIS installable variant?+//+// Ollama: the install id carries the quant in its tag, so the same normalization+// `installed` uses is exactly right.+//+// LM Studio: the id is repo-level and the quant lives beside it on the record+// (`quantization`). Both must agree — including "both absent". A record written+// before `quantization` was captured therefore matches only a quant-less+// variant, which is the honest answer: it cannot say which build it measured.+function measurementMatches(backend, installId, measuredId, measurement) {+ if (backend === 'ollama') return installIdInstalled(backend, installId, [measuredId])+ const variant = lmStudioParts(installId)+ const stored = lmStudioParts(measuredId)+ if (variant.base !== stored.base) return false+ const storedQuant = stored.quant || normalizeText(measurement?.quantization).toLowerCase()+ return variant.quant === storedQuant+}+/*** Fold MEASURED evidence into the estimated fit badge.*@@ -1241,10 +1259,13 @@ export async function enrichCatalogWithVariants(catalog, { backend, systemMemory* measurement is the better answer, and where the two DISAGREE is the most* useful thing this data can say — so both are kept on the variant.*- * Matching reuses `installIdInstalled`, the exact normalization that decides the- * `installed` flag (Ollama's `hf.co/<repo>:<quant>` casing/`:latest`, LM Studio's- * quant-aware `<repo>@<quant>`). A separate matcher here would eventually drift- * and mark a variant "installed" while showing someone else's measurement.+ * Matching shares `installIdInstalled`'s normalization for Ollama (casing and a+ * trailing `:latest`), but is STRICTER about quantization than the installed+ * flag is. `installIdInstalled` deliberately treats a quant-less id as matching+ * any quant — right for "is this repo installed", wrong here: an LM Studio+ * measurement is stored against a repo-level id, so a loose match would stamp+ * one quant's measured verdict onto every quant of the repo. A measurement+ * therefore only lands on a variant whose quant it actually names.** Mutates in place (the catalog builders already do) and returns `models`.*@@ -1257,10 +1278,9 @@ export function applyMeasuredFit(models, { backend, measured } = {}) {const list = Array.isArray(models) ? models : []const measuredIds = measured ? Object.keys(measured) : []if (!measuredIds.length) return list- // One id at a time so the backend-specific normalization decides the match.const measurementFor = (installId) => {if (!installId) return null- const hit = measuredIds.find((id) => installIdInstalled(backend, installId, [id]))+ const hit = measuredIds.find((id) => measurementMatches(backend, installId, id, measured[id]))return hit ? measured[hit] : null}for (const model of list) {diff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.jsindex 85d26938db..bdf575cc9b 100644--- a/server/services/huggingFaceCatalog.test.js+++ b/server/services/huggingFaceCatalog.test.js@@ -1297,16 +1297,37 @@ describe('applyMeasuredFit', () => {expect(models[0].variants[0]).toMatchObject({ fit: 'comfortable', fitSource: 'estimated', measuredFit: 'too-large', stale: true })})- it('matches LM Studio ids quant-aware, the same way `installed` does', () => {+ it('lands an LM Studio measurement only on the quant it actually measured', () => {+ // LM Studio ids are repo-level, so the measured quant travels beside the+ // record. Without that check one quant's verdict would stamp every quant of+ // the repo — which is exactly what the `installed` flag's looser matching does.const models = [{id: 'example-org/Example-14B-GGUF',- variants: [{ quant: 'Q4_K_M', installId: 'example-org/Example-14B-GGUF@Q4_K_M', fit: 'comfortable' }]+ variants: [+ { quant: 'Q4_K_M', installId: 'example-org/Example-14B-GGUF@Q4_K_M', fit: 'comfortable' },+ { quant: 'Q8_0', installId: 'example-org/Example-14B-GGUF@Q8_0', fit: 'comfortable' }+ ]}]applyMeasuredFit(models, {backend: 'lmstudio',- measured: { 'example-org/Example-14B-GGUF': { fit: 'tight', verdict: 'fits', stale: false } }+ measured: { 'example-org/Example-14B-GGUF': { fit: 'tight', verdict: 'fits', stale: false, quantization: 'Q4_K_M' } }})expect(models[0].variants[0]).toMatchObject({ fit: 'tight', fitSource: 'measured' })+ expect(models[0].variants[1]).toMatchObject({ fit: 'comfortable', fitSource: 'estimated' })+ })++ it('declines to decorate a quantized variant from a record that never captured a quant', () => {+ // Records written before `quantization` was stored cannot say WHICH build ran,+ // so they must decorate nothing rather than guess — absent is not a wildcard.+ const models = [{+ id: 'example-org/Example-14B-GGUF',+ variants: [{ quant: 'Q4_K_M', installId: 'example-org/Example-14B-GGUF@Q4_K_M', fit: 'comfortable' }]+ }]+ applyMeasuredFit(models, {+ backend: 'lmstudio',+ measured: { 'example-org/Example-14B-GGUF': { fit: 'tight', verdict: 'fits', stale: false, quantization: null } }+ })+ expect(models[0].variants[0]).toMatchObject({ fit: 'comfortable', fitSource: 'estimated' })})it('annotates a variant-less entry, where the measurement is the only evidence there is', () => {diff --git a/server/services/localModelAssessmentStore.js b/server/services/localModelAssessmentStore.jsindex e09a2307b3..ebebb0124b 100644--- a/server/services/localModelAssessmentStore.js+++ b/server/services/localModelAssessmentStore.js@@ -97,6 +97,33 @@ export async function captureEnvironment({ backend } = {}) {};}+// A backend UPDATE is one of the things that invalidates a measurement, so the+// read paths have to see the live version too — but the catalog path runs on+// every debounced keystroke, and an unconditional probe there would be one+// loopback GET per keystroke. Cache it briefly instead.+//+// `fetched` is the sentinel that keeps "never probed" distinct from "probed and+// Ollama is down" (a legitimate `null`); without it a down backend would be+// re-probed on every single call.+const VERSION_CACHE_MS = 60000;+let versionCache = { value: null, at: 0, fetched: false };++async function liveBackendVersion(backend) {+ // Only Ollama reports a version; LM Studio exposes none, so `null` there is+ // "not recorded", and a comparison against it is skipped rather than failed.+ if (backend !== 'ollama') return null;+ const now = Date.now();+ if (versionCache.fetched && now - versionCache.at < VERSION_CACHE_MS) return versionCache.value;+ const value = await getOllamaVersion().catch(() => null);+ versionCache = { value, at: now, fetched: true };+ return value;+}++/** Test seam: drop the cached backend version so a suite can re-probe. */+export function __resetBackendVersionCache() {+ versionCache = { value: null, at: 0, fetched: false };+}+/*** Live environment for a STALENESS comparison, including the backend version.* Costs one loopback GET for Ollama, so it belongs on paths that already talk to@@ -109,7 +136,7 @@ export async function captureLiveEnvironments({ backends = ['ollama', 'lmstudio'const durable = captureDurableEnvironment();const entries = await Promise.all(backends.map(async (backend) => [backend,- { ...durable, backendVersion: backend === 'ollama' ? await getOllamaVersion().catch(() => null) : null },+ { ...durable, backendVersion: await liveBackendVersion(backend) },]));return Object.fromEntries(entries);}@@ -212,17 +239,16 @@ export function withStaleness(assessment, liveEnvironment) {* Compact measured-fit records the catalog badge and the editorial* recommendation fold in, keyed by model id for one backend.*- * Disk only, and the staleness check uses the FREE durable environment (no- * subprocess, no HTTP) because this runs on the catalog path, which is hit on- * every debounced keystroke. A backend-version change therefore doesn't register- * here — it does on the assessments report, which can afford the probe.+ * Disk only apart from a 60s-cached backend-version probe: the memory/CPU facts+ * are free to read, and the version is what catches a backend update, which is+ * just as stale-making as a RAM change.** @param {string} backend* @returns {Promise<Record<string, {fit:string|null, verdict:string, assessedAt:string|null, stale:boolean, staleReason:string|null, meanCharsPerSecond:number|null, residentGb:number|null}>>}*/export async function getMeasuredFits(backend) {const { assessments } = await loadStore();- const live = captureDurableEnvironment();+ const live = { ...captureDurableEnvironment(), backendVersion: await liveBackendVersion(backend) };const out = {};for (const assessment of assessments) {if (assessment?.backend !== backend || !assessment?.modelId) continue;@@ -239,6 +265,12 @@ export async function getMeasuredFits(backend) {? assessment.performance.meanCharsPerSecond: null,residentGb: Number.isFinite(assessment.residentGb) ? assessment.residentGb : null,+ // LM Studio model ids are repo-level and carry no quant, so the quant the+ // measurement actually ran has to travel separately or a Q4 reading would+ // decorate every quant of the repo. `null` = the record predates this+ // field (or the backend reported none), and a consumer must then decline+ // to match a quantized variant rather than guess.+ quantization: assessment.quantization ?? null,};}return out;diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex 1b8162d17d..b6ceb0f3c1 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -259,6 +259,11 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_backend,modelId,params: card?.params ?? null,+ // LM Studio serves one quant per install but reports a repo-level id, so the+ // quant has to be recorded separately for a catalog badge to know WHICH+ // build was measured. `null` on Ollama (its id already carries the tag) and+ // whenever the backend reported none.+ quantization: card?.quantization ?? null,// `null` = never measured; the LM Studio path legitimately reports null.residentGb: verdict === 'fits' ? await residentGbFor(backend, modelId) : null,assessedAt: new Date().toISOString(),diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex 23f95ecdcb..e916dc649a 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -477,3 +477,45 @@ describe('getMeasuredFits', () => {expect(fits['example-model:7b'].staleReason).toMatch(/CPU count/i);});});++describe('backend-version staleness on the read paths', () => {+ beforeEach(() => store.__resetBackendVersionCache());++ it('marks a measurement stale after the backend is updated under it', async () => {+ ollamaVersion.mockResolvedValue('0.1.0');+ runLocalLlmTest.mockResolvedValue(okRun());+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });+ expect((await store.getMeasuredFits('ollama'))['example-model:7b'].stale).toBe(false);++ store.__resetBackendVersionCache();+ ollamaVersion.mockResolvedValue('0.2.0');+ const fits = await store.getMeasuredFits('ollama');+ expect(fits['example-model:7b'].stale).toBe(true);+ expect(fits['example-model:7b'].staleReason).toMatch(/backend version 0\.1\.0 → 0\.2\.0/);+ });++ it('probes the version at most once per cache window, not once per keystroke', async () => {+ // The catalog path calls this on every debounced keystroke; an unconditional+ // probe there would be one loopback GET per character typed.+ ollamaVersion.mockClear();+ await store.getMeasuredFits('ollama');+ await store.getMeasuredFits('ollama');+ await store.getMeasuredFits('ollama');+ expect(ollamaVersion).toHaveBeenCalledTimes(1);+ });++ it('does not re-probe a backend that is down — null is a fetched answer', async () => {+ store.__resetBackendVersionCache();+ ollamaVersion.mockClear().mockResolvedValue(null);+ await store.getMeasuredFits('ollama');+ await store.getMeasuredFits('ollama');+ expect(ollamaVersion).toHaveBeenCalledTimes(1);+ });++ it('never probes for LM Studio, which reports no version at all', async () => {+ store.__resetBackendVersionCache();+ ollamaVersion.mockClear();+ await store.getMeasuredFits('lmstudio');+ expect(ollamaVersion).not.toHaveBeenCalled();+ });+});diff --git a/server/services/localModelHealing.js b/server/services/localModelHealing.jsindex 08418accd0..b05359b149 100644--- a/server/services/localModelHealing.js+++ b/server/services/localModelHealing.js@@ -82,8 +82,22 @@ export function isModelNotFoundError(text) {export function chooseFallbackModel(models, { measured = {} } = {}) {const recommended = recommendEditorialModel(models, { measured });if (recommended?.id) return recommended.id;- const usable = (models || []).find((m) => m?.id && !isEmbeddingModel(m.id));- return usable?.id || (models || [])[0]?.id || null;+ // The recommender can come back empty (every candidate is an embedding /+ // code / media model, or measurement ruled them all out). The looser tiers+ // below must honour the same measured evidence, or a model PROVEN not to run+ // here gets repointed onto anyway and the next run fails identically.+ // A stale reading is not evidence — same rule as the recommender.+ const ruledOut = (id) => {+ const record = measured?.[id];+ return Boolean(record) && !record.stale && ['does-not-fit', 'incompatible'].includes(record.verdict);+ };+ const list = (models || []).filter((m) => m?.id);+ const runnable = list.filter((m) => !ruledOut(m.id));+ const usable = runnable.find((m) => !isEmbeddingModel(m.id));+ // Last resort keeps the pre-measurement behavior: when EVERY installed model+ // is ruled out, a doomed pick still beats leaving the provider pointed at a+ // model that is not installed at all.+ return usable?.id || runnable[0]?.id || list[0]?.id || null;}/**diff --git a/server/services/localModelHealing.test.js b/server/services/localModelHealing.test.jsindex 165dee1108..c79ed01d3c 100644--- a/server/services/localModelHealing.test.js+++ b/server/services/localModelHealing.test.js@@ -17,6 +17,9 @@ vi.mock('./notifications.js', () => ({}));vi.mock('./ollamaManager.js', () => ({getInstalledModels: mocks.ollamaInstalled,+ // The assessment store records/compares the backend version, so the module+ // graph now reaches this export on the self-heal path.+ getVersion: async () => '0.0.0-test',getBaseUrl: () => 'http://localhost:11434',// Mirror the real predicate so localBackendForProvider classifies correctly.isOllamaProvider: (p) => p?.id === 'ollama' ||@@ -114,6 +117,50 @@ describe('chooseFallbackModel', () => {expect(chooseFallbackModel([])).toBeNull();expect(chooseFallbackModel(null)).toBeNull();});++ describe('measured evidence', () => {+ const models = [+ { id: 'qwen3.6:35b', params: '35B' },+ { id: 'gemma4:9b', params: '9B' },+ ];++ it('never falls back onto a model measured NOT to run here', () => {+ expect(chooseFallbackModel(models, {+ measured: { 'qwen3.6:35b': { verdict: 'does-not-fit', stale: false } },+ })).toBe('gemma4:9b');+ });++ it('honours measurement in the LOOSE tier too, not just the recommender', () => {+ // Every candidate is a code model, so the editorial recommender returns+ // null and the generic non-embedding tier decides — that tier must apply+ // the same evidence or a proven-broken model gets repointed onto anyway.+ const coders = [+ { id: 'qwen3-coder:30b', params: '30B' },+ { id: 'codegemma:7b', params: '7B' },+ ];+ expect(chooseFallbackModel(coders)).toBe('qwen3-coder:30b');+ expect(chooseFallbackModel(coders, {+ measured: { 'qwen3-coder:30b': { verdict: 'incompatible', stale: false } },+ })).toBe('codegemma:7b');+ });++ it('still picks something when measurement rules out everything installed', () => {+ // A doomed pick beats leaving the provider on a model that is not even+ // installed — the retry fails either way, but the config stops being wrong.+ expect(chooseFallbackModel(models, {+ measured: {+ 'qwen3.6:35b': { verdict: 'does-not-fit', stale: false },+ 'gemma4:9b': { verdict: 'does-not-fit', stale: false },+ },+ })).toBe('qwen3.6:35b');+ });++ it('ignores a stale measurement', () => {+ expect(chooseFallbackModel(models, {+ measured: { 'qwen3.6:35b': { verdict: 'does-not-fit', stale: true } },+ })).toBe('qwen3.6:35b');+ });+ });});describe('computeProviderPatch', () => {