Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Make Jev discoverable and manageable; fix training corpus crash (#7768)
[._.]/596ee6d82014
diff --git a/client/src/components/models/JevIntegrations.jsx b/client/src/components/models/JevIntegrations.jsxnew file mode 100644index 0000000000..059bbd0ed7--- /dev/null+++ b/client/src/components/models/JevIntegrations.jsx@@ -0,0 +1,101 @@+import { useCallback, useRef, useState } from 'react';+import { getJevPolicy, updateJevPolicy, updateInstanceFeature } from '../../services/api';+import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { publishInstanceFeatures, useInstanceFeatures } from '../../hooks/useInstanceFeatures';++const SOURCES = [+ ['github-issue', 'Issue replies and forge maintenance'],+ ['email', 'Message triage action and priority'],+ ['stacker-news', 'Stacker News classification and risk'],+];+const MODES = { disabled: 'Disabled', off: 'Shadow', prefer: 'Prefer local', only: 'Local only' };++export default function JevIntegrations({ registry, status }) {+ const { features, error: featureError } = useInstanceFeatures();+ const feature = features?.find(item => item.id === 'jev');+ const generation = useRef(0);+ const [policy, setPolicy] = useState(null);+ const [saving, setSaving] = useState(false);+ const [saveError, setSaveError] = useState('');+ const load = useCallback(() => {+ const requested = ++generation.current;+ return getJevPolicy({ silent: true }).then(result => {+ if (generation.current === requested) setPolicy(result);+ });+ }, []);+ const { error, refetch } = useAutoRefetch(load, 30000, { enabled: !saving });+ const save = (patch) => {+ generation.current += 1;+ setSaving(true);+ setSaveError('');+ return updateJevPolicy(patch, { silent: true }).then(setPolicy)+ .catch(() => setSaveError('Could not save Jev settings. The previous settings remain displayed.'))+ .finally(() => setSaving(false));+ };+ const toggleFeature = () => {+ setSaving(true);+ setSaveError('');+ return updateInstanceFeature('jev', !feature.enabled, { silent: true })+ .then(result => publishInstanceFeatures(result.features, { groups: result.groups }))+ .catch(() => setSaveError('Could not change Jev enablement.'))+ .finally(() => setSaving(false));+ };++ return (+ <div className="space-y-4 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-white">Runtime and integrations</h3>+ <p className="text-sm text-gray-300" role="status">+ Integrations: {featureError || !feature ? 'unknown' : feature.enabled ? 'enabled' : 'disabled'}.+ {' '}Runtime: {!status ? 'unknown' : status.resident ? 'model loaded' : status.ready ? 'installed, idle' : 'not ready'}.+ </p>+ <button type="button" onClick={toggleFeature} disabled={!feature || !!featureError || saving}+ className="px-3 py-2 text-sm border border-port-border rounded text-port-accent disabled:opacity-50">+ {saving ? 'Saving…' : feature?.enabled ? 'Disable Jev integrations' : 'Enable Jev integrations'}+ </button>+ <p className="text-xs text-gray-400">The model starts on the first scoring request and unloads after ten idle minutes. Disabling integrations prevents new automatic scoring; manual scoring and training remain explicit actions. Use Unload now to release a resident model.</p>+ <p className="text-xs text-gray-400">Shadow compares with the chat provider without changing its answer. Prefer local falls back to chat on abstention or failure. Local only skips unresolved items. Disabled runs no Jev scoring for that source. All sources also require the global switch and an installed model.</p>+ {(error || saveError) && <p role="alert" className="text-xs text-port-warning">{saveError || 'Could not refresh integration settings; displayed settings may be stale.'} <button type="button" onClick={refetch} className="underline">Retry</button></p>}+ {!policy && !error && <p className="text-xs text-gray-400">Loading integration settings…</p>}+ <fieldset disabled={saving || !!error || !policy} className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ {SOURCES.map(([source, label]) => (+ <div key={source}>+ <label htmlFor={`jev-source-${source}`} className="block text-xs text-gray-300 mb-1">{label}</label>+ <select id={`jev-source-${source}`} value={policy?.sources?.[source]?.jevMode || 'off'}+ disabled={!policy?.sources?.[source]}+ onChange={event => save({ sources: { [source]: { jevMode: event.target.value } } })}+ className="w-full bg-port-bg border border-port-border rounded p-2 text-sm text-white">+ {Object.entries(MODES).map(([value, name]) => <option key={value} value={value}>{name}</option>)}+ </select>+ {policy && !policy.sources?.[source] && <p className="text-xs text-port-warning">Invalid policy; repair content safety settings.</p>}+ <p className="text-xs text-gray-500 mt-1">Additional margin floor: {policy?.sources?.[source]?.jevMinMargin ?? 'per-decision default'}</p>+ </div>+ ))}+ <div>+ <label htmlFor="jev-scope-enabled" className="block text-xs text-gray-300 mb-1">Issue / PR scope adherence</label>+ <select id="jev-scope-enabled" value={policy?.scopeAdherenceEnabled === false ? 'disabled' : 'enabled'}+ onChange={event => save({ scopeAdherenceEnabled: event.target.value === 'enabled' })}+ className="w-full bg-port-bg border border-port-border rounded p-2 text-sm text-white">+ <option value="enabled">Enabled — on-demand advisory</option><option value="disabled">Disabled</option>+ </select>+ </div>+ </fieldset>+ <p className="text-xs text-gray-400">Scope adherence runs when you click Check scope on an issue or PR: retrieve up to three relevant PRD.md / GOALS.md clauses, then score each change against a clause. It does not block completion. Stacker News uses Jev only to escalate; an allowed / low-risk answer still requires the existing analysis.</p>+ <p className="text-xs text-gray-400">Agent-completion goal fidelity uses a separate chat-model reviewer, with forge verification for merge objectives. Jev does not grade those completions. <a href="/models/code-reviewers" className="text-port-accent underline">Manage completion reviews</a></p>+ <a href="/models/llms/abuse" className="text-xs text-port-accent underline">Advanced source policies and margin overrides</a>+ <details className="text-xs text-gray-300 border border-port-border rounded p-3">+ <summary className="cursor-pointer text-port-accent">Questions, answer options, and decision formula</summary>+ <p className="my-3">Each option receives an entailment probability. Winner = highest entailment; margin = winner minus runner-up. Accept only when margin ≥ max(decision floor, winning option floor, source override); otherwise abstain. Agreement with chat measures consistency, not correctness. Scope adherence has no chat comparison.</p>+ {!registry && <p>Decision definitions unavailable. Refresh the page to retry.</p>}+ {Object.entries(registry || {}).map(([id, definition]) => (+ <div key={id} className="border-t border-port-border py-3 space-y-2">+ <h4 className="font-medium text-white">{definition.label}</h4>+ <p>Decision margin floor: {definition.minMargin}</p>+ <ul className="space-y-2">{definition.options.map(option => (+ <li key={option.value}><strong>{option.value}</strong>: {option.hypothesis} <span className="text-gray-500">(floor {Math.max(definition.minMargin, option.minMargin || 0)})</span></li>+ ))}</ul>+ </div>+ ))}+ </details>+ </div>+ );+}diff --git a/client/src/components/models/JevIntegrations.test.jsx b/client/src/components/models/JevIntegrations.test.jsxnew file mode 100644index 0000000000..ad67b182ff--- /dev/null+++ b/client/src/components/models/JevIntegrations.test.jsx@@ -0,0 +1,54 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import JevIntegrations from './JevIntegrations';+import { getJevPolicy, updateJevPolicy, updateInstanceFeature } from '../../services/api';+import { publishInstanceFeatures } from '../../hooks/useInstanceFeatures';++vi.mock('../../services/api', () => ({ getJevPolicy: vi.fn(), updateJevPolicy: vi.fn(), updateInstanceFeature: vi.fn() }));+vi.mock('../../hooks/useInstanceFeatures', () => ({+ useInstanceFeatures: () => ({ features: [{ id: 'jev', enabled: false }], error: null }),+ publishInstanceFeatures: vi.fn(),+}));+const policy = { scopeAdherenceEnabled: true, sources: {+ 'github-issue': { jevMode: 'off', jevMinMargin: null },+ email: { jevMode: 'prefer', jevMinMargin: 0.3 },+ 'stacker-news': { jevMode: 'only', jevMinMargin: null },+} };+beforeEach(() => {+ vi.clearAllMocks();+ getJevPolicy.mockResolvedValue(policy);+});++describe('Jev integration management', () => {+ it('distinguishes enablement from residency, displays definitions, and saves explicit disabling', async () => {+ let finishSave;+ updateJevPolicy.mockImplementation(() => new Promise(resolve => { finishSave = resolve; }));+ render(<JevIntegrations status={{ ready: true, resident: false }} registry={{ example: {+ label: 'Example question', minMargin: 0.2, options: [{ value: 'yes', hypothesis: 'Example hypothesis.' }],+ } }} />);+ const control = await screen.findByLabelText('Issue replies and forge maintenance');+ await waitFor(() => expect(control).toBeEnabled());+ expect(screen.getByRole('status')).toHaveTextContent('Integrations: disabled. Runtime: installed, idle.');+ expect(control).toHaveValue('off');+ expect(screen.getByText(/Example hypothesis/)).toBeInTheDocument();+ fireEvent.change(control, { target: { value: 'disabled' } });+ expect(updateJevPolicy).toHaveBeenCalledWith({ sources: { 'github-issue': { jevMode: 'disabled' } } }, { silent: true });+ expect(control).toBeDisabled();+ getJevPolicy.mockResolvedValue({ ...policy, sources: { ...policy.sources, 'github-issue': { jevMode: 'disabled' } } });+ finishSave(await getJevPolicy());+ await waitFor(() => expect(control).toHaveValue('disabled'));+ updateInstanceFeature.mockResolvedValue({ features: [{ id: 'jev', enabled: true }] });+ fireEvent.click(screen.getByRole('button', { name: 'Enable Jev integrations' }));+ await waitFor(() => expect(publishInstanceFeatures).toHaveBeenCalledWith([{ id: 'jev', enabled: true }], { groups: undefined }));+ });++ it('keeps the saved setting and reports failed writes', async () => {+ updateJevPolicy.mockRejectedValue(new Error('offline'));+ render(<JevIntegrations />);+ const control = await screen.findByLabelText('Issue / PR scope adherence');+ await waitFor(() => expect(control).toBeEnabled());+ fireEvent.change(control, { target: { value: 'disabled' } });+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not save');+ expect(control).toHaveValue('enabled');+ });+});diff --git a/client/src/components/models/JevPanel.jsx b/client/src/components/models/JevPanel.jsxindex 3764d1cc0d..6b0c6eb4b8 100644--- a/client/src/components/models/JevPanel.jsx+++ b/client/src/components/models/JevPanel.jsx@@ -1,6 +1,8 @@import { useCallback, useEffect, useRef, useState } from 'react';import { CheckCircle2, Circle, Download, ExternalLink, GraduationCap, RefreshCw, Scale } from 'lucide-react';import toast from '../ui/Toast';+import JevIntegrations from './JevIntegrations';+import { useAutoRefetch } from '../../hooks/useAutoRefetch';import BrailleSpinner from '../BrailleSpinner';import { formatBytes, formatCount, formatPercent } from '../../utils/formatters';import {@@ -56,7 +58,9 @@ export default function JevPanel() {const [scoring, setScoring] = useState(false);const [decision, setDecision] = useState(null);const [decisionStats, setDecisionStats] = useState(null);+ const [statsError, setStatsError] = useState(false);const [headState, setHeadState] = useState(null);+ const [headStatusError, setHeadStatusError] = useState(false);const [training, setTraining] = useState(false);const [headError, setHeadError] = useState('');// `linear` is the honest default: a 3-way logistic regression over a frozen@@ -75,21 +79,27 @@ export default function JevPanel() {.catch(() => { setStatusError(true); return null; })), []);+ const loadStats = useCallback(() => getJevDecisionStats({ silent: true })+ .then(res => { setDecisionStats(res); setStatsError(false); })+ .catch(() => setStatsError(true)), []);+// Metrics and adoption state only — no corpus row, premise, or path crosses// this boundary, so it is as safe to load on mount as the counters are.const loadHeads = useCallback(() => (getJevHeads({ silent: true })- .then((res) => { setHeadState(res); return res; })- .catch(() => { setHeadState(null); return null; })+ .then((res) => { setHeadState(res); setHeadStatusError(false); return res; })+ .catch(() => { setHeadStatusError(true); return null; })), []);+ useAutoRefetch(() => Promise.all([loadStatus(), loadStats(), loadHeads()]), 30000, { pollOnly: true, immediate: false });+useEffect(() => {let active = true;loadStatus();// Counters only, so this is safe to load beside status on every mount.getJevDecisionStats({ silent: true }).then((res) => { if (active) setDecisionStats(res); })- .catch(() => { if (active) setDecisionStats(null); });+ .catch(() => { if (active) setStatsError(true); });loadHeads();return () => { active = false; };}, [loadStatus, loadHeads]);@@ -193,6 +203,7 @@ export default function JevPanel() {const currentStageId = installingStage || (installing ? stages.find((stage) => !stage.ready)?.id : null);const ready = status?.ready === true;const incomplete = status?.setupState === 'incomplete';+ const trainingActive = training || headState?.training === true;return (<section@@ -221,6 +232,8 @@ export default function JevPanel() {)}</div>+ <JevIntegrations registry={decisionStats?.registry} status={statusError ? null : status} />+<p className="text-sm text-gray-300 max-w-2xl leading-relaxed">Answers closed-set questions — “which of these options does this text entail?” — without generating textor spending provider quota. When the top two options are too close to separate, it <strong>abstains</strong> rather@@ -288,7 +301,7 @@ export default function JevPanel() {</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">+ <button type="button" onClick={() => { loadStatus(); loadStats(); loadHeads(); }} 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 ? (@@ -333,12 +346,13 @@ export default function JevPanel() {<div className="space-y-3 border-t border-port-border pt-4"><h3 className="text-sm font-semibold text-white">Agreement with the chat model</h3><p className="text-xs text-gray-400 max-w-2xl">- While a source is set to <strong>Off</strong>, PortOS still asks the scorer each closed-set question and compares+ When the global feature is enabled and a source is set to <strong>Shadow</strong>, PortOS still asks the scorer each closed-set question and comparesits answer to the one the chat model gave — without changing anything. Use these rates to decide whether a sourceis ready for <strong>Prefer</strong>. Counts only: no message, comment, or diff text is recorded.</p>+ {statsError && <p role="alert" className="text-xs text-port-warning">Decision metrics unavailable; any displayed counts may be stale.</p>}{!decisionStats?.decisions?.length ? (- <p className="text-xs text-gray-500">No decisions measured yet on this machine.</p>+ <p className="text-xs text-gray-500">{statsError ? 'Refresh status to retry.' : decisionStats ? 'No decisions measured yet on this machine.' : 'Loading decision metrics…'}</p>) : (<div className="overflow-x-auto"><table className="w-full text-xs" data-testid="jev-decision-stats">@@ -347,6 +361,7 @@ export default function JevPanel() {<th scope="col" className="py-1 pr-3 font-medium">Decision</th><th scope="col" className="py-1 pr-3 font-medium">Observed</th><th scope="col" className="py-1 pr-3 font-medium">Abstained</th>+ <th scope="col" className="py-1 pr-3 font-medium">Unavailable</th><th scope="col" className="py-1 pr-3 font-medium">Agreed</th></tr></thead>@@ -356,6 +371,7 @@ export default function JevPanel() {<th scope="row" className="py-1.5 pr-3 font-normal text-white">{row.label}</th><td className="py-1.5 pr-3">{formatCount(row.observed, { fallback: '0' })}</td><td className="py-1.5 pr-3">{formatRate(row.abstentionRate)}</td>+ <td className="py-1.5 pr-3">{formatCount(row.unavailable, { fallback: '0' })}</td><td className="py-1.5 pr-3">{formatRate(row.agreementRate)}<span className="text-gray-500"> of {formatCount(row.compared, { fallback: '0' })}</span>@@ -366,7 +382,7 @@ export default function JevPanel() {</table></div>)}- <a href="/models/llms/abuse" className="text-xs text-port-accent hover:underline">Set a source to Prefer in Content safety policies</a>+ <a href="/models/llms/abuse" className="text-xs text-port-accent hover:underline">Configure advanced content safety policies</a></div><div className="space-y-3 border-t border-port-border pt-4">@@ -383,8 +399,9 @@ export default function JevPanel() {discarded, which is an ordinary result rather than a failure.</p>+ {headStatusError && <p role="alert" className="text-xs text-port-warning">Head status unavailable; refresh status to retry. Displayed head data may be stale.</p>}{(headState?.heads || []).length === 0 ? (- <p className="text-xs text-gray-500">No project head trained on this machine. Scope adherence answers zero-shot.</p>+ <p className="text-xs text-gray-500">{headStatusError ? 'Training and adoption state could not be verified.' : headState ? 'No project head trained on this machine. Scope adherence answers zero-shot.' : 'Loading project heads…'}</p>) : (<div className="overflow-x-auto"><table className="w-full text-xs" data-testid="jev-head-table">@@ -457,24 +474,24 @@ export default function JevPanel() {<buttontype="button"onClick={runTraining}- disabled={!ready || training || headState?.training === true}+ disabled={!ready || trainingActive || !headState || headStatusError}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">- <GraduationCap size={12} /> {training ? 'Training…' : 'Train a project head'}+ <GraduationCap size={12} /> {trainingActive ? 'Training…' : 'Train a project head'}</button><label htmlFor="jev-head-architecture" className="text-xs text-gray-400">Head</label><selectid="jev-head-architecture"value={architecture}onChange={(event) => setArchitecture(event.target.value)}- disabled={training}+ disabled={trainingActive}className="text-xs bg-port-bg border border-port-border rounded px-2 py-1 text-gray-200 disabled:opacity-50"><option value="linear">Linear</option><option value="mlp1">One hidden layer</option></select>{!ready && <span className="text-xs text-gray-500">Install jev first.</span>}- {training && (+ {trainingActive && (<span className="flex items-center gap-1.5 text-xs text-gray-300"><BrailleSpinner /> Reading this repository’s history and encoding it once — minutes on a cold cache, seconds after.</span>diff --git a/client/src/components/models/JevPanel.test.jsx b/client/src/components/models/JevPanel.test.jsxindex 84f13cfddd..59115d3efa 100644--- a/client/src/components/models/JevPanel.test.jsx+++ b/client/src/components/models/JevPanel.test.jsx@@ -13,6 +13,7 @@ vi.mock('../../services/api', () => ({adoptJevHead: vi.fn(),discardJevHead: vi.fn(),}));+vi.mock('./JevIntegrations', () => ({ default: () => <div>Integration controls</div> }));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() }),@@ -221,7 +222,7 @@ describe('JevPanel decision agreement', () => {it('keeps the panel usable when the counters cannot be read', async () => {getJevDecisionStats.mockRejectedValue(new Error('unavailable'));await renderPanel();- expect(await screen.findByText('No decisions measured yet on this machine.')).toBeInTheDocument();+ expect(await screen.findByRole('alert')).toHaveTextContent('Decision metrics unavailable');});});diff --git a/client/src/components/models/UntrustedContentPolicyPanel.jsx b/client/src/components/models/UntrustedContentPolicyPanel.jsxindex bd1883e614..b5fd33d829 100644--- a/client/src/components/models/UntrustedContentPolicyPanel.jsx+++ b/client/src/components/models/UntrustedContentPolicyPanel.jsx@@ -115,8 +115,9 @@ export default function UntrustedContentPolicyPanel() {if (value) patch({ jevMode: value });else clearField('jevMode');}} className={INPUT_CLASS}>- <option value="">{source === 'defaults' ? 'Off (shipped default)' : `Inherit ${inheritanceName} (${defaults.jevMode || 'off'})`}</option>- <option value="off">Off — always ask the provider</option>+ <option value="">{source === 'defaults' ? 'Shadow (shipped default)' : `Inherit ${inheritanceName} (${defaults.jevMode || 'off'})`}</option>+ <option value="off">Shadow — compare with the provider</option>+ <option value="disabled">Disabled — do not run Jev</option><option value="prefer">Prefer — local first, provider on abstain</option><option value="only">Only — local first, skip the item on abstain</option></select>diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 5fbd486e00..f09b6be323 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -9,7 +9,7 @@ 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, feature: 'jev' },+ { id: 'jev', label: 'jev', icon: Scale },];// Palettable LLM drill-downs. Model Library stays a focused view of@@ -31,14 +31,7 @@ export const LLM_NAV_SUBROUTES = [export function LocalLlmTab({ view }) {const navigate = useNavigate();const { isFeatureEnabled } = useInstanceFeatures();- // Resolved against the FULL list, never the visible one: a disabled feature- // hides the pill but leaves the route live, so a bookmark, a shared link, or- // voice `ui_navigate` still lands on the panel (client/src/lib/navFeatures.js)- // — and the pill stays visible while that panel is the one on screen.const activeView = LLM_VIEWS.some(({ id }) => id === view) ? view : 'library';- // The same gate the sidebar and ⌘K apply to the manifest. Without it a- // default-off feature still advertises itself here — for jev, a ~9 GB- // download the install has not opted into.const visibleViews = LLM_VIEWS.filter((tab) => tab.id === activeView || isFeatureEnabled(tab.feature));return (diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 2548179dc3..79f9ba1543 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -19,7 +19,8 @@ vi.mock('../models/ModelAbuseGuardPanel.jsx', () => ({vi.mock('../models/JevPanel.jsx', () => ({default: () => <div data-testid="jev-view">jev</div>,}));-// jev is an optional, default-OFF instance feature, so which pills the bar+// Jev integrations are optional; management stays discoverable regardless.+// Which pills the bar// advertises depends on live feature state rather than the static view list.const disabledFeatures = new Set();vi.mock('../../hooks/useInstanceFeatures.js', () => ({@@ -87,21 +88,12 @@ describe('LocalLlmTab view dispatch', () => {expect(screen.getByTestId('location')).toHaveTextContent('/models/llms/jev');});- // Settings > Features ships jev OFF, precisely so a fresh install does not- // advertise a page whose model is a ~9 GB download. The manifest entry is- // feature-tagged, so the sidebar and ⌘K already drop it; the pill bar is the- // third browse surface and has to apply the same gate or the opt-out leaks.- it('drops the jev pill while the feature is disabled', () => {+ it('keeps the Jev install and management page discoverable while disabled', () => {disabledFeatures.add('jev');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']);});- // Gating covers BROWSE surfaces only. A bookmark, a shared link, or voice- // `ui_navigate` still resolves /models/llms/jev, so the panel must mount —- // and its pill must stay visible while it is the one on screen, or the tab- // bar would render with nothing selected.it('still mounts jev from a direct URL while the feature is disabled', () => {disabledFeatures.add('jev');renderTab('jev');diff --git a/client/src/services/README.md b/client/src/services/README.mdindex fcc6b5b203..674c21e58e 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, the jev entailment scorer lifecycle (status / install / cancel / score / unload) plus its project-specific trained heads (list / train / adopt / discard, where adoption is gated server-side on beating both the stock zero-shot and the majority-class baseline), 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 / integration policies) plus its project-specific trained heads (list / train / adopt / discard, where adoption is gated server-side on beating both the stock zero-shot and the majority-class baseline), 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.jsindex d6df16eef5..6e63ec300d 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -442,3 +442,6 @@ export const applyLocalPersistentMindSetup = (body = {}, options = {}) =>body: JSON.stringify(body),...options,});++export const getJevPolicy = (options) => request('/local-llm/jev/policy', options);+export const updateJevPolicy = (body, options) => request('/local-llm/jev/policy', { method: 'PUT', body: JSON.stringify(body), ...options });diff --git a/docs/JEV_SETUP.md b/docs/JEV_SETUP.mdindex bb2e00ddcc..5942ad383b 100644--- a/docs/JEV_SETUP.md+++ b/docs/JEV_SETUP.md@@ -9,8 +9,9 @@ no provider quota. See the ADRfor 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.+Features** or **Models > LLMs > jev**. The management page and navigation stay+visible at `/models/llms/jev` even when integrations are disabled. Browsing the+page never installs or loads the model.## What gets installed@@ -128,3 +129,23 @@ provider or model picker can offer it.It is also not a replacement for the abuse guard. Prompt Guard screens externalcontent *before* anything reasons over it; jev is one of the things that maythen reason over it. See [features/messages-security.md](./features/messages-security.md).++## Integration management++The Jev page separates installation, model residency, global integration enablement,+and source policies. Source `off` retains its legacy meaning: **Shadow**, scoring+alongside chat for comparison. **Disabled** (`disabled`) actually suppresses scoring+for that source. **Prefer local** uses chat on abstention/failure; **Local only**+skips unresolved items. Existing policies are unchanged until explicitly edited.++Issue replies and forge maintenance share the GitHub issue policy; message action+and priority share email policy; Stacker News classification and risk share its+policy and remain escalation-only. Scope adherence has a separate on-demand switch+(default enabled under the global gate). It provides issue/PR advisories, not agent+completion grades. Completion goal fidelity remains the separate chat reviewer in+Models > Code Reviewers, with forge verification for merge objectives.++The page displays the shipped hypotheses directly from the decision registry and+explains margin floors. Agreement is comparison with chat, not measured correctness;+missing comparisons are not zero accuracy. Metrics and runtime status refresh while+the page is visible. Trained-head evaluation remains a separate held-out comparison.diff --git a/server/lib/README.md b/server/lib/README.mdindex a494006fc5..56c101eca9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -661,7 +661,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `streamingSpawn.js` | `runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?})` — run one command to completion and forward its stdout/stderr LINES to a hook, resolving `{ success, error? }`. Never rejects (spawn error, non-zero exit, and timeout all resolve as `success: false`) because every caller is an install/setup flow running outside the Express request lifecycle, and the `onLine` hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so `brew upgrade ollama` exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by `services/localLlm.js`'s package-manager installs and `services/localRuntimeSetup.js`'s one-click daemon setup. `splitRe` is forwarded to the line readers — pass `/[\r\n]+/` for a downloader whose progress bar redraws one line with a bare `\r`, or the stream goes silent for the whole download. `isCancelled` is polled once a second and SIGKILLs the child when it turns true (resolving `{success:false, error:'cancelled'}`) — required for a command that can run for hours while the caller holds a lock until it settles; a throwing predicate is logged and read as "not cancelled" rather than crashing the process from a timer callback. `bufferedSpawn.js` is the sibling for run-and-collect; use this one when live output IS the progress. || `repoIntakeActions.js` | `REPO_INTAKE_KEYS` + `normalizeRepoIntake(input)` — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (`malwareScan` → `/do:scan`, `learn` → a `repo-study` review). Pure half of `services/repoIntake.js` (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link. || `tombstones.js` | Generic timestamped tombstones (`{ <keyField>, deletedAt }`) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). `normalizeTombstones` / `recordTombstone` / `clearTombstone` / `tombstoneTimestamp` maintain the list; `mergeTombstones` unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; `isTombstoned(list, key, createdAt)` suppresses a record unless its own creation stamp is strictly NEWER than the deletion; `pruneTombstones(list, records)` drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); `supersedingTimestamp(deletedAt)` stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through `lwwTimestamp.js`, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. `DEFAULT_TOMBSTONE_LIMIT` (200) caps growth. |-| `untrustedContent.js` | Shared source policies, strict settings schema, data framing and API-only/local-private provider eligibility for untrusted GitHub and messaging content. |+| `untrustedContent.js` | `jevPolicyPatchSchema` validates narrow scorer-management updates. Shared source policies, strict settings schema, data framing and API-only/local-private provider eligibility for untrusted GitHub and messaging content. || `untrustedContentSources.js` | The ingress vocabulary alone — `UNTRUSTED_CONTENT_SOURCES` and `PRIVATE_UNTRUSTED_CONTENT_SOURCES`. Split out of `untrustedContent.js` (which reaches `zod` and `node:crypto`) so the browser can import it: the Abuse Guard panel offers exactly the sources the server screens, instead of restating them and drifting (#7680). || `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. || `userActionTypes.js` | Closed vocabulary for the operator-action ledger (`user_action_events`, #5594 / #5596): `USER_ACTION_TYPES` (CoS task/feedback/schedule + settings + instance-feature toggles + event-only creative/Brain pointers), `USER_ACTION_ACTORS` (`user` / `mind` / `schedule` / `system`), and the `isUserActionType` / `isUserActionActor` predicates. `recordUserAction` (`services/userActions.js`) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on. |diff --git a/server/lib/bm25.js b/server/lib/bm25.jsindex 283e470751..e81df3e9a6 100644--- a/server/lib/bm25.js+++ b/server/lib/bm25.js@@ -63,9 +63,10 @@ function calculateIDF(N, n) {* @returns {Object} - Inverted index structure*/function buildInvertedIndex(documents) {+ // Text tokens and caller-owned IDs must never resolve Object.prototype keys.const index = {- terms: {}, // term -> { docFreq, postings: { docId -> termFreq } }- docLengths: {}, // docId -> number of terms+ terms: Object.create(null), // term -> { docFreq, postings: { docId -> termFreq } }+ docLengths: Object.create(null), // docId -> number of termsavgDocLength: 0, // Average document lengthtotalDocs: 0, // Total number of documentsdocIds: new Set() // Set of all document IDs@@ -84,7 +85,7 @@ function buildInvertedIndex(documents) {totalTerms += terms.length// Count term frequencies in this document- const termFreqs = {}+ const termFreqs = Object.create(null)for (const term of terms) {termFreqs[term] = (termFreqs[term] || 0) + 1}@@ -92,7 +93,7 @@ function buildInvertedIndex(documents) {// Update inverted indexfor (const [term, freq] of Object.entries(termFreqs)) {if (!index.terms[term]) {- index.terms[term] = { docFreq: 0, postings: {} }+ index.terms[term] = { docFreq: 0, postings: Object.create(null) }}if (!index.terms[term].postings[docId]) {@@ -135,7 +136,7 @@ function addDocument(index, docId, text) {index.avgDocLength = (oldTotal + terms.length) / index.totalDocs// Count term frequencies- const termFreqs = {}+ const termFreqs = Object.create(null)for (const term of terms) {termFreqs[term] = (termFreqs[term] || 0) + 1}@@ -143,7 +144,7 @@ function addDocument(index, docId, text) {// Update inverted indexfor (const [term, freq] of Object.entries(termFreqs)) {if (!index.terms[term]) {- index.terms[term] = { docFreq: 0, postings: {} }+ index.terms[term] = { docFreq: 0, postings: Object.create(null) }}if (!index.terms[term].postings[docId]) {@@ -286,8 +287,8 @@ function search(query, index, options = {}) {*/function createEmptyIndex() {return {- terms: {},- docLengths: {},+ terms: Object.create(null),+ docLengths: Object.create(null),avgDocLength: 0,totalDocs: 0,docIds: new Set()@@ -315,8 +316,15 @@ function deserializeIndex(data) {if (!data) return createEmptyIndex()return {- terms: data.terms || {},- docLengths: data.docLengths || {},+ // JSON restores ordinary objects. Rebuild dictionaries without inherited+ // keys so terms and document IDs such as constructor stay ordinary data.+ terms: Object.assign(Object.create(null), Object.fromEntries(+ Object.entries(data.terms || {}).map(([term, entry]) => [term, {+ ...entry,+ postings: Object.assign(Object.create(null), entry.postings),+ }])+ )),+ docLengths: Object.assign(Object.create(null), data.docLengths),avgDocLength: data.avgDocLength || 0,totalDocs: data.totalDocs || 0,docIds: new Set(data.docIds || [])diff --git a/server/lib/bm25.test.js b/server/lib/bm25.test.jsindex af3eace11c..6032dd93ce 100644--- a/server/lib/bm25.test.js+++ b/server/lib/bm25.test.js@@ -15,6 +15,25 @@ import {} from './bm25.js';describe('BM25 Algorithm', () => {+ it('treats prototype names as terms and IDs across indexing, persistence, and updates', () => {+ const index = buildInvertedIndex([{ id: 'example', text: 'agent routing' }]);+ expect(search('constructor __proto__', index)).toEqual([]);+ addDocument(index, '__proto__', 'constructor constructor agent');+ expect(search('constructor', index).map(row => row.docId)).toEqual(['__proto__']);+ const restored = deserializeIndex(JSON.parse(JSON.stringify(serializeIndex(index))));+ addDocument(restored, 'constructor', '__proto__ routing');+ expect(search('__proto__', restored).map(row => row.docId)).toEqual(['constructor']);+ expect(search('constructor', restored)[0].score).toBeGreaterThan(0);+ addDocument(restored, '__proto__', 'ordinary replacement');+ expect(search('constructor', restored)).toEqual([]);+ removeDocument(restored, 'constructor');+ expect(search('__proto__', restored)).toEqual([]);+ // Initial bulk indexing must use the same dictionary semantics as updates.+ expect(search('constructor', buildInvertedIndex([+ { id: '__proto__', text: 'constructor' },+ ]))[0].docId).toBe('__proto__');+ });+describe('tokenize', () => {it('should tokenize text into lowercase terms', () => {const result = tokenize('Hello World');diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsindex 04461af4f0..e2b677898f 100644--- a/server/lib/instanceFeatureRegistry.js+++ b/server/lib/instanceFeatureRegistry.js@@ -67,9 +67,7 @@ export const INSTANCE_FEATURES = 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.+ // Gates scoring integrations, not discovery: the management page stays visible.defaultEnabled: false,}),Object.freeze({diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex b8fbe8342e..1912e64e58 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -324,7 +324,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'] },+ { id: 'nav.models.llms.jev', path: '/models/llms/jev', label: 'jev', section: 'Models', 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 adiff --git a/server/lib/untrustedContent.js b/server/lib/untrustedContent.jsindex 07adc46471..0a354246a4 100644--- a/server/lib/untrustedContent.js+++ b/server/lib/untrustedContent.js@@ -9,7 +9,7 @@ export const DEFAULT_UNTRUSTED_CONTENT_POLICY = Object.freeze({classifierMode: 'required', minBenignScore: 0.9,maxInputChars: MODEL_ABUSE_GUARD_MAX_INPUT_CHARS, maxOutputChars: 32_000,providerId: null, model: null,- // The local entailment scorer is OFF until an operator opts a source in.+ // The global feature gates scoring; legacy off means shadow-only comparison.// `jevMinMargin: null` means "use the per-decision floor in// `lib/jevDecisions.js`"; a number can only raise that floor, never lower it.jevMode: 'off', jevMinMargin: null,@@ -22,20 +22,30 @@ export const untrustedContentPolicySchema = z.object({maxOutputChars: z.number().int().min(100).max(100_000).optional(),providerId: z.string().trim().min(1).max(128).nullable().optional(),model: z.string().trim().min(1).max(300).nullable().optional(),- // off — today's behavior exactly, and the shipped default.+ // disabled — no scorer call, including no shadow measurement.+ // off — legacy shadow mode; chat still owns the answer (shipped default).// prefer — jev first, chat-LLM fallback whenever it abstains or is unavailable.// only — jev first, and an abstention SKIPS the item with a recorded reason// rather than spending provider quota. Never coerced into the// permissive enum member (`none`/`defer`); that would turn a// "cannot tell" into a silent approval.- jevMode: z.enum(['off', 'prefer', 'only']).optional(),+ jevMode: z.enum(['off', 'disabled', 'prefer', 'only']).optional(),jevMinMargin: z.number().min(0).max(1).nullable().optional(),}).strict();export const untrustedContentSettingsSchema = z.object({+ scopeAdherenceEnabled: z.boolean().optional(),defaults: untrustedContentPolicySchema.optional(),sources: z.object(Object.fromEntries(UNTRUSTED_CONTENT_SOURCES.map(source => [source, untrustedContentPolicySchema.optional()]))).strict().optional(),}).strict();+// Narrow management writes preserve screening and provider settings owned by other panels.+export const jevPolicyPatchSchema = z.object({+ scopeAdherenceEnabled: z.boolean().optional(),+ sources: z.object(Object.fromEntries(['github-issue', 'email', 'stacker-news'].map(source => [+ source, untrustedContentPolicySchema.pick({ jevMode: true, jevMinMargin: true }).optional(),+ ]))).strict().optional(),+}).strict();+/** Invalid persisted policies block processing instead of silently losing a pin. */export function resolveUntrustedContentPolicy(settings, source, override = {}) {if (!UNTRUSTED_CONTENT_SOURCES.includes(source)) return null;diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 4ca4ae74a1..891acc2307 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -9,6 +9,8 @@*/import os from 'os'+import { jevPolicyPatchSchema, resolveUntrustedContentPolicy } from '../lib/untrustedContent.js'+import { readSettingsStrict, updateSettingsWith } from '../services/settings.js'import { Router } from 'express'import { asyncHandler, ServerError } from '../lib/errorHandler.js'import {@@ -283,6 +285,37 @@ router.get('/jev/decisions', asyncHandler(async (_req, res) => {res.json(await readJevDecisionStats())}))+// Resolve inheritance on the server, and expose only the scorer's own settings.+const presentJevPolicy = (settings) => ({+ scopeAdherenceEnabled: settings.untrustedContent?.scopeAdherenceEnabled !== false,+ sources: Object.fromEntries(['github-issue', 'email', 'stacker-news'].map(source => {+ const policy = resolveUntrustedContentPolicy(settings.untrustedContent, source)+ return [source, policy ? { jevMode: policy.jevMode, jevMinMargin: policy.jevMinMargin } : null]+ })),+})++router.get('/jev/policy', asyncHandler(async (_req, res) => {+ const state = await readSettingsStrict()+ if (state.corrupt) throw new ServerError('Scorer settings could not be read.', { status: 503 })+ res.json(presentJevPolicy(state.settings))+}))++router.put('/jev/policy', asyncHandler(async (req, res) => {+ const patch = validateRequest(jevPolicyPatchSchema, req.body)+ const updated = await updateSettingsWith(current => {+ const policy = current.untrustedContent || {}+ const sources = { ...policy.sources }+ for (const [source, fields] of Object.entries(patch.sources || {})) {+ sources[source] = { ...sources[source], ...fields }+ }+ return { ...current, untrustedContent: { ...policy,+ ...(patch.scopeAdherenceEnabled === undefined ? {} : { scopeAdherenceEnabled: patch.scopeAdherenceEnabled }),+ sources,+ } }+ }, { actor: 'user' })+ res.json(presentJevPolicy(updated))+}))+router.post('/jev/install', asyncHandler(async (req, res) => {const emit = emitter(req)const result = await installJev({diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex 939541cb44..5ab1a9d445 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -11,7 +11,7 @@ import { startSweep, getSweepStatus, cancelSweep } from '../services/localModelAimport { runOpenCodeAgentBenchmark } from '../services/localModelAgentBenchmark.js';import { getLoadedModels, unloadModel } from '../services/ollamaManager.js';import { getLoadedModels as getLoadedLmStudioModels, getLastLoadedModelsError as getLmStudioResidencyError } from '../services/lmStudioManager.js';-import { getSettings } from '../services/settings.js';+import { getSettings, readSettingsStrict, updateSettingsWith } from '../services/settings.js';import { localLlmCompareSchema, localLlmTestSchema } from '../lib/validation.js';import { errorEvents } from '../lib/errorHandler.js';@@ -129,6 +129,8 @@ vi.mock('../services/specDecodeModels.js', () => ({// so mock it (defaults to no backends disabled; the disabled-case test flips it).vi.mock('../services/settings.js', () => ({getSettings: vi.fn(async () => ({})),+ readSettingsStrict: vi.fn(),+ updateSettingsWith: vi.fn(),// localPersistentMindSetup → cos → cosTaskStore → codeReview listens on boot.settingsEvents: { on: vi.fn(), emit: vi.fn(), setMaxListeners: vi.fn() },}));@@ -915,3 +917,31 @@ describe('llama-server routes', () => {);});});+++describe('Jev integration policies', () => {+ it('resolves inherited modes and changes only scorer fields, preserving other policies', async () => {+ let persisted = { unrelated: true, untrustedContent: {+ defaults: { jevMode: 'prefer', classifierMode: 'required' },+ sources: { messages: { jevMode: 'only' }, email: { model: 'example-model' },+ 'github-issue': { providerId: 'example-provider', jevMinMargin: 0.4 } },+ } };+ readSettingsStrict.mockImplementation(async () => ({ corrupt: false, settings: persisted }));+ updateSettingsWith.mockImplementation(async mutate => (persisted = mutate(persisted)));+ const app = makeApp();+ const before = await request(app).get('/api/local-llm/jev/policy');+ expect(before.body.sources.email.jevMode).toBe('only');+ expect(before.body.sources['github-issue']).toEqual({ jevMode: 'prefer', jevMinMargin: 0.4 });+ const changed = await request(app).put('/api/local-llm/jev/policy').send({+ sources: { email: { jevMode: 'disabled' } }, scopeAdherenceEnabled: false,+ });+ expect(changed.status).toBe(200);+ expect(changed.body.scopeAdherenceEnabled).toBe(false);+ expect(changed.body.sources.email.jevMode).toBe('disabled');+ expect(persisted.untrustedContent.sources.email.model).toBe('example-model');+ expect(persisted.untrustedContent.sources['github-issue'].providerId).toBe('example-provider');+ expect(persisted.unrelated).toBe(true);+ const invalid = await request(app).put('/api/local-llm/jev/policy').send({ sources: { email: { classifierMode: 'optional' } } });+ expect(invalid.status).toBe(400);+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex cfb3c36742..e1bd8deb63 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -47,7 +47,7 @@ const eidoverseRepoSchema = z.object({// the bounds describe lives.const decorateBounds = (settings) => ({...settings,- untrustedContent: { defaults: { ...DEFAULT_UNTRUSTED_CONTENT_POLICY, ...settings.untrustedContent?.defaults }, sources: settings.untrustedContent?.sources || {} },+ untrustedContent: { scopeAdherenceEnabled: settings.untrustedContent?.scopeAdherenceEnabled !== false, defaults: { ...DEFAULT_UNTRUSTED_CONTENT_POLICY, ...settings.untrustedContent?.defaults }, sources: settings.untrustedContent?.sources || {} },imageGen: {...(settings.imageGen || {}),codex: {diff --git a/server/services/jevCorpusBuilder.test.js b/server/services/jevCorpusBuilder.test.jsindex 145de8934d..a33979eae0 100644--- a/server/services/jevCorpusBuilder.test.js+++ b/server/services/jevCorpusBuilder.test.js@@ -67,8 +67,8 @@ beforeEach(async () => {});describe('buildScopeAdherenceCorpus', () => {- it('builds a split corpus and reports counts, never examples', async () => {- mockForge({ merged: changes(60), notPlanned: changes(60, 500) });+ it('builds a split corpus even when forge text names constructor, reporting counts only', async () => {+ mockForge({ merged: changes(60).map(row => ({ ...row, body: `${row.body} Fix constructor and __proto__ handling.` })), notPlanned: changes(60, 500) });const result = await buildScopeAdherenceCorpus({ repoPath });expect(result.ok).toBe(true);expect(result.trainSize).toBeGreaterThan(0);diff --git a/server/services/jevRouter.js b/server/services/jevRouter.jsindex a05ad1b4a7..852bae6641 100644--- a/server/services/jevRouter.js+++ b/server/services/jevRouter.js@@ -16,7 +16,7 @@import { join } from 'path';import { createCachedStore, PATHS } from '../lib/fileUtils.js';-import { getJevDecision, jevHypotheses, jevMinMarginFor, jevValueForHypothesis } from '../lib/jevDecisions.js';+import { JEV_DECISIONS, getJevDecision, jevHypotheses, jevMinMarginFor, jevValueForHypothesis } from '../lib/jevDecisions.js';const SHADOW_SCHEMA_VERSION = 1;const emptyShadow = () => ({ schemaVersion: SHADOW_SCHEMA_VERSION, decisions: {}, updatedAt: null });@@ -71,10 +71,12 @@ export async function isJevFeatureEnabled() {* Two independent gates, both of which must be open: the per-install feature* toggle (an operator saying this machine runs the scorer at all) and the* per-source `jevMode` (an operator saying this CHANNEL may be answered- * locally). `shadow` is not a mode an operator sets — it is what `off` means on+ * locally). `disabled` suppresses even shadow scoring. `shadow` is the+ * UI label for the legacy stored `off` value on* a machine where the feature is on, and it changes no behavior at all.*/export async function resolveJevMode(policy) {+ if (policy?.jevMode === 'disabled') return 'disabled';const configured = policy?.jevMode === 'prefer' || policy?.jevMode === 'only' ? policy.jevMode : 'off';if (!await isJevFeatureEnabled()) return 'disabled';return configured === 'off' ? 'shadow' : configured;@@ -187,6 +189,7 @@ export async function readJevDecisionStats() {const rate = (numerator, denominator) => (denominator > 0 ? numerator / denominator : null);return {updatedAt: stored?.updatedAt || null,+ registry: JEV_DECISIONS,decisions: Object.entries(decisions).filter(([id]) => getJevDecision(id)).map(([id, raw]) => {const counters = { ...emptyCounters(), ...raw };return {diff --git a/server/services/scopeAdherence.js b/server/services/scopeAdherence.jsindex 2d9b109068..166c9255b7 100644--- a/server/services/scopeAdherence.js+++ b/server/services/scopeAdherence.js@@ -136,6 +136,11 @@ export async function scoreAdherence({// (`server/lib/importScoping.test.js`).const { isJevFeatureEnabled, recordJevObservations, runJevDecision } = await import('./jevRouter.js');if (!await isJevFeatureEnabled()) return failure('scope-adherence-disabled');+ const { readSettingsStrict } = await import('./settings.js');+ const settingsState = await readSettingsStrict();+ if (settingsState.corrupt || settingsState.settings.untrustedContent?.scopeAdherenceEnabled === false) {+ return failure('scope-adherence-disabled');+ }// Normalized ONCE, here. The route's schema has already trimmed what it// validates, but this is also the entry point for a direct service caller.diff --git a/server/services/scopeAdherence.test.js b/server/services/scopeAdherence.test.jsindex 54780eb0f5..0f59fa37ad 100644--- a/server/services/scopeAdherence.test.js+++ b/server/services/scopeAdherence.test.js@@ -3,6 +3,7 @@ import { mkdtemp, mkdir, rm, writeFile, readFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';+vi.mock('./settings.js', () => ({ readSettingsStrict: vi.fn() }));vi.mock('./jevRouter.js', () => ({isJevFeatureEnabled: vi.fn(),runJevDecision: vi.fn(),@@ -10,6 +11,7 @@ vi.mock('./jevRouter.js', () => ({}));vi.mock('./untrustedContent.js', () => ({ screenUntrustedContent: vi.fn() }));+const { readSettingsStrict } = await import('./settings.js');const { isJevFeatureEnabled, runJevDecision, recordJevObservations } = await import('./jevRouter.js');const { screenUntrustedContent } = await import('./untrustedContent.js');const { scoreAdherence, loadClauseCorpus, resetClauseCorpusCache } = await import('./scopeAdherence.js');@@ -53,6 +55,7 @@ beforeEach(async () => {// queue would fire in the next test and score a change nobody asked about.vi.resetAllMocks();resetClauseCorpusCache();+ readSettingsStrict.mockResolvedValue({ corrupt: false, settings: {} });repoPath = await mkdtemp(join(tmpdir(), 'portos-scope-'));await writeFile(join(repoPath, 'PRD.md'), PRD);await writeFile(join(repoPath, 'GOALS.md'), GOALS);@@ -73,6 +76,13 @@ const score = (overrides = {}) => scoreAdherence({});describe('scoreAdherence', () => {+ it('does not screen or score when scope adherence alone is disabled', async () => {+ readSettingsStrict.mockResolvedValue({ corrupt: false, settings: { untrustedContent: { scopeAdherenceEnabled: false } } });+ expect(await score()).toEqual({ ok: false, code: 'scope-adherence-disabled' });+ expect(screenUntrustedContent).not.toHaveBeenCalled();+ expect(runJevDecision).not.toHaveBeenCalled();+ });+it('declines before touching the scorer when the jev feature is off', async () => {isJevFeatureEnabled.mockResolvedValue(false);expect(await score()).toEqual({ ok: false, code: 'scope-adherence-disabled' });diff --git a/server/services/untrustedContent.jev.test.js b/server/services/untrustedContent.jev.test.jsindex 0cd76fbb7f..fd6bcc41ce 100644--- a/server/services/untrustedContent.jev.test.js+++ b/server/services/untrustedContent.jev.test.js@@ -92,6 +92,18 @@ describe('jev rung of the untrusted-content ladder', () => {}));});+ it('disabled source uses chat without shadow scoring in both analysis paths', async () => {+ withPolicy({ jevMode: 'disabled' });+ expect(await runUntrustedContentAnalysis({ ...args, jev: jevPlan })).toMatchObject({ ok: true });+ const gate = await jevBatchGate({ content: args.content, source: args.source,+ items: [{ key: 'a', premise: 'x', decisionIds: ['issue-comment-reply'] }],+ });+ await gate.measure?.({ a: { 'issue-comment-reply': 'none' } });+ expect(gate.pending).toHaveLength(1);+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ expect(mocks.decide).not.toHaveBeenCalled();+ });+it('never consults the scorer for content phase 1 blocked', async () => {withPolicy({ jevMode: 'prefer' });mocks.scan.mockResolvedValue({ ok: true, safe: false, code: 'model-abuse-detected' });