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
refactor: give the jev head path one owner per contract after self-review (#7689)
[._.]/ Adam Eivyc0c9c4c55ad4
diff --git a/client/src/components/models/JevPanel.jsx b/client/src/components/models/JevPanel.jsxindex e6e5fa0907..3764d1cc0d 100644--- a/client/src/components/models/JevPanel.jsx+++ b/client/src/components/models/JevPanel.jsx@@ -16,6 +16,7 @@ import {unloadJev,} from '../../services/api';import socket from '../../services/socket';+import { jevHeadBlockerLabel } from '../../lib/jevHeadReasons';// Shown before the first status response lands, and if status is unavailable,// so the checklist never renders as an empty box. Mirrors JEV_STAGES in@@ -42,14 +43,6 @@ const formatRate = (rate) => formatPercent(rate === null ? null : rate * 100);// 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);@@ -66,6 +59,11 @@ export default function JevPanel() {const [headState, setHeadState] = useState(null);const [training, setTraining] = useState(false);const [headError, setHeadError] = useState('');+ // `linear` is the honest default: a 3-way logistic regression over a frozen+ // 4B encoder. `mlp1` buys one hidden layer for a corpus large enough to+ // support it — exposed rather than server-only, because a knob only a+ // hand-written request can reach is a knob nobody tunes.+ const [architecture, setArchitecture] = useState('linear');const progressTimer = useRef(null);const loadStatus = useCallback(() => (@@ -92,11 +90,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); });+ loadHeads();return () => { active = false; };- }, [loadStatus]);+ }, [loadStatus, loadHeads]);useEffect(() => {const handleProgress = (data) => {@@ -158,31 +154,40 @@ export default function JevPanel() {.finally(() => { setScoring(false); loadStatus(); });};- const runTraining = () => {+ /**+ * Run one head action and re-read the state either way.+ *+ * A failure is shown in the section beside the scores rather than as a toast:+ * the operator is reading the three numbers right here, and the reason a run+ * produced none belongs with them. Re-loading on the failure path too is what+ * keeps the table honest when the server refused for a reason the panel had+ * stale state about.+ */+ const runHeadAction = (action, fallbackMessage) => {setHeadError('');+ return action+ .then((result) => loadHeads().then(() => result))+ .catch((error) => { setHeadError(error.message || fallbackMessage); return loadHeads(); });+ };++ const runTraining = () => {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(); })+ return runHeadAction(trainJevHead({ architecture }, { silent: true }), 'Training failed.').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 adoptHead = (decisionId) => runHeadAction(+ adoptJevHead(decisionId, { silent: true }).then((result) => {+ toast.success('Project head adopted');+ return result;+ }),+ 'This head cannot be adopted.',+ );- const discardHead = (decisionId, adopted) => {- setHeadError('');- return discardJevHead(decisionId, { adopted }, { silent: true })- .then(() => loadHeads())- .catch((error) => { setHeadError(error.message || 'Discard failed.'); return loadHeads(); });- };+ const discardHead = (decisionId, adopted) => runHeadAction(+ discardJevHead(decisionId, { adopted }, { silent: true }),+ 'Discard failed.',+ );const stages = stagesFromStatus(status);const currentStageId = installingStage || (installing ? stages.find((stage) => !stage.ready)?.id : null);@@ -432,7 +437,7 @@ export default function JevPanel() {</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>+ <p className="text-[11px] text-port-warning mt-1 max-w-xs">{jevHeadBlockerLabel(row.blocker)}</p>)}{row.ok && (<p className="text-[11px] text-gray-500 mt-1">@@ -457,6 +462,17 @@ export default function JevPanel() {><GraduationCap size={12} /> {training ? 'Training…' : 'Train a project head'}</button>+ <label htmlFor="jev-head-architecture" className="text-xs text-gray-400">Head</label>+ <select+ id="jev-head-architecture"+ value={architecture}+ onChange={(event) => setArchitecture(event.target.value)}+ disabled={training}+ className="text-xs bg-port-bg border border-port-border rounded px-2 py-1 text-gray-200 disabled:opacity-50"+ >+ <option value="linear">Linear</option>+ <option value="mlp1">One hidden layer</option>+ </select>{!ready && <span className="text-xs text-gray-500">Install jev first.</span>}{training && (<span className="flex items-center gap-1.5 text-xs text-gray-300">diff --git a/client/src/components/models/JevPanel.test.jsx b/client/src/components/models/JevPanel.test.jsxindex 84c4677a68..84f13cfddd 100644--- a/client/src/components/models/JevPanel.test.jsx+++ b/client/src/components/models/JevPanel.test.jsx@@ -310,7 +310,7 @@ describe('JevPanel project head', () => {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 });+ expect(trainJevHead).toHaveBeenCalledWith({ architecture: 'linear' }, { silent: true });// Training NEVER promotes: the run's only follow-up is re-reading state.expect(adoptJevHead).not.toHaveBeenCalled();});@@ -325,3 +325,17 @@ describe('JevPanel project head', () => {expect(await screen.findByRole('alert')).toHaveTextContent('jev-corpus-too-small');});});++describe('JevPanel head architecture', () => {+ // `mlp1` is in the artifact contract and the trainer; a knob only a+ // hand-written request could reach is a knob nobody tunes.+ it('trains the architecture the operator picked', 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());+ fireEvent.change(screen.getByLabelText('Head'), { target: { value: 'mlp1' } });+ await act(async () => { fireEvent.click(button); });+ expect(trainJevHead).toHaveBeenCalledWith({ architecture: 'mlp1' }, { silent: true });+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 6bf00017e3..82959e39c1 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -267,6 +267,7 @@ grep -i "what you want to do" client/src/lib/README.md| `publicGuestRoutes.js` | `isPublicGuestRoute` identifies standalone guest pages that skip private app bootstrap. || `riggingReasons.js` | Client mirror of the character-rigging readiness reason labels in `server/services/rigging/readiness.js`: `RIGGING_UNAVAILABLE_REASONS` (reason code -> user-facing label), `RIGGING_REASON_FALLBACK`, and `riggingReasonLabel(code, fallback?)`. Render these anywhere a `GET /api/rigging/readiness` reason is shown; never re-declare the codes. Parity + code coverage enforced by `server/services/rigging/unavailableReasons.parity.test.js`. || `scopeAdherenceReasons.js` | Re-export of `server/lib/scopeAdherenceReasons.js` — operator-facing labels for a scope-adherence failure code (`SCOPE_ADHERENCE_REASONS`, `SCOPE_ADHERENCE_REASON_FALLBACK`, `scopeAdherenceReasonLabel`). Every label reads as "no advisory", never as a verdict. One definition, no mirror to keep in parity. |+| `jevHeadReasons.js` | Re-export of `server/lib/jevHeadReasons.js` - operator-facing labels for why a trained jev project head cannot be adopted (`JEV_HEAD_BLOCKER_REASONS`, `JEV_HEAD_BLOCKER_FALLBACK`, `jevHeadBlockerLabel`). Each label names WHICH baseline the head lost to, because the stock scorer and the majority class send an operator to different places. One definition, no mirror to keep in parity. || `usagePeriods.js` | The report windows every usage-cost surface offers — `USAGE_PERIOD_OPTIONS`, `DEFAULT_USAGE_PERIOD` (what a URL with no `?period` means) and `resolveUsagePeriod`. Shared because `?period` is a URL param the user carries between the Usage and Subscriptions pages; two copies had already disagreed on the default. || `usdzExport.js` | AR Quick Look (USDZ) export for the 3D viewer (#5756): `exportSceneToUsdz(scene, { maxTextureSize })` lazy-loads three's `USDZExporter` and serializes the already-decoded scene to bytes, `countSceneTriangles(object3d)` measures an object graph against `AR_TRIANGLE_BUDGET`, and `supportsArQuickLook()` feature-detects the `<a rel="ar">` handoff (Safari on iOS/iPadOS only — never sniff the user agent) so a desktop is offered a download instead of a button that does nothing. `AR_MAX_TEXTURE_SIZE` bounds the file: USDZ stores every texel raw, with no Draco/meshopt equivalent. || `installFailureTask.js` | Build the CoS task payload behind the installer-failure "Queue agent to investigate" button (#5981): `buildInstallFailureTask({ label, stage, error, logs, surface })` → `{ description, prompt }` carrying the installer name, failing stage, error text and a bounded log tail, and `installLogTail(logs)` (the `useInstallStream` `{ kind, text }` entries rendered as text, capped at `INSTALL_FAILURE_LOG_TAIL_LINES` / `INSTALL_FAILURE_LOG_TAIL_CHARS` so a 1000-line pip stream cannot push a huge body through `POST /api/cos/tasks`, cutting on a line boundary, redacting the home-directory paths pip/git echo, and neutralizing a log line that would close the prompt fence). Shared by both install modals and `LocalSetupPanel` so every surface queues the same reproducible context. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 2abcfa8cec..04701399ff 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -226,6 +226,7 @@ export * from './wrSceneCursor.js';export * from './writingGuide.js';export * from './qrCode.js';export * from './riggingReasons.js';+export * from './jevHeadReasons.js';export * from './scopeAdherenceReasons.js';export * from './usagePeriods.js';export * from './usdzExport.js';diff --git a/client/src/lib/jevHeadReasons.js b/client/src/lib/jevHeadReasons.jsnew file mode 100644index 0000000000..c0a5225cd6--- /dev/null+++ b/client/src/lib/jevHeadReasons.js@@ -0,0 +1,16 @@+/**+ * Re-export of `server/lib/jevHeadReasons.js` — the one definition of the+ * operator-facing labels for why a trained project head cannot be adopted.+ *+ * A re-export rather than a mirror, exactly as `scopeAdherenceReasons.js` is: a+ * mirror would need a parity test, and a parity test would need a server file+ * importing a client file, which `scripts/server-imports-no-client.test.js`+ * forbids. The server leaf has no imports of its own, so it is safe to pull+ * into the browser bundle.+ */++export {+ JEV_HEAD_BLOCKER_REASONS,+ JEV_HEAD_BLOCKER_FALLBACK,+ jevHeadBlockerLabel,+} from '../../../server/lib/jevHeadReasons.js';diff --git a/docs/features/scope-adherence.md b/docs/features/scope-adherence.mdindex 028622d1e3..e7db21d125 100644--- a/docs/features/scope-adherence.md+++ b/docs/features/scope-adherence.md@@ -92,7 +92,7 @@ Nothing about the advisory contract changes. A head emits the checkpoint's own t| 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 |+| issues labelled `future` or `needs-input` | `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.diff --git a/scripts/jev_head_kit.py b/scripts/jev_head_kit.pyindex 1e79d5127f..13003298f2 100644--- a/scripts/jev_head_kit.py+++ b/scripts/jev_head_kit.py@@ -35,6 +35,10 @@ LABELS = ("contradiction", "entailment", "neutral")SLUG = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")+# Used only when the checkpoint's config omits its own `nli_template`.+FALLBACK_TEMPLATE = "Premise: {premise}\nHypothesis: {hypothesis}"++class HeadError(Exception):"""A head failure the Node service can map to a code without reading text."""@@ -43,6 +47,100 @@ class HeadError(Exception):self.code = code+def resolve_template(config) -> str:+ """The checkpoint's own NLI template, or the fallback.++ Shared by the sidecar and the trainer: a head fit under one template and+ applied under another is fit on a different vector space than it is scored+ in, which is the exact drift this module exists to prevent.+ """+ template = getattr(config, "nli_template", None)+ if not isinstance(template, str) or "{premise}" not in template or "{hypothesis}" not in template:+ return FALLBACK_TEMPLATE+ return template+++def resolve_window(tokenizer, config) -> int:+ """The largest token count one pair may occupy.++ Transformers uses a sentinel-sized `model_max_length` for tokenizers that+ declare none, which would read as "everything fits" — so an implausible+ value falls through to the text config's position count.+ """+ candidates = []+ for value in (getattr(tokenizer, "model_max_length", None),+ getattr(getattr(config, "text_config", None), "max_position_embeddings", None),+ getattr(config, "max_position_embeddings", None)):+ if isinstance(value, int) and 0 < value < 10_000_000:+ candidates.append(value)+ if not candidates:+ raise HeadError("jev-response-invalid")+ return min(candidates)+++def load_encoder(model_dir):+ """Load the pinned snapshot and build the state `pool_pair` reads.++ ONE loader for both processes. The sidecar layers its `id2label` mapping on+ top (it needs the checkpoint's own classifier); the trainer freezes the+ parameters. Everything that decides how a pair becomes a vector — the+ device, the template, the window, the final-hidden-state hook — is decided+ here, once, or the trainer and the sidecar pool differently.+ """+ import torch+ from transformers import AutoModelForSequenceClassification, AutoTokenizer++ torch.set_num_threads(1)+ tokenizer = AutoTokenizer.from_pretrained(+ str(model_dir), local_files_only=True, trust_remote_code=False+ )+ model = AutoModelForSequenceClassification.from_pretrained(+ str(model_dir),+ local_files_only=True,+ trust_remote_code=False,+ use_safetensors=True,+ )+ # MPS where the host has it, CPU otherwise. Reported on /health so an+ # operator can tell a slow CPU fallback from a healthy accelerated load.+ device = "mps" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available() else "cpu"+ model.to(device)+ model.eval()++ captured, _handle = capture_final_hidden_state(model)+ return {+ "torch": torch,+ "tokenizer": tokenizer,+ "model": model,+ "device": device,+ "template": resolve_template(model.config),+ "window": resolve_window(tokenizer, model.config),+ "hiddenCapture": captured,+ }+++def capture_final_hidden_state(model):+ """Register a forward hook that keeps ONLY the final hidden state.++ Returns `(captured, handle)`, where `captured["value"]` holds the last+ encoder output after each forward pass.++ `output_hidden_states=True` would be one line shorter and is what this+ started as. It is also the expensive way: it retains one activation tensor+ per decoder layer for the whole pass, and this checkpoint has dozens — a+ few hundred megabytes of extra peak allocation per pair, on a machine that+ may already be holding the 9 GB sidecar copy resident, to use exactly one+ of them. A hook on the base model keeps the one.+ """+ captured = {}++ def keep(_module, _inputs, output):+ # A base `PreTrainedModel` returns either a tuple whose first element is+ # the last hidden state, or a ModelOutput carrying it by name.+ captured["value"] = output[0] if isinstance(output, tuple) else output.last_hidden_state++ return captured, model.base_model.register_forward_hook(keep)++def pool_pair(state, premise: str, hypothesis: str):"""Encode one pair and return `(pooled_vector, stock_logits)`.@@ -70,9 +168,16 @@ def pool_pair(state, premise: str, hypothesis: str):"input_ids": torch.tensor([token_ids]).to(device),"attention_mask": torch.tensor([[1] * len(token_ids)]).to(device),}+ # The hook is installed once per loaded model and lives in `state`;+ # re-registering it per pair would stack a new one on every call.+ captured = state["hiddenCapture"]+ captured.pop("value", None)with torch.inference_mode():- output = model(**model_inputs, output_hidden_states=True)- pooled = output.hidden_states[-1][0, -1, :].to("cpu").float().tolist()+ output = model(**model_inputs)+ hidden = captured.get("value")+ if hidden is None:+ raise HeadError("jev-head-invalid")+ pooled = hidden[0, -1, :].to("cpu").float().tolist()logits = output.logits[0].to("cpu").float().tolist()return pooled, logits@@ -103,6 +208,12 @@ def validate_head(raw, *, revision: str):hidden_size = raw.get("hiddenSize")if not isinstance(layers, list) or not 1 <= len(layers) <= 2:raise HeadError("jev-head-invalid")+ # The architecture's own layer count. Mirrors `parseJevHead`: a `linear`+ # head declaring two layers, or an `mlp1` declaring one, is an artifact+ # whose stated shape disagrees with its weights — and the two validators+ # disagreeing about that is precisely the drift this mirror must not have.+ if len(layers) != (2 if raw["architecture"] == "mlp1" else 1):+ raise HeadError("jev-head-invalid")if not isinstance(hidden_size, int) or hidden_size < 1:raise HeadError("jev-head-invalid")@@ -136,18 +247,41 @@ def validate_head(raw, *, revision: str):return raw-def load_head(heads_dir, slug: str, *, revision: str):- """Read and validate `<heads_dir>/<slug>.json`.+def head_path(heads_dir, slug: str):+ """Resolve `<heads_dir>/<slug>.json`, refusing a slug that is a path.- `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.+ The charset is matched BEFORE the name 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():+ if path.parent != root:+ raise HeadError("jev-head-invalid")+ return path+++def head_file_identity(heads_dir, slug: str):+ """A cheap `(mtime_ns, size)` fingerprint, or None when there is no file.++ What makes the sidecar's head cache invalidatable from the side that can+ observe an adoption: Node rewrites the file, the fingerprint moves, the+ next request re-reads it.+ """+ path = head_path(heads_dir, slug)+ try:+ info = path.stat()+ except OSError:+ return None+ return (info.st_mtime_ns, info.st_size)+++def load_head(heads_dir, slug: str, *, revision: str):+ """Read and validate `<heads_dir>/<slug>.json`."""+ path = head_path(heads_dir, slug)+ if not path.is_file():raise HeadError("jev-head-not-found")try:raw = json.loads(path.read_text(encoding="utf-8"))diff --git a/scripts/jev_head_kit.test.js b/scripts/jev_head_kit.test.jsindex dcc8d5253c..3f71b5ee70 100644--- a/scripts/jev_head_kit.test.js+++ b/scripts/jev_head_kit.test.js@@ -128,9 +128,37 @@ print(json.dumps({"top": max(scores, key=scores.get)}))expect(loadCode(dir, 'message-triage')).toBe('jev-head-unreadable');});+ // The sidecar outlives adopt and discard, and Node's `resetJevHeadCache`+ // cannot reach it — so the file's identity is what makes its cache+ // invalidatable from the side that can observe an adoption.+ it('moves a head file\'s identity when its contents are replaced', () => {+ const { dir } = headsDir();+ const first = identity(dir, 'scope-adherence');+ expect(first).not.toBeNull();+ // A different LENGTH as well as different bytes: a same-size rewrite in the+ // same clock tick would leave the fingerprint unchanged on a filesystem+ // with coarse mtime resolution, and this test is not the place to find out.+ writeFileSync(join(dir, 'scope-adherence.json'), JSON.stringify(head({+ corpusHash: 'cafe000000000002',+ corpusSources: ['merged-pr', 'closed-unmerged-pr', 'parked-issue'],+ })));+ expect(identity(dir, 'scope-adherence')).not.toEqual(first);+ // No file is an absence, not a fingerprint that could collide with one.+ expect(identity(dir, 'message-triage')).toBeNull();+ });+it('rejects the shapes the Node-side parser rejects', () => {const cases = {relabelled: head({ labels: ['entailment', 'contradiction', 'neutral'] }),+ // The two rules the Node parser enforces that this mirror once did not:+ // a `linear` head declaring two layers, and an `mlp1` declaring one.+ linearWithTwoLayers: head({+ layers: [+ { weight: [[1, 0, 0], [0, 1, 0]], bias: [0, 0] },+ { weight: [[1, 0], [0, 1], [1, 1]], bias: [0, 0, 0] },+ ],+ }),+ mlpWithOneLayer: head({ architecture: 'mlp1' }),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] }] }),@@ -151,6 +179,8 @@ print(json.dumps(out))`));expect(raw).toEqual({relabelled: 'jev-head-invalid',+ linearWithTwoLayers: 'jev-head-invalid',+ mlpWithOneLayer: 'jev-head-invalid',wrongHiddenSize: 'jev-head-invalid',wrongOutputWidth: 'jev-head-invalid',biasMismatch: 'jev-head-invalid',@@ -161,6 +191,14 @@ print(json.dumps(out))});});+/** `head_file_identity` for one slug, as a comparable value. */+function identity(dir, slug) {+ return JSON.parse(run(`+value = kit["head_file_identity"](${JSON.stringify(dir)}, ${JSON.stringify(slug)})+print(json.dumps({"identity": list(value) if value else None}))+`)).identity;+}+/** `load_head`'s failure code for one slug, or null when it loaded. */function loadCode(dir, slug) {return JSON.parse(run(`diff --git a/scripts/run_jev.py b/scripts/run_jev.pyindex 06df8ce049..1854d17b5c 100644--- a/scripts/run_jev.py+++ b/scripts/run_jev.py@@ -34,7 +34,9 @@ from threading import Lock# 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.+from jev_head_kit import ( # noqa: E402 - needs the sys.path line above.+ HeadError, apply_head, head_file_identity, load_encoder, load_head, pool_pair,+)# 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.@@ -44,10 +46,10 @@ MAX_HYPOTHESIS_CHARS = 512MAX_BODY_BYTES = 256_000LOOPBACK_HOSTS = ("127.0.0.1", "::1")-# The model's own label order, from the pinned config's `id2label`.+# The model's own label order, from the pinned config's `id2label`. The prompt+# template, the window resolution and the pooling live in `jev_head_kit.py`,+# because the trainer has to agree with this process about all three.LABELS = ("contradiction", "entailment", "neutral")-# Used only when the checkpoint's config omits its own `nli_template`.-FALLBACK_TEMPLATE = "Premise: {premise}\nHypothesis: {hypothesis}"class JevError(Exception):@@ -83,35 +85,22 @@ def validate_request(payload):def load_state(model_dir: Path):- """Load the pinned snapshot once. Imports happen only after path checks."""- import torch- from transformers import AutoModelForSequenceClassification, AutoTokenizer+ """Load the pinned snapshot once, then add the checkpoint's own label map.- torch.set_num_threads(1)- tokenizer = AutoTokenizer.from_pretrained(- str(model_dir), local_files_only=True, trust_remote_code=False- )- model = AutoModelForSequenceClassification.from_pretrained(- str(model_dir),- local_files_only=True,- trust_remote_code=False,- use_safetensors=True,- )- # MPS where the host has it, CPU otherwise. Reported on /health so an- # operator can tell a slow CPU fallback from a healthy accelerated load.- device = "mps" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available() else "cpu"- model.to(device)- model.eval()+ Everything that decides HOW a pair becomes a vector — device, template,+ window, final-hidden-state hook — comes from `jev_head_kit.load_encoder`,+ the one loader the trainer uses too. A trainer that pooled differently+ would fit a head on a vector space this process never produces.- config = model.config- template = getattr(config, "nli_template", None)- if not isinstance(template, str) or "{premise}" not in template or "{hypothesis}" not in template:- template = FALLBACK_TEMPLATE+ Imports happen inside the kit, after the path checks in `main`.+ """+ state = load_encoder(model_dir)# The label mapping is read from the checkpoint rather than assumed: a# re-trained head with a permuted id2label would otherwise silently turn- # every entailment score into a contradiction score.- id_to_label = getattr(config, "id2label", None) or {}+ # every entailment score into a contradiction score. Only the SIDECAR needs+ # it — the trainer never reads the checkpoint's own classifier by name.+ id_to_label = getattr(state["model"].config, "id2label", None) or {}label_index = {}for class_id, label in id_to_label.items():name = str(label).strip().lower()@@ -119,34 +108,8 @@ def load_state(model_dir: Path):label_index[name] = int(class_id)if len(label_index) != len(LABELS):raise JevError("jev-response-invalid", status=500)-- return {- "torch": torch,- "tokenizer": tokenizer,- "model": model,- "device": device,- "template": template,- "labelIndex": label_index,- "window": resolve_window(tokenizer, config),- }---def resolve_window(tokenizer, config) -> int:- """The largest token count one pair may occupy.-- Transformers uses a sentinel-sized `model_max_length` for tokenizers that- declare none, which would read as "everything fits" — so an implausible- value falls through to the text config's position count.- """- candidates = []- for value in (getattr(tokenizer, "model_max_length", None),- getattr(getattr(config, "text_config", None), "max_position_embeddings", None),- getattr(config, "max_position_embeddings", None)):- if isinstance(value, int) and 0 < value < 10_000_000:- candidates.append(value)- if not candidates:- raise JevError("jev-response-invalid", status=500)- return min(candidates)+ state["labelIndex"] = label_index+ return statedef score_with_head(state, head, premise: str, hypotheses):@@ -192,9 +155,13 @@ def score_pairs(state, premise: str, hypotheses):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.+ # Validated heads, keyed by slug AND the file's identity. Keying on the slug+ # alone would be a cache with no invalidation channel: this process outlives+ # adopt and discard, and Node's own `resetJevHeadCache` cannot reach it — so+ # a second train-then-adopt for the same decision would keep HITTING, and+ # the sidecar would answer with the superseded weights while the panel+ # reported the new head's scores. That is exactly the "measurement describes+ # something other than what ran" failure the head path exists to avoid.head_cache = {}def resolve_head(slug):@@ -202,9 +169,11 @@ def make_handler(state, model_id: str, revision: str, heads_dir):return Noneif 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]+ identity = head_file_identity(heads_dir, slug)+ cached = head_cache.get(slug)+ if cached is None or cached[0] != identity:+ head_cache[slug] = (identity, load_head(heads_dir, slug, revision=revision))+ return head_cache[slug][1]class JevHandler(BaseHTTPRequestHandler):protocol_version = "HTTP/1.1"diff --git a/scripts/run_jev.test.js b/scripts/run_jev.test.jsindex 7a2175009f..e24b12bb13 100644--- a/scripts/run_jev.test.js+++ b/scripts/run_jev.test.js@@ -38,6 +38,13 @@ model.config = SimpleNamespace()model.to = lambda *_args: Nonemodel.eval = lambda: None+# The base encoder the kit hooks to capture ONLY the final hidden state. The+# real one is a PreTrainedModel; all the kit needs of it is a place to hang a+# forward hook, so the double records the handler and lets each test fire it.+hooks = []+model.base_model = SimpleNamespace(+ register_forward_hook=lambda fn: hooks.append(fn) or SimpleNamespace(remove=lambda: None)+)def load(value):def from_pretrained(_path, **kwargs):@@ -190,9 +197,14 @@ class Hidden:assert key == (0, -1, slice(None)), keyreturn Row([0.0, 3.0, 0.0])+# The kit hooks the BASE model and reads what the hook captured, so the double+# fires the registered hook rather than returning hidden states inline — and+# asserts the caller no longer pays for every layer's activations.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()])+ assert "output_hidden_states" not in inputs, inputs+ for hook in hooks:+ hook(None, None, (Hidden(),))+ return SimpleNamespace(logits=[Row([0.0, 0.0, 0.0])])model_with_hidden.config = model.configstate["model"] = model_with_hiddendiff --git a/scripts/train_jev_head.py b/scripts/train_jev_head.pyindex 2d2842a5dc..134133f6ca 100644--- a/scripts/train_jev_head.py+++ b/scripts/train_jev_head.py@@ -40,7 +40,9 @@ from pathlib import Path# 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.+from jev_head_kit import ( # noqa: E402 - needs the sys.path line above.+ HEAD_SCHEMA_VERSION, LABELS, MAX_HIDDEN, POOLING, load_encoder, pool_pair,+)ENTAILMENT = LABELS.index("entailment")NEUTRAL = LABELS.index("neutral")@@ -72,6 +74,21 @@ def read_corpus(path: Path):return rows+def example_key(row) -> str:+ """One example's identity, mirroring `corpusExampleKey` in jevCorpus.js.++ Context and options, NUL-joined, first 32 hex of the SHA-256 — the same+ bytes the Node side hashes, so the two agree on what "the same question"+ means and the disjointness re-check below is checking the same thing the+ split enforced.+ """+ digest = hashlib.sha256()+ digest.update(row["context"].encode("utf-8"))+ digest.update(b"\x00")+ digest.update("\u0000".join(row["options"]).encode("utf-8"))+ return digest.hexdigest()[:32]++def pair_key(revision: str, context: str, hypothesis: str) -> str:"""Cache key for one encoded pair.@@ -86,13 +103,40 @@ def pair_key(revision: str, context: str, hypothesis: str) -> str:return digest.hexdigest()+def prune_cache(cache_dir: Path, live_keys):+ """Delete cached vectors this run did not use.++ Every corpus build produces new contexts as pull requests merge and issues+ close, so each run's keys are almost entirely fresh — without a prune the+ directory grows by the whole corpus every time and never shrinks, at tens+ of kilobytes per pair. The cache is per DECISION (see `jevPaths.js`), which+ is what makes "not used by this run" a safe thing to delete rather than+ another decision's working set.++ Runs after a successful encode only, and never fails the run: a cache is+ regenerable, so a file that will not unlink is a wasted byte, not an error.+ """+ removed = 0+ for path in cache_dir.glob("*.json"):+ if path.stem in live_keys:+ continue+ try:+ path.unlink()+ removed += 1+ except OSError:+ pass+ return removed++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.+ Returns `(encoded, keys)` — a list parallel to `rows`, each entry holding+ one pooled vector and one stock-classifier logit vector per option, plus+ the set of cache keys this run touched."""cache_dir.mkdir(parents=True, exist_ok=True)+ keys = set()encoded = []total = sum(len(row["options"]) for row in rows)done = 0@@ -100,7 +144,9 @@ def encode_corpus(state, rows, cache_dir: Path, revision: str, on_progress):pooled_options = []stock_options = []for hypothesis in row["options"]:- path = cache_dir / f"{pair_key(revision, row['context'], hypothesis)}.json"+ key = pair_key(revision, row["context"], hypothesis)+ keys.add(key)+ path = cache_dir / f"{key}.json"cached = Noneif path.is_file():try:@@ -116,7 +162,7 @@ def encode_corpus(state, rows, cache_dir: Path, revision: str, on_progress):done += 1on_progress(done, total)encoded.append({"pooled": pooled_options, "stock": stock_options, "label": row["label"]})- return encoded+ return encoded, keysdef choose(scores_per_option):@@ -267,47 +313,32 @@ def main() -> int:# (`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}+ #+ # `example_key` mirrors `corpusExampleKey` in server/lib/jevCorpus.js, not+ # `pair_key` above — the cache key deliberately folds in the revision and+ # the pooling, which is right for a cache and wrong for an identity.+ gold_keys = {example_key(row) for row in gold_rows}+ train_keys = {example_key(row) 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()+ # THE SAME LOADER THE SIDECAR USES. Device, prompt template, window and+ # pooling all come from `jev_head_kit.load_encoder`, because a trainer that+ # resolved any of them differently would fit a head on a vector space the+ # sidecar never produces — and nothing downstream could tell.+ #+ # Called HERE, not at module scope: it imports torch, and the argument+ # validation and corpus read above must fail in milliseconds rather than+ # after a multi-second import a malformed request never needed.+ state = load_encoder(Path(args.model_dir))+ torch = state["torch"]+ encoder = state["model"]+ device = state["device"]# 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.@@ -315,8 +346,9 @@ def main() -> int: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)+ train_encoded, train_keys = encode_corpus(state, train_rows, cache_dir, args.revision, progress)+ gold_encoded, gold_keys = encode_corpus(state, gold_rows, cache_dir, args.revision, progress)+ pruned = prune_cache(cache_dir, train_keys | gold_keys)head_model, hidden_size, final_loss = fit_head(train_encoded, torch,@@ -349,7 +381,7 @@ def main() -> int: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})+ emit({"ok": True, "metrics": metrics, "finalLoss": final_loss, "device": device, "cachePruned": pruned})return 0diff --git a/server/lib/README.md b/server/lib/README.mdindex 0fdf13d263..562f63de45 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -505,6 +505,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `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`. |+| `jevHeadReasons.js` | Operator-facing labels for why a trained project head cannot be adopted (`jev-head-below-zero-shot`, `-below-majority-class`, `-metrics-invalid`) plus `jevHeadBlockerLabel`. No imports at all, so `client/src/lib/jevHeadReasons.js` re-exports it rather than mirroring it - same contract as `scopeAdherenceReasons.js`. Coverage is asserted in `jevHead.test.js`, so a fourth blocker cannot render as a raw slug. |+| `jevPaths.js` | Where `data/jev/` lives: `jevDataDir` / `jevHeadsDir` / `jevCorporaDir` / `jevEmbeddingsDir` / `jevDecisionEmbeddingsDir`. One definition, because the head store writes them, `services/jev.js` passes the heads directory to the sidecar, and `services/backup.js` excludes two of the three by path. Kept out of the head store so the sidecar lifecycle does not import the head schema merely to spell a directory. Everything under it is machine-local. || `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 26319ddf1d..fe3d12be21 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -465,6 +465,8 @@ export * from './jev.js';export * from './jevCorpus.js';export * from './jevDecisions.js';export * from './jevHead.js';+export * from './jevHeadReasons.js';+export * from './jevPaths.js';export * from './prdClauses.js';export * from './scopeAdherence.js';export * from './scopeAdherenceReasons.js';diff --git a/server/lib/jevCorpus.js b/server/lib/jevCorpus.jsindex acfaac372b..b5ecaea299 100644--- a/server/lib/jevCorpus.js+++ b/server/lib/jevCorpus.js@@ -138,12 +138,23 @@ export function buildCorpusExample({ context, options, chosen, source } = {}) {* it, because there is no principled way to pick between two weak labels.*/export function dedupeCorpus(examples) {+ return [...keyedCorpus(examples).values()];+}++/**+ * Deduplicated examples by key, so a caller that needs both does not hash twice.+ *+ * A context can be up to 32 KB and a corpus a thousand rows, so the SHA-256 is+ * not free: `dedupeCorpus` followed by a bucketing loop that re-derived the+ * same key digested the whole corpus twice to learn nothing new.+ */+function keyedCorpus(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()];+ return seen;}/**@@ -155,16 +166,15 @@ export function dedupeCorpus(examples) {* 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);+ // Dedupe and bucket in one pass over the keys the dedupe already computed.+ for (const [key, example] of keyedCorpus(examples)) {+ (parseInt(key.slice(0, 4), 16) < cutoff ? gold : train).push(example);}return { train, gold };}@@ -236,13 +246,3 @@ 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/jevHead.js b/server/lib/jevHead.jsindex 349eed93f7..4259a017a7 100644--- a/server/lib/jevHead.js+++ b/server/lib/jevHead.js@@ -84,7 +84,26 @@ export const JEV_HEAD_POOLING = 'last-token';* 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 JEV_HEAD_SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;++/**+ * The slug a decision's head is addressed by, or null if the id cannot be one.+ *+ * The mapping is identity TODAY, and this function is where that is decided —+ * not re-derived at the four sites that need it (the store's filenames, the+ * router's `head` argument, the sidecar's resolve, the panel's row key). A+ * decision id that is not slug-safe fails here rather than by producing a+ * filename nobody meant to write.+ */+export const jevHeadSlug = (decisionId) => (+ typeof decisionId === 'string' && JEV_HEAD_SLUG.test(decisionId) ? decisionId : null+);++/** The on-disk filename for a decision's adopted or candidate head. */+export function jevHeadFileName(decisionId, { candidate = false } = {}) {+ const slug = jevHeadSlug(decisionId);+ return slug === null ? null : `${slug}${candidate ? '.candidate' : ''}.json`;+}const finite = () => z.number().finite();const vector = () => z.array(finite()).min(1);@@ -151,27 +170,33 @@ export function countHeadParams(head) {* artifact for a different encoder. They point at opposite remedies, so they* report different codes.*/+// Every structural rejection in `parseJevHead` reports the same thing: a+// trainer bug the operator cannot fix. One frozen value rather than nine+// identical literals, so the branch CONDITIONS — which are the content — are+// not buried in boilerplate.+const INVALID = Object.freeze({ ok: false, code: 'jev-head-invalid' });+export function parseJevHead(raw) {const result = jevHeadSchema.safeParse(raw);- if (!result.success) return { ok: false, code: 'jev-head-invalid' };+ if (!result.success) return INVALID;const head = result.data;- if (head.labels.join('\u0000') !== JEV_LABELS.join('\u0000')) return { ok: false, code: 'jev-head-invalid' };+ if (head.labels.join('\u0000') !== JEV_LABELS.join('\u0000')) return INVALID;const first = head.layers[0];- if (first.weight.some((row) => row.length !== head.hiddenSize)) return { ok: false, code: 'jev-head-invalid' };+ if (first.weight.some((row) => row.length !== head.hiddenSize)) return 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' };+ if (layer.bias.length !== layer.weight.length) return 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' };+ if (next && next.weight.some((row) => row.length !== layer.weight.length)) return 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 (last.weight.length !== JEV_LABELS.length) return INVALID;+ if (head.architecture === 'linear' && head.layers.length !== 1) return 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 (head.layers.length !== 2) return INVALID;+ if (head.layers[0].weight.length > JEV_HEAD_MAX_HIDDEN) return INVALID;}if (countHeadParams(head) > JEV_HEAD_MAX_PARAMS) return { ok: false, code: 'jev-head-too-large' };return { ok: true, head };diff --git a/server/lib/jevHead.test.js b/server/lib/jevHead.test.jsindex 5bf09acfd3..0c25326838 100644--- a/server/lib/jevHead.test.js+++ b/server/lib/jevHead.test.js@@ -1,16 +1,24 @@import { describe, expect, it } from 'vitest';-import { JEV_LABELS } from './jev.js';+import { JEV_LABELS, JEV_SIDECAR_FAILURE_CODES } from './jev.js';import { JEV_DECISION_IDS } from './jevDecisions.js';+import { SCOPE_ADHERENCE_REASONS } from './scopeAdherenceReasons.js';+import {+ JEV_HEAD_BLOCKER_FALLBACK,+ JEV_HEAD_BLOCKER_REASONS,+ jevHeadBlockerLabel,+} from './jevHeadReasons.js';import {countHeadParams,headAdoptionBlocker,headBeatsBaselines,isHeadCompatible,+ JEV_HEAD_FAILURE_CODES,JEV_HEAD_MAX_HIDDEN,JEV_HEAD_POOLING,JEV_HEAD_SCHEMA_VERSION,- JEV_HEAD_SLUG,jevHeadActionRequestSchema,+ jevHeadFileName,+ jevHeadSlug,jevHeadTrainRequestSchema,parseJevHead,} from './jevHead.js';@@ -168,14 +176,49 @@ describe('head slugs', () => {// 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`);+ for (const id of JEV_DECISION_IDS) expect(`${id}:${jevHeadSlug(id)}`).toBe(`${id}:${id}`);});- 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`);+ it('refuses a decision id that would escape the heads directory', () => {+ for (const bad of ['../escape', 'a/b', 'UPPER', '.hidden', '', 'a:b']) {+ expect(`${bad}:${jevHeadSlug(bad)}`).toBe(`${bad}:null`);}});++ it('names the adopted and candidate files apart', () => {+ expect(jevHeadFileName('scope-adherence')).toBe('scope-adherence.json');+ expect(jevHeadFileName('scope-adherence', { candidate: true })).toBe('scope-adherence.candidate.json');+ expect(jevHeadFileName('../escape')).toBeNull();+ });+});++describe('the head failure vocabulary', () => {+ // The head codes exist in three places — this list, the sidecar's forwardable+ // subset, and the operator-facing labels. Nothing tied them together, so the+ // copies could drift silently; these two assertions are that tie.+ it('declares every head code the sidecar is allowed to forward', () => {+ const forwardable = JEV_SIDECAR_FAILURE_CODES.filter((code) => code.startsWith('jev-head-'));+ expect(forwardable.length).toBeGreaterThan(3);+ expect(forwardable.filter((code) => !JEV_HEAD_FAILURE_CODES.includes(code))).toEqual([]);+ });++ it('gives every forwardable head code an operator-facing label', () => {+ for (const code of JEV_SIDECAR_FAILURE_CODES.filter((c) => c.startsWith('jev-head-'))) {+ expect(`${code}:${Object.hasOwn(SCOPE_ADHERENCE_REASONS, code)}`).toBe(`${code}:true`);+ }+ });++ // The other half of the vocabulary: every verdict `headAdoptionBlocker` can+ // return has to render as prose, or a fourth blocker shows an operator a raw+ // slug with a green suite behind it.+ it('gives every adoption blocker a label', () => {+ const blockers = JEV_HEAD_FAILURE_CODES.filter((code) => Object.hasOwn(JEV_HEAD_BLOCKER_REASONS, code));+ expect(blockers.sort()).toEqual(Object.keys(JEV_HEAD_BLOCKER_REASONS).sort());+ for (const code of blockers) expect(jevHeadBlockerLabel(code)).not.toBe(JEV_HEAD_BLOCKER_FALLBACK);+ // An unknown code degrades to the fallback rather than rendering undefined,+ // and a prototype key cannot return a function React would throw on.+ expect(jevHeadBlockerLabel('toString')).toBe(JEV_HEAD_BLOCKER_FALLBACK);+ });});describe('route schemas', () => {diff --git a/server/lib/jevHeadReasons.js b/server/lib/jevHeadReasons.jsnew file mode 100644index 0000000000..47d5f91225--- /dev/null+++ b/server/lib/jevHeadReasons.js@@ -0,0 +1,39 @@+/**+ * Operator-facing labels for why a trained project head cannot be adopted.+ *+ * ONE definition, here, re-exported by `client/src/lib/jevHeadReasons.js` — not+ * a table inside the panel component. Same contract as+ * `scopeAdherenceReasons.js`, and for the same reason: these codes are SERVER+ * vocabulary, produced by `headAdoptionBlocker` and enforced by `adoptJevHead`,+ * so a fourth blocker added there must fail a test rather than render as a raw+ * slug in a green suite. The client may import a pure `server/lib` leaf; the+ * reverse edge is what `scripts/server-imports-no-client.test.js` forbids.+ *+ * This module keeps itself importable from the browser by having no imports at+ * all. Coverage is asserted by `jevHead.test.js`, which owns the codes.+ *+ * Every label names WHICH baseline the head lost to, because the two send an+ * operator to different places: losing to the stock scorer means the corpus+ * taught it nothing the checkpoint did not already know, while losing to a+ * constant prediction means the corpus is too imbalanced for accuracy to be+ * measuring anything at all.+ */++export const JEV_HEAD_BLOCKER_REASONS = Object.freeze({+ '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 const JEV_HEAD_BLOCKER_FALLBACK = 'This head cannot be adopted.';++/**+ * Label for a blocker code.+ *+ * Own-property lookup only: `REASONS[code] || fallback` on a code that happens+ * to name an `Object.prototype` key (`toString`, `constructor`) returns a+ * function, and React throws when one is rendered as a child.+ */+export function jevHeadBlockerLabel(code, fallback = JEV_HEAD_BLOCKER_FALLBACK) {+ return Object.hasOwn(JEV_HEAD_BLOCKER_REASONS, code ?? '') ? JEV_HEAD_BLOCKER_REASONS[code] : fallback;+}diff --git a/server/lib/jevPaths.js b/server/lib/jevPaths.jsnew file mode 100644index 0000000000..eb57983ec9--- /dev/null+++ b/server/lib/jevPaths.js@@ -0,0 +1,47 @@+/**+ * Where a project-specific jev head, its corpora and its cached embeddings live.+ *+ * One definition of each directory, in a leaf, because three separate modules+ * need to agree about them and they disagree silently:+ *+ * `services/jevHeads.js` writes and reads the heads+ * `services/jev.js` passes the heads directory to the sidecar+ * `services/backup.js` excludes two of the three by path+ *+ * Kept OUT of `services/jevHeads.js` so the sidecar lifecycle — the module+ * `jevRouter` defers specifically to keep the pinned model contract out of+ * static import closures — does not have to import the head store (and through+ * it zod) just to spell one directory.+ *+ * Everything under `jevDataDir()` is a derived record of this install's private+ * repository history: machine-local, never federated, never in a status or+ * capability payload. See the ADR+ * [privacy records machine-local](../../docs/decisions/2026-08-08-privacy-records-machine-local.md)+ * and the guard `services/sharing/jevNeverFederates.test.js`.+ *+ * Pure apart from reading the install root: no I/O, no process state.+ */++import { join } from 'path';+import { PATHS } from './paths.js';++/** The one directory every jev artifact lives under. */+export const jevDataDir = () => join(PATHS.data, 'jev');++/** Trained heads — adopted and candidate. Retained in backups: not regenerable. */+export const jevHeadsDir = () => join(jevDataDir(), 'heads');++/** Built training corpora. Rebuildable from the forge, so excluded from backups. */+export const jevCorporaDir = () => join(jevDataDir(), 'corpora');++/** Cached frozen-encoder outputs, per decision. Pure cache, excluded from backups. */+export const jevEmbeddingsDir = () => join(jevDataDir(), 'embeddings');++/**+ * The embedding cache for ONE decision.+ *+ * Per-decision rather than one shared pool, so a training run can prune the+ * keys it did not use without deleting another decision's cache. A flat pool+ * would make that prune unsafe and the cache therefore unbounded.+ */+export const jevDecisionEmbeddingsDir = (decisionId) => join(jevEmbeddingsDir(), decisionId);diff --git a/server/lib/scopeAdherence.js b/server/lib/scopeAdherence.jsindex bde7761859..e281d47437 100644--- a/server/lib/scopeAdherence.js+++ b/server/lib/scopeAdherence.js@@ -68,6 +68,20 @@ const asRanking = (results) => (results || []).map((result) => ({ id: result.docexport const buildClauseIndex = (clauses) =>buildInvertedIndex(clauses.map((clause) => ({ id: clause.id, text: clause.text })));+/**+ * The scorable clauses and an id lookup over them.+ *+ * Both are per-CORPUS, not per-change, so a caller that runs many changes+ * against one corpus builds them once. The advisory endpoint scores a single+ * change and does not notice; the corpus builder scores up to a thousand forge+ * rows against the same few hundred clauses, which turns an O(C) prep into+ * O(R·C) the moment it is rebuilt inside the loop.+ */+export function prepareClauseCorpus(clauses) {+ const corpus = Array.isArray(clauses) ? clauses.filter((clause) => clause?.id && clause.text) : [];+ return { corpus, byId: new Map(corpus.map((clause) => [clause.id, clause])) };+}+/*** Pick the clauses worth scoring, best match first.*@@ -81,11 +95,14 @@ export const buildClauseIndex = (clauses) =>** @param {Array} clauses The corpus.* @param {{title?: string, body?: string, diffSummary?: string}} change Already normalized.- * @param {{k?: number, index?: object}} options A prebuilt `index` skips the rebuild.+ * @param {{k?: number, index?: object, prepared?: {corpus: Array, byId: Map}}} options+ * A prebuilt `index` skips the BM25 rebuild; a prebuilt `prepared`+ * (`prepareClauseCorpus`) skips the per-call filter and id map. Both matter+ * only to a caller in a loop — see `prepareClauseCorpus`.* @returns {Array} up to `k` clauses, in fused-rank order.*/-export function selectCandidateClauses(clauses, change, { k = SCOPE_ADHERENCE_TOP_K, index } = {}) {- const corpus = Array.isArray(clauses) ? clauses.filter((clause) => clause?.id && clause.text) : [];+export function selectCandidateClauses(clauses, change, { k = SCOPE_ADHERENCE_TOP_K, index, prepared } = {}) {+ const { corpus, byId } = prepared || prepareClauseCorpus(clauses);if (!corpus.length || k <= 0) return [];const narrative = [change?.title, change?.body].filter(Boolean).join('\n');@@ -102,7 +119,6 @@ export function selectCandidateClauses(clauses, change, { k = SCOPE_ADHERENCE_TO{ ftsWeight: NARRATIVE_WEIGHT, vectorWeight: CODE_WEIGHT },);- const byId = new Map(corpus.map((clause) => [clause.id, clause]));return [...fused.entries()].sort((a, b) => b[1].rrfScore - a[1].rrfScore).slice(0, k)diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex ad38ab28dc..4ca4ae74a1 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -78,8 +78,6 @@ 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'@@ -106,6 +104,15 @@ import {getLoadedModels as getLoadedLmStudioModels,} from '../services/lmStudioManager.js'+// The head store and the trainer are DEFERRED into their handlers, not+// imported at module scope: `jevTraining.js` reaches the sidecar lifecycle, the+// pinned model contract and the corpus builder's forge stack, and this route+// module sits in the static closure of a great many suites+// (`server/lib/importScoping.test.js`). Four endpoints nobody calls by default+// must not make every one of them pay for that subtree.+const jevHeadStore = () => import('../services/jevHeads.js')+const jevTrainer = () => import('../services/jevTraining.js')+const router = Router()const emitter = (req) => {@@ -321,6 +328,7 @@ router.post('/jev/unload', asyncHandler(async (_req, res) => {// 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) => {+ const [{ describeJevHeads }, { isJevTrainingRunning }] = await Promise.all([jevHeadStore(), jevTrainer()])res.json({ ...await describeJevHeads(), training: isJevTrainingRunning() })}))@@ -331,6 +339,7 @@ router.get('/jev/heads', asyncHandler(async (_req, res) => {// anything else.router.post('/jev/heads/train', asyncHandler(async (req, res) => {const { architecture } = validateRequest(jevHeadTrainRequestSchema, req.body || {})+ const { trainScopeAdherenceHead } = await jevTrainer()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)@@ -341,6 +350,7 @@ router.post('/jev/heads/train', asyncHandler(async (req, res) => {// 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 { adoptJevHead } = await jevHeadStore()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 })@@ -351,6 +361,7 @@ router.post('/jev/heads/adopt', asyncHandler(async (req, res) => {// training run.router.post('/jev/heads/discard', asyncHandler(async (req, res) => {const { decisionId, adopted } = validateRequest(jevHeadActionRequestSchema, req.body || {})+ const { discardJevHead } = await jevHeadStore()res.json(await discardJevHead(decisionId, { candidate: adopted !== true }))}))diff --git a/server/services/backup.js b/server/services/backup.jsindex d3bb9c3ad8..347a9f89d5 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -215,20 +215,11 @@ export const DEFAULT_EXCLUDES = [// 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.+ // Two of the three `data/jev/` directories are excluded; `heads/` deliberately+ // is NOT, because a trained head is the one artifact there that does not+ // re-derive. The full three-way tier argument lives in docs/BACKUP.md+ // ("jev project heads — excluded bulk, retained artifact"), which is where a+ // tier change belongs.{ 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`)diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 2c724966cc..d5be45570c 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -100,12 +100,21 @@ export const CATEGORIES = {'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 },+ // them.+ //+ // NOT deletable: 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 the category would silently return scope+ // adherence to the stock scorer with nothing to restore.+ //+ // NOT archivable either, and for the opposite reason: this tree is mostly the+ // embedding cache, which `backup.js` excludes precisely because it is+ // gigabytes of pure cache. Archiving gzips exactly those gigabytes INTO+ // `data/backup/` — growing the directory an operator opened this page to+ // shrink, and blowing the shared tar timeout on the way. The few kilobytes+ // worth keeping (the heads) are already in every snapshot.+ '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, and the cache beside it is bulk that rebuilds', archivable: false, 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 3afda52373..6af0480fe3 100644--- a/server/services/jev.js+++ b/server/services/jev.js@@ -49,10 +49,11 @@ 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+// One path helper, from the leaf 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';+// writes end up pointing at two different directories — and taking it from the+// STORE instead would drag the head schema into this module's static closure.+import { jevHeadsDir } from '../lib/jevPaths.js';const execFileAsync = promisify(execFile);const IS_WIN = platform() === 'win32';@@ -138,15 +139,31 @@ function availableJevPython() {}/**- * The dedicated jev interpreter, or null.+ * How to run Python inside the dedicated jev venv, or null when it is absent.*- * 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.+ * Returns `{ pythonPath, options }` — the interpreter AND the hardened spawn+ * options together, because that pairing IS the guarantee: 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.+ *+ * One function rather than exporting `jevPythonPath` and `buildJevEnv` for a+ * caller to recompose: `startSidecar` below and `services/jevTraining.js` both+ * use it, so a future change to the hardening cannot land in one and leave the+ * other describing a process that is not the one running.*/-export const jevPythonPath = () => availableJevPython();+export function jevVenvSpawnTarget(overrides = {}) {+ const pythonPath = availableJevPython();+ if (!pythonPath) return null;+ const cwd = dirname(pythonPath);+ return {+ pythonPath,+ options: safeChildProcessOptions({+ cwd,+ env: withSpawnCwdEnv(buildJevEnv(), cwd),+ ...overrides,+ }),+ };+}async function isBasePythonSupported(pythonPath) {if (!pythonPath) return false;@@ -373,8 +390,8 @@ const delay = (ms) => new Promise((resolve) => { setTimeout(resolve, ms).unref?.* them bound to nothing and the other reaped by a caller that never saw it.*/async function startSidecar() {- const pythonPath = availableJevPython();- if (!pythonPath) return failure('jev-not-installed');+ const target = jevVenvSpawnTarget({ stdio: ['ignore', 'pipe', 'pipe'] });+ if (!target) return failure('jev-not-installed');const files = await findCachedRepoFiles(JEV_MODEL.repository, JEV_REQUIRED_FILES, { revision: JEV_MODEL.revision });if (!files?.[0]) return failure('jev-not-installed');// Every required file sits in the pinned subfolder, so its parent IS the@@ -387,7 +404,7 @@ async function startSidecar() {const headsDir = jevHeadsDir();const proc = spawn(- pythonPath,+ target.pythonPath,[HELPER_SCRIPT,'--model-dir', modelDir,@@ -397,11 +414,7 @@ async function startSidecar() {'--revision', JEV_MODEL.revision,'--heads-dir', headsDir,],- safeChildProcessOptions({- cwd: dirname(pythonPath),- env: withSpawnCwdEnv(buildJevEnv(), dirname(pythonPath)),- stdio: ['ignore', 'pipe', 'pipe'],- }),+ target.options,);startingProc = proc;let exited = false;diff --git a/server/services/jevCorpusBuilder.js b/server/services/jevCorpusBuilder.jsindex 569e1b3388..0974bd9c2f 100644--- a/server/services/jevCorpusBuilder.js+++ b/server/services/jevCorpusBuilder.js@@ -59,11 +59,12 @@ import { getJevDecision, jevHypotheses } from '../lib/jevDecisions.js';import {composeAdherencePremise,formatChangeEvidence,+ prepareClauseCorpus,SCOPE_ADHERENCE_DECISION_ID,SCOPE_ADHERENCE_TOP_K,selectCandidateClauses,} from '../lib/scopeAdherence.js';-import { jevCorporaDir } from './jevHeads.js';+import { jevCorporaDir } from '../lib/jevPaths.js';const execFileAsync = promisify(execFile);const FORGE_TIMEOUT_MS = 60_000;@@ -108,7 +109,9 @@ async function fetchForgeRows({ cwd, env }) {'--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',+ // `--search 'label:a,b'` is OR on the server; repeated `--label` flags+ // would be AND, and would find only the issues carrying both.+ ghJson(['issue', 'list', '--state', 'open', '--search', 'label:future,needs-input','--limit', String(FORGE_PAGE_LIMIT), '--json', 'number,title,body'], { cwd, env }),]);// Every query failing means the forge is unreachable. One failing on a@@ -140,6 +143,10 @@ async function fetchForgeRows({ cwd, env }) {*/function toExamples({ rows, clauses, index, options, verdicts, topK }) {const examples = [];+ // Built ONCE for the whole batch. `selectCandidateClauses` would otherwise+ // re-filter the corpus and rebuild its id map per forge row — O(rows ×+ // clauses) where O(clauses) does.+ const prepared = prepareClauseCorpus(clauses);for (const row of rows) {const change = {kind: row.kind,@@ -149,7 +156,7 @@ function toExamples({ rows, clauses, index, options, verdicts, topK }) {};if (!change.title && !change.body) continue;const evidence = formatChangeEvidence(change);- for (const clause of selectCandidateClauses(clauses, change, { k: topK, index })) {+ for (const clause of selectCandidateClauses(clauses, change, { k: topK, index, prepared })) {const context = composeAdherencePremise({ clause, evidence });if (!context) continue;const example = buildCorpusExample({@@ -232,7 +239,7 @@ export async function buildScopeAdherenceCorpus({ repoPath, env = null, topK = S'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',+ 'gh issue list --state open --search label:future,needs-input',],// Counts only, and only for context: the shadow counters carry no premise,// so they inform whether this decision has been measured at all — never adiff --git a/server/services/jevCorpusBuilder.test.js b/server/services/jevCorpusBuilder.test.jsindex 3e33a94f90..145de8934d 100644--- a/server/services/jevCorpusBuilder.test.js+++ b/server/services/jevCorpusBuilder.test.js@@ -10,15 +10,17 @@import { mkdtemp, mkdir, writeFile, readdir } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';-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 } };-});+// The shared helper re-roots every `PATHS` member under `data/`, not just+// `PATHS.data` — a bare spread leaves the rest pointing at the live install.+const PREFIX = 'portos-jev-corpus-';+vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot(PREFIX),+}));// promisify(execFile) needs the callback form, so a bare vi.fn() would hang// every query rather than failing one.@@ -29,6 +31,8 @@ vi.mock('../lib/childProcess.js', () => ({const { buildScopeAdherenceCorpus } = await import('./jevCorpusBuilder.js');+afterAll(() => cleanupTempDataRoots());+// 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) => (@@ -42,7 +46,9 @@ function mockForge({ merged = [], closed = [], notPlanned = [], parked = [], faiif (failAll) return callback(new Error('gh: not authenticated'));const rows = args[0] === 'pr'? (args.includes('merged') ? merged : closed)- : (args.includes('future') ? parked : notPlanned);+ // Matched on a substring: the parked query passes both labels inside one+ // `--search` value rather than as their own argv tokens.+ : (args.some((arg) => String(arg).includes('future')) ? parked : notPlanned);return callback(null, { stdout: JSON.stringify(rows), stderr: '' });});}@@ -116,7 +122,7 @@ describe('buildScopeAdherenceCorpus', () => {// 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');+ const corpora = join(lazyTempDataRoot(PREFIX), '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.diff --git a/server/services/jevHeads.js b/server/services/jevHeads.jsindex d9bd392bd1..e5b8591751 100644--- a/server/services/jevHeads.js+++ b/server/services/jevHeads.js@@ -38,28 +38,29 @@import { readdir, unlink } from 'fs/promises';import { join } from 'path';-import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { atomicWrite, ensureDir, 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');+import { headAdoptionBlocker, isHeadCompatible, jevHeadFileName, jevHeadSlug, parseJevHead } from '../lib/jevHead.js';+import { jevHeadsDir } from '../lib/jevPaths.js';const failure = (code) => ({ ok: false, code });-const headPath = (decisionId, { candidate = false } = {}) => join(- jevHeadsDir(),- `${decisionId}${candidate ? '.candidate' : ''}.json`,-);+// Filenames come from `jevHeadFileName`, the one owner of the decision-id ↔+// slug mapping. Spelling `${decisionId}.json` here would be a fourth+// independent derivation of it.+const headPath = (decisionId, options) => join(jevHeadsDir(), jevHeadFileName(decisionId, options));/**- * 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.+ * Which decisions have an applicable adopted head, by id.+ *+ * The VERDICT, not the head: the sole caller (`runJevDecision`) turns it into a+ * slug-or-null and the weights are read by the sidecar from disk, so caching+ * the parsed artifact would pin megabytes of float arrays in module scope for+ * the process lifetime to answer a boolean. A `false` entry is cached too — a+ * no-head install is the common case and must not re-stat per clause.+ *+ * Invalidated by every write path in this module, and by the test seam below.*/let adoptedCache = null;@@ -75,7 +76,12 @@ async function readHeadFile(path) {}/**- * The head `decisionId` is currently scored with, or null.+ * The head slug `decisionId` is currently scored with, or null.+ *+ * The slug IS the decision id — `jevHeadSlug` owns that mapping — and the+ * sidecar resolves it inside the heads directory. Returning it rather than the+ * artifact is what lets a caller pass it straight through without ever holding+ * the weights.** 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@@ -84,14 +90,14 @@ async function readHeadFile(path) {* is always correct. An operator who wants to know WHY sees it in the panel,* which calls `describeJevHeads` instead.*/-export async function getAdoptedJevHead(decisionId) {+export async function getAdoptedJevHeadSlug(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;+ const slug = result.ok && isHeadCompatible(result.head, JEV_MODEL) ? jevHeadSlug(decisionId) : null;adoptedCache ??= new Map();- adoptedCache.set(decisionId, head);- return head;+ adoptedCache.set(decisionId, slug);+ return slug;}/**@@ -108,14 +114,18 @@ export async function describeJevHeads() {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 name = jevHeadFileName(decisionId, { candidate });+ if (name === null || !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;+ // The blocker is computed ONCE and `beatsBaselines` derived from it:+ // `headBeatsBaselines` re-validates the same metrics object, so asking+ // both would parse it twice to answer one question two ways.+ const blocker = headAdoptionBlocker(head.metrics);rows.push({decisionId,adopted: !candidate,@@ -127,8 +137,8 @@ export async function describeJevHeads() {trainedAt: head.trainedAt,baseRevision: head.baseModel.revision,compatible: isHeadCompatible(head, JEV_MODEL),- beatsBaselines: headBeatsBaselines(head.metrics),- blocker: headAdoptionBlocker(head.metrics),+ beatsBaselines: blocker === null,+ blocker,});}}diff --git a/server/services/jevHeads.test.js b/server/services/jevHeads.test.jsindex 559257a75a..b3a80cb2a2 100644--- a/server/services/jevHeads.test.js+++ b/server/services/jevHeads.test.js@@ -7,25 +7,31 @@* 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 { mkdir, writeFile, readFile } from 'fs/promises';import { join } from 'path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, 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';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.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 } };-});+// The shared helper, not a hand-rolled `{ ...PATHS, data }` spread: the spread+// re-roots `PATHS.data` and leaves every other member pointing at the LIVE+// install's `data/`, and the eager `mkdtemp` it needs is the TDZ hazard+// `lazyTempDataRoot` exists to sidestep.+const PREFIX = 'portos-jev-heads-';+vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot(PREFIX),+}));const {- adoptJevHead, describeJevHeads, discardJevHead, getAdoptedJevHead,- jevHeadsDir, resetJevHeadCache, saveCandidateJevHead,+ adoptJevHead, describeJevHeads, discardJevHead, getAdoptedJevHeadSlug,+ resetJevHeadCache, saveCandidateJevHead,} = await import('./jevHeads.js');+const { jevCorporaDir, jevDataDir, jevEmbeddingsDir, jevHeadsDir } = await import('../lib/jevPaths.js');const { JEV_MODEL } = await import('../lib/jev.js');+afterAll(() => cleanupTempDataRoots());+const head = (overrides = {}) => ({schemaVersion: JEV_HEAD_SCHEMA_VERSION,decisionId: 'scope-adherence',@@ -58,7 +64,7 @@ describe('saveCandidateJevHead', () => {// 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();+ expect(await getAdoptedJevHeadSlug('scope-adherence')).toBeNull();const described = await describeJevHeads();expect(described.heads).toHaveLength(1);expect(described.heads[0]).toMatchObject({ decisionId: 'scope-adherence', adopted: false, beatsBaselines: true });@@ -81,7 +87,9 @@ 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 SLUG, not the artifact: the caller passes it straight to the sidecar+ // and never holds the weights.+ expect(await getAdoptedJevHeadSlug('scope-adherence')).toBe('scope-adherence');// 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();@@ -93,7 +101,7 @@ describe('adoptJevHead — the gate', () => {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();+ expect(await getAdoptedJevHeadSlug('scope-adherence')).toBeNull();});it('refuses a head that does not beat the majority class', async () => {@@ -121,7 +129,7 @@ describe('adoptJevHead — the gate', () => {});});-describe('getAdoptedJevHead', () => {+describe('getAdoptedJevHeadSlug', () => {// 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 () => {@@ -129,7 +137,7 @@ describe('getAdoptedJevHead', () => {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();+ expect(await getAdoptedJevHeadSlug('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' });@@ -137,12 +145,12 @@ describe('getAdoptedJevHead', () => {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 getAdoptedJevHeadSlug('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();+ expect(await getAdoptedJevHeadSlug('not-a-decision')).toBeNull();});});@@ -151,7 +159,7 @@ describe('discardJevHead', () => {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();+ expect(await getAdoptedJevHeadSlug('scope-adherence')).toBeNull();});it('is idempotent when there is nothing to discard', async () => {@@ -162,12 +170,12 @@ describe('discardJevHead', () => {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'));+ it('keeps heads, corpora and embeddings under data/jev/', () => {+ const root = lazyTempDataRoot(PREFIX);+ expect(jevDataDir()).toBe(join(root, 'jev'));+ expect(jevHeadsDir()).toBe(join(root, 'jev', 'heads'));+ expect(jevCorporaDir()).toBe(join(root, 'jev', 'corpora'));+ expect(jevEmbeddingsDir()).toBe(join(root, 'jev', 'embeddings'));});// The slug the sidecar resolves is the decision id, so an adopted head hasdiff --git a/server/services/jevRouter.js b/server/services/jevRouter.jsindex 5bb8fe0b50..a05ad1b4a7 100644--- a/server/services/jevRouter.js+++ b/server/services/jevRouter.js@@ -100,17 +100,16 @@ 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);+ // An adopted project-specific head's slug, 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. The+ // slug is resolved inside the heads directory by the sidecar, never treated+ // as a path.+ const { getAdoptedJevHeadSlug } = await import('./jevHeads.js');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,+ head: await getAdoptedJevHeadSlug(decisionId),// 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.jsindex 5ca9dbea27..63354c0b83 100644--- a/server/services/jevTraining.js+++ b/server/services/jevTraining.js@@ -29,16 +29,16 @@ 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 { jevDecisionEmbeddingsDir } from '../lib/jevPaths.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';+// The trainer runs under the SAME interpreter AND the SAME hardened spawn+// options the sidecar runs under, resolved as ONE value from the module that+// owns both. Recomposing the interpreter and the environment here is how the+// "offline, no provider call" guarantee drifts apart from the process it is+// supposed to describe.+import { getJevStatus, jevVenvSpawnTarget } from './jev.js';import { buildScopeAdherenceCorpus } from './jevCorpusBuilder.js';-import { jevEmbeddingsDir, saveCandidateJevHead } from './jevHeads.js';+import { saveCandidateJevHead } from './jevHeads.js';const execFileAsync = promisify(execFile);const TRAINER_SCRIPT = join(PATHS.root, 'scripts', 'train_jev_head.py');@@ -87,8 +87,8 @@ async function runTraining({ repoPath, architecture }) {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');+ const target = jevVenvSpawnTarget({ timeout: TRAIN_TIMEOUT_MS, maxBuffer: MAX_TRAINER_OUTPUT });+ if (!target) 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.@@ -106,7 +106,10 @@ async function runTraining({ repoPath, architecture }) {'--corpus', join(corpus.corpusDir, 'train.jsonl'),'--gold', join(corpus.corpusDir, 'gold.jsonl'),'--out', outPath,- '--cache-dir', jevEmbeddingsDir(),+ // Per-decision, so the trainer can prune the keys this run did not use+ // without deleting a cache another decision depends on. A flat shared pool+ // would make that prune unsafe, and the cache therefore unbounded.+ '--cache-dir', jevDecisionEmbeddingsDir(SCOPE_ADHERENCE_DECISION_ID),'--decision-id', SCOPE_ADHERENCE_DECISION_ID,'--model-id', JEV_MODEL.id,'--repository', JEV_MODEL.repository,@@ -116,17 +119,13 @@ async function runTraining({ repoPath, architecture }) {'--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 || '' }));+ // `target.options` carries the hardened environment the sidecar runs under:+ // 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 result = await execFileAsync(target.pythonPath, args, target.options)+ .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@@ -138,6 +137,16 @@ async function runTraining({ repoPath, architecture }) {const head = written === null ? null : safeJSONParse(written, null, { allowArray: false, logError: false });if (!head) return failure('jev-head-training-failed');+ // Both sides compute the majority-class baseline — Node over the gold rows it+ // wrote (`majorityClassAccuracy`), Python over the gold rows it read — and+ // the gate reads the Python one. A disagreement means the two are not looking+ // at the same gold set, which would make the adoption evidence meaningless,+ // so it fails the run rather than shipping a head scored against an unknown.+ if (!Number.isFinite(head.metrics?.majorityClass)+ || Math.abs(head.metrics.majorityClass - corpus.majorityClass) > 1e-9) {+ return failure('jev-head-training-failed');+ }+const saved = await saveCandidateJevHead(SCOPE_ADHERENCE_DECISION_ID, head);if (!saved.ok) return saved;return {diff --git a/server/services/jevTraining.test.js b/server/services/jevTraining.test.jsindex db6984aed1..0921408f6b 100644--- a/server/services/jevTraining.test.js+++ b/server/services/jevTraining.test.js@@ -6,16 +6,18 @@* 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';+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++// The shared helper re-roots every `PATHS` member under `data/`, not just+// `PATHS.data` — a bare spread leaves the rest pointing at the live install.+const PREFIX = 'portos-jev-training-';+vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot(PREFIX),+}));-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 } };-});+afterAll(() => cleanupTempDataRoots());const execFile = vi.fn();vi.mock('../lib/childProcess.js', () => ({@@ -24,19 +26,8 @@ vi.mock('../lib/childProcess.js', () => ({}));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 jevVenvSpawnTarget = vi.fn();+vi.mock('./jev.js', () => ({ getJevStatus, jevVenvSpawnTarget }));const findCachedRepoFiles = vi.fn();vi.mock('../lib/hfCache.js', () => ({ findCachedRepoFiles, getHfCacheRoot: () => '/tmp/hf-cache-double' }));@@ -45,13 +36,10 @@ 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'),-}));+// No `adoptJevHead` double: this module does not import it, so a spy on one+// could never fire and would assert nothing. "Training never promotes" is+// enforced where promotion actually lives — `jevHeads.test.js`.+vi.mock('./jevHeads.js', () => ({ saveCandidateJevHead }));const resolveForgeForRepo = vi.fn();vi.mock('./forgeAuth.js', () => ({ resolveForgeForRepo }));@@ -68,12 +56,21 @@ const HEAD = { decisionId: 'scope-adherence', architecture: 'linear', metrics: Mfunction happyPath() {getJevStatus.mockResolvedValue({ ready: true });findCachedRepoFiles.mockResolvedValue(['/hf/snapshots/abc/qwen3.5-4b-nli/config.json']);- jevPythonPath.mockReturnValue('/venv/bin/python3');+ // The one value the service is given: interpreter AND hardened options+ // together, exactly as `services/jev.js` composes them for the sidecar.+ jevVenvSpawnTarget.mockReturnValue({+ pythonPath: '/venv/bin/python3',+ options: {+ cwd: '/venv/bin',+ env: { PATH: '/usr/bin', HOME: '/home/test', HF_HUB_OFFLINE: '1', TRANSFORMERS_OFFLINE: '1' },+ },+ });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'),+ majorityClass: 0.52,+ corpusDir: join(lazyTempDataRoot(PREFIX), '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 },@@ -93,11 +90,10 @@ beforeEach(() => {});describe('trainScopeAdherenceHead', () => {- it('writes a candidate and never promotes it', async () => {+ it('writes a candidate and reports its scores without a corpus row', 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');@@ -111,13 +107,37 @@ describe('trainScopeAdherenceHead', () => {const [command, args, options] = execFile.mock.calls[0];expect(command).toBe('/venv/bin/python3');expect(args[0]).toMatch(/train_jev_head\.py$/);+ // The options come from `jevVenvSpawnTarget` — the SAME value the sidecar+ // is spawned with — rather than being recomposed here, so the environment+ // cannot drift from the one the guarantee describes.expect(options.env.GH_TOKEN).toBeUndefined();expect(options.env.GITHUB_TOKEN).toBeUndefined();expect(options.env.HF_HUB_OFFLINE).toBe('1');+ expect(jevVenvSpawnTarget).toHaveBeenCalledWith(expect.objectContaining({ timeout: expect.any(Number) }));// 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');+ // Per-decision embedding cache, so a run can prune its own stale keys.+ expect(args[args.indexOf('--cache-dir') + 1]).toMatch(/embeddings[/\\]scope-adherence$/);+ });++ // Both languages compute the majority-class baseline; the gate reads the+ // Python one. A disagreement means they are not looking at the same gold set,+ // which would make the adoption evidence meaningless.+ it('refuses a head whose majority-class baseline disagrees with the corpus', async () => {+ buildScopeAdherenceCorpus.mockResolvedValue({+ ok: true,+ corpusHash: 'deadbeefcafe0001',+ majorityClass: 0.61,+ corpusDir: join(lazyTempDataRoot(PREFIX), '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 },+ });+ expect(await trainScopeAdherenceHead()).toEqual({ ok: false, code: 'jev-head-training-failed' });+ expect(saveCandidateJevHead).not.toHaveBeenCalled();});// Two overlapping runs would load a second 4B encoder on a machine that may