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: add a local entailment scorer that abstains instead of guessing (#7641)

[._.]/ Adam Eivy5b522def7df3
diff --git a/client/src/components/models/JevPanel.jsx b/client/src/components/models/JevPanel.jsx
new file mode 100644
index 0000000000..5dd1dc6db0
--- /dev/null
+++ b/client/src/components/models/JevPanel.jsx
@@ -0,0 +1,317 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { CheckCircle2, Circle, Download, ExternalLink, RefreshCw, Scale } from 'lucide-react';
+import toast from '../ui/Toast';
+import BrailleSpinner from '../BrailleSpinner';
+import { formatBytes } from '../../utils/formatters';
+import {
+ cancelJevInstall,
+ getJevStatus,
+ installJev,
+ scoreJev,
+ unloadJev,
+} from '../../services/api';
+import socket from '../../services/socket';
+
+// Shown before the first status response lands, and if status is unavailable,
+// so the checklist never renders as an empty box. Mirrors JEV_STAGES in
+// server/lib/jev.js — four stages, no Hugging Face token: openjev is ungated.
+const FALLBACK_STAGES = [
+ { id: 'python', label: 'Host Python', description: 'Python 3.10 or newer, with a supported PyTorch wheel for this machine.' },
+ { id: 'venv', label: 'Dedicated jev runtime', description: 'A private virtualenv that never shares packages with Prompt Guard, image, or video generation.' },
+ { id: 'packages', label: 'Scorer packages', description: 'Pinned torch, transformers, safetensors, and huggingface_hub imports.' },
+ { id: 'model', label: 'Pinned model snapshot', description: 'The four required files from the pinned 4B NLI subfolder.' },
+];
+
+const stagesFromStatus = (status) => (
+ Array.isArray(status?.stages) && status.stages.length ? status.stages : FALLBACK_STAGES
+);
+
+const parseHypotheses = (text) => text.split('\n').map((line) => line.trim()).filter(Boolean);
+
+export default function JevPanel() {
+ const [status, setStatus] = useState(null);
+ const [statusError, setStatusError] = useState(false);
+ const [installing, setInstalling] = useState(false);
+ const [progressMsg, setProgressMsg] = useState('');
+ const [installError, setInstallError] = useState('');
+ const [installingStage, setInstallingStage] = useState(null);
+ const [premise, setPremise] = useState('');
+ const [hypothesesText, setHypothesesText] = useState('');
+ const [scoring, setScoring] = useState(false);
+ const [decision, setDecision] = useState(null);
+ 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; })
+ ), []);
+
+ useEffect(() => { loadStatus(); }, [loadStatus]);
+
+ useEffect(() => {
+ const handleProgress = (data) => {
+ if (data?.scope !== 'jev') return;
+ clearTimeout(progressTimer.current);
+ if (data?.stage) setInstallingStage(data.stage);
+ setProgressMsg(data?.message || '');
+ if (data?.event === 'complete') {
+ setInstalling(false);
+ setInstallingStage(null);
+ progressTimer.current = setTimeout(() => setProgressMsg(''), 3000);
+ loadStatus();
+ }
+ if (data?.event === 'error') {
+ setInstalling(false);
+ setInstallError(data.message || 'Installation failed. Refresh status for diagnostics.');
+ loadStatus();
+ }
+ };
+ socket.on('localLlm:progress', handleProgress);
+ return () => {
+ socket.off('localLlm:progress', handleProgress);
+ clearTimeout(progressTimer.current);
+ };
+ }, [loadStatus]);
+
+ const install = () => {
+ setInstallError('');
+ setInstallingStage(null);
+ setInstalling(true);
+ setProgressMsg('Installing the jev scorer…');
+ return installJev({ silent: true })
+ .then((result) => {
+ if (result?.ready === true) toast.success('jev scorer installed and ready');
+ return loadStatus();
+ })
+ .catch((error) => { setInstallError(error.message || 'Installation failed.'); return loadStatus(); })
+ .finally(() => {
+ setInstalling(false);
+ setInstallingStage(null);
+ });
+ };
+
+ const cancel = () => cancelJevInstall({ silent: true }).then(loadStatus).catch(() => null);
+
+ const unload = () => unloadJev({ silent: true }).then(loadStatus).catch(() => null);
+
+ const hypotheses = parseHypotheses(hypothesesText);
+ const canScore = status?.ready === true && premise.trim().length > 0 && hypotheses.length >= 2;
+
+ const runScore = () => {
+ setScoring(true);
+ setDecision(null);
+ return scoreJev({ premise: premise.trim(), hypotheses }, { silent: true })
+ .then((result) => setDecision(result))
+ // A failing score is shown in the result box beside the button rather
+ // than as a toast: the operator is iterating on this input right here.
+ .catch((error) => setDecision({ ok: false, code: error.message || 'jev-request-invalid' }))
+ .finally(() => { setScoring(false); loadStatus(); });
+ };
+
+ const stages = stagesFromStatus(status);
+ const currentStageId = installingStage || (installing ? stages.find((stage) => !stage.ready)?.id : null);
+ const ready = status?.ready === true;
+ const incomplete = status?.setupState === 'incomplete';
+
+ return (
+ <section
+ id="llm-management-panel-jev"
+ role="tabpanel"
+ aria-labelledby="tab-jev"
+ data-testid="jev-card"
+ className="max-w-6xl bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-5"
+ >
+ <div className="flex items-start justify-between gap-3 flex-wrap">
+ <div className="flex items-start gap-2">
+ <Scale size={18} className="text-port-accent mt-0.5" aria-hidden="true" />
+ <div>
+ <h2 className="text-lg font-semibold text-white">jev decision scorer</h2>
+ <p className="text-xs text-port-accent mt-0.5">Optional · local entailment model · no provider quota</p>
+ </div>
+ </div>
+ {ready ? (
+ <span className="text-xs px-2 py-1 rounded border border-port-success/40 text-port-success">Ready</span>
+ ) : status ? (
+ <span className="text-xs px-2 py-1 rounded border border-port-warning/40 text-port-warning">{incomplete ? 'Setup incomplete' : 'Not installed'}</span>
+ ) : statusError ? (
+ <span role="status" className="text-xs text-port-warning">Status unavailable</span>
+ ) : (
+ <span className="text-xs text-gray-500">Checking status…</span>
+ )}
+ </div>
+
+ <p className="text-sm text-gray-300 max-w-2xl leading-relaxed">
+ Answers closed-set questions — &ldquo;which of these options does this text entail?&rdquo; — without generating text
+ or spending provider quota. When the top two options are too close to separate, it <strong>abstains</strong> rather
+ than guessing.
+ </p>
+
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <h3 className="text-sm font-semibold text-white">Installation</h3>
+ <span className="text-xs text-gray-400">{stages.filter((stage) => stage.ready).length} of {stages.length} checks ready</span>
+ </div>
+ <ol className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2 list-none p-0" aria-label="jev setup stages">
+ {stages.map((stage) => {
+ const current = installing && currentStageId === stage.id;
+ const waiting = installing && !stage.ready && currentStageId && currentStageId !== stage.id;
+ return (
+ <li
+ key={stage.id}
+ data-testid={`jev-stage-${stage.id}`}
+ data-ready={stage.ready ? 'true' : 'false'}
+ className="flex items-start gap-2 rounded-lg border border-port-border/70 bg-port-bg/40 px-3 py-2"
+ >
+ <span className="mt-0.5 shrink-0" aria-hidden="true">
+ {stage.ready ? (
+ <CheckCircle2 size={14} className="text-port-success" />
+ ) : current ? (
+ <BrailleSpinner />
+ ) : (
+ <Circle size={14} className={waiting ? 'text-gray-600' : 'text-port-warning'} />
+ )}
+ </span>
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <p className="text-xs font-medium text-white">{stage.label}</p>
+ <span className={`text-[11px] ${stage.ready ? 'text-port-success' : current ? 'text-gray-300' : 'text-gray-500'}`}>
+ {stage.ready ? 'Ready' : current ? 'Installing…' : waiting ? 'Waiting' : 'Not ready'}
+ </span>
+ </div>
+ <details className="mt-1 text-xs text-gray-400">
+ <summary className="cursor-pointer hover:text-port-accent">Details</summary>
+ <p className="mt-1 leading-relaxed">{stage.description}</p>
+ </details>
+ {stage.id === 'python' && !stage.ready && (
+ <a href="https://www.python.org/downloads/" target="_blank" rel="noopener noreferrer" className="text-xs text-port-accent hover:underline">Install Python, then refresh status</a>
+ )}
+ {current && progressMsg && <p className="text-[11px] text-gray-400 mt-1">{progressMsg}</p>}
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+
+ <div className="flex items-center gap-2 flex-wrap text-[11px] text-gray-500">
+ <span>{status?.name || 'OpenJEV Qwen3.5 4B NLI'}</span>
+ <span>·</span>
+ <span>{status?.weightsBytes ? formatBytes(status.weightsBytes) : '~9 GB'} · offline · no tools</span>
+ <a
+ href={status?.sourceUrl || 'https://huggingface.co/AlexWortega/openjev'}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-port-accent hover:underline inline-flex items-center gap-1"
+ >
+ Model card <ExternalLink size={11} />
+ </a>
+ </div>
+
+ <div className="flex items-center gap-2 flex-wrap">
+ <button type="button" onClick={loadStatus} disabled={installing} className="px-2.5 py-1 text-xs border border-port-border text-gray-300 rounded flex items-center gap-1 disabled:opacity-50">
+ <RefreshCw size={12} /> Refresh status
+ </button>
+ {ready ? (
+ <span className="text-xs text-port-success">Installed from the pinned model revision.</span>
+ ) : installing ? (
+ <>
+ <span className="flex items-center gap-1.5 text-xs text-gray-300"><BrailleSpinner /> Installing the jev scorer…</span>
+ <button type="button" onClick={cancel} className="px-2.5 py-1 text-xs bg-port-border hover:bg-port-border/70 text-gray-300 rounded">Cancel</button>
+ </>
+ ) : (
+ <button
+ type="button"
+ onClick={install}
+ disabled={!status || status.pythonAvailable !== true}
+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1"
+ >
+ <Download size={12} /> {incomplete ? 'Repair jev' : 'Install jev'}
+ </button>
+ )}
+ {status?.resident && (
+ <>
+ <span className="text-xs text-gray-400">Model resident on port {status.port}</span>
+ <button type="button" onClick={unload} className="px-2.5 py-1 text-xs border border-port-border text-gray-300 rounded">Unload now</button>
+ </>
+ )}
+ {installing && progressMsg && !installingStage && <span className="text-[11px] text-gray-500">{progressMsg}</span>}
+ </div>
+
+ {(installError || status?.lastInstallFailure) && (
+ <div role="alert" className="text-xs text-port-warning space-y-1 break-words">
+ {installError && <p>{installError}</p>}
+ {status?.lastInstallFailure && <p>{status.lastInstallFailure.stage}: {status.lastInstallFailure.code}. {status.lastInstallFailure.message} {status.lastInstallFailure.action}</p>}
+ </div>
+ )}
+ {status?.runtimeIssue && <p className="text-xs text-port-warning">{status.runtimeIssue.message} {status.runtimeIssue.action}</p>}
+ <p className="text-xs text-gray-400">
+ Install downloads Python packages and the pinned 4B weights only — the repository&rsquo;s larger variants are never fetched.
+ The scorer loads on the first question and unloads itself after ten idle minutes.
+ </p>
+ </div>
+
+ <div className="space-y-3 border-t border-port-border pt-4">
+ <h3 className="text-sm font-semibold text-white">Try a decision</h3>
+ <p className="text-xs text-gray-400 max-w-2xl">
+ Paste the text to reason over, then one option per line. At least two options: the confidence margin is the gap
+ between the best two, so a single option has nothing to be measured against.
+ </p>
+ <div>
+ <label htmlFor="jev-premise" className="block text-xs text-gray-400 mb-1">Premise</label>
+ <textarea
+ id="jev-premise"
+ value={premise}
+ onChange={(event) => setPremise(event.target.value)}
+ rows={4}
+ className="w-full text-sm bg-port-bg border border-port-border rounded p-2 text-gray-200"
+ placeholder="The text to reason over."
+ />
+ </div>
+ <div>
+ <label htmlFor="jev-hypotheses" className="block text-xs text-gray-400 mb-1">Options (one per line)</label>
+ <textarea
+ id="jev-hypotheses"
+ value={hypothesesText}
+ onChange={(event) => setHypothesesText(event.target.value)}
+ rows={4}
+ className="w-full text-sm bg-port-bg border border-port-border rounded p-2 text-gray-200"
+ placeholder={'This warrants a reply.\nThis warrants no reply.'}
+ />
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={runScore}
+ disabled={!canScore || scoring}
+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {scoring ? 'Scoring…' : 'Score'}
+ </button>
+ {!ready && <span className="text-xs text-gray-500">Install jev first.</span>}
+ {ready && hypotheses.length < 2 && <span className="text-xs text-gray-500">Add at least two options.</span>}
+ {scoring && <span className="flex items-center gap-1.5 text-xs text-gray-300"><BrailleSpinner /> The first question loads the model, which can take a minute.</span>}
+ </div>
+ {decision && (
+ <div role="status" data-testid="jev-decision" className="text-sm rounded-lg border border-port-border p-3 space-y-1">
+ {decision.ok === false ? (
+ <p className="text-port-warning">Scoring failed: {decision.code}</p>
+ ) : decision.abstained ? (
+ <>
+ <p className="text-port-warning">Abstained — the top two options were too close to separate.</p>
+ <p className="text-xs text-gray-400">Margin {decision.margin?.toFixed(3)}. A caller treats this as &ldquo;ask something else&rdquo;, never as &ldquo;take the top one anyway&rdquo;.</p>
+ </>
+ ) : (
+ <>
+ <p className="text-port-success break-words">Chose: {decision.choice}</p>
+ <p className="text-xs text-gray-400">Entailment {decision.confidence?.toFixed(3)} · margin {decision.margin?.toFixed(3)}</p>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/client/src/components/models/JevPanel.test.jsx b/client/src/components/models/JevPanel.test.jsx
new file mode 100644
index 0000000000..f913063723
--- /dev/null
+++ b/client/src/components/models/JevPanel.test.jsx
@@ -0,0 +1,167 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../services/api', () => ({
+ getJevStatus: vi.fn(),
+ installJev: vi.fn(),
+ cancelJevInstall: vi.fn(),
+ scoreJev: vi.fn(),
+ unloadJev: vi.fn(),
+}));
+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+vi.mock('../ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
+}));
+
+import { cancelJevInstall, getJevStatus, installJev, scoreJev, unloadJev } from '../../services/api';
+import socket from '../../services/socket';
+import JevPanel from './JevPanel';
+
+const stages = (ready) => [
+ { id: 'python', label: 'Host Python', description: 'A Python interpreter.', ready: true },
+ { id: 'venv', label: 'Dedicated jev runtime', description: 'A private virtualenv.', ready },
+ { id: 'packages', label: 'Scorer packages', description: 'Pinned scorer imports.', ready },
+ { id: 'model', label: 'Pinned model snapshot', description: 'The pinned subfolder files.', ready },
+];
+
+const status = (overrides = {}) => ({
+ id: 'openjev-qwen3.5-4b-nli',
+ name: 'OpenJEV Qwen3.5 4B NLI',
+ sourceUrl: 'https://huggingface.co/AlexWortega/openjev',
+ ready: false,
+ pythonAvailable: true,
+ setupState: 'not-installed',
+ port: 5566,
+ resident: false,
+ stages: stages(false),
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getJevStatus.mockResolvedValue(status());
+ installJev.mockResolvedValue({ ok: true, ready: true });
+ cancelJevInstall.mockResolvedValue({ cancelled: true });
+ unloadJev.mockResolvedValue({ unloaded: true });
+});
+
+const renderPanel = async () => {
+ render(<JevPanel />);
+ expect(await screen.findByRole('heading', { name: 'jev decision scorer' })).toBeInTheDocument();
+};
+
+describe('JevPanel install', () => {
+ it('shows four stages and no Hugging Face token step — openjev is ungated', async () => {
+ await renderPanel();
+ await waitFor(() => expect(screen.getByTestId('jev-stage-model')).toBeInTheDocument());
+ expect(screen.getAllByTestId(/^jev-stage-/)).toHaveLength(4);
+ expect(screen.queryByTestId('jev-stage-huggingface-token')).not.toBeInTheDocument();
+ });
+
+ it('offers repair for a partial setup and blocks installation without host Python', async () => {
+ getJevStatus.mockResolvedValue(status({ setupState: 'incomplete' }));
+ await renderPanel();
+ expect(await screen.findByRole('button', { name: 'Repair jev' })).toBeEnabled();
+
+ getJevStatus.mockResolvedValue(status({ pythonAvailable: false }));
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Refresh status' })); });
+ expect(await screen.findByRole('button', { name: 'Install jev' })).toBeDisabled();
+ });
+
+ it('marks the live install stage from jev progress frames and ignores other scopes', async () => {
+ let settle;
+ installJev.mockReturnValue(new Promise((resolve) => { settle = resolve; }));
+ await renderPanel();
+ const handler = socket.on.mock.calls.find(([event]) => event === 'localLlm:progress')[1];
+ fireEvent.click(await screen.findByRole('button', { name: 'Install jev' }));
+
+ // A Prompt Guard frame must not drive this panel's checklist — both panels
+ // subscribe to the same socket event and are told apart only by scope.
+ act(() => handler({ scope: 'security-guard', event: 'stage', stage: 'model', message: 'Downloading Prompt Guard…' }));
+ expect(screen.queryByText('Downloading Prompt Guard…')).not.toBeInTheDocument();
+
+ act(() => handler({ scope: 'jev', event: 'stage', stage: 'packages', message: 'Installing scorer runtime packages…' }));
+ expect(await screen.findByText('Installing scorer runtime packages…')).toBeInTheDocument();
+ await act(async () => { settle({ ok: false }); });
+ });
+
+ it('cancels an in-flight install', async () => {
+ let settle;
+ installJev.mockReturnValue(new Promise((resolve) => { settle = resolve; }));
+ await renderPanel();
+ fireEvent.click(await screen.findByRole('button', { name: 'Install jev' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }));
+ expect(cancelJevInstall).toHaveBeenCalled();
+ await act(async () => { settle({ ok: false }); });
+ });
+});
+
+describe('JevPanel try-it box', () => {
+ const ready = () => getJevStatus.mockResolvedValue(status({ ready: true, setupState: 'ready', stages: stages(true) }));
+
+ const fill = (premise, options) => {
+ fireEvent.change(screen.getByLabelText('Premise'), { target: { value: premise } });
+ fireEvent.change(screen.getByLabelText('Options (one per line)'), { target: { value: options } });
+ };
+
+ // The margin is top1 - top2, so one option has no runner-up. The UI must not
+ // let an operator send a request the service will only refuse.
+ it('requires at least two options before it will score', async () => {
+ ready();
+ await renderPanel();
+ fill('Some text.', 'only one option');
+ expect(screen.getByRole('button', { name: 'Score' })).toBeDisabled();
+ expect(screen.getByText('Add at least two options.')).toBeInTheDocument();
+
+ fill('Some text.', 'first\nsecond');
+ expect(screen.getByRole('button', { name: 'Score' })).toBeEnabled();
+ });
+
+ it('sends trimmed, blank-stripped options and renders the chosen option', async () => {
+ ready();
+ scoreJev.mockResolvedValue({ ok: true, choice: 'first', confidence: 0.91, margin: 0.8, abstained: false });
+ await renderPanel();
+ fill(' Some text. ', ' first \n\n second \n');
+ fireEvent.click(screen.getByRole('button', { name: 'Score' }));
+
+ await waitFor(() => expect(scoreJev).toHaveBeenCalledWith(
+ { premise: 'Some text.', hypotheses: ['first', 'second'] },
+ { silent: true },
+ ));
+ expect(await screen.findByText('Chose: first')).toBeInTheDocument();
+ });
+
+ // Abstention is the contract: the panel must never present a near-tie as a
+ // choice, because that is exactly what a caller is forbidden to do with it.
+ it('renders an abstention as an abstention, never as a winner', async () => {
+ ready();
+ scoreJev.mockResolvedValue({ ok: true, choice: null, confidence: null, margin: 0.03, abstained: true });
+ await renderPanel();
+ fill('Some text.', 'first\nsecond');
+ fireEvent.click(screen.getByRole('button', { name: 'Score' }));
+
+ const box = await screen.findByTestId('jev-decision');
+ expect(box).toHaveTextContent('Abstained');
+ expect(box).toHaveTextContent('0.030');
+ expect(box).not.toHaveTextContent('Chose:');
+ });
+
+ it('shows a failure code beside the input rather than swallowing it', async () => {
+ ready();
+ scoreJev.mockRejectedValue(new Error('jev-timeout'));
+ await renderPanel();
+ fill('Some text.', 'first\nsecond');
+ fireEvent.click(screen.getByRole('button', { name: 'Score' }));
+ expect(await screen.findByText('Scoring failed: jev-timeout')).toBeInTheDocument();
+ });
+
+ it('offers an immediate unload only while the model is resident', async () => {
+ await renderPanel();
+ expect(screen.queryByRole('button', { name: 'Unload now' })).not.toBeInTheDocument();
+
+ getJevStatus.mockResolvedValue(status({ ready: true, setupState: 'ready', stages: stages(true), resident: true }));
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Refresh status' })); });
+ await act(async () => { fireEvent.click(await screen.findByRole('button', { name: 'Unload now' })); });
+ expect(unloadJev).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index b73ccda097..283c993bf6 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -1,12 +1,14 @@
import { useNavigate } from 'react-router';
-import { Download, ShieldCheck } from 'lucide-react';
+import { Download, Scale, ShieldCheck } from 'lucide-react';
import TabPills from '../ui/TabPills.jsx';
+import JevPanel from '../models/JevPanel.jsx';
import ModelAbuseGuardPanel from '../models/ModelAbuseGuardPanel.jsx';
import LocalLlmLibraryView from './LocalLlmLibraryView.jsx';
export const LLM_VIEWS = [
{ id: 'library', label: 'Model Library', icon: Download },
{ id: 'abuse', label: 'Abuse Guard', icon: ShieldCheck },
+ { id: 'jev', label: 'jev', icon: Scale },
];
// Palettable LLM drill-downs. Model Library stays a focused view of
@@ -17,6 +19,7 @@ export const LLM_VIEWS = [
// Scraped by server/lib/navManifest.test.js.
export const LLM_NAV_SUBROUTES = [
{ id: 'abuse' },
+ { id: 'jev' },
];
// Dispatcher only. The two working surfaces are entirely disjoint — different
@@ -44,10 +47,13 @@ export function LocalLlmTab({ view }) {
<p className="text-xs text-gray-500">
{activeView === 'abuse'
? 'Install and verify each stage of the pinned Prompt Guard classifier used to screen external content.'
- : 'Find, install, compare, and remove the model weights available to Ollama and LM Studio.'}
+ : activeView === 'jev'
+ ? 'Install and try the pinned entailment scorer that answers closed-set questions locally — and abstains when the options are too close to call.'
+ : 'Find, install, compare, and remove the model weights available to Ollama and LM Studio.'}
</p>
</div>
{activeView === 'abuse' && <ModelAbuseGuardPanel />}
+ {activeView === 'jev' && <JevPanel />}
{activeView === 'library' && <LocalLlmLibraryView />}
</div>
);
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index 26eb070226..72f52be4ad 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -16,6 +16,9 @@ vi.mock('./LocalLlmLibraryView.jsx', () => ({
vi.mock('../models/ModelAbuseGuardPanel.jsx', () => ({
default: () => <div data-testid="abuse-view">abuse</div>,
}));
+vi.mock('../models/JevPanel.jsx', () => ({
+ default: () => <div data-testid="jev-view">jev</div>,
+}));
import { LocalLlmTab } from './LocalLlmTab';
@@ -61,7 +64,7 @@ describe('LocalLlmTab view dispatch', () => {
it('no longer advertises Runtimes as one of its pills', () => {
renderTab();
- expect(screen.getAllByRole('tab').map((t) => t.textContent)).toEqual(['Model Library', 'Abuse Guard']);
+ expect(screen.getAllByRole('tab').map((t) => t.textContent)).toEqual(['Model Library', 'Abuse Guard', 'jev']);
});
it('navigates between the focused panels with a shareable URL', () => {
@@ -71,6 +74,8 @@ describe('LocalLlmTab view dispatch', () => {
expect(screen.getByTestId('location')).toHaveTextContent('/models/llms/library');
fireEvent.click(screen.getByRole('tab', { name: 'Abuse Guard' }));
expect(screen.getByTestId('location')).toHaveTextContent('/models/llms/abuse');
+ fireEvent.click(screen.getByRole('tab', { name: 'jev' }));
+ expect(screen.getByTestId('location')).toHaveTextContent('/models/llms/jev');
});
it('describes the selected panel under the pills', () => {
diff --git a/client/src/hooks/useLocalLlmStatus.js b/client/src/hooks/useLocalLlmStatus.js
index 05d364365e..17cbed53c7 100644
--- a/client/src/hooks/useLocalLlmStatus.js
+++ b/client/src/hooks/useLocalLlmStatus.js
@@ -63,7 +63,7 @@ export default function useLocalLlmStatus({ onRefresh, onReload } = {}) {
// per model, so answering them would reload the status AND re-query the
// Hugging Face catalog once per measured model, all night. This tab owns
// the unscoped install/migrate/upgrade frames only.
- if (data?.scope === 'assessment' || data?.scope === 'assessment-sweep' || data?.scope === 'security-guard') return;
+ if (data?.scope === 'assessment' || data?.scope === 'assessment-sweep' || data?.scope === 'security-guard' || data?.scope === 'jev') return;
clearTimeout(progressTimer.current);
setProgressMsg(data.message || '');
if (data.event === 'complete') {
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 1ce8e24909..fec1e084a9 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -45,7 +45,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiCommands.js` | CLI command dispatch. |
| `apiDashboard.js` | Dashboard state. |
| `apiDatabase.js` | Database introspection. |
-| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, the managed Prompt Guard model-abuse classifier lifecycle, backend install (Homebrew/script), switch/migrate, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking + the server-side "measure everything" sweep). Also the PM2-managed runtime servers (llama.cpp, MTPLX, Slotstream) and their checkpoint catalogs — `searchMtplxModels` / `pullMtplxModel` / `removeMtplxModel` and `downloadSlotstreamModel` / `cancelSlotstreamModelDownload`, so weights are managed in-app rather than from a terminal. |
+| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, the managed Prompt Guard model-abuse classifier lifecycle, the jev entailment scorer lifecycle (status / install / cancel / score / unload), backend install (Homebrew/script), switch/migrate, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking + the server-side "measure everything" sweep). Also the PM2-managed runtime servers (llama.cpp, MTPLX, Slotstream) and their checkpoint catalogs — `searchMtplxModels` / `pullMtplxModel` / `removeMtplxModel` and `downloadSlotstreamModel` / `cancelSlotstreamModelDownload`, so weights are managed in-app rather than from a terminal. |
| `apiGit.js` | Git operations. |
| `apiGithub.js` | GitHub repo metadata. |
| `apiHistory.js` | Historical logs / runs. |
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index e1d6b08df5..897605cc61 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -38,6 +38,24 @@ export const cancelModelAbuseGuardInstall = (options) =>
...options,
});
+// The jev entailment scorer's own lifecycle, separate from the chat catalog
+// and from Prompt Guard's.
+export const getJevStatus = (options) => request('/local-llm/jev/status', options);
+
+export const installJev = (options) =>
+ request('/local-llm/jev/install', { method: 'POST', body: '{}', ...options });
+
+export const cancelJevInstall = (options) =>
+ request('/local-llm/jev/install/cancel', { method: 'POST', body: '{}', ...options });
+
+// Starts the sidecar on first use, so this is only ever called from an explicit
+// operator action.
+export const scoreJev = (body, options) =>
+ request('/local-llm/jev/score', { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const unloadJev = (options) =>
+ request('/local-llm/jev/unload', { method: 'POST', body: '{}', ...options });
+
export const getLocalLlmHuggingFaceSearch = (backend, q = '', category = 'all', limit = 12) =>
request(`/local-llm/huggingface-search?backend=${encodeURIComponent(backend)}&category=${encodeURIComponent(category)}&limit=${encodeURIComponent(limit)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);
diff --git a/docs/JEV_SETUP.md b/docs/JEV_SETUP.md
new file mode 100644
index 0000000000..bb2e00ddcc
--- /dev/null
+++ b/docs/JEV_SETUP.md
@@ -0,0 +1,130 @@
+# jev setup and recovery
+
+**jev** is PortOS's local *entailment scorer*: give it a premise and a list of
+hypotheses, get back a per-hypothesis entailment distribution and an argmax with
+a confidence margin. It answers **closed-set questions** — "which of these
+options does this text entail?" — with no text generation, no tool surface, and
+no provider quota. See the ADR
+[local jev decision service](./decisions/2026-09-18-local-jev-decision-service.md)
+for why it exists and what was rejected.
+
+It is an **optional** feature, off by default. Turn it on in **Settings >
+Features**; its page stays reachable at `/models/llms/jev` either way, and the
+nav entry appears once the feature is enabled.
+
+## What gets installed
+
+| | |
+|---|---|
+| Model | `AlexWortega/openjev`, subfolder `qwen3.5-4b-nli`, revision `f8187e6e11d413d0771bcc7970b85f78e194264c` |
+| License | MIT, ungated — **no Hugging Face token or model-card approval** |
+| Download | 4 files, ~9.1 GB (weights dominate). The repository's 35B variant, its trained MLP heads, and its `code/` directory are never fetched and never executed |
+| Runtime | A dedicated virtualenv at `data/python/venv-jev` (fallback `~/.portos/venv-jev`) — separate from Prompt Guard's and from the image/video runtimes |
+| Packages | `torch`, `transformers`, `safetensors`, `huggingface_hub`, pinned in `server/lib/jev.js` |
+| Port | `PORTS.JEV` = 5566, loopback only, bound on demand |
+
+Nothing above happens at boot, on a status refresh, or on first request. The
+download runs only from an explicit operator install.
+
+## Install and diagnose
+
+Models → LLMs → jev shows the four install stages (`python`, `venv`,
+`packages`, `model`), the failed runtime check, expected package versions, and
+the last failed installation stage with its diagnosis. Overall **ready** is true
+only when the pinned packages import *and* the pinned snapshot is cached.
+
+For unattended local diagnosis, run from the PortOS checkout:
+
+```sh
+node scripts/setup-jev.js --status
+node scripts/setup-jev.js --install
+```
+
+Both print JSON to stdout and exit 0 only when ready (1 otherwise). Install
+progress goes to stderr. `--status` never installs, downloads, or loads a model.
+Run these from the primary installation after updating it — CoS worktrees
+deliberately use isolated data and ignore `PORTOS_DATA_ROOT`.
+
+Install prefers an already-installed `uv` package installer and falls back to
+Python pip, for machines where uv can reach the package index but pip cannot.
+Repair retries the dedicated runtime without touching Prompt Guard or the image
+and video environments.
+
+## The sidecar
+
+Unlike Prompt Guard, which spawns a Python process per scanned item, jev runs a
+**persistent sidecar**: `scripts/run_jev.py` binds `127.0.0.1:5566`, loads the
+checkpoint once, and answers JSON scoring requests. A 4B model is far too
+expensive to re-import per call.
+
+- It starts on the **first scoring call**, never at boot.
+- Two concurrent first callers produce exactly one process.
+- An idle timer unloads it after **10 minutes**; **Unload now** on the panel
+ frees it immediately.
+- It refuses to start without its model directory, refuses a non-loopback peer,
+ and refuses a premise that exceeds the model window rather than truncating and
+ answering about the prefix.
+- It never echoes the premise or a hypothesis back in an error, and its stderr
+ is drained but never retained — a dependency traceback can carry local paths
+ or the input itself.
+
+## Abstention is the contract
+
+`decide()` returns `abstained: true` whenever the margin between the top two
+options' entailment probabilities falls below the threshold (default `0.15`).
+
+**A caller must treat abstention as "ask something else" — never as "take the
+top one anyway."** The margin is the entire difference between "the model
+distinguished these options" and "the model produced a number". A caller that
+wants an additional floor beneath a clear-but-weak winner applies it on top of
+the reported `confidence`; the service itself gates on margin alone.
+
+The margin needs a runner-up, so `decide()` requires **at least two options**. A
+yes/no question is expressed as two hypotheses (`"…warrants a reply"` /
+`"…warrants no reply"`), not one.
+
+## Failure codes
+
+Codes, never text. A Python traceback can carry local paths or the premise, so
+nothing from the sidecar's stderr ever reaches a payload or a log line.
+
+| Code | Meaning |
+|---|---|
+| `jev-not-installed` | No dedicated virtualenv, or the pinned snapshot is not cached. Install from Models → LLMs → jev. |
+| `jev-start-failed` | The sidecar could not be started, or died before reporting a loaded model. Check the install stages, then free memory — the checkpoint needs roughly its 9 GB on disk plus room to load. |
+| `jev-timeout` | A scoring request exceeded its timeout (default 30 s). |
+| `jev-request-invalid` | The premise or hypothesis list failed the bounds in `server/lib/jev.js`, or fewer than two options reached `decide()`. |
+| `jev-response-invalid` | The sidecar's reply did not match the wire schema, or described a different hypothesis list than the one asked about. |
+| `jev-premise-too-large` | The premise exceeded 32,000 characters, or the rendered pair exceeded the model window. The request is refused, not truncated. |
+
+Install-stage failures reuse the shared Python diagnosis vocabulary —
+`package-missing`, `package-version-mismatch`, `network-failed`,
+`certificate-failed`, `wheel-unavailable`, `dependency-conflict`, `disk-full`
+(`server/lib/pythonRuntimeDiagnosis.js`). For `network-failed`, check Python's
+access to the configured package index; a browser or curl succeeding does not
+prove Python can connect. For `certificate-failed`, repair certificate trust
+rather than disabling TLS verification.
+
+## Bounds
+
+Declared once in `server/lib/jev.js` and mirrored into `scripts/run_jev.py` so
+the boundary still holds if the script is invoked directly:
+
+| | |
+|---|---|
+| Premise | 32,000 characters |
+| Hypotheses | 32 per request, 512 characters each |
+| Default margin | 0.15 |
+| Request timeout | 30 s |
+| Idle unload | 10 minutes |
+
+## What jev is not
+
+It is **not selectable as a chat provider**. The descriptor is exposed beside
+the catalog under its own `decisionScorers` key — the same guarantee
+`securityGuards` gives Prompt Guard — and is never merged into `models`, so no
+provider or model picker can offer it.
+
+It is also not a replacement for the abuse guard. Prompt Guard screens external
+content *before* anything reasons over it; jev is one of the things that may
+then reason over it. See [features/messages-security.md](./features/messages-security.md).
diff --git a/docs/PORTS.md b/docs/PORTS.md
index d6a4845fff..2296a9bba6 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -37,6 +37,7 @@ Common port labels:
| 5562 | portos-whisper | whisper-server | Loopback whisper.cpp speech-to-text server. |
| 5563 | portos-server | eidoverse-host | Optional legacy HTTPS/WebSocket bridge for Eidoverse Worlds (on demand → loopback `:8940`). Prefer the same-origin path on `:5555` — `/eidoverse-host` plus root allowlist proxies — so a single-port tailcat forward (`:15555` → `:5555`) can embed the iframe. |
| 5564 | portos-slotstream | - | Loopback SSD-streaming MoE runtime. Optional PM2 process, started/stopped from Models → Runtimes. Never 11434 — that port is a PortOS-managed Ollama. |
+| 5566 | jev sidecar (loopback) | - | Loopback openjev entailment scorer. Not a PM2 process: `server/services/jev.js` starts it on the first scoring call and reaps it after ten idle minutes. See [JEV_SETUP.md](./JEV_SETUP.md). |
| 5568 | portos-llama-server | - | Loopback llama.cpp speculative-decoding server. Optional PM2 process, started/stopped from Models → Runtimes. |
| 8000 | portos-mtplx | - | Loopback MTPLX OpenAI-compatible API (upstream's own default, kept so the shipped provider presets match). Optional PM2 process, started/stopped from Models → Runtimes. See [features/mtplx.md](./features/mtplx.md). |
| 18022 | PortOS model host | - | Opt-in bearer-authenticated inference queue for dedicated hosts; one active generation. See [fleet host](./features/fleet-llm-host.md). |
@@ -142,7 +143,7 @@ PortOS automatically detects ports from env vars:
| Range | Purpose |
|-------|---------|
| 5553-5561 | PortOS core services (includes the `:5553` loopback mirror and the `portos-db` Docker container on `:5561`) |
-| 5562-5569 | Reserved for PortOS extensions. Assigned: 5562 whisper, 5563 Eidoverse bridge (on demand), 5564 slotstream (on demand), 5565 Tailcat ingress (on demand), 5568 llama-server. Unassigned but still reserved: 5566-5567, 5569 |
+| 5562-5569 | Reserved for PortOS extensions. Assigned: 5562 whisper, 5563 Eidoverse bridge (on demand), 5564 slotstream (on demand), 5565 Tailcat ingress (on demand), 5566 jev scorer (on demand), 5568 llama-server. Unassigned but still reserved: 5567, 5569 |
| 5570-5599 | User applications — **put managed apps here** |
> **A collision inside `5553-5569` is silent, not loud.** The natural assumption is
@@ -157,7 +158,7 @@ PortOS automatically detects ports from env vars:
> without an error, PortOS logged `🌐 Eidoverse host listening`, and the Eidoverse page
> served the other app's admin UI. Nothing in either process reported a problem.
>
-> The on-demand ports (5563, 5564, 5568) are the easiest to get wrong, because they are free
+> The on-demand ports (5563, 5564, 5566, 5568) are the easiest to get wrong, because they are free
> at boot and only bind once a user opens the relevant page — so a port scan taken at
> install time shows them available. Treat the whole band as taken regardless.
>
diff --git a/docs/README.md b/docs/README.md
index 5cbacd57ab..27ec7abd7b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -59,7 +59,7 @@ Comms & voice: [beeper](./features/beeper.md) · [openclaw-operator-chat](./feat
## Point-in-time records
- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs. See [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md) for stable executable routes, migration and management flows.
-- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md), [Eidoverse guest chat](./decisions/2026-09-05-eidoverse-guest-chat.md), [numeric PortOS quality federation](./decisions/2026-09-10-portos-quality-federation.md), [federated Eidoverse foundations](./decisions/2026-09-18-federated-eidoverse-foundations.md)), and why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md).
+- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md), [Eidoverse guest chat](./decisions/2026-09-05-eidoverse-guest-chat.md), [numeric PortOS quality federation](./decisions/2026-09-10-portos-quality-federation.md), [federated Eidoverse foundations](./decisions/2026-09-18-federated-eidoverse-foundations.md)), why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md), and why closed-set decisions run on a [local entailment model that abstains](./decisions/2026-09-18-local-jev-decision-service.md).
- **research/** — dated investigation and incident write-ups (e.g. the [mflux GPU-watchdog panic](./research/2026-06-13-mflux-training-watchdog-panic.md) and the [local LLM performance audit](./research/2026-08-22-local-llm-performance-audit.md)).
- **superpowers/** — plan/spec pairs from superpowers-driven builds: `specs/<date>-<slug>-design.md` (design) + `plans/<date>-<slug>.md` (implementation plan).
diff --git a/docs/decisions/2026-09-18-local-jev-decision-service.md b/docs/decisions/2026-09-18-local-jev-decision-service.md
new file mode 100644
index 0000000000..9d7a0bffcf
--- /dev/null
+++ b/docs/decisions/2026-09-18-local-jev-decision-service.md
@@ -0,0 +1,149 @@
+# ADR: Closed-Set Decisions Run on a Local Entailment Model That Abstains
+
+- **Date:** 2026-09-18
+- **Status:** Accepted
+- **Related:** epic #7640 (the decision-primitive epic), issue #7641 (this record,
+ the substrate), #7642 (switching callers), #7643 (training a head),
+ [`server/lib/jev.js`](../../server/lib/jev.js),
+ [`server/services/jev.js`](../../server/services/jev.js),
+ [`scripts/run_jev.py`](../../scripts/run_jev.py),
+ [`docs/JEV_SETUP.md`](../JEV_SETUP.md),
+ [`docs/features/messages-security.md`](../features/messages-security.md).
+
+## Context
+
+PortOS had no way to ask a local model a **closed-set question**. Every decision
+over untrusted external text went through `runUntrustedContentAnalysis`
+(`server/services/untrustedContent.js`), which is a generative chat completion —
+even when the required answer is one of two fixed tokens.
+
+Using a generative model for a two-way classification is wrong in three
+independent ways, and they compound:
+
+- **It spends what it does not need.** Every `reply | none` question costs a
+ provider call, a quota unit, and a round trip, on a decision that needs no
+ prose.
+- **It cannot report its own uncertainty.** A chat model asked to pick one of
+ two options picks one. There is no calibrated quantity in the response that
+ distinguishes "the text clearly warrants a reply" from "the model had to say
+ something." An unreliable answer and a confident one look identical at the
+ call site.
+- **It widens the blast radius of untrusted input.** The decision path runs a
+ general-purpose instruction-following model over attacker-influenced text.
+ Prompt Guard screens that text first, but a classifier boundary is narrower
+ than a generative one by construction: a cross-encoder has no instructions to
+ follow.
+
+This ADR is also the first record under `docs/decisions/` covering **local-model
+usage and AI provider selection at all** — there was none, so every one of these
+questions was re-derived per review.
+
+## Decision
+
+**A closed-set question is answered by a local entailment model that is allowed
+to refuse to answer.**
+
+Concretely, four commitments:
+
+### 1. The engine is a pinned, ungated NLI cross-encoder
+
+`AlexWortega/openjev`, subfolder `qwen3.5-4b-nli`, revision
+`f8187e6e11d413d0771bcc7970b85f78e194264c` — MIT, ungated,
+`Qwen3_5ForSequenceClassification`, three labels (`contradiction`, `entailment`,
+`neutral`). It is loaded offline through `transformers` with
+`local_files_only=True`, `trust_remote_code=False`, `use_safetensors=True`, and
+a required-file allowlist that pins **four files inside one subfolder**. The
+repository also carries a 35B MoE variant, trained MLP heads, and a `code/`
+directory; none of those are ever downloaded and none are ever executed.
+
+Three alternatives were rejected in #7640:
+
+- **A prompted local chat model** (Ollama/LM Studio). Cheaper to build — it
+ reuses an installed model — but it reproduces the calibration problem exactly:
+ the output is still generated text, and a log-prob over a single token is not
+ the same quantity as an entailment probability. It would also have re-created
+ the instruction-following surface this decision exists to remove.
+- **A cloud classification endpoint.** Fastest to ship and needs no local
+ runtime, but the premise IS the untrusted external text, often quoted
+ alongside the operator's own records. Sending it off the machine per decision
+ contradicts the machine-local constraint below, and it re-introduces the quota
+ cost the local path exists to eliminate.
+- **A trained-from-scratch head on an existing embedding model.** Cheapest at
+ inference, and PortOS already runs embeddings — but it needs labelled data
+ PortOS does not have, and a head trained on one install's records is exactly
+ the artifact the privacy constraint forbids sharing. That path is not closed:
+ #7643 revisits it *on top of* this substrate, where a trained head is an
+ optimization over a working baseline rather than a prerequisite for having one.
+
+### 2. Abstention is the contract, not a nicety
+
+`decide()` returns `abstained: true` whenever the margin between the top two
+options' entailment probabilities falls below a threshold (default `0.15`).
+
+**A caller must treat that as "ask something else" — never as "take the top one
+anyway."** This is the load-bearing clause of the whole decision. A scorer that
+always answers is a scorer whose confidence is uninformative, which is the
+defect that made the generative path unsatisfactory in the first place. The
+value this service adds over a coin flip *is* the margin.
+
+Two corollaries fall out of defining the margin as `top1 - top2`:
+
+- `decide()` requires **at least two options**. With one hypothesis there is no
+ runner-up, and defining a fallback scale for that case (entailment against its
+ own contradiction mass) would make one threshold mean two different things.
+ A yes/no question is expressed as two hypotheses.
+- The winner's raw `confidence` is **reported but not gated on**. A clear-but-
+ weak winner (0.20 against 0.02) clears a 0.15 margin. Callers that want a
+ floor apply it themselves; this service does not grow a second knob until a
+ caller actually needs one.
+
+### 3. It is machine-local, and it is never a chat provider
+
+The model, the weights, the virtualenv, and the sidecar all live on one machine.
+The scorer runs with credentials stripped, `HF_HUB_OFFLINE=1` and
+`TRANSFORMERS_OFFLINE=1` set, a loopback-only bind, and no URL fetching. The
+premise — which routinely contains external content quoted next to the
+operator's own records — never leaves the host, and nothing about jev crosses
+the federation layer. That follows the existing constraint in ADR
+[privacy records machine-local](./2026-08-08-privacy-records-machine-local.md)
+rather than carving a new exception: this is a *decision service*, not a media
+job, and none of the job-body carve-outs apply to it.
+
+The descriptor is exposed beside the local-model catalog under its own
+`decisionScorers` key and is never merged into `models`, mirroring the guarantee
+`securityGuards` already gives Prompt Guard. No provider or model picker can
+offer it as a chat model.
+
+### 4. Nothing runs until an operator asks
+
+The feature is **off by default** in `instanceFeatureRegistry.js`. The ~9 GB
+download runs only from an explicit install action. The sidecar starts on the
+**first scoring call**, never at boot, and an idle timer unloads it after ten
+minutes. That is the AI Provider Usage Policy applied to a local model: the fact
+that a call costs no quota does not make it something a fresh install may do
+uninvited — it costs memory, and on a laptop that is the scarcer resource.
+
+## Consequences
+
+- PortOS gains a decision primitive with a **reportable uncertainty**, which is
+ what lets #7642 switch existing callers incrementally: each one can fall back
+ to its current generative path on abstention, so the switch is strictly
+ additive rather than a cutover.
+- It costs a second managed Python runtime and a second install surface. That is
+ deliberate: sharing a virtualenv with Prompt Guard would couple two
+ independent boundaries to one dependency resolution, and repairing one could
+ break the other. The shared part is the *diagnosis vocabulary*
+ (`server/lib/pythonRuntimeDiagnosis.js`), not the environment.
+- A long-lived subprocess on a new port is a new operational failure mode.
+ Mitigated by a single-flight start guard, an idle reaper, an explicit unload
+ control, and a loopback-only bind — but it is a real addition to what can be
+ wrong on an install, and `docs/JEV_SETUP.md` carries the failure-code table
+ for it.
+- No entry is added to `server/lib/creativeLatitude.js`. That module classifies
+ stage names and `runPromptThroughProvider` source tags; jev builds no prompt
+ and reaches neither shared runner, so there is nothing for either guard test
+ to see. Recorded here rather than added as a row no code path consults.
+- The sidecar is **unauthenticated on loopback**, like whisper, llama-server,
+ and slotstream before it. Adding a shared secret would make it the only local
+ runtime in the tree that has one, for a threat the Security Model's trust
+ boundary does not include.
diff --git a/docs/features/messages-security.md b/docs/features/messages-security.md
index 0468dfbe81..50e6052ff5 100644
--- a/docs/features/messages-security.md
+++ b/docs/features/messages-security.md
@@ -19,6 +19,8 @@ The GitHub role split does not change explicitly configured Jira or existing Git
1. **Screen complete accepted input.** Reject oversized content before inference rather than scanning a prefix. Deterministic hidden-content checks precede the offline Prompt Guard classifier: invisible/direction-control Unicode (including filenames), HTML comments and collapsed markup (`hidden`, `aria-hidden`, `display:none`) that address a model, encoded/compressed payloads, a new symlink that leaves the tree or a new git submodule, a non-media binary patch, and inline script in SVG/HTML. PR review also screens commit messages with the same title/body/diff pass. The classifier is required by default. Invalid policies, a broken/partial installation, malformed results and incomplete token-window coverage stop processing.
2. **Analyze without tools or private context.** `runUntrustedContentAnalysis` uses an API text completion, offers no tools or agent harness, and disables provider fallback. Private message sources require a loopback endpoint. Raw messages are not combined with digital-twin identity documents. External text is framed as evidence; framing itself is not an injection detector.
+
+ **Optional phase-2 reasoner: the local jev entailment scorer.** Where the required answer is one of a fixed set of options rather than prose, `server/services/jev.js` can answer it locally with no provider call, no generated text, and no tool surface — and it **abstains** when the top two options are too close to separate, which returns the question to the generative path above rather than producing a confident guess. It is off by default, installs its own pinned model, and is never selectable as a chat provider. It does not replace layer 1: Prompt Guard still screens the content before anything, including jev, reasons over it. See [JEV_SETUP.md](../JEV_SETUP.md) and the ADR [local jev decision service](../decisions/2026-09-18-local-jev-decision-service.md). No caller is switched to it yet.
3. **Validate and authorize effects in code.** Callers supply strict response contracts and check source identities and fresh state before acting. Issue replies and assignments use known issue/comment IDs; model prose never becomes a shell command. Maintenance analysis returns only fixed enums, not a freeform model summary that could repeat an attack. Issue maintenance separately receives screened requirements authored by a trusted account and a verified merge commit on the default branch; it can inspect that accepted code without importing outside PR descriptions. Message triage remains recommendations; replies remain drafts under the existing send-authorization flow.
PR review does not execute contributor tests or apply patches in its default stages. Read-only filesystem access and a disposable worktree are not equivalent to denying tools or isolating malicious code. A provider must expose an actual maintained recipe for the requested posture; unsupported stage pins must be corrected in schedule settings. A screening pass never grants broader permissions.
@@ -66,5 +68,6 @@ Message triage and replies use `email` by default. Channel-aware outreach select
- `server/services/messageEvaluator.js`: triage recommendations and reply drafts.
- `server/services/modelAbuseGuard.js` and `scripts/run_prompt_guard.py`: passive readiness, explicit install/scan, offline classification.
- `client/src/components/models/ModelAbuseGuardPanel.jsx`: install/repair and source-policy settings.
+- `server/lib/jev.js`, `server/services/jev.js` and `scripts/run_jev.py`: the optional local entailment scorer — pinned contract, sidecar lifecycle, and the abstaining `decide()`.
Remediation plans: [#6255](https://github.com/atomantic/PortOS/issues/6255), [#6256](https://github.com/atomantic/PortOS/issues/6256), [#6257](https://github.com/atomantic/PortOS/issues/6257), [#6258](https://github.com/atomantic/PortOS/issues/6258).
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 49e679945f..1f7a8bc228 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -123,6 +123,7 @@ const PORTS = {
WHISPER: 5562, // Loopback whisper.cpp speech-to-text server
EIDOVERSE_HOST: 5563, // Optional HTTPS/WebSocket bridge to Eidoverse Worlds on :8940
SLOTSTREAM: 5564, // Loopback SSD-streaming MoE runtime (never 11434 — that collides with Ollama)
+ JEV: 5566, // Loopback openjev entailment scorer. On-demand sidecar started by services/jev.js on first score, reaped when idle.
LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding server
FLEET_LLM: 18022, // Authenticated shared inference queue for dedicated hosts
diff --git a/scripts/run_jev.py b/scripts/run_jev.py
new file mode 100644
index 0000000000..f862f7c236
--- /dev/null
+++ b/scripts/run_jev.py
@@ -0,0 +1,262 @@
+#!/usr/bin/env python3
+"""Serve the pinned openjev entailment scorer on a loopback port.
+
+Unlike `run_prompt_guard.py`, which classifies one item per process, this is a
+long-lived sidecar: the Node service starts it on first use and reaps it after
+an idle period. A 4B checkpoint costs far too much to load per request, and the
+scorer is meant to answer dozens of closed-set questions per sweep.
+
+It is deliberately a classifier, not an agent: it accepts no tools, fetches no
+URLs, executes no repository code, and never emits the premise or hypothesis
+text back in an error.
+
+ POST /score {"premise": str, "hypotheses": [str, ...]}
+ -> {"schemaVersion": 1, "complete": true, "scores": [...]}
+ GET /health -> {"ready": bool, "model": str, "revision": str, "device": str}
+"""
+
+import argparse
+import json
+import sys
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from threading import Lock
+
+# Mirrors of the bounds in server/lib/jev.js. Repeated rather than imported so
+# this boundary still holds if the script is ever invoked directly.
+MAX_PREMISE_CHARS = 32_000
+MAX_HYPOTHESES = 32
+MAX_HYPOTHESIS_CHARS = 512
+MAX_BODY_BYTES = 256_000
+LOOPBACK_HOSTS = ("127.0.0.1", "::1")
+
+# The model's own label order, from the pinned config's `id2label`.
+LABELS = ("contradiction", "entailment", "neutral")
+# Used only when the checkpoint's config omits its own `nli_template`.
+FALLBACK_TEMPLATE = "Premise: {premise}\nHypothesis: {hypothesis}"
+
+
+class JevError(Exception):
+ """A failure the Node service can map to a code without reading text."""
+
+ def __init__(self, code: str, status: int = 400) -> None:
+ super().__init__(code)
+ self.code = code
+ self.status = status
+
+
+def validate_request(payload):
+ """Validate a scoring request. Never returns partial input on failure."""
+ if not isinstance(payload, dict):
+ raise JevError("jev-request-invalid")
+ premise = payload.get("premise")
+ hypotheses = payload.get("hypotheses")
+ if not isinstance(premise, str) or not premise.strip():
+ raise JevError("jev-request-invalid")
+ if len(premise) > MAX_PREMISE_CHARS:
+ raise JevError("jev-premise-too-large")
+ if not isinstance(hypotheses, list) or not 1 <= len(hypotheses) <= MAX_HYPOTHESES:
+ raise JevError("jev-request-invalid")
+ for hypothesis in hypotheses:
+ if not isinstance(hypothesis, str) or not hypothesis.strip():
+ raise JevError("jev-request-invalid")
+ if len(hypothesis) > MAX_HYPOTHESIS_CHARS:
+ raise JevError("jev-request-invalid")
+ return premise, hypotheses
+
+
+def load_state(model_dir: Path):
+ """Load the pinned snapshot once. Imports happen only after path checks."""
+ import torch
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
+
+ torch.set_num_threads(1)
+ tokenizer = AutoTokenizer.from_pretrained(
+ str(model_dir), local_files_only=True, trust_remote_code=False
+ )
+ model = AutoModelForSequenceClassification.from_pretrained(
+ str(model_dir),
+ local_files_only=True,
+ trust_remote_code=False,
+ use_safetensors=True,
+ )
+ # MPS where the host has it, CPU otherwise. Reported on /health so an
+ # operator can tell a slow CPU fallback from a healthy accelerated load.
+ device = "mps" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available() else "cpu"
+ model.to(device)
+ model.eval()
+
+ config = model.config
+ template = getattr(config, "nli_template", None)
+ if not isinstance(template, str) or "{premise}" not in template or "{hypothesis}" not in template:
+ template = FALLBACK_TEMPLATE
+
+ # The label mapping is read from the checkpoint rather than assumed: a
+ # re-trained head with a permuted id2label would otherwise silently turn
+ # every entailment score into a contradiction score.
+ id_to_label = getattr(config, "id2label", None) or {}
+ label_index = {}
+ for class_id, label in id_to_label.items():
+ name = str(label).strip().lower()
+ if name in LABELS:
+ label_index[name] = int(class_id)
+ if len(label_index) != len(LABELS):
+ raise JevError("jev-response-invalid", status=500)
+
+ return {
+ "torch": torch,
+ "tokenizer": tokenizer,
+ "model": model,
+ "device": device,
+ "template": template,
+ "labelIndex": label_index,
+ "window": resolve_window(tokenizer, config),
+ }
+
+
+def resolve_window(tokenizer, config) -> int:
+ """The largest token count one pair may occupy.
+
+ Transformers uses a sentinel-sized `model_max_length` for tokenizers that
+ declare none, which would read as "everything fits" — so an implausible
+ value falls through to the text config's position count.
+ """
+ candidates = []
+ for value in (getattr(tokenizer, "model_max_length", None),
+ getattr(getattr(config, "text_config", None), "max_position_embeddings", None),
+ getattr(config, "max_position_embeddings", None)):
+ if isinstance(value, int) and 0 < value < 10_000_000:
+ candidates.append(value)
+ if not candidates:
+ raise JevError("jev-response-invalid", status=500)
+ return min(candidates)
+
+
+def score_pairs(state, premise: str, hypotheses):
+ """One forward pass per premise/hypothesis pair, in request order."""
+ torch = state["torch"]
+ tokenizer = state["tokenizer"]
+ model = state["model"]
+ label_index = state["labelIndex"]
+ scores = []
+ with torch.inference_mode():
+ for hypothesis in hypotheses:
+ text = state["template"].format(premise=premise, hypothesis=hypothesis)
+ token_ids = tokenizer.encode(text, add_special_tokens=True, truncation=False)
+ # Never truncate and then return a verdict on the prefix: a
+ # decision about the first half of a diff is not a decision about
+ # the diff, and nothing downstream could tell the difference.
+ if len(token_ids) > state["window"]:
+ raise JevError("jev-premise-too-large")
+ model_inputs = {
+ "input_ids": torch.tensor([token_ids]),
+ "attention_mask": torch.tensor([[1] * len(token_ids)]),
+ }
+ probabilities = torch.softmax(model(**model_inputs).logits[0], dim=-1)
+ scores.append({
+ "hypothesis": hypothesis,
+ **{label: float(probabilities[label_index[label]].item()) for label in LABELS},
+ })
+ return scores
+
+
+def make_handler(state, model_id: str, revision: str):
+ lock = Lock()
+
+ class JevHandler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *_args):
+ """Silence the default access log — request lines are not ours to keep."""
+
+ def _respond(self, status: int, payload: dict) -> None:
+ body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _is_loopback(self) -> bool:
+ # Defence in depth: the socket is bound to loopback already, so a
+ # remote peer cannot normally arrive here at all.
+ return str(self.client_address[0]).split("%")[0] in LOOPBACK_HOSTS
+
+ def do_GET(self): # noqa: N802 - BaseHTTPRequestHandler's naming
+ if not self._is_loopback():
+ self._respond(403, {"error": "jev-request-invalid"})
+ return
+ if self.path != "/health":
+ self._respond(404, {"error": "jev-request-invalid"})
+ return
+ self._respond(200, {
+ "ready": True,
+ "model": model_id,
+ "revision": revision,
+ "device": state["device"],
+ })
+
+ def do_POST(self): # noqa: N802 - BaseHTTPRequestHandler's naming
+ if not self._is_loopback():
+ self._respond(403, {"error": "jev-request-invalid"})
+ return
+ if self.path != "/score":
+ self._respond(404, {"error": "jev-request-invalid"})
+ return
+ length = self.headers.get("Content-Length")
+ if not str(length or "").isdigit() or int(length) > MAX_BODY_BYTES:
+ self._respond(400, {"error": "jev-request-invalid"})
+ return
+ raw = self.rfile.read(int(length))
+ try:
+ premise, hypotheses = validate_request(json.loads(raw.decode("utf-8")))
+ # One model, one accelerator queue: serialize so two concurrent
+ # callers cannot interleave forward passes on the same weights.
+ with lock:
+ scores = score_pairs(state, premise, hypotheses)
+ except JevError as error:
+ self._respond(error.status, {"error": error.code})
+ return
+ except Exception: # noqa: BLE001 - must fail closed without leaking input or paths.
+ self._respond(500, {"error": "jev-response-invalid"})
+ return
+ self._respond(200, {"schemaVersion": 1, "complete": True, "scores": scores})
+
+ return JevHandler
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Serve openjev entailment scoring locally and offline.")
+ parser.add_argument("--model-dir", required=True)
+ parser.add_argument("--port", required=True, type=int)
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--model-id", default="openjev")
+ parser.add_argument("--revision", default="")
+ args = parser.parse_args()
+
+ if args.host not in LOOPBACK_HOSTS:
+ raise ValueError("host must be loopback")
+ if not 1 <= args.port <= 65535:
+ raise ValueError("port is out of range")
+ model_dir = Path(args.model_dir)
+ if not model_dir.is_dir():
+ raise ValueError("model snapshot is unavailable")
+
+ state = load_state(model_dir)
+ server = ThreadingHTTPServer((args.host, args.port), make_handler(state, args.model_id, args.revision))
+ # The single readiness signal the Node service waits on before polling
+ # /health. Nothing else is ever written to stdout.
+ sys.stdout.write(json.dumps({"ready": True, "port": args.port, "device": state["device"]}) + "\n")
+ sys.stdout.flush()
+ server.serve_forever()
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except KeyboardInterrupt:
+ raise SystemExit(0)
+ except Exception: # noqa: BLE001 - CLI boundary must fail closed without leaking input or paths.
+ print("jev failed to start; verify the dedicated runtime and pinned model snapshot.", file=sys.stderr)
+ raise SystemExit(1)
diff --git a/scripts/run_jev.test.js b/scripts/run_jev.test.js
new file mode 100644
index 0000000000..1920ad1f72
--- /dev/null
+++ b/scripts/run_jev.test.js
@@ -0,0 +1,161 @@
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../server/lib/testHelper.js';
+import { normalizeJevScores } from '../server/lib/jev.js';
+
+const python = resolveTestPython();
+const script = fileURLToPath(new URL('./run_jev.py', import.meta.url));
+
+// Synthetic tokenizer/model doubles exercise the shipped Python runner without
+// downloading 9 GB of weights or invoking a provider in the test suite.
+const HARNESS = `
+import contextlib, json, runpy, sys
+from types import SimpleNamespace
+helper = runpy.run_path(sys.argv[1])
+
+encoded = []
+def encode(text, **kwargs):
+ assert kwargs == {"add_special_tokens": True, "truncation": False}, kwargs
+ encoded.append(text)
+ return list(range(TOKEN_COUNT))
+tokenizer = SimpleNamespace(encode=encode, model_max_length=WINDOW)
+
+class Probabilities(list):
+ def __getitem__(self, index):
+ return SimpleNamespace(item=lambda: list.__getitem__(self, index))
+
+def model(**inputs):
+ assert len(inputs["input_ids"]) == 1
+ assert inputs["attention_mask"][0] == [1] * len(inputs["input_ids"][0])
+ return SimpleNamespace(logits=[None])
+# id2label deliberately NOT in (contradiction, entailment, neutral) index order:
+# reading the mapping rather than assuming it is the whole point.
+model.config = SimpleNamespace(
+ id2label={0: "contradiction", 1: "entailment", 2: "neutral"},
+ nli_template="Premise: {premise}\\nHypothesis: {hypothesis}",
+ max_position_embeddings=WINDOW,
+)
+model.to = lambda *_args: None
+model.eval = lambda: None
+
+def load(value):
+ def from_pretrained(_path, **kwargs):
+ assert kwargs["local_files_only"] is True and kwargs["trust_remote_code"] is False
+ return value
+ return SimpleNamespace(from_pretrained=from_pretrained)
+
+sys.modules["transformers"] = SimpleNamespace(
+ AutoTokenizer=load(tokenizer),
+ AutoModelForSequenceClassification=load(model),
+)
+sys.modules["torch"] = SimpleNamespace(
+ set_num_threads=lambda *_: None,
+ inference_mode=contextlib.nullcontext,
+ tensor=lambda value: value,
+ softmax=lambda *_args, **_kwargs: Probabilities([0.1, 0.85, 0.05]),
+ backends=SimpleNamespace(mps=SimpleNamespace(is_available=lambda: False)),
+)
+
+state = helper["load_state"](__import__("pathlib").Path("."))
+`;
+
+const run = (body, { tokenCount = 64, window = 1024 } = {}) => execFileSync(
+ python,
+ ['-c', HARNESS.replace('TOKEN_COUNT', String(tokenCount)).replaceAll('WINDOW', String(window)) + body, script],
+ { encoding: 'utf8', timeout: 20_000 },
+);
+
+describe.skipIf(!python)('jev Python wire contract', () => {
+ it('renders the model\'s own NLI template per pair and maps labels by id2label', () => {
+ const raw = JSON.parse(run(`
+scores = helper["score_pairs"](state, "A premise.", ["first", "second"])
+print(json.dumps({"scores": scores, "encoded": encoded, "device": state["device"]}))
+`));
+ // In request order, one forward pass per pair, and the entailment
+ // probability read from the id2label index rather than a fixed slot.
+ expect(raw.scores).toEqual([
+ { hypothesis: 'first', contradiction: 0.1, entailment: 0.85, neutral: 0.05 },
+ { hypothesis: 'second', contradiction: 0.1, entailment: 0.85, neutral: 0.05 },
+ ]);
+ expect(raw.encoded).toEqual([
+ 'Premise: A premise.\nHypothesis: first',
+ 'Premise: A premise.\nHypothesis: second',
+ ]);
+ expect(raw.device).toBe('cpu');
+ expect(normalizeJevScores(
+ { schemaVersion: 1, complete: true, scores: raw.scores },
+ { hypotheses: ['first', 'second'] },
+ ).ok).toBe(true);
+ });
+
+ // The regression this uniquely catches: silently truncating and returning a
+ // verdict about the PREFIX of a diff. Nothing downstream could detect it.
+ it('refuses a pair that overflows the model window instead of truncating it', () => {
+ const raw = JSON.parse(run(`
+try:
+ helper["score_pairs"](state, "A premise.", ["first"])
+ print(json.dumps({"code": None}))
+except helper["JevError"] as error:
+ print(json.dumps({"code": error.code}))
+`, { tokenCount: 4096, window: 512 }));
+ expect(raw).toEqual({ code: 'jev-premise-too-large' });
+ });
+
+ it('validates a request against its declared bounds before importing anything', () => {
+ const raw = JSON.parse(run(`
+def code_for(payload):
+ try:
+ helper["validate_request"](payload)
+ return None
+ except helper["JevError"] as error:
+ return error.code
+
+print(json.dumps({
+ "ok": helper["validate_request"]({"premise": "p", "hypotheses": ["a"]})[1],
+ "empty": code_for({"premise": " ", "hypotheses": ["a"]}),
+ "huge": code_for({"premise": "x" * 40000, "hypotheses": ["a"]}),
+ "noHypotheses": code_for({"premise": "p", "hypotheses": []}),
+ "tooMany": code_for({"premise": "p", "hypotheses": ["a"] * 33}),
+ "longHypothesis": code_for({"premise": "p", "hypotheses": ["a" * 513]}),
+ "notAnObject": code_for(["premise"]),
+}))
+`));
+ expect(raw).toEqual({
+ ok: ['a'],
+ empty: 'jev-request-invalid',
+ // The one length failure an operator can act on keeps its own code.
+ huge: 'jev-premise-too-large',
+ noHypotheses: 'jev-request-invalid',
+ tooMany: 'jev-request-invalid',
+ longHypothesis: 'jev-request-invalid',
+ notAnObject: 'jev-request-invalid',
+ });
+ });
+
+ it('fails rather than guessing when the checkpoint\'s label set is not the pinned one', () => {
+ const raw = JSON.parse(run(`
+model.config.id2label = {0: "yes", 1: "no"}
+try:
+ helper["load_state"](__import__("pathlib").Path("."))
+ print(json.dumps({"code": None}))
+except helper["JevError"] as error:
+ print(json.dumps({"code": error.code}))
+`));
+ expect(raw).toEqual({ code: 'jev-response-invalid' });
+ });
+});
+
+describe.skipIf(!python)('jev sidecar bind', () => {
+ it('refuses a non-loopback host on the command line', () => {
+ const raw = JSON.parse(run(`
+sys.argv = ["run_jev", "--model-dir", ".", "--port", "5566", "--host", "0.0.0.0"]
+try:
+ helper["main"]()
+ print(json.dumps({"refused": False}))
+except ValueError as error:
+ print(json.dumps({"refused": "host must be loopback" in str(error)}))
+`));
+ expect(raw).toEqual({ refused: true });
+ });
+});
diff --git a/scripts/setup-jev.js b/scripts/setup-jev.js
new file mode 100755
index 0000000000..f83b61bf18
--- /dev/null
+++ b/scripts/setup-jev.js
@@ -0,0 +1,15 @@
+#!/usr/bin/env node
+/** Non-interactive, machine-readable access to the same installer as the UI. */
+import { getJevStatus, installJev } from '../server/services/jev.js';
+
+const mode = process.argv[2];
+if (!['--status', '--install'].includes(mode) || process.argv.length !== 3) {
+ console.error('Usage: node scripts/setup-jev.js --status | --install');
+ process.exit(2);
+}
+
+const result = await (mode === '--status'
+ ? getJevStatus()
+ : installJev({ onEvent: (event) => console.error(JSON.stringify(event)) }));
+console.log(JSON.stringify(result, null, 2));
+process.exit(result.ready === true ? 0 : 1);
diff --git a/server/lib/README.md b/server/lib/README.md
index 9050584ea8..eaf86dd5e8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -497,6 +497,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. |
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localPersistentMindRecommendation.js` | CPU-only / low-RAM Persistent Mind defaults (Grok-box path): recommended Ollama + Qwen2.5 7B instruct profile, model aliases, and host gates so GPU coding-agent presets are not steered here. Pure. |
+| `jev.js` | Pinned local entailment ("jev") contract: the `JEV_MODEL` descriptor (repo, revision, `qwen3.5-4b-nli` subfolder, MIT/ungated), the four-file required allowlist, pinned Python packages, `JEV_STAGES` / `jevStageReadiness()` for the operator install checklist, the premise/hypothesis bounds, the `jevScoreRequestSchema` / `jevScoreResponseSchema` wire pair, `normalizeJevScores` (rejects a reply describing a different hypothesis list), and `decideFromScores` — the margin arithmetic that ABSTAINS rather than picking a near-tie. Pure. Lifecycle is `services/jev.js`; see [docs/JEV_SETUP.md](../../docs/JEV_SETUP.md). |
+| `pythonRuntimeDiagnosis.js` | `diagnosePythonRuntimeText(text, { subject, repairLabel, imports, fallback })` — maps raw pip/interpreter output onto the fixed operator-facing diagnosis vocabulary (`package-missing`, `certificate-failed`, `wheel-unavailable`, `dependency-conflict`, `disk-full`, `network-failed`), naming the specific pinned import when one is missing. Evidence is matched and DISCARDED: nothing from the subprocess output (tokens, authenticated index URLs, local paths) is ever returned. Shared by the Prompt Guard and jev installers. Pure. |
| `modelAbuseGuard.js` | Pinned model-abuse boundary contract: Prompt Guard metadata, deterministic abuse signals (`hiddenCodePointSummary` for invisible/direction-control/C0-C1 code points, `invisibleClusterSummary` for a dense cluster of the exempt ones, `describeEncodedPayload` for compressed/opaque blobs — the last scoped to `CODE_CONTENT_SOURCES` so a private message carrying base64 is not model abuse — plus hidden HTML comments/collapsed markup that address a model), complete classifier-window coverage validation, chunk/timeout limits, fixed dependency versions (`MODEL_ABUSE_GUARD_PYTHON_PACKAGES`), and `MODEL_ABUSE_GUARD_STAGES` / `modelAbuseGuardStageReadiness` for the operator-facing install checklist. Pure. |
| `diffHiddenContentScan.js` | Pre-LLM gate over a unified diff — `scanDiffForHiddenContent(diff)` reports invisible/direction-control Unicode (added lines and filenames), dense clusters of the invisible characters the rules otherwise exempt, compressed or opaque encoded payloads, a new symlink that leaves the repository or a new git submodule, a non-media binary patch, and inline script in SVG/HTML/XML, keyed `path:line`; `formatHiddenContentFindings` renders them for a CI log. Detectors for the Unicode/encoded rules are shared with `modelAbuseGuard.js` (same rules, applied to external PR content). Lockfiles skip the encoded rule but never the Unicode ones, a leading BOM is allowed, and `portos-allow-hidden-content` on the line itself opts out of the added-line rules. Driven by `scripts/scan-diff-hidden-content.js`, which CI runs on every pull request before any reviewer reads the diff (`core.quotepath=false` so a stealth filename is not octal-escaped past the detector). Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |
diff --git a/server/lib/index.js b/server/lib/index.js
index e1350ccc29..555f7b16c3 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -456,7 +456,9 @@ export * from './huggingfaceLora.js';
export * from './huggingfaceModel.js';
export * from './localLlmCatalog.js';
export * from './localPersistentMindRecommendation.js';
+export * from './jev.js';
export * from './modelAbuseGuard.js';
+export * from './pythonRuntimeDiagnosis.js';
export * from './diffHiddenContentScan.js';
export * from './localLlmDisk.js';
export * from './specDecodePresets.js';
diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.js
index ebbbe5c050..04461af4f0 100644
--- a/server/lib/instanceFeatureRegistry.js
+++ b/server/lib/instanceFeatureRegistry.js
@@ -63,6 +63,15 @@ export const INSTANCE_FEATURES = Object.freeze([
description: 'An optional shared 3D world for you and your agents, installed as a separately managed app.',
defaultEnabled: false,
}),
+ Object.freeze({
+ id: 'jev',
+ label: 'jev decision scorer',
+ description: 'A local entailment model that answers closed-set questions and abstains when it cannot separate the options. Needs a ~9 GB one-time model download.',
+ // Off until an operator installs it: the feature gates the nav entry, and
+ // advertising a page whose model is a multi-gigabyte download on a fresh
+ // install would be a capability claim the install cannot honour.
+ defaultEnabled: false,
+ }),
Object.freeze({
id: 'gsd',
label: 'GSD',
diff --git a/server/lib/jev.js b/server/lib/jev.js
new file mode 100644
index 0000000000..5bfe778064
--- /dev/null
+++ b/server/lib/jev.js
@@ -0,0 +1,271 @@
+/**
+ * Static contract for PortOS's local entailment ("jev") scoring boundary.
+ *
+ * This is the closed-set counterpart to `modelAbuseGuard.js`. Where Prompt
+ * Guard answers "is this content attacking a model?", jev answers "which of
+ * these fixed options does this text entail?" — a natural-language-inference
+ * cross-encoder, not a chat model. It is installed from one pinned Hugging Face
+ * revision, executed by a separate offline Python sidecar, never handed a
+ * PortOS tool definition, and never selectable as a chat provider.
+ *
+ * Pure: no I/O, no process state. Lifecycle lives in `services/jev.js`.
+ */
+
+import { z } from 'zod';
+
+export const JEV_ID = 'openjev-qwen3.5-4b-nli';
+
+/**
+ * The model's own three-way label set, in the `id2label` order the pinned
+ * `config.json` declares. Declared once here: the wire schema's per-hypothesis
+ * shape is built from it, the descriptor carries it, and `run_jev.py` mirrors
+ * it — so a re-labelled checkpoint cannot leave the two sides disagreeing about
+ * which number is the entailment probability.
+ */
+export const JEV_LABELS = Object.freeze(['contradiction', 'entailment', 'neutral']);
+
+// The repository is an aggregate: it also carries a 35B MoE variant and a
+// directory of trained MLP heads. Only the 4B NLI subfolder is ever fetched,
+// which is why `subfolder` is part of the identity rather than a runner flag.
+export const JEV_SUBFOLDER = 'qwen3.5-4b-nli';
+
+export const JEV_MODEL = Object.freeze({
+ id: JEV_ID,
+ name: 'OpenJEV Qwen3.5 4B NLI',
+ repository: 'AlexWortega/openjev',
+ revision: 'f8187e6e11d413d0771bcc7970b85f78e194264c',
+ subfolder: JEV_SUBFOLDER,
+ pipelineTag: 'text-classification',
+ runtime: 'python-transformers',
+ params: '4B',
+ // The tokenizer and the text config both declare 262144 positions. The
+ // service bounds requests far below that (see JEV_MAX_PREMISE_CHARS); this
+ // is the model's ceiling, not the operator-facing budget.
+ contextTokens: 262_144,
+ gated: false,
+ license: 'mit',
+ capabilities: ['entailment', 'closed-set-decision'],
+ labels: JEV_LABELS,
+ sourceUrl: 'https://huggingface.co/AlexWortega/openjev',
+ // Weights only, from the pinned subfolder. Surfaced so the install panel can
+ // state the download size before an operator commits to it.
+ weightsBytes: 9_078_635_984,
+ featured: {
+ label: 'Recommended for closed-set decisions',
+ description: 'Local entailment scorer with no chat, agent, tool, or MCP loop.',
+ },
+});
+
+// Only these files are downloaded, and only from the pinned subfolder. The
+// repository's `code/` directory, its 35B weights, and `mlp_heads_35b/` are
+// never fetched and never executed. `chat_template.jinja` and
+// `train_result.json` exist in the subfolder but are not load-bearing for
+// sequence classification, so they stay out of the allowlist.
+export const JEV_REQUIRED_FILES = Object.freeze([
+ `${JEV_SUBFOLDER}/config.json`,
+ `${JEV_SUBFOLDER}/model.safetensors`,
+ `${JEV_SUBFOLDER}/tokenizer.json`,
+ `${JEV_SUBFOLDER}/tokenizer_config.json`,
+]);
+
+// Fixed import names, not user-controlled pip arguments.
+export const JEV_PYTHON_IMPORTS = Object.freeze([
+ 'torch',
+ 'transformers',
+ 'safetensors',
+ 'huggingface_hub',
+]);
+
+// The same pins Prompt Guard runs, in a SEPARATE virtualenv (see
+// `services/jev.js`). Sharing an environment would couple two independent
+// security boundaries to one dependency resolution. Updating these pins
+// requires the explicit install canary, and a bump here that is driven by a
+// transformers requirement must bump `modelAbuseGuard.js` in the same change.
+export const JEV_PYTHON_PACKAGES = Object.freeze([
+ 'torch==2.14.0',
+ 'transformers==5.16.1',
+ 'safetensors==0.8.0',
+ 'huggingface_hub==1.30.0',
+]);
+
+/**
+ * Operator-facing install stages, in the order `installJev` runs them.
+ *
+ * FOUR stages, not five: openjev is ungated and MIT-licensed, so there is no
+ * Hugging Face token or model-card approval step the way Prompt Guard has one.
+ */
+export const JEV_STAGES = Object.freeze([
+ {
+ id: 'python',
+ label: 'Host Python',
+ description: 'Python 3.10 or newer, with a supported PyTorch wheel for this machine.',
+ },
+ {
+ id: 'venv',
+ label: 'Dedicated jev runtime',
+ description: 'A private virtualenv that never shares packages with Prompt Guard, image, or video generation.',
+ },
+ {
+ id: 'packages',
+ label: 'Scorer packages',
+ description: 'Pinned torch, transformers, safetensors, and huggingface_hub imports.',
+ },
+ {
+ id: 'model',
+ label: 'Pinned model snapshot',
+ description: 'The four required files from the pinned 4B NLI subfolder.',
+ },
+]);
+
+/**
+ * Map host facts onto the fixed install-stage list.
+ *
+ * `ready` is the scoring-time gate: importable runtime AND cached weights.
+ * Python and the virtualenv are prerequisites the installer still has to
+ * clear; neither by itself makes the scorer usable.
+ */
+export function jevStageReadiness({
+ pythonAvailable = false,
+ venvReady = false,
+ runtimeReady = false,
+ modelCached = false,
+} = {}) {
+ const readyById = {
+ python: pythonAvailable === true,
+ venv: venvReady === true,
+ packages: runtimeReady === true,
+ model: modelCached === true,
+ };
+ return {
+ stages: JEV_STAGES.map((stage) => ({ ...stage, ready: readyById[stage.id] === true })),
+ ready: runtimeReady === true && modelCached === true,
+ };
+}
+
+// ── Bounds ────────────────────────────────────────────────────────────────
+// One window of a PR diff or a PRD section. Well under the model's 262k-token
+// ceiling: the premise is re-encoded once per hypothesis, so the cost of a
+// request is (premise + hypothesis) x hypotheses.
+export const JEV_MAX_PREMISE_CHARS = 32_000;
+export const JEV_MAX_HYPOTHESES = 32;
+export const JEV_MAX_HYPOTHESIS_CHARS = 512;
+// top1 - top2 entailment probability. Below this, `decide` abstains.
+export const JEV_DEFAULT_MIN_MARGIN = 0.15;
+export const JEV_REQUEST_TIMEOUT_MS = 30_000;
+export const JEV_IDLE_UNLOAD_MS = 10 * 60 * 1000;
+// A 9 GB checkpoint is slow to page in from cold storage on first use. This
+// bounds the wait for `/health` to report `ready`, not a scoring request.
+export const JEV_START_TIMEOUT_MS = 5 * 60 * 1000;
+// The sidecar reply is a small fixed-shape JSON document (32 hypotheses x 3
+// floats, plus each hypothesis echoed back at most 512 chars).
+export const JEV_MAX_RESPONSE_CHARS = 128_000;
+
+/**
+ * Every failure `scoreHypotheses` / `decide` can report.
+ *
+ * Codes, never text: a Python traceback can carry local paths or the premise
+ * itself, and neither may reach an operator-facing payload or a log line.
+ */
+// The subset the SIDECAR itself puts in an error body. The service accepts
+// only these from a reply — a body claiming `jev-not-installed` would send an
+// operator to reinstall a working install, so an unrecognized one collapses to
+// `jev-response-invalid` instead of being forwarded.
+export const JEV_SIDECAR_FAILURE_CODES = Object.freeze([
+ 'jev-request-invalid',
+ 'jev-response-invalid',
+ 'jev-premise-too-large',
+]);
+
+export const JEV_FAILURE_CODES = Object.freeze([
+ // Only the Node lifecycle can produce these three.
+ 'jev-not-installed',
+ 'jev-start-failed',
+ 'jev-timeout',
+ ...JEV_SIDECAR_FAILURE_CODES,
+]);
+
+// ── Wire contract ─────────────────────────────────────────────────────────
+
+/**
+ * What a caller may ask the sidecar to score. Also the route-input schema,
+ * re-exported as `localLlmJevScoreSchema` from `mediaValidation.js`.
+ *
+ * `.strict()`: the sidecar is a fixed-shape endpoint, so an unexpected key is
+ * a caller bug (or an attempt to reach a parameter that does not exist), not
+ * something to silently drop.
+ */
+export const jevScoreRequestSchema = z.object({
+ premise: z.string().min(1).max(JEV_MAX_PREMISE_CHARS),
+ hypotheses: z.array(z.string().min(1).max(JEV_MAX_HYPOTHESIS_CHARS))
+ .min(1)
+ .max(JEV_MAX_HYPOTHESES),
+ minMargin: z.number().min(0).max(1).optional(),
+}).strict();
+
+const probability = z.number().min(0).max(1);
+
+/** What `scripts/run_jev.py` returns from `POST /score`. */
+export const jevScoreResponseSchema = z.object({
+ schemaVersion: z.literal(1),
+ complete: z.literal(true),
+ scores: z.array(z.object({
+ hypothesis: z.string(),
+ ...Object.fromEntries(JEV_LABELS.map((label) => [label, probability])),
+ }).strict()).min(1).max(JEV_MAX_HYPOTHESES),
+}).strict();
+
+/**
+ * Validate a sidecar reply against the hypotheses that were actually asked
+ * about, in order.
+ *
+ * Order and identity are both checked. A reply that is well-formed but
+ * describes a DIFFERENT hypothesis list would otherwise silently re-label
+ * every score — the decision would be confidently about the wrong options.
+ */
+export function normalizeJevScores(parsed, { hypotheses } = {}) {
+ const result = jevScoreResponseSchema.safeParse(parsed);
+ if (!result.success) return { ok: false, code: 'jev-response-invalid' };
+ const asked = Array.isArray(hypotheses) ? hypotheses : null;
+ const { scores } = result.data;
+ if (!asked || scores.length !== asked.length) return { ok: false, code: 'jev-response-invalid' };
+ if (scores.some((score, index) => score.hypothesis !== asked[index])) {
+ return { ok: false, code: 'jev-response-invalid' };
+ }
+ return { ok: true, scores };
+}
+
+/**
+ * Turn per-hypothesis entailment probabilities into a choice, or an
+ * abstention.
+ *
+ * ABSTENTION IS THE CONTRACT. A caller that treats `abstained: true` as
+ * permission to take the top option anyway has defeated the entire point of
+ * this service: the margin is what separates "the model distinguished these
+ * options" from "the model produced a number". The documented handling is to
+ * fall back to a chat model, or to do nothing.
+ *
+ * `margin` is `top1.entailment - top2.entailment`, so it needs a runner-up:
+ * a single hypothesis is a yes/no question, not a closed-set choice, and gets
+ * `jev-request-invalid` rather than a margin on an invented scale. Express
+ * yes/no as two hypotheses.
+ *
+ * `confidence` is the winner's raw entailment probability — reported, but NOT
+ * part of the gate. A caller that wants a floor beneath a clear-but-weak
+ * winner (0.20 vs 0.02 clears a 0.15 margin) applies it on top of this.
+ */
+export function decideFromScores(scores, minMargin = JEV_DEFAULT_MIN_MARGIN) {
+ if (!Array.isArray(scores) || scores.length < 2) return { ok: false, code: 'jev-request-invalid' };
+ const threshold = Number.isFinite(minMargin) ? minMargin : JEV_DEFAULT_MIN_MARGIN;
+ // Copy before sorting: `scores` is the caller's request-ordered array and
+ // several callers report it alongside the decision.
+ const ranked = [...scores].sort((a, b) => b.entailment - a.entailment);
+ const margin = ranked[0].entailment - ranked[1].entailment;
+ if (margin < threshold) return { ok: true, choice: null, confidence: null, margin, abstained: true };
+ return {
+ ok: true,
+ choice: ranked[0].hypothesis,
+ confidence: ranked[0].entailment,
+ margin,
+ abstained: false,
+ };
+}
diff --git a/server/lib/jev.test.js b/server/lib/jev.test.js
new file mode 100644
index 0000000000..81ab3ca236
--- /dev/null
+++ b/server/lib/jev.test.js
@@ -0,0 +1,164 @@
+import { describe, expect, it } from 'vitest';
+import {
+ JEV_DEFAULT_MIN_MARGIN,
+ JEV_FAILURE_CODES,
+ JEV_SIDECAR_FAILURE_CODES,
+ JEV_MAX_HYPOTHESES,
+ JEV_MAX_HYPOTHESIS_CHARS,
+ JEV_MAX_PREMISE_CHARS,
+ JEV_MODEL,
+ JEV_REQUIRED_FILES,
+ JEV_STAGES,
+ JEV_SUBFOLDER,
+ decideFromScores,
+ jevScoreRequestSchema,
+ jevStageReadiness,
+ normalizeJevScores,
+} from './jev.js';
+
+const score = (hypothesis, entailment, rest = {}) => ({
+ hypothesis,
+ entailment,
+ contradiction: 0,
+ neutral: 0,
+ ...rest,
+});
+
+describe('pinned jev contract', () => {
+ // The repository is an aggregate carrying a 35B MoE variant, trained MLP
+ // heads, and a `code/` directory. A file escaping the pinned subfolder would
+ // be downloaded — and in the `code/` case, would be repository Python.
+ it('confines every required file to the pinned 4B subfolder', () => {
+ expect(JEV_REQUIRED_FILES.length).toBeGreaterThan(0);
+ for (const file of JEV_REQUIRED_FILES) {
+ expect(file.startsWith(`${JEV_SUBFOLDER}/`)).toBe(true);
+ expect(file).not.toContain('..');
+ }
+ expect(JEV_REQUIRED_FILES.some((file) => file.includes('mlp_heads'))).toBe(false);
+ expect(JEV_REQUIRED_FILES.some((file) => file.startsWith('code/'))).toBe(false);
+ });
+
+ it('pins an exact revision and declares the model ungated', () => {
+ expect(JEV_MODEL.revision).toMatch(/^[a-f0-9]{40}$/);
+ // Ungated is why JEV_STAGES has four entries and no token step; if the
+ // model ever became gated, both would have to change together.
+ expect(JEV_MODEL.gated).toBe(false);
+ expect(JEV_STAGES.map((stage) => stage.id)).toEqual(['python', 'venv', 'packages', 'model']);
+ });
+});
+
+describe('failure codes', () => {
+ // A code the sidecar may put in an error body is forwarded verbatim; one it
+ // may not is collapsed. Widening the sidecar subset to the full list would
+ // let a reply send an operator to reinstall a working install.
+ it('keeps the sidecar-reportable subset narrower than the full vocabulary', () => {
+ expect(JEV_SIDECAR_FAILURE_CODES.every((code) => JEV_FAILURE_CODES.includes(code))).toBe(true);
+ for (const code of ['jev-not-installed', 'jev-start-failed', 'jev-timeout']) {
+ expect(JEV_SIDECAR_FAILURE_CODES).not.toContain(code);
+ }
+ });
+});
+
+describe('jevStageReadiness', () => {
+ // `ready` is the scoring-time gate. Cleared prerequisites do not make the
+ // scorer usable, and a status that said otherwise would let a caller reach a
+ // sidecar that cannot load.
+ it('is ready only when the packages import AND the snapshot is cached', () => {
+ const prerequisites = { pythonAvailable: true, venvReady: true };
+ expect(jevStageReadiness({ ...prerequisites }).ready).toBe(false);
+ expect(jevStageReadiness({ ...prerequisites, runtimeReady: true }).ready).toBe(false);
+ expect(jevStageReadiness({ ...prerequisites, modelCached: true }).ready).toBe(false);
+ expect(jevStageReadiness({ ...prerequisites, runtimeReady: true, modelCached: true }).ready).toBe(true);
+ });
+
+ it('reports every declared stage, with no invented entries', () => {
+ const { stages } = jevStageReadiness({ pythonAvailable: true });
+ expect(stages.map((stage) => stage.id)).toEqual(JEV_STAGES.map((stage) => stage.id));
+ expect(stages.find((stage) => stage.id === 'python').ready).toBe(true);
+ expect(stages.find((stage) => stage.id === 'model').ready).toBe(false);
+ });
+});
+
+describe('jevScoreRequestSchema', () => {
+ it('refuses input past each declared bound rather than clamping it', () => {
+ const valid = { premise: 'a', hypotheses: ['x', 'y'] };
+ expect(jevScoreRequestSchema.safeParse(valid).success).toBe(true);
+ expect(jevScoreRequestSchema.safeParse({ ...valid, premise: 'a'.repeat(JEV_MAX_PREMISE_CHARS + 1) }).success).toBe(false);
+ expect(jevScoreRequestSchema.safeParse({ ...valid, hypotheses: Array.from({ length: JEV_MAX_HYPOTHESES + 1 }, (_, i) => `h${i}`) }).success).toBe(false);
+ expect(jevScoreRequestSchema.safeParse({ ...valid, hypotheses: ['a'.repeat(JEV_MAX_HYPOTHESIS_CHARS + 1)] }).success).toBe(false);
+ // Strict: an unrecognized key is a caller reaching for a parameter that
+ // does not exist, not something to silently drop.
+ expect(jevScoreRequestSchema.safeParse({ ...valid, modelDir: '/etc' }).success).toBe(false);
+ });
+});
+
+describe('normalizeJevScores', () => {
+ const wire = (scores) => ({ schemaVersion: 1, complete: true, scores });
+
+ it('accepts a reply that matches the asked hypotheses in order', () => {
+ const scores = [score('a', 0.8), score('b', 0.1)];
+ expect(normalizeJevScores(wire(scores), { hypotheses: ['a', 'b'] })).toEqual({ ok: true, scores });
+ });
+
+ // The failure this uniquely catches: a well-formed reply describing a
+ // DIFFERENT hypothesis list silently re-labels every score, so the decision
+ // is confidently about options nobody asked about.
+ it('rejects a well-formed reply whose hypotheses are reordered or substituted', () => {
+ expect(normalizeJevScores(wire([score('b', 0.8), score('a', 0.1)]), { hypotheses: ['a', 'b'] }))
+ .toEqual({ ok: false, code: 'jev-response-invalid' });
+ expect(normalizeJevScores(wire([score('a', 0.8), score('c', 0.1)]), { hypotheses: ['a', 'b'] }))
+ .toEqual({ ok: false, code: 'jev-response-invalid' });
+ expect(normalizeJevScores(wire([score('a', 0.8)]), { hypotheses: ['a', 'b'] }))
+ .toEqual({ ok: false, code: 'jev-response-invalid' });
+ });
+
+ it('rejects a malformed or out-of-range wire payload', () => {
+ expect(normalizeJevScores(null, { hypotheses: ['a'] }).code).toBe('jev-response-invalid');
+ expect(normalizeJevScores(wire([score('a', 1.4)]), { hypotheses: ['a'] }).code).toBe('jev-response-invalid');
+ expect(normalizeJevScores({ ...wire([score('a', 0.9)]), complete: false }, { hypotheses: ['a'] }).code).toBe('jev-response-invalid');
+ });
+});
+
+describe('decideFromScores', () => {
+ // The load-bearing behavior of the whole service: a near-tie must ABSTAIN,
+ // not pick. A regression here is silent — every caller still gets a choice.
+ it('abstains on a near-tie rather than picking the nominal winner', () => {
+ const result = decideFromScores([score('reply', 0.52), score('none', 0.49)]);
+ expect(result).toMatchObject({ ok: true, abstained: true, choice: null, confidence: null });
+ expect(result.margin).toBeCloseTo(0.03, 5);
+ });
+
+ it('picks when the margin clears the threshold, reporting the raw confidence', () => {
+ const result = decideFromScores([score('none', 0.12), score('reply', 0.88)]);
+ expect(result).toMatchObject({ ok: true, abstained: false, choice: 'reply' });
+ expect(result.confidence).toBeCloseTo(0.88, 5);
+ expect(result.margin).toBeCloseTo(0.76, 5);
+ });
+
+ // Confidence is reported but NOT gated on — documented in lib/jev.js and the
+ // ADR, so a caller that wants a floor knows it has to apply one itself.
+ it('picks a clear but weak winner, leaving any confidence floor to the caller', () => {
+ expect(decideFromScores([score('a', 0.2), score('b', 0.02)])).toMatchObject({ abstained: false, choice: 'a' });
+ });
+
+ it('honours an explicit threshold on either side of the default', () => {
+ const near = [score('a', 0.52), score('b', 0.49)];
+ expect(decideFromScores(near, 0.01).abstained).toBe(false);
+ expect(decideFromScores([score('a', 0.88), score('b', 0.12)], 0.9).abstained).toBe(true);
+ // A non-numeric threshold falls back to the shipped default rather than
+ // producing NaN comparisons, which would never abstain.
+ expect(decideFromScores(near, undefined).abstained).toBe(true);
+ expect(JEV_DEFAULT_MIN_MARGIN).toBeGreaterThan(0.03);
+ });
+
+ it('refuses a single option instead of inventing a runner-up', () => {
+ expect(decideFromScores([score('a', 0.99)])).toEqual({ ok: false, code: 'jev-request-invalid' });
+ expect(decideFromScores([])).toEqual({ ok: false, code: 'jev-request-invalid' });
+ });
+
+ it('does not reorder the caller\'s request-ordered score array', () => {
+ const scores = [score('a', 0.1), score('b', 0.9)];
+ decideFromScores(scores);
+ expect(scores.map((entry) => entry.hypothesis)).toEqual(['a', 'b']);
+ });
+});
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 224df5bdc0..01581780ed 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -250,6 +250,10 @@ export const localLlmMigrateSchema = z.object({
mode: z.enum(['link', 'copy']).optional().default('link'),
});
export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });
+// The jev scorer route input IS the service contract — declared once beside the
+// pinned model descriptor (lib/jev.js) and re-exported here so routes keep
+// importing every schema from validation.js.
+export { jevScoreRequestSchema as localLlmJevScoreSchema } from './jev.js';
export const localPersistentMindSetupApplySchema = z.object({
setMindProfile: z.boolean().optional(),
modelId: z.string().trim().max(200).optional(),
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 853f5ed79f..2acb0cc268 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -322,6 +322,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.settings.embeddings', path: '/models/embeddings', label: 'Embeddings', section: 'Models', tabId: 'embeddings', previousPaths: ['/settings/embeddings'], aliases: ['settings-embeddings', 'embeddings', 'embedding'], keywords: ['vector', 'pgvector', 'semantic search', 'nomic', 'ollama', 'lm studio'] },
{ id: 'nav.settings.local-llm', path: '/models/llms', label: 'LLMs', section: 'Models', tabId: 'llms', previousPaths: ['/settings/local-llm'], aliases: ['local-llm', 'local-llms', 'llms', 'models-llms', 'ollama', 'lm-studio', 'lmstudio'], keywords: ['ollama', 'lm studio', 'local model', 'local llm', 'gguf', 'pull model', 'install model', 'migrate', 'switch backend', 'llama.cpp'] },
{ id: 'nav.models.llms.abuse', path: '/models/llms/abuse', label: 'Abuse Guard', section: 'Models', aliases: ['abuse-guard', 'model-abuse', 'model-abuse-guard', 'prompt-guard', 'prompt guard'], keywords: ['classifier', 'prompt injection', 'security scan', 'llama prompt guard', 'install guard'] },
+ { id: 'nav.models.llms.jev', path: '/models/llms/jev', label: 'jev', section: 'Models', feature: 'jev', aliases: ['jev', 'openjev', 'entailment', 'nli', 'decision-scorer'], keywords: ['entailment', 'nli', 'closed set', 'abstain', 'margin', 'scorer', 'decision', 'install jev'] },
// Split out of the LLMs page (#7414): managing the SERVERS that run models is
// a different job from browsing the weights they serve, and it was the LLMs
// default view, not a drill-down — so it gets a sibling tab rather than a
diff --git a/server/lib/ports.js b/server/lib/ports.js
index 88133c58da..2d4ed49dad 100644
--- a/server/lib/ports.js
+++ b/server/lib/ports.js
@@ -26,6 +26,7 @@ export const PORTS = Object.freeze({
WHISPER: 5562, // Loopback whisper.cpp speech-to-text server
EIDOVERSE_HOST: 5563, // Optional HTTPS/WebSocket bridge to Eidoverse Worlds on :8940
SLOTSTREAM: 5564, // Loopback SSD-streaming MoE runtime (never 11434 — that collides with Ollama)
+ JEV: 5566, // Loopback openjev entailment scorer — on-demand sidecar, never bound at boot
LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding server
FLEET_LLM: 18022, // Authenticated shared inference queue for dedicated hosts
diff --git a/server/lib/pythonRuntimeDiagnosis.js b/server/lib/pythonRuntimeDiagnosis.js
new file mode 100644
index 0000000000..db67d23581
--- /dev/null
+++ b/server/lib/pythonRuntimeDiagnosis.js
@@ -0,0 +1,65 @@
+/**
+ * Map Python setup/exec output onto a fixed operator-facing diagnosis.
+ *
+ * Every managed Python runtime in PortOS (Prompt Guard, jev, and any future
+ * pinned-model boundary) hits the same short list of real-world failures: a
+ * missing module, a broken certificate chain, no wheel for this platform, an
+ * unsolvable resolution, a full disk, an unreachable index. Each one needs a
+ * DIFFERENT operator action, so a single "install failed" is useless.
+ *
+ * The evidence is raw pip/interpreter output, which can carry an authenticated
+ * package-index URL, a private path, or a token — so it is matched against
+ * static patterns and DISCARDED. Nothing from `text` is ever returned.
+ *
+ * Pure: no I/O, no process state.
+ */
+
+const EVIDENCE = [
+ [/No module named/, 'package-missing', (subject) => `A ${subject} package or dependency is missing.`, 'repair-packages'],
+ [/CERTIFICATE_VERIFY_FAILED|certificate verify failed/i, 'certificate-failed', () => 'Python could not verify the package server certificate.', 'Repair Python certificate trust, then retry installation.'],
+ [/No matching distribution|Could not find a version that satisfies/i, 'wheel-unavailable', () => 'A pinned package has no matching distribution for this Python and platform.', 'Use a Python version and platform supported by the pinned packages, then repair the runtime.'],
+ [/ResolutionImpossible|conflicting dependencies/i, 'dependency-conflict', (subject) => `The ${subject} dependencies could not be resolved.`, 'Check the pinned package compatibility before retrying.'],
+ [/No space left on device/i, 'disk-full', (subject) => `There is not enough disk space for the ${subject}.`, 'Free disk space, then retry installation.'],
+ [/timed? ?out|ReadTimeout|ConnectionError|NameResolution|Temporary failure|Network is unreachable|No route to host|connection error|NewConnectionError/i, 'network-failed', () => 'The download could not reach its server.', 'Check this machine’s network and Python connection to the download server, then retry.'],
+];
+
+/**
+ * @param text Raw subprocess output. Read for evidence, never returned.
+ * @param subject The noun for this runtime's packages ("classifier", "scorer").
+ * @param repairLabel What the operator repairs, as the UI names it
+ * ("model-abuse guard", "jev"). Completes both repair actions.
+ * @param imports The pinned import names, so a named missing module can be
+ * reported precisely rather than as "a package".
+ * @param fallback The code to use when no pattern matches.
+ */
+export function diagnosePythonRuntimeText(text, {
+ subject = 'runtime',
+ repairLabel = 'the runtime',
+ imports = [],
+ fallback = 'runtime-check-failed',
+} = {}) {
+ const evidence = String(text || '');
+ const repairPackages = `Repair ${repairLabel} to install the pinned packages.`;
+ const action = (value) => (value === 'repair-packages' ? repairPackages : value);
+
+ // A named module beats the generic "No module named" row: it tells the
+ // operator WHICH pinned package did not survive, which is the difference
+ // between a repair and a bug report.
+ const missing = imports.find((name) => evidence.includes(`No module named '${name}'`));
+ if (missing) {
+ return {
+ code: 'package-missing',
+ package: missing,
+ message: `The ${subject} package ${missing} is missing.`,
+ action: repairPackages,
+ };
+ }
+
+ const match = EVIDENCE.find(([pattern]) => pattern.test(evidence));
+ if (match) return { code: match[1], message: match[2](subject), action: action(match[3]) };
+ return {
+ code: fallback,
+ message: `The dedicated ${subject} runtime could not be verified.`,
+ action: `Repair ${repairLabel} and inspect the reported install stage and exit code.`,
+ };
+}
diff --git a/server/lib/pythonRuntimeDiagnosis.test.js b/server/lib/pythonRuntimeDiagnosis.test.js
new file mode 100644
index 0000000000..437c1e861d
--- /dev/null
+++ b/server/lib/pythonRuntimeDiagnosis.test.js
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import { diagnosePythonRuntimeText } from './pythonRuntimeDiagnosis.js';
+
+const guard = { subject: 'classifier', repairLabel: 'model-abuse guard', imports: ['torch', 'transformers'] };
+
+describe('diagnosePythonRuntimeText', () => {
+ // The privacy guarantee this file exists for: pip output routinely carries an
+ // authenticated index URL, a token, or a home-directory path, and all three
+ // reach an operator-facing payload if any of it is echoed back.
+ it('returns none of the evidence it matched on', () => {
+ const evidence = [
+ 'Looking in indexes: https://user:[email protected]/simple',
+ 'WARNING: Retrying after ReadTimeout',
+ 'Could not install packages due to an OSError: /Users/someone/.cache/pip',
+ ].join('\n');
+ const result = diagnosePythonRuntimeText(evidence, guard);
+ const rendered = JSON.stringify(result);
+ expect(result.code).toBe('network-failed');
+ for (const secret of ['hunter2', 'packages.example.com', '/Users/someone', 'ReadTimeout']) {
+ expect(rendered).not.toContain(secret);
+ }
+ });
+
+ // "A package is missing" and "torch is missing" are different repairs, and
+ // the generic row would swallow the specific one if it were checked first.
+ it('names the specific pinned import ahead of the generic missing-module row', () => {
+ expect(diagnosePythonRuntimeText("ModuleNotFoundError: No module named 'torch'", guard))
+ .toMatchObject({ code: 'package-missing', package: 'torch' });
+ // Not a pinned import, so the generic row answers and names no package.
+ const generic = diagnosePythonRuntimeText("No module named 'scipy'", guard);
+ expect(generic.code).toBe('package-missing');
+ expect(generic).not.toHaveProperty('package');
+ expect(generic.message).not.toContain('scipy');
+ });
+
+ it.each([
+ ['CERTIFICATE_VERIFY_FAILED', 'certificate-failed'],
+ ['No matching distribution found for torch==2.14.0', 'wheel-unavailable'],
+ ['ResolutionImpossible', 'dependency-conflict'],
+ ['No space left on device', 'disk-full'],
+ ['NewConnectionError', 'network-failed'],
+ ])('maps %s to %s', (evidence, code) => {
+ expect(diagnosePythonRuntimeText(evidence, guard).code).toBe(code);
+ });
+
+ it('falls back to the caller-supplied code for unrecognized output', () => {
+ expect(diagnosePythonRuntimeText('something nobody has seen before', { ...guard, fallback: 'model-download-failed' }))
+ .toMatchObject({ code: 'model-download-failed' });
+ expect(diagnosePythonRuntimeText(null, guard).code).toBe('runtime-check-failed');
+ });
+
+ // Both boundaries share the table but must name themselves, or an operator is
+ // pointed at the wrong repair screen.
+ it('renders each boundary\'s own noun and repair label', () => {
+ expect(diagnosePythonRuntimeText("No module named 'torch'", guard))
+ .toMatchObject({
+ message: 'The classifier package torch is missing.',
+ action: 'Repair model-abuse guard to install the pinned packages.',
+ });
+ expect(diagnosePythonRuntimeText("No module named 'torch'", { ...guard, subject: 'scorer', repairLabel: 'jev' }))
+ .toMatchObject({
+ message: 'The scorer package torch is missing.',
+ action: 'Repair jev to install the pinned packages.',
+ });
+ });
+});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 63216fc999..49138a0d67 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -19,6 +19,7 @@ import {
localLlmUnloadSchema,
localLlmMigrateSchema,
localLlmInstallBackendSchema,
+ localLlmJevScoreSchema,
localLlmOllamaServiceSchema,
localLlmHuggingFaceSearchSchema,
localLlmTestSchema,
@@ -60,6 +61,7 @@ import { getSpecDecodePresetStatus, downloadSpecDecodeModel, previewSpecDecodeDo
import { SPEC_TYPE_SUGGESTIONS } from '../lib/specDecodePresets.js'
import { resetProviderReadinessCache } from '../services/providerReadiness.js'
import { MODEL_ABUSE_GUARD } from '../lib/modelAbuseGuard.js'
+import { JEV_MODEL } from '../lib/jev.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { isAppleSilicon } from '../lib/platform.js'
import {
@@ -74,6 +76,7 @@ import {
describeInstallProgress
} from '../services/localLlm.js'
import { getModelAbuseGuardStatus, installModelAbuseGuard, cancelModelAbuseGuardInstall } from '../services/modelAbuseGuard.js'
+import { cancelJevInstall, decide, getJevStatus, installJev, stopJevSidecar } from '../services/jev.js'
import { getSettings } from '../services/settings.js'
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'
import { getAssessmentReport, runAssessment, deleteAssessment } from '../services/localModelAssessments.js'
@@ -212,6 +215,10 @@ router.get('/catalog', asyncHandler(async (req, res) => {
// the catalog response so the UI can highlight the safety recommendation
// without making it selectable in any normal provider/model picker.
securityGuards: [MODEL_ABUSE_GUARD],
+ // Same guarantee, separate key: jev is a managed entailment scorer, not a
+ // chat model. Neither descriptor is ever merged into `models`, so no
+ // provider/model picker can offer either one.
+ decisionScorers: [JEV_MODEL],
systemMemoryGb: Math.round(systemMemoryBytes / 1024 ** 3),
})
}))
@@ -253,6 +260,53 @@ router.post('/security-guard/install/cancel', asyncHandler(async (_req, res) =>
res.json({ cancelled: true })
}))
+// The jev scorer mirrors the guard's lifecycle: a pinned, offline model with
+// its own venv and its own installer, never reachable through the general
+// chat-model path.
+router.get('/jev/status', asyncHandler(async (_req, res) => {
+ res.json(await getJevStatus())
+}))
+
+router.post('/jev/install', asyncHandler(async (req, res) => {
+ const emit = emitter(req)
+ const result = await installJev({
+ onEvent: ({ event, message, stage }) => emit(event, message, { scope: 'jev', stage }),
+ })
+ if (!result?.ok) {
+ const code = result?.code || 'jev-install-failed'
+ const message = code === 'jev-python-unavailable'
+ ? 'Install Python 3.10 or newer on this machine, restart PortOS if needed to detect it, then refresh jev status.'
+ : code === 'jev-runtime-install-failed'
+ ? 'Scorer package installation failed. Check internet access and Python compatibility, then retry from Models > LLMs > jev.'
+ : code === 'jev-model-download-failed'
+ ? 'The pinned jev model snapshot could not be downloaded. Check internet access and free disk space, then retry.'
+ : code
+ const detail = result?.diagnostic
+ const actionableMessage = detail ? `${message} ${detail.message} ${detail.action}` : message
+ emit('error', actionableMessage, { scope: 'jev', stage: detail?.stage })
+ throw new ServerError(actionableMessage, { status: 502, code })
+ }
+ res.json(result)
+}))
+
+router.post('/jev/install/cancel', asyncHandler(async (_req, res) => {
+ cancelJevInstall()
+ res.json({ cancelled: true })
+}))
+
+// An explicit operator action in the same request, per the AI Provider Usage
+// Policy: this is the only path that starts the sidecar, and it starts it
+// because someone asked for a score.
+router.post('/jev/score', asyncHandler(async (req, res) => {
+ const { premise, hypotheses, minMargin } = validateRequest(localLlmJevScoreSchema, req.body)
+ res.json(await decide({ premise, options: hypotheses, minMargin }))
+}))
+
+// Free the resident weights without waiting out the idle timer.
+router.post('/jev/unload', asyncHandler(async (_req, res) => {
+ res.json({ unloaded: stopJevSidecar() })
+}))
+
// GET /api/local-llm/huggingface-search?backend=ollama&q=qwen&category=coding
// Live Hub discovery — GGUF-compatible community models, plus (for the `audio`
// category) audio/music generators that install into the shared audio-model
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index e0597418a5..939541cb44 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -183,6 +183,20 @@ describe('local LLM playground routes', () => {
expect(res.body.models.some((model) => model.id === 'llama-prompt-guard-2-86m')).toBe(false);
});
+ // Same guarantee for the jev scorer: a descriptor that leaked into `models`
+ // would be offered by every provider/model picker that reads the catalog.
+ it('GET /catalog exposes the jev decision scorer separately from chat models', async () => {
+ const res = await request(makeApp()).get('/api/local-llm/catalog?backend=ollama');
+
+ expect(res.status).toBe(200);
+ expect(res.body.decisionScorers).toEqual([expect.objectContaining({
+ id: 'openjev-qwen3.5-4b-nli',
+ pipelineTag: 'text-classification',
+ runtime: 'python-transformers',
+ })]);
+ expect(res.body.models.some((model) => model.id === 'openjev-qwen3.5-4b-nli')).toBe(false);
+ });
+
it('keeps the Prompt Guard lifecycle out of the general model installer', async () => {
const status = await request(makeApp()).get('/api/local-llm/security-guard/status');
expect(status.status).toBe(200);
diff --git a/server/services/jev.js b/server/services/jev.js
new file mode 100644
index 0000000000..01914e6698
--- /dev/null
+++ b/server/services/jev.js
@@ -0,0 +1,490 @@
+/**
+ * Local entailment ("jev") scoring service.
+ *
+ * PortOS's decision primitive for CLOSED-SET questions over untrusted external
+ * text. Where `untrustedContent.js` asks a chat model to generate an answer,
+ * this hands a premise and a fixed list of hypotheses to a pinned NLI
+ * cross-encoder and gets back a per-hypothesis entailment distribution. No text
+ * generation, no tool surface, no provider quota.
+ *
+ * Two things distinguish it from `modelAbuseGuard.js`, which it otherwise
+ * mirrors file for file:
+ *
+ * 1. The Python helper is a long-lived SIDECAR on a loopback port, not a
+ * process per item. A 9 GB checkpoint cannot be re-imported per call.
+ * 2. It ABSTAINS. `decide()` returns `abstained: true` whenever the top two
+ * hypotheses are too close to separate, and a caller is required to treat
+ * that as "ask something else", never as "take the top one anyway".
+ *
+ * Nothing here runs at boot. The sidecar starts on the first `scoreHypotheses`
+ * call and an idle timer reaps it — see the AI Provider Usage Policy in
+ * AGENTS.md.
+ */
+
+import { existsSync } from 'node:fs';
+import { homedir, platform } from 'node:os';
+import { dirname, join } from 'node:path';
+import { promisify } from 'node:util';
+import { execFile, spawn } from '../lib/childProcess.js';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { findCachedRepoFiles, getHfCacheRoot } from '../lib/hfCache.js';
+import {
+ JEV_IDLE_UNLOAD_MS,
+ JEV_MAX_RESPONSE_CHARS,
+ JEV_MODEL,
+ JEV_PYTHON_IMPORTS,
+ JEV_PYTHON_PACKAGES,
+ JEV_REQUEST_TIMEOUT_MS,
+ JEV_REQUIRED_FILES,
+ JEV_SIDECAR_FAILURE_CODES,
+ JEV_START_TIMEOUT_MS,
+ decideFromScores,
+ jevScoreRequestSchema,
+ jevStageReadiness,
+ normalizeJevScores,
+} from '../lib/jev.js';
+import { PORTS } from '../lib/ports.js';
+import { safeChildProcessOptions } from '../lib/processEnv.js';
+import { diagnosePythonRuntimeText } from '../lib/pythonRuntimeDiagnosis.js';
+import { createVenv, detectVenvBasePythonSync, installPackages } from '../lib/pythonSetup.js';
+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
+import { downloadHfRepo } from './hfDownload.js';
+
+const execFileAsync = promisify(execFile);
+const IS_WIN = platform() === 'win32';
+// A SEPARATE virtualenv from Prompt Guard's, on purpose: two independent
+// boundaries must not share one dependency resolution, and repairing one must
+// never be able to break the other.
+const JEV_VENV_DIR = join(PATHS.data, 'python', 'venv-jev');
+const JEV_PYTHON = IS_WIN
+ ? join(JEV_VENV_DIR, 'Scripts', 'python.exe')
+ : join(JEV_VENV_DIR, 'bin', 'python3');
+const FALLBACK_JEV_PYTHON = IS_WIN
+ ? join(homedir(), '.portos', 'venv-jev', 'Scripts', 'python.exe')
+ : join(homedir(), '.portos', 'venv-jev', 'bin', 'python3');
+const HELPER_SCRIPT = join(PATHS.root, 'scripts', 'run_jev.py');
+const SIDECAR_ORIGIN = `http://127.0.0.1:${PORTS.JEV}`;
+const RUNTIME_PROBE_TIMEOUT_MS = 30_000;
+const MAX_INSTALL_EVENT_CHARS = 300;
+const HEALTH_POLL_INTERVAL_MS = 1_000;
+const HEALTH_PROBE_TIMEOUT_MS = 5_000;
+
+let cachedRuntime = null;
+let installInFlight = null;
+let installKill = null;
+let runtimeIssue = null;
+let lastInstallFailure = null;
+
+// Sidecar state. `startInFlight` is the single-start guard: two concurrent
+// first-callers must produce exactly ONE process, not two competing 9 GB loads.
+let sidecar = null;
+let startInFlight = null;
+let idleTimer = null;
+// The child between spawn and its first healthy /health. `sidecar` is not set
+// yet, so without this a stop during a cold start (an operator unload, a test
+// teardown) would leave a 9 GB load running with nothing holding its handle.
+let startingProc = null;
+
+const failure = (code, extra = {}) => ({ ok: false, code, ...extra });
+
+const setupIssue = (text, fallback = 'runtime-check-failed') => diagnosePythonRuntimeText(text, {
+ subject: 'scorer',
+ repairLabel: 'jev',
+ imports: JEV_PYTHON_IMPORTS,
+ fallback,
+});
+
+const emitInstall = (onEvent, event, message, stage) => {
+ if (typeof onEvent !== 'function') return;
+ onEvent({
+ event,
+ message: String(message || '').slice(0, MAX_INSTALL_EVENT_CHARS),
+ ...(stage ? { stage } : {}),
+ });
+};
+
+/**
+ * Build the sidecar's environment.
+ *
+ * Deliberately not the normal CLI environment builder: that one carries
+ * forge/provider auth so an agent can work. jev must receive no API keys,
+ * GitHub tokens, MCP/Codex variables, provider settings, or arbitrary
+ * PYTHONPATH — and must never reach the network.
+ */
+export function buildJevEnv(source = process.env) {
+ const keys = ['PATH', 'Path', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL'];
+ const env = Object.fromEntries(keys
+ .filter((key) => source?.[key] != null)
+ .map((key) => [key, String(source[key])]));
+ return {
+ ...env,
+ PYTHONNOUSERSITE: '1',
+ HF_HUB_OFFLINE: '1',
+ TRANSFORMERS_OFFLINE: '1',
+ HF_HUB_DISABLE_TELEMETRY: '1',
+ TOKENIZERS_PARALLELISM: 'false',
+ PYTHONWARNINGS: 'ignore',
+ };
+}
+
+function availableJevPython() {
+ if (existsSync(JEV_PYTHON)) return JEV_PYTHON;
+ if (existsSync(FALLBACK_JEV_PYTHON)) return FALLBACK_JEV_PYTHON;
+ return null;
+}
+
+async function isBasePythonSupported(pythonPath) {
+ if (!pythonPath) return false;
+ return execFileAsync(pythonPath, ['-c', 'import sys; print("supported" if sys.version_info >= (3, 10) else "unsupported")'],
+ safeChildProcessOptions({ env: buildJevEnv(), timeout: 5_000, maxBuffer: 1000 }))
+ .then(({ stdout }) => stdout.trim() === 'supported').catch(() => false);
+}
+
+function probeScript() {
+ const imports = JEV_PYTHON_IMPORTS.map((name) => `import ${name}`).join('; ');
+ const expected = Object.fromEntries(JEV_PYTHON_PACKAGES.map((spec) => spec.split('==')));
+ return `${imports}; import importlib.metadata as metadata; expected = ${JSON.stringify(expected)}; ready = all(metadata.version(name).split('+')[0] == version for name, version in expected.items()); print('{"ready":true}' if ready else '{"ready":false}')`;
+}
+
+async function isRuntimeReady(pythonPath) {
+ if (!pythonPath) { runtimeIssue = null; return false; }
+ if (cachedRuntime?.pythonPath === pythonPath && Date.now() - cachedRuntime.checkedAt < 60_000) return true;
+ runtimeIssue = null;
+ const importsReady = await execFileAsync(
+ pythonPath,
+ ['-c', probeScript()],
+ safeChildProcessOptions({ env: buildJevEnv(), timeout: RUNTIME_PROBE_TIMEOUT_MS, maxBuffer: 4_000 }),
+ ).then(({ stdout }) => stdout.trim().split(/\r?\n/).pop() === '{"ready":true}')
+ .catch((error) => { runtimeIssue = setupIssue(error.stderr || error.message); return false; });
+ if (!importsReady && !runtimeIssue) {
+ runtimeIssue = {
+ code: 'package-version-mismatch',
+ message: 'Installed scorer package versions do not match the pinned runtime.',
+ action: 'Repair jev to install the expected versions.',
+ };
+ }
+ if (importsReady) cachedRuntime = { pythonPath, checkedAt: Date.now() };
+ return importsReady;
+}
+
+/**
+ * Operator-safe status only. Runtime paths and exception text are
+ * intentionally omitted from the API contract.
+ *
+ * Observational: importing packages is permitted here, but no model is loaded
+ * and no download runs. A status refresh never starts the sidecar.
+ */
+export async function getJevStatus() {
+ const files = await findCachedRepoFiles(JEV_MODEL.repository, JEV_REQUIRED_FILES, {
+ revision: JEV_MODEL.revision,
+ });
+ const pythonPath = availableJevPython();
+ const modelCached = Array.isArray(files);
+ const venvReady = Boolean(pythonPath);
+ const pythonAvailable = await isBasePythonSupported(detectVenvBasePythonSync());
+ const runtimeReady = await isRuntimeReady(pythonPath);
+ const { stages, ready } = jevStageReadiness({ pythonAvailable, venvReady, runtimeReady, modelCached });
+ const installationPresent = modelCached || venvReady || existsSync(JEV_VENV_DIR)
+ || existsSync(dirname(dirname(FALLBACK_JEV_PYTHON)))
+ || existsSync(join(getHfCacheRoot(), `models--${JEV_MODEL.repository.replaceAll('/', '--')}`));
+ return {
+ ...JEV_MODEL,
+ modelCached,
+ runtimeReady,
+ pythonAvailable,
+ venvReady,
+ stages,
+ ready,
+ runtimeIssue,
+ lastInstallFailure,
+ resident: sidecar !== null,
+ port: PORTS.JEV,
+ expectedPackages: [...JEV_PYTHON_PACKAGES],
+ setupState: ready ? 'ready' : installationPresent ? 'incomplete' : 'not-installed',
+ };
+}
+
+/**
+ * Install the fixed scorer and its private runtime. There are no request
+ * parameters for repository, revision, package, or destination: all of those
+ * are owned by the static contract in `lib/jev.js`.
+ */
+export function installJev({ onEvent } = {}) {
+ if (installInFlight) return installInFlight;
+ lastInstallFailure = null;
+ let activeStage = 'python';
+ const failInstall = (code, diagnostic = setupIssue('', code)) => {
+ lastInstallFailure = { ...diagnostic, stage: activeStage };
+ return failure(code, { diagnostic: lastInstallFailure });
+ };
+ installInFlight = (async () => {
+ // No token stage: openjev is ungated and MIT-licensed.
+ const cachedFiles = await findCachedRepoFiles(JEV_MODEL.repository, JEV_REQUIRED_FILES, { revision: JEV_MODEL.revision });
+ const basePython = detectVenvBasePythonSync();
+ if (!await isBasePythonSupported(basePython)) return failInstall('jev-python-unavailable');
+
+ activeStage = 'venv';
+ await ensureDir(dirname(JEV_VENV_DIR));
+ emitInstall(onEvent, 'stage', 'Preparing the dedicated jev runtime…', 'venv');
+ const clear = existsSync(JEV_PYTHON) && !await isBasePythonSupported(JEV_PYTHON);
+ const pythonPath = await createVenv(basePython, JEV_VENV_DIR, { clear });
+ cachedRuntime = null;
+
+ activeStage = 'packages';
+ let packageIssue = null;
+ emitInstall(onEvent, 'stage', 'Installing the fixed scorer runtime packages…', 'packages');
+ const packageRun = installPackages(pythonPath, [...JEV_PYTHON_PACKAGES], ({ type, message }) => {
+ const issue = setupIssue(message);
+ if (issue.code !== 'runtime-check-failed' && !packageIssue) {
+ packageIssue = issue;
+ emitInstall(onEvent, 'stage', `${issue.message} ${issue.action}`, 'packages');
+ }
+ if (type === 'complete') emitInstall(onEvent, 'stage', 'Scorer runtime packages are ready.', 'packages');
+ else if (type === 'error') emitInstall(onEvent, 'error', 'Scorer runtime package installation failed.', 'packages');
+ else if (message && /install|uninstall/i.test(message)) emitInstall(onEvent, 'stage', 'Installing scorer runtime packages…', 'packages');
+ }, { preferUv: true });
+ installKill = packageRun.kill;
+ const packageResult = await packageRun.promise;
+ installKill = null;
+ if (!packageResult?.ok) {
+ return failInstall('jev-runtime-install-failed', {
+ ...(packageIssue || setupIssue('', 'package-install-failed')),
+ ...(Number.isInteger(packageResult?.code) ? { exitCode: packageResult.code } : {}),
+ });
+ }
+
+ activeStage = 'model';
+ if (!cachedFiles) {
+ emitInstall(onEvent, 'stage', 'Downloading the pinned jev model snapshot…', 'model');
+ // `only` keeps this in single-file mode: the repository also carries a
+ // 35B variant, trained MLP heads, and a `code/` directory, none of which
+ // are ever fetched and none of which are ever executed.
+ const download = downloadHfRepo({
+ repo: JEV_MODEL.repository,
+ revision: JEV_MODEL.revision,
+ only: [...JEV_REQUIRED_FILES],
+ pythonPath,
+ onEvent: (event) => {
+ if (event?.type === 'error') emitInstall(onEvent, 'error', 'jev model download failed.', 'model');
+ else if (event?.type === 'progress') emitInstall(onEvent, 'progress', event.stage || 'Downloading jev…', 'model');
+ else if (event?.type === 'complete') emitInstall(onEvent, 'stage', 'Pinned jev model snapshot downloaded.', 'model');
+ },
+ });
+ installKill = download.kill;
+ const downloadResult = await download.promise;
+ installKill = null;
+ if (!downloadResult?.ok) {
+ return failInstall('jev-model-download-failed', setupIssue(downloadResult?.errorMessage, 'model-download-failed'));
+ }
+ }
+
+ activeStage = 'verification';
+ const status = await getJevStatus();
+ if (!status.ready) return failInstall('jev-install-incomplete', runtimeIssue || undefined);
+ emitInstall(onEvent, 'complete', 'jev is ready for closed-set scoring.');
+ return { ok: true, ...status };
+ })()
+ .catch((error) => failInstall('jev-install-failed', setupIssue(error.stderr || error.message)))
+ .finally(() => {
+ installKill = null;
+ installInFlight = null;
+ });
+ return installInFlight;
+}
+
+export function cancelJevInstall() {
+ if (typeof installKill === 'function') installKill();
+}
+
+// ── Sidecar lifecycle ─────────────────────────────────────────────────────
+
+function clearIdleTimer() {
+ if (idleTimer) clearTimeout(idleTimer);
+ idleTimer = null;
+}
+
+/**
+ * Stop the sidecar and free its weights. Safe to call when nothing is running.
+ *
+ * Exported because the idle reaper, an explicit operator unload, and test
+ * teardown all need exactly this, and a module that keeps a 9 GB process alive
+ * with no way to end it is a resource leak with a UI.
+ */
+export function stopJevSidecar() {
+ clearIdleTimer();
+ const running = sidecar;
+ const starting = startingProc;
+ sidecar = null;
+ startingProc = null;
+ startInFlight = null;
+ for (const proc of [running?.proc, starting]) {
+ if (proc && proc.exitCode === null && !proc.killed) proc.kill('SIGTERM');
+ }
+ return running !== null || starting !== null;
+}
+
+export const isJevSidecarRunning = () => sidecar !== null;
+
+function armIdleReaper() {
+ clearIdleTimer();
+ // Outside the request lifecycle: an uncaught throw here would take the whole
+ // Node process down, so the callback owns its failures (Code Conventions).
+ idleTimer = setTimeout(() => {
+ try {
+ stopJevSidecar();
+ console.log('💤 jev sidecar unloaded after idle timeout');
+ } catch (error) {
+ console.error(`❌ jev idle unload failed: ${error.message}`);
+ }
+ }, JEV_IDLE_UNLOAD_MS);
+ if (typeof idleTimer.unref === 'function') idleTimer.unref();
+}
+
+async function probeHealth(timeoutMs = HEALTH_PROBE_TIMEOUT_MS) {
+ const response = await fetch(`${SIDECAR_ORIGIN}/health`, { signal: AbortSignal.timeout(timeoutMs) })
+ .catch(() => null);
+ if (!response?.ok) return null;
+ const parsed = await response.json().catch(() => null);
+ return parsed?.ready === true ? parsed : null;
+}
+
+const delay = (ms) => new Promise((resolve) => { setTimeout(resolve, ms).unref?.(); });
+
+/**
+ * Spawn the sidecar and wait for it to report a loaded model.
+ *
+ * Wrapped by `ensureSidecar`'s single-flight promise, so this never runs twice
+ * concurrently — two 9 GB loads racing for the same port would leave one of
+ * them bound to nothing and the other reaped by a caller that never saw it.
+ */
+async function startSidecar() {
+ const pythonPath = availableJevPython();
+ if (!pythonPath) return failure('jev-not-installed');
+ const files = await findCachedRepoFiles(JEV_MODEL.repository, JEV_REQUIRED_FILES, { revision: JEV_MODEL.revision });
+ if (!files?.[0]) return failure('jev-not-installed');
+ // Every required file sits in the pinned subfolder, so its parent IS the
+ // directory `from_pretrained` loads.
+ const modelDir = dirname(files[0]);
+
+ const proc = spawn(
+ pythonPath,
+ [
+ HELPER_SCRIPT,
+ '--model-dir', modelDir,
+ '--port', String(PORTS.JEV),
+ '--host', '127.0.0.1',
+ '--model-id', JEV_MODEL.id,
+ '--revision', JEV_MODEL.revision,
+ ],
+ safeChildProcessOptions({
+ cwd: dirname(pythonPath),
+ env: withSpawnCwdEnv(buildJevEnv(), dirname(pythonPath)),
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }),
+ );
+ startingProc = proc;
+ let exited = false;
+ // Outside the request lifecycle: these handlers must not throw.
+ proc.on('error', () => { exited = true; });
+ proc.on('close', (code) => {
+ exited = true;
+ if (startingProc === proc) startingProc = null;
+ if (sidecar?.proc === proc) { sidecar = null; clearIdleTimer(); }
+ if (code) console.error(`❌ jev sidecar exited with code ${code}`);
+ });
+ // Drained, never retained: a dependency exception can carry the premise or a
+ // private path, and stderr would otherwise fill the pipe buffer and wedge
+ // the child once it exceeded it.
+ proc.stdout?.resume();
+ proc.stderr?.resume();
+
+ const deadline = Date.now() + JEV_START_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ // `startingProc` moving off this child means a stop landed mid-start.
+ if (exited || startingProc !== proc) return failure('jev-start-failed');
+ const health = await probeHealth();
+ if (health) {
+ startingProc = null;
+ sidecar = { proc, device: typeof health.device === 'string' ? health.device : null };
+ armIdleReaper();
+ console.log(`🧮 jev sidecar ready on 127.0.0.1:${PORTS.JEV} (${sidecar.device || 'unknown device'})`);
+ return { ok: true };
+ }
+ await delay(HEALTH_POLL_INTERVAL_MS);
+ }
+ if (startingProc === proc) startingProc = null;
+ if (proc.exitCode === null && !proc.killed) proc.kill('SIGTERM');
+ return failure('jev-start-failed');
+}
+
+function ensureSidecar() {
+ if (sidecar) { armIdleReaper(); return Promise.resolve({ ok: true }); }
+ // Single in-flight start. Cleared in `finally` so a failed start does not
+ // pin every later caller to the same rejection.
+ if (!startInFlight) {
+ startInFlight = startSidecar().finally(() => { startInFlight = null; });
+ }
+ return startInFlight;
+}
+
+// ── Scoring ───────────────────────────────────────────────────────────────
+
+/**
+ * Score a premise against a list of hypotheses.
+ *
+ * Returns the per-hypothesis entailment distribution in REQUEST ORDER, or a
+ * failure code. Never a Python traceback, never the premise, never a path.
+ */
+export async function scoreHypotheses({ premise, hypotheses, timeoutMs = JEV_REQUEST_TIMEOUT_MS } = {}) {
+ const parsed = jevScoreRequestSchema.safeParse({ premise, hypotheses });
+ if (!parsed.success) {
+ // The one length failure an operator can act on gets its own code; every
+ // other malformed input is a caller bug.
+ const tooLarge = typeof premise === 'string' && parsed.error.issues.some((issue) => issue.path[0] === 'premise' && issue.code === 'too_big');
+ return failure(tooLarge ? 'jev-premise-too-large' : 'jev-request-invalid');
+ }
+
+ const started = await ensureSidecar();
+ if (!started.ok) return started;
+
+ const response = await fetch(`${SIDECAR_ORIGIN}/score`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ premise: parsed.data.premise, hypotheses: parsed.data.hypotheses }),
+ signal: AbortSignal.timeout(timeoutMs),
+ }).catch((error) => (error?.name === 'TimeoutError' || error?.name === 'AbortError' ? 'timeout' : null));
+
+ if (response === 'timeout') return failure('jev-timeout');
+ if (!response) return failure('jev-start-failed');
+ armIdleReaper();
+
+ const body = await response.text().catch(() => null);
+ if (typeof body !== 'string' || body.length > JEV_MAX_RESPONSE_CHARS) return failure('jev-response-invalid');
+ // The sidecar's own codes are already operator-safe; anything else it could
+ // say is not, so an unrecognized body collapses to one code.
+ if (!response.ok) return failure(safeErrorCode(body));
+ const wire = safeJSONParse(body, null, { allowArray: false, logError: false });
+ return normalizeJevScores(wire, { hypotheses: parsed.data.hypotheses });
+}
+
+function safeErrorCode(body) {
+ const parsed = safeJSONParse(body, null, { allowArray: false, logError: false });
+ return JEV_SIDECAR_FAILURE_CODES.includes(parsed?.error) ? parsed.error : 'jev-response-invalid';
+}
+
+/**
+ * Ask the scorer to pick one of `options`, or to abstain.
+ *
+ * `abstained: true` means the top two options were within `minMargin` of each
+ * other. The caller MUST fall back (ask a chat model, do nothing) — picking
+ * the top option anyway discards the only signal this service adds over a
+ * coin flip.
+ */
+export async function decide({ premise, options, minMargin } = {}) {
+ // Checked BEFORE scoring: a single option has no runner-up, so there is no
+ // margin to compute and no reason to pay for a forward pass to learn that.
+ if (!Array.isArray(options) || options.length < 2) return failure('jev-request-invalid');
+ const scored = await scoreHypotheses({ premise, hypotheses: options });
+ if (!scored.ok) return scored;
+ return decideFromScores(scored.scores, minMargin);
+}
diff --git a/server/services/jev.test.js b/server/services/jev.test.js
new file mode 100644
index 0000000000..53df4e31a9
--- /dev/null
+++ b/server/services/jev.test.js
@@ -0,0 +1,255 @@
+/**
+ * jev sidecar lifecycle.
+ *
+ * The regressions these pin are all invisible to a behavioral assertion on the
+ * scores: a second 9 GB process, a sidecar spawned at import time, weights that
+ * stay resident forever, and a Python traceback reaching an operator payload.
+ * Each one leaves `scoreHypotheses` returning correct numbers.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const spawn = vi.fn();
+const findCachedRepoFiles = vi.fn();
+const existsSync = vi.fn();
+
+// The runtime probe runs through promisify(execFile); a bare vi.fn() would
+// never invoke the callback and every status read would hang.
+const execFile = vi.fn((_command, _args, options, callback) => {
+ (typeof options === 'function' ? options : callback)(new Error('probe unavailable'));
+ return {};
+});
+vi.mock('../lib/childProcess.js', () => ({ spawn, execFile }));
+vi.mock('../lib/hfCache.js', () => ({ findCachedRepoFiles, getHfCacheRoot: () => '/tmp/hf-cache-double' }));
+vi.mock('node:fs', async (importOriginal) => ({ ...(await importOriginal()), existsSync }));
+vi.mock('./hfDownload.js', () => ({ downloadHfRepo: vi.fn() }));
+vi.mock('../lib/pythonSetup.js', () => ({
+ createVenv: vi.fn(),
+ detectVenvBasePythonSync: vi.fn(() => null),
+ installPackages: vi.fn(),
+}));
+
+const MODEL_FILE = '/hf/snapshots/abc/qwen3.5-4b-nli/config.json';
+
+/** A spawned child that never exits on its own, like a healthy sidecar. */
+function fakeChild() {
+ const listeners = new Map();
+ return {
+ exitCode: null,
+ killed: false,
+ stdout: { resume: vi.fn() },
+ stderr: { resume: vi.fn() },
+ on(event, handler) { listeners.set(event, handler); return this; },
+ kill(signal) { this.killed = true; this.exitCode = 0; listeners.get('close')?.(0, signal); },
+ emitClose(code) { this.exitCode = code; listeners.get('close')?.(code); },
+ };
+}
+
+/** An installed, cached, ready host. */
+function makeInstalled() {
+ existsSync.mockReturnValue(true);
+ findCachedRepoFiles.mockResolvedValue([MODEL_FILE]);
+}
+
+const healthOk = { ok: true, json: async () => ({ ready: true, device: 'cpu' }) };
+const scoreOk = (scores) => ({
+ ok: true,
+ text: async () => JSON.stringify({ schemaVersion: 1, complete: true, scores }),
+});
+
+let jev;
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ jev = await import('./jev.js');
+});
+
+afterEach(() => {
+ jev.stopJevSidecar();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('no cold bootstrap', () => {
+ // AI Provider Usage Policy: importing the module must load nothing. A
+ // top-level `ensureSidecar()` would pass every scoring assertion below.
+ it('spawns nothing on import', () => {
+ expect(spawn).not.toHaveBeenCalled();
+ expect(jev.isJevSidecarRunning()).toBe(false);
+ });
+
+ it('spawns nothing for a status read', async () => {
+ makeInstalled();
+ await jev.getJevStatus();
+ expect(spawn).not.toHaveBeenCalled();
+ });
+});
+
+describe('scoreHypotheses', () => {
+ it('reports jev-not-installed when the pinned snapshot is absent, and starts nothing', async () => {
+ existsSync.mockReturnValue(true);
+ findCachedRepoFiles.mockResolvedValue(null);
+ expect(await jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] }))
+ .toEqual({ ok: false, code: 'jev-not-installed' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('reports jev-not-installed when no dedicated virtualenv exists', async () => {
+ existsSync.mockReturnValue(false);
+ findCachedRepoFiles.mockResolvedValue([MODEL_FILE]);
+ expect(await jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] }))
+ .toEqual({ ok: false, code: 'jev-not-installed' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('separates a too-large premise from an otherwise malformed request', async () => {
+ makeInstalled();
+ expect(await jev.scoreHypotheses({ premise: 'x'.repeat(40_000), hypotheses: ['a', 'b'] }))
+ .toEqual({ ok: false, code: 'jev-premise-too-large' });
+ expect(await jev.scoreHypotheses({ premise: '', hypotheses: ['a'] }))
+ .toEqual({ ok: false, code: 'jev-request-invalid' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('binds the sidecar to loopback on the declared port and returns ordered scores', async () => {
+ makeInstalled();
+ spawn.mockReturnValue(fakeChild());
+ const scores = [
+ { hypothesis: 'a', entailment: 0.9, contradiction: 0.05, neutral: 0.05 },
+ { hypothesis: 'b', entailment: 0.1, contradiction: 0.8, neutral: 0.1 },
+ ];
+ vi.stubGlobal('fetch', vi.fn(async (url) => (String(url).endsWith('/health') ? healthOk : scoreOk(scores))));
+
+ const result = await jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] });
+ expect(result).toEqual({ ok: true, scores });
+
+ const { PORTS } = await import('../lib/ports.js');
+ const args = spawn.mock.calls[0][1];
+ expect(args).toContain('--host');
+ expect(args[args.indexOf('--host') + 1]).toBe('127.0.0.1');
+ expect(args[args.indexOf('--port') + 1]).toBe(String(PORTS.JEV));
+ // The model directory is derived from the resolved cache path, never from
+ // a request field.
+ expect(args[args.indexOf('--model-dir') + 1]).toBe('/hf/snapshots/abc/qwen3.5-4b-nli');
+ });
+
+ it('starts exactly one sidecar for two concurrent first callers', async () => {
+ makeInstalled();
+ spawn.mockReturnValue(fakeChild());
+ 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 },
+ ]))));
+
+ const [first, second] = await Promise.all([
+ jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] }),
+ jev.scoreHypotheses({ premise: 'q', hypotheses: ['a', 'b'] }),
+ ]);
+ expect(first.ok).toBe(true);
+ expect(second.ok).toBe(true);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports jev-start-failed when the sidecar dies before reporting ready', async () => {
+ makeInstalled();
+ const child = fakeChild();
+ spawn.mockImplementation(() => { queueMicrotask(() => child.emitClose(1)); return child; });
+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNREFUSED'); }));
+ const pending = jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] });
+ // Past one health-poll interval, so the readiness loop re-checks and sees
+ // the exit rather than waiting out the full start timeout.
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(await pending).toEqual({ ok: false, code: 'jev-start-failed' });
+ });
+
+ it('collapses a sidecar error body to a known code rather than forwarding its text', async () => {
+ makeInstalled();
+ spawn.mockReturnValue(fakeChild());
+ // A traceback can carry local paths or the premise. Nothing from it may
+ // reach the caller, so an unrecognized body becomes one fixed code.
+ vi.stubGlobal('fetch', vi.fn(async (url) => (String(url).endsWith('/health') ? healthOk : {
+ ok: false,
+ text: async () => 'Traceback (most recent call last): File "/Users/someone/…", premise=secret',
+ })));
+ const result = await jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] });
+ expect(result).toEqual({ ok: false, code: 'jev-response-invalid' });
+ });
+
+ it('rejects a reply describing different hypotheses than the ones asked about', async () => {
+ makeInstalled();
+ spawn.mockReturnValue(fakeChild());
+ vi.stubGlobal('fetch', vi.fn(async (url) => (String(url).endsWith('/health') ? healthOk : scoreOk([
+ { hypothesis: 'c', entailment: 0.9, contradiction: 0, neutral: 0.1 },
+ { hypothesis: 'd', entailment: 0.1, contradiction: 0, neutral: 0.9 },
+ ]))));
+ expect(await jev.scoreHypotheses({ premise: 'p', hypotheses: ['a', 'b'] }))
+ .toEqual({ ok: false, code: 'jev-response-invalid' });
+ });
+});
+
+describe('idle unload', () => {
+ it('reaps the sidecar after the idle window, and only after it', async () => {
+ 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'] });
+ expect(jev.isJevSidecarRunning()).toBe(true);
+
+ const { JEV_IDLE_UNLOAD_MS } = await import('../lib/jev.js');
+ vi.advanceTimersByTime(JEV_IDLE_UNLOAD_MS - 1);
+ expect(jev.isJevSidecarRunning()).toBe(true);
+ vi.advanceTimersByTime(1);
+ expect(child.killed).toBe(true);
+ expect(jev.isJevSidecarRunning()).toBe(false);
+ });
+});
+
+describe('decide', () => {
+ const scoringHost = (scores) => {
+ makeInstalled();
+ spawn.mockReturnValue(fakeChild());
+ vi.stubGlobal('fetch', vi.fn(async (url) => (String(url).endsWith('/health') ? healthOk : scoreOk(scores))));
+ };
+
+ it('abstains on a near-tie instead of returning the nominal winner', async () => {
+ scoringHost([
+ { hypothesis: 'reply', entailment: 0.52, contradiction: 0.2, neutral: 0.28 },
+ { hypothesis: 'none', entailment: 0.49, contradiction: 0.2, neutral: 0.31 },
+ ]);
+ const result = await jev.decide({ premise: 'p', options: ['reply', 'none'] });
+ expect(result).toMatchObject({ ok: true, abstained: true, choice: null });
+ });
+
+ // Checked before any forward pass: a single option has no runner-up, so
+ // there is no margin and no reason to load a 9 GB model to discover that.
+ it('refuses a single option without starting the sidecar', async () => {
+ makeInstalled();
+ expect(await jev.decide({ premise: 'p', options: ['only'] }))
+ .toEqual({ ok: false, code: 'jev-request-invalid' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+});
+
+describe('buildJevEnv', () => {
+ it('forces the offline flags and passes through no credentials', () => {
+ const env = jev.buildJevEnv({
+ PATH: '/usr/bin',
+ HOME: '/home/example',
+ HF_TOKEN: 'secret',
+ GITHUB_TOKEN: 'secret',
+ OPENAI_API_KEY: 'secret',
+ ANTHROPIC_API_KEY: 'secret',
+ PYTHONPATH: '/attacker',
+ });
+ expect(env).toMatchObject({ HF_HUB_OFFLINE: '1', TRANSFORMERS_OFFLINE: '1', PYTHONNOUSERSITE: '1' });
+ expect(Object.keys(env)).toEqual(expect.not.arrayContaining([
+ 'HF_TOKEN', 'GITHUB_TOKEN', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'PYTHONPATH',
+ ]));
+ });
+});
diff --git a/server/services/modelAbuseGuard.js b/server/services/modelAbuseGuard.js
index 729bf2151a..cb7f420f12 100644
--- a/server/services/modelAbuseGuard.js
+++ b/server/services/modelAbuseGuard.js
@@ -43,6 +43,7 @@ import {
normalizeModelAbuseGuardResult,
} from '../lib/modelAbuseGuard.js';
import { findCachedRepoFiles, getHfCacheRoot } from '../lib/hfCache.js';
+import { diagnosePythonRuntimeText } from '../lib/pythonRuntimeDiagnosis.js';
import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { publicReviewProviderBlock, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';
import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
@@ -328,21 +329,14 @@ function availableGuardPython() {
// Never return raw subprocess output: it can contain tokens, private paths,
// or authenticated package-index URLs. Match evidence to static diagnoses.
-function setupIssue(text, fallback = 'runtime-check-failed') {
- const missing = MODEL_ABUSE_GUARD_PYTHON_IMPORTS.find((name) => String(text || '').includes(`No module named '${name}'`));
- if (missing) return { code: 'package-missing', package: missing, message: `The classifier package ${missing} is missing.`, action: 'Repair model-abuse guard to install the pinned packages.' };
- const diagnoses = [
- [/No module named/, 'package-missing', 'A classifier package or dependency is missing.', 'Repair model-abuse guard to install the pinned packages.'],
- [/CERTIFICATE_VERIFY_FAILED|certificate verify failed/i, 'certificate-failed', 'Python could not verify the package server certificate.', 'Repair Python certificate trust, then retry installation.'],
- [/No matching distribution|Could not find a version that satisfies/i, 'wheel-unavailable', 'A pinned package has no matching distribution for this Python and platform.', 'Use a Python version and platform supported by the pinned packages, then repair the runtime.'],
- [/ResolutionImpossible|conflicting dependencies/i, 'dependency-conflict', 'The classifier dependencies could not be resolved.', 'Check the pinned package compatibility before retrying.'],
- [/No space left on device/i, 'disk-full', 'There is not enough disk space for the classifier.', 'Free disk space, then retry installation.'],
- [/timed? ?out|ReadTimeout|ConnectionError|NameResolution|Temporary failure|Network is unreachable|No route to host|connection error|NewConnectionError/i, 'network-failed', 'The download could not reach its server.', 'Check this machine’s network and Python connection to the download server, then retry.'],
- ];
- const match = diagnoses.find(([pattern]) => pattern.test(String(text || '')));
- if (match) return { code: match[1], message: match[2], action: match[3] };
- return { code: fallback, message: 'The dedicated classifier runtime could not be verified.', action: 'Repair model-abuse guard and inspect the reported install stage and exit code.' };
-}
+// The table itself is shared with the jev scorer (lib/pythonRuntimeDiagnosis.js)
+// — same failure vocabulary, different package noun and repair label.
+const setupIssue = (text, fallback = 'runtime-check-failed') => diagnosePythonRuntimeText(text, {
+ subject: 'classifier',
+ repairLabel: 'model-abuse guard',
+ imports: MODEL_ABUSE_GUARD_PYTHON_IMPORTS,
+ fallback,
+});
function probeScript() {
const imports = MODEL_ABUSE_GUARD_PYTHON_IMPORTS