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
feat: add decision classifiers workspace with Laya-MLX experiments
[._.]/ Adam Eivy5b6d444ca096
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 1fdf471807..366fb20954 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -394,6 +394,7 @@ export default function App() {its own tab. A literal segment outranks `models/:tab/:recordId`, soa bookmark on the old pill lands on the new page instead of LLMsrendering an unknown sub-view. */}+ <Route path="models/llms/jev" element={<Navigate to="/models/decision-classifiers/jev" replace />} /><Route path="models/llms/runtimes" element={<Navigate to="/models/llms-runtimes" replace />} />{/* Harnesses folded into the AI Providers harnesses view (/ai/harnesses);retires the duplicate /models/harnesses page while keeping bookmarks working. */}diff --git a/client/src/components/models/DecisionClassifiers.jsx b/client/src/components/models/DecisionClassifiers.jsxnew file mode 100644index 0000000000..7005cd0cfe--- /dev/null+++ b/client/src/components/models/DecisionClassifiers.jsx@@ -0,0 +1,33 @@+import { Navigate, useNavigate } from 'react-router';+import { Scale, FlaskConical } from 'lucide-react';+import TabPills from '../ui/TabPills';+import JevPanel from './JevPanel';+import LayaMlxPanel from './LayaMlxPanel';++// Selection is route-backed and stays discoverable while integrations are off.+export const CLASSIFIERS = [+ { id: 'jev', label: 'Jev', icon: Scale },+ { id: 'laya-mlx', label: 'Laya-MLX', icon: FlaskConical },+];++export default function DecisionClassifiers({ view }) {+ const navigate = useNavigate();+ if (!view) return <Navigate to="/models/decision-classifiers/jev" replace />;+ if (!CLASSIFIERS.some(item => item.id === view)) return (+ <div role="alert">Unknown decision classifier. <button type="button" className="text-port-accent underline"+ onClick={() => navigate('/models/decision-classifiers/jev')}>Open Jev</button></div>+ );+ return (+ <div className="space-y-4 min-w-0">+ <div>+ <h2 className="text-lg font-semibold text-white">Decision Classifiers</h2>+ <p className="text-sm text-gray-400">Manage local systems that choose between fixed answers. Selecting a system here does not change automated integrations.</p>+ </div>+ <TabPills tabs={CLASSIFIERS} activeTab={view} onChange={id => navigate(`/models/decision-classifiers/${id}`)}+ ariaLabel="Decision classifiers" controlsIdPrefix="decision-classifier" mobileCompact />+ <div role="tabpanel" id={`decision-classifier-${view}`} aria-labelledby={`tab-${view}`}>+ {view === 'jev' ? <JevPanel /> : <LayaMlxPanel />}+ </div>+ </div>+ );+}diff --git a/client/src/components/models/DecisionClassifiers.test.jsx b/client/src/components/models/DecisionClassifiers.test.jsxnew file mode 100644index 0000000000..27cd943420--- /dev/null+++ b/client/src/components/models/DecisionClassifiers.test.jsx@@ -0,0 +1,19 @@+import { expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter, Route, Routes, useParams } from 'react-router';+vi.mock('./JevPanel', () => ({ default: () => <div>Jev controls</div> }));+vi.mock('./LayaMlxPanel', () => ({ default: () => <div>Laya controls</div> }));+import DecisionClassifiers from './DecisionClassifiers';+const Page = () => <DecisionClassifiers view={useParams().view} />;+it('keeps classifier selection in the URL and mounts only the selected adapter', async () => {+ render(<MemoryRouter initialEntries={['/models/decision-classifiers']}><Routes>+ <Route path="/models/decision-classifiers/:view?" element={<Page />} />+ </Routes></MemoryRouter>);+ expect(await screen.findByText('Jev controls')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('tab', { name: 'Laya-MLX' }));+ expect(await screen.findByText('Laya controls')).toBeInTheDocument();+ expect(screen.queryByText('Jev controls')).not.toBeInTheDocument();+ const tab = screen.getByRole('tab', { name: 'Laya-MLX' });+ expect(tab).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByRole('tabpanel')).toHaveAttribute('id', tab.getAttribute('aria-controls'));+});diff --git a/client/src/components/models/LayaMlxPanel.jsx b/client/src/components/models/LayaMlxPanel.jsxnew file mode 100644index 0000000000..4bc5c29137--- /dev/null+++ b/client/src/components/models/LayaMlxPanel.jsx@@ -0,0 +1,118 @@+import { useCallback, useRef, useState } from 'react';+import { getLayaStatus, installLaya, scoreLaya, updateInstanceFeature } from '../../services/api';+import { publishInstanceFeatures, useInstanceFeatures } from '../../hooks/useInstanceFeatures';+import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { formatCount, formatPercent } from '../../utils/formatters';++const ERRORS = {+ 'laya-unsupported': 'Laya-MLX requires Apple Silicon and macOS 14 or newer. Jev remains available on other platforms.',+ 'laya-not-ready': 'Install or repair Laya-MLX before scoring.',+ 'laya-disabled': 'Enable Laya-MLX experiments before scoring.',+ 'laya-busy': 'A Laya operation is already running. Wait for it to finish.',+ 'laya-context-too-long': 'The input exceeds this model’s token budget. Shorten the premise, question or options; no truncated decision was returned.',+ 'laya-install-python-failed': 'Setup requires a native Apple Silicon Python 3.11+ and macOS 14+. Install a compatible Python, then retry.',+ 'laya-install-runtime-failed': 'Runtime setup failed. Check Python compatibility and internet access, then retry.',+ 'laya-install-model-failed': 'The pinned model download failed. Check free disk space and internet access, then retry.',+ 'laya-install-verify-failed': 'The installed runtime could not load the model. Repair the installation and check macOS/MLX compatibility.',+};+const errorLabel = code => Object.hasOwn(ERRORS, code) ? ERRORS[code] : 'Laya could not complete this request. Refresh status or repair the installation, then retry.';++export default function LayaMlxPanel() {+ const { features, error: featureError } = useInstanceFeatures();+ const feature = features?.find(item => item.id === 'laya-mlx');+ const statusGeneration = useRef(0);+ const [status, setStatus] = useState(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const [premise, setPremise] = useState('');+ const [instructions, setInstructions] = useState('Which option best describes this text?');+ const [optionsText, setOptionsText] = useState('');+ const [margin, setMargin] = useState('0.15');+ const [result, setResult] = useState(null);+ const load = useCallback(() => {+ const requested = ++statusGeneration.current;+ return getLayaStatus({ silent: true }).then(value => {+ if (statusGeneration.current === requested) setStatus(value);+ });+ }, []);+ const { error: statusError, refetch } = useAutoRefetch(load, 5000, { enabled: !busy });+ const options = optionsText.split('\n').map(value => value.trim()).filter(Boolean);+ const valid = premise.trim() && instructions.trim() && options.length >= 2 && options.length <= 12+ && new Set(options).size === options.length && options.every(option => option.length <= 200)+ && margin !== '' && Number(margin) >= 0 && Number(margin) <= 1;+ const run = (action) => {+ setBusy(true);+ setError('');+ return action().catch(() => setError('The request failed. Check the connection and retry.')).finally(() => setBusy(false));+ };+ const toggle = () => run(() => updateInstanceFeature('laya-mlx', !feature.enabled, { silent: true })+ .then(value => publishInstanceFeatures(value.features, { groups: value.groups })));+ const install = () => run(() => installLaya({ silent: true }).then(value => {+ if (!value.ok) setError(errorLabel(value.code));+ else {+ statusGeneration.current += 1;+ setStatus(previous => ({ ...previous, installing: true, installError: null }));+ }+ }));+ const score = () => run(() => {+ setResult(null);+ return scoreLaya({ premise, instructions, options, minMargin: Number(margin) }, { silent: true }).then(value => {+ if (!value.ok) setError(errorLabel(value.code));+ else setResult(value);+ });+ });+ const edit = setter => event => { setter(event.target.value); setResult(null); };++ return (+ <section className="space-y-4 min-w-0" aria-label="Laya-MLX experiments">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h3 className="font-semibold text-white">Laya-MLX multilingual <span className="text-xs text-port-warning">Experimental</span></h3>+ <p className="text-sm text-gray-400">322M parameters · native Apple Silicon · 1,024-token context including the question and options.</p>+ <p role="status" className="text-sm text-gray-300">Runtime: {statusError ? 'unavailable' : !status ? 'loading…' : !status.supported ? 'unsupported platform' : status.installing ? `installing (${status.stage || 'starting'})` : status.ready ? 'installed' : 'not installed'}.+ {' '}Experiments: {featureError || !feature ? 'unknown' : feature.enabled ? 'enabled' : 'disabled'}.</p>+ </div>+ <button type="button" onClick={toggle} disabled={busy || !feature || !!featureError || !status?.supported}+ className="px-3 py-2 rounded border border-port-border text-port-accent disabled:opacity-50">+ {feature?.enabled ? 'Disable experiments' : 'Enable experiments'}+ </button>+ </div>+ <p className="text-xs text-gray-400">Manual experiments only. Jev integrations, source policies, training and agreement counters remain independent. Disabling prevents new experiments; an in-flight request can finish. Models unload when each experiment finishes.</p>+ {(error || statusError || status?.installError) && <p role="alert" className="text-sm text-port-warning">{error || (statusError ? 'Could not refresh runtime status.' : errorLabel(status.installError))}</p>}+ {status && !status.supported && <p className="text-sm text-port-warning">{ERRORS['laya-unsupported']}</p>}+ <div className="flex flex-wrap items-center gap-3">+ <button type="button" onClick={install} disabled={busy || !status?.supported || status.installing || status.scoring || !!statusError}+ className="px-3 py-2 rounded border border-port-border text-port-accent disabled:opacity-50">+ {status?.installing ? 'Installing…' : status?.ready ? 'Repair Laya-MLX' : 'Install Laya-MLX'}+ </button>+ <button type="button" onClick={refetch} className="text-sm text-port-accent underline">Refresh status</button>+ <a href="https://github.com/mizorewww/laya-mlx" target="_blank" rel="noreferrer" className="text-sm text-port-accent underline">Project and benchmarks</a>+ </div>+ <p className="text-xs text-gray-400">Install downloads a pinned runtime and roughly 650 MB of model weights into a dedicated environment, then verifies model loading. Allow additional disk space for dependencies. Requires native Python 3.11+ and macOS 14+. Nothing downloads when this page opens.</p>+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">+ <div className="space-y-3 min-w-0">+ <div><label htmlFor="laya-question" className="block text-sm text-gray-300 mb-1">Question</label>+ <input id="laya-question" value={instructions} maxLength={1000} onChange={edit(setInstructions)} disabled={busy} className="w-full bg-port-bg border border-port-border rounded p-2" /></div>+ <div><label htmlFor="laya-premise" className="block text-sm text-gray-300 mb-1">Premise</label>+ <textarea id="laya-premise" value={premise} maxLength={12000} rows={5} onChange={edit(setPremise)} disabled={busy} className="w-full bg-port-bg border border-port-border rounded p-2" /></div>+ <div><label htmlFor="laya-options" className="block text-sm text-gray-300 mb-1">Options (2–12 unique answers, one per line)</label>+ <textarea id="laya-options" value={optionsText} rows={4} onChange={edit(setOptionsText)} disabled={busy} className="w-full bg-port-bg border border-port-border rounded p-2" /></div>+ <div><label htmlFor="laya-margin" className="block text-sm text-gray-300 mb-1">Minimum margin (0–1)</label>+ <input id="laya-margin" type="number" min="0" max="1" step="0.01" value={margin} onChange={edit(setMargin)} disabled={busy} className="w-28 bg-port-bg border border-port-border rounded p-2" /></div>+ <button type="button" onClick={score} disabled={busy || !valid || !status?.ready || status.installing || status.scoring || !!statusError || !!featureError || !feature?.enabled}+ className="px-3 py-2 rounded bg-port-accent/20 text-port-accent disabled:opacity-50">{busy ? 'Working…' : 'Run experiment'}</button>+ </div>+ <div className="space-y-3 min-w-0 rounded border border-port-border p-4" role="status">+ <h4 className="font-medium text-white">Experiment result</h4>+ {!result ? <p className="text-sm text-gray-400">Enter a short premise and options, then run an experiment. Inputs and results are not saved.</p> : <>+ <p className="text-sm break-words">{result.abstained ? 'Abstained — options are too close to separate.' : `Choice: ${result.choice}`}</p>+ <p className="text-xs text-gray-400">Margin: {result.margin.toFixed(4)} · entropy confidence: {formatPercent(result.entropyConfidence * 100)}</p>+ <p className="text-xs text-gray-400">Total time: {formatCount(result.elapsedMs)} ms, including Python startup and model loading.</p>+ <ul className="space-y-2 text-sm">{result.scores.map(row => <li key={row.option} className="flex justify-between gap-4"><span className="break-words min-w-0">{row.option}</span><span>{formatPercent(row.probability * 100)}</span></li>)}</ul>+ </>}+ <p className="text-xs text-gray-500">Choice probabilities and entropy confidence are not Jev entailment scores. The margin is an experimental abstention threshold, not a calibrated accuracy guarantee. These timings are not comparable to upstream’s warm inference benchmarks.</p>+ </div>+ </div>+ </section>+ );+}diff --git a/client/src/components/models/LayaMlxPanel.test.jsx b/client/src/components/models/LayaMlxPanel.test.jsxnew file mode 100644index 0000000000..795e4c14ca--- /dev/null+++ b/client/src/components/models/LayaMlxPanel.test.jsx@@ -0,0 +1,41 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+const mocks = vi.hoisted(() => ({ status: vi.fn(), install: vi.fn(), score: vi.fn(), toggle: vi.fn(), publish: vi.fn(), enabled: true }));+vi.mock('../../services/api', () => ({ getLayaStatus: mocks.status, installLaya: mocks.install, scoreLaya: mocks.score, updateInstanceFeature: mocks.toggle }));+vi.mock('../../hooks/useInstanceFeatures', () => ({ publishInstanceFeatures: mocks.publish, useInstanceFeatures: () => ({ features: [{ id: 'laya-mlx', enabled: mocks.enabled }] }) }));+import LayaMlxPanel from './LayaMlxPanel';+beforeEach(() => {+ vi.clearAllMocks(); mocks.enabled = true;+ mocks.status.mockResolvedValue({ supported: true, ready: true });+ mocks.score.mockResolvedValue({ ok: true, choice: 'billing', margin: 0.8, entropyConfidence: 0.53, elapsedMs: 1200, scores: [{ option: 'billing', probability: 0.9 }, { option: 'sales', probability: 0.1 }] });+});+it('scores only on explicit action and clears stale results when input changes', async () => {+ render(<LayaMlxPanel />);+ await screen.findByText(/Runtime: installed/);+ expect(mocks.score).not.toHaveBeenCalled(); expect(mocks.install).not.toHaveBeenCalled();+ fireEvent.change(screen.getByLabelText('Premise'), { target: { value: 'Duplicate invoice' } });+ fireEvent.change(screen.getByLabelText(/Options/), { target: { value: 'billing\nsales' } });+ fireEvent.click(screen.getByRole('button', { name: 'Run experiment' }));+ expect(await screen.findByText('Choice: billing')).toBeInTheDocument();+ expect(mocks.score).toHaveBeenCalledWith(expect.objectContaining({ premise: 'Duplicate invoice', options: ['billing', 'sales'] }), { silent: true });+ fireEvent.change(screen.getByLabelText('Premise'), { target: { value: 'Another input' } });+ expect(screen.queryByText('Choice: billing')).not.toBeInTheDocument();+});+it('keeps setup discoverable while disabled and publishes confirmed enablement', async () => {+ mocks.enabled = false;+ mocks.toggle.mockResolvedValue({ features: [{ id: 'laya-mlx', enabled: true }], groups: [] });+ render(<LayaMlxPanel />);+ await screen.findByText(/Runtime: installed/);+ expect(screen.getByRole('button', { name: 'Run experiment' })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: 'Enable experiments' }));+ await waitFor(() => expect(mocks.publish).toHaveBeenCalled());+ expect(mocks.toggle).toHaveBeenCalledWith('laya-mlx', true, { silent: true });+});+it('explains unsupported hardware without offering installation or scoring', async () => {+ mocks.enabled = false;+ mocks.status.mockResolvedValue({ supported: false, ready: false });+ render(<LayaMlxPanel />);+ await screen.findByText(/Jev remains available on other platforms/);+ expect(screen.getByRole('button', { name: 'Install Laya-MLX' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Enable experiments' })).toBeDisabled();+});diff --git a/client/src/components/models/UntrustedContentPolicyPanel.jsx b/client/src/components/models/UntrustedContentPolicyPanel.jsxindex b5fd33d829..78d82ac926 100644--- a/client/src/components/models/UntrustedContentPolicyPanel.jsx+++ b/client/src/components/models/UntrustedContentPolicyPanel.jsx@@ -131,7 +131,7 @@ export default function UntrustedContentPolicyPanel() {</div></div>{effectiveValue('jevMode') === 'only' && <p className="text-xs text-port-warning">Only skips an item the scorer cannot separate instead of calling a provider. Skipped items are reported, never treated as “no action needed”.</p>}- <p className="text-xs text-gray-500">The margin raises the bar for every decision on this source; it cannot lower a decision’s own floor, so a destructive recommendation keeps deferring to the provider. <a href="/models/llms/jev" className="text-port-accent hover:underline">Install and measure jev</a></p>+ <p className="text-xs text-gray-500">The margin raises the bar for every decision on this source; it cannot lower a decision’s own floor, so a destructive recommendation keeps deferring to the provider. <a href="/models/decision-classifiers/jev" className="text-port-accent hover:underline">Install and measure jev</a></p></div><div className="border-t border-port-border pt-4 space-y-3"><h4 className="text-sm font-medium text-white">Analysis provider</h4>diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex f09b6be323..e7c9a52632 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,15 +1,13 @@import { useNavigate } from 'react-router';-import { Download, Scale, ShieldCheck } from 'lucide-react';+import { Download, ShieldCheck } from 'lucide-react';import TabPills from '../ui/TabPills.jsx';import { useInstanceFeatures } from '../../hooks/useInstanceFeatures.js';-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@@ -20,7 +18,6 @@ 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@@ -50,13 +47,10 @@ 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.'- : 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.'}+ : '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.jsxindex 79f9ba1543..ca0bd208b3 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -74,7 +74,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', 'jev']);+ expect(screen.getAllByRole('tab').map((t) => t.textContent)).toEqual(['Model Library', 'Abuse Guard']);});it('navigates between the focused panels with a shareable URL', () => {@@ -84,22 +84,6 @@ 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('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', 'jev']);- });-- it('still mounts jev from a direct URL while the feature is disabled', () => {- disabledFeatures.add('jev');- renderTab('jev');-- expect(screen.getByTestId('jev-view')).toBeInTheDocument();- expect(screen.getAllByRole('tab').map((t) => t.textContent)).toEqual(['Model Library', 'Abuse Guard', 'jev']);});it('describes the selected panel under the pills', () => {diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.jsindex 8171422f5b..5816dd2a2c 100644--- a/client/src/lib/navPresentation.js+++ b/client/src/lib/navPresentation.js@@ -227,6 +227,7 @@ export const NAV_PRESENTATION = {'/meatspace/overview': { icon: Activity },'/meatspace/settings': { icon: Settings },'/models/3d': { icon: Boxes },+ '/models/decision-classifiers': { icon: Scale },'/models/embeddings': { icon: Braces },'/models/llms': { icon: Cpu },'/models/llms-runtimes': { icon: Server },diff --git a/client/src/pages/Models.jsx b/client/src/pages/Models.jsxindex 4604503cc6..932ec502c6 100644--- a/client/src/pages/Models.jsx+++ b/client/src/pages/Models.jsx@@ -31,6 +31,7 @@ const MediaModels = lazyWithReload(() => import('./MediaModels'));** - **3D** — image-to-3D runtime install/repair (TRELLIS.2, Pixal3D).* - **Code Reviewers** — the review-loop chain and its model/effort pins.+ * - **Decision Classifiers** — Jev integrations and local Laya-MLX experiments.* - **Embeddings** — the embedding model backing pgvector search.* - **LLMs** — the model-library and abuse-guard sub-routes (the weights).* - **Runtimes** — the local model servers, their lifecycle and downloads.@@ -56,6 +57,7 @@ const TAB_CONTENT = {comparison: lazyWithReload(() => import('../components/models/ModelComparison')),'3d': Image3dRuntimes,'code-reviewers': CodeReviewersTab,+ 'decision-classifiers': lazyWithReload(() => import('../components/models/DecisionClassifiers')),embeddings: EmbeddingsTab,llms: LocalLlmTab,'llms-runtimes': LocalLlmRuntimesView,@@ -83,6 +85,7 @@ const TAB_DETAIL = {export default function Models() {const { tab, recordId } = useParams();+ if (tab === 'llms' && recordId === 'jev') return <Navigate to="/models/decision-classifiers/jev" replace />;// An unknown slug lands on LLMs rather than rendering a blank page, matching// the section's default destination in App and the primary navigation.//diff --git a/client/src/pages/Models.test.jsx b/client/src/pages/Models.test.jsxindex 2df88f9f21..d8774c0654 100644--- a/client/src/pages/Models.test.jsx+++ b/client/src/pages/Models.test.jsx@@ -23,6 +23,7 @@ vi.mock('../components/models/ModelStatusTab', () => ({ default: () => <div>statvi.mock('../components/models/SubscriptionsTab', () => ({ default: () => <div>subscriptions panel</div> }));vi.mock('../components/settings/CodeReviewersTab', () => ({ default: () => <div>code reviewers panel</div> }));vi.mock('../components/models/ModelComparison', () => ({ default: () => <div>comparison panel</div> }));+vi.mock('../components/models/DecisionClassifiers', () => ({ default: ({ view }) => <div>classifiers panel {view}</div> }));vi.mock('./Loras', () => ({ default: () => <div>loras panel</div> }));vi.mock('./LoraTraining', () => ({ default: () => <div>training panel</div> }));vi.mock('./MediaModels', () => ({ default: () => <div>media models panel</div> }));@@ -38,6 +39,7 @@ const PANEL_MARKER = {comparison: 'comparison panel','3d': '3d runtimes panel','code-reviewers': 'code reviewers panel',+ 'decision-classifiers': 'classifiers panel',embeddings: 'embeddings panel',llms: 'llms panel','llms-runtimes': 'runtimes panel',@@ -175,3 +177,9 @@ describe('Models — tab drill-downs', () => {expect(await screen.findByText('loras panel')).toBeInTheDocument();});});++it('redirects the old Jev URL into Decision Classifiers', async () => {+ renderAt('/models/llms/jev');+ expect(await screen.findByText('classifiers panel jev')).toBeInTheDocument();+ expect(screen.getByRole('tab', { name: 'Decision Classifiers' })).toHaveAttribute('aria-selected', 'true');+});diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 6e63ec300d..cc3451daa2 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -445,3 +445,7 @@ export const applyLocalPersistentMindSetup = (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 });++export const getLayaStatus = (options) => request('/local-llm/laya-mlx/status', options);+export const installLaya = (options) => request('/local-llm/laya-mlx/install', { method: 'POST', body: '{}', ...options });+export const scoreLaya = (body, options) => request('/local-llm/laya-mlx/score', { method: 'POST', body: JSON.stringify(body), ...options });diff --git a/docs/features/decision-classifiers.md b/docs/features/decision-classifiers.mdnew file mode 100644index 0000000000..5f87f4acd8--- /dev/null+++ b/docs/features/decision-classifiers.md@@ -0,0 +1,66 @@+# Decision classifiers++**Models → Decision Classifiers** groups closed-set decision systems separately+from chat models. Each classifier has a shareable URL and remains discoverable+when disabled. The old `/models/llms/jev` URL redirects to+`/models/decision-classifiers/jev`; its command-palette identity remains stable.++## Jev++Jev retains installation, manual scoring, trained-head adoption, integration+switches, per-source policies and agreement counters. Its stored feature ID,+API endpoints and defaults are unchanged. Disabling Jev integrations does not+disable its explicit manual experiments. No migration is necessary.++## Laya-MLX++`/models/decision-classifiers/laya-mlx` offers native Apple Silicon experiments+using the 322M multilingual checkpoint. Windows and Intel hosts can discover it+but cannot install or run it; Jev remains a separate choice.++1. Install a native Apple Silicon Python 3.11+ on macOS 14+.+2. Click **Install Laya-MLX** to create a dedicated environment, install the+ pinned runtime, download approximately 650 MB of weights, and verify loading.+ Additional disk space is needed for runtime dependencies.+3. Enable experiments, supply a question, premise and 2–12 distinct options,+ then click **Run experiment**. Installation and enablement are separate.++The runtime Git revision and multilingual weight revision are pinned in+`server/lib/layaMlx.js`. Setup downloads only on an explicit action. Status+reads local installation metadata and file presence; it never loads a model.+Scoring runs offline, passes the premise through stdin, and releases the process+and model after each request. Only one experiment or installation can run at a+time. A request has a two-minute timeout and disconnect cancellation. Disable+blocks subsequent experiments; it does not cancel one already in flight.++The checkpoint has a 1,024-token combined budget, with a smaller question/options+budget. PortOS rejects over-budget input and option labels that upstream would+truncate, rather than classifying a partial premise. The UI reports normalized+choice probabilities, entropy confidence, winner/runner-up margin and total+elapsed time including process/model startup. These are not Jev entailment+probabilities or upstream warm-inference latency measurements. Ties always+abstain, including at a zero margin floor.++Laya is currently a **manual experiment adapter**. Selecting or enabling it does+not replace Jev for triage, issue replies, scope checks or any other automation.+Its thresholds need task-specific evaluation before production adoption; no+speed or accuracy superiority is claimed by this integration. Additional+classifiers can add their own panel/adapter and declared route without changing+Jev's persisted policy format or pretending all scoring semantics are identical.++## Storage and privacy++The enable flag uses the existing machine-local instance-feature store. Runtime,+model and installation marker live under `data/python/laya-mlx/`, in the existing+rebuildable Python-runtime asset tree; they are not native app records or new+JSON collections. No new database schema, seed, migration or federation payload+is introduced. The anchored `/python/laya-mlx/` backup exclusion covers this rebuildable+installation. Inputs/results are memory-only and never enter logs, counters,+files, issue reports or federation. Errors returned by the service are bounded+codes, not subprocess output or paths.++## Sources++- [Laya-MLX runtime and requirements](https://github.com/mizorewww/laya-mlx/tree/fc1df62828a3fedf4d8229fdac1cbd85f1cdf337)+- [Pinned publication provenance](https://github.com/mizorewww/laya-mlx/blob/fc1df62828a3fedf4d8229fdac1cbd85f1cdf337/benchmarks/results/hub-publication.json)+- [Multilingual checkpoint](https://huggingface.co/aac6fef/laya-multilingual-mlx/tree/ba40c87fcb357f1643d04d71323af9cdc3b9e591)diff --git a/scripts/run_laya_mlx.py b/scripts/run_laya_mlx.pynew file mode 100644index 0000000000..ebbf38aef6--- /dev/null+++ b/scripts/run_laya_mlx.py@@ -0,0 +1,48 @@+"""PortOS's narrow Laya-MLX bridge. Scoring is offline; only setup downloads.++The upstream package owns inference and formatting. No upstream code is vendored.+Each experiment releases its process/model when complete, including on timeout.+"""+import contextlib+import json+from pathlib import Path+import sys+++def score(agent, request):+ from laya_mlx.common import build_prefix, render_options, serialize_state++ question = {"type": "choice", "instructions": request["instructions"], "criteria": request["options"]}+ internal = agent._to_internal(question)+ # Upstream silently truncates state and question prefixes to its short token+ # budget. Reject instead: a decision about part of a premise is misleading.+ for option in render_options(internal):+ option_ids = agent.tok(" " + option.replace(agent.tok.mask_token, " "), add_special_tokens=False)["input_ids"]+ if len(option_ids) > 48:+ return {"code": "laya-context-too-long"}+ prefix, _ = build_prefix(agent.tok, internal, 1_000_000)+ state_ids = agent.tok(serialize_state(request["premise"]).replace(agent.tok.mask_token, " "),+ add_special_tokens=False)["input_ids"]+ if len(prefix) > agent.cfg.get("head_max_len", 192) or len(prefix) + len(state_ids) + 1 > agent.cfg.get("max_len", 512):+ return {"code": "laya-context-too-long"}+ return agent.predict(request["premise"], {"decision": question})+++def main():+ mode, model_dir = sys.argv[1:3]+ if mode == "download":+ from huggingface_hub import snapshot_download+ snapshot_download(repo_id=sys.argv[3], revision=sys.argv[4], local_dir=model_dir)+ return+ # Refuse a missing local path before load can interpret it as a Hub repo ID.+ if not Path(model_dir).is_dir():+ raise ValueError("Local model is missing")+ import laya_mlx+ with contextlib.redirect_stdout(sys.stderr):+ agent = laya_mlx.load(model_dir, dtype="float16")+ result = score(agent, json.load(sys.stdin)) if mode == "score" else {"ok": True}+ print(json.dumps(result, allow_nan=False))+++if __name__ == "__main__":+ main()diff --git a/scripts/run_laya_mlx.test.js b/scripts/run_laya_mlx.test.jsnew file mode 100644index 0000000000..c7aec5dd26--- /dev/null+++ b/scripts/run_laya_mlx.test.js@@ -0,0 +1,36 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';+const python = resolveTestPython();+const script = fileURLToPath(new URL('./run_laya_mlx.py', import.meta.url));++// The regression is silent upstream truncation: a long option, question or+// premise must never reach predict as if it were the complete user input.+it.skipIf(!python)('rejects every truncation boundary before inference, while allowing a fitting request', () => {+ const result = execFileSync(python, ['-c', `+import json, runpy, sys+from types import SimpleNamespace+common = SimpleNamespace(+ build_prefix=lambda tok, q, budget: (list(range(len(q['instructions']) + 4)), []),+ render_options=lambda q: q['criteria'],+ serialize_state=lambda state: state,+)+sys.modules['laya_mlx.common'] = common+score = runpy.run_path(sys.argv[1])['score']+class Tokenizer:+ mask_token = '[MASK]'+ def __call__(self, text, **kwargs):+ return {'input_ids': list(range(len(text)))}+calls = []+agent = SimpleNamespace(tok=Tokenizer(), cfg={'max_len': 100, 'head_max_len': 40},+ _to_internal=lambda q: q, predict=lambda state, q: calls.append(state) or {'ok': True})+request = {'premise': 'A short state', 'instructions': 'Choose', 'options': ['one', 'two']}+assert score(agent, request) == {'ok': True}+for patch in [{'premise': 's' * 100}, {'instructions': 'q' * 50}, {'options': ['x' * 49, 'two']}]:+ assert score(agent, {**request, **patch}) == {'code': 'laya-context-too-long'}+assert calls == ['A short state'], calls+print('ok')+`, script], { encoding: 'utf8' });+ expect(result.trim()).toBe('ok');+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 463669bc37..e6b2768951 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -717,3 +717,4 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `deckValidation.js` | Zod schemas + limits for the `/api/decks` routes (create/update deck, card patch, sample analysis, prompt generation, render). || `kilo.js` | Kilo Code command identity (`kilo`/`kilocode`), `run` headless argv, `--auto` approval posture, and TUI arguments. || `openchamber.js` | OpenChamber control-CLI identity, `session create` headless argv, `provider/model` gate, and `--dir`/`--prompt` spawn-time delivery. |+| `layaMlx.js` | Pinned Laya-MLX experiment model, request validation and probability normalization; entropy confidence stays distinct from entailment. |diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 09fdcb65a5..9f84bfcc19 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -38,6 +38,8 @@ const reaches = (entry, target) => staticImportClosure(abs(entry)).files.has(abs// Each row: the entry that was narrowed, the module it must no longerconst NARROWED = [+ ['services/backup.js', 'services/socket.js',+ 'loads socket/auth listeners only when a failed scheduled DB dump needs the global socket'],['services/eidoverseWorld.js', 'services/eidoverseWorldSources.js','uses pure Eidoverse signals without eagerly loading source readers'],['services/eidoverseTravel.js', 'services/eidoverseWorldSources.js',diff --git a/server/lib/index.js b/server/lib/index.jsindex 5dde8ed2ca..9b961d7489 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -699,3 +699,5 @@ export * from './deckValidation.js';export * from './ecosystemProcessPorts.js';export * from './kilo.js';export * from './openchamber.js';++export * from './layaMlx.js';diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsindex e2b677898f..828110a884 100644--- a/server/lib/instanceFeatureRegistry.js+++ b/server/lib/instanceFeatureRegistry.js@@ -70,6 +70,12 @@ export const INSTANCE_FEATURES = Object.freeze([// Gates scoring integrations, not discovery: the management page stays visible.defaultEnabled: false,}),+ Object.freeze({+ id: 'laya-mlx',+ label: 'Laya-MLX experiments',+ description: 'Enable explicit local decision-classifier experiments on Apple Silicon. Does not change automated Jev integrations.',+ defaultEnabled: false,+ }),Object.freeze({id: 'gsd',label: 'GSD',diff --git a/server/lib/layaMlx.js b/server/lib/layaMlx.jsnew file mode 100644index 0000000000..5319c9861d--- /dev/null+++ b/server/lib/layaMlx.js@@ -0,0 +1,39 @@+import { z } from 'zod';++// Runtime and weights are independently pinned. Never download during scoring.+export const LAYA_MLX = Object.freeze({+ id: 'laya-mlx',+ name: 'Laya-MLX multilingual',+ repository: 'aac6fef/laya-multilingual-mlx',+ revision: 'ba40c87fcb357f1643d04d71323af9cdc3b9e591',+ runtimeRevision: 'fc1df62828a3fedf4d8229fdac1cbd85f1cdf337',+ contextTokens: 1024,+ parameters: '322M',+});++export const layaScoreRequestSchema = z.object({+ premise: z.string().trim().min(1).max(12000),+ instructions: z.string().trim().min(1).max(1000),+ options: z.array(z.string().trim().min(1).max(200)).min(2).max(12)+ .refine(values => new Set(values).size === values.length, 'Options must be unique'),+ minMargin: z.number().min(0).max(1).default(0.15),+}).strict();++// Laya's entropy-based confidence is NOT Jev's entailment probability. Preserve+// its meaning and independently compute an experimental winner/runner-up margin.+export function normalizeLayaResult(raw, options, minMargin) {+ const answer = raw?.answers?.decision;+ const probabilities = answer?.probabilities;+ if (answer?.type !== 'choice' || !probabilities || typeof probabilities !== 'object'+ || Object.keys(probabilities).length !== options.length+ || !Number.isFinite(answer.confidence) || answer.confidence < 0 || answer.confidence > 1) return null;+ const scores = options.map(option => ({ option, probability: Object.hasOwn(probabilities, option) ? probabilities[option] : null }));+ if (scores.some(row => !Number.isFinite(row.probability) || row.probability < 0 || row.probability > 1)) return null;+ if (Math.abs(scores.reduce((sum, row) => sum + row.probability, 0) - 1) > 0.002) return null;+ const ranked = [...scores].sort((a, b) => b.probability - a.probability);+ if (answer.choice !== ranked[0].option) return null;+ const margin = ranked[0].probability - ranked[1].probability;+ const abstained = margin <= 0 || margin < minMargin;+ return { ok: true, classifier: LAYA_MLX.id, choice: abstained ? null : answer.choice,+ abstained, margin, entropyConfidence: answer.confidence, scores };+}diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 1912e64e58..2e03219c10 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -324,7 +324,9 @@ 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', aliases: ['jev', 'openjev', 'entailment', 'nli', 'decision-scorer'], keywords: ['entailment', 'nli', 'closed set', 'abstain', 'margin', 'scorer', 'decision', 'install jev'] },+ { id: 'nav.models.decision-classifiers', path: '/models/decision-classifiers', label: 'Decision Classifiers', section: 'Models', tabId: 'decision-classifiers', aliases: ['decision-classifiers', 'classifiers'], keywords: ['jev', 'laya', 'mlx', 'decision systems', 'experiments'] },+ { id: 'nav.models.laya-mlx', path: '/models/decision-classifiers/laya-mlx', label: 'Laya-MLX', section: 'Models', aliases: ['laya', 'laya-mlx', 'layla'], keywords: ['classifier', 'apple silicon', 'typed decisions'] },+ { id: 'nav.models.llms.jev', path: '/models/decision-classifiers/jev', previousPaths: ['/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/navManifest.test.js b/server/lib/navManifest.test.jsindex 1f1abd6deb..a774137c49 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -37,6 +37,7 @@ const TABBED_PAGES = [{ prefix: '/settings', section: 'Settings', file: 'client/src/components/settings/SettingsTabsHeader.jsx', kind: 'section', constName: 'TABS' },{ prefix: '/models', section: 'Models', file: 'client/src/components/models/ModelsTabsHeader.jsx', kind: 'section', constName: 'TABS',nestedIdSources: [+ { parent: 'decision-classifiers', file: 'client/src/components/models/DecisionClassifiers.jsx', constName: 'CLASSIFIERS' },{ parent: 'llms', file: 'client/src/components/settings/LocalLlmTab.jsx', constName: 'LLM_NAV_SUBROUTES' },] },// POST's morse tab has routed `:mode` sub-pages (/post/morse/copy|send) and thediff --git a/server/lib/scopeAdherenceReasons.js b/server/lib/scopeAdherenceReasons.jsindex d5ec91da0d..cf003f668a 100644--- a/server/lib/scopeAdherenceReasons.js+++ b/server/lib/scopeAdherenceReasons.js@@ -42,23 +42,23 @@ export const SCOPE_ADHERENCE_REASONS = Object.freeze({'scope-adherence-corpus-missing': 'This repository has no PRD.md or GOALS.md to score against.','scope-adherence-corpus-unreadable': 'This repository\'s PRD.md / GOALS.md could not be read.','scope-adherence-no-clause': 'No stated goal in this repository is close enough to score against.',- 'jev-not-installed': 'The local scorer is not installed yet — see Models > LLMs > jev.',- 'jev-start-failed': 'The local scorer could not start. Check Models > LLMs > jev.',+ 'jev-not-installed': 'The local scorer is not installed yet — see Models > Decision Classifiers > Jev.',+ 'jev-start-failed': 'The local scorer could not start. Check Models > Decision Classifiers > Jev.','jev-timeout': 'The local scorer did not answer in time.','jev-request-invalid': 'The local scorer rejected the request for this change.','jev-response-invalid': 'The local scorer returned an answer PortOS could not read.','jev-premise-too-large': 'This change is too large for the local scorer to read at once.',// A trained project head the scorer could not apply. Each one reads as "no- // advisory" and points at Models > LLMs > jev, where the head can be+ // advisory" and points at Models > Decision Classifiers > Jev, where the head can be// discarded — which returns the decision to the stock scorer immediately.// Never answered by silently falling back: the operator adopted this head on// three measured numbers, and quietly substituting a different classifier// would make that measurement describe something other than what ran.- 'jev-head-not-found': 'The adopted project head is missing — discard it in Models > LLMs > jev to go back to the stock scorer.',- 'jev-head-invalid': 'The adopted project head could not be read — discard it in Models > LLMs > jev.',- 'jev-head-too-large': 'The adopted project head is larger than PortOS will load — discard it in Models > LLMs > jev.',- 'jev-head-unreadable': 'The adopted project head\'s file could not be read — discard it in Models > LLMs > jev.',- 'jev-head-revision-mismatch': 'The adopted project head was trained on a different scorer version — retrain or discard it in Models > LLMs > jev.',+ 'jev-head-not-found': 'The adopted project head is missing — discard it in Models > Decision Classifiers > Jev to go back to the stock scorer.',+ 'jev-head-invalid': 'The adopted project head could not be read — discard it in Models > Decision Classifiers > Jev.',+ 'jev-head-too-large': 'The adopted project head is larger than PortOS will load — discard it in Models > Decision Classifiers > Jev.',+ 'jev-head-unreadable': 'The adopted project head\'s file could not be read — discard it in Models > Decision Classifiers > Jev.',+ 'jev-head-revision-mismatch': 'The adopted project head was trained on a different scorer version — retrain or discard it in Models > Decision Classifiers > Jev.',});export const SCOPE_ADHERENCE_REASON_FALLBACK = 'The local scorer could not answer for this change.';diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 891acc2307..f46f546aff 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -116,6 +116,19 @@ const jevHeadStore = () => import('../services/jevHeads.js')const jevTrainer = () => import('../services/jevTraining.js')const router = Router()+const layaService = () => import('../services/layaMlx.js')++router.get('/laya-mlx/status', asyncHandler(async (_req, res) => {+ res.json(await (await layaService()).getLayaStatus())+}))+router.post('/laya-mlx/install', asyncHandler(async (_req, res) => {+ res.status(202).json(await (await layaService()).installLaya())+}))+router.post('/laya-mlx/score', asyncHandler(async (req, res) => {+ const { layaScoreRequestSchema } = await import('../lib/layaMlx.js')+ const input = validateRequest(layaScoreRequestSchema, req.body)+ res.json(await (await layaService()).scoreLaya(input, abortSignalFromResponse(res)))+}))const emitter = (req) => {const io = req.app.get('io')@@ -326,7 +339,7 @@ router.post('/jev/install', asyncHandler(async (req, res) => {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.'+ ? 'Scorer package installation failed. Check internet access and Python compatibility, then retry from Models > Decision Classifiers > Jev.': code === 'jev-model-download-failed'? 'The pinned jev model snapshot could not be downloaded. Check internet access and free disk space, then retry.': codediff --git a/server/services/backup.js b/server/services/backup.jsindex 347a9f89d5..5b2d5a9fec 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -21,7 +21,6 @@ import { resolvePgDumpBinary } from '../lib/pgTools.js';import { getBackendName } from './memoryBackend.js';import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';import { isSafeSnapshotSource, isSafeSubdirFilter, anchorUserExcludes } from '../lib/sharedSchemas.js';-import { getIo } from './socket.js';import { reloadSettings } from './settings.js';import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';@@ -142,6 +141,7 @@ const queueStateWrite = createFileWriteQueue();// matches any `loras/` directory anywhere under data/ (e.g. a user's// brain/.../loras/ collection), which would silently exclude unrelated user data.export const DEFAULT_EXCLUDES = [+ { path: '/python/laya-mlx/', reason: 'Rebuildable Laya-MLX experiment runtime and pinned model weights', overridable: false },{ path: '/browser-profile/', reason: 'Browser CDP profile — cache/cookies, can be several GB', overridable: false },{ path: '/cos/worktrees/', reason: 'Ephemeral agent git worktrees — recreated on demand', overridable: false },{ path: '/cos/slashdo-resolved/', reason: 'Resolved slashdo command bodies staged for agent prompts — derived from the bundled submodule, regenerated on demand', overridable: false },@@ -592,7 +592,8 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl// Loud-on-failure: surface a degraded DB dump as a warning toast, even on// unattended scheduled runs (which pass io=null) via the module-level io.if (pgResult.status === 'failed') {- const errIo = io || getIo();+ // Keep socket/auth initialization out of backup metadata reads and tests.+ const errIo = io || (await import('./socket.js')).getIo();if (errIo) {emitErrorEvent(errIo, new ServerError(`Backup DB dump failed: ${pgResult.reason}`,diff --git a/server/services/layaMlx.js b/server/services/layaMlx.jsnew file mode 100644index 0000000000..74c919dd96--- /dev/null+++ b/server/services/layaMlx.js@@ -0,0 +1,103 @@+/** Explicit, experimental Laya execution. No boot hooks, automatic routing or prompt persistence. */+import { existsSync } from 'node:fs';+import { mkdir, readFile, writeFile, rename, unlink } from 'node:fs/promises';+import { join } from 'node:path';+import { promisify } from 'node:util';+import { execFile } from '../lib/childProcess.js';+import { PATHS } from '../lib/paths.js';+import { isAppleSilicon } from '../lib/platform.js';+import { LAYA_MLX, layaScoreRequestSchema, normalizeLayaResult } from '../lib/layaMlx.js';++const execFileAsync = promisify(execFile);+const root = () => join(PATHS.data, 'python', 'laya-mlx');+const python = () => join(root(), 'venv', 'bin', 'python3');+const model = () => join(root(), 'model');+const marker = () => join(root(), 'installed.json');+const script = () => join(PATHS.root, 'scripts', 'run_laya_mlx.py');+let installation = null;+let stage = null;+let installError = null;+let scoring = false;+const failure = code => ({ ok: false, code });++// These processes receive neither provider credentials nor arbitrary Python paths.+function environment(offline = true) {+ const env = Object.fromEntries(['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL']+ .filter(key => process.env[key] != null).map(key => [key, process.env[key]]));+ return { ...env, PYTHONNOUSERSITE: '1', HF_HUB_DISABLE_TELEMETRY: '1',+ TOKENIZERS_PARALLELISM: 'false', ...(offline ? { HF_HUB_OFFLINE: '1' } : {}) };+}++export async function getLayaStatus() {+ const supported = isAppleSilicon();+ const installed = await readFile(marker(), 'utf8').then(JSON.parse).catch(() => null);+ const ready = supported && installed?.revision === LAYA_MLX.revision+ && installed?.runtimeRevision === LAYA_MLX.runtimeRevision+ && existsSync(python()) && ['model.safetensors', 'rl_agent_config.json', 'encoder/config.json', 'tokenizer/tokenizer.json']+ .every(file => existsSync(join(model(), file)));+ return { ...LAYA_MLX, supported, ready: !!ready, installing: !!installation, stage, installError, scoring };+}++async function performInstall() {+ const { detectVenvBasePythonSync } = await import('../lib/pythonSetup.js');+ stage = 'python';+ const base = detectVenvBasePythonSync();+ if (!base) throw new Error('python');+ await execFileAsync(base, ['-c', 'import sys,platform; assert sys.version_info >= (3,11) and platform.machine() == "arm64" and int(platform.mac_ver()[0].split(".")[0]) >= 14'],+ { env: environment(), timeout: 10000, maxBuffer: 4096 });+ await mkdir(root(), { recursive: true });+ await unlink(marker()).catch(error => { if (error.code !== 'ENOENT') throw error; });+ stage = 'runtime';+ await execFileAsync(base, ['-m', 'venv', join(root(), 'venv')], { env: environment(), timeout: 120000, maxBuffer: 4096 });+ await execFileAsync(python(), ['-m', 'pip', 'install', '--force-reinstall', '--disable-pip-version-check',+ `https://github.com/mizorewww/laya-mlx/archive/${LAYA_MLX.runtimeRevision}.zip`],+ { env: environment(false), timeout: 600000, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL' });+ stage = 'model';+ await execFileAsync(python(), [script(), 'download', model(), LAYA_MLX.repository, LAYA_MLX.revision],+ { env: environment(false), timeout: 1200000, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL' });+ stage = 'verify';+ await execFileAsync(python(), [script(), 'verify', model()],+ { env: environment(), timeout: 120000, maxBuffer: 4096, killSignal: 'SIGKILL' });+ await writeFile(`${marker()}.tmp`, JSON.stringify(LAYA_MLX));+ await rename(`${marker()}.tmp`, marker());+}++export async function installLaya() {+ if (!isAppleSilicon()) return failure('laya-unsupported');+ if (scoring) return failure('laya-busy');+ if (!installation) {+ installError = null;+ installation = performInstall().catch(() => { installError = `laya-install-${stage}-failed`; })+ .finally(() => { installation = null; stage = null; });+ }+ return { ok: true, installing: true };+}++export async function scoreLaya(input, signal) {+ const parsed = layaScoreRequestSchema.safeParse(input);+ if (!parsed.success) return failure('laya-request-invalid');+ const { isInstanceFeatureEnabled } = await import('./instanceFeatures.js');+ if (!await isInstanceFeatureEnabled('laya-mlx')) return failure('laya-disabled');+ if (installation || scoring) return failure('laya-busy');+ // Reserve before the first asynchronous readiness check: overlapping requests+ // must not each load a separate copy of the model into unified memory.+ scoring = true;+ const started = Date.now();+ return (async () => {+ const status = await getLayaStatus();+ if (!status.supported) return failure('laya-unsupported');+ if (!status.ready) return failure('laya-not-ready');+ const task = execFileAsync(python(), [script(), 'score', model()], {+ env: environment(), timeout: 120000, maxBuffer: 65536, killSignal: 'SIGKILL', signal,+ });+ // Never place the premise in argv, a temporary file, a log, or an error.+ task.child.stdin.on('error', () => {});+ task.child.stdin.end(JSON.stringify(parsed.data));+ const { stdout } = await task;+ const raw = JSON.parse(stdout);+ if (raw.code === 'laya-context-too-long') return failure(raw.code);+ const result = normalizeLayaResult(raw, parsed.data.options, parsed.data.minMargin);+ return result ? { ...result, elapsedMs: Date.now() - started } : failure('laya-response-invalid');+ })().catch(() => failure(signal?.aborted ? 'laya-cancelled' : 'laya-scoring-failed'))+ .finally(() => { scoring = false; });+}diff --git a/server/services/layaMlx.test.js b/server/services/layaMlx.test.jsnew file mode 100644index 0000000000..6334a09315--- /dev/null+++ b/server/services/layaMlx.test.js@@ -0,0 +1,83 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { promisify } from 'node:util';+const mocks = vi.hoisted(() => ({ exec: vi.fn(), enabled: vi.fn(), supported: vi.fn(), exists: vi.fn(), read: vi.fn() }));+vi.mock('../lib/childProcess.js', () => ({ execFile: Object.assign(() => {}, { [promisify.custom]: mocks.exec }) }));+vi.mock('../lib/pythonSetup.js', () => ({ detectVenvBasePythonSync: () => '/example/python3' }));+vi.mock('../lib/platform.js', () => ({ isAppleSilicon: mocks.supported }));+vi.mock('./instanceFeatures.js', () => ({ isInstanceFeatureEnabled: mocks.enabled }));+vi.mock('node:fs', () => ({ existsSync: mocks.exists }));+vi.mock('node:fs/promises', () => ({ readFile: mocks.read, mkdir: vi.fn().mockResolvedValue(), writeFile: vi.fn().mockResolvedValue(), rename: vi.fn().mockResolvedValue(), unlink: vi.fn().mockResolvedValue() }));+import { LAYA_MLX } from '../lib/layaMlx.js';+import { getLayaStatus, installLaya, scoreLaya } from './layaMlx.js';+const input = { premise: 'The invoice was paid twice.', instructions: 'Choose a department.', options: ['billing', 'sales'], minMargin: 0.15 };+const output = { answers: { decision: { type: 'choice', choice: 'billing', probabilities: { billing: 0.9, sales: 0.1 }, confidence: 0.53 } } };+let stdin;+beforeEach(() => {+ vi.clearAllMocks();+ mocks.enabled.mockResolvedValue(true);+ mocks.supported.mockReturnValue(true);+ mocks.exists.mockReturnValue(true);+ mocks.read.mockResolvedValue(JSON.stringify(LAYA_MLX));+ stdin = { on: vi.fn(), end: vi.fn() };+ mocks.exec.mockImplementation(() => Object.assign(Promise.resolve({ stdout: JSON.stringify(output) }), { child: { stdin } }));+});+describe('Laya manual experiment workflow', () => {+ it('observes installation without starting Python and rejects unsupported installs', async () => {+ expect(await getLayaStatus()).toMatchObject({ ready: true, supported: true });+ mocks.supported.mockReturnValue(false);+ expect(await installLaya()).toEqual({ ok: false, code: 'laya-unsupported' });+ expect(mocks.exec).not.toHaveBeenCalled();+ });+ it('gates disabled experiments before spawning and validates requests', async () => {+ mocks.enabled.mockResolvedValue(false);+ expect(await scoreLaya(input)).toMatchObject({ code: 'laya-disabled' });+ expect(await scoreLaya({ ...input, options: ['same', 'same'] })).toMatchObject({ code: 'laya-request-invalid' });+ expect(mocks.exec).not.toHaveBeenCalled();+ });+ it('scores offline through stdin without leaking credentials or confusing confidence with entailment', async () => {+ vi.stubEnv('GH_TOKEN', 'test-secret');+ const result = await scoreLaya(input);+ expect(result).toMatchObject({ ok: true, choice: 'billing', abstained: false, entropyConfidence: 0.53 });+ const [, args, options] = mocks.exec.mock.calls[0];+ expect(args).not.toContain(input.premise);+ expect(options.env).toMatchObject({ HF_HUB_OFFLINE: '1', PYTHONNOUSERSITE: '1' });+ expect(options.env.GH_TOKEN).toBeUndefined();+ expect(stdin.end).toHaveBeenCalledWith(JSON.stringify(input));+ vi.unstubAllEnvs();+ });+ it('rejects malformed probabilities and propagates context rejection without private output', async () => {+ for (const raw of [{ answers: { decision: { ...output.answers.decision, probabilities: { billing: 1.2, sales: -0.2 } } } },+ { answers: { decision: { ...output.answers.decision, choice: 'other' } } }]) {+ mocks.exec.mockImplementationOnce(() => Object.assign(Promise.resolve({ stdout: JSON.stringify(raw) }), { child: { stdin } }));+ expect(await scoreLaya(input)).toMatchObject({ code: 'laya-response-invalid' });+ }+ mocks.exec.mockImplementationOnce(() => Object.assign(Promise.resolve({ stdout: '{"code":"laya-context-too-long"}' }), { child: { stdin } }));+ expect(await scoreLaya(input)).toMatchObject({ code: 'laya-context-too-long' });+ });+ it('abstains on low margins and ties, including when the requested floor is zero', async () => {+ expect(await scoreLaya({ ...input, minMargin: 0.9 })).toMatchObject({ ok: true, abstained: true, choice: null });+ mocks.exec.mockImplementationOnce(() => Object.assign(Promise.resolve({ stdout: JSON.stringify({ answers: { decision: { ...output.answers.decision, probabilities: { billing: 0.5, sales: 0.5 } } } }) }), { child: { stdin } }));+ expect(await scoreLaya({ ...input, minMargin: 0 })).toMatchObject({ ok: true, abstained: true, choice: null });+ });+ it('prevents overlapping model loads and releases the guard after child failure', async () => {+ let reject;+ mocks.exec.mockImplementationOnce(() => Object.assign(new Promise((_, fail) => { reject = fail; }), { child: { stdin } }));+ const first = scoreLaya(input);+ await vi.waitFor(() => expect(mocks.exec).toHaveBeenCalled());+ expect(await scoreLaya(input)).toMatchObject({ code: 'laya-busy' });+ expect(await installLaya()).toMatchObject({ code: 'laya-busy' });+ reject(new Error('private traceback'));+ expect(await first).toEqual({ ok: false, code: 'laya-scoring-failed' });+ expect(await scoreLaya(input)).toMatchObject({ ok: true });+ });+});++it('installs only on request, pins runtime and weights, and reports bounded setup failures', async () => {+ expect(await installLaya()).toEqual({ ok: true, installing: true });+ await vi.waitFor(async () => expect((await getLayaStatus()).installing).toBe(false));+ expect(mocks.exec.mock.calls.some(([, args]) => args.includes(`https://github.com/mizorewww/laya-mlx/archive/${LAYA_MLX.runtimeRevision}.zip`))).toBe(true);+ expect(mocks.exec.mock.calls.some(([, args]) => args.includes(LAYA_MLX.revision) && args.includes(LAYA_MLX.repository))).toBe(true);+ mocks.exec.mockRejectedValueOnce(new Error('private Python diagnostic'));+ await installLaya();+ await vi.waitFor(async () => expect(await getLayaStatus()).toMatchObject({ installing: false, installError: 'laya-install-python-failed' }));+});