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: train an optional project-specific jev head for scope adherence (#7689)
[._.]/ Adam Eivy07a0ce7fb18d
diff --git a/client/src/components/models/JevPanel.jsx b/client/src/components/models/JevPanel.jsxindex c62a4b6fcc..e6e5fa0907 100644--- a/client/src/components/models/JevPanel.jsx+++ b/client/src/components/models/JevPanel.jsx@@ -1,14 +1,18 @@import { useCallback, useEffect, useRef, useState } from 'react';-import { CheckCircle2, Circle, Download, ExternalLink, RefreshCw, Scale } from 'lucide-react';+import { CheckCircle2, Circle, Download, ExternalLink, GraduationCap, RefreshCw, Scale } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import { formatBytes, formatCount, formatPercent } from '../../utils/formatters';import {+ adoptJevHead,cancelJevInstall,+ discardJevHead,getJevDecisionStats,+ getJevHeads,getJevStatus,installJev,scoreJev,+ trainJevHead,unloadJev,} from '../../services/api';import socket from '../../services/socket';@@ -33,6 +37,20 @@ const parseHypotheses = (text) => text.split('\n').map((line) => line.trim()).fi// unmeasured decision must not argue against itself.const formatRate = (rate) => formatPercent(rate === null ? null : rate * 100);+// The one decision a project head can be trained for today. The triage+// decisions share the same machinery but their cutover waits on shadow-mode+// evidence, so there is deliberately nothing to pick between yet.+const TRAINABLE_DECISION_ID = 'scope-adherence';++// Why a measured head cannot be adopted, in the operator's words. Naming the+// losing baseline matters: "did not beat the stock scorer" and "did not beat+// always guessing the most common answer" send them to different places.+const BLOCKER_LABELS = {+ 'jev-head-below-zero-shot': 'Did not beat the stock zero-shot scorer, which needs no corpus at all.',+ 'jev-head-below-majority-class': 'Did not beat always predicting the most common answer, so it learned the label balance rather than the product.',+ 'jev-head-metrics-invalid': 'This head carries no readable scores.',+};+export default function JevPanel() {const [status, setStatus] = useState(null);const [statusError, setStatusError] = useState(false);@@ -45,6 +63,9 @@ export default function JevPanel() {const [scoring, setScoring] = useState(false);const [decision, setDecision] = useState(null);const [decisionStats, setDecisionStats] = useState(null);+ const [headState, setHeadState] = useState(null);+ const [training, setTraining] = useState(false);+ const [headError, setHeadError] = useState('');const progressTimer = useRef(null);const loadStatus = useCallback(() => (@@ -56,6 +77,14 @@ export default function JevPanel() {.catch(() => { setStatusError(true); return null; })), []);+ // 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; })+ ), []);+useEffect(() => {let active = true;loadStatus();@@ -63,6 +92,9 @@ export default function JevPanel() {getJevDecisionStats({ silent: true }).then((res) => { if (active) setDecisionStats(res); }).catch(() => { if (active) setDecisionStats(null); });+ getJevHeads({ silent: true })+ .then((res) => { if (active) setHeadState(res); })+ .catch(() => { if (active) setHeadState(null); });return () => { active = false; };}, [loadStatus]);@@ -126,6 +158,32 @@ export default function JevPanel() {.finally(() => { setScoring(false); loadStatus(); });};+ const runTraining = () => {+ setHeadError('');+ setTraining(true);+ return trainJevHead({}, { silent: true })+ .then(() => loadHeads())+ // Shown in the section beside the button, not as a toast: the operator is+ // reading the three scores right here, and the reason a run produced none+ // belongs with them.+ .catch((error) => { setHeadError(error.message || 'Training failed.'); return loadHeads(); })+ .finally(() => setTraining(false));+ };++ const adoptHead = (decisionId) => {+ setHeadError('');+ return adoptJevHead(decisionId, { silent: true })+ .then(() => { toast.success('Project head adopted'); return loadHeads(); })+ .catch((error) => { setHeadError(error.message || 'This head cannot be adopted.'); return loadHeads(); });+ };++ const discardHead = (decisionId, adopted) => {+ setHeadError('');+ return discardJevHead(decisionId, { adopted }, { silent: true })+ .then(() => loadHeads())+ .catch((error) => { setHeadError(error.message || 'Discard failed.'); return loadHeads(); });+ };+const stages = stagesFromStatus(status);const currentStageId = installingStage || (installing ? stages.find((stage) => !stage.ready)?.id : null);const ready = status?.ready === true;@@ -306,6 +364,110 @@ export default function JevPanel() {<a href="/models/llms/abuse" className="text-xs text-port-accent hover:underline">Set a source to Prefer in Content safety policies</a></div>+ <div className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-white">Project-specific head</h3>+ <p className="text-xs text-gray-400 max-w-2xl">+ Fits a small classifier on the frozen scorer using this machine’s own history — merged pull requests,+ closed-unmerged ones, and issues closed as not planned or parked — so scope adherence learns <em>this</em>{' '}+ codebase’s notion of in-scope instead of answering zero-shot. Everything stays on this machine: the corpus,+ the cached embeddings and the trained head never leave it and never reach a peer.+ </p>+ <p className="text-xs text-gray-400 max-w-2xl">+ A trained head is <strong>only adoptable if it beats both baselines</strong> on a held-out set it was never+ trained on — the stock zero-shot scorer and always predicting the most common answer. A head that does not is+ discarded, which is an ordinary result rather than a failure.+ </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>+ ) : (+ <div className="overflow-x-auto">+ <table className="w-full text-xs" data-testid="jev-head-table">+ <thead>+ <tr className="text-gray-400 text-left">+ <th scope="col" className="py-1 pr-3 font-medium">Head</th>+ <th scope="col" className="py-1 pr-3 font-medium">Trained</th>+ <th scope="col" className="py-1 pr-3 font-medium">Zero-shot</th>+ <th scope="col" className="py-1 pr-3 font-medium">Majority class</th>+ <th scope="col" className="py-1 pr-3 font-medium">Actions</th>+ </tr>+ </thead>+ <tbody>+ {headState.heads.map((row) => (+ <tr key={`${row.decisionId}-${row.adopted}`} className="border-t border-port-border/60 text-gray-300 align-top">+ <th scope="row" className="py-1.5 pr-3 font-normal text-white">+ {row.decisionId}+ <span className="block text-[11px] text-gray-500">+ {row.adopted ? 'Adopted' : 'Candidate'}+ {row.ok && row.compatible === false && ' · fit on a different model revision'}+ </span>+ </th>+ {row.ok ? (+ <>+ <td className="py-1.5 pr-3 text-white">{formatRate(row.metrics.trained)}</td>+ <td className="py-1.5 pr-3">{formatRate(row.metrics.stockZeroShot)}</td>+ <td className="py-1.5 pr-3">{formatRate(row.metrics.majorityClass)}</td>+ </>+ ) : (+ <td className="py-1.5 pr-3 text-port-warning" colSpan={3}>Unreadable: {row.code}</td>+ )}+ <td className="py-1.5 pr-3">+ <div className="flex flex-wrap items-center gap-2">+ {!row.adopted && row.ok && (+ <button+ type="button"+ onClick={() => adoptHead(row.decisionId)}+ disabled={row.beatsBaselines !== true || row.compatible === false}+ className="px-2 py-0.5 text-[11px] bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 disabled:cursor-not-allowed"+ >+ Adopt+ </button>+ )}+ <button+ type="button"+ onClick={() => discardHead(row.decisionId, row.adopted)}+ className="px-2 py-0.5 text-[11px] border border-port-border text-gray-300 rounded"+ >+ Discard+ </button>+ </div>+ {row.ok && row.blocker && (+ <p className="text-[11px] text-port-warning mt-1 max-w-xs">{BLOCKER_LABELS[row.blocker] || row.blocker}</p>+ )}+ {row.ok && (+ <p className="text-[11px] text-gray-500 mt-1">+ {formatCount(row.metrics.goldSize, { fallback: '0' })} held-out ·{' '}+ {formatCount(row.metrics.trainSize, { fallback: '0' })} trained+ </p>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}++ <div className="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ onClick={runTraining}+ disabled={!ready || training || headState?.training === true}+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1"+ >+ <GraduationCap size={12} /> {training ? 'Training…' : 'Train a project head'}+ </button>+ {!ready && <span className="text-xs text-gray-500">Install jev first.</span>}+ {training && (+ <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>+ )}+ <span className="text-[11px] text-gray-500">Trains {TRAINABLE_DECISION_ID}. Never adopts on its own.</span>+ </div>+ {headError && <p role="alert" className="text-xs text-port-warning">{headError}</p>}+ </div>+<div className="space-y-3 border-t border-port-border pt-4"><h3 className="text-sm font-semibold text-white">Try a decision</h3><p className="text-xs text-gray-400 max-w-2xl">diff --git a/client/src/components/models/JevPanel.test.jsx b/client/src/components/models/JevPanel.test.jsxindex 66cb8c6c27..84c4677a68 100644--- a/client/src/components/models/JevPanel.test.jsx+++ b/client/src/components/models/JevPanel.test.jsx@@ -8,13 +8,20 @@ vi.mock('../../services/api', () => ({cancelJevInstall: vi.fn(),scoreJev: vi.fn(),unloadJev: vi.fn(),+ getJevHeads: vi.fn(),+ trainJevHead: vi.fn(),+ adoptJevHead: vi.fn(),+ discardJevHead: vi.fn(),}));vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));vi.mock('../ui/Toast', () => ({default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),}));-import { cancelJevInstall, getJevDecisionStats, getJevStatus, installJev, scoreJev, unloadJev } from '../../services/api';+import {+ adoptJevHead, cancelJevInstall, discardJevHead, getJevDecisionStats, getJevHeads,+ getJevStatus, installJev, scoreJev, trainJevHead, unloadJev,+} from '../../services/api';import socket from '../../services/socket';import JevPanel from './JevPanel';@@ -45,6 +52,27 @@ beforeEach(() => {installJev.mockResolvedValue({ ok: true, ready: true });cancelJevInstall.mockResolvedValue({ cancelled: true });unloadJev.mockResolvedValue({ unloaded: true });+ getJevHeads.mockResolvedValue({ heads: [], training: false });+ trainJevHead.mockResolvedValue({ ok: true });+ adoptJevHead.mockResolvedValue({ adopted: true });+ discardJevHead.mockResolvedValue({ ok: true, removed: true });+});++/** A described head as `GET /jev/heads` returns one. */+const headRow = (overrides = {}) => ({+ decisionId: 'scope-adherence',+ adopted: false,+ ok: true,+ architecture: 'linear',+ metrics: { trained: 0.71, stockZeroShot: 0.58, majorityClass: 0.52, goldSize: 40, trainSize: 120 },+ corpusHash: 'deadbeefcafe0001',+ corpusSources: ['merged-pr'],+ trainedAt: '2026-09-19T00:00:00.000Z',+ baseRevision: 'abc123',+ compatible: true,+ beatsBaselines: true,+ blocker: null,+ ...overrides,});const renderPanel = async () => {@@ -196,3 +224,104 @@ describe('JevPanel decision agreement', () => {expect(await screen.findByText('No decisions measured yet on this machine.')).toBeInTheDocument();});});++describe('JevPanel project head', () => {+ it('says scope adherence answers zero-shot when no head is trained', async () => {+ await renderPanel();+ expect(await screen.findByText(/answers zero-shot/)).toBeInTheDocument();+ expect(screen.queryByTestId('jev-head-table')).not.toBeInTheDocument();+ });++ // The whole point of the feature's honesty: the operator sees the trained+ // head NEXT TO both baselines it has to beat, not a single score.+ it('shows the trained head beside both baselines', async () => {+ getJevHeads.mockResolvedValue({ heads: [headRow()], training: false });+ await renderPanel();+ const row = within(await screen.findByTestId('jev-head-table')).getByRole('row', { name: /scope-adherence/ });+ expect(row).toHaveTextContent('71%');+ expect(row).toHaveTextContent('58%');+ expect(row).toHaveTextContent('52%');+ expect(row).toHaveTextContent('40 held-out');+ });++ it('adopts a candidate that beats both baselines', async () => {+ getJevHeads.mockResolvedValue({ heads: [headRow()], training: false });+ await renderPanel();+ await screen.findByTestId('jev-head-table');+ fireEvent.click(screen.getByRole('button', { name: 'Adopt' }));+ await waitFor(() => expect(adoptJevHead).toHaveBeenCalledWith('scope-adherence', { silent: true }));+ });++ it('refuses to offer adoption for a head that lost to the stock zero-shot scorer', async () => {+ getJevHeads.mockResolvedValue({+ heads: [headRow({+ metrics: { trained: 0.55, stockZeroShot: 0.62, majorityClass: 0.40, goldSize: 40, trainSize: 120 },+ beatsBaselines: false,+ blocker: 'jev-head-below-zero-shot',+ })],+ training: false,+ });+ await renderPanel();+ await screen.findByTestId('jev-head-table');+ expect(screen.getByRole('button', { name: 'Adopt' })).toBeDisabled();+ expect(screen.getByText(/Did not beat the stock zero-shot scorer/)).toBeInTheDocument();+ // Discard stays available: a head that lost is meant to be thrown away.+ expect(screen.getByRole('button', { name: 'Discard' })).toBeEnabled();+ });++ it('refuses to offer adoption for a head that lost to the majority class', async () => {+ getJevHeads.mockResolvedValue({+ heads: [headRow({+ metrics: { trained: 0.74, stockZeroShot: 0.61, majorityClass: 0.80, goldSize: 40, trainSize: 120 },+ beatsBaselines: false,+ blocker: 'jev-head-below-majority-class',+ })],+ training: false,+ });+ await renderPanel();+ const table = await screen.findByTestId('jev-head-table');+ expect(screen.getByRole('button', { name: 'Adopt' })).toBeDisabled();+ // Scoped to the table: the section's intro prose explains the same rule, so+ // an unscoped query would pass on the explanation rather than the verdict.+ expect(within(table).getByText(/always predicting the most common answer/)).toBeInTheDocument();+ });++ // A head fit on a different encoder revision is a correct artifact for+ // another checkpoint, so it is stated rather than hidden — an absence would+ // read as "no head trained".+ it('names an incompatible head instead of hiding it', async () => {+ getJevHeads.mockResolvedValue({+ heads: [headRow({ adopted: true, compatible: false, baseRevision: 'stale' })],+ training: false,+ });+ await renderPanel();+ const row = within(await screen.findByTestId('jev-head-table')).getByRole('row', { name: /scope-adherence/ });+ expect(row).toHaveTextContent('fit on a different model revision');+ });++ it('cannot start a training run before jev is installed', async () => {+ await renderPanel();+ expect(await screen.findByRole('button', { name: /Train a project head/ })).toBeDisabled();+ });++ it('trains on an explicit click and reloads the head state without adopting', async () => {+ getJevStatus.mockResolvedValue(status({ ready: true, setupState: 'ready', stages: stages(true) }));+ await renderPanel();+ const button = await screen.findByRole('button', { name: /Train a project head/ });+ await waitFor(() => expect(button).toBeEnabled());+ await act(async () => { fireEvent.click(button); });+ expect(trainJevHead).toHaveBeenCalledWith({}, { silent: true });+ // Training NEVER promotes: the run's only follow-up is re-reading state.+ expect(adoptJevHead).not.toHaveBeenCalled();+ });++ it('reports a failed training run beside the scores rather than as a toast', async () => {+ getJevStatus.mockResolvedValue(status({ ready: true, setupState: 'ready', stages: stages(true) }));+ trainJevHead.mockRejectedValue(new Error('jev-corpus-too-small'));+ await renderPanel();+ const button = await screen.findByRole('button', { name: /Train a project head/ });+ await waitFor(() => expect(button).toBeEnabled());+ await act(async () => { fireEvent.click(button); });+ expect(await screen.findByRole('alert')).toHaveTextContent('jev-corpus-too-small');+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex ec04e8c128..88daec1d7b 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), 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) 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 9b3216a980..d6df16eef5 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -60,6 +60,24 @@ export const scoreJev = (body, options) =>export const unloadJev = (options) =>request('/local-llm/jev/unload', { method: 'POST', body: '{}', ...options });+// Project-specific trained heads. Metrics and adoption state only — never a+// corpus row, a premise, or a path.+export const getJevHeads = (options) => request('/local-llm/jev/heads', options);++// Builds a corpus from this install's own forge history and fits a head on the+// frozen encoder. Minutes on a cold embedding cache, so callers give it a long+// leash and an explicit in-progress state.+export const trainJevHead = (body = {}, options) =>+ request('/local-llm/jev/heads/train', { method: 'POST', body: JSON.stringify(body), ...options });++// Refused server-side unless the head beats BOTH the stock zero-shot and the+// majority-class baseline — a disabled button is a suggestion, not the gate.+export const adoptJevHead = (decisionId, options) =>+ request('/local-llm/jev/heads/adopt', { method: 'POST', body: JSON.stringify({ decisionId }), ...options });++export const discardJevHead = (decisionId, { adopted = false } = {}, options) =>+ request('/local-llm/jev/heads/discard', { method: 'POST', body: JSON.stringify({ decisionId, adopted }), ...options });+export const getLocalLlmHuggingFaceSearch = (backend, q = '', category = 'all', limit = 12) =>request(`/local-llm/huggingface-search?backend=${encodeURIComponent(backend)}&category=${encodeURIComponent(category)}&limit=${encodeURIComponent(limit)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex e3a617c66b..4565cafa0d 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -29,8 +29,20 @@ A backup run (`runBackup` in `server/services/backup.js`) writes to:`DEFAULT_EXCLUDES` (in `backup.js`) skips ephemeral/cache data and large re-downloadable assets — all anchored with a leading `/` (rsync filter syntax). Two tiers:-- **Non-overridable** (`overridable: false`): browser CDP profile, agent worktrees — caches with no irreplaceable user data; never backed up.-- **Overridable** (`overridable: true`): LoRA weight files, cloned repos, reference repos, browser downloads — re-downloadable; the user can disable these built-in exclusion rules from the Backup settings UI via `disabledDefaultExcludes`.+- **Non-overridable** (`overridable: false`): browser CDP profile, agent worktrees, cached jev training embeddings — caches with no irreplaceable user data; never backed up.+- **Overridable** (`overridable: true`): LoRA weight files, cloned repos, reference repos, browser downloads, jev training corpora — re-downloadable or rebuildable; the user can disable these built-in exclusion rules from the Backup settings UI via `disabledDefaultExcludes`.++#### jev project heads — excluded bulk, retained artifact++`data/jev/` (#7689) holds three things that are deliberately NOT one tier:++| Path | Tier | Why |+|---|---|---|+| `/jev/embeddings/` | excluded, non-overridable | Frozen-encoder outputs keyed by `(pair, model revision)`. Byte-identical on re-encode, and gigabytes. |+| `/jev/corpora/` | excluded, **overridable** | Rebuildable by `node scripts/jev-corpus.js`. Overridable because the forge moves on, so someone archiving a measured adoption decision may want the exact rows the numbers came from. |+| `data/jev/heads/` | **NOT excluded** | A trained head is a few thousand floats and is **not regenerable once its corpus is stale** — the queries that produced one a month ago return different rows today. It is also the only artifact here an operator made a decision about, on the strength of three measured gold-set scores. |++Everything under `data/jev/` is machine-local (ADR [privacy records machine-local](decisions/2026-08-08-privacy-records-machine-local.md)), so a snapshot that carries a head is the only copy that survives a rebuild. Retaining it costs kilobytes; excluding it would silently discard the decision.The effective exclude list is computed by the pure `computeEffectiveExcludes()` helper (unit-tested in `backup.test.js`). The scheduled cron handler in `backupScheduler.js` re-reads settings on every run, so `destPath`, `excludePaths`, `disabledDefaultExcludes`, and `enabled` all take effect on the next run without a restart. See [Scheduling & status](#scheduling--status) for how the cron registration itself tracks settings.diff --git a/docs/decisions/2026-08-08-privacy-records-machine-local.md b/docs/decisions/2026-08-08-privacy-records-machine-local.mdindex 5303dde41f..b5db28a09e 100644--- a/docs/decisions/2026-08-08-privacy-records-machine-local.md+++ b/docs/decisions/2026-08-08-privacy-records-machine-local.md@@ -92,6 +92,30 @@ that no user-authored text may ever be addressed to a peer: its one scopedcarve-out, submitted image/video job bodies, is decided in ADR[federated visual prompts](./2026-08-20-federated-visual-prompts.md) (#4682).+### Covered paths beyond the Privacy Center tables++The rule was written for the nine `privacy_*` tables, but it governs a *class* of+record — private data about the operator, held on one machine — not a table+prefix. Later work has added derived records of the same class, each with its own+guard test modelled on `privacyNeverFederates.test.js`:++| Path | What it holds | Guard |+|---|---|---|+| the nine `privacy_*` tables | the PII vault, orgs, holdings, broker cases | `privacyNeverFederates.test.js` |+| `beeper_*` tables | mirrored conversation bodies and attachment metadata | `beeperNeverFederates.test.js` |+| `ai_connections` / `ai_*_bindings` | this machine's endpoints and credential material | `providerGraphNeverFederates.test.js` |+| **`data/jev/`** (#7689) | **trained project heads, their training corpora, and cached frozen-encoder outputs** | `jevNeverFederates.test.js` |++`data/jev/` earns its place for a reason worth stating: nothing in it *looks* like+PII. A corpus is this install's merged pull requests, closed-unmerged ones and+issues closed as not planned, rendered as premises; a trained head is a few+thousand floats fit on exactly that. Both are **derived records of private+repository history and the operator's own judgement calls about what was worth+shipping** — a corpus quotes it directly, and a head encodes it. Pooling corpora+across peers to train a better shared head is the obvious feature request and is+refused for the same reason the vault is: it would move that history across the+federation layer, and a model's weights are not an anonymization step.+### Why not "federate, but gate it on HTTPS + the instance password"This was seriously considered, and the machinery for it already exists: thediff --git a/docs/features/scope-adherence.md b/docs/features/scope-adherence.mdindex 9c30f54a8e..028622d1e3 100644--- a/docs/features/scope-adherence.md+++ b/docs/features/scope-adherence.md@@ -77,9 +77,72 @@ The repository path comes from the loaded app record, never from the request: `PEach reads as "no advisory" in the UI, never as a verdict.+## An optional project-specific head++Zero-shot is the default and the only thing a fresh install runs. Optionally, an operator can fit a small classifier on the **frozen** encoder using this machine's own history, so the scorer learns *this* codebase's notion of in-scope rather than answering from the stock checkpoint's general priors.++Nothing about the advisory contract changes. A head emits the checkpoint's own three labels, in the same order, so `decideFromScores`, the `minMargin: 0.2` floor and the informativeness ranking are byte-identical whether one is adopted or not. There is still no auto-close, no gating label, and no CI check.++### Where the corpus comes from++`scripts/jev-corpus.js` (and the panel's Train button, through the same `services/jevCorpusBuilder.js`) reads four weak signals off the forge with `gh`:++| Source | Weak verdict | Why it is evidence |+|---|---|---|+| merged PRs on the default branch | `aligned` | the maintainer wanted it |+| closed-unmerged PRs | `unrelated` | they did not |+| issues closed `not planned` | `unrelated` | they did not |+| issues labelled `future` | `unrelated` | parked rather than refused |++Each row is paired with the clauses the SAME retriever picks at inference time, and the premise is composed by the SAME helpers — so a corpus row asks exactly the question the scorer is asked in production. The output is open-jev **Route A** JSONL (`{"context", "options", "label"}`), which keeps `openjev eval` usable as an independent cross-check on a corpus PortOS built.++**Every label is weak.** A merged pull request is evidence the maintainer wanted it, not an annotation that it advances the clause the retriever happened to pair it with. The held-out split, the two baselines and the adoption gate below exist precisely because "the head trained fine" proves nothing on its own.++Two sources named in the original proposal are deliberately absent, and the reasons are worth keeping:++- **The jev shadow-mode counters** record counts only — decision id, bucket, agreement flag, never a premise. That is exactly what makes shadow mode safe to leave on, and it also means they contain no labelled example and never will. They are carried on the corpus manifest as a readiness signal an operator can read, not folded in as rows.+- **`messageTriageRules.js`** corrections are email-sender keyed and belong to the `message-triage` decision, whose cutover waits on its own shadow-mode evidence. The builder is decision-generic so those callers can be added without reshaping anything.++### The split refusal++`splitCorpus` assigns train/gold by each example's **own content hash** — deterministic across machines and rebuilds, so a reported score can be reproduced by the person reading it. `assertSplitDisjoint` then **refuses** a split whose halves share an example key, or whose gold set is under 20 rows. A gold set contaminated by its training split reports a score that is partly memorization, and that score is the only evidence the adoption gate reads, so the refusal is a hard stop before anything is written — not a warning beside a corpus somebody might still train on. `dedupeCorpus` runs first, because a goal re-stated across `PRD.md` and `GOALS.md` produces the same question twice and would otherwise land in both halves by definition of the hash.++### Training++`scripts/train_jev_head.py` runs in the existing `venv-jev`, under the same hardened environment the sidecar gets — `HF_HUB_OFFLINE=1`, no API keys, no forge token, no arbitrary `PYTHONPATH`. **The encoder is frozen and never updated.** Frozen-encoder outputs are cached once per `(pair, model revision)` under `data/jev/embeddings/`, so a hyperparameter sweep costs seconds rather than re-paying a 4B forward pass per pair. The head is a linear classifier by default, or one hidden layer, over the last token's final hidden state; weights ship as bounded JSON so the compatibility check, the backup retention decision and code review are all inspectable.++Weak labels map the chosen option to `entailment` and the others to `neutral`, **not** `contradiction`: an option the maintainer did not take is unsupported by the change, not refuted by it — and training the third label on evidence that never meant refutation would teach the head to say *contradicts*, which is the one verdict this feature reports that a human would go and argue with.++### The adoption rule: beat BOTH baselines++A training run produces a **candidate** and three accuracies on the held-out gold set. It never promotes anything.++| Number | What it is |+|---|---|+| trained | the fitted head |+| stock zero-shot | the checkpoint's own classifier — needs no corpus, no training run, no privacy argument |+| majority class | always predicting the most common gold label |++`headBeatsBaselines` (`server/lib/jevHead.js`) requires the trained head to beat **both**, strictly. Beating only the majority class means it learned the label prior and nothing about the product; beating only zero-shot while losing to a constant prediction means the gold split is skewed enough that accuracy is not measuring anything, and the head would be adopted on the strength of that imbalance. Ties lose.++The gate is enforced in `adoptJevHead`, server-side. The panel also disables the button, but a hidden button is a suggestion — the refusal has to be on the function every surface goes through.++**A real outcome of a training run is that no head ships.** That is an acceptable result, not a failure.++### Revision compatibility++A head records the encoder revision it was fit on, and both the Node loader (`isHeadCompatible`) and the Python sidecar (`jev_head_kit.validate_head`) refuse one that does not match the installed checkpoint. Embeddings from a different revision are a different vector space: applying a head across one produces confident numbers with nothing anywhere to signal they are meaningless. An incompatible head falls back to the stock classifier and says so in the panel, rather than reading as "no head trained".++### Privacy and backup++Everything under `data/jev/` is a derived record of private repository history and is **machine-local**: never federated, never in a peer sync, never in a status or capability payload. The covered-path table in the ADR [privacy records machine-local](../decisions/2026-08-08-privacy-records-machine-local.md) names it, and `server/services/sharing/jevNeverFederates.test.js` is the guard. Cross-install or federated training is refused, not unimplemented.++Backup tiers are decided explicitly ([BACKUP.md](../BACKUP.md)): corpora and cached embeddings are regenerable bulk and are excluded, while **trained heads are retained** — a head is not regenerable once its corpus is stale.+## What is deliberately not here-- **A trained, project-specific head.** Fitting a small head on the frozen encoder from this install's merged PRs, closed-unmerged PRs and triage corrections — with a hand-labeled gold set and a "must beat both the stock zero-shot and the majority-class baseline to be adopted" rule — is tracked separately. Zero-shot ships first because it is useful on its own and needs no corpus.+- **Fine-tuning the encoder.** Frozen encoder plus a small head, only.+- **Trained heads for the triage decisions.** The same machinery serves them; that cutover belongs with those callers once their shadow-mode logs have accumulated.- **Any enforcement**, now or later. See the opening paragraph.## Source@@ -93,3 +156,9 @@ Each reads as "no advisory" in the UI, never as a verdict.| HTTP surface | `server/routes/apps/scopeAdherence.js` || UI | `client/src/components/apps/ScopeAdherenceCheck.jsx` || Failure labels | `server/lib/scopeAdherenceReasons.js` (re-exported to the client) |+| Trained-head contract and the adoption gate | `server/lib/jevHead.js` |+| Corpus schema, split and the overlap refusal | `server/lib/jevCorpus.js` |+| Corpus builder (forge reads) | `server/services/jevCorpusBuilder.js`, CLI `scripts/jev-corpus.js` |+| Head store, adoption, discard | `server/services/jevHeads.js` |+| Training orchestration | `server/services/jevTraining.js` |+| Trainer and shared pooling/head application | `scripts/train_jev_head.py`, `scripts/jev_head_kit.py` |diff --git a/scripts/jev-corpus.js b/scripts/jev-corpus.jsnew file mode 100644index 0000000000..0c31fdc581--- /dev/null+++ b/scripts/jev-corpus.js@@ -0,0 +1,51 @@+#!/usr/bin/env node+/**+ * Build the scope-adherence training corpus from this checkout's forge history.+ *+ * node scripts/jev-corpus.js [--repo <path>] [--json]+ *+ * A thin CLI over `services/jevCorpusBuilder.js` — the same code path the+ * "Train a project head" action in the jev panel runs, so a corpus built here+ * and a corpus built there are the same corpus. Writes+ * `data/jev/corpora/scope-adherence-<hash>/{train,gold,manifest}` and prints the+ * manifest.+ *+ * It prints COUNTS. Never an example, never a premise, never a clause: the+ * corpus is this install's private repository history, and a terminal is not+ * where that belongs. Read the JSONL directly if you need to audit it.+ *+ * Exits non-zero on the refusals that matter — most importantly+ * `jev-corpus-split-overlap`, which means the gold set shares rows with the+ * training split and any score measured on it would be partly memorization.+ */++import { buildScopeAdherenceCorpus } from '../server/services/jevCorpusBuilder.js';+import { resolveForgeForRepo } from '../server/services/forgeAuth.js';+import { PATHS } from '../server/lib/paths.js';++const argv = process.argv.slice(2);+const flag = (name, fallback = null) => {+ const position = argv.indexOf(name);+ return position >= 0 && argv[position + 1] ? argv[position + 1] : fallback;+};++const repoPath = flag('--repo', PATHS.root);+const asJson = argv.includes('--json');++const forge = await resolveForgeForRepo(repoPath).catch(() => null);+const result = await buildScopeAdherenceCorpus({ repoPath, env: forge?.env || null });++if (!result.ok) {+ console.error(`❌ jev corpus build failed: ${result.code}`);+ process.exit(1);+}++if (asJson) {+ console.log(JSON.stringify(result, null, 2));+} else {+ console.log(`📚 jev corpus ${result.corpusHash} — ${result.trainSize} train / ${result.goldSize} gold`);+ for (const [source, count] of Object.entries(result.sources)) console.log(` ${source}: ${count}`);+ console.log(` majority-class baseline on gold: ${(result.majorityClass * 100).toFixed(1)}%`);+ console.log(` shadow evidence: ${result.shadow.observed} observed, ${result.shadow.compared} compared`);+ console.log(` written to ${result.corpusDir.replace(PATHS.installRoot, '.')}`);+}diff --git a/scripts/jev_head_kit.py b/scripts/jev_head_kit.pynew file mode 100644index 0000000000..1e79d5127f--- /dev/null+++ b/scripts/jev_head_kit.py@@ -0,0 +1,184 @@+#!/usr/bin/env python3+"""Shared frozen-encoder pooling and trained-head application for jev.++Imported by BOTH `run_jev.py` (which applies an adopted head at inference) and+`train_jev_head.py` (which fits one). They must agree exactly on two things or+a head silently scores a different vector space than it was fit on:++ * how a (premise, hypothesis) pair is pooled into one vector, and+ * how a head's layers map that vector onto the checkpoint's three labels.++Both live here, once. The Node-side contract they mirror is+`server/lib/jevHead.js`; the constants below are repeated rather than imported+so this boundary still holds if either script is invoked directly.++Nothing here reaches the network, reads a repository, or executes model code:+`trust_remote_code` is never set, and a head is plain JSON validated before a+single number of it is used.+"""++import json+import math+import re+from pathlib import Path++# Mirrors of server/lib/jevHead.js.+HEAD_SCHEMA_VERSION = 1+POOLING = "last-token"+ARCHITECTURES = ("linear", "mlp1")+MAX_PARAMS = 2_000_000+MAX_HIDDEN = 256+# Mirrors JEV_LABELS in server/lib/jev.js, in the checkpoint's id2label order.+LABELS = ("contradiction", "entailment", "neutral")+# A head is addressed by slug, never by path: the sidecar resolves it inside a+# directory the Node service owns, so a request cannot name a file elsewhere.+SLUG = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")+++class HeadError(Exception):+ """A head failure the Node service can map to a code without reading text."""++ def __init__(self, code: str) -> None:+ super().__init__(code)+ self.code = code+++def pool_pair(state, premise: str, hypothesis: str):+ """Encode one pair and return `(pooled_vector, stock_logits)`.++ The pooled vector is the LAST token's final hidden state. openjev's 4B NLI+ checkpoint is a causal decoder, so that is the only position which has+ attended to the whole pair — a mean over the sequence would dilute the+ hypothesis, which is the half that varies.++ The checkpoint's own classifier logits come out of the same forward pass.+ The trainer needs both (the head's input, and the stock baseline it has to+ beat), and paying for two passes to collect them would double the cost of+ the one step that dominates a training run.+ """+ torch = state["torch"]+ tokenizer = state["tokenizer"]+ model = state["model"]+ text = state["template"].format(premise=premise, hypothesis=hypothesis)+ token_ids = tokenizer.encode(text, add_special_tokens=True, truncation=False)+ # Same refusal as `score_pairs`: a verdict on a truncated prefix is not a+ # verdict on the pair, and nothing downstream could tell the difference.+ if len(token_ids) > state["window"]:+ raise HeadError("jev-premise-too-large")+ device = state.get("device", "cpu")+ model_inputs = {+ "input_ids": torch.tensor([token_ids]).to(device),+ "attention_mask": torch.tensor([[1] * len(token_ids)]).to(device),+ }+ with torch.inference_mode():+ output = model(**model_inputs, output_hidden_states=True)+ pooled = output.hidden_states[-1][0, -1, :].to("cpu").float().tolist()+ logits = output.logits[0].to("cpu").float().tolist()+ return pooled, logits+++def validate_head(raw, *, revision: str):+ """Validate a head artifact's shape, size and encoder revision.++ Mirrors `parseJevHead` + `isHeadCompatible` in server/lib/jevHead.js. The+ revision check is not a nicety: the head's inputs are hidden states from one+ specific checkpoint, so applying it across a different one produces+ confident numbers with nothing anywhere to signal they are meaningless.+ """+ if not isinstance(raw, dict):+ raise HeadError("jev-head-invalid")+ if raw.get("schemaVersion") != HEAD_SCHEMA_VERSION:+ raise HeadError("jev-head-invalid")+ if raw.get("pooling") != POOLING:+ raise HeadError("jev-head-invalid")+ if raw.get("architecture") not in ARCHITECTURES:+ raise HeadError("jev-head-invalid")+ if list(raw.get("labels") or []) != list(LABELS):+ raise HeadError("jev-head-invalid")+ base = raw.get("baseModel")+ if not isinstance(base, dict) or base.get("revision") != revision:+ raise HeadError("jev-head-revision-mismatch")++ layers = raw.get("layers")+ hidden_size = raw.get("hiddenSize")+ if not isinstance(layers, list) or not 1 <= len(layers) <= 2:+ raise HeadError("jev-head-invalid")+ if not isinstance(hidden_size, int) or hidden_size < 1:+ raise HeadError("jev-head-invalid")++ params = 0+ expected_input = hidden_size+ for position, layer in enumerate(layers):+ if not isinstance(layer, dict):+ raise HeadError("jev-head-invalid")+ weight = layer.get("weight")+ bias = layer.get("bias")+ if not isinstance(weight, list) or not weight or not isinstance(bias, list):+ raise HeadError("jev-head-invalid")+ if len(bias) != len(weight):+ raise HeadError("jev-head-invalid")+ for row in weight:+ if not isinstance(row, list) or len(row) != expected_input:+ raise HeadError("jev-head-invalid")+ if not all(isinstance(cell, (int, float)) and math.isfinite(cell) for cell in row):+ raise HeadError("jev-head-invalid")+ params += len(row)+ if not all(isinstance(cell, (int, float)) and math.isfinite(cell) for cell in bias):+ raise HeadError("jev-head-invalid")+ params += len(bias)+ expected_input = len(weight)+ if position == 0 and len(layers) == 2 and len(weight) > MAX_HIDDEN:+ raise HeadError("jev-head-invalid")+ if expected_input != len(LABELS):+ raise HeadError("jev-head-invalid")+ if params > MAX_PARAMS:+ raise HeadError("jev-head-too-large")+ return raw+++def load_head(heads_dir, slug: str, *, revision: str):+ """Read and validate `<heads_dir>/<slug>.json`.++ `slug` is matched against a fixed charset BEFORE it touches the filesystem,+ and the resolved path is required to stay inside `heads_dir` — the sidecar+ accepts a head name from a local caller, and a name is not a path.+ """+ if not isinstance(slug, str) or not SLUG.match(slug):+ raise HeadError("jev-head-invalid")+ root = Path(heads_dir).resolve()+ path = (root / f"{slug}.json").resolve()+ if path.parent != root or not path.is_file():+ raise HeadError("jev-head-not-found")+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ raise HeadError("jev-head-unreadable")+ return validate_head(raw, revision=revision)+++def apply_head(head, pooled):+ """Run a validated head over one pooled vector, returning label probabilities.++ Plain Python arithmetic, not a torch graph: the head is at most a couple of+ thousand multiply-accumulates per pair on top of a 4B forward pass, and+ keeping it here means the applied maths is the same code an operator can+ read next to the weights they are being asked to adopt.+ """+ activations = list(pooled)+ layers = head["layers"]+ for position, layer in enumerate(layers):+ weight = layer["weight"]+ bias = layer["bias"]+ activations = [+ sum(cell * value for cell, value in zip(row, activations)) + offset+ for row, offset in zip(weight, bias)+ ]+ # ReLU between layers only. The final layer emits logits, which the+ # softmax below turns into the same distribution the stock classifier+ # head produces — so everything downstream is unchanged.+ if position < len(layers) - 1:+ activations = [value if value > 0 else 0.0 for value in activations]+ ceiling = max(activations)+ exponentiated = [math.exp(value - ceiling) for value in activations]+ total = sum(exponentiated)+ return {label: value / total for label, value in zip(LABELS, exponentiated)}diff --git a/scripts/jev_head_kit.test.js b/scripts/jev_head_kit.test.jsnew file mode 100644index 0000000000..dcc8d5253c--- /dev/null+++ b/scripts/jev_head_kit.test.js@@ -0,0 +1,173 @@+/**+ * The Python half of the trained-head contract.+ *+ * `jev_head_kit.py` is the code the SIDECAR runs, and every assertion below+ * pins something a Node-side test cannot reach: the head file a request+ * actually resolves to, the revision refusal at the point of load, and the+ * arithmetic that turns a head's layers into the checkpoint's three labels.+ * `server/lib/jevHead.test.js` asserts the same contract on the Node side —+ * both sides have to agree or a head is validated by one and misapplied by the+ * other.+ *+ * No torch: `validate_head`, `load_head` and `apply_head` need only `json` and+ * `math`, so this runs on a bare interpreter in CI.+ */++import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const python = resolveTestPython();+const scriptsDir = fileURLToPath(new URL('.', import.meta.url));+const REVISION = 'pinned-revision';++const HARNESS = `+import json, runpy, sys+kit = runpy.run_path(sys.argv[1])+`;++const run = (body) => execFileSync(+ python,+ ['-c', HARNESS + body, join(scriptsDir, 'jev_head_kit.py')],+ { encoding: 'utf8', timeout: 20_000 },+);++/**+ * A head whose weights make the label mapping observable: each output row picks+ * a different input, so a permuted mapping would move the entailment score+ * rather than merely scaling it.+ */+const head = (overrides = {}) => ({+ schemaVersion: 1,+ decisionId: 'scope-adherence',+ architecture: 'linear',+ pooling: 'last-token',+ baseModel: { id: 'openjev-qwen3.5-4b-nli', repository: 'AlexWortega/openjev', revision: REVISION },+ hiddenSize: 3,+ labels: ['contradiction', 'entailment', 'neutral'],+ layers: [{ weight: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], bias: [0, 0, 0] }],+ metrics: { trained: 0.71, stockZeroShot: 0.58, majorityClass: 0.52, goldSize: 40, trainSize: 120 },+ corpusHash: 'deadbeefcafe0001',+ corpusSources: ['merged-pr'],+ trainedAt: '2026-09-19T00:00:00.000Z',+ ...overrides,+});++/** A heads directory holding `scope-adherence.json`, plus a file outside it. */+function headsDir(contents = head()) {+ const root = mkdtempSync(join(tmpdir(), 'portos-jev-kit-'));+ const dir = join(root, 'heads');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'scope-adherence.json'), JSON.stringify(contents));+ // The file a path-traversal slug would reach if the charset check were absent.+ writeFileSync(join(root, 'escaped.json'), JSON.stringify(contents));+ return { root, dir };+}++describe.skipIf(!python)('jev trained-head kit', () => {+ it('applies a head and reports the checkpoint\'s three labels in its own order', () => {+ const raw = JSON.parse(run(`+scores = kit["apply_head"](json.loads(${JSON.stringify(JSON.stringify(head()))}), [0.0, 2.0, 0.0])+print(json.dumps({"labels": list(scores.keys()), "top": max(scores, key=scores.get), "sum": round(sum(scores.values()), 9)}))+`));+ // The second input dominates, and the second output row reads it — so the+ // winner is `entailment` only if the label mapping is positional and+ // correct. A permuted mapping moves the winner, not just the magnitude.+ expect(raw.labels).toEqual(['contradiction', 'entailment', 'neutral']);+ expect(raw.top).toBe('entailment');+ expect(raw.sum).toBe(1);+ });++ it('puts a ReLU between layers and none after the last', () => {+ const mlp = head({+ architecture: 'mlp1',+ layers: [+ // The negative row is clamped to zero by the hidden ReLU; without it the+ // -5 would flow through and flip the winner.+ { weight: [[1, 0, 0], [-5, 0, 0]], bias: [0, 0] },+ { weight: [[0, 1], [1, 0], [0, 1]], bias: [0, 0, 0] },+ ],+ });+ const raw = JSON.parse(run(`+scores = kit["apply_head"](json.loads(${JSON.stringify(JSON.stringify(mlp))}), [2.0, 0.0, 0.0])+print(json.dumps({"top": max(scores, key=scores.get)}))+`));+ expect(raw).toEqual({ top: 'entailment' });+ });++ it('refuses a head fit on a different encoder revision', () => {+ const { dir } = headsDir(head({+ baseModel: { id: 'openjev-qwen3.5-4b-nli', repository: 'AlexWortega/openjev', revision: 'other' },+ }));+ expect(loadCode(dir, 'scope-adherence')).toBe('jev-head-revision-mismatch');+ });++ // A head is addressed by SLUG and resolved inside a directory the Node+ // service owns. This is what keeps a slug from becoming a path.+ it('refuses a slug that would escape the heads directory', () => {+ const { dir } = headsDir();+ expect(loadCode(dir, '../escaped')).toBe('jev-head-invalid');+ expect(loadCode(dir, 'sub/scope-adherence')).toBe('jev-head-invalid');+ expect(loadCode(dir, 'Scope-Adherence')).toBe('jev-head-invalid');+ // Non-vacuity: the same loader accepts the legitimate slug in that dir.+ expect(loadCode(dir, 'scope-adherence')).toBeNull();+ });++ it('reports a missing head rather than an unreadable one', () => {+ const { dir } = headsDir();+ expect(loadCode(dir, 'message-triage')).toBe('jev-head-not-found');+ });++ it('reports an unparseable head file as unreadable', () => {+ const { dir } = headsDir();+ writeFileSync(join(dir, 'message-triage.json'), 'not json');+ expect(loadCode(dir, 'message-triage')).toBe('jev-head-unreadable');+ });++ it('rejects the shapes the Node-side parser rejects', () => {+ const cases = {+ relabelled: head({ labels: ['entailment', 'contradiction', 'neutral'] }),+ wrongHiddenSize: head({ hiddenSize: 8 }),+ wrongOutputWidth: head({ layers: [{ weight: [[1, 0, 0], [0, 1, 0]], bias: [0, 0] }] }),+ biasMismatch: head({ layers: [{ weight: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], bias: [0, 0] }] }),+ unknownPooling: head({ pooling: 'mean' }),+ futureSchema: head({ schemaVersion: 2 }),+ nonFiniteWeight: head({ layers: [{ weight: [[1, 0, 0], [0, 1, 0], [0, 0, 'x']], bias: [0, 0, 0] }] }),+ };+ const raw = JSON.parse(run(`+cases = json.loads(${JSON.stringify(JSON.stringify(cases))})+out = {}+for name, value in cases.items():+ try:+ kit["validate_head"](value, revision=${JSON.stringify(REVISION)})+ out[name] = None+ except kit["HeadError"] as error:+ out[name] = error.code+print(json.dumps(out))+`));+ expect(raw).toEqual({+ relabelled: 'jev-head-invalid',+ wrongHiddenSize: 'jev-head-invalid',+ wrongOutputWidth: 'jev-head-invalid',+ biasMismatch: 'jev-head-invalid',+ unknownPooling: 'jev-head-invalid',+ futureSchema: 'jev-head-invalid',+ nonFiniteWeight: 'jev-head-invalid',+ });+ });+});++/** `load_head`'s failure code for one slug, or null when it loaded. */+function loadCode(dir, slug) {+ return JSON.parse(run(`+try:+ kit["load_head"](${JSON.stringify(dir)}, ${JSON.stringify(slug)}, revision=${JSON.stringify(REVISION)})+ print(json.dumps({"code": None}))+except kit["HeadError"] as error:+ print(json.dumps({"code": error.code}))+`)).code;+}diff --git a/scripts/run_jev.py b/scripts/run_jev.pyindex f862f7c236..06df8ce049 100644--- a/scripts/run_jev.py+++ b/scripts/run_jev.py@@ -10,9 +10,15 @@ It is deliberately a classifier, not an agent: it accepts no tools, fetches noURLs, executes no repository code, and never emits the premise or hypothesistext back in an error.- POST /score {"premise": str, "hypotheses": [str, ...]}+ POST /score {"premise": str, "hypotheses": [str, ...], "head": str|None}-> {"schemaVersion": 1, "complete": true, "scores": [...]}GET /health -> {"ready": bool, "model": str, "revision": str, "device": str}++`head` names a project-specific trained head under `--heads-dir` (see+`jev_head_kit.py`). It replaces the checkpoint's own classifier layer on a+FROZEN encoder, emits the same three labels in the same order, and is refused+outright when it was fit on a different model revision. Absent or null, the+stock zero-shot classifier answers exactly as it always has."""import argparse@@ -22,6 +28,14 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Pathfrom threading import Lock+# This file's own directory, so the sibling import below resolves however the+# script was loaded. A normal `python <path>` spawn already puts it on the path;+# `runpy.run_path` (which the wire-contract test uses to drive this file with+# synthetic model doubles) does not.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from jev_head_kit import HeadError, apply_head, load_head, pool_pair # noqa: E402 - needs the sys.path line above.+# Mirrors of the bounds in server/lib/jev.js. Repeated rather than imported so# this boundary still holds if the script is ever invoked directly.MAX_PREMISE_CHARS = 32_000@@ -51,6 +65,9 @@ def validate_request(payload):raise JevError("jev-request-invalid")premise = payload.get("premise")hypotheses = payload.get("hypotheses")+ head = payload.get("head")+ if head is not None and not isinstance(head, str):+ raise JevError("jev-request-invalid")if not isinstance(premise, str) or not premise.strip():raise JevError("jev-request-invalid")if len(premise) > MAX_PREMISE_CHARS:@@ -62,7 +79,7 @@ def validate_request(payload):raise JevError("jev-request-invalid")if len(hypothesis) > MAX_HYPOTHESIS_CHARS:raise JevError("jev-request-invalid")- return premise, hypotheses+ return premise, hypotheses, head or Nonedef load_state(model_dir: Path):@@ -132,6 +149,19 @@ def resolve_window(tokenizer, config) -> int:return min(candidates)+def score_with_head(state, head, premise: str, hypotheses):+ """Score every pair through a trained head on the FROZEN encoder.++ Identical contract to `score_pairs` — same labels, same order, same+ response shape — so nothing on the Node side can tell which classifier+ answered except by having asked for one.+ """+ return [+ {"hypothesis": hypothesis, **apply_head(head, pool_pair(state, premise, hypothesis)[0])}+ for hypothesis in hypotheses+ ]++def score_pairs(state, premise: str, hypotheses):"""One forward pass per premise/hypothesis pair, in request order."""torch = state["torch"]@@ -160,8 +190,21 @@ def score_pairs(state, premise: str, hypotheses):return scores-def make_handler(state, model_id: str, revision: str):+def make_handler(state, model_id: str, revision: str, heads_dir):lock = Lock()+ # Validated heads, keyed by slug. A head is a few thousand floats, the+ # revision gate has already run, and the alternative is re-reading and+ # re-validating the same file on every forward pass.+ head_cache = {}++ def resolve_head(slug):+ if slug is None:+ return None+ if heads_dir is None:+ raise HeadError("jev-head-not-found")+ if slug not in head_cache:+ head_cache[slug] = load_head(heads_dir, slug, revision=revision)+ return head_cache[slug]class JevHandler(BaseHTTPRequestHandler):protocol_version = "HTTP/1.1"@@ -209,11 +252,21 @@ def make_handler(state, model_id: str, revision: str):returnraw = self.rfile.read(int(length))try:- premise, hypotheses = validate_request(json.loads(raw.decode("utf-8")))+ premise, hypotheses, head_slug = validate_request(json.loads(raw.decode("utf-8")))# One model, one accelerator queue: serialize so two concurrent# callers cannot interleave forward passes on the same weights.with lock:- scores = score_pairs(state, premise, hypotheses)+ head = resolve_head(head_slug)+ scores = (score_with_head(state, head, premise, hypotheses) if head+ else score_pairs(state, premise, hypotheses))+ except HeadError as error:+ # A head failure is the operator's to fix and must never fall+ # back to the stock classifier: they asked for the head that+ # their adoption decision was measured on, and silently+ # answering with a different one would make that measurement a+ # lie. Reported as its own code, not as a scoring failure.+ self._respond(400, {"error": error.code})+ returnexcept JevError as error:self._respond(error.status, {"error": error.code})return@@ -232,6 +285,11 @@ def main() -> int:parser.add_argument("--host", default="127.0.0.1")parser.add_argument("--model-id", default="openjev")parser.add_argument("--revision", default="")+ # Optional: the directory holding adopted project-specific heads. A request+ # names a head by SLUG, never by path, and the slug is resolved inside this+ # directory — so an install that passes no heads directory has no way to+ # reach one, whatever a caller asks for.+ parser.add_argument("--heads-dir", default=None)args = parser.parse_args()if args.host not in LOOPBACK_HOSTS:@@ -242,8 +300,18 @@ def main() -> int:if not model_dir.is_dir():raise ValueError("model snapshot is unavailable")+ # Deliberately NOT checked for existence here. The directory is created the+ # first time a head is saved, which may be long after this process started —+ # latching "no heads directory" at start-up would make a head adopted later+ # unreachable until the next cold start. `load_head` reports+ # `jev-head-not-found` when the file is absent, which is the same answer.+ heads_dir = Path(args.heads_dir) if args.heads_dir else None+state = load_state(model_dir)- server = ThreadingHTTPServer((args.host, args.port), make_handler(state, args.model_id, args.revision))+ server = ThreadingHTTPServer(+ (args.host, args.port),+ make_handler(state, args.model_id, args.revision, heads_dir),+ )# The single readiness signal the Node service waits on before polling# /health. Nothing else is ever written to stdout.sys.stdout.write(json.dumps({"ready": True, "port": args.port, "device": state["device"]}) + "\n")diff --git a/scripts/run_jev.test.js b/scripts/run_jev.test.jsindex 1920ad1f72..7a2175009f 100644--- a/scripts/run_jev.test.js+++ b/scripts/run_jev.test.js@@ -49,10 +49,16 @@ sys.modules["transformers"] = SimpleNamespace(AutoTokenizer=load(tokenizer),AutoModelForSequenceClassification=load(model),)+# A tensor double that still compares equal to the plain list the assertions+# above use, but carries the device move the trained-head path performs.+class Tensor(list):+ def to(self, *_args):+ return self+sys.modules["torch"] = SimpleNamespace(set_num_threads=lambda *_: None,inference_mode=contextlib.nullcontext,- tensor=lambda value: value,+ tensor=Tensor,softmax=lambda *_args, **_kwargs: Probabilities([0.1, 0.85, 0.05]),backends=SimpleNamespace(mps=SimpleNamespace(is_available=lambda: False)),)@@ -159,3 +165,89 @@ except ValueError as error:expect(raw).toEqual({ refused: true });});});++describe.skipIf(!python)('jev trained project head', () => {+ // The regression this uniquely catches: an adopted head changing the WIRE+ // SHAPE. `normalizeJevScores` matches the reply against the hypotheses that+ // were asked about, position for position — a head that dropped a label or+ // re-ordered the list would be rejected as a contract break rather than+ // scored, and the install would silently lose the feature it just adopted.+ it('scores through a head with the same shape and order the stock classifier uses', () => {+ const raw = JSON.parse(run(`+# Extend the model double with the hidden states pool_pair reads. The last row+# is what last-token pooling must select, so a mean or first-token pooling+# would produce a different winner rather than a slightly different number.+class Row(list):+ def to(self, *_args):+ return self+ def float(self):+ return self+ def tolist(self):+ return list(self)++class Hidden:+ def __getitem__(self, key):+ assert key == (0, -1, slice(None)), key+ return Row([0.0, 3.0, 0.0])++def model_with_hidden(**inputs):+ assert inputs["output_hidden_states"] is True+ return SimpleNamespace(logits=[Row([0.0, 0.0, 0.0])], hidden_states=[Hidden()])+model_with_hidden.config = model.config+state["model"] = model_with_hidden++head = {+ "schemaVersion": 1, "decisionId": "scope-adherence", "architecture": "linear",+ "pooling": "last-token",+ "baseModel": {"id": "m", "repository": "r", "revision": "rev"},+ "hiddenSize": 3, "labels": ["contradiction", "entailment", "neutral"],+ "layers": [{"weight": [[1, 0, 0], [0, 1, 0], [0, 0, 1]], "bias": [0, 0, 0]}],+ "metrics": {"trained": 0.7, "stockZeroShot": 0.5, "majorityClass": 0.4, "goldSize": 40, "trainSize": 120},+ "corpusHash": "deadbeefcafe0001", "corpusSources": ["merged-pr"],+ "trainedAt": "2026-09-19T00:00:00.000Z",+}+scores = helper["score_with_head"](state, head, "A premise.", ["first", "second"])+print(json.dumps({"scores": scores, "keys": sorted(scores[0].keys())}))+`));+ expect(raw.keys).toEqual(['contradiction', 'entailment', 'hypothesis', 'neutral']);+ expect(raw.scores.map((score) => score.hypothesis)).toEqual(['first', 'second']);+ // Row 1 of the head reads input 1, which carries the 3.0 — so entailment+ // wins only if last-token pooling and the label order both held.+ for (const score of raw.scores) {+ expect(score.entailment).toBeGreaterThan(score.contradiction);+ expect(score.entailment).toBeGreaterThan(score.neutral);+ expect(score.contradiction + score.entailment + score.neutral).toBeCloseTo(1, 9);+ }+ expect(normalizeJevScores(+ { schemaVersion: 1, complete: true, scores: raw.scores },+ { hypotheses: ['first', 'second'] },+ ).ok).toBe(true);+ });++ it('accepts a head name on a scoring request and defaults to none', () => {+ const raw = JSON.parse(run(`+def head_for(payload):+ try:+ return {"head": helper["validate_request"](payload)[2]}+ except helper["JevError"] as error:+ return {"code": error.code}++print(json.dumps({+ "absent": head_for({"premise": "p", "hypotheses": ["a"]}),+ "named": head_for({"premise": "p", "hypotheses": ["a"], "head": "scope-adherence"}),+ "null": head_for({"premise": "p", "hypotheses": ["a"], "head": None}),+ "blank": head_for({"premise": "p", "hypotheses": ["a"], "head": ""}),+ "notAString": head_for({"premise": "p", "hypotheses": ["a"], "head": 7}),+}))+`));+ expect(raw).toEqual({+ // Absent, null and blank all mean "the stock classifier answers" — the+ // state every install ships in.+ absent: { head: null },+ named: { head: 'scope-adherence' },+ null: { head: null },+ blank: { head: null },+ notAString: { code: 'jev-request-invalid' },+ });+ });+});diff --git a/scripts/train_jev_head.py b/scripts/train_jev_head.pynew file mode 100644index 0000000000..2d2842a5dc--- /dev/null+++ b/scripts/train_jev_head.py@@ -0,0 +1,363 @@+#!/usr/bin/env python3+"""Fit a project-specific head on the FROZEN jev encoder, and score it honestly.++Run inside the dedicated `venv-jev` by `server/services/jevTraining.js`. Fully+offline: `HF_HUB_OFFLINE=1` is set by the caller, every load is+`local_files_only`, `trust_remote_code` is never set, and nothing here contacts+a provider or downloads a second model. The encoder is never updated — only the+small head on top of it is.++ --corpus <train.jsonl> --gold <gold.jsonl> Route A: {"context","options","label"}+ --model-dir <pinned snapshot> the SAME checkpoint the sidecar loads+ --out <head.json> the candidate artifact+ --cache-dir <dir> frozen-encoder outputs, per (pair, revision)++Writes ONE JSON line to stdout: the training report, carrying the trained+head's accuracy on the held-out gold set beside BOTH baselines it has to beat —+the checkpoint's own zero-shot classifier and the majority class. Whether the+head may be adopted is decided from those numbers on the Node side+(`headBeatsBaselines` in server/lib/jevHead.js); this script never promotes+anything and has no idea where an adopted head lives.++## Why the cache matters++The dominant cost is one 4B forward pass per (context, option) pair, and a+hyperparameter sweep re-uses every one of them. Cached by a hash of the pair+plus the encoder revision, a second run costs seconds instead of minutes — and+a cache from a different revision can never be read back, because the revision+is part of the key rather than a field beside it.+"""++import argparse+import hashlib+import json+import sys+from datetime import datetime, timezone+from pathlib import Path++# This file's own directory, so the sibling import below resolves however the+# script was loaded — including under `runpy.run_path`, which does not put it on+# the path the way a normal `python <path>` spawn does.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from jev_head_kit import HEAD_SCHEMA_VERSION, LABELS, MAX_HIDDEN, POOLING, pool_pair # noqa: E402 - needs the sys.path line above.++ENTAILMENT = LABELS.index("entailment")+NEUTRAL = LABELS.index("neutral")+++def read_corpus(path: Path):+ """Read Route A JSONL, dropping any row that is not a usable example."""+ rows = []+ for line in path.read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ row = json.loads(line)+ except ValueError:+ continue+ options = row.get("options")+ label = row.get("label")+ context = row.get("context")+ if not isinstance(context, str) or not context.strip():+ continue+ if not isinstance(options, list) or len(options) < 2:+ continue+ if not all(isinstance(option, str) and option.strip() for option in options):+ continue+ if not isinstance(label, int) or not 0 <= label < len(options):+ continue+ rows.append({"context": context, "options": options, "label": label})+ return rows+++def pair_key(revision: str, context: str, hypothesis: str) -> str:+ """Cache key for one encoded pair.++ The revision is part of the KEY, not a field stored beside it: a cache+ written against one checkpoint must be unreadable by another rather than+ readable-and-wrong.+ """+ digest = hashlib.sha256()+ for part in (revision, POOLING, context, hypothesis):+ digest.update(part.encode("utf-8"))+ digest.update(b"\x00")+ return digest.hexdigest()+++def encode_corpus(state, rows, cache_dir: Path, revision: str, on_progress):+ """Embed every (context, option) pair once, reading and filling the cache.++ Returns a list parallel to `rows`, each entry holding one pooled vector and+ one stock-classifier logit vector per option.+ """+ cache_dir.mkdir(parents=True, exist_ok=True)+ encoded = []+ total = sum(len(row["options"]) for row in rows)+ done = 0+ for row in rows:+ pooled_options = []+ stock_options = []+ for hypothesis in row["options"]:+ path = cache_dir / f"{pair_key(revision, row['context'], hypothesis)}.json"+ cached = None+ if path.is_file():+ try:+ cached = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ cached = None+ if not isinstance(cached, dict) or "pooled" not in cached or "stock" not in cached:+ pooled, stock = pool_pair(state, row["context"], hypothesis)+ cached = {"pooled": pooled, "stock": stock}+ path.write_text(json.dumps(cached, separators=(",", ":")), encoding="utf-8")+ pooled_options.append(cached["pooled"])+ stock_options.append(cached["stock"])+ done += 1+ on_progress(done, total)+ encoded.append({"pooled": pooled_options, "stock": stock_options, "label": row["label"]})+ return encoded+++def choose(scores_per_option):+ """Pick the option with the highest entailment probability."""+ return max(range(len(scores_per_option)), key=lambda index: scores_per_option[index])+++def stock_accuracy(encoded, torch):+ """The checkpoint's OWN zero-shot accuracy on these examples.++ The first baseline, and the one that matters: it needs no corpus, no+ training run and no privacy argument, so a head that cannot beat it has+ bought nothing at a real cost.+ """+ if not encoded:+ return None+ correct = 0+ for example in encoded:+ probabilities = [+ torch.softmax(torch.tensor(logits), dim=-1)[ENTAILMENT].item()+ for logits in example["stock"]+ ]+ correct += int(choose(probabilities) == example["label"])+ return correct / len(encoded)+++def majority_accuracy(encoded):+ """Accuracy of always predicting the most common gold label."""+ if not encoded:+ return None+ counts = {}+ for example in encoded:+ counts[example["label"]] = counts.get(example["label"], 0) + 1+ return max(counts.values()) / len(encoded)+++def build_pair_dataset(encoded, torch):+ """Flatten examples into per-pair NLI rows.++ The chosen option becomes `entailment`; every other option becomes+ `neutral`, NOT `contradiction`. An option the maintainer did not take is+ unsupported by the change, not refuted by it — and training the third label+ on evidence that never meant refutation would teach the head to say+ "contradicts", which is the one verdict this feature reports that a human+ would go and argue with.+ """+ vectors = []+ targets = []+ for example in encoded:+ for index, pooled in enumerate(example["pooled"]):+ vectors.append(pooled)+ targets.append(ENTAILMENT if index == example["label"] else NEUTRAL)+ return torch.tensor(vectors, dtype=torch.float32), torch.tensor(targets, dtype=torch.long)+++def fit_head(train_encoded, torch, *, architecture: str, hidden: int, epochs: int, seed: int):+ """Fit the head. The encoder is untouched — only these layers are trained."""+ torch.manual_seed(seed)+ features, targets = build_pair_dataset(train_encoded, torch)+ hidden_size = features.shape[1]+ modules = []+ if architecture == "mlp1":+ modules += [torch.nn.Linear(hidden_size, hidden), torch.nn.ReLU()]+ modules.append(torch.nn.Linear(hidden, len(LABELS)))+ else:+ modules.append(torch.nn.Linear(hidden_size, len(LABELS)))+ model = torch.nn.Sequential(*modules)++ # Class weights, because the flattened dataset is imbalanced BY+ # CONSTRUCTION: a k-option decision produces one entailment row per k-1+ # neutral ones, so an unweighted fit would learn to answer "neutral" and+ # score well doing it.+ counts = torch.bincount(targets, minlength=len(LABELS)).float()+ weights = torch.where(counts > 0, counts.sum() / (counts * (counts > 0).sum()), torch.zeros_like(counts))+ loss_fn = torch.nn.CrossEntropyLoss(weight=weights)+ # Weight decay, not early stopping: the gold split is the adoption+ # evidence, and touching it to decide when to stop would make the score it+ # reports a validation score the head was tuned against.+ optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)+ for _ in range(epochs):+ optimizer.zero_grad()+ loss = loss_fn(model(features), targets)+ loss.backward()+ optimizer.step()+ return model, hidden_size, float(loss.item())+++def head_accuracy(model, encoded, torch):+ """The trained head's accuracy, scored the way inference scores."""+ if not encoded:+ return None+ correct = 0+ with torch.inference_mode():+ for example in encoded:+ features = torch.tensor(example["pooled"], dtype=torch.float32)+ probabilities = torch.softmax(model(features), dim=-1)[:, ENTAILMENT].tolist()+ correct += int(choose(probabilities) == example["label"])+ return correct / len(encoded)+++def serialize_layers(model, torch):+ """Row-major `[out][in]` weights plus biases, matching `apply_head`."""+ layers = []+ for module in model:+ if isinstance(module, torch.nn.Linear):+ layers.append({+ "weight": module.weight.detach().to("cpu").tolist(),+ "bias": module.bias.detach().to("cpu").tolist(),+ })+ return layers+++def emit(payload):+ sys.stdout.write(json.dumps(payload, separators=(",", ":")) + "\n")+ sys.stdout.flush()+++def main() -> int:+ parser = argparse.ArgumentParser(description="Fit a project-specific head on the frozen jev encoder.")+ parser.add_argument("--model-dir", required=True)+ parser.add_argument("--corpus", required=True)+ parser.add_argument("--gold", required=True)+ parser.add_argument("--out", required=True)+ parser.add_argument("--cache-dir", required=True)+ parser.add_argument("--decision-id", required=True)+ parser.add_argument("--model-id", required=True)+ parser.add_argument("--repository", required=True)+ parser.add_argument("--revision", required=True)+ parser.add_argument("--corpus-hash", required=True)+ parser.add_argument("--corpus-sources", default="")+ parser.add_argument("--architecture", default="linear", choices=["linear", "mlp1"])+ parser.add_argument("--hidden", type=int, default=64)+ parser.add_argument("--epochs", type=int, default=400)+ parser.add_argument("--seed", type=int, default=17)+ args = parser.parse_args()++ if not 1 <= args.hidden <= MAX_HIDDEN:+ emit({"ok": False, "code": "jev-head-invalid"})+ return 1++ train_rows = read_corpus(Path(args.corpus))+ gold_rows = read_corpus(Path(args.gold))+ if not train_rows or not gold_rows:+ emit({"ok": False, "code": "jev-corpus-too-small"})+ return 1++ # The overlap refusal is enforced on the Node side before this runs+ # (`assertSplitDisjoint`), and AGAIN here on the files actually handed over:+ # a contaminated gold set reports a score that is partly memorization, and+ # that score is the only evidence the adoption gate reads.+ gold_keys = {pair_key(args.revision, row["context"], "\u0000".join(row["options"])) for row in gold_rows}+ train_keys = {pair_key(args.revision, row["context"], "\u0000".join(row["options"])) for row in train_rows}+ if gold_keys & train_keys:+ emit({"ok": False, "code": "jev-corpus-split-overlap"})+ return 1++ # Imported HERE, not at module scope: argument validation and the corpus+ # read above must fail in milliseconds, not after a multi-second torch+ # import that a malformed request never needed.+ import torch+ from transformers import AutoModelForSequenceClassification, AutoTokenizer++ torch.set_num_threads(1)+ model_dir = Path(args.model_dir)+ tokenizer = AutoTokenizer.from_pretrained(str(model_dir), local_files_only=True, trust_remote_code=False)+ encoder = AutoModelForSequenceClassification.from_pretrained(+ str(model_dir), local_files_only=True, trust_remote_code=False, use_safetensors=True,+ )+ device = "mps" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available() else "cpu"+ encoder.to(device)+ encoder.eval()+ # FROZEN. The whole design rests on this: only the head below is fit.+ for parameter in encoder.parameters():+ parameter.requires_grad_(False)++ config = encoder.config+ template = getattr(config, "nli_template", None)+ if not isinstance(template, str) or "{premise}" not in template or "{hypothesis}" not in template:+ template = "Premise: {premise}\nHypothesis: {hypothesis}"+ window = min(+ value for value in (+ getattr(tokenizer, "model_max_length", None),+ getattr(getattr(config, "text_config", None), "max_position_embeddings", None),+ getattr(config, "max_position_embeddings", None),+ ) if isinstance(value, int) and 0 < value < 10_000_000+ )+ state = {+ "torch": torch, "tokenizer": tokenizer, "model": encoder,+ "device": device, "template": template, "window": window,+ }++ cache_dir = Path(args.cache_dir)+ # Progress on stderr, never stdout: stdout carries exactly one line, the+ # report, so the Node side parses it without scanning for it.+ def progress(done, total):+ if done == total or done % 25 == 0:+ print(f"encoded {done}/{total}", file=sys.stderr, flush=True)++ train_encoded = encode_corpus(state, train_rows, cache_dir, args.revision, progress)+ gold_encoded = encode_corpus(state, gold_rows, cache_dir, args.revision, progress)++ head_model, hidden_size, final_loss = fit_head(+ train_encoded, torch,+ architecture=args.architecture, hidden=args.hidden, epochs=args.epochs, seed=args.seed,+ )++ metrics = {+ "trained": head_accuracy(head_model, gold_encoded, torch),+ "stockZeroShot": stock_accuracy(gold_encoded, torch),+ "majorityClass": majority_accuracy(gold_encoded),+ "goldSize": len(gold_encoded),+ "trainSize": len(train_encoded),+ }++ head = {+ "schemaVersion": HEAD_SCHEMA_VERSION,+ "decisionId": args.decision_id,+ "architecture": args.architecture,+ "pooling": POOLING,+ "baseModel": {"id": args.model_id, "repository": args.repository, "revision": args.revision},+ "hiddenSize": hidden_size,+ "labels": list(LABELS),+ "layers": serialize_layers(head_model, torch),+ "metrics": metrics,+ "corpusHash": args.corpus_hash,+ "corpusSources": [part for part in args.corpus_sources.split(",") if part],+ "trainedAt": datetime.now(timezone.utc).isoformat(),+ }+ out = Path(args.out)+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_text(json.dumps(head, separators=(",", ":")), encoding="utf-8")++ emit({"ok": True, "metrics": metrics, "finalLoss": final_loss, "device": device})+ return 0+++if __name__ == "__main__":+ try:+ raise SystemExit(main())+ except KeyboardInterrupt:+ raise SystemExit(0)+ except Exception: # noqa: BLE001 - CLI boundary must fail closed without leaking input or paths.+ emit({"ok": False, "code": "jev-head-training-failed"})+ raise SystemExit(1)diff --git a/server/lib/README.md b/server/lib/README.mdindex ac107a0104..0fdf13d263 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -503,6 +503,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `localPersistentMindRecommendation.js` | CPU-only / low-RAM Persistent Mind defaults (Grok-box path): recommended Ollama + Qwen2.5 7B instruct profile, model aliases, and host gates so GPU coding-agent presets are not steered here. Pure. || `jev.js` | Pinned local entailment ("jev") contract: the `JEV_MODEL` descriptor (repo, revision, `qwen3.5-4b-nli` subfolder, MIT/ungated), the four-file required allowlist, pinned Python packages, `JEV_STAGES` / `jevStageReadiness()` for the operator install checklist, the premise/hypothesis bounds, the `jevScoreRequestSchema` / `jevScoreResponseSchema` wire pair, `normalizeJevScores` (rejects a reply describing a different hypothesis list), and `decideFromScores` — the margin arithmetic that ABSTAINS rather than picking a near-tie. Pure. Lifecycle is `services/jev.js`; see [docs/JEV_SETUP.md](../../docs/JEV_SETUP.md). || `jevDecisions.js` | `JEV_DECISIONS` — the closed-set decisions PortOS may answer with the local scorer instead of a chat completion, each with its frozen hypothesis wording and its abstention floor. `getJevDecision` / `jevHypotheses` / `jevValueForHypothesis` map between an enum value and the hypothesis that stands for it; `jevMinMarginFor` composes the per-decision floor, the per-OPTION floor (a destructive `delete` clears a far wider margin than the `archive` beside it), and the operator setting, which can only RAISE the bar. `isValidJevDecision` is the contract every shipped descriptor is tested against. `source` names the ingress CHANNEL and is `null` for a decision that has none (`scope-adherence` asks about the operator's own product documents). Pure. Routing, mode resolution and the counts-only agreement store live in `services/jevRouter.js`. |+| `jevCorpus.js` | The weakly-labelled training corpus a project-specific jev head is fit on, in open-jev Route A shape (`{context, options, label}`) so `openjev eval` stays usable as an independent cross-check. `splitCorpus` assigns train/gold by the example's own content hash — deterministic across machines and rebuilds — and `assertSplitDisjoint` REFUSES a split whose halves share a key or whose gold set is too small to separate three numbers. `dedupeCorpus` drops the duplicate question a goal re-stated across PRD.md and GOALS.md produces, which is contamination arriving through the front door. Also `corpusHash` (order-independent), `majorityClassAccuracy` (one of the two adoption baselines) and `summarizeCorpusSources`. Pure; the forge reads live in `services/jevCorpusBuilder.js`. |+| `jevHead.js` | The artifact contract for a project-specific head trained on the FROZEN jev encoder: `jevHeadSchema` + `parseJevHead` (shape, chained layer widths, a bounded parameter count so weights stay inspectable JSON), `isHeadCompatible` (exact encoder-revision equality — a different checkpoint is a different vector space), and THE ADOPTION GATE, `headBeatsBaselines` / `headAdoptionBlocker`: a head must beat BOTH the stock zero-shot classifier and the majority class on the held-out gold set, strictly, or it cannot be adopted through any surface. A head emits the checkpoint's own three labels, so every abstention floor downstream is unchanged. Also `JEV_HEAD_SLUG` and the train/adopt route schemas. Pure; the store is `services/jevHeads.js`. || `prdClauses.js` | Chops `PRD.md` / `GOALS.md` into addressable clauses — one per paragraph, top-level list item, blockquote or table data row — each carrying its heading path, source file and line. Clause ids are `<file>#<heading-slug>:<content-hash>` with NO line number and NO document ordinal, so a clause keeps its id when an unrelated paragraph is inserted above it. `indexClausesById` / `formatClauseCitation` render a verdict back to a citation a human can go read. Pure; the files are read by `services/scopeAdherence.js`. || `scopeAdherence.js` | The retrieval and premise half of "does this change advance the stated product goal?" — the QUESTION itself is the `scope-adherence` entry in `jevDecisions.js`. `selectCandidateClauses` fuses two BM25 views of the change (prose, changed files) with `fuseRankingsRRF`, so scoring is bounded by k rather than the whole corpus; `buildClauseIndex` is exported so a caller can cache the index beside the corpus. `formatChangeEvidence` builds the change half ONCE — the same string is screened and scored, so the two cannot drift — and `composeAdherencePremise` puts the clause first and in full. Also the route-input `scopeAdherenceRequestSchema`. ADVISORY ONLY: nothing here returns a gateable boolean. Pure; the ladder lives in `services/scopeAdherence.js`. || `scopeAdherenceReasons.js` | Operator-facing labels for the codes `scoreAdherence` returns instead of a verdict: `SCOPE_ADHERENCE_REASONS`, `SCOPE_ADHERENCE_REASON_FALLBACK`, and `scopeAdherenceReasonLabel(code, fallback?)` (own-property lookup, so a code naming an `Object.prototype` key cannot render as a function). Re-exported by `client/src/lib/scopeAdherenceReasons.js` rather than mirrored — a mirror would need a parity test, and that would need the server→client import `scripts/server-imports-no-client.test.js` forbids. Keep it import-free so it stays bundleable. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 6e11a01f25..26319ddf1d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -462,7 +462,9 @@ export * from './huggingfaceModel.js';export * from './localLlmCatalog.js';export * from './localPersistentMindRecommendation.js';export * from './jev.js';+export * from './jevCorpus.js';export * from './jevDecisions.js';+export * from './jevHead.js';export * from './prdClauses.js';export * from './scopeAdherence.js';export * from './scopeAdherenceReasons.js';diff --git a/server/lib/jev.js b/server/lib/jev.jsindex bff15a8567..e1ca4a698a 100644--- a/server/lib/jev.js+++ b/server/lib/jev.js@@ -174,6 +174,16 @@ export const JEV_SIDECAR_FAILURE_CODES = Object.freeze(['jev-request-invalid','jev-response-invalid','jev-premise-too-large',+ // A trained project head the sidecar could not apply. Forwarded rather than+ // collapsed, and deliberately NOT answered by silently falling back to the+ // stock classifier: the operator adopted a head on the strength of three+ // measured numbers, and answering with a different classifier would make+ // that measurement describe something other than what ran.+ 'jev-head-not-found',+ 'jev-head-invalid',+ 'jev-head-too-large',+ 'jev-head-unreadable',+ 'jev-head-revision-mismatch',]);export const JEV_FAILURE_CODES = Object.freeze([diff --git a/server/lib/jevCorpus.js b/server/lib/jevCorpus.jsnew file mode 100644index 0000000000..acfaac372b--- /dev/null+++ b/server/lib/jevCorpus.js@@ -0,0 +1,248 @@+/**+ * The training corpus a project-specific jev head is fit on.+ *+ * Schema is daseinlabs/open-jev's **Route A**: one JSON object per line,+ * `{"context": str, "options": [str, ...], "label": int}`, where `label`+ * indexes `options`. Adopted deliberately rather than invented — it keeps+ * `openjev eval` usable as an independent cross-check on a corpus PortOS+ * built, which is the only outside opinion available on whether a head that+ * beat our baselines actually learned anything.+ *+ * ## What the labels are worth+ *+ * They are WEAK. A merged pull request is evidence that the maintainer wanted+ * it, not a hand-annotation that it advances the clause the retriever paired it+ * with; a closed-unmerged one is evidence they did not. The whole apparatus+ * downstream — a held-out gold split, two baselines, a strictly-better+ * adoption gate — exists because these labels are weak enough that "the head+ * trained fine" proves nothing on its own.+ *+ * ## The split is the safety property+ *+ * `splitCorpus` assigns each example to train or gold by hashing its own+ * content, so the split is deterministic across machines and rebuilds, and an+ * example cannot migrate between splits when the corpus grows around it.+ * `assertSplitDisjoint` then REFUSES a split whose two halves share an example+ * key. A gold set contaminated by its training split reports a score that is+ * partly memorization, and that score is the single number the adoption gate+ * reads — so the refusal is a hard stop, never a warning.+ *+ * Pure: no I/O, no forge access. `services/jevCorpusBuilder.js` runs the+ * queries and writes the file.+ */++import { createHash } from 'crypto';+import { z } from 'zod';++export const JEV_CORPUS_SCHEMA_VERSION = 1;++/**+ * Bounds on one example. `context` is a composed premise, so it inherits the+ * scorer's premise budget; the option list inherits the decision's.+ */+export const JEV_CORPUS_MAX_CONTEXT_CHARS = 32_000;+export const JEV_CORPUS_MAX_OPTIONS = 32;++/**+ * The share of examples held out for the gold set.+ *+ * A third, not the customary tenth: these corpora are small (a few hundred+ * examples on a busy repository, far fewer on a young one), and the gold set+ * has to separate three numbers that may differ by a few points. A 10% split of+ * 200 examples is 20 rows, where one flipped label moves accuracy 5 points.+ */+export const JEV_CORPUS_GOLD_FRACTION = 1 / 3;++/**+ * The fewest examples a corpus may have and still be trained on.+ *+ * Below this the gold set cannot support a comparison against two baselines+ * at all, and the honest answer is "this install has no history to learn+ * from", not a head with a score.+ */+export const JEV_CORPUS_MIN_EXAMPLES = 60;++/** The weak-evidence sources a corpus may draw from. */+export const JEV_CORPUS_SOURCES = Object.freeze([+ 'merged-pr',+ 'closed-unmerged-pr',+ 'closed-not-planned-issue',+ 'parked-issue',+]);++export const jevCorpusExampleSchema = z.object({+ context: z.string().min(1).max(JEV_CORPUS_MAX_CONTEXT_CHARS),+ options: z.array(z.string().min(1)).min(2).max(JEV_CORPUS_MAX_OPTIONS),+ label: z.number().int().min(0),+ // PortOS's own provenance, ignored by `openjev eval`. Kept so a corpus can be+ // audited for source balance without re-running the forge queries.+ source: z.enum(JEV_CORPUS_SOURCES),+}).strict().refine((row) => row.label < row.options.length, { path: ['label'] });++/**+ * A stable identity for one example.+ *+ * Content-addressed, and covering the OPTIONS as well as the context: the same+ * change scored against the same clause under a different option wording is a+ * different question, and collapsing the two would let a re-worded decision+ * silently inherit the old split assignment.+ */+export function corpusExampleKey(example) {+ return createHash('sha256')+ .update(String(example?.context || ''))+ .update('\u0000')+ .update((example?.options || []).join('\u0000'))+ .digest('hex')+ .slice(0, 32);+}++/**+ * Hash of the whole corpus, order-independent.+ *+ * Recorded on both the manifest and every head fit from it. Order-independent+ * because the builder's forge queries are paginated and a page boundary moving+ * must not re-key a corpus that contains exactly the same examples.+ */+export function corpusHash(examples) {+ const keys = (Array.isArray(examples) ? examples : [])+ .map((example) => `${corpusExampleKey(example)}:${example?.label}`)+ .sort();+ return createHash('sha256').update(keys.join('\n')).digest('hex').slice(0, 32);+}++/**+ * Turn a weakly-labelled observation into a Route A example.+ *+ * `options` is the decision's own hypothesis list, in its own order, so a+ * corpus row asks exactly the question the scorer is asked at inference time.+ * Returns null rather than throwing on anything malformed — the builder pulls+ * from a forge, and one unusable row must not fail a build of four hundred.+ */+export function buildCorpusExample({ context, options, chosen, source } = {}) {+ if (!Array.isArray(options)) return null;+ const label = options.indexOf(chosen);+ if (label < 0) return null;+ const candidate = { context: String(context || '').slice(0, JEV_CORPUS_MAX_CONTEXT_CHARS), options, label, source };+ return jevCorpusExampleSchema.safeParse(candidate).success ? candidate : null;+}++/**+ * Drop examples that ask the same question twice.+ *+ * A repository re-states a goal across `PRD.md` and `GOALS.md` often enough+ * that the retriever pairs one change with two byte-identical clauses. Left in,+ * those duplicates land in different splits by definition of the hash — the+ * same question appearing in both train and gold, which is precisely the+ * contamination `assertSplitDisjoint` exists to catch, arriving through the+ * front door. The FIRST label wins; a duplicate that disagrees is dropped with+ * it, because there is no principled way to pick between two weak labels.+ */+export function dedupeCorpus(examples) {+ const seen = new Map();+ for (const example of Array.isArray(examples) ? examples : []) {+ const key = corpusExampleKey(example);+ if (!seen.has(key)) seen.set(key, example);+ }+ return [...seen.values()];+}++/**+ * Deterministic train/gold split.+ *+ * The bucket comes from the example's OWN content hash, not from a shuffle and+ * not from its position: two builds of the same corpus on two machines must+ * produce the same gold set, or a head's reported score cannot be reproduced by+ * the person reading it.+ */+export function splitCorpus(examples, { goldFraction = JEV_CORPUS_GOLD_FRACTION } = {}) {+ const rows = dedupeCorpus(examples);+ const train = [];+ const gold = [];+ // 16 bits of the key, compared against the same fraction of 65536. Enough+ // resolution that a corpus of a few hundred lands within a point of the+ // requested fraction, and cheap to recompute anywhere.+ const cutoff = Math.round(goldFraction * 0x10000);+ for (const example of rows) {+ const bucket = parseInt(corpusExampleKey(example).slice(0, 4), 16);+ (bucket < cutoff ? gold : train).push(example);+ }+ return { train, gold };+}++/**+ * REFUSE a split whose halves overlap.+ *+ * The gold score is the only evidence the adoption gate reads. An example that+ * appears in both halves makes that score partly a memorization check, and+ * nothing downstream could tell the difference — the head would simply look+ * better than it is and get adopted for it.+ *+ * Also refuses a gold set too small to separate three numbers: with fewer than+ * `JEV_CORPUS_MIN_GOLD` rows, one label flip moves accuracy by more than the+ * margin the gate is deciding on.+ */+export const JEV_CORPUS_MIN_GOLD = 20;++export function assertSplitDisjoint({ train, gold } = {}) {+ if (!Array.isArray(train) || !Array.isArray(gold)) return { ok: false, code: 'jev-corpus-split-invalid' };+ const trainKeys = new Set(train.map(corpusExampleKey));+ const overlap = gold.filter((example) => trainKeys.has(corpusExampleKey(example)));+ if (overlap.length) return { ok: false, code: 'jev-corpus-split-overlap', overlap: overlap.length };+ if (gold.length < JEV_CORPUS_MIN_GOLD) return { ok: false, code: 'jev-corpus-gold-too-small' };+ if (!train.length) return { ok: false, code: 'jev-corpus-split-invalid' };+ return { ok: true, train: train.length, gold: gold.length };+}++/**+ * Accuracy of always predicting the most common gold label.+ *+ * One of the two baselines the adoption gate compares against, computed here+ * rather than in the trainer so the Node side can state it without a Python+ * round trip — and so the number an operator is shown comes from the same code+ * path in a test as it does in the panel.+ */+export function majorityClassAccuracy(gold) {+ const rows = Array.isArray(gold) ? gold : [];+ if (!rows.length) return null;+ const counts = new Map();+ for (const row of rows) counts.set(row.label, (counts.get(row.label) || 0) + 1);+ return Math.max(...counts.values()) / rows.length;+}++/** Per-source example counts, for the manifest and the panel's build summary. */+export function summarizeCorpusSources(examples) {+ const counts = Object.fromEntries(JEV_CORPUS_SOURCES.map((source) => [source, 0]));+ for (const example of Array.isArray(examples) ? examples : []) {+ if (Object.hasOwn(counts, example?.source)) counts[example.source] += 1;+ }+ return counts;+}++/** Serialize to JSONL. `source` is kept: it is ours, and `openjev eval` ignores it. */+export const toCorpusJsonl = (examples) => (Array.isArray(examples) ? examples : [])+ .map((example) => JSON.stringify(example))+ .join('\n');++/**+ * Validate one already-parsed JSONL row, or null.+ *+ * Takes an OBJECT, not a line of text: `JSON.parse` throws, and the sanctioned+ * non-throwing wrapper lives in `fileUtils.js`, whose closure reaches `fs` and+ * `child_process`. Keeping the decode in `services/jevCorpusBuilder.js` is what+ * lets this file stay the pure leaf it advertises itself as+ * (`server/lib/importScoping.test.js`).+ */+export function validateCorpusRow(parsed) {+ const result = jevCorpusExampleSchema.safeParse(parsed);+ return result.success ? result.data : null;+}++export const JEV_CORPUS_FAILURE_CODES = Object.freeze([+ 'jev-corpus-split-overlap',+ 'jev-corpus-split-invalid',+ 'jev-corpus-gold-too-small',+ 'jev-corpus-too-small',+ 'jev-corpus-forge-unavailable',+ 'jev-corpus-no-clauses',+ 'jev-corpus-unreadable',+]);diff --git a/server/lib/jevCorpus.test.js b/server/lib/jevCorpus.test.jsnew file mode 100644index 0000000000..270300e01a--- /dev/null+++ b/server/lib/jevCorpus.test.js@@ -0,0 +1,178 @@+import { describe, expect, it } from 'vitest';+import {+ assertSplitDisjoint,+ buildCorpusExample,+ corpusExampleKey,+ corpusHash,+ dedupeCorpus,+ JEV_CORPUS_GOLD_FRACTION,+ JEV_CORPUS_MIN_GOLD,+ majorityClassAccuracy,+ splitCorpus,+ summarizeCorpusSources,+ toCorpusJsonl,+ validateCorpusRow,+} from './jevCorpus.js';++const OPTIONS = ['advances the goal', 'unrelated to the goal', 'works against the goal'];++const example = (n, { chosen = OPTIONS[0], source = 'merged-pr' } = {}) => buildCorpusExample({+ context: `Stated product goal (GOALS.md#a:${n}):\nship things\n\nProposed change (issue):\nTitle: change ${n}`,+ options: OPTIONS,+ chosen,+ source,+});++const corpusOf = (count, options = {}) => Array.from({ length: count }, (_unused, index) => example(index, options));++describe('buildCorpusExample', () => {+ it('records the label as the index of the chosen option', () => {+ expect(example(1).label).toBe(0);+ expect(example(1, { chosen: OPTIONS[2] }).label).toBe(2);+ });++ // A forge read is paginated and untidy; one unusable row must not fail a+ // build of four hundred, so this returns null rather than throwing.+ it('returns null rather than throwing on an unusable row', () => {+ expect(buildCorpusExample({ context: 'x', options: OPTIONS, chosen: 'not an option', source: 'merged-pr' })).toBeNull();+ expect(buildCorpusExample({ context: '', options: OPTIONS, chosen: OPTIONS[0], source: 'merged-pr' })).toBeNull();+ expect(buildCorpusExample({ context: 'x', options: [OPTIONS[0]], chosen: OPTIONS[0], source: 'merged-pr' })).toBeNull();+ expect(buildCorpusExample({ context: 'x', options: OPTIONS, chosen: OPTIONS[0], source: 'invented' })).toBeNull();+ });+});++describe('corpusExampleKey', () => {+ // Re-wording a hypothesis makes it a different question. Collapsing the two+ // would let a re-worded decision silently inherit the old split assignment,+ // which is how a gold row becomes a training row without anybody moving it.+ it('changes when the options change, not only when the context does', () => {+ const base = example(1);+ const reworded = { ...base, options: [...OPTIONS.slice(0, 2), 'contradicts the goal'] };+ expect(corpusExampleKey(reworded)).not.toBe(corpusExampleKey(base));+ });++ it('is stable across two constructions of the same example', () => {+ expect(corpusExampleKey(example(7))).toBe(corpusExampleKey(example(7)));+ });+});++describe('corpusHash', () => {+ it('ignores example order', () => {+ const rows = corpusOf(5);+ expect(corpusHash([...rows].reverse())).toBe(corpusHash(rows));+ });++ // A relabelled corpus is a different corpus even when it holds the same+ // questions — otherwise a head could claim provenance from a build that never+ // taught it what it learned.+ it('changes when a label changes', () => {+ const rows = corpusOf(5);+ const relabelled = [{ ...rows[0], label: 1 }, ...rows.slice(1)];+ expect(corpusHash(relabelled)).not.toBe(corpusHash(rows));+ });+});++describe('splitCorpus', () => {+ it('is deterministic across repeated builds', () => {+ const rows = corpusOf(200);+ const first = splitCorpus(rows);+ const second = splitCorpus([...rows].reverse());+ expect(new Set(second.gold.map(corpusExampleKey))).toEqual(new Set(first.gold.map(corpusExampleKey)));+ });++ it('holds out roughly the requested fraction', () => {+ const { train, gold } = splitCorpus(corpusOf(600));+ expect(train.length + gold.length).toBe(600);+ expect(Math.abs(gold.length / 600 - JEV_CORPUS_GOLD_FRACTION)).toBeLessThan(0.08);+ });++ // A repository re-states a goal across PRD.md and GOALS.md often enough that+ // the retriever pairs one change with two identical clauses. Left in, the+ // same question lands in both splits by definition of the hash — the+ // contamination arriving through the front door.+ it('drops a duplicated question before it can land in both splits', () => {+ const rows = corpusOf(4);+ const { train, gold } = splitCorpus([...rows, ...rows]);+ expect(train.length + gold.length).toBe(4);+ });+});++describe('dedupeCorpus', () => {+ it('keeps the first label when a question appears twice with different labels', () => {+ const first = example(1);+ const disagreeing = { ...first, label: 2 };+ expect(dedupeCorpus([first, disagreeing])).toEqual([first]);+ });+});++describe('assertSplitDisjoint — the refusal', () => {+ it('accepts a clean split', () => {+ const { train, gold } = splitCorpus(corpusOf(300));+ expect(assertSplitDisjoint({ train, gold }).ok).toBe(true);+ });++ // THE acceptance criterion. A gold set sharing rows with the training split+ // reports a score that is partly memorization, and that score is the only+ // evidence the adoption gate reads.+ it('refuses a split whose gold set overlaps the training split', () => {+ const { train, gold } = splitCorpus(corpusOf(300));+ const contaminated = [...gold, train[0]];+ expect(assertSplitDisjoint({ train, gold: contaminated }))+ .toEqual({ ok: false, code: 'jev-corpus-split-overlap', overlap: 1 });+ });++ it('refuses a gold set too small to separate three numbers', () => {+ const rows = corpusOf(200);+ const { train } = splitCorpus(rows);+ const tiny = splitCorpus(corpusOf(6)).gold;+ expect(tiny.length).toBeLessThan(JEV_CORPUS_MIN_GOLD);+ expect(assertSplitDisjoint({ train, gold: tiny }).code).toBe('jev-corpus-gold-too-small');+ });++ it('refuses a split with no training rows at all', () => {+ const { gold } = splitCorpus(corpusOf(300));+ expect(assertSplitDisjoint({ train: [], gold }).code).toBe('jev-corpus-split-invalid');+ });++ it('refuses a malformed split rather than reading it as empty', () => {+ expect(assertSplitDisjoint({}).code).toBe('jev-corpus-split-invalid');+ });+});++describe('majorityClassAccuracy', () => {+ it('is the share of the most common label', () => {+ const rows = [...corpusOf(3), ...corpusOf(1, { chosen: OPTIONS[1] })];+ expect(majorityClassAccuracy(rows)).toBeCloseTo(0.75, 5);+ });++ // `null`, never 0: an install with no gold rows has no baseline, and 0 would+ // read as "a constant prediction gets everything wrong" — which would make+ // any head look adoptable.+ it('reports null rather than zero on an empty gold set', () => {+ expect(majorityClassAccuracy([])).toBeNull();+ });+});++describe('serialization', () => {+ it('round-trips through JSONL', () => {+ const rows = corpusOf(3);+ const parsed = toCorpusJsonl(rows).split('\n').map((line) => validateCorpusRow(JSON.parse(line)));+ expect(parsed).toEqual(rows);+ });++ it('rejects a row whose label points past its options', () => {+ expect(validateCorpusRow({ context: 'x', options: OPTIONS, label: 9, source: 'merged-pr' })).toBeNull();+ });+});++describe('summarizeCorpusSources', () => {+ it('counts every known source, including the ones with no rows', () => {+ const rows = [...corpusOf(2), ...corpusOf(1, { source: 'parked-issue', chosen: OPTIONS[1] })];+ expect(summarizeCorpusSources(rows)).toEqual({+ 'merged-pr': 2,+ 'closed-unmerged-pr': 0,+ 'closed-not-planned-issue': 0,+ 'parked-issue': 1,+ });+ });+});diff --git a/server/lib/jevHead.js b/server/lib/jevHead.jsnew file mode 100644index 0000000000..349eed93f7--- /dev/null+++ b/server/lib/jevHead.js@@ -0,0 +1,267 @@+/**+ * Static contract for a PROJECT-SPECIFIC trained head on the frozen jev encoder.+ *+ * Phase 1 of scope adherence (#7643) scores a change against the repository's+ * own `PRD.md` / `GOALS.md` clauses with the checkpoint's stock zero-shot NLI+ * classifier. This module describes the optional alternative: a small head fit+ * on THIS install's history, sitting on the same frozen encoder.+ *+ * Three properties are load-bearing and none of them is negotiable:+ *+ * 1. **The head emits the checkpoint's OWN three labels.** `JEV_LABELS`, in+ * that order. Everything downstream — `normalizeJevScores`,+ * `decideFromScores`, every per-option abstention floor in+ * `jevDecisions.js` — is byte-identical whether a head is adopted or not.+ * A head changes which numbers come out of the encoder, never what the+ * numbers mean or what may be decided from them.+ * 2. **A head names the encoder revision it was fit on.** Embeddings from a+ * different checkpoint are a different vector space; a head applied across+ * one would produce confident nonsense with nothing to signal it. The+ * loader refuses a mismatch rather than degrading.+ * 3. **A head cannot be adopted unless it beats BOTH baselines** on the+ * held-out gold set — the stock zero-shot classifier AND the majority+ * class. Beating only the majority class means it learned the label prior;+ * beating only zero-shot on a corpus whose prior it memorized means the+ * same thing from the other side.+ *+ * A head is also a DERIVED RECORD OF PRIVATE DATA: it encodes the operator's+ * merged pull requests, closed issues and their own judgement calls. Weights+ * live under `data/jev/` and are machine-local — see the ADR+ * [privacy records machine-local](../../docs/decisions/2026-08-08-privacy-records-machine-local.md).+ *+ * Pure: no I/O, no process state. `services/jevHeads.js` owns the files.+ */++import { z } from 'zod';+import { JEV_LABELS } from './jev.js';+import { JEV_DECISION_IDS } from './jevDecisions.js';++export const JEV_HEAD_SCHEMA_VERSION = 1;++/**+ * Architectures a head may declare.+ *+ * `linear` is the default and the honest one: a 3-way logistic regression over+ * a frozen 4B encoder's pooled state. `mlp1` buys one hidden layer for a+ * corpus large enough to support it. Nothing deeper ships — the issue's own+ * out-of-scope list rules out touching the encoder, and a deep head on a few+ * hundred weak labels is a memorizer with a validation score.+ */+export const JEV_HEAD_ARCHITECTURES = Object.freeze(['linear', 'mlp1']);++/**+ * Hard ceiling on a head's parameter count.+ *+ * Weights ship as JSON so the compatibility check, the backup retention+ * decision and code review are all inspectable without a numpy import. That+ * only stays true while the artifact is small: 2M parameters is ~40 MB of+ * JSON, which is already past "inspectable" and far past anything a few+ * hundred weakly-labelled examples can fit. A trainer that wants more is+ * asking the wrong question.+ */+export const JEV_HEAD_MAX_PARAMS = 2_000_000;++/** Hidden width `mlp1` may declare. Bounded for the same reason. */+export const JEV_HEAD_MAX_HIDDEN = 256;++/**+ * The pooling both sides must agree on.+ *+ * openjev's 4B NLI checkpoint is a causal decoder, so the LAST non-padding+ * token is the only position that has attended to the whole pair. Declared in+ * the artifact rather than assumed, so a future pooling change makes an old+ * head unloadable instead of silently re-pooled — `scripts/jev_head_kit.py`+ * mirrors this string and refuses one it does not implement.+ */+export const JEV_HEAD_POOLING = 'last-token';++/**+ * The charset a head's on-disk slug may use.+ *+ * A head is addressed by SLUG — its decision id — and the sidecar resolves that+ * slug inside a directory the Node service owns. A slug is not a path, and this+ * is what keeps it from becoming one. `jevHead.test.js` asserts every shipped+ * decision id satisfies it, so a future decision named with a colon or a slash+ * fails at test time rather than at the first adoption.+ */+export const JEV_HEAD_SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;++const finite = () => z.number().finite();+const vector = () => z.array(finite()).min(1);++const layerSchema = z.object({+ // Row-major `[out][in]`, matching `numpy.dot(weight, x) + bias`.+ weight: z.array(vector()).min(1),+ bias: vector(),+}).strict();++/**+ * The three numbers an operator is shown before adopting anything, and the+ * three the adoption gate reads. All are accuracy on the SAME held-out gold+ * split, so they are directly comparable.+ */+export const jevHeadMetricsSchema = z.object({+ trained: z.number().min(0).max(1),+ stockZeroShot: z.number().min(0).max(1),+ majorityClass: z.number().min(0).max(1),+ goldSize: z.number().int().min(1),+ trainSize: z.number().int().min(1),+}).strict();++export const jevHeadSchema = z.object({+ schemaVersion: z.literal(JEV_HEAD_SCHEMA_VERSION),+ decisionId: z.enum(JEV_DECISION_IDS),+ architecture: z.enum(JEV_HEAD_ARCHITECTURES),+ pooling: z.literal(JEV_HEAD_POOLING),+ // The frozen encoder this head's input space belongs to. `revision` is the+ // gate; the other two are for the operator reading the panel.+ baseModel: z.object({+ id: z.string().min(1),+ repository: z.string().min(1),+ revision: z.string().min(1),+ }).strict(),+ // Declared, then checked against the first layer: a head whose stated input+ // width disagrees with its own weights would fail deep inside a forward pass.+ hiddenSize: z.number().int().min(1),+ labels: z.array(z.enum(JEV_LABELS)).length(JEV_LABELS.length),+ layers: z.array(layerSchema).min(1).max(2),+ metrics: jevHeadMetricsSchema,+ // Which corpus produced it, so a head can be traced back to a build without+ // the corpus itself having to survive.+ corpusHash: z.string().min(8),+ corpusSources: z.array(z.string().min(1)).min(1),+ trainedAt: z.string().min(1),+}).strict();++/** Total scalar parameters in `layers`. */+export function countHeadParams(head) {+ if (!Array.isArray(head?.layers)) return 0;+ return head.layers.reduce((total, layer) => {+ const rows = Array.isArray(layer?.weight) ? layer.weight : [];+ const cells = rows.reduce((sum, row) => sum + (Array.isArray(row) ? row.length : 0), 0);+ return total + cells + (Array.isArray(layer?.bias) ? layer.bias.length : 0);+ }, 0);+}++/**+ * Validate a head artifact's SHAPE — schema, dimensions, size bound.+ *+ * Separate from `isHeadCompatible` on purpose: a structurally broken head is a+ * trainer bug an operator cannot fix, while an incompatible one is a correct+ * artifact for a different encoder. They point at opposite remedies, so they+ * report different codes.+ */+export function parseJevHead(raw) {+ const result = jevHeadSchema.safeParse(raw);+ if (!result.success) return { ok: false, code: 'jev-head-invalid' };+ const head = result.data;+ if (head.labels.join('\u0000') !== JEV_LABELS.join('\u0000')) return { ok: false, code: 'jev-head-invalid' };++ const first = head.layers[0];+ if (first.weight.some((row) => row.length !== head.hiddenSize)) return { ok: false, code: 'jev-head-invalid' };+ // Every layer's bias must be one entry per output row, and each layer's+ // output width must be the next layer's input width.+ for (const [position, layer] of head.layers.entries()) {+ if (layer.bias.length !== layer.weight.length) return { ok: false, code: 'jev-head-invalid' };+ const next = head.layers[position + 1];+ if (next && next.weight.some((row) => row.length !== layer.weight.length)) return { ok: false, code: 'jev-head-invalid' };+ }+ const last = head.layers.at(-1);+ if (last.weight.length !== JEV_LABELS.length) return { ok: false, code: 'jev-head-invalid' };+ if (head.architecture === 'linear' && head.layers.length !== 1) return { ok: false, code: 'jev-head-invalid' };+ if (head.architecture === 'mlp1') {+ if (head.layers.length !== 2) return { ok: false, code: 'jev-head-invalid' };+ if (head.layers[0].weight.length > JEV_HEAD_MAX_HIDDEN) return { ok: false, code: 'jev-head-invalid' };+ }+ if (countHeadParams(head) > JEV_HEAD_MAX_PARAMS) return { ok: false, code: 'jev-head-too-large' };+ return { ok: true, head };+}++/**+ * Whether a head may be applied on this machine's installed encoder.+ *+ * Revision equality, not "close enough". The head's inputs are hidden states+ * from one specific checkpoint; a different revision is a different vector+ * space, and applying a head across one yields confident numbers with nothing+ * anywhere to signal that they are meaningless.+ */+export function isHeadCompatible(head, { repository, revision } = {}) {+ if (!head?.baseModel) return false;+ return head.baseModel.revision === revision && head.baseModel.repository === repository;+}++/**+ * THE ADOPTION GATE.+ *+ * A trained head is worth running only if it beats the stock zero-shot+ * classifier AND the majority-class baseline on the held-out gold set. Both,+ * strictly.+ *+ * Beating only the majority class means it learned the label prior and nothing+ * about the product. Beating only zero-shot, while losing to a constant+ * prediction, means the gold split is so skewed that accuracy is not measuring+ * anything — a head that "wins" there would be adopted on the strength of the+ * corpus's imbalance. Ties lose: the stock classifier needs no corpus, no+ * training run, and no privacy argument, so it wins every draw.+ */+export function headBeatsBaselines(metrics) {+ const parsed = jevHeadMetricsSchema.safeParse(metrics);+ if (!parsed.success) return false;+ const { trained, stockZeroShot, majorityClass } = parsed.data;+ return trained > stockZeroShot && trained > majorityClass;+}++/**+ * The one-line verdict the panel renders beside the numbers.+ *+ * Returns the reason a head is NOT adoptable, or `null` when it is. Naming the+ * losing baseline matters: "did not beat the stock scorer" and "did not beat+ * always guessing the most common label" send an operator to different places.+ */+export function headAdoptionBlocker(metrics) {+ const parsed = jevHeadMetricsSchema.safeParse(metrics);+ if (!parsed.success) return 'jev-head-metrics-invalid';+ const { trained, stockZeroShot, majorityClass } = parsed.data;+ if (trained <= stockZeroShot) return 'jev-head-below-zero-shot';+ if (trained <= majorityClass) return 'jev-head-below-majority-class';+ return null;+}++/**+ * Route input for starting a training run.+ *+ * Validated from HERE rather than through `lib/validation.js`, for the same+ * reason `jevScoreRequestSchema` is: re-exporting a one-route schema through+ * that barrel drags this module into the static import closure of every suite+ * that reaches it (`server/lib/importScoping.test.js`).+ *+ * `.strict()`, and deliberately carrying NO repository path: a head is trained+ * on THIS install's own checkout, and a client-supplied path would turn a+ * training button into an arbitrary-directory reader with a `gh` token beside+ * it. Same reasoning as `scopeAdherenceRequestSchema`.+ */+export const jevHeadTrainRequestSchema = z.object({+ architecture: z.enum(JEV_HEAD_ARCHITECTURES).optional(),+}).strict();++/** Route input for adopting or discarding an artifact. */+export const jevHeadActionRequestSchema = z.object({+ decisionId: z.enum(JEV_DECISION_IDS),+ // Which artifact to discard. Ignored by adoption, which only ever promotes a+ // candidate.+ adopted: z.boolean().optional(),+}).strict();++/** Every failure the head store, trainer and loader can report. */+export const JEV_HEAD_FAILURE_CODES = Object.freeze([+ 'jev-head-invalid',+ 'jev-head-too-large',+ 'jev-head-revision-mismatch',+ 'jev-head-not-found',+ 'jev-head-below-zero-shot',+ 'jev-head-below-majority-class',+ 'jev-head-metrics-invalid',+ 'jev-head-unreadable',+ 'jev-head-training-failed',+ 'jev-head-runtime-unavailable',+]);diff --git a/server/lib/jevHead.test.js b/server/lib/jevHead.test.jsnew file mode 100644index 0000000000..5bf09acfd3--- /dev/null+++ b/server/lib/jevHead.test.js@@ -0,0 +1,195 @@+import { describe, expect, it } from 'vitest';+import { JEV_LABELS } from './jev.js';+import { JEV_DECISION_IDS } from './jevDecisions.js';+import {+ countHeadParams,+ headAdoptionBlocker,+ headBeatsBaselines,+ isHeadCompatible,+ JEV_HEAD_MAX_HIDDEN,+ JEV_HEAD_POOLING,+ JEV_HEAD_SCHEMA_VERSION,+ JEV_HEAD_SLUG,+ jevHeadActionRequestSchema,+ jevHeadTrainRequestSchema,+ parseJevHead,+} from './jevHead.js';++const BASE = { id: 'openjev-qwen3.5-4b-nli', repository: 'AlexWortega/openjev', revision: 'abc123' };++const linearHead = (overrides = {}) => ({+ schemaVersion: JEV_HEAD_SCHEMA_VERSION,+ decisionId: 'scope-adherence',+ architecture: 'linear',+ pooling: JEV_HEAD_POOLING,+ baseModel: { ...BASE },+ hiddenSize: 4,+ labels: [...JEV_LABELS],+ layers: [{+ weight: [[0.1, 0.2, 0.3, 0.4], [1, 0, 0, 0], [0, 1, 0, 0]],+ bias: [0, 0.5, -0.5],+ }],+ metrics: { trained: 0.71, stockZeroShot: 0.58, majorityClass: 0.52, goldSize: 40, trainSize: 120 },+ corpusHash: 'deadbeefcafe0001',+ corpusSources: ['merged-pr'],+ trainedAt: '2026-09-19T00:00:00.000Z',+ ...overrides,+});++describe('parseJevHead', () => {+ it('accepts a well-formed linear head', () => {+ const result = parseJevHead(linearHead());+ expect(result.ok).toBe(true);+ expect(countHeadParams(result.head)).toBe(15);+ });++ it('accepts a two-layer mlp1 head whose widths chain', () => {+ const result = parseJevHead(linearHead({+ architecture: 'mlp1',+ layers: [+ { weight: [[1, 0, 0, 0], [0, 1, 0, 0]], bias: [0, 0] },+ { weight: [[1, 0], [0, 1], [1, 1]], bias: [0, 0, 0] },+ ],+ }));+ expect(result.ok).toBe(true);+ });++ // The failure this rejects is silent otherwise: a head whose DECLARED input+ // width disagrees with its own first layer would fail deep inside a forward+ // pass, on a machine, with a Python traceback the operator never sees.+ it('rejects a head whose declared hiddenSize does not match its weights', () => {+ expect(parseJevHead(linearHead({ hiddenSize: 8 }))).toEqual({ ok: false, code: 'jev-head-invalid' });+ });++ it('rejects a head whose layer widths do not chain', () => {+ expect(parseJevHead(linearHead({+ architecture: 'mlp1',+ layers: [+ { weight: [[1, 0, 0, 0], [0, 1, 0, 0]], bias: [0, 0] },+ // Three inputs, but the layer above emits two.+ { weight: [[1, 0, 0], [0, 1, 0], [1, 1, 0]], bias: [0, 0, 0] },+ ],+ })), 'a mismatched chain must not parse').toEqual({ ok: false, code: 'jev-head-invalid' });+ });++ // The output width IS the label contract. A head emitting two logits would+ // make `decideFromScores` read a neutral probability as an entailment one.+ it('rejects a head whose final layer does not emit one logit per label', () => {+ expect(parseJevHead(linearHead({+ layers: [{ weight: [[0.1, 0.2, 0.3, 0.4], [1, 0, 0, 0]], bias: [0, 0] }],+ }))).toEqual({ ok: false, code: 'jev-head-invalid' });+ });++ it('rejects relabelled or reordered labels', () => {+ expect(parseJevHead(linearHead({ labels: ['entailment', 'contradiction', 'neutral'] })))+ .toEqual({ ok: false, code: 'jev-head-invalid' });+ });++ it('rejects an mlp1 hidden layer wider than the bound', () => {+ const wide = JEV_HEAD_MAX_HIDDEN + 1;+ expect(parseJevHead(linearHead({+ architecture: 'mlp1',+ layers: [+ { weight: Array.from({ length: wide }, () => [1, 0, 0, 0]), bias: Array.from({ length: wide }, () => 0) },+ { weight: Array.from({ length: 3 }, () => Array.from({ length: wide }, () => 0)), bias: [0, 0, 0] },+ ],+ }))).toEqual({ ok: false, code: 'jev-head-invalid' });+ });++ it('rejects a linear head that ships two layers', () => {+ expect(parseJevHead(linearHead({+ layers: [+ { weight: [[1, 0, 0, 0], [0, 1, 0, 0]], bias: [0, 0] },+ { weight: [[1, 0], [0, 1], [1, 1]], bias: [0, 0, 0] },+ ],+ }))).toEqual({ ok: false, code: 'jev-head-invalid' });+ });++ it('rejects an unknown key rather than dropping it', () => {+ expect(parseJevHead({ ...linearHead(), adopted: true })).toEqual({ ok: false, code: 'jev-head-invalid' });+ });+});++describe('isHeadCompatible', () => {+ it('accepts the exact pinned revision', () => {+ expect(isHeadCompatible(linearHead(), BASE)).toBe(true);+ });++ // Embeddings from another checkpoint are another vector space. A head applied+ // across one produces confident numbers with nothing anywhere to signal they+ // are meaningless, which is strictly worse than no head at all.+ it('refuses a head fit on a different encoder revision', () => {+ expect(isHeadCompatible(linearHead(), { ...BASE, revision: 'other' })).toBe(false);+ });++ it('refuses a head fit on a different repository at the same revision', () => {+ expect(isHeadCompatible(linearHead(), { ...BASE, repository: 'someone/else' })).toBe(false);+ });+});++describe('the adoption gate', () => {+ it('adopts only a head that beats BOTH baselines', () => {+ expect(headBeatsBaselines(linearHead().metrics)).toBe(true);+ expect(headAdoptionBlocker(linearHead().metrics)).toBeNull();+ });++ it('refuses a head that beats the majority class but not stock zero-shot', () => {+ const metrics = { trained: 0.60, stockZeroShot: 0.66, majorityClass: 0.52, goldSize: 40, trainSize: 120 };+ expect(headBeatsBaselines(metrics)).toBe(false);+ expect(headAdoptionBlocker(metrics)).toBe('jev-head-below-zero-shot');+ });++ // The skew case the second baseline exists for: on a corpus that is 80% one+ // label, a head can beat a weak zero-shot classifier while still losing to a+ // constant prediction — and would otherwise be adopted on the strength of the+ // corpus's imbalance.+ it('refuses a head that beats stock zero-shot but not the majority class', () => {+ const metrics = { trained: 0.74, stockZeroShot: 0.61, majorityClass: 0.80, goldSize: 40, trainSize: 120 };+ expect(headBeatsBaselines(metrics)).toBe(false);+ expect(headAdoptionBlocker(metrics)).toBe('jev-head-below-majority-class');+ });++ // Ties lose. The stock classifier needs no corpus, no training run and no+ // privacy argument, so a draw is not a reason to adopt anything.+ it('refuses an exact tie with either baseline', () => {+ expect(headBeatsBaselines({ trained: 0.6, stockZeroShot: 0.6, majorityClass: 0.5, goldSize: 40, trainSize: 120 })).toBe(false);+ expect(headBeatsBaselines({ trained: 0.6, stockZeroShot: 0.5, majorityClass: 0.6, goldSize: 40, trainSize: 120 })).toBe(false);+ });++ it('refuses metrics it cannot read at all', () => {+ expect(headBeatsBaselines({ trained: 0.9 })).toBe(false);+ expect(headAdoptionBlocker(null)).toBe('jev-head-metrics-invalid');+ });+});++describe('head slugs', () => {+ // A head is addressed by slug and resolved inside a directory the Node+ // service owns. A decision id with a colon or a slash would make the slug a+ // path; this is what makes that a test failure rather than a runtime one.+ it('every shipped decision id is a usable slug', () => {+ expect(JEV_DECISION_IDS.length).toBeGreaterThan(1);+ for (const id of JEV_DECISION_IDS) expect(`${id}:${JEV_HEAD_SLUG.test(id)}`).toBe(`${id}:true`);+ });++ it('rejects a slug that would escape the heads directory', () => {+ for (const bad of ['../escape', 'a/b', 'UPPER', '.hidden', '']) {+ expect(`${bad}:${JEV_HEAD_SLUG.test(bad)}`).toBe(`${bad}:false`);+ }+ });+});++describe('route schemas', () => {+ // No `repoPath`, ever: a client-supplied checkout would turn a training+ // button into an arbitrary-directory reader with a forge token beside it.+ it('the train request accepts only an architecture', () => {+ expect(jevHeadTrainRequestSchema.safeParse({}).success).toBe(true);+ expect(jevHeadTrainRequestSchema.safeParse({ architecture: 'mlp1' }).success).toBe(true);+ expect(jevHeadTrainRequestSchema.safeParse({ repoPath: '/etc' }).success).toBe(false);+ expect(jevHeadTrainRequestSchema.safeParse({ architecture: 'transformer' }).success).toBe(false);+ });++ it('the action request accepts only a known decision id', () => {+ expect(jevHeadActionRequestSchema.safeParse({ decisionId: 'scope-adherence' }).success).toBe(true);+ expect(jevHeadActionRequestSchema.safeParse({ decisionId: 'made-up' }).success).toBe(false);+ });+});diff --git a/server/lib/scopeAdherenceReasons.js b/server/lib/scopeAdherenceReasons.jsindex 123bbb170e..d5ec91da0d 100644--- a/server/lib/scopeAdherenceReasons.js+++ b/server/lib/scopeAdherenceReasons.js@@ -48,6 +48,17 @@ export const SCOPE_ADHERENCE_REASONS = Object.freeze({'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+ // 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.',});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 6563e92a4d..ad38ab28dc 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -61,6 +61,7 @@ import { SPEC_TYPE_SUGGESTIONS } from '../lib/specDecodePresets.js'import { resetProviderReadinessCache } from '../services/providerReadiness.js'import { MODEL_ABUSE_GUARD } from '../lib/modelAbuseGuard.js'import { JEV_MODEL, jevScoreRequestSchema } from '../lib/jev.js'+import { jevHeadActionRequestSchema, jevHeadTrainRequestSchema } from '../lib/jevHead.js'import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'import { isAppleSilicon } from '../lib/platform.js'import {@@ -77,6 +78,8 @@ import {import { getModelAbuseGuardStatus, installModelAbuseGuard, cancelModelAbuseGuardInstall } from '../services/modelAbuseGuard.js'import { cancelJevInstall, decide, getJevStatus, installJev, stopJevSidecar } from '../services/jev.js'import { readJevDecisionStats } from '../services/jevRouter.js'+import { adoptJevHead, describeJevHeads, discardJevHead } from '../services/jevHeads.js'+import { isJevTrainingRunning, trainScopeAdherenceHead } from '../services/jevTraining.js'import { getSettings } from '../services/settings.js'import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'import { getAssessmentReport, runAssessment, deleteAssessment } from '../services/localModelAssessments.js'@@ -313,6 +316,44 @@ router.post('/jev/unload', asyncHandler(async (_req, res) => {res.json({ unloaded: stopJevSidecar() })}))+// ── Project-specific trained heads ────────────────────────────────────────+// Every artifact under `data/jev/` is a derived record of this install's own+// repository history. These routes report metrics and adoption state; none of+// them returns a corpus row, a premise, or a path.+router.get('/jev/heads', asyncHandler(async (_req, res) => {+ res.json({ ...await describeJevHeads(), training: isJevTrainingRunning() })+}))++// An explicit operator action in the same request, per the AI Provider Usage+// Policy — and the only path that builds a corpus or starts a training run.+// Trains against THIS install's own checkout: a head learns the product the+// operator is actually running, and there is no client-supplied path to reach+// anything else.+router.post('/jev/heads/train', asyncHandler(async (req, res) => {+ const { architecture } = validateRequest(jevHeadTrainRequestSchema, req.body || {})+ const result = await trainScopeAdherenceHead({ architecture })+ if (!result?.ok) throw new ServerError('Training a project head failed.', { status: 502, code: result?.code || 'jev-head-training-failed' })+ res.json(result)+}))++// THE ADOPTION GATE is in `adoptJevHead`, not here: a head that does not beat+// both the stock zero-shot and the majority-class baseline cannot be promoted+// through any surface, and hiding a button is a suggestion, not a gate.+router.post('/jev/heads/adopt', asyncHandler(async (req, res) => {+ const { decisionId } = validateRequest(jevHeadActionRequestSchema, req.body || {})+ const result = await adoptJevHead(decisionId)+ if (!result?.ok) throw new ServerError('This head cannot be adopted.', { status: 400, code: result?.code || 'jev-head-invalid' })+ res.json({ adopted: true, decisionId, metrics: result.head.metrics })+}))++// Discarding the ADOPTED head returns the decision to the stock zero-shot+// classifier — the state every install ships in, so nothing is lost but the+// training run.+router.post('/jev/heads/discard', asyncHandler(async (req, res) => {+ const { decisionId, adopted } = validateRequest(jevHeadActionRequestSchema, req.body || {})+ res.json(await discardJevHead(decisionId, { candidate: adopted !== true }))+}))+// GET /api/local-llm/huggingface-search?backend=ollama&q=qwen&category=coding// Live Hub discovery — GGUF-compatible community models, plus (for the `audio`// category) audio/music generators that install into the shared audio-modeldiff --git a/server/services/backup.js b/server/services/backup.jsindex 07c6b6c625..d3bb9c3ad8 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -211,7 +211,26 @@ export const DEFAULT_EXCLUDES = [// directory that turns a nightly snapshot into an hour.// Overridable, because an archive of a conversation is more useful with its// photos in it, and someone keeping one may well want to pay for them.- { path: '/beeper/attachments/', reason: 'Beeper attachment byte mirror — a lazy cache re-fetchable from Beeper Desktop; the message bodies and attachment metadata live in Postgres and ARE backed up', overridable: true }+ { path: '/beeper/attachments/', reason: 'Beeper attachment byte mirror — a lazy cache re-fetchable from Beeper Desktop; the message bodies and attachment metadata live in Postgres and ARE backed up', overridable: true },+ // Anchored with a leading `/`, like every entry here — an unanchored+ // `corpora/` would match at any depth and silently drop unrelated user data.+ //+ // Two of the three jev directories are excluded and the third is deliberately+ // NOT, because they fail differently:+ //+ // corpora/ a snapshot of forge history, rebuildable by `gh` reads.+ // Overridable: the forge moves on, so someone archiving a+ // measured adoption decision may well want the exact corpus+ // the numbers came from.+ // embeddings/ frozen-encoder outputs, keyed by (pair, model revision).+ // Pure cache — byte-identical on re-encode, and gigabytes.+ // heads/ NOT excluded. A trained head is a few thousand floats and+ // is NOT regenerable once its corpus is gone: the queries that+ // produced one a month ago return different rows today. It is+ // also the only artifact here an operator made a decision+ // about, on the strength of three measured numbers.+ { path: '/jev/corpora/', reason: 'jev training corpora — rebuildable from the forge by scripts/jev-corpus.js. Trained heads in data/jev/heads/ are NOT excluded: a head is not regenerable once its corpus is stale.', overridable: true },+ { path: '/jev/embeddings/', reason: 'Cached frozen-encoder outputs for jev head training — keyed by (pair, model revision) and byte-identical on re-encode', overridable: false }// NOTE: legacy file→Postgres migration artifacts (`.imported` / `.bak-NNN`)// are intentionally NOT excluded here. They are deleted on disk by the// boot-time prune (pruneImportedLegacyFiles.js) the same boot the migrationdiff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex e72c63d24a..2c724966cc 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -99,6 +99,13 @@ export const CATEGORIES = {'image-to-3d': { label: 'Image to 3D', description: 'Generated GLB meshes — the only copy; records live in Postgres', archivable: false, deletable: false },'images': { label: 'Images', description: 'Uploaded and generated images — delete individually; gallery, pipeline, and collection records point at these files', archivable: true, deletable: true, purgeScope: 'items' },'insights': { label: 'Insights', description: 'Derived goal scorecards and insights — rebuilt on the next insights run', archivable: true, deletable: true, purgeScope: 'category' },+ // Project-specific jev heads plus the corpora and cached embeddings behind+ // them. NOT deletable as a category: the corpus and the embedding cache+ // regenerate, but a trained head does not — the forge queries that built its+ // corpus return different rows a month later, and it is the one artifact here+ // an operator made an adoption decision about. Purging it would silently+ // return scope adherence to the stock scorer with nothing to restore.+ 'jev': { label: 'jev Project Heads', description: 'Trained project-specific scorer heads, their training corpora, and cached frozen-encoder outputs — machine-local; a head is not regenerable once its corpus is stale', archivable: true, deletable: false },'jira-reports': { label: 'Jira Reports', description: 'Generated Jira reports — regenerable from Jira', archivable: true, deletable: true, purgeScope: 'category' },'loops': { label: 'Loops', description: 'Output history from scheduled loop runs', archivable: true, deletable: false },'lora-datasets': { label: 'LoRA Datasets', description: 'Training images and captions for LoRA runs — uploaded source material, not regenerable', archivable: false, deletable: false },diff --git a/server/services/jev.js b/server/services/jev.jsindex 01914e6698..3afda52373 100644--- a/server/services/jev.js+++ b/server/services/jev.js@@ -49,6 +49,10 @@ import { diagnosePythonRuntimeText } from '../lib/pythonRuntimeDiagnosis.js';import { createVenv, detectVenvBasePythonSync, installPackages } from '../lib/pythonSetup.js';import { withSpawnCwdEnv } from '../lib/spawnCwd.js';import { downloadHfRepo } from './hfDownload.js';+// One path helper, from the module that owns the directory. Re-deriving+// `data/jev/heads` here is how the sidecar's `--heads-dir` and the store's+// writes end up pointing at two different directories.+import { jevHeadsDir } from './jevHeads.js';const execFileAsync = promisify(execFile);const IS_WIN = platform() === 'win32';@@ -133,6 +137,17 @@ function availableJevPython() {return null;}+/**+ * The dedicated jev interpreter, or null.+ *+ * Exported for ONE caller: `services/jevTraining.js`, which has to run the head+ * trainer under exactly the interpreter and environment the scorer runs under,+ * or the "offline, no provider call, no second download" guarantee describes a+ * process that is not the one executing. Nothing else may spawn against this+ * venv — the sidecar lifecycle above owns it.+ */+export const jevPythonPath = () => availableJevPython();+async function isBasePythonSupported(pythonPath) {if (!pythonPath) return false;return execFileAsync(pythonPath, ['-c', 'import sys; print("supported" if sys.version_info >= (3, 10) else "unsupported")'],@@ -365,6 +380,11 @@ async function startSidecar() {// Every required file sits in the pinned subfolder, so its parent IS the// directory `from_pretrained` loads.const modelDir = dirname(files[0]);+ // Where adopted project heads live. Passed as a path, never created here: the+ // head store owns that directory, and the sidecar resolves a head inside it+ // per request rather than latching its existence at start-up — so a head+ // adopted while the sidecar is resident is reachable without a cold start.+ const headsDir = jevHeadsDir();const proc = spawn(pythonPath,@@ -375,6 +395,7 @@ async function startSidecar() {'--host', '127.0.0.1','--model-id', JEV_MODEL.id,'--revision', JEV_MODEL.revision,+ '--heads-dir', headsDir,],safeChildProcessOptions({cwd: dirname(pythonPath),@@ -434,8 +455,16 @@ function ensureSidecar() {** Returns the per-hypothesis entailment distribution in REQUEST ORDER, or a* failure code. Never a Python traceback, never the premise, never a path.+ *+ * `head` names an adopted project-specific head (`services/jevHeads.js`) to+ * apply in place of the checkpoint's own classifier, on the SAME frozen+ * encoder. It is a slug the server resolved, never a caller-supplied path, and+ * it is deliberately absent from `jevScoreRequestSchema`: which classifier+ * answers a decision is an install-level adoption, not something an HTTP body+ * may choose. The response shape is identical either way, so everything+ * downstream — margins, abstention floors — is unchanged.*/-export async function scoreHypotheses({ premise, hypotheses, timeoutMs = JEV_REQUEST_TIMEOUT_MS } = {}) {+export async function scoreHypotheses({ premise, hypotheses, head = null, timeoutMs = JEV_REQUEST_TIMEOUT_MS } = {}) {const parsed = jevScoreRequestSchema.safeParse({ premise, hypotheses });if (!parsed.success) {// The one length failure an operator can act on gets its own code; every@@ -450,7 +479,11 @@ export async function scoreHypotheses({ premise, hypotheses, timeoutMs = JEV_REQconst response = await fetch(`${SIDECAR_ORIGIN}/score`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ premise: parsed.data.premise, hypotheses: parsed.data.hypotheses }),+ body: JSON.stringify({+ premise: parsed.data.premise,+ hypotheses: parsed.data.hypotheses,+ ...(typeof head === 'string' && head ? { head } : {}),+ }),signal: AbortSignal.timeout(timeoutMs),}).catch((error) => (error?.name === 'TimeoutError' || error?.name === 'AbortError' ? 'timeout' : null));@@ -480,11 +513,11 @@ function safeErrorCode(body) {* the top option anyway discards the only signal this service adds over a* coin flip.*/-export async function decide({ premise, options, minMargin } = {}) {+export async function decide({ premise, options, minMargin, head = null } = {}) {// Checked BEFORE scoring: a single option has no runner-up, so there is no// margin to compute and no reason to pay for a forward pass to learn that.if (!Array.isArray(options) || options.length < 2) return failure('jev-request-invalid');- const scored = await scoreHypotheses({ premise, hypotheses: options });+ const scored = await scoreHypotheses({ premise, hypotheses: options, head });if (!scored.ok) return scored;return decideFromScores(scored.scores, minMargin);}diff --git a/server/services/jevCorpusBuilder.js b/server/services/jevCorpusBuilder.jsnew file mode 100644index 0000000000..569e1b3388--- /dev/null+++ b/server/services/jevCorpusBuilder.js@@ -0,0 +1,253 @@+/**+ * Build a weakly-labelled training corpus from one checkout's own forge history.+ *+ * The signal this install already has, and what each piece is worth:+ *+ * merged PR on the default branch → the maintainer wanted it → `aligned`+ * closed-unmerged PR → they did not → `unrelated`+ * issue closed `not planned` → they did not → `unrelated`+ * issue labelled `future`/`needs-input` → parked, not refused → `unrelated`+ *+ * Every one of those is WEAK. A merged pull request is evidence the maintainer+ * wanted it, not an annotation that it advances the specific clause the+ * retriever paired it with. Nothing here pretends otherwise — the held-out+ * split, the two baselines and the strictly-better adoption gate in+ * `lib/jevHead.js` exist precisely because these labels cannot be trusted on+ * their own.+ *+ * ## Two sources that are deliberately NOT here+ *+ * **The #7642 shadow counters.** `recordJevObservations` records counts only —+ * decision id, bucket, agreement flag, never a premise. That is exactly what+ * makes shadow mode safe to leave on, and it also means the counters contain no+ * labelled example and never will. They are carried on the manifest as a+ * readiness signal an operator can read beside the corpus, not folded in as+ * rows.+ *+ * **`messageTriageRules.js`.** Those corrections are email-sender keyed and+ * belong to the `message-triage` decision, whose cutover the issue that+ * introduced this module puts out of scope. The builder is decision-generic so+ * that caller can be added without reshaping anything; only the forge sources+ * ship wired.+ *+ * ## Privacy+ *+ * A corpus is this install's private repository history, rendered as premises.+ * It is written under `data/jev/corpora/`, is machine-local, and never crosses+ * the federation layer — see `services/jevHeads.js` and the ADR+ * [privacy records machine-local](../../docs/decisions/2026-08-08-privacy-records-machine-local.md).+ * Nothing here contacts a provider: the forge queries are `gh` reads against+ * the operator's own repository.+ */++import { promisify } from 'util';+import { join } from 'path';+import { execFile } from '../lib/childProcess.js';+import { atomicWrite, ensureDir, safeJSONParse } from '../lib/fileUtils.js';+import {+ assertSplitDisjoint,+ buildCorpusExample,+ corpusHash,+ JEV_CORPUS_MIN_EXAMPLES,+ JEV_CORPUS_SCHEMA_VERSION,+ majorityClassAccuracy,+ splitCorpus,+ summarizeCorpusSources,+ toCorpusJsonl,+} from '../lib/jevCorpus.js';+import { getJevDecision, jevHypotheses } from '../lib/jevDecisions.js';+import {+ composeAdherencePremise,+ formatChangeEvidence,+ SCOPE_ADHERENCE_DECISION_ID,+ SCOPE_ADHERENCE_TOP_K,+ selectCandidateClauses,+} from '../lib/scopeAdherence.js';+import { jevCorporaDir } from './jevHeads.js';++const execFileAsync = promisify(execFile);+const FORGE_TIMEOUT_MS = 60_000;+// One `gh` page per query. Large enough that a busy repository yields a usable+// corpus in four reads, bounded so a decade-old repository cannot turn a+// button press into a multi-minute paginated crawl.+const FORGE_PAGE_LIMIT = 300;+const failure = (code) => ({ ok: false, code });++/**+ * Run one `gh` read.+ *+ * Fixed argv, never a shell string: every value that varies is a separate+ * argument, so nothing a forge returns can become a command. Returns null on+ * any failure — a repository with no `gh`, no auth, or no network is a corpus+ * that cannot be built, which the caller reports as one code.+ */+async function ghJson(args, { cwd, env }) {+ const result = await execFileAsync('gh', args, {+ cwd,+ env: env || process.env,+ timeout: FORGE_TIMEOUT_MS,+ maxBuffer: 32 * 1024 * 1024,+ }).catch(() => null);+ if (!result) return null;+ const parsed = safeJSONParse(result.stdout, null, { allowArray: true, logError: false });+ return Array.isArray(parsed) ? parsed : null;+}++/**+ * The forge rows this corpus draws from, each already carrying its weak verdict.+ *+ * `--search` narrows on the SERVER. A client-side filter over a fetched page+ * would silently drop the older half of a busy repository's history, which is+ * the half a young corpus most needs.+ */+async function fetchForgeRows({ cwd, env }) {+ const [merged, closedPrs, notPlanned, parked] = await Promise.all([+ ghJson(['pr', 'list', '--state', 'merged', '--limit', String(FORGE_PAGE_LIMIT),+ '--json', 'number,title,body'], { cwd, env }),+ ghJson(['pr', 'list', '--state', 'closed', '--limit', String(FORGE_PAGE_LIMIT),+ '--json', 'number,title,body,mergedAt'], { cwd, env }),+ ghJson(['issue', 'list', '--state', 'closed', '--search', 'reason:"not planned"',+ '--limit', String(FORGE_PAGE_LIMIT), '--json', 'number,title,body'], { cwd, env }),+ ghJson(['issue', 'list', '--state', 'open', '--label', 'future',+ '--limit', String(FORGE_PAGE_LIMIT), '--json', 'number,title,body'], { cwd, env }),+ ]);+ // Every query failing means the forge is unreachable. One failing on a+ // repository that simply has no such rows is an empty list, which is fine —+ // `null` and `[]` are kept apart for exactly this reason.+ if ([merged, closedPrs, notPlanned, parked].every((rows) => rows === null)) return null;++ const rows = [];+ for (const row of merged || []) rows.push({ ...row, kind: 'pr', source: 'merged-pr', verdict: 'aligned' });+ // `gh pr list --state closed` includes merged ones; the merged query already+ // claimed those, and a PR counted as both evidence for and against would be+ // pure noise with a label on it.+ for (const row of closedPrs || []) {+ if (row?.mergedAt) continue;+ rows.push({ ...row, kind: 'pr', source: 'closed-unmerged-pr', verdict: 'unrelated' });+ }+ for (const row of notPlanned || []) rows.push({ ...row, kind: 'issue', source: 'closed-not-planned-issue', verdict: 'unrelated' });+ for (const row of parked || []) rows.push({ ...row, kind: 'issue', source: 'parked-issue', verdict: 'unrelated' });+ return rows;+}++/**+ * Turn forge rows into Route A examples against the repository's own clauses.+ *+ * The premise is composed by the SAME helpers inference uses+ * (`formatChangeEvidence` + `composeAdherencePremise`), and the retriever picks+ * the clauses the same way. A corpus built with different wording would train a+ * head on questions the scorer is never asked.+ */+function toExamples({ rows, clauses, index, options, verdicts, topK }) {+ const examples = [];+ for (const row of rows) {+ const change = {+ kind: row.kind,+ title: String(row.title || '').trim(),+ body: String(row.body || '').trim(),+ diffSummary: '',+ };+ if (!change.title && !change.body) continue;+ const evidence = formatChangeEvidence(change);+ for (const clause of selectCandidateClauses(clauses, change, { k: topK, index })) {+ const context = composeAdherencePremise({ clause, evidence });+ if (!context) continue;+ const example = buildCorpusExample({+ context,+ options,+ chosen: verdicts[row.verdict],+ source: row.source,+ });+ if (example) examples.push(example);+ }+ }+ return examples;+}++/**+ * Build, split and persist a corpus for `scope-adherence`.+ *+ * Returns the manifest — counts, hashes, per-source balance and the majority+ * baseline — never a single example. The corpus itself is on disk; what a+ * caller and the panel get back is a description of it.+ *+ * @param {object} options+ * @param {string} options.repoPath Checkout holding `PRD.md` / `GOALS.md` and the forge remote.+ * @param {object} [options.env] Environment for the `gh` reads (a resolved forge token overlay).+ */+export async function buildScopeAdherenceCorpus({ repoPath, env = null, topK = SCOPE_ADHERENCE_TOP_K } = {}) {+ if (typeof repoPath !== 'string' || !repoPath.trim()) return failure('jev-corpus-no-clauses');++ // Deferred: the scope-adherence service reaches the untrusted-content ladder+ // and, through it, the sidecar lifecycle. Corpus building needs only its+ // clause parser (`server/lib/importScoping.test.js`).+ const { loadClauseCorpus } = await import('./scopeAdherence.js');+ const corpus = await loadClauseCorpus(repoPath);+ if (!corpus.ok) return failure('jev-corpus-no-clauses');++ const rows = await fetchForgeRows({ cwd: repoPath, env });+ if (rows === null) return failure('jev-corpus-forge-unavailable');++ const options = jevHypotheses(SCOPE_ADHERENCE_DECISION_ID);+ // The hypothesis each weak verdict stands for, resolved from the registry+ // rather than restated: a re-worded hypothesis must move the corpus with it,+ // or a head trained today would be scored against a different question+ // tomorrow.+ const decisionOptions = getJevDecision(SCOPE_ADHERENCE_DECISION_ID).options;+ const verdicts = Object.fromEntries(decisionOptions.map((option) => [option.value, option.hypothesis]));++ const examples = toExamples({ rows, clauses: corpus.clauses, index: corpus.index, options, verdicts, topK });+ const { train, gold } = splitCorpus(examples);+ // THE REFUSAL. A gold set sharing rows with the training split reports a+ // score that is partly memorization, and that score is the only evidence the+ // adoption gate reads — so this is a hard stop before anything is written,+ // not a warning beside a corpus somebody might still train on.+ //+ // The total-size floor is checked FIRST, so a young repository is told it has+ // no history to learn from rather than being handed the narrower "gold set+ // too small" — which describes a split problem it cannot act on.+ if (train.length + gold.length < JEV_CORPUS_MIN_EXAMPLES) return failure('jev-corpus-too-small');+ const split = assertSplitDisjoint({ train, gold });+ if (!split.ok) return failure(split.code);++ const hash = corpusHash([...train, ...gold]);+ const dir = join(jevCorporaDir(), `${SCOPE_ADHERENCE_DECISION_ID}-${hash}`);+ await ensureDir(dir);+ // Strings, so `atomicWrite` passes them through unchanged rather than+ // re-encoding them as a JSON document.+ await atomicWrite(join(dir, 'train.jsonl'), toCorpusJsonl(train));+ await atomicWrite(join(dir, 'gold.jsonl'), toCorpusJsonl(gold));++ const manifest = {+ schemaVersion: JEV_CORPUS_SCHEMA_VERSION,+ decisionId: SCOPE_ADHERENCE_DECISION_ID,+ corpusHash: hash,+ trainSize: train.length,+ goldSize: gold.length,+ majorityClass: majorityClassAccuracy(gold),+ sources: summarizeCorpusSources([...train, ...gold]),+ // The exact reads that produced it, so a corpus can be rebuilt — or+ // disputed — without reading this file's source.+ queries: [+ 'gh pr list --state merged',+ 'gh pr list --state closed (unmerged only)',+ 'gh issue list --state closed --search reason:"not planned"',+ 'gh issue list --state open --label future',+ ],+ // Counts only, and only for context: the shadow counters carry no premise,+ // so they inform whether this decision has been measured at all — never a+ // training row.+ shadow: await readShadowContext(),+ builtAt: new Date().toISOString(),+ };+ await atomicWrite(join(dir, 'manifest.json'), manifest);+ return { ok: true, ...manifest, corpusDir: dir };+}++async function readShadowContext() {+ const { readJevDecisionStats } = await import('./jevRouter.js');+ const stats = await readJevDecisionStats().catch(() => null);+ const row = stats?.decisions?.find((entry) => entry.decisionId === SCOPE_ADHERENCE_DECISION_ID);+ if (!row) return { observed: 0, compared: 0, agreementRate: null };+ return { observed: row.observed, compared: row.compared, agreementRate: row.agreementRate };+}diff --git a/server/services/jevCorpusBuilder.test.js b/server/services/jevCorpusBuilder.test.jsnew file mode 100644index 0000000000..3e33a94f90--- /dev/null+++ b/server/services/jevCorpusBuilder.test.js@@ -0,0 +1,128 @@+/**+ * The corpus builder's forge boundary.+ *+ * Three regressions none of the pure `lib/jevCorpus.js` tests can reach:+ * a failed forge read read as an empty repository, a merged pull request+ * counted twice (once as evidence FOR and once against), and a corpus written+ * to disk despite a refusal.+ */++import { mkdtemp, mkdir, writeFile, readdir } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const dataRoot = await mkdtemp(join(tmpdir(), 'portos-jev-corpus-'));+const repoPath = await mkdtemp(join(tmpdir(), 'portos-jev-repo-'));++vi.mock('../lib/paths.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: dataRoot } };+});++// promisify(execFile) needs the callback form, so a bare vi.fn() would hang+// every query rather than failing one.+const execFile = vi.fn();+vi.mock('../lib/childProcess.js', () => ({+ execFile: (command, args, options, callback) => execFile(command, args, options, callback),+}));++const { buildScopeAdherenceCorpus } = await import('./jevCorpusBuilder.js');++// Enough distinct goals that the retriever has something to rank, and enough+// prose per clause to clear the parser's minimum.+const GOALS = Array.from({ length: 12 }, (_unused, index) => (+ `PortOS must ${['index', 'render', 'schedule', 'archive'][index % 4]} ${['agents', 'issues', 'media', 'peers'][index % 4]} `+ + `so the operator can review goal ${index} without leaving the machine.`+)).join('\n\n');++/** A forge answer per query, keyed by the `gh` subcommand shape. */+function mockForge({ merged = [], closed = [], notPlanned = [], parked = [], failAll = false } = {}) {+ execFile.mockImplementation((_command, args, _options, callback) => {+ if (failAll) return callback(new Error('gh: not authenticated'));+ const rows = args[0] === 'pr'+ ? (args.includes('merged') ? merged : closed)+ : (args.includes('future') ? parked : notPlanned);+ return callback(null, { stdout: JSON.stringify(rows), stderr: '' });+ });+}++const changes = (count, offset = 0) => Array.from({ length: count }, (_unused, index) => ({+ number: offset + index,+ title: `Change ${offset + index} to the ${['agent', 'issue', 'media', 'peer'][index % 4]} surface`,+ body: `Reworks how PortOS ${['indexes', 'renders', 'schedules', 'archives'][index % 4]} them for goal ${index % 12}.`,+}));++beforeEach(async () => {+ vi.clearAllMocks();+ await writeFile(join(repoPath, 'GOALS.md'), `# Goals\n\n${GOALS}\n`);+ const { resetClauseCorpusCache } = await import('./scopeAdherence.js');+ resetClauseCorpusCache();+});++describe('buildScopeAdherenceCorpus', () => {+ it('builds a split corpus and reports counts, never examples', async () => {+ mockForge({ merged: changes(60), notPlanned: changes(60, 500) });+ const result = await buildScopeAdherenceCorpus({ repoPath });+ expect(result.ok).toBe(true);+ expect(result.trainSize).toBeGreaterThan(0);+ expect(result.goldSize).toBeGreaterThanOrEqual(20);+ expect(result.sources['merged-pr']).toBeGreaterThan(0);+ expect(result.sources['closed-not-planned-issue']).toBeGreaterThan(0);+ // The manifest is a description of the corpus, not the corpus.+ expect(JSON.stringify(result)).not.toContain('Stated product goal');++ const written = await readdir(result.corpusDir);+ expect(written.sort()).toEqual(['gold.jsonl', 'manifest.json', 'train.jsonl']);+ });++ // `null` and `[]` must not collapse: a repository that has merged nothing is+ // not a machine that cannot reach its forge, and the two point at opposite+ // remedies.+ it('distinguishes an unreachable forge from a repository with no history', async () => {+ mockForge({ failAll: true });+ expect(await buildScopeAdherenceCorpus({ repoPath })).toEqual({ ok: false, code: 'jev-corpus-forge-unavailable' });++ mockForge({});+ expect(await buildScopeAdherenceCorpus({ repoPath })).toEqual({ ok: false, code: 'jev-corpus-too-small' });+ });++ // A PR counted as evidence both FOR and AGAINST is pure noise with a label+ // on it. `gh pr list --state closed` includes merged ones, so the merged+ // query's rows have to be dropped from it.+ it('does not count a merged pull request again as a closed-unmerged one', async () => {+ const merged = changes(60);+ mockForge({+ merged,+ // The same rows come back from the closed query, carrying `mergedAt`.+ closed: [...merged.map((row) => ({ ...row, mergedAt: '2026-09-01T00:00:00Z' })), ...changes(5, 900)],+ notPlanned: changes(30, 500),+ });+ const result = await buildScopeAdherenceCorpus({ repoPath });+ expect(result.ok).toBe(true);+ expect(result.sources['closed-unmerged-pr']).toBeGreaterThan(0);+ // Five unmerged rows at k clauses each, and not one row per merged PR.+ expect(result.sources['closed-unmerged-pr']).toBeLessThan(result.sources['merged-pr']);+ });++ it('refuses a repository that states no product intent', async () => {+ const bare = await mkdtemp(join(tmpdir(), 'portos-jev-bare-'));+ mockForge({ merged: changes(60) });+ expect(await buildScopeAdherenceCorpus({ repoPath: bare })).toEqual({ ok: false, code: 'jev-corpus-no-clauses' });+ // A missing repoPath must not silently grade against this install's own.+ expect(await buildScopeAdherenceCorpus({})).toEqual({ ok: false, code: 'jev-corpus-no-clauses' });+ });++ // The gold set is too small to separate three numbers, so no corpus is+ // written at all — a refusal before the write, not a warning beside one.+ it('writes nothing when the corpus cannot support a comparison', async () => {+ const corpora = join(dataRoot, 'jev', 'corpora');+ await mkdir(corpora, { recursive: true });+ // Compared against a snapshot, not against empty: earlier cases in this+ // file legitimately wrote corpora into the same data root.+ const before = (await readdir(corpora)).sort();+ mockForge({ merged: changes(3) });+ expect((await buildScopeAdherenceCorpus({ repoPath })).ok).toBe(false);+ expect((await readdir(corpora)).sort()).toEqual(before);+ });+});diff --git a/server/services/jevHeads.js b/server/services/jevHeads.jsnew file mode 100644index 0000000000..d9bd392bd1--- /dev/null+++ b/server/services/jevHeads.js@@ -0,0 +1,187 @@+/**+ * The on-disk store for project-specific trained jev heads.+ *+ * Three states a decision can be in, and they are never collapsed:+ *+ * no candidate — nothing has been trained for this decision+ * candidate, not adopted — trained and scored, awaiting an operator's call+ * adopted — in use by `runJevDecision` for this decision+ *+ * TRAINING NEVER ADOPTS. A run writes a candidate and stops; adoption is a+ * separate explicit action, and `adoptJevHead` refuses one whose measured+ * accuracy does not beat BOTH baselines. That refusal is server-side on+ * purpose: a UI that merely hides the button is a suggestion, and the number it+ * hides the button over came from this machine's own private history.+ *+ * ## Layout, and why it is where it is+ *+ * data/jev/heads/<decisionId>.json adopted — BACKED UP+ * data/jev/heads/<decisionId>.candidate.json awaiting a decision — BACKED UP+ * data/jev/corpora/ regenerable — excluded+ * data/jev/embeddings/ regenerable cache — excluded+ *+ * A head is NOT regenerable once the corpus behind it is gone: the forge moves+ * on, issues close, and the exact query that produced a corpus a month ago+ * returns something else today. It is also the only artifact here an operator+ * made a decision about. Corpora and cached embeddings are bulk that re-derives+ * — see `DEFAULT_EXCLUDES` in `services/backup.js` and `docs/BACKUP.md`.+ *+ * ## Privacy+ *+ * Every byte under `data/jev/` is a derived record of this install's private+ * repository history and the operator's own judgement calls. It is+ * MACHINE-LOCAL: never federated, never in a peer sync, never in a status or+ * capability payload. The ADR+ * [privacy records machine-local](../../docs/decisions/2026-08-08-privacy-records-machine-local.md)+ * covers the path, and `sharing/jevNeverFederates.test.js` is the guard.+ */++import { readdir, unlink } from 'fs/promises';+import { join } from 'path';+import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { JEV_MODEL } from '../lib/jev.js';+import { JEV_DECISION_IDS } from '../lib/jevDecisions.js';+import { headAdoptionBlocker, headBeatsBaselines, isHeadCompatible, parseJevHead } from '../lib/jevHead.js';++/** The one directory every jev artifact lives under. Machine-local, always. */+export const jevDataDir = () => join(PATHS.data, 'jev');+export const jevHeadsDir = () => join(jevDataDir(), 'heads');+export const jevCorporaDir = () => join(jevDataDir(), 'corpora');+export const jevEmbeddingsDir = () => join(jevDataDir(), 'embeddings');++const failure = (code) => ({ ok: false, code });++const headPath = (decisionId, { candidate = false } = {}) => join(+ jevHeadsDir(),+ `${decisionId}${candidate ? '.candidate' : ''}.json`,+);++/**+ * Adopted heads by decision id, so a per-clause scoring loop does not re-read+ * and re-validate the same file on every forward pass. Invalidated by every+ * write path in this module, and by the test seam below.+ */+let adoptedCache = null;++/** Test seam, mirroring the cache resets on the sibling local-model services. */+export const resetJevHeadCache = () => { adoptedCache = null; };++async function readHeadFile(path) {+ const content = await tryReadFile(path);+ if (content === null) return failure('jev-head-not-found');+ const parsed = safeJSONParse(content, null, { allowArray: false, logError: false });+ if (parsed === null) return failure('jev-head-unreadable');+ return parseJevHead(parsed);+}++/**+ * The head `decisionId` is currently scored with, or null.+ *+ * Returns null — never a failure — for every reason a head might not apply:+ * none adopted, an unreadable file, a head fit on a different encoder+ * revision. Scoring falls back to the stock zero-shot classifier in all three+ * cases, because that is what the install did before any head existed and it+ * is always correct. An operator who wants to know WHY sees it in the panel,+ * which calls `describeJevHeads` instead.+ */+export async function getAdoptedJevHead(decisionId) {+ if (!JEV_DECISION_IDS.includes(decisionId)) return null;+ if (adoptedCache?.has(decisionId)) return adoptedCache.get(decisionId);+ const result = await readHeadFile(headPath(decisionId));+ const head = result.ok && isHeadCompatible(result.head, JEV_MODEL) ? result.head : null;+ adoptedCache ??= new Map();+ adoptedCache.set(decisionId, head);+ return head;+}++/**+ * Operator-facing state for every decision that has an artifact on disk.+ *+ * Reports the metrics and the adoption blocker, never a corpus row, a premise+ * or a path. `compatible: false` is stated rather than silently hidden: a head+ * that stopped applying because the pinned model revision moved is a fact the+ * operator needs, not an absence.+ */+export async function describeJevHeads() {+ const dir = jevHeadsDir();+ const entries = await readdir(dir).catch(() => []);+ const rows = [];+ for (const decisionId of JEV_DECISION_IDS) {+ for (const candidate of [false, true]) {+ const name = `${decisionId}${candidate ? '.candidate' : ''}.json`;+ if (!entries.includes(name)) continue;+ const result = await readHeadFile(join(dir, name));+ if (!result.ok) {+ rows.push({ decisionId, adopted: !candidate, ok: false, code: result.code });+ continue;+ }+ const { head } = result;+ rows.push({+ decisionId,+ adopted: !candidate,+ ok: true,+ architecture: head.architecture,+ metrics: head.metrics,+ corpusHash: head.corpusHash,+ corpusSources: head.corpusSources,+ trainedAt: head.trainedAt,+ baseRevision: head.baseModel.revision,+ compatible: isHeadCompatible(head, JEV_MODEL),+ beatsBaselines: headBeatsBaselines(head.metrics),+ blocker: headAdoptionBlocker(head.metrics),+ });+ }+ }+ return { heads: rows };+}++/** Persist a freshly trained head as a CANDIDATE. Never adopts. */+export async function saveCandidateJevHead(decisionId, raw) {+ if (!JEV_DECISION_IDS.includes(decisionId)) return failure('jev-head-invalid');+ const parsed = parseJevHead(raw);+ if (!parsed.ok) return parsed;+ if (parsed.head.decisionId !== decisionId) return failure('jev-head-invalid');+ if (!isHeadCompatible(parsed.head, JEV_MODEL)) return failure('jev-head-revision-mismatch');+ await ensureDir(jevHeadsDir());+ await atomicWrite(headPath(decisionId, { candidate: true }), parsed.head);+ return { ok: true, head: parsed.head };+}++/**+ * Promote the candidate for `decisionId` into the adopted slot.+ *+ * THE GATE LIVES HERE. A head that does not beat both the stock zero-shot+ * classifier and the majority class on the held-out gold set cannot be adopted+ * through any surface, and the refusal names which baseline it lost to.+ */+export async function adoptJevHead(decisionId) {+ if (!JEV_DECISION_IDS.includes(decisionId)) return failure('jev-head-invalid');+ const result = await readHeadFile(headPath(decisionId, { candidate: true }));+ if (!result.ok) return result;+ const { head } = result;+ if (!isHeadCompatible(head, JEV_MODEL)) return failure('jev-head-revision-mismatch');+ const blocker = headAdoptionBlocker(head.metrics);+ if (blocker) return failure(blocker);+ await ensureDir(jevHeadsDir());+ await atomicWrite(headPath(decisionId), head);+ // The candidate is consumed, not kept: leaving a byte-identical copy beside+ // the adopted head would make the panel show the same artifact twice, in two+ // states, with no way to tell which one is answering.+ await unlink(headPath(decisionId, { candidate: true })).catch(() => null);+ resetJevHeadCache();+ return { ok: true, head };+}++/**+ * Discard an artifact.+ *+ * Discarding the ADOPTED head returns the decision to the stock zero-shot+ * classifier immediately — which is the state every install ships in, so there+ * is nothing to restore and nothing to warn about.+ */+export async function discardJevHead(decisionId, { candidate = true } = {}) {+ if (!JEV_DECISION_IDS.includes(decisionId)) return failure('jev-head-invalid');+ const removed = await unlink(headPath(decisionId, { candidate })).then(() => true, () => false);+ resetJevHeadCache();+ return { ok: true, removed };+}diff --git a/server/services/jevHeads.test.js b/server/services/jevHeads.test.jsnew file mode 100644index 0000000000..559257a75a--- /dev/null+++ b/server/services/jevHeads.test.js@@ -0,0 +1,181 @@+/**+ * The trained-head store, and the one thing it exists to enforce.+ *+ * ADOPTION IS GATED SERVER-SIDE. A UI that merely hides the button is a+ * suggestion, and the number it would hide the button over came from this+ * machine's own private history — so the refusal is asserted here, on the+ * function every surface has to go through, not on a rendered disabled state.+ */++import { mkdtemp, mkdir, writeFile, readFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { JEV_LABELS } from '../lib/jev.js';+import { JEV_HEAD_POOLING, JEV_HEAD_SCHEMA_VERSION } from '../lib/jevHead.js';++const dataRoot = await mkdtemp(join(tmpdir(), 'portos-jev-heads-'));+vi.mock('../lib/paths.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: dataRoot } };+});++const {+ adoptJevHead, describeJevHeads, discardJevHead, getAdoptedJevHead,+ jevHeadsDir, resetJevHeadCache, saveCandidateJevHead,+} = await import('./jevHeads.js');+const { JEV_MODEL } = await import('../lib/jev.js');++const head = (overrides = {}) => ({+ schemaVersion: JEV_HEAD_SCHEMA_VERSION,+ decisionId: 'scope-adherence',+ architecture: 'linear',+ pooling: JEV_HEAD_POOLING,+ baseModel: { id: JEV_MODEL.id, repository: JEV_MODEL.repository, revision: JEV_MODEL.revision },+ hiddenSize: 2,+ labels: [...JEV_LABELS],+ layers: [{ weight: [[1, 0], [0, 1], [1, 1]], bias: [0, 0, 0] }],+ metrics: { trained: 0.71, stockZeroShot: 0.58, majorityClass: 0.52, goldSize: 40, trainSize: 120 },+ corpusHash: 'deadbeefcafe0001',+ corpusSources: ['merged-pr'],+ trainedAt: '2026-09-19T00:00:00.000Z',+ ...overrides,+});++beforeEach(async () => {+ await mkdir(jevHeadsDir(), { recursive: true });+ resetJevHeadCache();+});++afterEach(async () => {+ const { rm } = await import('fs/promises');+ await rm(jevHeadsDir(), { recursive: true, force: true });+ resetJevHeadCache();+});++describe('saveCandidateJevHead', () => {+ // Training NEVER adopts. A run that promoted its own output would make the+ // three measured numbers decoration.+ it('writes a candidate and leaves nothing adopted', async () => {+ expect((await saveCandidateJevHead('scope-adherence', head())).ok).toBe(true);+ expect(await getAdoptedJevHead('scope-adherence')).toBeNull();+ const described = await describeJevHeads();+ expect(described.heads).toHaveLength(1);+ expect(described.heads[0]).toMatchObject({ decisionId: 'scope-adherence', adopted: false, beatsBaselines: true });+ });++ it('refuses a head fit on a different encoder revision', async () => {+ const result = await saveCandidateJevHead('scope-adherence', head({+ baseModel: { id: JEV_MODEL.id, repository: JEV_MODEL.repository, revision: 'some-other-revision' },+ }));+ expect(result).toEqual({ ok: false, code: 'jev-head-revision-mismatch' });+ });++ it('refuses a head whose declared decision is not the one being saved', async () => {+ const result = await saveCandidateJevHead('scope-adherence', head({ decisionId: 'message-triage' }));+ expect(result).toEqual({ ok: false, code: 'jev-head-invalid' });+ });+});++describe('adoptJevHead — the gate', () => {+ it('promotes a candidate that beats both baselines, and consumes it', async () => {+ await saveCandidateJevHead('scope-adherence', head());+ expect((await adoptJevHead('scope-adherence')).ok).toBe(true);+ expect(await getAdoptedJevHead('scope-adherence')).toMatchObject({ corpusHash: 'deadbeefcafe0001' });+ // The candidate is gone, so the panel cannot show one artifact twice in two+ // states with no way to tell which is answering.+ const described = await describeJevHeads();+ expect(described.heads.map((row) => row.adopted)).toEqual([true]);+ });++ it('refuses a head that does not beat the stock zero-shot classifier', async () => {+ await saveCandidateJevHead('scope-adherence', head({+ metrics: { trained: 0.55, stockZeroShot: 0.62, majorityClass: 0.40, goldSize: 40, trainSize: 120 },+ }));+ expect(await adoptJevHead('scope-adherence')).toEqual({ ok: false, code: 'jev-head-below-zero-shot' });+ expect(await getAdoptedJevHead('scope-adherence')).toBeNull();+ });++ it('refuses a head that does not beat the majority class', async () => {+ await saveCandidateJevHead('scope-adherence', head({+ metrics: { trained: 0.74, stockZeroShot: 0.61, majorityClass: 0.80, goldSize: 40, trainSize: 120 },+ }));+ expect(await adoptJevHead('scope-adherence')).toEqual({ ok: false, code: 'jev-head-below-majority-class' });+ });++ // Bypass probe: the refusals above must be the GATE firing, not the store+ // failing to find anything. Same candidate, one metric moved.+ it('the same artifact adopts once its trained score clears both baselines', async () => {+ await saveCandidateJevHead('scope-adherence', head({+ metrics: { trained: 0.55, stockZeroShot: 0.62, majorityClass: 0.40, goldSize: 40, trainSize: 120 },+ }));+ expect((await adoptJevHead('scope-adherence')).ok).toBe(false);+ await saveCandidateJevHead('scope-adherence', head({+ metrics: { trained: 0.71, stockZeroShot: 0.62, majorityClass: 0.40, goldSize: 40, trainSize: 120 },+ }));+ expect((await adoptJevHead('scope-adherence')).ok).toBe(true);+ });++ it('reports a missing candidate rather than adopting nothing', async () => {+ expect(await adoptJevHead('scope-adherence')).toEqual({ ok: false, code: 'jev-head-not-found' });+ });+});++describe('getAdoptedJevHead', () => {+ // Every reason a head might not apply falls back to the stock classifier —+ // which is what the install did before heads existed, and is always correct.+ it('falls back to null when the adopted head was fit on a stale revision', async () => {+ await mkdir(jevHeadsDir(), { recursive: true });+ await writeFile(join(jevHeadsDir(), 'scope-adherence.json'), JSON.stringify(head({+ baseModel: { id: JEV_MODEL.id, repository: JEV_MODEL.repository, revision: 'stale' },+ })));+ expect(await getAdoptedJevHead('scope-adherence')).toBeNull();+ // ...and says so, rather than reading as "no head trained".+ const described = await describeJevHeads();+ expect(described.heads[0]).toMatchObject({ adopted: true, compatible: false, baseRevision: 'stale' });+ });++ it('falls back to null on a corrupt file', async () => {+ await writeFile(join(jevHeadsDir(), 'scope-adherence.json'), 'not json');+ expect(await getAdoptedJevHead('scope-adherence')).toBeNull();+ expect((await describeJevHeads()).heads[0]).toMatchObject({ ok: false, code: 'jev-head-unreadable' });+ });++ it('returns null for a decision id that is not in the registry', async () => {+ expect(await getAdoptedJevHead('not-a-decision')).toBeNull();+ });+});++describe('discardJevHead', () => {+ it('returns an adopted decision to the stock classifier', async () => {+ await saveCandidateJevHead('scope-adherence', head());+ await adoptJevHead('scope-adherence');+ expect(await discardJevHead('scope-adherence', { candidate: false })).toEqual({ ok: true, removed: true });+ expect(await getAdoptedJevHead('scope-adherence')).toBeNull();+ });++ it('is idempotent when there is nothing to discard', async () => {+ expect(await discardJevHead('scope-adherence')).toEqual({ ok: true, removed: false });+ });+});++describe('on-disk layout', () => {+ // The backup tiers in `services/backup.js` are anchored to these exact+ // directory names; a rename here silently changes what is snapshotted.+ it('keeps heads, corpora and embeddings under data/jev/', async () => {+ const { jevCorporaDir, jevDataDir, jevEmbeddingsDir } = await import('./jevHeads.js');+ expect(jevDataDir()).toBe(join(dataRoot, 'jev'));+ expect(jevHeadsDir()).toBe(join(dataRoot, 'jev', 'heads'));+ expect(jevCorporaDir()).toBe(join(dataRoot, 'jev', 'corpora'));+ expect(jevEmbeddingsDir()).toBe(join(dataRoot, 'jev', 'embeddings'));+ });++ // The slug the sidecar resolves is the decision id, so an adopted head has+ // to land at exactly `<decisionId>.json`.+ it('names an adopted head after its decision id', async () => {+ await saveCandidateJevHead('scope-adherence', head());+ await adoptJevHead('scope-adherence');+ const written = JSON.parse(await readFile(join(jevHeadsDir(), 'scope-adherence.json'), 'utf8'));+ expect(written.decisionId).toBe('scope-adherence');+ });+});diff --git a/server/services/jevRouter.js b/server/services/jevRouter.jsindex 1b80e5cc6f..5bb8fe0b50 100644--- a/server/services/jevRouter.js+++ b/server/services/jevRouter.js@@ -100,9 +100,17 @@ export async function runJevDecision({ decisionId, premise, policyMinMargin = nu// Deferred so an install that never opts in keeps the sidecar lifecycle, the// `PORTS` table, and the model contract out of its static import closure.const { decide } = await import('./jev.js');+ // An adopted project-specific head, or null on every install that has not+ // trained one — which is every install by default. Null means the stock+ // zero-shot classifier answers, exactly as it did before heads existed.+ const { getAdoptedJevHead } = await import('./jevHeads.js');+ const head = await getAdoptedJevHead(decisionId);const scored = await decide({premise,options: jevHypotheses(decisionId),+ // The decision id IS the head's slug. Resolved inside the heads directory+ // by the sidecar, never treated as a path.+ head: head ? decisionId : null,// The base floor gates the forward pass; a per-option floor is applied// below, once there is a winner to look up.minMargin: jevMinMarginFor(decisionId, { policyMinMargin }),diff --git a/server/services/jevTraining.js b/server/services/jevTraining.jsnew file mode 100644index 0000000000..5ca9dbea27--- /dev/null+++ b/server/services/jevTraining.js@@ -0,0 +1,157 @@+/**+ * Run one project-head training job, entirely on this machine.+ *+ * buildScopeAdherenceCorpus() ← forge reads + the operator's own clauses+ * ↓ train.jsonl / gold.jsonl, split disjointness already REFUSED on overlap+ * scripts/train_jev_head.py ← venv-jev, frozen encoder, offline+ * ↓ candidate head + three gold scores+ * saveCandidateJevHead() ← a CANDIDATE. Never adopted here.+ *+ * Three properties this module exists to hold:+ *+ * 1. **No provider call and no second download.** The trainer runs in the+ * dedicated `venv-jev` under the same hardened environment the sidecar gets+ * — `HF_HUB_OFFLINE=1`, no API keys, no forge token, no PYTHONPATH — over+ * the snapshot that is already on disk. The one network-touching step is+ * the corpus build's `gh` reads, which happen before Python starts and get+ * an environment of their own.+ * 2. **Training never promotes.** The run ends with a candidate and three+ * numbers. `adoptJevHead` is a separate operator action, and it refuses a+ * head that does not beat both baselines.+ * 3. **One run at a time.** A 4B encoder is loaded twice over if two runs+ * overlap, on a machine that may already be holding the sidecar's copy+ * resident — so a second request joins the first rather than starting one.+ */++import { promisify } from 'util';+import { dirname, join } from 'path';+import { execFile } from '../lib/childProcess.js';+import { PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { findCachedRepoFiles } from '../lib/hfCache.js';+import { JEV_MODEL, JEV_REQUIRED_FILES } from '../lib/jev.js';+import { SCOPE_ADHERENCE_DECISION_ID } from '../lib/scopeAdherence.js';+import { safeChildProcessOptions } from '../lib/processEnv.js';+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';+// The trainer runs the SAME interpreter and the SAME hardened environment the+// sidecar runs, resolved from the one module that owns both. Re-deriving either+// here is how the "offline, no provider call" guarantee drifts apart from the+// process it is supposed to describe.+import { buildJevEnv, getJevStatus, jevPythonPath } from './jev.js';+import { buildScopeAdherenceCorpus } from './jevCorpusBuilder.js';+import { jevEmbeddingsDir, saveCandidateJevHead } from './jevHeads.js';++const execFileAsync = promisify(execFile);+const TRAINER_SCRIPT = join(PATHS.root, 'scripts', 'train_jev_head.py');+// Generous: the dominant cost is one forward pass per (clause, change) pair on+// a cold cache, which on a CPU-only host is minutes. A warm cache is seconds.+const TRAIN_TIMEOUT_MS = 60 * 60 * 1000;+const MAX_TRAINER_OUTPUT = 64 * 1024 * 1024;++const failure = (code, extra = {}) => ({ ok: false, code, ...extra });++let trainingInFlight = null;++/** Whether a training run is currently occupying the machine. */+export const isJevTrainingRunning = () => trainingInFlight !== null;++/**+ * Train a candidate head for `scope-adherence` against one checkout.+ *+ * `repoPath` defaults to THIS install's own checkout and has no route-level+ * override: a project head learns the product the operator is actually running,+ * and a caller-supplied path would turn a training button into an+ * arbitrary-directory reader with a forge token beside it — the same reasoning+ * that keeps `repoPath` out of `scopeAdherenceRequestSchema`.+ *+ * @param {object} [options]+ * @param {string} [options.repoPath] Checkout holding `PRD.md` / `GOALS.md` and the forge remote.+ * @param {'linear'|'mlp1'} [options.architecture]+ * @returns {Promise<{ok: true, metrics: object, corpus: object} | {ok: false, code: string}>}+ */+export function trainScopeAdherenceHead({ repoPath = PATHS.root, architecture = 'linear' } = {}) {+ // Single in-flight run, cleared in `finally` so one failure does not pin+ // every later request to the same rejection.+ if (trainingInFlight) return trainingInFlight;+ trainingInFlight = runTraining({ repoPath, architecture })+ .finally(() => { trainingInFlight = null; });+ return trainingInFlight;+}++async function runTraining({ repoPath, architecture }) {+ const status = await getJevStatus();+ // The trainer loads the same snapshot through the same venv the sidecar+ // uses. An install that has not finished the scorer install cannot train,+ // and saying so is more useful than a Python import error.+ if (!status.ready) return failure('jev-head-runtime-unavailable');++ const files = await findCachedRepoFiles(JEV_MODEL.repository, JEV_REQUIRED_FILES, { revision: JEV_MODEL.revision });+ if (!files?.[0]) return failure('jev-head-runtime-unavailable');+ const modelDir = dirname(files[0]);+ const pythonPath = jevPythonPath();+ if (!pythonPath) return failure('jev-head-runtime-unavailable');++ // The forge token overlay for the corpus reads, and ONLY for those: the+ // trainer below gets `buildJevEnv`, which carries no credential at all.+ // Deferred because `forgeAuth.js` reaches the git/forge stack this module has+ // no other use for.+ const { resolveForgeForRepo } = await import('./forgeAuth.js');+ const forge = await resolveForgeForRepo(repoPath).catch(() => null);+ const corpus = await buildScopeAdherenceCorpus({ repoPath, env: forge?.env || null });+ if (!corpus.ok) return corpus;++ const outPath = join(corpus.corpusDir, 'head.json');+ const args = [+ TRAINER_SCRIPT,+ '--model-dir', modelDir,+ '--corpus', join(corpus.corpusDir, 'train.jsonl'),+ '--gold', join(corpus.corpusDir, 'gold.jsonl'),+ '--out', outPath,+ '--cache-dir', jevEmbeddingsDir(),+ '--decision-id', SCOPE_ADHERENCE_DECISION_ID,+ '--model-id', JEV_MODEL.id,+ '--repository', JEV_MODEL.repository,+ '--revision', JEV_MODEL.revision,+ '--corpus-hash', corpus.corpusHash,+ '--corpus-sources', Object.keys(corpus.sources).filter((key) => corpus.sources[key] > 0).join(','),+ '--architecture', architecture,+ ];++ // The SAME hardened environment the sidecar gets: no API keys, no forge+ // token, no MCP or provider variables, no arbitrary PYTHONPATH, and+ // `HF_HUB_OFFLINE=1` so a missing file fails rather than downloading. The+ // forge token that built the corpus is deliberately not in scope here.+ const env = withSpawnCwdEnv(buildJevEnv(), dirname(pythonPath));+ const result = await execFileAsync(pythonPath, args, safeChildProcessOptions({+ cwd: dirname(pythonPath),+ env,+ timeout: TRAIN_TIMEOUT_MS,+ maxBuffer: MAX_TRAINER_OUTPUT,+ })).catch((error) => ({ failed: true, stdout: error?.stdout || '' }));++ // The trainer writes exactly one JSON line to stdout, so the report is the+ // last line whether or not the process exited cleanly — a failing run still+ // names its own code rather than collapsing into "training failed".+ const report = safeJSONParse(String(result.stdout || '').trim().split('\n').pop(), null, { allowArray: false, logError: false });+ if (!report?.ok) return failure(report?.code || 'jev-head-training-failed');++ const written = await tryReadFile(outPath);+ const head = written === null ? null : safeJSONParse(written, null, { allowArray: false, logError: false });+ if (!head) return failure('jev-head-training-failed');++ const saved = await saveCandidateJevHead(SCOPE_ADHERENCE_DECISION_ID, head);+ if (!saved.ok) return saved;+ return {+ ok: true,+ decisionId: SCOPE_ADHERENCE_DECISION_ID,+ metrics: saved.head.metrics,+ architecture: saved.head.architecture,+ corpus: {+ corpusHash: corpus.corpusHash,+ trainSize: corpus.trainSize,+ goldSize: corpus.goldSize,+ sources: corpus.sources,+ shadow: corpus.shadow,+ },+ };+}+diff --git a/server/services/jevTraining.test.js b/server/services/jevTraining.test.jsnew file mode 100644index 0000000000..db6984aed1--- /dev/null+++ b/server/services/jevTraining.test.js@@ -0,0 +1,167 @@+/**+ * The training run's boundaries.+ *+ * Every assertion here pins something invisible to the trained head's scores:+ * a forge token reaching the trainer's environment, a second 4B encoder load+ * from two overlapping runs, and a run that promotes its own output.+ */++import { mkdtemp } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const dataRoot = await mkdtemp(join(tmpdir(), 'portos-jev-training-'));+vi.mock('../lib/paths.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: dataRoot } };+});++const execFile = vi.fn();+vi.mock('../lib/childProcess.js', () => ({+ execFile: (command, args, options, callback) => execFile(command, args, options, callback),+ spawn: vi.fn(),+}));++const getJevStatus = vi.fn();+const jevPythonPath = vi.fn();+vi.mock('./jev.js', () => ({+ getJevStatus,+ jevPythonPath,+ // The real one, re-declared rather than imported: importing the module under+ // mock would defeat the mock. Its contract is what the assertion below reads.+ buildJevEnv: (source = process.env) => ({+ PATH: source.PATH,+ HOME: source.HOME,+ HF_HUB_OFFLINE: '1',+ TRANSFORMERS_OFFLINE: '1',+ }),+}));++const findCachedRepoFiles = vi.fn();+vi.mock('../lib/hfCache.js', () => ({ findCachedRepoFiles, getHfCacheRoot: () => '/tmp/hf-cache-double' }));++const buildScopeAdherenceCorpus = vi.fn();+vi.mock('./jevCorpusBuilder.js', () => ({ buildScopeAdherenceCorpus }));++const saveCandidateJevHead = vi.fn();+const adoptJevHead = vi.fn();+vi.mock('./jevHeads.js', () => ({+ saveCandidateJevHead,+ adoptJevHead,+ jevEmbeddingsDir: () => join(dataRoot, 'jev', 'embeddings'),+ jevHeadsDir: () => join(dataRoot, 'jev', 'heads'),+}));++const resolveForgeForRepo = vi.fn();+vi.mock('./forgeAuth.js', () => ({ resolveForgeForRepo }));++const tryReadFile = vi.fn();+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({ ...(await importOriginal()), tryReadFile }));++const { trainScopeAdherenceHead, isJevTrainingRunning } = await import('./jevTraining.js');++const METRICS = { trained: 0.71, stockZeroShot: 0.58, majorityClass: 0.52, goldSize: 40, trainSize: 120 };+const HEAD = { decisionId: 'scope-adherence', architecture: 'linear', metrics: METRICS };++/** A run where every dependency is healthy and the trainer reports success. */+function happyPath() {+ getJevStatus.mockResolvedValue({ ready: true });+ findCachedRepoFiles.mockResolvedValue(['/hf/snapshots/abc/qwen3.5-4b-nli/config.json']);+ jevPythonPath.mockReturnValue('/venv/bin/python3');+ resolveForgeForRepo.mockResolvedValue({ cli: 'gh', env: { ...process.env, GH_TOKEN: 'synthetic-token' } });+ buildScopeAdherenceCorpus.mockResolvedValue({+ ok: true,+ corpusHash: 'deadbeefcafe0001',+ corpusDir: join(dataRoot, 'jev', 'corpora', 'scope-adherence-deadbeefcafe0001'),+ trainSize: 120,+ goldSize: 40,+ sources: { 'merged-pr': 90, 'closed-unmerged-pr': 0, 'closed-not-planned-issue': 70, 'parked-issue': 0 },+ shadow: { observed: 12, compared: 4, agreementRate: 0.75 },+ });+ execFile.mockImplementation((_command, _args, _options, callback) => callback(null, {+ stdout: `encoded 1/2\n${JSON.stringify({ ok: true, metrics: METRICS, finalLoss: 0.3, device: 'cpu' })}\n`,+ stderr: '',+ }));+ tryReadFile.mockResolvedValue(JSON.stringify(HEAD));+ saveCandidateJevHead.mockResolvedValue({ ok: true, head: HEAD });+}++beforeEach(() => {+ vi.clearAllMocks();+ happyPath();+});++describe('trainScopeAdherenceHead', () => {+ it('writes a candidate and never promotes it', async () => {+ const result = await trainScopeAdherenceHead();+ expect(result).toMatchObject({ ok: true, decisionId: 'scope-adherence', metrics: METRICS });+ expect(saveCandidateJevHead).toHaveBeenCalledWith('scope-adherence', HEAD);+ expect(adoptJevHead).not.toHaveBeenCalled();+ // The three baselines and the corpus balance come back; no example does.+ expect(result.corpus.sources['merged-pr']).toBe(90);+ expect(JSON.stringify(result)).not.toContain('synthetic-token');+ });++ // The privacy boundary the whole design rests on: the corpus build reads the+ // forge with a token, and the TRAINER must not receive it — nor any other+ // credential, nor a network-capable Hugging Face mode.+ it('gives the trainer the hardened offline environment, never the forge token', async () => {+ await trainScopeAdherenceHead();+ const [command, args, options] = execFile.mock.calls[0];+ expect(command).toBe('/venv/bin/python3');+ expect(args[0]).toMatch(/train_jev_head\.py$/);+ expect(options.env.GH_TOKEN).toBeUndefined();+ expect(options.env.GITHUB_TOKEN).toBeUndefined();+ expect(options.env.HF_HUB_OFFLINE).toBe('1');+ // Which encoder it is fit on is passed explicitly, so the head can record+ // the revision its loader will later refuse a mismatch against.+ expect(args).toContain('--revision');+ expect(args).toContain('--corpus-hash');+ });++ // Two overlapping runs would load a second 4B encoder on a machine that may+ // already be holding the sidecar's copy resident.+ it('joins a run already in flight rather than starting a second', async () => {+ let release;+ // Resolved when the trainer has actually been spawned. Calling `release`+ // before that point would throw inside the test and leave the in-flight+ // promise pending forever, wedging every case after this one.+ const spawned = new Promise((reached) => {+ execFile.mockImplementation((_command, _args, _options, callback) => {+ release = () => callback(null, { stdout: JSON.stringify({ ok: true, metrics: METRICS }), stderr: '' });+ reached();+ });+ });+ const first = trainScopeAdherenceHead();+ const second = trainScopeAdherenceHead();+ await spawned;+ expect(isJevTrainingRunning()).toBe(true);+ release();+ await Promise.all([first, second]);+ expect(execFile).toHaveBeenCalledTimes(1);+ expect(isJevTrainingRunning()).toBe(false);+ });++ it('reports the trainer\'s own code rather than collapsing every failure into one', async () => {+ execFile.mockImplementation((_command, _args, _options, callback) => {+ const error = new Error('exit 1');+ error.stdout = `${JSON.stringify({ ok: false, code: 'jev-corpus-split-overlap' })}\n`;+ callback(error);+ });+ expect(await trainScopeAdherenceHead()).toEqual({ ok: false, code: 'jev-corpus-split-overlap' });+ expect(saveCandidateJevHead).not.toHaveBeenCalled();+ });++ it('refuses to train before the scorer install is finished', async () => {+ getJevStatus.mockResolvedValue({ ready: false });+ expect(await trainScopeAdherenceHead()).toEqual({ ok: false, code: 'jev-head-runtime-unavailable' });+ expect(buildScopeAdherenceCorpus).not.toHaveBeenCalled();+ });++ it('forwards a corpus refusal untouched instead of training on it', async () => {+ buildScopeAdherenceCorpus.mockResolvedValue({ ok: false, code: 'jev-corpus-split-overlap' });+ expect(await trainScopeAdherenceHead()).toEqual({ ok: false, code: 'jev-corpus-split-overlap' });+ expect(execFile).not.toHaveBeenCalled();+ });+});diff --git a/server/services/sharing/jevNeverFederates.test.js b/server/services/sharing/jevNeverFederates.test.jsnew file mode 100644index 0000000000..d427977f03--- /dev/null+++ b/server/services/sharing/jevNeverFederates.test.js@@ -0,0 +1,105 @@+/**+ * Guard: trained jev heads, their corpora and their cached embeddings must+ * NEVER federate (#7689).+ *+ * `data/jev/` is a DERIVED RECORD OF PRIVATE DATA. A corpus is this install's+ * merged pull requests and closed issues rendered as premises; a trained head+ * is a few thousand floats fit on exactly that, plus the operator's own+ * judgement calls about which of them were worth shipping. The machine-local+ * ADR (`docs/decisions/2026-08-08-privacy-records-machine-local.md`) covers the+ * path, and the issue that introduced heads names pooling corpora across peers+ * as refused rather than unimplemented.+ *+ * Blunt on purpose, the same way `privacyNeverFederates.test.js` and+ * `beeperNeverFederates.test.js` are: it matches `jev` and `head` broadly+ * across each federation surface, so a future `jevHead`, `jevCorpus` or+ * `trainedHead` kind trips it whatever it ends up being called.+ *+ * Every filter is paired with a floor on the list it filters. A federation+ * surface that collapsed to `[]` — a renamed export, a registry read too early+ * — would satisfy a bare `.filter(...).toEqual([])` while guarding nothing.+ */++import { describe, it, expect } from 'vitest';+import { basename } from 'path';+import { PEER_SUBSCRIBABLE_KINDS } from './peerSyncShared.js';+import { NON_RECORD_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';+import { mediaLibraryDirs } from './peerMediaLibrarySync.js';++// `jev` alone would miss a kind called `trainedHead`; `head` alone would fire+// on an unrelated `headshot`. Both, anchored on a word-ish boundary.+const JEV_TERMS = /jev|trained_?head|head_?weights|scope_?adherence/i;+const mentionsJev = (value) => JEV_TERMS.test(String(value));++/**+ * A media-library walk entry that would carry `data/jev/` to a peer.+ *+ * Matched on the BASENAME only, for the reason the Beeper guard states: entries+ * are always `<installRoot>/data/<kind>`, so matching any path segment would+ * also fire on an ancestor directory that merely happens to be called `jev`.+ */+const namesJevMedia = ({ kind, dir }) => mentionsJev(kind) || /^jev/i.test(basename(String(dir)));++describe('trained jev heads and their corpora never federate (#7689)', () => {+ it('exposes no jev kind to peer-sync subscriptions', () => {+ expect(PEER_SUBSCRIBABLE_KINDS.length).toBeGreaterThan(10);+ expect(PEER_SUBSCRIBABLE_KINDS.filter(mentionsJev)).toEqual([]);+ });++ it('declares no jev wire-schema category', () => {+ expect(Object.keys(PORTOS_SCHEMA_VERSIONS).length).toBeGreaterThan(15);+ expect([...NON_RECORD_SCHEMA_CATEGORIES].length).toBeGreaterThan(1);+ expect(Object.keys(PORTOS_SCHEMA_VERSIONS).filter(mentionsJev)).toEqual([]);+ expect([...NON_RECORD_SCHEMA_CATEGORIES].filter(mentionsJev)).toEqual([]);+ });++ // Explicit timeout: the lazy import resolves the whole dataSync service graph+ // inside the test body (see privacyNeverFederates.test.js for why that cost+ // is paid here rather than at module load).+ it('declares no jev dataSync snapshot category', async () => {+ const { getSupportedCategories } = await import('../dataSync.js');+ expect(getSupportedCategories().length).toBeGreaterThan(5);+ expect(getSupportedCategories().filter(mentionsJev)).toEqual([]);+ }, 30000);++ // The media-library manifest is the OTHER way `data/` bytes reach a peer: it+ // walks whole directories rather than record kinds, so no schema-version or+ // subscription guard above covers it.+ it('carries no jev directory into the media-library federation walk', () => {+ const dirs = mediaLibraryDirs();+ // Non-vacuity pin: image, video, audio, music.+ expect(dirs).toHaveLength(4);+ expect(dirs.filter(namesJevMedia)).toEqual([]);+ });++ // The BACKUP tier, which is the other decision `data/jev/` needed making+ // explicitly. Corpora and cached embeddings are regenerable bulk and are+ // excluded; a trained head is NOT regenerable once its corpus is stale, so it+ // must NOT be. Every pattern is anchored with a leading `/` — an unanchored+ // rsync filter matches at any depth and silently drops unrelated user data,+ // which is a data-loss bug (AGENTS.md, "Backup excludes").+ it('excludes jev corpora and embeddings from backups, and retains trained heads', async () => {+ const { DEFAULT_EXCLUDES } = await import('../backup.js');+ const jevEntries = DEFAULT_EXCLUDES.filter((entry) => /^\/jev\//.test(entry.path));+ expect(jevEntries.map((entry) => entry.path).sort()).toEqual(['/jev/corpora/', '/jev/embeddings/']);+ expect(jevEntries.every((entry) => entry.path.startsWith('/'))).toBe(true);+ // The retention half, stated as an assertion rather than an absence: no+ // exclude may match the heads directory.+ expect(DEFAULT_EXCLUDES.filter((entry) => entry.path.includes('/jev/heads'))).toEqual([]);+ }, 30000);++ // Bypass probe — proves the assertions above actually fire.+ it('the guard predicates reject a planted violation', () => {+ expect(['universe', 'jevHead', 'trainedHead'].filter(mentionsJev)).toEqual(['jevHead', 'trainedHead']);+ // The planted dir entry carries a NON-jev kind, so only the basename branch+ // can catch it; the trailing entry pins that an ancestor named `jev` is not+ // itself a violation.+ expect(+ [+ { kind: 'image', dir: '/data/images' },+ { kind: 'weights', dir: '/data/jev' },+ { kind: 'image', dir: '/jev/checkout/data/images' },+ ].filter(namesJevMedia),+ ).toEqual([{ kind: 'weights', dir: '/data/jev' }]);+ });+});