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: refresh JEV status and training results from events (#8667)
[._.]/ Adam Eivydf20c4a23614
diff --git a/client/src/components/models/JevPanel.jsx b/client/src/components/models/JevPanel.jsxindex e5ddb8a848..10734acde5 100644--- a/client/src/components/models/JevPanel.jsx+++ b/client/src/components/models/JevPanel.jsx@@ -1,11 +1,11 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { CheckCircle2, Circle, Download, ExternalLink, GraduationCap, RefreshCw, Scale, Plug, BarChart3, Wrench } from 'lucide-react';import { useLocation, useNavigate, useParams } from 'react-router';import TabPills from '../ui/TabPills';import toast from '../ui/Toast';import JevIntegrations from './JevIntegrations';import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';-import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { useSocketResource } from '../../hooks/useSocketResource';import BrailleSpinner from '../BrailleSpinner';import { formatBytes, formatCount, formatPercent } from '../../utils/formatters';import {@@ -56,6 +56,13 @@ const TASK_VIEWS = [{ id: 'training', label: 'Training', icon: GraduationCap },{ id: 'setup', label: 'Setup', icon: Wrench },];+const STATUS_EVENTS = ['jev:status'];+const STATS_EVENTS = ['jev:stats'];+const HEAD_EVENTS = ['jev:heads'];+const readStatus = ({ signal }) => getJevStatus({ silent: true, signal });+const readStats = ({ signal }) => getJevDecisionStats({ silent: true, signal });+const readHeads = ({ signal }) => getJevHeads({ silent: true, signal });+const JEV_PATH = '/models/decision-classifiers/jev';export default function JevPanel() {@@ -71,8 +78,9 @@ export default function JevPanel() {if (!validView) navigate({ pathname: `${JEV_PATH}/try`, search: location.search }, { replace: true });}, [validView, navigate, location.search]);- const [status, setStatus] = useState(null);- const [statusError, setStatusError] = useState(false);+ const { data: status, error: statusError, refetch: loadStatus, updateData: setStatus } = useSocketResource(readStatus, { events: STATUS_EVENTS });+ const { data: decisionStats, error: statsError, refetch: loadStats } = useSocketResource(readStats, { events: STATS_EVENTS });+ const { data: headState, error: headStatusError, refetch: loadHeads } = useSocketResource(readHeads, { events: HEAD_EVENTS });const [installing, setInstalling] = useState(false);const [progressMsg, setProgressMsg] = useState('');const [installError, setInstallError] = useState('');@@ -81,10 +89,6 @@ export default function JevPanel() {const [hypothesesText, setHypothesesText] = useState('');const [scoring, setScoring] = useState(false);const [decision, setDecision] = useState(null);- const [decisionStats, setDecisionStats] = useState(null);- const [statsError, setStatsError] = useState(false);- const [headState, setHeadState] = useState(null);- const [headStatusError, setHeadStatusError] = useState(false);const [training, setTraining] = useState(false);const [headError, setHeadError] = useState('');// `linear` is the honest default: a 3-way logistic regression over a frozen@@ -94,40 +98,6 @@ export default function JevPanel() {const [architecture, setArchitecture] = useState('linear');const progressTimer = useRef(null);- const loadStatus = useCallback(() => (- getJevStatus({ silent: true })- .then((res) => {- if (res) { setStatus(res); setStatusError(false); }- return res;- })- .catch(() => { setStatusError(true); return null; })- ), []);-- const loadStats = useCallback(() => getJevDecisionStats({ silent: true })- .then(res => { setDecisionStats(res); setStatsError(false); })- .catch(() => setStatsError(true)), []);-- // Metrics and adoption state only — no corpus row, premise, or path crosses- // this boundary, so it is as safe to load on mount as the counters are.- const loadHeads = useCallback(() => (- getJevHeads({ silent: true })- .then((res) => { setHeadState(res); setHeadStatusError(false); return res; })- .catch(() => { setHeadStatusError(true); return null; })- ), []);-- useAutoRefetch(() => Promise.all([loadStatus(), loadStats(), loadHeads()]), 30000, { pollOnly: true, immediate: false });-- useEffect(() => {- let active = true;- loadStatus();- // Counters only, so this is safe to load beside status on every mount.- getJevDecisionStats({ silent: true })- .then((res) => { if (active) setDecisionStats(res); })- .catch(() => { if (active) setStatsError(true); });- loadHeads();- return () => { active = false; };- }, [loadStatus, loadHeads]);-useEffect(() => {const handleProgress = (data) => {if (data?.scope !== 'jev') return;@@ -160,8 +130,10 @@ export default function JevPanel() {setProgressMsg('Installing the jev scorer…');return installJev({ silent: true }).then((result) => {- if (result?.ready === true) toast.success('jev scorer installed and ready');- return loadStatus();+ if (result?.ready === true) {+ setStatus(result);+ toast.success('jev scorer installed and ready');+ } else return loadStatus();}).catch((error) => { setInstallError(error.message || 'Installation failed.'); return loadStatus(); }).finally(() => {@@ -172,7 +144,9 @@ export default function JevPanel() {const cancel = () => cancelJevInstall({ silent: true }).then(loadStatus).catch(() => null);- const unload = () => unloadJev({ silent: true }).then(loadStatus).catch(() => null);+ const unload = () => unloadJev({ silent: true }).then(() => {+ setStatus(current => current ? { ...current, resident: false } : current);+ }).catch(() => null);const hypotheses = parseHypotheses(hypothesesText);const canScore = status?.ready === true && premise.trim().length > 0 && hypotheses.length >= 2;diff --git a/client/src/components/models/JevPanel.test.jsx b/client/src/components/models/JevPanel.test.jsxindex 19a913d157..0256fe2631 100644--- a/client/src/components/models/JevPanel.test.jsx+++ b/client/src/components/models/JevPanel.test.jsx@@ -1,5 +1,5 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';vi.mock('../../services/api', () => ({getJevStatus: vi.fn(),@@ -15,7 +15,13 @@ vi.mock('../../services/api', () => ({}));vi.mock('../../hooks/useInstanceFeatures', () => ({ useInstanceFeatures: () => ({ features: [{ id: 'jev', enabled: false }] }) }));vi.mock('./JevIntegrations', () => ({ default: () => <div>Integration controls</div> }));-vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));+vi.mock('../../services/socket', async () => {+ const { EventEmitter } = await import('node:events');+ const bus = new EventEmitter();+ bus.on = vi.fn(bus.on.bind(bus));+ bus.off = vi.fn(bus.off.bind(bus));+ return { default: bus };+});vi.mock('../ui/Toast', () => ({default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),}));@@ -202,8 +208,14 @@ describe('JevPanel try-it box', () => {getJevStatus.mockResolvedValue(status({ ready: true, setupState: 'ready', stages: stages(true), resident: true }));await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Refresh status' })); });+ let resolveOldStatus;+ getJevStatus.mockImplementationOnce(() => new Promise(resolve => { resolveOldStatus = resolve; }));+ await act(async () => { socket.emit('jev:status', {}); });await act(async () => { fireEvent.click(await screen.findByRole('button', { name: 'Unload now' })); });expect(unloadJev).toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: 'Unload now' })).not.toBeInTheDocument();+ await act(async () => { resolveOldStatus(status({ ready: true, resident: true, stages: stages(true) })); });+ expect(screen.queryByRole('button', { name: 'Unload now' })).not.toBeInTheDocument();});});@@ -390,3 +402,72 @@ describe('Jev task navigation', () => {expect(trainJevHead).not.toHaveBeenCalled();});});++afterEach(() => {+ cleanup();+ socket.removeAllListeners();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('JEV realtime resources', () => {+ it('updates only the affected resource and reconciles once without timer reads', async () => {+ vi.useFakeTimers();+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ initialView = 'setup';+ const view = render(<MemoryRouter initialEntries={['/models/decision-classifiers/jev/setup']}><Routes>+ <Route path="/models/decision-classifiers/jev/:taskView?" element={<JevPanel />} />+ </Routes></MemoryRouter>);+ await act(async () => {});+ const reads = [getJevStatus, getJevDecisionStats, getJevHeads];+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(1));+ await act(async () => { await vi.advanceTimersByTimeAsync(90_000); });+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(1));++ getJevStatus.mockResolvedValue(status({ ready: true, setupState: 'ready', stages: stages(true) }));+ await act(async () => { socket.emit('jev:status', {}); });+ expect(screen.getByTestId('jev-stage-model')).toHaveAttribute('data-ready', 'true');+ expect(getJevStatus).toHaveBeenCalledTimes(2);+ expect(getJevDecisionStats).toHaveBeenCalledTimes(1);+ expect(getJevHeads).toHaveBeenCalledTimes(1);++ getJevDecisionStats.mockResolvedValue({ decisions: [{+ decisionId: 'scope-adherence', label: 'Scope adherence', observed: 1234,+ abstained: 0, unavailable: 0, compared: 0, agreed: 0, agreementRate: null,+ }] });+ await act(async () => { socket.emit('jev:stats', {}); });+ expect(within(screen.getByTestId('jev-decision-stats')).getByText('1,234')).toBeInTheDocument();++ getJevHeads.mockResolvedValue({ heads: [headRow()], training: true });+ await act(async () => { socket.emit('jev:heads', {}); });+ expect(screen.getByRole('button', { name: 'Training in progress' })).toBeInTheDocument();+ expect(screen.getByTestId('jev-head-table')).toHaveTextContent('Candidate');+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(2));++ getJevHeads.mockRejectedValueOnce(new Error('unavailable'));+ await act(async () => { socket.emit('jev:heads', {}); });+ expect(screen.getByText(/Head status unavailable/)).toBeInTheDocument();+ expect(screen.getByTestId('jev-head-table')).toHaveTextContent('Candidate');+ reads.forEach(read => read.mockClear());++ await act(async () => { socket.emit('connect'); });+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(1));+ await act(async () => {+ visibility.mockReturnValue('hidden');+ document.dispatchEvent(new Event('visibilitychange'));+ socket.emit('jev:status', {});+ });+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(1));+ await act(async () => {+ visibility.mockReturnValue('visible');+ document.dispatchEvent(new Event('visibilitychange'));+ });+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(2));+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(2));++ view.unmount();+ await act(async () => { socket.emit('jev:status', {}); socket.emit('connect'); });+ reads.forEach(read => expect(read).toHaveBeenCalledTimes(2));+ });+});diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 22bc39c0bf..a51a8309fc 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -62,6 +62,21 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({summary: 'Payload-free invalidation after persisted Eidoverse world changes; clients read projection progress through the authenticated API.',payloadSchema: { type: 'object', additionalProperties: false, properties: {} },},+ 'jev:status': {+ direction: 'server-to-client',+ summary: 'JEV install or sidecar lifecycle changed; reread status without loading a model.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },+ 'jev:stats': {+ direction: 'server-to-client',+ summary: 'JEV decision counters persisted; reread aggregate statistics.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },+ 'jev:heads': {+ direction: 'server-to-client',+ summary: 'JEV head artifacts or training state changed; reread head metadata.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },'jev:policy': {direction: 'server-to-client',summary: 'Invalidate Jev integration policy after settings persistence or restore invalidation; no settings content.',diff --git a/server/services/jev.js b/server/services/jev.jsindex 6af0480fe3..aee4d79ff0 100644--- a/server/services/jev.js+++ b/server/services/jev.js@@ -21,6 +21,7 @@* AGENTS.md.*/+import { notifyJevChanged } from './jevEvents.js';import { existsSync } from 'node:fs';import { homedir, platform } from 'node:os';import { dirname, join } from 'node:path';@@ -320,6 +321,7 @@ export function installJev({ onEvent } = {}) {.finally(() => {installKill = null;installInFlight = null;+ notifyJevChanged('status');});return installInFlight;}@@ -352,6 +354,7 @@ export function stopJevSidecar() {for (const proc of [running?.proc, starting]) {if (proc && proc.exitCode === null && !proc.killed) proc.kill('SIGTERM');}+ if (running !== null || starting !== null) notifyJevChanged('status');return running !== null || starting !== null;}@@ -423,7 +426,11 @@ async function startSidecar() {proc.on('close', (code) => {exited = true;if (startingProc === proc) startingProc = null;- if (sidecar?.proc === proc) { sidecar = null; clearIdleTimer(); }+ if (sidecar?.proc === proc) {+ sidecar = null;+ clearIdleTimer();+ notifyJevChanged('status');+ }if (code) console.error(`❌ jev sidecar exited with code ${code}`);});// Drained, never retained: a dependency exception can carry the premise or a@@ -441,6 +448,7 @@ async function startSidecar() {startingProc = null;sidecar = { proc, device: typeof health.device === 'string' ? health.device : null };armIdleReaper();+ notifyJevChanged('status');console.log(`🧮 jev sidecar ready on 127.0.0.1:${PORTS.JEV} (${sidecar.device || 'unknown device'})`);return { ok: true };}diff --git a/server/services/jev.test.js b/server/services/jev.test.jsindex 53df4e31a9..6d887ccb11 100644--- a/server/services/jev.test.js+++ b/server/services/jev.test.js@@ -192,6 +192,9 @@ describe('scoreHypotheses', () => {describe('idle unload', () => {it('reaps the sidecar after the idle window, and only after it', async () => {makeInstalled();+ const { jevEvents } = await import('./jevEvents.js');+ const states = [];+ jevEvents.on('status', () => states.push(jev.isJevSidecarRunning()));const child = fakeChild();spawn.mockReturnValue(child);vi.stubGlobal('fetch', vi.fn(async (url) => (String(url).endsWith('/health') ? healthOk : scoreOk([@@ -207,6 +210,7 @@ describe('idle unload', () => {vi.advanceTimersByTime(1);expect(child.killed).toBe(true);expect(jev.isJevSidecarRunning()).toBe(false);+ expect(states).toEqual([true, false]);});});@@ -253,3 +257,26 @@ describe('buildJevEnv', () => {]));});});++it('notifies a failed install and an unexpected resident process exit', async () => {+ const { jevEvents } = await import('./jevEvents.js');+ const changed = vi.fn();+ jevEvents.on('status', changed);+ existsSync.mockReturnValue(false);+ findCachedRepoFiles.mockResolvedValue(null);+ expect((await jev.installJev()).ok).toBe(false);+ expect(changed).toHaveBeenCalledWith({});++ makeInstalled();+ const child = fakeChild();+ spawn.mockReturnValue(child);+ vi.stubGlobal('fetch', vi.fn(async (url) => String(url).endsWith('/health') ? healthOk : scoreOk([+ { hypothesis: 'a', entailment: 0.9, contradiction: 0, neutral: 0.1 },+ { hypothesis: 'b', entailment: 0.1, contradiction: 0, neutral: 0.9 },+ ])));+ await jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] });+ changed.mockClear();+ child.emitClose(1);+ expect(jev.isJevSidecarRunning()).toBe(false);+ expect(changed).toHaveBeenCalledExactlyOnceWith({});+});diff --git a/server/services/jevEvents.js b/server/services/jevEvents.jsnew file mode 100644index 0000000000..52e298eadd--- /dev/null+++ b/server/services/jevEvents.js@@ -0,0 +1,13 @@+import { EventEmitter } from 'node:events';++// Invalidation only: no premises, corpus rows, paths or trained weights.+export const jevEvents = new EventEmitter();++export function notifyJevChanged(resource) {+ // Install, idle-reaper and child-exit paths run outside Express.+ try {+ jevEvents.emit(resource, {});+ } catch (error) {+ console.error(`❌ JEV notification failed: ${error.message}`);+ }+}diff --git a/server/services/jevHeads.js b/server/services/jevHeads.jsindex e5b8591751..edba81b94b 100644--- a/server/services/jevHeads.js+++ b/server/services/jevHeads.js@@ -36,6 +36,7 @@* covers the path, and `sharing/jevNeverFederates.test.js` is the guard.*/+import { notifyJevChanged } from './jevEvents.js';import { readdir, unlink } from 'fs/promises';import { join } from 'path';import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';@@ -154,6 +155,7 @@ export async function saveCandidateJevHead(decisionId, raw) {if (!isHeadCompatible(parsed.head, JEV_MODEL)) return failure('jev-head-revision-mismatch');await ensureDir(jevHeadsDir());await atomicWrite(headPath(decisionId, { candidate: true }), parsed.head);+ notifyJevChanged('heads');return { ok: true, head: parsed.head };}@@ -179,6 +181,7 @@ export async function adoptJevHead(decisionId) {// states, with no way to tell which one is answering.await unlink(headPath(decisionId, { candidate: true })).catch(() => null);resetJevHeadCache();+ notifyJevChanged('heads');return { ok: true, head };}@@ -193,5 +196,6 @@ export async function discardJevHead(decisionId, { candidate = true } = {}) {if (!JEV_DECISION_IDS.includes(decisionId)) return failure('jev-head-invalid');const removed = await unlink(headPath(decisionId, { candidate })).then(() => true, () => false);resetJevHeadCache();+ if (removed) notifyJevChanged('heads');return { ok: true, removed };}diff --git a/server/services/jevHeads.test.js b/server/services/jevHeads.test.jsindex b3a80cb2a2..68b78db864 100644--- a/server/services/jevHeads.test.js+++ b/server/services/jevHeads.test.js@@ -1,3 +1,4 @@+import { jevEvents } from './jevEvents.js';/*** The trained-head store, and the one thing it exists to enforce.*@@ -187,3 +188,21 @@ describe('on-disk layout', () => {expect(written.decisionId).toBe('scope-adherence');});});++it('announces readable head changes after persistence, never rejected adoption', async () => {+ const snapshots = [];+ const changed = () => snapshots.push(describeJevHeads());+ jevEvents.on('heads', changed);+ try {+ await saveCandidateJevHead('scope-adherence', head());+ expect((await snapshots[0]).heads.map(row => row.adopted)).toEqual([false]);+ await adoptJevHead('scope-adherence');+ expect((await snapshots[1]).heads.map(row => row.adopted)).toEqual([true]);+ await discardJevHead('scope-adherence', { candidate: false });+ expect((await snapshots[2]).heads).toEqual([]);+ await adoptJevHead('scope-adherence');+ expect(snapshots).toHaveLength(3);+ } finally {+ jevEvents.off('heads', changed);+ }+});diff --git a/server/services/jevRouter.js b/server/services/jevRouter.jsindex 852bae6641..bae1a5cd96 100644--- a/server/services/jevRouter.js+++ b/server/services/jevRouter.js@@ -14,6 +14,7 @@* decides what a caller does with an abstention.*/+import { notifyJevChanged } from './jevEvents.js';import { join } from 'path';import { createCachedStore, PATHS } from '../lib/fileUtils.js';import { JEV_DECISIONS, getJevDecision, jevHypotheses, jevMinMarginFor, jevValueForHypothesis } from '../lib/jevDecisions.js';@@ -170,6 +171,9 @@ export async function recordJevObservations(observations) {decisions[row.decisionId] = counters;}return { schemaVersion: SHADOW_SCHEMA_VERSION, decisions, updatedAt: new Date().toISOString() };+ }).then((result) => {+ notifyJevChanged('stats');+ return result;}).catch((error) => {console.error(`❌ jev: could not record decision agreement counters: ${error.message}`);return null;diff --git a/server/services/jevTraining.js b/server/services/jevTraining.jsindex 44d827d5b4..5acaf0f546 100644--- a/server/services/jevTraining.js+++ b/server/services/jevTraining.js@@ -23,6 +23,7 @@* resident — so a second request joins the first rather than starting one.*/+import { notifyJevChanged } from './jevEvents.js';import { promisify } from 'util';import { dirname, join } from 'path';import { execFile } from '../lib/childProcess.js';@@ -81,7 +82,8 @@ export function trainScopeAdherenceHead({ repoPath = PATHS.root, architecture =// every later request to the same rejection.if (trainingInFlight) return trainingInFlight;trainingInFlight = runTraining({ repoPath, architecture })- .finally(() => { trainingInFlight = null; });+ .finally(() => { trainingInFlight = null; notifyJevChanged('heads'); });+ notifyJevChanged('heads');return trainingInFlight;}diff --git a/server/services/jevTraining.test.js b/server/services/jevTraining.test.jsindex 0921408f6b..4a8da41e44 100644--- a/server/services/jevTraining.test.js+++ b/server/services/jevTraining.test.js@@ -1,3 +1,4 @@+import { jevEvents } from './jevEvents.js';/*** The training run's boundaries.*@@ -153,6 +154,9 @@ describe('trainScopeAdherenceHead', () => {reached();});});+ const states = [];+ const changed = () => states.push(isJevTrainingRunning());+ jevEvents.on('heads', changed);const first = trainScopeAdherenceHead();const second = trainScopeAdherenceHead();await spawned;@@ -161,6 +165,8 @@ describe('trainScopeAdherenceHead', () => {await Promise.all([first, second]);expect(execFile).toHaveBeenCalledTimes(1);expect(isJevTrainingRunning()).toBe(false);+ jevEvents.off('heads', changed);+ expect(states).toEqual([true, false]);});it('reports the trainer\'s own code rather than collapsing every failure into one', async () => {diff --git a/server/services/socket.js b/server/services/socket.jsindex a8e2b59597..530651dae9 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -38,6 +38,7 @@ import { audioGenEvents } from './audioGen/events.js';import { aiStatusEvents } from './aiStatusEvents.js';import { usageBackfillEvents } from './usageBackfillEvents.js';import { eidoverseWorldEvents } from './eidoverseWorldEvents.js';+import { jevEvents } from './jevEvents.js';import { layaMlxEvents } from './layaMlxEvents.js';import { providerQuotaEvents } from './providerQuotaEvents.js';import { wireProactiveTriggers } from './voice/proactiveTriggers.js';@@ -250,6 +251,9 @@ function setupEventForwarding() {meatspaceEvents.on('death-clock:changed', data => ioInstance?.emit('meatspace:death-clock:changed', data));usageBackfillEvents.on('updated', () => ioInstance?.emit('usage-backfill:updated', {}));eidoverseWorldEvents.on('updated', () => ioInstance?.emit('eidoverse:projection', {}));+ jevEvents.on('status', () => ioInstance?.emit('jev:status', {}));+ jevEvents.on('stats', () => ioInstance?.emit('jev:stats', {}));+ jevEvents.on('heads', () => ioInstance?.emit('jev:heads', {}));layaMlxEvents.on('updated', () => ioInstance?.emit('laya:status', {}));providerQuotaEvents.on('updated', () => ioInstance?.emit('provider-quota:updated', {}));setupCosEventForwarding();diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 222afcfdb2..92b94bd4e4 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -1,3 +1,4 @@+import { jevEvents } from './jevEvents.js';import { spriteEvents } from './sprites/events.js';import { modelLifecycleEvents } from './modelLifecycleEvents.js';import { meatspaceEvents, invalidateMeatspace } from './meatspaceEvents.js';@@ -159,6 +160,7 @@ describe('socket.js — initSocket', () => {modelLifecycleEvents.removeAllListeners();eidoverseWorldEvents.removeAllListeners();layaMlxEvents.removeAllListeners();+ jevEvents.removeAllListeners();providerQuotaEvents.removeAllListeners();usageBackfillEvents.removeAllListeners();});@@ -219,6 +221,14 @@ describe('socket.js — initSocket', () => {expect(io.emitted).toEqual([['eidoverse:projection', {}]]);});+ it('forwards JEV resource invalidations without private scorer data', () => {+ io.emitted.length = 0;+ for (const resource of ['status', 'stats', 'heads']) {+ jevEvents.emit(resource, { premise: 'Example private input', corpus: ['Example row'] });+ }+ expect(io.emitted).toEqual([['jev:status', {}], ['jev:stats', {}], ['jev:heads', {}]]);+ });+it('forwards Laya status without experiment content', () => {io.emitted.length = 0;layaMlxEvents.emit('updated', { premise: 'Example private experiment' });diff --git a/server/services/untrustedContent.jev.test.js b/server/services/untrustedContent.jev.test.jsindex 18a2f1b128..0987f1a754 100644--- a/server/services/untrustedContent.jev.test.js+++ b/server/services/untrustedContent.jev.test.js@@ -1,3 +1,4 @@+import { jevEvents } from './jevEvents.js';/*** The jev rung of the screen → reason → validate ladder.*@@ -32,7 +33,7 @@ import { JEV_DECISIONS, jevHypotheses } from '../lib/jevDecisions.js';// Dynamic: a static import is hoisted above `makeProxy`'s initializer, so the// mock factory would run before the temp data root exists.const { jevBatchGate, runUntrustedContentAnalysis } = await import('./untrustedContent.js');-const { resetJevShadowCache } = await import('./jevRouter.js');+const { resetJevShadowCache, recordJevObservations } = await import('./jevRouter.js');const local = { id: 'local', type: 'api', enabled: true, endpoint: 'http://127.0.0.1:11434/v1', defaultModel: 'example-text' };const dispositionSchema = z.object({@@ -250,3 +251,19 @@ describe('jev rung of the untrusted-content ladder', () => {expect(result.via).toBeUndefined();});});++it('announces aggregate counters only after the durable observation write', async () => {+ const snapshots = [];+ const changed = payload => snapshots.push({ payload, read: readShadow() });+ jevEvents.on('stats', changed);+ try {+ await recordJevObservations({ decisionId: 'scope-adherence', kind: 'decided', agreed: true });+ expect(snapshots).toHaveLength(1);+ expect(snapshots[0].payload).toEqual({});+ expect((await snapshots[0].read).decisions['scope-adherence']).toMatchObject({ observed: 1, agreed: 1 });+ await recordJevObservations({ decisionId: 'unknown-decision', kind: 'decided' });+ expect(snapshots).toHaveLength(1);+ } finally {+ jevEvents.off('stats', changed);+ }+});