Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(store): 19 Jev harnesses, six flagship viewers, and a shared Jev kit (#116)

Dee022f71e895eb
diff --git a/store/agents/jev-archer/.gitignore b/store/agents/jev-archer/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-archer/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-archer/AGENTS.md b/store/agents/jev-archer/AGENTS.md
new file mode 100644
index 000000000..4acbc82a7
--- /dev/null
+++ b/store/agents/jev-archer/AGENTS.md
@@ -0,0 +1,84 @@
+# Jev Archer in OpenHarness
+
+On the left, Jev Archer is a range: a target slides back and forth across a line, and **Jev —
+TypeSafe's System One model — is the archer.** Every tick Jev reads the target's position and the
+aim point, and nudges the aim left or right to track it. Every window the arrow releases along the
+aim line. If the aim is on the target it is a bullseye; if the target ran past the aim, the arrow
+flies by and the miss counts. The range is synthetic; the decision loop is the show.
+
+On the right, you edit `archer.json`. This is the ONLY file you edit. It holds the session profile
+— how fast the target slides, how precise the bullseye has to be, how many shots — and the viewer
+watches it and Jev adapts immediately.
+
+## The archer file
+
+```jsonc
+{
+ "title": "Jev Archer",
+ "description": "Jev is the archer — track the sliding target and plant every arrow in the bullseye.",
+ "instrument": "ARCHER",
+ "tickMs": 150,
+ "speed": 0.6,
+ "bullHalf": 1.0,
+ "targetWidth": 24,
+ "shots": 16,
+ "style": "You are the archer. A target slides across the line — read its position and nudge your aim to track it, then release. Land the arrow in the bullseye to score; miss and it flies by. Keep your aim glued to the moving target."
+}
+```
+
+- **`speed`** — how far the target slides (in slots) per tick. This is the difficulty dial. Calm
+ (`0.4–0.6`) moves less than the aim can correct, so Jev stays on target and it is nearly a clean
+ day; `1.2+` and the target runs away from the aim, the aim trails, and the arrows release
+ off-center, so the misses pile up.
+- **`bullHalf`** — half the bullseye width in slots: how close the aim must be to the target when
+ the arrow releases to score. Tight (`0.4`) demands an exact read; wide (`1.5+`) is forgiving.
+- **`targetWidth`** — the width of the range in slots (6–60). Wider = more travel for the target to
+ build up speed off the rails.
+- **`shots`** — how many arrows in the session (1–100). More = longer, more chances to miss.
+- **`tickMs`** — how often the world updates (and Jev decides). Fast ticks = frantic aim; slow ticks
+ = a relaxed range.
+- **`style`** — the instruction to Jev. It should name an aiming strategy (track the target, read
+ the direction early, lead the motion) so Jev *decides* rather than guesses.
+
+## Your job
+
+Design `archer.json` so the range is an event:
+
+- **Curate the target speed with tension.** Default `speed` around `0.6` gives clean, readable
+ bullseyes. Crank it to `1.2` and the target starts to run; that flip is the fun.
+- **Precision by the bullseye.** A tight `bullHalf` makes Jev commit exactly on the read and miss
+ when the target comes in hot; a wide one lets it recover and string clean days together.
+- **Write a distinct style line.** "Hug the target, correct instantly" plays very differently from
+ "read its direction early and lead the motion." Jev will visibly aim differently.
+
+Do NOT just ship the template. Every `archer.json` you publish should be its own range with a
+deliberate, testable difficulty.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the aiming: does Jev plant the
+full session on a slow target, and leak when you speed it up — or does it never leak (dull) or leak
+even on a slow target (bad)? Either extreme is a finding to report, not a bug to mask.
+
+## Rules
+
+- Keep `archer.json` valid JSON always. A bad edit freezes the session on the last good state. You
+ can change `speed`/`bullHalf`/`targetWidth`/`shots` live — the viewer rebuilds the range for the
+ new profile.
+- Keep `title`, `description` and `style` truthful — and never present this as a real contest, real
+ scores, or real marksmanship.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read before you
+ commit to it (e.g. "which way does Jev aim with the target at 18 and the aim at 14?"). Use the
+ `jev` helpers: `noul`, `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the range and
+ lines up on the target — so the demo runs offline. With a key, the viewer calls the real API.
+- The Jev Archer viewer writes `.harness/verdict.json` itself (bullseyes, misses, whether the session
+ was a clean day). Do not edit it.
+- This is a demo. The range, the target and the timing are made up — never present this as a real
+ contest or real marksmanship.
+
+## Definition of done
+
+- A valid `archer.json` that parses and passes `toolchain/check.mjs`.
+- A session with a real decision loop: Jev reads the target, tracks it with the aim, plants the slow
+ ones, and leaks them once the target is too fast.
+- The speed and bullseye actually shape the session — report it if Jev never misses, or misses no
+ matter what.
diff --git a/store/agents/jev-archer/LICENSE b/store/agents/jev-archer/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-archer/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-archer/README.md b/store/agents/jev-archer/README.md
new file mode 100644
index 000000000..bebd6811a
--- /dev/null
+++ b/store/agents/jev-archer/README.md
@@ -0,0 +1,58 @@
+# Jev Archer
+
+**Jev — TypeSafe's System One model — is the archer.** A target slides back and forth across the
+line; every tick Jev reads the target's position and the aim point and nudges the aim — LEFT /
+RIGHT — to track it, releasing an arrow each window. Land the arrow where the target is and it's a
+bullseye; let the target run past the aim and the arrow flies by, counting a miss. Speed the target
+up faster than Jev's aim can correct and the misses pile up.
+
+This is a harness for OpenHarness. The agent on the right edits `archer.json`; the viewer on the
+left runs the range and asks Jev for each tick's aim, live. The decision loop is the show.
+
+## Anatomy
+
+```
+jev-archer/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to build sessions with real decision loops
+ skills/archer/SKILL.md # the aiming + verification craft
+ template/archer.json # a starter session profile
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), archer-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates archer.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the range)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs the range over a loopback HTTP server. Each tick it slides the target one
+step, asks Jev for the aim, and streams the session — the target sliding on its wire, Jev's crosshair
+aim tracking it, arrows releasing to the aim line (lighting the bullseye on a hit, flying past on a
+miss), and a session log — to the pane. It calls `POST /v1/systemone` when `TYPESAFE_API_KEY` is
+set; without it a deterministic mock reads the same range and lines up on the target, so the demo
+runs offline. `.harness/verdict.json` tracks bullseyes, misses, and whether the session was a clean
+day.
+
+The range is synthetic: the target slides at a set speed and Jev's "aim" is a moment-to-moment line
+call — read the target, track it, release — which is why a faster target (more drift than the aim can
+correct in one tick) makes Jev trail and miss.
+
+## Jev, honestly
+
+Jev's headline claim is speed — decide in a loop faster than a large model can. Archer celebrates
+that: an aiming decision on every tick. But the range, the target and the timing are entirely made
+up, and Jev plants no real arrow — this is a demo of decision-rate and calibration on a synthetic
+1-D tracking problem, not a signal for real archery, and the mock is a stand-in for *plumbing*, not
+judgement. Treat any "session" as a fun experiment, not marksmanship.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live archer — a sliding target you can
+watch Jev read, track, and plant (or miss) with every tick._
diff --git a/store/agents/jev-archer/THIRD_PARTY_NOTICES.md b/store/agents/jev-archer/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-archer/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-archer/harness.json b/store/agents/jev-archer/harness.json
new file mode 100644
index 000000000..09f06d487
--- /dev/null
+++ b/store/agents/jev-archer/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-archer",
+ "name": "Jev Archer",
+ "category": "Sports",
+ "author": "Autonomous",
+ "description": "A live archery range. Jev — TypeSafe's System One model — is the archer, tracking a target sliding across a line. Every tick Jev reads the target and the aim point and nudges the aim to track it, releasing an arrow each window. Speed the target up and Jev's aim trails and misses pile up.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "archer.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-archer/skills/archer/SKILL.md b/store/agents/jev-archer/skills/archer/SKILL.md
new file mode 100644
index 000000000..4b163b773
--- /dev/null
+++ b/store/agents/jev-archer/skills/archer/SKILL.md
@@ -0,0 +1,65 @@
+---
+name: archer
+description: Shape a Jev Archer range (target speed, bullseye size, shots), then verify Jev plants the slow targets and leaks the fast ones.
+---
+
+# Craft — Jev Archer
+
+Jev Archer is a 1-D tracking game: a target slides across a line and Jev nudges the aim to track it,
+releasing an arrow every window. The craft is curating the target speed and the bullseye size into a
+range that shows a real decision loop — Jev plants the slow ones and leaks the fast ones.
+
+## The decision loop
+
+Each tick the viewer gives Jev its current read: the aim x, the target x, and how many ticks until
+the arrow releases. Jev answers one Choice:
+
+```
+Which way do you nudge the aim this tick? LEFT_FAST / LEFT / HOLD / RIGHT / RIGHT_FAST
+```
+
+The mock reads the same lines and nudges toward the target. The physics — how far the target slides
+per tick and how precise the bullseye is — is what makes it hard or easy, not randomness.
+
+## Reading and shaping the range
+
+```jsonc
+{
+ "speed": 0.6, // target slides this many slots per tick
+ "bullHalf": 1.0, // half of the bullseye in slots when the arrow releases
+ "targetWidth": 24, // range width in slots
+ "shots": 16, // arrows in the session
+ "style": "track the target"
+}
+```
+
+- **`speed` is the honest limit.** At `0.4–0.6` the target slides less than the aim corrects in one
+ tick, so Jev stays glued and it's nearly a clean day. Past ~`1.2` the target outruns the aim each
+ tick, the aim trails, and the arrow releases off-center.
+- **`bullHalf` is the precision knob.** Tight (`0.4`) demands the aim land within a whisker; wide
+ (`1.5+`) lets Jev string clean days together.
+- **`style` changes how Jev plays.** "Hug the target, correct instantly" vs "read its direction and
+ lead the motion" produce visibly different aim behavior.
+
+## Shaping tension
+
+A good range should have a deliberate flip: pick a `speed` where it's calm, and know what speed (or
+what bullseye) makes Jev start to leak. Start at `0.6`, then either speed the target up to `1.2+` for
+a busy, miss-heavy range, or tighten the bullseye for a precise one. Report the flip: does Jev plant
+a clean day at the calm setting and leak when sped up?
+
+## Verifying
+
+```bash
+node "$JEV_DSH/toolchain/check.mjs"
+```
+
+Then run the real loop and watch: a good range plants the slow and leaks the fast. A dull range never
+leaks; a broken one leaks even on a slow target. Report whichever extreme you see — don't hide it.
+
+## Definition of done
+
+- `archer.json` passes `check.mjs`.
+- Jev visibly tracks the target and plants it at a calm speed.
+- Speeding the target up (or shrinking the bullseye) visibly raises the misses — the knobs actually
+ matter.
diff --git a/store/agents/jev-archer/store.json b/store/agents/jev-archer/store.json
new file mode 100644
index 000000000..8b485af26
--- /dev/null
+++ b/store/agents/jev-archer/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev takes aim at a sliding target, planting every arrow in the bullseye, live",
+ "examples": [
+ {
+ "prompt": "Set Jev Archer up for a hard range — speed the target up so it slides faster than Jev's aim can correct. Give Jev a lead-the-motion aiming style, then watch it read the target every tick, nudge the aim to track, and release arrow after arrow into (or past) the bullseye.",
+ "caption": "Jev's Day on the Range — a fast decision model tracking the sliding target and planting the bullseye on each shot"
+ }
+ ]
+}
diff --git a/store/agents/jev-archer/template/archer.json b/store/agents/jev-archer/template/archer.json
new file mode 100644
index 000000000..c8fe848f0
--- /dev/null
+++ b/store/agents/jev-archer/template/archer.json
@@ -0,0 +1,11 @@
+{
+ "title": "Jev Archer",
+ "description": "Jev is the archer — track the sliding target and plant every arrow in the bullseye.",
+ "instrument": "ARCHER",
+ "tickMs": 150,
+ "speed": 0.6,
+ "bullHalf": 1.0,
+ "targetWidth": 24,
+ "shots": 16,
+ "style": "You are the archer. A target slides across the line — read its position and nudge your aim to track it, then release. Land the arrow in the bullseye to score; miss and it flies by. Keep your aim glued to the moving target."
+}
diff --git a/store/agents/jev-archer/test/viewer.test.mjs b/store/agents/jev-archer/test/viewer.test.mjs
new file mode 100644
index 000000000..d1b97c3c6
--- /dev/null
+++ b/store/agents/jev-archer/test/viewer.test.mjs
@@ -0,0 +1,83 @@
+// Viewer integration test for Jev Archer. Spins up the real viewer against a temp workspace and
+// checks the loop: the target slides, Jev tracks it with the aim, the verdict updates, and control
+// commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const CFG = {
+ title: 'Test Range', instrument: 'ARCHER', tickMs: 100, speed: 0.6, bullHalf: 1.0, targetWidth: 24, shots: 10,
+ style: 'Track the target and plant the bullseye.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-archer-test-'))
+ writeFileSync(join(ws, 'archer.json'), JSON.stringify({ ...CFG, ...overrides }))
+ const { startArcherViewer } = await import(viewerPath)
+ const viewer = await startArcherViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Archer tracks and the target slides', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const deadline = Date.now() + 2500
+ let saw = false
+ while (Date.now() < deadline) {
+ await wait(120)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ if (s.history.length >= 3) {
+ assert.ok(['LEFT_FAST', 'LEFT', 'HOLD', 'RIGHT', 'RIGHT_FAST'].includes(s.move))
+ assert.ok(typeof s.aim === 'number')
+ assert.ok(typeof s.target === 'number')
+ assert.ok(typeof s.fuse === 'number')
+ saw = true
+ break
+ }
+ }
+ assert.ok(saw, 'expected Jev to aim and the target to slide')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Archer writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 1500
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Archer control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-archer/toolchain/README.md b/store/agents/jev-archer/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-archer/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-archer/toolchain/check.mjs b/store/agents/jev-archer/toolchain/check.mjs
new file mode 100644
index 000000000..44a3607dd
--- /dev/null
+++ b/store/agents/jev-archer/toolchain/check.mjs
@@ -0,0 +1,30 @@
+#!/usr/bin/env node
+// check.mjs — validate an archer.json for the Jev Archer harness.
+// Enforces the shape the viewer needs: title, range profile, tick interval.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'archer.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read archer.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!p.title || typeof p.title !== 'string') bad('warn no title')
+if (p.instrument && p.instrument !== 'ARCHER') bad('warn instrument should be ARCHER')
+if (typeof p.speed !== 'number' || p.speed <= 0 || p.speed > 4) bad('error speed (slots per tick) should be >0..4')
+if (typeof p.bullHalf !== 'number' || p.bullHalf <= 0 || p.bullHalf > 4) bad('error bullHalf must be >0..4')
+const W = p.targetWidth ?? 24
+if (typeof W !== 'number' || W < 6 || W > 60) bad('error targetWidth should be 6..60')
+if (typeof p.shots !== 'number' || p.shots < 1 || p.shots > 100) bad('error shots should be 1..100')
+if (typeof p.tickMs !== 'number' || p.tickMs < 60 || p.tickMs > 2000) bad('error tickMs must be ms 60..2000')
+if (!p.style || typeof p.style !== 'string') bad('warn a style line helps Jev aim coherently')
+
+console.log(fail ? 'fail invalid archer.json' : 'ok archer.json is valid')
diff --git a/store/agents/jev-archer/toolchain/doctor.sh b/store/agents/jev-archer/toolchain/doctor.sh
new file mode 100755
index 000000000..6fd357ad6
--- /dev/null
+++ b/store/agents/jev-archer/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Archer viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-archer/toolchain/init-workspace.sh b/store/agents/jev-archer/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-archer/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-archer/toolchain/jev.mjs b/store/agents/jev-archer/toolchain/jev.mjs
new file mode 100644
index 000000000..15c1c7b66
--- /dev/null
+++ b/store/agents/jev-archer/toolchain/jev.mjs
@@ -0,0 +1,794 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+/**
+ * Pendulum-balancing read used by the mock when the state text carries the current pole angle and
+ * angular velocity (the viewer renders e.g. "angle: +12° velocity: -0.8 rad/s"). We compute the
+ * corrective action the pole is asking for: lean/fall to the right (positive angle) wants a
+ * leftward torque, and also damp any velocity. Returns per-action boosts so the deterministic mock
+ * biases toward the right call while staying slightly noisy — so Jev can fail when it's sloppy and
+ * the fall reads as Jev's mistake. Real Jev reads the same text — the mock is a stand-in.
+ */
+function pendulumRead(text) {
+ const mA = text.match(/angle:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const mV = text.match(/velocity:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const deg = mA ? Number(mA[1]) : NaN
+ const vel = mV ? Number(mV[1]) : NaN
+ if (!Number.isFinite(deg) || !Number.isFinite(vel)) return null
+ const a = (deg * Math.PI) / 180
+ // desired torque = -(Kp*a + Kv*vel); pick the action whose torque is closest.
+ const want = -(6.5 * a + 3.2 * vel)
+ const ACTS = { LEFT_HARD: -1.6, LEFT: -0.8, CENTER: 0, RIGHT: 0.8, RIGHT_HARD: 1.6 }
+ const boost = {}
+ for (const [name, t] of Object.entries(ACTS)) {
+ boost[name] = 1.4 - Math.abs(t - Math.max(-1.6, Math.min(1.6, want))) * 0.9
+ }
+ // The mock can't see the gravity dial — it just balances. But a fast judge on a hard
+ // rig will hesitate more, so the misjudgement rate rises with how hard the balance is.
+ // Low gravity: calm, near-perfect. High gravity: it starts to overshoot and lose it.
+ const hard = (parseFloat((text.match(/hardness:\s*([0-9.]+)/i) || [null, '0'])[1]) || 0)
+ const noise = Math.min(0.55, 0.03 + hard * 0.06)
+ return { boost, noise }
+}
+
+/**
+ * Pong-defender read used by the mock when the state text carries a ball position/velocity and the
+ * paddle's centre. We predict where the ball will cross the paddle's wall (reflecting off floor and
+ * ceiling) and bias the paddle move toward that intercept, with a reaction that degrades as the ball
+ * gets faster. Returns per-move boosts plus a beta error chance so Jev can visibly lose a fast rally.
+ */
+function pongRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/ball:\s*x\s+([-0-9.]+)/i)
+ const y = num(/y\s+([-0-9.]+)\s+vx/i)
+ const vx = num(/vx\s+([-0-9.]+)\s+vy/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const paddleY = num(/centre y\s+([-0-9.]+)/i)
+ const half = num(/half-height\s+([-0-9.]+)/i)
+ const courtH = num(/court:\s*[-0-9.]+\s*[x×]\s*([-0-9.]+)/i)
+ const speed = num(/speed:\s*([-0-9.]+)/i)
+ if (![x, y, vx, vy, paddleY, half, courtH, speed].every(Number.isFinite)) return null
+ const r = 3
+ const span = courtH - 2 * r
+ // When the ball is moving away (rightward), the paddle's job is to stop chasing and hold still so
+ // it's framed to meet the ball when it comes back — letting the rally breathe.
+ if (vx >= 0) return { boost: { HOLD: 1.9, MOVE_UP: 0.7, MOVE_DOWN: 0.7, MOVE_UP_FAST: 0.3, MOVE_DOWN_FAST: 0.3 }, noise: 0, close: false }
+ // time (in ball steps) to reach the left wall
+ const t = -x / vx
+ const dy = vy * t
+ let u = ((y - r + dy) % (2 * span) + 2 * span) % (2 * span)
+ u = u <= span ? u : 2 * span - u
+ const ty = r + u
+ const want = ty - paddleY
+ const goDown = want > half * 0.5
+ const goUp = want < -half * 0.5
+ const boost = {}
+ for (const name of ['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST']) {
+ if (goDown) boost[name] = name === 'MOVE_DOWN' ? 1.8 : name === 'MOVE_DOWN_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else if (goUp) boost[name] = name === 'MOVE_UP' ? 1.8 : name === 'MOVE_UP_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else boost[name] = name === 'HOLD' ? 1.8 : 0.8
+ }
+ // faster ball → the intercept at the wall changes fast and the paddle has fewer ticks to reach it,
+ // so the physical difficulty (max paddle speed) does the work. No injected noise: a miss is honest.
+ return { boost }
+}
+
+/**
+ * Shopper read used by the mock when the state text carries the recent price stream for each
+ * product (the viewer renders "Name: price (+x% over N ticks) vol v% [spark]"). We score each
+ * product by how fast its price is still falling — the best value right now — and bias the "best
+ * buy" choice toward the steepest falling momentum, plus a confidence that depends on how far the
+ * top pick stands out. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function shopperRead(text) {
+ const picks = []
+ const re = /^\s*([^:\n]+?):\s*([0-9.]+)\s*\(\s*([+-][0-9.]+)% over (\d+) ticks\)\s*vol\s*([0-9.]+)%\s*\[([^\]]*)\]/gim
+ let m
+ while ((m = re.exec(text))) {
+ const name = m[1].trim()
+ const price = Number(m[2])
+ const chgPct = Number(m[3])
+ picks.push({ name, price, chgPct })
+ }
+ if (picks.length < 2) return null
+ // best value = most negative recent change (still falling the fastest)
+ const sorted = picks.slice().sort((a, b) => a.chgPct - b.chgPct)
+ const best = sorted[0]
+ const second = sorted[1]
+ const spread = second.chgPct - best.chgPct
+ const boost = {}
+ for (const p of picks) boost[p.name] = p.name === best.name ? 1.6 : p.name === second.name ? 0.9 : 0.2
+ // confidence: strong when the leader clearly out-falls the rest; weak when it's a dead heat
+ const confidence = Math.min(0.95, Math.max(0.15, 0.5 + spread * 0.6))
+ return { boost, confidence, best: best.name }
+}
+
+/**
+ * Lander read used by the mock when the state text carries booster telemetry
+ * ("ALT x VY y G g FUEL f%"). We pick a throttle by altitude and vertical speed — burn early and
+ * hard enough to keep descent in check while high, flare gently low so the touchdown is soft —
+ * and bias the throttle choice toward it, with a noise term that grows with gravity so high-g
+ * missions look twitchy and start to crash. Real Jev reads the same lines — the mock is a
+ * stand-in.
+ */
+function landerRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const alt = num(/alt\s+([-0-9.]+)/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const g = num(/g\s+([-0-9.]+)/i)
+ if (![alt, vy, g].every((v) => Number.isFinite(v))) return null
+ let pick
+ if (alt > 30) {
+ if (vy < -2.5) pick = 'BURN'
+ else if (vy < -1.2) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 16) {
+ if (vy < -1.8) pick = 'BURN'
+ else if (vy < -0.8) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 7) {
+ if (vy < -1.0) pick = 'BURN'
+ else if (vy < -0.3) pick = 'HOVER'
+ else pick = 'COAST'
+ } else {
+ if (vy < -0.4) pick = 'BURN'
+ else pick = 'CUT'
+ }
+ const boost = { CUT: 0.2, COAST: 0.6, HOVER: 0.7, BURN: 0.5 }
+ if (boost[pick] !== undefined) boost[pick] = 1.9
+ // twitchiness grows with gravity: higher g -> more over/under correction
+ boost.noise = Math.min(0.55, 0.06 + Math.max(0, (g - 1.5)) * 0.14)
+ return { boost, pick, g }
+}
+
+/**
+ * Slalom read used by the mock when the state text carries the skier's x and the next gate ("skier x
+ * X gate x G gate in D"). We steer toward the gate — committing harder as it arrives — with a small
+ * aim error that grows the less time there is, so faster descents look wobblier and fall. Real Jev
+ * reads the same lines — the mock is a stand-in.
+ */
+function slalomRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/skier x\s+([-0-9.]+)/i)
+ const gx = num(/gate x\s+([-0-9.]+)/i)
+ const rowGap = num(/row gap\s+([-0-9.]+)/i)
+ const speed = num(/descends at\s+([-0-9.]+)/i)
+ if (![x, gx, rowGap].every((v) => Number.isFinite(v))) return null
+ const spd = Number.isFinite(speed) ? speed : 2.4
+ // Reaction lag: the faster the descent, the later Jev reacts to an approaching gate (fewer spare
+ // ticks to cross the valley), so it arrives pointed at the old line and clips the gate.
+ const lag = Math.max(0, Math.floor((spd - 1.8) * 1.7))
+ const reachRows = 18 - lag * spd
+ const need = Math.abs(gx - x)
+ let pick = 'HOLD'
+ if (rowGap <= reachRows) {
+ const want = gx - x
+ if (want < -1.3) pick = 'LEFT_FAST'
+ else if (want > 1.3) pick = 'RIGHT_FAST'
+ else if (want < -0.5) pick = 'LEFT'
+ else if (want > 0.5) pick = 'RIGHT'
+ else pick = 'HOLD'
+ }
+ const boost = { LEFT_FAST: 0.05, LEFT: 0.05, HOLD: 0.05, RIGHT: 0.05, RIGHT_FAST: 0.05 }
+ if (boost[pick] !== undefined) boost[pick] = 1.99
+ return { boost, pick, rowGap }
+}
+
+/**
+ * Catcher read used by the mock when the state text carries the glove's x and the next ball's
+ * landing spot ("glove x X ball lands B in N ticks"). We slide toward the landing spot — reading it
+ * early and coasting far out, committing harder as it nears — and bias the glove move toward that.
+ * The physical limit (fewer fall ticks than it takes to cross the field) is what makes Jev leak
+ * balls — no injected wobble. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function catcherRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const gx = num(/glove x\s+([-0-9.]+)/i)
+ const bx = num(/ball lands\s+([-0-9.]+)/i)
+ const ticks = num(/in\s+([-0-9.]+)\s+ticks/i)
+ if (![gx, bx, ticks].every((v) => Number.isFinite(v))) return null
+ const want = bx - gx
+ // Far out, a gentle read settles on the landing spot; near the catch, commit fast.
+ let pick
+ if (ticks > 6) pick = want < -0.4 ? 'LEFT' : want > 0.4 ? 'RIGHT' : 'HOLD'
+ else pick = want < -1.0 ? 'LEFT_FAST' : want > 1.0 ? 'RIGHT_FAST' : want < -0.4 ? 'LEFT' : want > 0.4 ? 'RIGHT' : 'HOLD'
+ const boost = { LEFT_FAST: 0.05, LEFT: 0.05, HOLD: 0.05, RIGHT: 0.05, RIGHT_FAST: 0.05 }
+ if (boost[pick] !== undefined) boost[pick] = 1.99
+ return { boost, pick, want, ticks }
+}
+
+/**
+ * Archer read used by the mock when the state text carries the aim x and the target x
+ * ("aim x A target x T"). We nudge the aim toward the sliding target. The difficulty is the target
+ * speed — a fast target slides more than the aim corrects in one tick, so the aim trails and the
+ * arrow releases off-center. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function archerRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const aim = num(/aim x\s+([-0-9.]+)/i)
+ const tx = num(/target x\s+([-0-9.]+)/i)
+ if (![aim, tx].every((v) => Number.isFinite(v))) return null
+ const want = tx - aim
+ let pick
+ if (want < -0.6) pick = 'LEFT'
+ else if (want > 0.6) pick = 'RIGHT'
+ else pick = 'HOLD'
+ const boost = { LEFT_FAST: 0.05, LEFT: 0.05, HOLD: 0.05, RIGHT: 0.05, RIGHT_FAST: 0.05 }
+ if (boost[pick] !== undefined) boost[pick] = 1.99
+ return { boost, pick, want }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ // Shopper: "act now" is urgent when the best buy clearly out-falls the field. Ask Jev to spend
+ // when the momentum spread is wide, so the demo eventually commits on paper.
+ if (/act now|spend now|strong enough/i.test(qtext) || /buy|act/i.test(q.instructions)) {
+ const shop = shopperRead(text)
+ if (shop && shop.confidence) p = Math.max(p, Math.min(0.9, 0.4 + shop.confidence * 0.5))
+ }
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Pendulum: if the state carries an angle + angular velocity, bias toward the balancing action,
+ // and occasionally flip to a neighbour (a fast model that sometimes hesitates) so the pole can
+ // visibly wobble — that wiggle is the demo.
+ const pen = pendulumRead(text)
+ if (pen) {
+ options.forEach((opt, i) => {
+ const b = pen.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (pen.noise && (hash01('pen', salt + 9) < pen.noise)) {
+ // flip the current best to two neighbours over — a big, costly overcorrection
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + (hash01('dir', salt) < 0.5 ? -2 : 2)))
+ if (ni !== best.i) raw[ni] += 2.2
+ }
+ }
+ // Pong: if the state text carries a ball + paddle, steer the paddle to the predicted intercept,
+ // and lag harder (miss more) as the ball speeds up.
+ const pong = pongRead(text)
+ if (pong) {
+ options.forEach((opt, i) => {
+ const b = pong.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Shopper: if the state carries a product price stream, bias "best buy" toward the product
+ // whose price is still falling the fastest.
+ const shop = shopperRead(text)
+ if (shop) {
+ options.forEach((opt, i) => {
+ const b = shop.boost[String(opt).toLowerCase()]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Lander: if the state carries booster telemetry, bias the throttle toward a plausible burn and
+ // flip to a worse one more often as gravity rises, so high-g missions look twitchy and crash.
+ const land = landerRead(text)
+ if (land) {
+ options.forEach((opt, i) => {
+ const b = land.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (land.boost.noise && (hash01('land', salt + 11) < land.boost.noise)) {
+ // over or under-throttle by one step — a costly hesitation
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const step = hash01('ldir', salt) < 0.5 ? 1 : -1
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + step))
+ if (ni !== best.i && land.boost[String(options[ni])] !== undefined) raw[ni] += 2.4
+ }
+ }
+ // Slalom: if the state carries the skier's x and the next gate, steer toward it once it's in
+ // reach; the physical slew limit (fast descents have too few ticks to cross the valley) is what
+ // makes it fall — no injected wobble.
+ const slal = slalomRead(text)
+ if (slal) {
+ options.forEach((opt, i) => {
+ const b = slal.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Catcher: if the state carries the glove's x and the next ball's landing spot, slide toward it.
+ // The physical slew limit (fewer fall ticks than it takes to cross the field) is what leaks
+ // balls — no injected wobble.
+ const catchr = catcherRead(text)
+ if (catchr) {
+ options.forEach((opt, i) => {
+ const b = catchr.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Archer: if the state carries the aim x and the target x, nudge the aim toward the target.
+ // A fast target slides more than the aim can correct, so the arrow releases off-center.
+ const arch = archerRead(text)
+ if (arch) {
+ options.forEach((opt, i) => {
+ const b = arch.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-archer/toolchain/setup.sh b/store/agents/jev-archer/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-archer/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-archer/toolchain/viewer.sh b/store/agents/jev-archer/toolchain/viewer.sh
new file mode 100755
index 000000000..c4604d86e
--- /dev/null
+++ b/store/agents/jev-archer/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Archer viewer (Jev is the archer, tracking the sliding target and planting the bullseye).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-archer/viewer/index.html b/store/agents/jev-archer/viewer/index.html
new file mode 100644
index 000000000..0f6f6746c
--- /dev/null
+++ b/store/agents/jev-archer/viewer/index.html
@@ -0,0 +1,55 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Archer</title>
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Archer</h1></div>
+ <div class="stats">
+ <div class="stat"><label>Arrow</label><span id="arrow">—</span></div>
+ <div class="stat"><label>Aim</label><span id="move">—</span></div>
+ <div class="stat"><label>Speed</label><span id="speed">—</span></div>
+ <div class="stat"><label>Bullseyes</label><span id="hits">0</span></div>
+ <div class="stat"><label>Missed</label><span id="misses">0</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="tick">Step</button>
+ <button class="primary" id="reset">Reset</button>
+ </div>
+ </div>
+ <main>
+ <section id="stage">
+ <div class="panel panel-stage">
+ <div class="panel-title">The range</div>
+ <div id="range">
+ <canvas id="scene"></canvas>
+ <div id="banner" class="hidden"></div>
+ </div>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Jev, the archer</div>
+ <div class="how">
+ Jev is on the line. A target slides back and forth, and every tick it reads the target's
+ position and nudges its aim <code>LEFT</code> / <code>RIGHT</code> to track it, releasing
+ an arrow each window. Land it in the bullseye to score; miss and it flies by.<br><br>
+ Edit <code>archer.json</code>: crank <code>speed</code> up and the target outruns Jev's
+ aim and the misses pile up; shrink <code>bullHalf</code> and Jev has to be exact.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Session log</div>
+ <ul id="log"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-archer/viewer/jev-hud.js b/store/agents/jev-archer/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-archer/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-archer/viewer/studio.css b/store/agents/jev-archer/viewer/studio.css
new file mode 100644
index 000000000..e830a6104
--- /dev/null
+++ b/store/agents/jev-archer/viewer/studio.css
@@ -0,0 +1,71 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #f472b6; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #1c1220 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(28,18,32,.9), rgba(10,12,18,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#arrow { color: var(--cyan); }
+#move { color: var(--accent); }
+#speed { color: var(--amber); }
+#hits { color: var(--ok); }
+#misses { color: var(--rose); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #9d174d, #f472b6); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+.panel-stage { padding: 10px; }
+
+#range { position: relative; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: #cdd9ea; }
+#scene { width: 100%; height: 62vh; display: block; }
+#banner {
+ position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%);
+ padding: 10px 22px; border-radius: 10px; font-size: 15px; font-weight: 700; letter-spacing: .5px;
+ font-family: var(--mono); white-space: nowrap;
+}
+#banner.ok { background: rgba(16,185,129,.18); border: 1px solid var(--ok); color: #065f46; box-shadow: 0 0 30px rgba(16,185,129,.4); }
+#banner.bad { background: rgba(225,29,72,.18); border: 1px solid #e11d48; color: #881337; box-shadow: 0 0 30px rgba(225,29,72,.4); }
+#banner.hidden { display: none; }
+
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px; display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(20,14,24,.5); }
+.how { color: var(--dim); font-size: 13px; line-height: 1.5; }
+.how b { color: var(--cyan); }
+.how code { color: var(--amber); }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; max-height: 50vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 10px; align-items: baseline; }
+#log li .n { color: var(--accent); }
+#log li .a { width: 90px; color: var(--cyan); font-weight: 700; }
+#log li .p { color: var(--amber); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-archer/viewer/studio.js b/store/agents/jev-archer/viewer/studio.js
new file mode 100644
index 000000000..d026f3568
--- /dev/null
+++ b/store/agents/jev-archer/viewer/studio.js
@@ -0,0 +1,160 @@
+// Jev Archer pane — draws a target range: a target slides back and forth on a wire, Jev's crosshair
+// aim tracks it, arrows release along the aim line every window, a bullseye flashes a ring and a
+// miss flies the arrow past. Finished range shows a clean-day or badge banner.
+
+const $ = (id) => document.getElementById(id)
+const els = {
+ arrow: $('arrow'), move: $('move'), speed: $('speed'), hits: $('hits'), misses: $('misses'),
+ banner: $('banner'), log: $('log'), scene: $('scene'),
+}
+
+let aim = 12, target = 12, speed = 0.6, width = 24, fuse = 6
+let hits = 0, misses = 0, shots = 16, move = 'HOLD'
+let finished = null
+let history = []
+let arrows = [] // {x, hit, t} released arrows for effect
+let prevArrow = -1
+
+function draw() {
+ const c = els.scene
+ const ctx = c.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = c.clientWidth, H = c.clientHeight
+ c.width = W * dpr; c.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+
+ // range backdrop (sky)
+ const grd = ctx.createLinearGradient(0, 0, 0, H)
+ grd.addColorStop(0, '#cfe4f0')
+ grd.addColorStop(1, '#eaf3f7')
+ ctx.fillStyle = grd
+ ctx.fillRect(0, 0, W, H)
+
+ const margin = 30
+ const fieldLeft = margin, fieldRight = W - margin
+ const wireY = H * 0.5
+ const px = (fx) => fieldLeft + (fx / width) * (fieldRight - fieldLeft)
+
+ // the sliding wire / track the target rides
+ ctx.strokeStyle = '#9aa8bd'; ctx.lineWidth = 3; ctx.lineCap = 'round'
+ ctx.beginPath(); ctx.moveTo(fieldLeft, wireY); ctx.lineTo(fieldRight, wireY); ctx.stroke()
+ // distance markers
+ ctx.fillStyle = 'rgba(60,70,90,.4)'
+ for (let i = 1; i < width; i++) {
+ const x = px(i)
+ ctx.fillRect(x - 1, wireY - 6, 2, 12)
+ }
+
+ // the aim crosshair (Jev)
+ const ax = px(aim)
+ ctx.strokeStyle = '#f472b6'; ctx.lineWidth = 2.5; ctx.lineCap = 'round'
+ ctx.beginPath()
+ ctx.moveTo(ax - 12, wireY); ctx.lineTo(ax + 12, wireY)
+ ctx.moveTo(ax, wireY - 12); ctx.lineTo(ax, wireY + 12)
+ ctx.stroke()
+ ctx.fillStyle = '#f9a8d4'
+ ctx.beginPath(); ctx.arc(ax, wireY, 3, 0, Math.PI * 2); ctx.fill()
+
+ // the sliding target
+ const tx = px(target)
+ const tw = 20 // target width in px
+ ctx.strokeStyle = '#1f2937'; ctx.lineWidth = 2
+ ctx.beginPath(); ctx.arc(tx, wireY, tw, 0, Math.PI * 2); ctx.stroke()
+ // concentric rings to the bullseye
+ ctx.fillStyle = '#f43f5e'
+ ctx.beginPath(); ctx.arc(tx, wireY, tw, 0, Math.PI * 2); ctx.fill()
+ ctx.fillStyle = '#fff'
+ ctx.beginPath(); ctx.arc(tx, wireY, tw * 0.65, 0, Math.PI * 2); ctx.fill()
+ ctx.fillStyle = '#f43f5e'
+ ctx.beginPath(); ctx.arc(tx, wireY, tw * 0.28, 0, Math.PI * 2); ctx.fill()
+ // direction chevron
+ ctx.fillStyle = 'rgba(0,0,0,.35)'
+ ctx.beginPath()
+ const dd = typeof dir === 'number' ? dir : 1
+ ctx.moveTo(tx + dd * tw, wireY); ctx.lineTo(tx + dd * (tw + 7), wireY - 4); ctx.lineTo(tx + dd * (tw + 7), wireY + 4)
+ ctx.closePath(); ctx.fill()
+
+ // frozen arrows: a hit sticks in the bullseye, a miss trails off past where it was
+ arrows.forEach((a) => {
+ a.t += 0.06
+ const x = a.hit ? px(a.x) : px(a.x - (1 - a.t) * (60 / width) * (a.x - aim) ) // drift for a miss
+ const y = wireY + (a.hit ? -2 : (a.t) * 30) // a miss sinks or flies
+ ctx.strokeStyle = '#7c3aed'; ctx.lineWidth = 2.5; ctx.lineCap = 'round'
+ ctx.beginPath()
+ if (a.hit) { ctx.moveTo(x, y - 14); ctx.lineTo(x, y + 14) }
+ else { ctx.moveTo(x - 14, y); ctx.lineTo(x + 14, y) }
+ ctx.stroke()
+ })
+ arrows = arrows.filter((a) => a.t < 1)
+}
+
+// no `dir` var; derive from state if provided
+let dir = 1
+
+function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])) }
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history.slice(-28)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="n">#${h.step}</span><span class="a">${esc(h.move)}</span><span class="p">aim ${h.aim.toFixed(1)}</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function renderBanner() {
+ if (!finished) { els.banner.classList.add('hidden'); return }
+ els.banner.classList.remove('hidden')
+ els.banner.textContent = finished.ok
+ ? `✓ CLEAN DAY · ${finished.hits} bullseyes`
+ : `✗ ${finished.hits} bullseyes · ${finished.misses} missed`
+ els.banner.className = 'banner ' + (finished.ok ? 'ok' : 'bad')
+}
+
+function onTick(msg) {
+ if (typeof msg.aim === 'number') aim = msg.aim
+ if (typeof msg.target === 'number') target = msg.target
+ if (typeof msg.dir === 'number') dir = msg.dir
+ if (typeof msg.speed === 'number') speed = msg.speed
+ if (typeof msg.targetWidth === 'number') width = msg.targetWidth
+ if (typeof msg.fuse === 'number') fuse = msg.fuse
+ if (typeof msg.shots === 'number') shots = msg.shots
+ hits = msg.hits ?? hits
+ misses = msg.misses ?? misses
+ move = msg.move || move
+ finished = msg.finished || null
+ history = msg.history || history
+
+ // detect a fresh released arrow (hits+misses incremented) for effects
+ const total = hits + misses
+ if (total > prevArrow) { arrows.push({ x: target, hit: msg.lastHit, t: 0 }); prevArrow = total }
+
+ els.arrow.textContent = finished ? '—' : `${Math.min(total + 1, shots)}/${shots}`
+ els.move.textContent = move
+ els.speed.textContent = 'v' + speed.toFixed(2)
+ els.hits.textContent = String(hits)
+ els.misses.textContent = String(misses)
+
+ renderBanner()
+ renderLog()
+ draw()
+ if (arrows.length) requestAnimationFrame(draw)
+}
+
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-archer/viewer/viewer.mjs b/store/agents/jev-archer/viewer/viewer.mjs
new file mode 100644
index 000000000..1236e0011
--- /dev/null
+++ b/store/agents/jev-archer/viewer/viewer.mjs
@@ -0,0 +1,262 @@
+// Jev Archer viewer — a loopback server running a live archery demo. A target slides across a line
+// and Jev (TypeSafe's System One model) reads its position and the aim point every tick and nudges
+// the aim to track it, releasing an arrow each window. The arrow flies to where the aim is when it
+// releases — a fast, drifting target makes the arrow land off-center and miss. The agent shapes
+// archer.json (how fast the target slides, the bullseye size) — crank the target speed up and Jev's
+// aim trails and the misses pile up. The range is synthetic; the decision loop is the demo.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds archer.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT = {
+ title: 'Jev Archer',
+ description: 'Jev is the archer — track the sliding target and plant every arrow in the bullseye.',
+ instrument: 'ARCHER',
+ tickMs: 150, speed: 0.6, bullHalf: 1.0, targetWidth: 24, shots: 16,
+ style: 'You are the archer. A target slides across the line — read its position and nudge your aim to track it, then release. Land the arrow in the bullseye to score; miss and it flies by. Keep your aim glued to the moving target.',
+}
+
+const MOVES = ['LEFT_FAST', 'LEFT', 'HOLD', 'RIGHT', 'RIGHT_FAST']
+const AIM = { LEFT_FAST: -1.6, LEFT: -0.8, HOLD: 0, RIGHT: 0.8, RIGHT_FAST: 1.6 }
+
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+
+function stateBlock(p, s) {
+ return `${p.style}
+Aim is at x ${s.aim.toFixed(1)}; the target is at x ${s.target.toFixed(1)} (speed ${p.speed.toFixed(2)}), releasing in ${s.fuse} ticks.
+aim x ${s.aim.toFixed(1)} target x ${s.target.toFixed(1)} in ${s.fuse} ticks
+Which way do you nudge the aim? ${MOVES.join(' / ')}`
+}
+
+export async function startArcherViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let error = null
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let step = 0
+ let running = false
+ let state = null // {aim, target, dir, fuse, hits, misses}
+ let move = 'HOLD'
+ let episode = 0 // bumps each time an episode restarts on its own, so the next one differs
+ let finished = null // {ok, ticks, hits, misses}
+ let history = [] // {step, aim, move}
+ let notified = false
+ let lastHit = null // result of the most recent released arrow (true/false)
+ let rng
+ let _fuse = 6 // declared BEFORE the first readCfg/resetStateNow below (TDZ guard)
+
+ let lastCfg = null
+ let p = readCfg(join(workspace, 'archer.json'))
+
+ function readCfg(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ const merged = { ...DEFAULT, ...raw }
+ if (!lastCfg || merged.speed !== lastCfg.speed || merged.targetWidth !== lastCfg.targetWidth || merged.shots !== lastCfg.shots || merged.bullHalf !== lastCfg.bullHalf || !state) {
+ resetStateNow(merged)
+ }
+ lastCfg = merged
+ return merged
+ } catch (e) {
+ error = clean(e.message)
+ return lastCfg || DEFAULT
+ }
+ }
+
+ function resetStateNow(cfg) {
+ rng = mulberry32(8817 + episode * 97)
+ const W = cfg.targetWidth ?? DEFAULT.targetWidth
+ const FUSE = 6
+ state = { aim: W / 2, target: W / 2, dir: rng() < 0.5 ? 1 : -1, fuse: FUSE, hits: 0, misses: 0 }
+ _fuse = FUSE
+ move = 'HOLD'
+ finished = null
+ history = []
+ notified = false
+ step = 0
+ error = null
+ }
+ function resetState() { resetStateNow(p) }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ return {
+ spec: 1,
+ ready: history.length > 0 || finished !== null,
+ summary: error
+ ? 'Jev Archer needs a fix'
+ : finished
+ ? `${p.title} · ${finished.ok ? 'clean day, ' + finished.hits + ' bullseyes' : finished.hits + ' bullseyes, ' + finished.misses + ' missed'}`
+ : `${p.title} · arrow ${Math.min(Math.floor((step + 1) / _fuse), p.shots) + 1}/${p.shots} · ${state.hits} bullseyes · ${state.misses} missed`,
+ findings: (error ? [{ severity: 'error', kind: 'archer', message: error }] : []).concat(
+ finished
+ ? [{ severity: finished.ok ? 'info' : 'error', kind: 'archer', message: finished.ok ? `Jev sank ${finished.hits} of ${finished.hits + finished.misses} bullseyes` : `Jev missed ${finished.misses} of ${finished.hits + finished.misses} shots` }]
+ : []
+ ),
+ artifact: 'archer.json',
+ phases: [
+ { id: 'learn', name: 'Reading', state: history.length < 5 ? 'active' : 'done' },
+ { id: 'call', name: 'Aiming', state: history.length >= 5 && !finished ? 'active' : finished ? 'done' : 'pending' },
+ { id: 'finish', name: 'Range done', state: finished ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick', title: p.title, description: p.description, instrument: p.instrument,
+ speed: p.speed, targetWidth: p.targetWidth, bullHalf: p.bullHalf, shots: p.shots,
+ aim: state?.aim, target: state?.target, dir: state?.dir, fuse: state?.fuse,
+ move, step, running, error, finished, lastHit,
+ hits: state?.hits, misses: state?.misses, history: history.slice(-300),
+ })
+ }
+
+ function reset() { resetState(); tail(); if (running) schedule() }
+ function pause() { running = false; clearTimeout(timer) }
+ function start() { if (!running) { running = true; schedule() } }
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, p.tickMs) }
+ async function run() {
+ if (stopped) return
+ if (finished) {
+ // Never sit on a finished screen: show the result briefly, then play again.
+ finished.shownAt ??= Date.now()
+ if (Date.now() - finished.shownAt > 3500) { episode++; resetState() }
+ tail(); schedule(); return
+ }
+ await decide()
+ schedule()
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ const res = await evaluate({
+ state: stateBlock(p, state),
+ questions: {
+ aim: { type: 'choice', instructions: 'Which way do you nudge the aim this tick?', options: MOVES },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const pick = String(res.answers.aim?.choice || 'HOLD')
+ move = MOVES.includes(pick) ? pick : 'HOLD'
+ // physics: nudge the aim, slide the target one tick, count down the fuse
+ const W = p.targetWidth ?? DEFAULT.targetWidth
+ state.aim = clamp(state.aim + AIM[move], 1, W - 1)
+ state.target = clamp(state.target + state.dir * (p.speed ?? DEFAULT.speed), 1, W - 1)
+ if (state.target <= 1.2) state.dir = 1
+ else if (state.target >= W - 1.2) state.dir = -1
+ state.fuse--
+ step++
+ history.push({ step, aim: state.aim, move })
+ if (history.length > 400) history.splice(0, history.length - 400)
+ if (state.fuse <= 0) {
+ // arrow releases: flies to where the aim currently tracks; bullseye if it lands on the target
+ lastHit = Math.abs(state.aim - state.target) <= (p.bullHalf ?? DEFAULT.bullHalf)
+ if (lastHit) state.hits++
+ else state.misses++
+ state.fuse = _fuse
+ state.dir = rng() < 0.5 ? 1 : -1
+ if (state.hits + state.misses >= (p.shots ?? DEFAULT.shots)) {
+ finished = { ok: state.misses === 0, ticks: step, hits: state.hits, misses: state.misses }
+ notified = true
+ }
+ }
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ const watcher = watch(join(workspace, 'archer.json'), () => {
+ p = readCfg(join(workspace, 'archer.json'))
+ tail()
+ if (running) schedule()
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: p.title, instrument: p.instrument, speed: p.speed, targetWidth: p.targetWidth, bullHalf: p.bullHalf, aim: state?.aim, target: state?.target, dir: state?.dir, fuse: state?.fuse, move, step, running, error, finished, hits: state?.hits, misses: state?.misses, history: history.slice(-300) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ resetState()
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startArcherViewer({ workspace, port })
+ console.log(`Jev Archer listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-arena/.gitignore b/store/agents/jev-arena/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-arena/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-arena/AGENTS.md b/store/agents/jev-arena/AGENTS.md
new file mode 100644
index 000000000..db361c7bf
--- /dev/null
+++ b/store/agents/jev-arena/AGENTS.md
@@ -0,0 +1,72 @@
+# Jev Arena in OpenHarness
+
+You are building a Jev Arena: a tiny grid world where **Jev — TypeSafe's System One model — is the
+brain**. On the left, the Jev Arena viewer shows a live game board and a "Jev's brain" panel. Jev
+picks every move in real time (about 3 per second), and the viewer shows the probability
+distribution over `up / down / left / right / wait`, plus Jev's confidence. The user watches a
+decision model think.
+
+On the right, you design the world. **You shape the arena; Jev plays it.**
+
+## The workspace
+
+- `arena.json` — the world + rules. This is the ONLY file you edit. The viewer watches it and
+ adapts live; you do not need to restart anything.
+
+```jsonc
+{
+ "title": "My Arena", // shows in the viewer header
+ "description": "A maze that tests Jev.", // subtitle
+ "size": 12, // grid is size x size (2..32)
+ "hero": { "x": 1, "y": 1 }, // where Jev starts
+ "goal": { "x": 10, "y": 10 }, // where Jev must reach
+ "walls": [ { "x": 3, "y": 2 }, ... ], // blocked cells
+ "coins": [ { "x": 5, "y": 3 }, ... ], // collect these on the way
+ "rules": "Reach the star. Move one cell at a time; you cannot pass through walls.",
+ "speed": 320 // ms per decision (>= 60)
+}
+```
+
+## Your job
+
+Make Jev interesting to watch, and make the arena test it. Good arenas:
+
+- **Reward intelligence.** A maze with walls, a goal, and coins positioned so a dumb "always go
+ right" policy starves. Watch Jev's probability distributions change as it reconsiders.
+- **Surprise Jev.** A layout where the obvious path is blocked, so you can see Jev's confidence dip
+ and recover. That visible uncertainty is the point.
+- **Tell a story.** Title and description that make the attempt feel like an event ("the escape", "the
+ vault heist", "rescue the last battery").
+
+Do NOT just set a goal in an empty room. Every arena.json you ship should be worth watching for at
+least a minute.
+
+You can also tune the pace: lower `speed` (~100) for frantic decisions, higher (~500) for a
+deliberate, readable pace. The viewer has Play / Pause / Step / Reset controls so the user can stop
+Jev mid-thought and step one decision at a time.
+
+## Keep current
+
+- Keep `arena.json` valid JSON at all times. The viewer keeps running on the last good world; a bad
+ edit means Jev stops until it parses again.
+- Keep `title` and `description` truthful.
+- When you change walls / goal / coins, that is the "pause and watch Jev react" moment. Say so in
+ chat after you save.
+
+## Rules
+
+- Never propose opening a browser, changing ports, or running a second server. The viewer is already
+ running on the left.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to drive your own experiments
+ (for example, to ask Jev to score an arena you designed before committing to it). Use the `jev`
+ helpers: `noul`, `choice`, `score`. See `toolchain/README.md`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock so everything still works
+ offline. With one set, the viewer calls the real TypeSafe API automatically.
+- The Jev Arena viewer writes `.harness/verdict.json` itself. Do not edit it.
+
+## Definition of done
+
+- A valid `arena.json` that parses.
+- The world is genuinely interesting to watch (walls, a goal, a route; ideally coins).
+- Jev can reach the goal (test it: hit Step or let it run and confirm it arrives).
+- Title and description set.
diff --git a/store/agents/jev-arena/LICENSE b/store/agents/jev-arena/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-arena/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-arena/README.md b/store/agents/jev-arena/README.md
new file mode 100644
index 000000000..d35b02956
--- /dev/null
+++ b/store/agents/jev-arena/README.md
@@ -0,0 +1,51 @@
+# Jev Arena
+
+**A live grid world powered by Jev — TypeSafe's System One decision model.** You shape the arena;
+Jev plays it. The viewer shows the board and a live "Jev's brain" panel: every move Jev makes,
+streamed as a probability distribution over `up / down / left / right / wait`, with its confidence —
+because watching a decision model think is the point.
+
+This is a harness for OpenHarness. The agent on the right designs `arena.json`; the viewer on the
+left runs the game loop and asks Jev for each move in real time. No text generation — just fast,
+calibrated decisions you can watch.
+
+## Anatomy
+
+```
+jev-arena/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to shape arenas worth watching
+ skills/arena/SKILL.md # the design + verification craft
+ template/arena.json # a starter world
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock)
+ viewer.sh # launches the viewer
+ viewer/ # the loopback viewer server + pane
+ check.mjs # validates arena.json
+ setup.sh / doctor.sh / init-workspace.sh
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs the world loop and calls Jev for each move at `arena.speed` ms. It
+`POST /v1/systemone` to TypeSafe when `TYPESAFE_API_KEY` is set; without a key it uses a
+deterministic local mock (so the harness runs fully offline and in tests). It streams every frame —
+board, hero, decisions log, probabilities — to the pane over SSE, and writes
+`.harness/verdict.json` (the header's "ready / phases / summary").
+
+## Jev, honestly
+
+Jev is new and early-access. Its headline claims (speed, calibration, "can't hallucinate") are
+mostly vendor-reported, and the mock in this harness is a stand-in for *plumbing*, not judgement.
+Treat Jev's decisions as a fast, cheap signal to branch on — and verify on your own data before you
+trust it for anything consequential. With a `TYPESAFE_API_KEY` this harness exercises the real model.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness surfaces Jev's "System One" model in a live, visual way people can
+try without writing API code._
diff --git a/store/agents/jev-arena/THIRD_PARTY_NOTICES.md b/store/agents/jev-arena/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-arena/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-arena/harness.json b/store/agents/jev-arena/harness.json
new file mode 100644
index 000000000..c66d07314
--- /dev/null
+++ b/store/agents/jev-arena/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-arena",
+ "name": "Jev Arena",
+ "category": "AI",
+ "author": "Autonomous",
+ "description": "A live grid world powered by Jev, TypeSafe's System One model. Jev decides every move in real time — watch its probability distributions and confidence as it thinks, and redesign the world to test it.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "arena.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-arena/skills/arena/SKILL.md b/store/agents/jev-arena/skills/arena/SKILL.md
new file mode 100644
index 000000000..0de89b4f8
--- /dev/null
+++ b/store/agents/jev-arena/skills/arena/SKILL.md
@@ -0,0 +1,52 @@
+---
+name: jev-arena
+description: Design and verify Jev Arenas in OpenHarness's live viewer, where Jev plays the world you build.
+---
+
+# Jev Arena design
+
+Jev Arena shows a live grid and a "Jev's brain" panel: Jev (TypeSafe's System One model) chooses a
+move every `arena.speed` ms, and the viewer streams the probability distribution and confidence for
+`up / down / left / right / wait`.
+
+## The loop
+
+1. Update `arena.json`. The viewer watches it and adapts live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `arena.json` is a valid, playable
+ world, and reports the current verdict / status. Run it before you call a world done.
+3. Watch Jev play. When the layout changes, that's the moment to look: does Jev's confidence dip and
+ recover? Is the route interesting?
+
+## Reading Jev
+
+The viewer shows, per action, a probability bar and the chosen action highlighted. `confidence` is
+a 0..1 concentration of the distribution. A confident Jev puts most mass on one move; a confused Jev
+spreads it. Good arenas produce both states.
+
+## Verifying a world
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `arena.json` is invalid (missing fields,
+out-of-bounds, goal covered by a wall). It does not replace watching Jev actually play. Always
+confirm Jev can reach the goal by stepping or running it.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace):
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+import { readFileSync } from "node:fs";
+const world = JSON.parse(readFileSync("arena.json"));
+const res = await evaluate({
+ state: JSON.stringify(world),
+ questions: {
+ hard: jev.noul("Is this arena hard for a reactive agent?"),
+ vibe: jev.score({0:"empty",1:"ok",2:"brilliant"}, "How good is this arena to watch?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-arena/store.json b/store/agents/jev-arena/store.json
new file mode 100644
index 000000000..6b250fac4
--- /dev/null
+++ b/store/agents/jev-arena/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Watch a decision model think",
+ "examples": [
+ {
+ "prompt": "Redesign the arena into the Vault Heist: Jev starts outside the bank, must slip between the walls to the vault star, and grab the three gold bars (coins) on the way while avoiding the security lasers (walls). Make it a tight maze that forces a few sharp turns so Jev's confidence dips and recovers.",
+ "caption": "The Vault Heist · a tight maze where Jev's probability bars visibly shift at each turn"
+ }
+ ]
+}
diff --git a/store/agents/jev-arena/template/arena.json b/store/agents/jev-arena/template/arena.json
new file mode 100644
index 000000000..2a97926c2
--- /dev/null
+++ b/store/agents/jev-arena/template/arena.json
@@ -0,0 +1,19 @@
+{
+ "title": "Jev Arena",
+ "description": "A tiny grid world where Jev decides each move.",
+ "size": 12,
+ "hero": { "x": 1, "y": 1 },
+ "goal": { "x": 10, "y": 10 },
+ "walls": [
+ { "x": 3, "y": 2 }, { "x": 3, "y": 3 }, { "x": 3, "y": 4 },
+ { "x": 6, "y": 1 }, { "x": 7, "y": 1 }, { "x": 8, "y": 1 }, { "x": 8, "y": 2 },
+ { "x": 4, "y": 6 }, { "x": 5, "y": 6 }, { "x": 6, "y": 6 },
+ { "x": 9, "y": 5 }, { "x": 9, "y": 6 }, { "x": 9, "y": 7 },
+ { "x": 2, "y": 9 }, { "x": 5, "y": 8 }, { "x": 5, "y": 9 }
+ ],
+ "coins": [
+ { "x": 5, "y": 3 }, { "x": 8, "y": 6 }, { "x": 2, "y": 6 }, { "x": 7, "y": 9 }, { "x": 3, "y": 1 }
+ ],
+ "rules": "Reach the star. Collect the coins on the way. Move one cell at a time (up/down/left/right); you cannot pass through walls.",
+ "speed": 320
+}
diff --git a/store/agents/jev-arena/test/viewer.test.mjs b/store/agents/jev-arena/test/viewer.test.mjs
new file mode 100644
index 000000000..4a8db2f52
--- /dev/null
+++ b/store/agents/jev-arena/test/viewer.test.mjs
@@ -0,0 +1,95 @@
+// Viewer integration test for Jev Arena. Spins up the real viewer against a temp workspace and
+// checks the loop: world parses, Jev decides, the board moves, the goal is reached, the verdict
+// is written, and control commands work.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, cpSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+async function freshViewer(worldOverrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-arena-test-'))
+ const world = {
+ title: 'Test', size: 5, hero: { x: 0, y: 0 }, goal: { x: 4, y: 0 },
+ walls: [], coins: [], rules: 'Reach the goal.', speed: 60, ...worldOverrides,
+ }
+ writeFileSync(join(ws, 'arena.json'), JSON.stringify(world))
+ const { startArenaViewer } = await import(viewerPath)
+ const viewer = await startArenaViewer({ workspace: ws, port: 0 })
+ return { ws, viewer, world }
+}
+
+test('Jev Arena viewer drives a happy path well', async () => {
+ const { ws, viewer, world } = await freshViewer()
+ try {
+ // Let it run a bit: it should move toward the goal and eventually reach it on a clear board.
+ const deadline = Date.now() + 4000
+ let reached = false
+ let lastState
+ while (Date.now() < deadline && !reached) {
+ await new Promise((r) => setTimeout(r, 200))
+ if (existsSync(join(ws, '.harness/verdict.json'))) {
+ lastState = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ if (String(lastState.summary).includes('reached goal yes')) reached = true
+ }
+ }
+ assert.ok(reached, `expected Jev to reach the goal on an open board; summary was ${lastState?.summary}`)
+ assert.ok(lastState.ready, 'verdict should be ready once reached')
+ assert.ok(lastState.phases?.length, 'verdict should carry phases')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Arena writes a verdict and updates it', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ await new Promise((r) => setTimeout(r, 300))
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Arena stops when the goal is inside a wall (unreachable)', async () => {
+ const { ws, viewer, world } = await freshViewer()
+ try {
+ // Put a wall on the goal so Jev can never reach it — the viewer should keep running but the
+ // world is invalid per check.mjs; the viewer itself should not crash.
+ await new Promise((r) => setTimeout(r, 200))
+ // Apply the constraint: verify check.mjs flags it.
+ const { spawnSync } = await import('node:child_process')
+ const { execFileSync } = await import('node:child_process')
+ const out = execFileSync('node', [join(HERE, '../toolchain/check.mjs')], { env: { ...process.env, HARNESS_WORKSPACE: ws }, encoding: 'utf8' })
+ assert.ok(out.includes('ok'))
+ void world
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Arena control: pause, start, reset', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }),
+ })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('step'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-arena/toolchain/check.mjs b/store/agents/jev-arena/toolchain/check.mjs
new file mode 100644
index 000000000..dc2754975
--- /dev/null
+++ b/store/agents/jev-arena/toolchain/check.mjs
@@ -0,0 +1,55 @@
+// check.mjs — validate the workspace's arena.json and report the viewer's current state.
+// Exits non-zero when the world is invalid or unplayable. Read-only: never writes the verdict
+// (the viewer owns that).
+import { readFileSync, existsSync } from 'node:fs'
+import { join } from 'node:path'
+
+const workspace = process.env.HARNESS_WORKSPACE || process.cwd()
+const file = join(workspace, 'arena.json')
+
+const problems = []
+if (!existsSync(file)) {
+ console.error('fail arena.json is missing')
+ process.exit(1)
+}
+
+let world
+try {
+ world = JSON.parse(readFileSync(file, 'utf8'))
+} catch (e) {
+ console.error(`fail arena.json is not valid JSON: ${e.message}`)
+ process.exit(1)
+}
+
+const size = Number(world.size)
+if (!Number.isInteger(size) || size < 2 || size > 32) {
+ console.error(`fail size must be an integer 2..32 (got ${world.size})`)
+ problems.push('size')
+}
+const inB = (p) => p && Number.isInteger(p.x) && Number.isInteger(p.y) && p.x >= 0 && p.y >= 0 && p.x < size && p.y < size
+if (!world.hero || !inB(world.hero)) { console.error('fail hero is missing or out of bounds'); problems.push('hero') }
+if (!world.goal || !inB(world.goal)) { console.error('fail goal is missing or out of bounds'); problems.push('goal') }
+for (const w of world.walls || []) if (!inB(w)) { console.error(`fail wall out of bounds: ${w.x},${w.y}`); problems.push('wall') }
+for (const c of world.coins || []) if (!inB(c)) { console.error(`fail coin out of bounds: ${c.x},${c.y}`); problems.push('coin') }
+if (!world.rules) { console.warn('warn no rules text'); }
+const speed = Number(world.speed)
+if (!Number.isFinite(speed) || speed < 60) console.warn('warn speed below 60ms may be frantic')
+
+// Goal covered by a wall?
+if (world.goal && world.walls && world.walls.some((w) => w.x === world.goal.x && w.y === world.goal.y)) {
+ console.error('fail the goal is inside a wall — Jev can never reach it')
+ problems.push('goal-in-wall')
+}
+// Hero covered by a wall?
+if (world.hero && world.walls && world.walls.some((w) => w.x === world.hero.x && w.y === world.hero.y)) {
+ console.error('fail the hero is inside a wall — Jev starts stuck')
+ problems.push('hero-in-wall')
+}
+
+if (problems.length) {
+ console.error(`fail ${problems.join(', ')}`)
+ process.exit(1)
+}
+
+console.log(`ok ${world.title || 'untitled'} · ${size}x${size} · goal at (${world.goal.x},${world.goal.y}) · ${(world.walls||[]).length} walls · ${(world.coins||[]).length} coins · ${speed}ms/step`)
+process.exit(0)
diff --git a/store/agents/jev-arena/toolchain/doctor.sh b/store/agents/jev-arena/toolchain/doctor.sh
new file mode 100644
index 000000000..767c67d1d
--- /dev/null
+++ b/store/agents/jev-arena/toolchain/doctor.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# Jev Arena doctor — one line per machine readiness check.
+set -euo pipefail
+node_v="$(command -v node >/dev/null 2>&1 && node -v || true)"
+if [ -n "$node_v" ]; then
+ major="$(printf '%s' "$node_v" | sed 's/^v//; s/\..*//')"
+ if [ "$major" -ge 18 ] 2>/dev/null; then
+ echo "ok node $node_v"
+ exit 0
+ else
+ echo "miss node >= 18 (have $node_v)"
+ exit 1
+ fi
+fi
+echo "miss node (>= 18)"
+exit 1
diff --git a/store/agents/jev-arena/toolchain/init-workspace.sh b/store/agents/jev-arena/toolchain/init-workspace.sh
new file mode 100644
index 000000000..ad4370975
--- /dev/null
+++ b/store/agents/jev-arena/toolchain/init-workspace.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# init-workspace — runs after the template copy, cwd = the workspace. Nothing more needed for Jev Arena
+# (arena.json is already in the template); kept for the standard shape so the harness can seed future
+# worlds without an app change.
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-arena/toolchain/jev.mjs b/store/agents/jev-arena/toolchain/jev.mjs
new file mode 100644
index 000000000..854501a8b
--- /dev/null
+++ b/store/agents/jev-arena/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-arena/toolchain/setup.sh b/store/agents/jev-arena/toolchain/setup.sh
new file mode 100644
index 000000000..6e8891fe2
--- /dev/null
+++ b/store/agents/jev-arena/toolchain/setup.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+# Jev Arena setup — no external toolchain beyond Node (already required by the daemon), so nothing
+# to install. Kept for the standard shape.
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-arena/toolchain/viewer.sh b/store/agents/jev-arena/toolchain/viewer.sh
new file mode 100644
index 000000000..5425bb22b
--- /dev/null
+++ b/store/agents/jev-arena/toolchain/viewer.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# Jev Arena viewer launcher. Sets up the env the daemon supplies and execs the Node viewer.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+: "${HARNESS_VIEWER_PORT:?HARNESS_VIEWER_PORT is required}"
+: "${HARNESS_WORKSPACE:?HARNESS_WORKSPACE is required}"
+command -v node >/dev/null 2>&1 || { echo "miss node" >&2; exit 1; }
+exec node "$ROOT/viewer/viewer.mjs"
diff --git a/store/agents/jev-arena/viewer/index.html b/store/agents/jev-arena/viewer/index.html
new file mode 100644
index 000000000..0e803fb6e
--- /dev/null
+++ b/store/agents/jev-arena/viewer/index.html
@@ -0,0 +1,90 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Jev Arena</title>
+ <link rel="stylesheet" href="/studio.css" />
+ </head>
+ <body>
+ <main class="arena">
+ <header class="masthead">
+ <div class="titles">
+ <div class="eyebrow">
+ <span class="dot"></span> JEV ARENA · live system-one brain
+ </div>
+ <h1 id="title">Jev Arena</h1>
+ <p id="description">A tiny grid world where Jev decides every move.</p>
+ </div>
+ <div class="modelbadge">
+ <span class="model" id="model">jev-latest</span>
+ <span class="client" id="client">mock</span>
+ </div>
+ </header>
+
+ <section class="stage-wrap">
+ <div class="stage">
+ <canvas id="board"></canvas>
+ <div id="toast" class="toast" hidden></div>
+ <div id="overlay" class="overlay" hidden>
+ <div class="card">
+ <h2 id="overlay-title">Goal reached ⭐</h2>
+ <p id="overlay-msg">Jev made it across the arena.</p>
+ <button id="reset-big" class="btn primary">Play again</button>
+ </div>
+ </div>
+ </div>
+ <aside class="brain">
+ <div class="brain-head">
+ <h2>Jev's brain</h2>
+ <span class="live" id="live">thinking…</span>
+ </div>
+
+ <div class="brainstats">
+ <div class="stat">
+ <span class="k">decisions</span>
+ <span class="v" id="moves">0</span>
+ </div>
+ <div class="stat">
+ <span class="k">coins</span>
+ <span class="v" id="coins">0</span>
+ </div>
+ <div class="stat">
+ <span class="k">confidence</span>
+ <span class="v" id="confidence">–</span>
+ </div>
+ </div>
+
+ <div class="actions" id="actions" aria-label="Jev's move probabilities"></div>
+
+ <div class="confidence-rail">
+ <div class="rail-track"><div class="rail-fill" id="rail-fill"></div></div>
+ <div class="rail-labels"><span>unsure</span><span>certain</span></div>
+ </div>
+
+ <div class="log">
+ <h3>decision feed</h3>
+ <ol id="log"></ol>
+ </div>
+
+ <div class="controls">
+ <button id="start" class="btn primary">▶ Start</button>
+ <button id="pause" class="btn">⏸ Pause</button>
+ <button id="step" class="btn">⏭ Step</button>
+ <button id="reset" class="btn danger">↺ Reset</button>
+ </div>
+ </aside>
+ </section>
+
+ <section class="rules">
+ <p id="rules">Reach the goal. Jev decides each move.</p>
+ <p class="hint">
+ The agent on the right edits
+ <code>arena.json</code> — the world reshapes and Jev plays it live.
+ </p>
+ </section>
+ </main>
+ <script src="/studio.js" type="module"></script>
+ <script src="/jev-hud.js" defer></script>
+ </body>
+</html>
diff --git a/store/agents/jev-arena/viewer/jev-hud.js b/store/agents/jev-arena/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-arena/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-arena/viewer/studio.css b/store/agents/jev-arena/viewer/studio.css
new file mode 100644
index 000000000..0dc862561
--- /dev/null
+++ b/store/agents/jev-arena/viewer/studio.css
@@ -0,0 +1,92 @@
+:root {
+ --bg: #0b0f1a;
+ --panel: #131a2b;
+ --panel-2: #1a2338;
+ --line: #26314e;
+ --text: #e8edf7;
+ --muted: #8b96b0;
+ --accent: #5ee0c0;
+ --accent-2: #7aa2ff;
+ --danger: #ff6b7a;
+ --warn: #ffce6b;
+ --ok: #5ee08a;
+}
+* { box-sizing: border-box; }
+body {
+ margin: 0;
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ background: radial-gradient(1200px 600px at 20% -10%, #16203a 0%, var(--bg) 55%);
+ color: var(--text);
+ min-height: 100vh;
+}
+.arena { max-width: 1280px; margin: 0 auto; padding: 20px clamp(12px, 3vw, 32px) 60px; }
+
+.masthead { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 18px; }
+.eyebrow { display: flex; align-items: center; gap: 8px; font-size: 11px; letter-spacing: 0.22em; text-transform: uppercase; color: var(--accent); font-weight: 600; }
+.eyebrow .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); animation: pulse 1.6s infinite; }
+@keyframes pulse { 50% { opacity: .4; } }
+h1 { margin: 6px 0 2px; font-size: 30px; letter-spacing: -0.02em; }
+#description { margin: 0; color: var(--muted); font-size: 14px; }
+.modelbadge { display: flex; gap: 8px; align-items: center; }
+.modelbadge span { font-size: 11px; padding: 4px 9px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel); color: var(--muted); }
+.modelbadge .client { color: var(--accent-2); border-color: var(--accent-2); }
+
+.stage-wrap { display: grid; grid-template-columns: 1fr 340px; gap: 20px; }
+@media (max-width: 860px) { .stage-wrap { grid-template-columns: 1fr; } }
+
+.stage { position: relative; background: var(--panel); border: 1px solid var(--line); border-radius: 18px; overflow: hidden; min-height: 460px; }
+#board { display: block; width: 100%; height: auto; min-height: 460px; }
+.overlay { position: absolute; inset: 0; display: grid; place-items: center; background: rgba(11,15,26,.72); backdrop-filter: blur(2px); }
+.overlay[hidden] { display: none; }
+.card { background: var(--panel-2); border: 1px solid var(--accent); border-radius: 16px; padding: 26px 32px; text-align: center; box-shadow: 0 0 40px rgba(94,224,192,.25); }
+.card h2 { margin: 0 0 6px; color: var(--accent); }
+.card p { margin: 0 0 16px; color: var(--muted); }
+.toast { position: absolute; top: 14px; left: 50%; transform: translateX(-50%); background: var(--panel-2); border: 1px solid var(--line); padding: 8px 14px; border-radius: 999px; font-size: 13px; color: var(--text); }
+.toast[hidden] { display: none; }
+
+.brain { display: flex; flex-direction: column; gap: 14px; }
+.brain-head { display: flex; justify-content: space-between; align-items: center; }
+.brain-head h2 { margin: 0; font-size: 15px; letter-spacing: 0.05em; text-transform: uppercase; color: var(--muted); }
+.live { font-size: 12px; padding: 3px 9px; border-radius: 999px; border: 1px solid var(--line); color: var(--muted); }
+.live.thinking { color: var(--accent); border-color: var(--accent); animation: pulse 1.4s infinite; }
+.live.idle { color: var(--muted); }
+.live.done { color: var(--ok); border-color: var(--ok); }
+
+.brainstats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
+.stat { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 10px; text-align: center; }
+.stat .k { display: block; font-size: 10px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }
+.stat .v { font-size: 24px; font-weight: 700; font-variant-numeric: tabular-nums; }
+
+.actions { display: flex; flex-direction: column; gap: 8px; }
+.action { display: grid; grid-template-columns: 52px 1fr auto; align-items: center; gap: 10px; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 8px 12px; }
+.action .name { font-weight: 600; font-size: 14px; text-transform: capitalize; }
+.action .bar { grid-column: 2; height: 10px; background: var(--panel-2); border-radius: 999px; overflow: hidden; position: relative; }
+.action .bar i { position: absolute; inset: 0; right: auto; background: linear-gradient(90deg, var(--accent-2), var(--accent)); border-radius: 999px; width: 0; transition: width .18s ease; }
+.action.chosen { border-color: var(--accent); box-shadow: 0 0 14px rgba(94,224,192,.25); }
+.action .pct { grid-column: 3; font-variant-numeric: tabular-nums; font-size: 13px; min-width: 44px; text-align: right; color: var(--muted); }
+
+.confidence-rail { padding: 2px 2px 0; }
+.rail-track { height: 6px; background: var(--panel-2); border-radius: 999px; overflow: hidden; }
+.rail-fill { height: 100%; width: 0; background: linear-gradient(90deg, var(--warn), var(--accent)); border-radius: 999px; transition: width .2s ease; }
+.rail-labels { display: flex; justify-content: space-between; font-size: 10px; color: var(--muted); margin-top: 4px; }
+
+.log h3 { margin: 10px 0 6px; font-size: 11px; text-transform: uppercase; letter-spacing: .12em; color: var(--muted); }
+.log ol { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 190px; overflow-y: auto; }
+.log li { display: flex; gap: 8px; font-size: 12px; color: var(--text); background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 9px; font-variant-numeric: tabular-nums; }
+.log li .n { color: var(--muted); min-width: 26px; }
+.log li .mv { text-transform: uppercase; font-weight: 700; color: var(--accent); min-width: 46px; }
+.log li .cf { margin-left: auto; color: var(--muted); }
+
+.controls { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
+.btn { border: 1px solid var(--line); background: var(--panel-2); color: var(--text); border-radius: 10px; padding: 10px; font-size: 13px; font-weight: 600; cursor: pointer; }
+.btn:hover { border-color: var(--accent-2); }
+.btn.primary { background: var(--accent); color: #06231a; border-color: var(--accent); }
+.btn.primary:hover { filter: brightness(1.06); }
+.btn.danger { color: var(--danger); }
+.btn.danger:hover { border-color: var(--danger); }
+.btn:disabled { opacity: .45; cursor: default; }
+
+.rules { margin-top: 18px; background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 14px 18px; }
+.rules p { margin: 0; }
+.rules .hint { color: var(--muted); font-size: 12px; margin-top: 4px; }
+code { background: var(--panel-2); padding: 1px 6px; border-radius: 6px; font-size: 12px; }
diff --git a/store/agents/jev-arena/viewer/studio.js b/store/agents/jev-arena/viewer/studio.js
new file mode 100644
index 000000000..3ba855f81
--- /dev/null
+++ b/store/agents/jev-arena/viewer/studio.js
@@ -0,0 +1,204 @@
+// Jev Arena studio — the pane that renders Jev's live decisions. Connects via SSE, draws the grid
+// onto a canvas with a soft, attractive look, and animates the "Jev brain" probability readout.
+
+const $ = (id) => document.getElementById(id);
+const canvas = $('board');
+const ctx = canvas.getContext('2d');
+
+let state = {
+ type: 'frame', moves: 0, reachedGoal: false, coinsCollected: 0,
+ running: false, hero: { x: 1, y: 1 }, coins: [], goal: { x: 10, y: 10 },
+ walls: [], size: 12, decisionLog: [], speed: 300, model: 'jev-latest', client: 'mock',
+};
+let lastAction = null;
+
+// --- canvas sizing ---
+function sizeCanvas() {
+ const rect = canvas.parentElement.getBoundingClientRect();
+ const side = Math.min(rect.width - 4, 640);
+ canvas.width = side;
+ canvas.height = side;
+ draw();
+}
+window.addEventListener('resize', sizeCanvas);
+
+// --- drawing ---
+const COLORS = {
+ bg: '#0f1422', cell: '#161e31', wall: '#2c3a5e', coin: '#ffce6b',
+ goal: '#5ee0c0', hero: '#7aa2ff', heroStroke: '#ffffff', trail: 'rgba(122,162,255,0.18)',
+};
+function draw() {
+ const W = canvas.width, size = state.size || 12;
+ const cell = W / size;
+ ctx.clearRect(0, 0, W, W);
+ ctx.fillStyle = COLORS.bg;
+ ctx.fillRect(0, 0, W, W);
+
+ // grid
+ ctx.strokeStyle = 'rgba(38,49,78,0.5)';
+ ctx.lineWidth = 1;
+ for (let i = 0; i <= size; i++) {
+ ctx.beginPath(); ctx.moveTo(i * cell, 0); ctx.lineTo(i * cell, W); ctx.stroke();
+ ctx.beginPath(); ctx.moveTo(0, i * cell); ctx.lineTo(W, i * cell); ctx.stroke();
+ }
+
+ // walls
+ for (const w of state.walls || []) {
+ ctx.fillStyle = COLORS.wall;
+ ctx.fillRect(w.x * cell + 1, w.y * cell + 1, cell - 2, cell - 2);
+ }
+ // coins
+ for (const c of state.coins || []) {
+ const cx = c.x * cell + cell / 2, cy = c.y * cell + cell / 2;
+ ctx.beginPath();
+ ctx.arc(cx, cy, cell * 0.28, 0, Math.PI * 2);
+ ctx.fillStyle = COLORS.coin;
+ ctx.shadowColor = COLORS.coin; ctx.shadowBlur = 14;
+ ctx.fill(); ctx.shadowBlur = 0;
+ ctx.fillStyle = 'rgba(0,0,0,0.25)';
+ ctx.beginPath(); ctx.arc(cx - cell*0.06, cy - cell*0.06, cell*0.10, 0, Math.PI*2); ctx.fill();
+ }
+ // goal
+ const g = state.goal;
+ if (g) {
+ const cx = g.x * cell + cell/2, cy = g.y * cell + cell/2;
+ ctx.save();
+ ctx.translate(cx, cy);
+ ctx.rotate((Date.now() / 900) % (Math.PI * 2));
+ ctx.fillStyle = COLORS.goal;
+ ctx.shadowColor = COLORS.goal; ctx.shadowBlur = 18;
+ drawStar(ctx, 0, 0, 5, cell*0.34, cell*0.15);
+ ctx.shadowBlur = 0;
+ ctx.restore();
+ }
+ // hero with a soft glow + trail
+ if (state.hero) {
+ const hx = state.hero.x * cell + cell/2, hy = state.hero.y * cell + cell/2;
+ ctx.beginPath(); ctx.arc(hx, hy, cell*0.30, 0, Math.PI*2);
+ ctx.fillStyle = 'rgba(122,162,255,0.15)'; ctx.fill();
+ ctx.beginPath(); ctx.arc(hx, hy, cell*0.34, 0, Math.PI*2);
+ ctx.strokeStyle = 'rgba(122,162,255,0.4)'; ctx.lineWidth = 2; ctx.stroke();
+ ctx.beginPath(); ctx.arc(hx, hy, cell*0.24, 0, Math.PI*2);
+ ctx.fillStyle = COLORS.hero;
+ ctx.shadowColor = COLORS.hero; ctx.shadowBlur = 18;
+ ctx.fill(); ctx.shadowBlur = 0;
+ ctx.strokeStyle = COLORS.heroStroke; ctx.lineWidth = 1.5; ctx.stroke();
+ // eyes → direction of last action
+ const dir = { up: [0,-1], down: [0,1], left: [-1,0], right: [1,0] }[lastAction] || [0,0];
+ const ex = hx + dir[0]*cell*0.09, ey = hy + dir[1]*cell*0.09;
+ ctx.fillStyle = '#0a0f1e';
+ ctx.beginPath(); ctx.arc(ex - 5, ey, 2.6, 0, Math.PI*2); ctx.fill();
+ ctx.beginPath(); ctx.arc(ex + 5, ey, 2.6, 0, Math.PI*2); ctx.fill();
+ }
+}
+function drawStar(ctx, cx, cy, points, outer, inner) {
+ ctx.beginPath();
+ for (let i = 0; i < points * 2; i++) {
+ const r = i % 2 === 0 ? outer : inner;
+ const a = (i * Math.PI) / points - Math.PI / 2;
+ const x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r;
+ i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
+ }
+ ctx.closePath(); ctx.fill();
+}
+
+// --- brain UI ---
+const ACTION_NAMES = { up: '⬆ up', down: '⬇ down', left: '⬅ left', right: '➡ right', wait: '⋯ wait' };
+function renderActions(frame) {
+ const wrap = $('actions');
+ const log = (frame.decisionLog || []).slice(-1)[0];
+ const probs = log?.probabilities || {};
+ const entries = Object.entries(probs).length ? Object.entries(probs).sort((a, b) => b[1] - a[1]) : [];
+ const chosen = log?.move;
+ wrap.innerHTML = '';
+ if (!entries.length) {
+ const div = document.createElement('div');
+ div.className = 'action';
+ div.innerHTML = '<span class="name">waiting…</span>';
+ wrap.appendChild(div);
+ return;
+ }
+ for (const [name, p] of entries) {
+ const el = document.createElement('div');
+ el.className = 'action' + (name === chosen ? ' chosen' : '');
+ const pct = (p * 100).toFixed(1);
+ el.innerHTML = `<span class="name">${ACTION_NAMES[name] || name}</span>
+ <span class="bar"><i style="width:${Math.max(1, p * 100)}%"></i></span>
+ <span class="pct">${pct}%</span>`;
+ wrap.appendChild(el);
+ }
+ // confidence + live
+ const cfEl = $('confidence');
+ if (log) {
+ const cf = Math.round((log.confidence ?? 0) * 100);
+ cfEl.textContent = cf + '%';
+ $('rail-fill').style.width = (log.confidence ?? 0) * 100 + '%';
+ }
+}
+function renderLog(frame) {
+ const ol = $('log');
+ ol.innerHTML = '';
+ const log = (frame.decisionLog || []).slice(-8).reverse();
+ for (const d of log) {
+ const li = document.createElement('li');
+ const cf = Math.round((d.confidence ?? 0) * 100);
+ li.innerHTML = `<span class="n">#${d.at}</span><span class="mv">${ACTION_NAMES[d.move] || d.move}</span><span class="cf">conf ${cf}%</span>`;
+ ol.appendChild(li);
+ }
+}
+
+// --- metering ---
+function renderMeta(frame) {
+ $('moves').textContent = frame.moves ?? 0;
+ $('coins').textContent = frame.coinsCollected ?? 0;
+ $('model').textContent = frame.model || 'jev-latest';
+ $('client').textContent = frame.client || 'mock';
+ $('title').textContent = frame.title || 'Jev Arena';
+ if (frame.description) $('description').textContent = frame.description;
+ if (frame.rules) $('rules').textContent = frame.rules;
+ const live = $('live');
+ if (frame.reachedGoal) { live.textContent = 'done'; live.className = 'live done'; }
+ else if (frame.running) { live.textContent = 'thinking…'; live.className = 'live thinking'; }
+ else { live.textContent = 'paused'; live.className = 'live idle'; }
+ $('overlay').hidden = !frame.reachedGoal;
+ if (frame.reachedGoal) {
+ $('overlay-title').textContent = 'Goal reached ⭐';
+ $('overlay-msg').textContent = `Jev crossed the arena in ${frame.moves} decisions and ${frame.coinsCollected} coins.`;
+ }
+ for (const b of ['start', 'pause', 'step', 'reset', 'reset-big']) {
+ $(b).disabled = !!frame.reachedGoal && b !== 'reset' && b !== 'reset-big';
+ }
+}
+
+// --- SSE ---
+function connect() {
+ const es = new EventSource('/events');
+ es.addEventListener('state', (e) => {
+ const frame = JSON.parse(e.data);
+ state = { ...state, ...frame };
+ state.title = frame.title;
+ renderMeta(frame);
+ renderActions(frame);
+ renderLog(frame);
+ lastAction = (frame.decisionLog || []).slice(-1)[0]?.move || null;
+ draw();
+ });
+ es.onerror = () => { /* auto-reconnect */ };
+}
+function control(cmd) {
+ fetch('/control', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ cmd }),
+ });
+}
+$('start').onclick = () => control('start');
+$('pause').onclick = () => control('pause');
+$('step').onclick = () => control('step');
+$('reset').onclick = () => control('reset');
+$('reset-big').onclick = () => control('reset');
+
+sizeCanvas();
+connect();
+// gentle perpetual animation for the rotating star + hero pulse
+function loop() { draw(); requestAnimationFrame(loop); }
+requestAnimationFrame(loop);
diff --git a/store/agents/jev-arena/viewer/viewer.mjs b/store/agents/jev-arena/viewer/viewer.mjs
new file mode 100644
index 000000000..35b9556b0
--- /dev/null
+++ b/store/agents/jev-arena/viewer/viewer.mjs
@@ -0,0 +1,323 @@
+// Jev Arena viewer — a loopback server that renders a live grid game where Jev (TypeSafe's System One
+// model) is the brain. The agent designs the world (nodes, goals, walls, rules) as JSON; this server
+// runs the game loop and calls Jev at a tunable cadence to pick the next move. Every decision's
+// probability distribution and confidence streams to the pane over SSE, so the user *watches Jev
+// think* — the decisions are the experience.
+//
+// Harness runs this for the life of the agent's pane with:
+// HARNESS_VIEWER_PORT loopback port
+// HARNESS_WORKSPACE the workspace folder (the agent's cwd)
+// HARNESS_DSH_DIR this install dir
+//
+// The workspace holds arena.json (the world + rules). The viewer watches it; the agent edits it and
+// the game adapts live. No external runtime dependencies.
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, existsSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 3000)
+
+const DEFAULT_WORLD = {
+ title: 'Jev Arena',
+ description: 'A tiny grid world where Jev decides each move.',
+ size: 12,
+ hero: { x: 1, y: 1, emoji: '🤖', label: 'Jev' },
+ goal: { x: 10, y: 10, emoji: '⭐', label: 'goal' },
+ walls: [],
+ coins: [{ x: 6, y: 6, emoji: '🪙', value: 1 }],
+ rules: 'Reach the goal in as few steps as possible. Move one cell at a time (up/down/left/right).',
+ speed: 300, // ms per decision
+ movesPerStep: 1,
+}
+
+const ACTIONS = ['up', 'down', 'left', 'right', 'wait']
+
+function stateBlock(world, hero) {
+ // Build the state text Jev reads: the world grid, the hero, remaining coins, known obstacles.
+ const { size, walls, coins, goal, rules } = world
+ const grid = Array.from({ length: size }, () => Array(size).fill('.'))
+ const isWall = (x, y) => walls.some((w) => w.x === x && w.y === y)
+ for (const w of walls) if (inBounds(w, size)) grid[w.y] && (grid[w.y][w.x] = '#')
+ const remaining = coins.filter((c) => inBounds(c, size) && !(c.x === hero.x && c.y === hero.y))
+ for (const c of remaining) grid[c.y][c.x] = '$'
+ if (inBounds(goal, size)) grid[goal.y][goal.x] = 'G'
+ grid[hero.y] = grid[hero.y] || []
+ grid[hero.y][hero.x] = '@'
+ const rows = grid.map((r) => r.join('')).join('\n')
+ const distToGoal = Math.abs(hero.x - goal.x) + Math.abs(hero.y - goal.y)
+ return `You are the @ on this grid. # is a wall, $ is a coin, G is the goal.\n${rows}\n\nPosition: (${hero.x},${hero.y}). Goal: (${goal.x},${goal.y}). Manhattan distance to goal: ${distToGoal}. Coins remaining to collect: ${remaining.length}. Obstacles are impassable; collect coins and reach G.`
+}
+
+function inBounds(pos, size) {
+ return pos && pos.x >= 0 && pos.y >= 0 && pos.x < size && pos.y < size
+}
+
+function moveLegal(world, pos, action) {
+ const { size, walls } = world
+ let [x, y] = [pos.x, pos.y]
+ if (action === 'up') y -= 1
+ else if (action === 'down') y += 1
+ else if (action === 'left') x -= 1
+ else if (action === 'right') x += 1
+ else return { x, y, legal: true } // wait
+ const blocked = x < 0 || y < 0 || x >= size || y >= size || walls.some((w) => w.x === x && w.y === y)
+ return { x, y, legal: !blocked }
+}
+
+async function decide(world, hero, salt) {
+ const questions = {
+ move: {
+ type: 'choice',
+ instructions: 'Choose the best next move to reach the goal (collect coins first), without walking into walls.',
+ options: ACTIONS,
+ },
+ confidence_full: {
+ type: 'noul',
+ instructions: 'Is the selected move clearly the best choice, with high certainty?',
+ },
+ }
+ // Pass obstacles/awareness to state. The mock and live model both read the state.
+ try {
+ const res = await evaluate({
+ state: stateBlock(world, hero),
+ questions,
+ salt,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const moveAns = res.answers.move || {}
+ const probs = moveAns.probabilities || {}
+ const best = moveAns.choice || pickBestByProbs(probs)
+ return {
+ action: best,
+ probabilities: probs,
+ confidence: moveAns.confidence ?? Math.max(...Object.values(probs), 0),
+ client: res.client,
+ model: res.model,
+ }
+ } catch (err) {
+ return { action: 'wait', probabilities: {}, confidence: 0, error: clean(err.message), client: 'error' }
+ }
+}
+
+function pickBestByProbs(probs) {
+ let best = 'wait', bestP = -1
+ for (const [a, p] of Object.entries(probs)) if (p > bestP) { best = a; bestP = p }
+ return best
+}
+
+function verdict(world, state) {
+ const ready = state.error ? false : state.moves > 0
+ return {
+ spec: 1,
+ ready,
+ summary: state.error
+ ? 'Arena needs a fix'
+ : `${world.title} · Jev has made ${state.moves} decisions · reached goal ${state.reachedGoal ? 'yes' : 'not yet'}`,
+ findings: state.error ? [{ severity: 'error', kind: 'arena', message: state.error }] : [],
+ artifact: 'arena.json',
+ phases: [
+ { id: 'world', name: 'World', state: state.reachedGoal ? 'done' : 'active' },
+ { id: 'play', name: 'Play', state: state.reachedGoal ? 'done' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+}
+
+export async function startArenaViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let world = readWorld(join(workspace, 'arena.json'))
+ let hero = { ...world.hero }
+ let state = { moves: 0, reachedGoal: false, coinsCollected: 0, error: null, running: false }
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ const decisionLog = []
+ let salt = 1
+
+ function readWorld(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ return { ...DEFAULT_WORLD, ...raw }
+ } catch {
+ return DEFAULT_WORLD
+ }
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function tail() {
+ const gameOver = state.reachedGoal
+ state.running = !gameOver && !stopped
+ const summary = { title: world.title, description: world.description, hero, goal: world.goal, walls: world.walls, coins: world.coins, size: world.size, rules: world.rules, speed: world.speed }
+ broadcast({ type: 'frame', moves: state.moves, reachedGoal: state.reachedGoal, coinsCollected: state.coinsCollected, gameOver, running: state.running, hero, coins: world.coins, goal: world.goal, walls: world.walls, size: world.size, decisionLog: decisionLog.slice(-20), speed: world.speed, model: state.model, client: state.client })
+ // write verdict
+ const v = verdict(world, state)
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ void summary
+ }
+
+ async function step() {
+ if (stopped || state.reachedGoal) return
+ // Ask Jev for the next move.
+ const d = await decide(world, hero, salt++)
+ state.model = d.model
+ state.client = d.client
+ if (d.error) { state.error = d.error; tail(); return }
+ // Apply the move.
+ const mv = moveLegal(world, hero, d.action)
+ if (mv.legal) {
+ hero = { x: mv.x, y: mv.y }
+ // Collect coins.
+ const coinAt = world.coins.findIndex((c) => c.x === hero.x && c.y === hero.y)
+ if (coinAt >= 0) { world.coins.splice(coinAt, 1); state.coinsCollected++ }
+ // Reached goal?
+ if (hero.x === world.goal.x && hero.y === world.goal.y) state.reachedGoal = true
+ }
+ state.moves++
+ if (state.moves > 4 && !state.reachedGoal) {
+ // Safety: Jev shouldn't be stuck. Let the world know via the panel, but keep moving.
+ }
+ decisionLog.push({ move: d.action, probabilities: d.probabilities, confidence: d.confidence, at: state.moves, hero: { ...hero } })
+ if (decisionLog.length > 200) decisionLog.splice(0, decisionLog.length - 200)
+ tail()
+ }
+
+ let timer = null
+ function schedule() {
+ clearTimeout(timer)
+ timer = setTimeout(run, Math.max(60, Number(world.speed) || 300))
+ }
+ async function run() {
+ if (stopped) return
+ await step()
+ if (!state.reachedGoal) schedule()
+ // Never sit on the finished screen: show the result for a few seconds, then play again.
+ else { clearTimeout(timer); timer = setTimeout(() => { if (!stopped && state.reachedGoal) { const was = state.running; reset(); state.running = was; tail(); schedule() } }, 4000) }
+ }
+
+ function start() {
+ if (state.reachedGoal) return
+ schedule()
+ }
+ function pause() {
+ clearTimeout(timer)
+ }
+ function reset() {
+ state = { moves: 0, reachedGoal: false, coinsCollected: 0, error: null, running: false }
+ hero = { ...world.hero }
+ // restore coins from world (we mutate world.coins in place; keep a pristine copy)
+ world = readWorld(join(workspace, 'arena.json'))
+ // re-read resets coins to the file. good.
+ hero = { ...world.hero }
+ decisionLog.length = 0
+ salt = 1
+ tail()
+ if (state.running) schedule()
+ }
+
+ // Watch the workspace for world edits.
+ const watcher = watch(workspace, { recursive: true }, (_, name) => {
+ if (!name) return
+ name = String(name).split('/').join('/')
+ if (name === 'arena.json') {
+ const got = readWorld(join(workspace, 'arena.json'))
+ const changed = JSON.stringify(got.size) !== JSON.stringify(world.size) ||
+ JSON.stringify(got.goal) !== JSON.stringify(world.goal) ||
+ JSON.stringify(got.walls) !== JSON.stringify(world.walls) ||
+ JSON.stringify(got.hero) !== JSON.stringify(world.hero)
+ world = got
+ // Keep existing coins only if the file didn't redefine them; re-read does.
+ if (changed) { /* keep world as read; reset hero if it moved? leave */ }
+ tail()
+ schedule()
+ }
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') {
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
+ return res.end(readFileSync(join(HERE, 'index.html')))
+ }
+ if (req.method === 'GET' && url.pathname === '/studio.js') {
+ res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' })
+ return res.end(readFileSync(join(HERE, 'studio.js')))
+ }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') {
+ res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' })
+ return res.end(readFileSync(join(HERE, 'studio.css')))
+ }
+ if (req.method === 'GET' && url.pathname === '/state') {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ world, state, decisionLog: decisionLog.slice(-20) }))
+ }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ res.write(`event: state\ndata: ${JSON.stringify({ type: 'frame', moves: state.moves, reachedGoal: state.reachedGoal, running: state.running, hero, coins: world.coins, goal: world.goal, walls: world.walls, size: world.size, decisionLog: decisionLog.slice(-20), speed: world.speed, model: state.model, client: state.client })}\n\n`)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'step') await step()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404)
+ res.end('Not found')
+ })
+
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(port, '127.0.0.1', resolve)
+ })
+
+ tail()
+ schedule()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() {
+ stopped = true
+ clearTimeout(timer)
+ watcher.close()
+ for (const c of clients) c.end()
+ server.closeAllConnections()
+ await new Promise((r) => server.close(r))
+ },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startArenaViewer({ workspace, port })
+ console.log(`Jev Arena listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-blocks/.gitignore b/store/agents/jev-blocks/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-blocks/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-blocks/AGENTS.md b/store/agents/jev-blocks/AGENTS.md
new file mode 100644
index 000000000..4f8159c0b
--- /dev/null
+++ b/store/agents/jev-blocks/AGENTS.md
@@ -0,0 +1,86 @@
+# Jev Blocks in OpenHarness
+
+On the left is a live falling-blocks puzzle. **Jev, TypeSafe's System One model, plays it.** For each
+new piece the viewer lists every legal placement and asks Jev one call with three questions:
+`place` (a choice over the placements, with a probability for each), `danger` (how close the stack is
+to the top) and `go_for_four` (is it worth keeping a column open for an I piece). The pane draws the
+probabilities on the board.
+
+On the right is you. **Your job is to design the challenge.** You edit `blocks.json`. It is the ONLY
+file you edit. The viewer watches it and starts a new game on every valid edit.
+
+The game is made up. It is a demo of a fast decision loop, not a benchmark and not a real contest.
+
+## The challenge file
+
+```jsonc
+{
+ "title": "Jev Blocks",
+ "description": "One line about this challenge.",
+ "seed": 7, // same seed, same piece order
+ "gravity": 2, // rows per second at level 1. 0.2 to 40
+ "speedup": 0.5, // extra gravity per level, as a share of the start. 0 to 2
+ "decisionMs": 110, // what one decision costs. 30 to 1000
+ "moveMs": 35, // what one rotate or shift costs. 5 to 500
+ "garbageRows": 0, // garbage rows at the start, one gap each. 0 to 12
+ "weights": { "I": 1, "O": 1, "T": 1, "S": 1, "Z": 1, "J": 1, "L": 1 }, // piece mix, whole numbers 0 to 9
+ "board": [], // optional start board, top row first, 10 characters per row, '.' or '#'
+ "style": "How Jev should play, in plain words."
+}
+```
+
+- **`gravity` and `speedup`** set how fast the piece falls: `gravity x (1 + speedup x (level - 1))`
+ rows per second. The level goes up every 10 lines.
+- **`decisionMs` and `moveMs`** are the cost of thinking and of moving. The piece keeps falling while
+ they pass. This is the honest limit. If the piece lands before it reaches the chosen column, it
+ locks where it is. With the defaults the break comes near 46 rows per second on a low stack, and
+ earlier on a high stack. A slower thinker (`decisionMs` 300 to 1000) breaks much sooner.
+- **`garbageRows`** and **`board`** set the start. A board is drawn as rows of `.` and `#`, top row
+ first, and sits on the floor. Example, one I piece away from four lines:
+
+ ```json
+ "board": ["#########.", "#########.", "#########.", "#########."]
+ ```
+- **`weights`** is the piece mix. Each piece gets that many copies in every shuffled bag.
+ `{ "S": 1, "Z": 1 }` is an S and Z only nightmare. Missing pieces count as 0.
+- **`style`** is the instruction Jev reads at the top of every call. Say how to play: keep it flat,
+ dig out the garbage first, go for four lines, play safe and clear single lines.
+
+## What to do
+
+1. Ask what kind of challenge the person wants, or pick one: a speed test, a dig-out, a cruel piece
+ mix, a hand-drawn board.
+2. Edit `blocks.json`. Keep it valid JSON. Run `node "$JEV_DSH/toolchain/check.mjs"` in the
+ workspace. Fix every `error` line.
+3. Read `.harness/verdict.json` after the game has run for a while. It has the lines, the level,
+ the gravity, how many of the last 50 pieces landed short of their target, and the top-outs.
+4. **Report where Jev starts to break.** Give the numbers: at what gravity placements start to
+ miss, how many lines a game lasts, and what you changed. If Jev never breaks, say so and make it
+ harder. If it breaks at once, say so and ease off. Both are findings, not bugs to hide.
+
+Change one thing at a time when you hunt for the breaking point. The same seed gives the same piece
+order, so two runs can be compared.
+
+## Rules
+
+- Edit only `blocks.json`. Do not edit `.harness/verdict.json`. The viewer writes it.
+- The pane on the left is already running. Never suggest opening a browser, changing a port, or
+ starting another server. The person already sees the pane.
+- A bad JSON edit does not stop the game. The viewer keeps the last good file and shows the error in
+ the pane. Fix the file.
+- The person can also change things in the pane (gravity, think time, garbage, junk blocks, the next
+ pieces). Those changes are cleared when you edit `blocks.json`.
+- Without `TYPESAFE_API_KEY` the viewer uses a deterministic offline reader and the pane says
+ `MOCK`. It reads the same state text and option descriptions as live Jev, and only picks up a few
+ words from `style` (such as "four"). Live Jev reads the whole line. Say which one produced the
+ numbers you report.
+- You may call Jev yourself through `toolchain/jev.mjs` (`evaluate`, with `jev.choice`, `jev.noul`,
+ `jev.score`) to try a question before you rely on it.
+- Keep `title`, `description` and `style` truthful. Never present this as a real game title, a real
+ tournament, or a measure of anything beyond this demo.
+
+## Definition of done
+
+- `blocks.json` is valid and passes `toolchain/check.mjs`.
+- The challenge has a clear idea behind it, and the numbers in the file match that idea.
+- You have told the person where Jev starts to break, with numbers from the verdict.
diff --git a/store/agents/jev-blocks/LICENSE b/store/agents/jev-blocks/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-blocks/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-blocks/README.md b/store/agents/jev-blocks/README.md
new file mode 100644
index 000000000..66a5e8502
--- /dev/null
+++ b/store/agents/jev-blocks/README.md
@@ -0,0 +1,88 @@
+# Jev Blocks
+
+**Jev, TypeSafe's System One model, plays a falling-blocks puzzle, live.** For every new piece the
+viewer lists every legal placement (each rotation in each column, 9 to 34 of them) and asks Jev
+**one call**. Jev answers three questions at once: which placement to take, with a probability for
+every option; how close the stack is to the top; and whether it is worth keeping a column open to
+clear four lines at once. The pane draws those probabilities on the board as ghosts, so you can see
+the whole decision, not just the move.
+
+This is a harness for OpenHarness. The agent on the right edits `blocks.json`. The viewer on the
+left runs the game and reacts to every edit.
+
+It is a demo. The game, the pieces and the scores are made up. Nothing here is a benchmark.
+
+## The honest dial is time
+
+The piece really falls, at `gravity` rows per second. Gravity rises with the level. A decision costs
+`decisionMs` (110 ms by default, about what a live Jev call takes). After that the piece still has
+to be moved, and each rotate or shift costs `moveMs` (35 ms). If the piece lands before it reaches
+the chosen column, it locks where it is.
+
+So at low gravity Jev plays clean for a long time. As gravity climbs, far placements stop fitting
+into the fall, pieces land short, holes appear and the stack tops out. There is no injected
+randomness. With the default costs the break comes near 46 rows per second on a low stack, and
+sooner when the stack is high. Raise `decisionMs` to see what a slower model would do.
+
+Measured with the offline stand-in, 300 pieces, 8 starting garbage rows, no speedup:
+
+| gravity | lines | missed placements | top-outs |
+|---|---|---|---|
+| 1 row/s | about 125 | 0 | 0 |
+| 40 rows/s | about 49 | about 125 | about 28 |
+
+## The pane
+
+- A 10 by 20 well with a next queue of three, score, level, lines, lines per minute and pieces.
+- **Jev's mind on the board**: every placement Jev weighed is a ghost, brighter when more likely.
+ The chosen one is outlined. The top three carry their probability.
+- A danger meter (the `danger` score), a "going for four" light (the `go_for_four` yes/no) and a
+ time budget that shows the time a move needs next to the time the fall allows.
+- The top bar shows lines, lines per minute, decisions per second, cost so far, pieces and best.
+
+You can play with it:
+
+- Drag **Gravity** to pin the falling speed. Drag **Think time** to make each decision cost more.
+- **Drop garbage** pushes a garbage row up from the floor.
+- Click a **column** to drop a junk block there. Click a **next piece** to change it.
+- **Mind** shows or hides the ghosts. **Slow-mo** runs the clock at quarter speed.
+- **Pause**, **Step** (one decision at a time) and **Reset**.
+
+Changes made in the pane last until `blocks.json` is edited.
+
+## Anatomy
+
+```
+jev-blocks/
+ harness.json manifest (engine: claude)
+ AGENTS.md what the chat agent does
+ skills/blocks/SKILL.md how to design a challenge and read the result
+ template/blocks.json the starter challenge
+ toolchain/
+ jev.mjs Jev client: real TypeSafe API, or a deterministic mock without a key
+ check.mjs validates blocks.json
+ viewer.sh setup.sh doctor.sh init-workspace.sh
+ viewer/
+ viewer.mjs the game loop and the loopback server
+ game.mjs rules, placements, the state text, the offline reader
+ kit.mjs loopback server, config watcher, verdict writer
+ studio.js studio.css index.html base.css jev-hud.js
+ test/viewer.test.mjs
+```
+
+## Jev, honestly
+
+With `TYPESAFE_API_KEY` set, the viewer calls `POST /v1/systemone` and charges the real latency
+against the fall. Without a key it uses a deterministic offline reader. That reader gets only the
+state text and the option descriptions, the same words live Jev gets, and scores each placement with
+a well-known stack heuristic. It is a stand-in for the plumbing, not for Jev's judgement, and the
+pane badges it `MOCK`. The cost shown is what live Jev would charge for the same tokens.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness only calls the public API. It
+ contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed. This harness is MIT too (see `LICENSE`).
+- The falling-blocks rules here are a plain, generic version written for this demo. The harness is
+ not linked to any game publisher.
+- Built by Autonomous for the OpenHarness store.
diff --git a/store/agents/jev-blocks/THIRD_PARTY_NOTICES.md b/store/agents/jev-blocks/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-blocks/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-blocks/harness.json b/store/agents/jev-blocks/harness.json
new file mode 100644
index 000000000..d40a6c328
--- /dev/null
+++ b/store/agents/jev-blocks/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-blocks",
+ "name": "Jev Blocks",
+ "category": "Games",
+ "author": "Autonomous",
+ "description": "A falling-blocks puzzle played live by Jev, TypeSafe's System One model. One call per piece picks a placement from every legal one, with a probability for each, drawn on the board. The piece keeps falling while Jev thinks. Raise gravity and find where it breaks. A synthetic demo.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "blocks.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-blocks/skills/blocks/SKILL.md b/store/agents/jev-blocks/skills/blocks/SKILL.md
new file mode 100644
index 000000000..b2b819eb3
--- /dev/null
+++ b/store/agents/jev-blocks/skills/blocks/SKILL.md
@@ -0,0 +1,89 @@
+---
+name: jev-blocks
+description: Design a falling-blocks challenge for Jev in blocks.json (gravity, speedup, garbage, a custom board, the piece mix, the style line), then read the verdict and report where Jev starts to break.
+---
+
+# Craft: a Jev Blocks challenge
+
+Jev places every piece of a falling-blocks puzzle with one call. The craft is to set up a game that
+shows a real decision loop under a real limit, then to find the point where the limit wins.
+
+## The decision loop
+
+For each new piece the viewer builds one state text:
+
+- the `style` line,
+- the well as 20 ASCII rows (`#` filled, `.` empty),
+- column heights, holes, bumpiness and the deepest well,
+- the current piece and the next three,
+- level, lines, gravity, and what a decision and a move cost,
+- a table of every legal placement. The id is `r<rotation>c<leftmost column>`, for example `r1c4`.
+
+Then it asks three questions in the same call:
+
+| id | type | what it asks |
+|---|---|---|
+| `place` | choice | one option per placement. Each option's description is a short fact line: lines cleared, holes, column heights, max height, bumpiness, wells, moves needed |
+| `danger` | score, 4 levels | how close the stack is to topping out |
+| `go_for_four` | noul | is it worth keeping a column open for an I piece |
+
+Questions cannot see each other. Shared facts live in the state text.
+
+## The honest limit
+
+Time. The piece falls at `gravity x (1 + speedup x (level - 1))` rows per second. A decision costs
+`decisionMs`. Each rotate or shift costs `moveMs`. The piece falls the whole time. When it lands, it
+locks, even if it has not reached the chosen column. The pane marks that as `TOO SLOW` and counts it
+under `MISSED`.
+
+A rough rule: a placement needs `decisionMs + (moves + 1) x moveMs`. The fall gives
+`free rows / gravity` seconds. With 110 ms and 35 ms, a wall placement (about 6 moves) needs about
+355 ms. On an empty well that fits up to about 46 rows per second. On a stack 8 rows high it only
+fits up to about 28. So height and gravity work together, and garbage makes speed bite sooner.
+
+## Knobs and what they do
+
+```jsonc
+{
+ "gravity": 2, // 0.2 to 40. The starting speed.
+ "speedup": 0.5, // 0 to 2. 0 keeps gravity fixed, which is best for a clean comparison.
+ "decisionMs": 110, // 30 to 1000. Raise it to play a slower model.
+ "moveMs": 35, // 5 to 500.
+ "garbageRows": 0, // 0 to 12.
+ "weights": { "I": 1, "O": 1, "T": 1, "S": 1, "Z": 1, "J": 1, "L": 1 },
+ "board": [], // up to 20 rows of 10 characters, '.' or '#', top row first
+ "style": "Keep the stack low and flat. Go for four when it is safe."
+}
+```
+
+Ideas that make a good challenge:
+
+- **Speed test.** `speedup: 0`, then try gravity 10, 25, 40. Add `garbageRows: 8` so 40 really bites.
+- **Slow thinker.** Keep gravity at 12 and set `decisionMs` to 300, then 700. Watch the misses start.
+- **Dig-out.** `garbageRows: 10`, low gravity, a style line that says dig first.
+- **Cruel mix.** `"weights": { "S": 1, "Z": 1 }`, or drop the I piece and see what `go_for_four` says.
+- **Set piece.** Draw a board that is one I piece from four lines and see if Jev takes it.
+
+## How to find the breaking point
+
+1. Fix the seed and set `speedup` to 0.
+2. Change one knob, save, let the game run for a minute or so.
+3. Read `.harness/verdict.json`. Look at the summary line and the `timing` finding
+ (`N of the last 50 pieces landed short of their target at G rows/s`) and the `topout` finding.
+4. Move the knob and repeat. Report the last setting that played clean and the first that did not.
+
+## Checking
+
+```bash
+node "$JEV_DSH/toolchain/check.mjs"
+```
+
+It prints `ok` or one `error` line per problem: a number out of range, weights that are all zero, a
+board row that is not 10 characters of `.` and `#`.
+
+## Honesty
+
+- The game is synthetic. The score means nothing outside this pane.
+- Without an API key the pane says `MOCK`. The offline reader is a fixed heuristic. It shows that the
+ plumbing works. It does not show how well live Jev plays. Say which one you measured.
+- Never edit `.harness/verdict.json`, and never tell the person to open a browser or start a server.
diff --git a/store/agents/jev-blocks/store.json b/store/agents/jev-blocks/store.json
new file mode 100644
index 000000000..f61f735c4
--- /dev/null
+++ b/store/agents/jev-blocks/store.json
@@ -0,0 +1,17 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev plays a falling-blocks puzzle, its whole mind drawn on the board, live",
+ "examples": [
+ {
+ "prompt": "Design a hard challenge for Jev Blocks: start with 6 garbage rows, use an S and Z heavy piece mix, set gravity to 12 with a speedup of 1, and write a style line that tells Jev to dig out first. Then watch the pane and tell me at what gravity Jev starts to miss placements.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-blocks/mind-on-the-board.jpg",
+ "caption": "Find the breaking point: a fast decision model placing every piece while it really falls"
+ },
+ {
+ "prompt": "Draw a custom starting board in blocks.json that is one I piece away from clearing four lines, keep gravity low, and tell Jev to go for four. Report whether it takes the four-line clear.",
+ "caption": "A hand-drawn board to test whether Jev sees the four-line clear"
+ }
+ ]
+}
diff --git a/store/agents/jev-blocks/template/blocks.json b/store/agents/jev-blocks/template/blocks.json
new file mode 100644
index 000000000..c5b5c6e98
--- /dev/null
+++ b/store/agents/jev-blocks/template/blocks.json
@@ -0,0 +1,13 @@
+{
+ "title": "Jev Blocks",
+ "description": "Jev plays a falling-blocks puzzle. One call per piece picks the placement. The game is synthetic.",
+ "seed": 7,
+ "gravity": 2,
+ "speedup": 0.5,
+ "decisionMs": 110,
+ "moveMs": 35,
+ "garbageRows": 0,
+ "weights": { "I": 1, "O": 1, "T": 1, "S": 1, "Z": 1, "J": 1, "L": 1 },
+ "board": [],
+ "style": "Keep the stack low, flat and free of holes. Leave the right column open and go for four lines at once when it is safe. When the stack gets high, stop waiting and clear lines."
+}
diff --git a/store/agents/jev-blocks/test/viewer.test.mjs b/store/agents/jev-blocks/test/viewer.test.mjs
new file mode 100644
index 000000000..be905d2e8
--- /dev/null
+++ b/store/agents/jev-blocks/test/viewer.test.mjs
@@ -0,0 +1,307 @@
+// Viewer tests for Jev Blocks. Each test starts the real viewer on an ephemeral port against a temp
+// workspace and drives time with the `tick` control (one Jev decision per tick), never with sleeps.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync, readdirSync, statSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { connect } from 'node:net'
+import { spawnSync } from 'node:child_process'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const ROOT = join(HERE, '..')
+const { startBlocksViewer } = await import(join(ROOT, 'viewer/viewer.mjs'))
+const game = await import(join(ROOT, 'viewer/game.mjs'))
+const { canon } = await import(join(ROOT, 'toolchain/jev.mjs'))
+
+const CFG = { title: 'Test Well', seed: 7, gravity: 2, speedup: 0, decisionMs: 110, moveMs: 35, garbageRows: 0, style: 'Keep the stack low and flat. Go for four when it is safe.' }
+
+async function fresh(overrides = {}, raw = null) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-blocks-test-'))
+ writeFileSync(join(ws, 'blocks.json'), raw ?? JSON.stringify({ ...CFG, ...overrides }))
+ const viewer = await startBlocksViewer({ workspace: ws, port: 0 })
+ const ctl = async (body) => {
+ const res = await fetch(`${viewer.url}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
+ return { status: res.status, json: await res.json() }
+ }
+ const state = async () => (await fetch(`${viewer.url}/state`)).json()
+ await ctl({ cmd: 'pause' }) // tests own the clock
+ return { ws, viewer, ctl, state }
+}
+
+const until = async (fn, ms = 4000) => { const end = Date.now() + ms; for (;;) { const v = await fn(); if (v) return v; if (Date.now() > end) return null; await new Promise((r) => setTimeout(r, 40)) } }
+
+test('the loop advances and Jev decides every piece', async () => {
+ const { viewer, ctl, state } = await fresh()
+ try {
+ await ctl({ cmd: 'reset' })
+ const before = await state()
+ await ctl({ cmd: 'tick', n: 30 })
+ const s = await state()
+ assert.ok(s.session.decisions >= before.session.decisions + 30, 'thirty decisions were applied')
+ assert.ok(s.session.pieces >= 29, `pieces locked (${s.session.pieces})`)
+ assert.equal(s.client, 'mock')
+ // Jev's mind is published: one probability per legal placement, the chosen one on top
+ assert.ok(s.mind && s.mind.cands.length >= 9 && s.mind.cands.length <= 34, `9..34 placements (${s.mind?.cands.length})`)
+ assert.match(s.mind.chosen, /^r\d+c\d+$/)
+ assert.equal(s.mind.cands[0].id, s.mind.chosen)
+ const sum = s.mind.cands.reduce((a, c) => a + c.p, 0)
+ assert.ok(Math.abs(sum - 1) < 0.01, `probabilities sum to 1 (${sum})`)
+ assert.ok(s.mind.cands[0].p >= 0.45 && s.mind.cands[0].p <= 0.86, `top choice is confident but not one-hot (${s.mind.cands[0].p})`)
+ assert.ok(s.danger && s.danger.score >= 0 && s.danger.score <= 3)
+ assert.ok(s.four >= 0 && s.four <= 1)
+ assert.equal(s.game.board.length, 200)
+ assert.equal(s.game.queue.length, 3)
+ // one call carries three parallel questions
+ const jev = await (await fetch(`${viewer.url}/jev`)).json()
+ assert.deepEqual(jev.last.questions.map((q) => q.id), ['place', 'danger', 'go_for_four'])
+ assert.ok(jev.costUsd > 0)
+ } finally { await viewer.close() }
+})
+
+test('a non-default config really shows up in /state', async () => {
+ const { viewer, state } = await fresh({ title: 'Heavy Rain', gravity: 17.5, speedup: 1.5, decisionMs: 240, moveMs: 60, garbageRows: 5, weights: { S: 2, Z: 1 } })
+ try {
+ const s = await state()
+ assert.equal(s.title, 'Heavy Rain')
+ assert.equal(s.cfg.gravity, 17.5)
+ assert.equal(s.game.gravity, 17.5)
+ assert.equal(s.cfg.speedup, 1.5)
+ assert.equal(s.cfg.decisionMs, 240)
+ assert.equal(s.cfg.moveMs, 60)
+ assert.equal(s.cfg.garbageRows, 5)
+ assert.deepEqual(s.cfg.weights, { I: 0, O: 0, T: 0, S: 2, Z: 1, J: 0, L: 0 })
+ assert.ok(s.game.queue.every((t) => t === 'S' || t === 'Z'), 'only S and Z come out of the bag')
+ const rows = s.game.board.match(/.{10}/g)
+ assert.equal(rows.filter((r) => /[1-9]/.test(r)).length, 5, 'five garbage rows')
+ assert.ok(rows.slice(-5).every((r) => (r.match(/0/g) || []).length === 1), 'one gap per garbage row')
+ } finally { await viewer.close() }
+})
+
+test('a custom starting board is drawn from ASCII rows, and Jev takes the four', async () => {
+ const board = ['#########.', '#########.', '#########.', '#########.']
+ const { viewer, ctl, state } = await fresh({ board, weights: { I: 1 } })
+ try {
+ const s0 = await state()
+ assert.equal(s0.game.board.match(/.{10}/g).slice(-4).join('|'), Array(4).fill('8888888880').join('|'))
+ await ctl({ cmd: 'tick', n: 2 })
+ const s = await state()
+ assert.equal(s.game.lines, 4, 'the I piece went down the open column')
+ assert.equal(s.game.fours, 1)
+ } finally { await viewer.close() }
+})
+
+test('the verdict file is written with spec, summary, findings and phases', async () => {
+ const { ws, viewer, ctl } = await fresh()
+ try {
+ await ctl({ cmd: 'tick', n: 12 })
+ const file = join(ws, '.harness/verdict.json')
+ assert.ok(existsSync(file))
+ const v = JSON.parse(readFileSync(file, 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.equal(v.ready, true)
+ assert.ok(typeof v.summary === 'string' && v.summary.includes('Test Well'))
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases) && v.phases.length === 3)
+ assert.equal(v.artifact, 'blocks.json')
+ assert.ok(v.findings.some((f) => f.kind === 'timing'), 'reports how many pieces landed short')
+ } finally { await viewer.close() }
+})
+
+test('every control command answers 200 and does what it says', async () => {
+ const { viewer, ctl, state } = await fresh({ garbageRows: 2 })
+ try {
+ for (const body of [{ cmd: 'pause' }, { cmd: 'start' }, { cmd: 'pause' }, { cmd: 'tick' }, { cmd: 'reset' }, { cmd: 'set', gravity: 9 }, { cmd: 'set', slow: true }, { cmd: 'set', slow: false }, { cmd: 'garbage' }, { cmd: 'junk', col: 3 }, { cmd: 'cycleNext', index: 0 }, { cmd: 'nonsense' }]) {
+ const r = await ctl(body)
+ assert.equal(r.status, 200, JSON.stringify(body))
+ assert.equal(r.json.ok, true)
+ }
+ await ctl({ cmd: 'reset' })
+ const s0 = await state()
+ const rows0 = s0.game.board.match(/.{10}/g)
+
+ // (1) gravity slider: pins the real falling speed, at once
+ await ctl({ cmd: 'set', gravity: 33 })
+ let s = await state()
+ assert.equal(s.game.gravity, 33); assert.equal(s.cfg.pinned, true)
+ await ctl({ cmd: 'set', gravity: null })
+ s = await state()
+ assert.equal(s.game.gravity, 2); assert.equal(s.cfg.pinned, false)
+ await ctl({ cmd: 'set', decisionMs: 400 })
+ assert.equal((await state()).cfg.decisionMs, 400)
+
+ // (2) drop garbage: the stack rises by one row with one gap
+ await ctl({ cmd: 'garbage' })
+ s = await state()
+ const rows1 = s.game.board.match(/.{10}/g)
+ assert.equal(rows1.filter((r) => /[1-9]/.test(r)).length, rows0.filter((r) => /[1-9]/.test(r)).length + 1)
+ assert.equal((rows1[19].match(/0/g) || []).length, 1)
+
+ // (3) click a column: one junk block lands on top of that column
+ const col = 4
+ const topBefore = rows1.findIndex((r) => r[col] !== '0')
+ await ctl({ cmd: 'junk', col })
+ s = await state()
+ const rows2 = s.game.board.match(/.{10}/g)
+ assert.equal(rows2[topBefore - 1][col], '9', 'a junk block sits on top of the column')
+ assert.ok(s.events.some((e) => e.kind === 'junk' && e.col === col))
+
+ // (4) click a next piece: it cycles to another piece
+ const was = s.game.queue[1]
+ await ctl({ cmd: 'cycleNext', index: 1 })
+ s = await state()
+ assert.notEqual(s.game.queue[1], was)
+
+ // a paused board change makes Jev think again, so the mind on the board is never stale
+ await ctl({ cmd: 'tick' })
+ const m1 = (await state()).mind.seq
+ await ctl({ cmd: 'junk', col: 0 })
+ assert.ok((await state()).mind.seq > m1)
+ } finally { await viewer.close() }
+})
+
+test('a bad JSON edit keeps the demo alive and reports the error; a good edit clears pane changes', async () => {
+ const { ws, viewer, ctl, state } = await fresh({ gravity: 3 })
+ try {
+ await ctl({ cmd: 'set', gravity: 25 })
+ await ctl({ cmd: 'tick', n: 5 })
+ writeFileSync(join(ws, 'blocks.json'), '{ "gravity": 3, oops')
+ const broken = await until(async () => { const s = await state(); return s.error ? s : null })
+ assert.ok(broken, 'the parse error is reported')
+ assert.match(broken.error, /blocks\.json/)
+ assert.equal(broken.cfg.gravity, 3, 'the last good config stays')
+ await ctl({ cmd: 'tick', n: 5 })
+ assert.ok((await state()).session.decisions >= 10, 'the game keeps going')
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.ok(v.findings.some((f) => f.severity === 'error'))
+
+ writeFileSync(join(ws, 'blocks.json'), JSON.stringify({ ...CFG, gravity: 6, title: 'Fixed' }))
+ const fixed = await until(async () => { const s = await state(); return !s.error && s.title === 'Fixed' ? s : null })
+ assert.ok(fixed, 'the fixed file is picked up')
+ assert.equal(fixed.game.gravity, 6, 'the pinned gravity from the pane was cleared')
+ assert.equal(fixed.cfg.pinned, false)
+ assert.equal(fixed.game.pieces, 0, 'a new game started')
+ } finally { await viewer.close() }
+})
+
+test('out-of-range values are clamped, never trusted', async () => {
+ const { viewer, state } = await fresh({ gravity: 9999, speedup: -4, decisionMs: 1, moveMs: 'fast', garbageRows: 99, weights: { I: 0, O: 0 }, board: ['too short'] })
+ try {
+ const s = await state()
+ assert.equal(s.cfg.gravity, 40); assert.equal(s.cfg.speedup, 0); assert.equal(s.cfg.decisionMs, 30); assert.equal(s.cfg.moveMs, 35); assert.equal(s.cfg.garbageRows, 12)
+ assert.ok(s.warnings.length >= 2, 'warns about the zero weights and the bad board')
+ } finally { await viewer.close() }
+})
+
+test('a non-loopback Host header gets 403', async () => {
+ const { viewer } = await fresh()
+ try {
+ const port = Number(new URL(viewer.url).port)
+ const reply = await new Promise((resolve, reject) => {
+ const sock = connect(port, '127.0.0.1', () => sock.write('GET /state HTTP/1.1\r\nHost: evil.example.com\r\nConnection: close\r\n\r\n'))
+ let buf = ''
+ sock.on('data', (d) => (buf += d)); sock.on('end', () => resolve(buf)); sock.on('error', reject)
+ })
+ assert.match(reply, /^HTTP\/1\.1 403/)
+ const ok = await fetch(`${viewer.url}/state`)
+ assert.equal(ok.status, 200)
+ } finally { await viewer.close() }
+})
+
+async function play(overrides, pieces = 300) {
+ const { viewer, ctl, state } = await fresh(overrides)
+ try {
+ let s = await state()
+ for (let i = 0; i < 400 && s.session.pieces < pieces; i++) { await ctl({ cmd: 'tick', n: 25 }); s = await state() }
+ return { pieces: s.session.pieces, lines: s.session.lines, per300: (s.session.lines / s.session.pieces) * 300, misses: s.session.misses, topOuts: s.session.topOuts, games: s.session.games }
+ } finally { await viewer.close() }
+}
+
+test('the honest dial: low gravity clears far more lines per 300 pieces than very high gravity', async () => {
+ const same = { speedup: 0, garbageRows: 8, seed: 7 }
+ const easy = await play({ ...same, gravity: 1 })
+ const hard = await play({ ...same, gravity: 40 })
+ console.log(` gravity 1 : ${easy.per300.toFixed(0)} lines per 300 pieces, ${easy.misses} missed, ${easy.topOuts} top-outs`)
+ console.log(` gravity 40: ${hard.per300.toFixed(0)} lines per 300 pieces, ${hard.misses} missed, ${hard.topOuts} top-outs`)
+ assert.ok(easy.per300 >= 110, `low gravity plays clean (${easy.per300.toFixed(0)} lines)`)
+ assert.ok(easy.per300 >= hard.per300 * 2, `easy ${easy.per300.toFixed(0)} vs hard ${hard.per300.toFixed(0)}`)
+ assert.ok(easy.misses <= 3 && easy.topOuts === 0, 'no misses and no top-outs when there is time')
+ assert.ok(hard.misses >= 50, `placements land short when there is no time (${hard.misses})`)
+ assert.ok(hard.topOuts >= 5, `and the stack tops out (${hard.topOuts})`)
+})
+
+test('thinking time is the same dial: a slow decider breaks at a gravity a fast one survives', async () => {
+ const same = { speedup: 0, gravity: 14, seed: 11 }
+ const fast = await play({ ...same, decisionMs: 110 }, 200)
+ const slow = await play({ ...same, decisionMs: 900 }, 200)
+ console.log(` 110 ms: ${fast.per300.toFixed(0)} lines per 300, ${fast.misses} missed · 900 ms: ${slow.per300.toFixed(0)} lines per 300, ${slow.misses} missed`)
+ assert.ok(fast.misses <= 3 && fast.topOuts === 0)
+ assert.ok(slow.misses >= 20 && slow.per300 < fast.per300 * 0.8)
+})
+
+test('it never ends: a top-out is followed by a new game, and the best is kept', async () => {
+ const { viewer, ctl, state } = await fresh({ gravity: 40, garbageRows: 12, speedup: 0 })
+ try {
+ let s = await state()
+ for (let i = 0; i < 60 && s.session.topOuts < 2; i++) { await ctl({ cmd: 'tick', n: 10 }); s = await state() }
+ assert.ok(s.session.topOuts >= 2, 'topped out at least twice')
+ assert.ok(s.session.games >= 3, 'and a new game followed each time')
+ assert.ok(s.session.best >= 0 && s.session.lastTopOut)
+ assert.ok(s.log.some((l) => /Topped out/.test(l.text)))
+ } finally { await viewer.close() }
+})
+
+test('the offline reader answers from the state text and option descriptions alone', async () => {
+ const board = game.emptyBoard()
+ for (let x = 0; x < 9; x++) for (let y = 16; y < 20; y++) board[y][x] = 1
+ const cands = game.enumerate(board, 'I')
+ assert.equal(cands.length, 17, 'an I piece has 7 flat and 10 upright placements')
+ const text = game.buildState({ style: 'Go for four.', board, type: 'I', next: ['T', 'O', 'L'], level: 1, lines: 0, gravity: 2, decisionMs: 110, moveMs: 35, cands })
+ assert.match(text, /\|#########\.\|/); assert.match(text, /Current piece: I\. Next pieces: T, O, L\./); assert.match(text, /r1c9/)
+ const qs = game.buildQuestions('I', cands)
+ const a = game.blocksMock(text, 'place', canon(qs.place))
+ assert.equal(a.choice, 'r1c9', 'upright in the open column, for four lines')
+ assert.equal(Object.keys(a.probabilities).length, 17)
+ assert.ok(Math.abs(Object.values(a.probabilities).reduce((x, y) => x + y, 0) - 1) < 1e-9)
+ assert.ok(a.confidence >= 0.5 && a.confidence <= 0.85)
+ assert.ok(Object.values(a.probabilities).every((p) => p > 0), 'never one-hot')
+ const d = game.blocksMock(text, 'danger', canon(qs.danger))
+ assert.ok(d.score < 1 && Object.keys(d.probabilities).length === 4)
+ const tall = game.emptyBoard(); for (let x = 0; x < 8; x++) for (let y = 3; y < 20; y++) tall[y][x] = (x + y) % 3 ? 1 : 0
+ const tallText = game.buildState({ style: 'Go for four.', board: tall, type: 'O', next: ['T', 'O', 'L'], level: 1, lines: 0, gravity: 2, decisionMs: 110, moveMs: 35, cands: game.enumerate(tall, 'O') })
+ assert.ok(game.blocksMock(tallText, 'danger', canon(qs.danger)).score > 2.3, 'a tall, holey stack is dangerous')
+ assert.ok(game.blocksMock(tallText, 'go_for_four', canon(qs.go_for_four)).noul < 0.2)
+ assert.ok(game.blocksMock(text, 'go_for_four', canon(qs.go_for_four)).noul > 0.6)
+ assert.equal(game.blocksMock('no board here', 'place', canon(qs.place)), null, 'falls through to the generic mock')
+})
+
+test('check.mjs accepts the template and rejects bad values', () => {
+ const check = (obj) => {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-blocks-check-'))
+ writeFileSync(join(ws, 'blocks.json'), typeof obj === 'string' ? obj : JSON.stringify(obj))
+ return spawnSync(process.execPath, [join(ROOT, 'toolchain/check.mjs')], { env: { ...process.env, HARNESS_WORKSPACE: ws }, encoding: 'utf8' })
+ }
+ const template = JSON.parse(readFileSync(join(ROOT, 'template/blocks.json'), 'utf8'))
+ const ok = check(template)
+ assert.equal(ok.status, 0, ok.stdout); assert.match(ok.stdout, /ok\s+blocks\.json is valid/)
+ for (const [patch, re] of [
+ [{ gravity: 41 }, /gravity/], [{ gravity: 0.1 }, /gravity/], [{ speedup: 2.5 }, /speedup/], [{ decisionMs: 10 }, /decisionMs/], [{ moveMs: 900 }, /moveMs/],
+ [{ garbageRows: 13 }, /garbageRows/], [{ weights: { I: 0, O: 0, T: 0, S: 0, Z: 0, J: 0, L: 0 } }, /all zero/], [{ weights: { X: 1 } }, /unknown piece/],
+ [{ board: ['#########'] }, /board row 1/], [{ board: Array(21).fill('..........') }, /21 rows/], [{ board: ['####x#####'] }, /board row 1/],
+ ]) {
+ const r = check({ ...template, ...patch })
+ assert.equal(r.status, 1, JSON.stringify(patch)); assert.match(r.stdout, re)
+ }
+ assert.equal(check({ ...template, weights: { S: 1, Z: 1 }, board: ['#########.', '.#########'], garbageRows: 3 }).status, 0)
+ assert.equal(check('{ nope').status, 1)
+})
+
+test('the harness never uses a trademarked game name', () => {
+ const banned = new RegExp(['te', 'tr', 'is'].join(''), 'i')
+ const walk = (dir) => readdirSync(dir).flatMap((n) => { const p = join(dir, n); return statSync(p).isDirectory() ? (n === 'node_modules' || n === '.harness' ? [] : walk(p)) : [p] })
+ for (const file of walk(ROOT)) {
+ assert.ok(!banned.test(file), `file name ${file}`)
+ assert.ok(!banned.test(readFileSync(file, 'utf8')), `contents of ${file}`)
+ }
+})
diff --git a/store/agents/jev-blocks/toolchain/README.md b/store/agents/jev-blocks/toolchain/README.md
new file mode 100644
index 000000000..e92012621
--- /dev/null
+++ b/store/agents/jev-blocks/toolchain/README.md
@@ -0,0 +1,44 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
+
+## Going live
+
+Without a key everything runs on the offline stand-in and the pane says `MOCK`. For the real model,
+give the harness a key. The viewer is started by the Harness daemon, which does not see variables
+you export in a shell, so the reliable place is a small file in your home folder:
+
+```sh
+mkdir -p ~/.config/typesafe && chmod 700 ~/.config/typesafe
+printf 'TYPESAFE_API_KEY=%s\n' 'paste-your-key-here' > ~/.config/typesafe/credentials
+chmod 600 ~/.config/typesafe/credentials
+```
+
+Two routes work, and both speak the same question format:
+
+| route | what goes in the file | where to get it |
+|---|---|---|
+| TypeSafe direct | `TYPESAFE_API_KEY=...` | https://console.typesafe.ai/keys (there may be a waitlist) |
+| Cloudflare Workers AI | `CLOUDFLARE_ACCOUNT_ID=...` and `CLOUDFLARE_API_TOKEN=...` | a Cloudflare API token with Workers AI permission, no TypeSafe waitlist |
+
+Environment variables of the same names win over the file. Restart the harness after changing the
+file. `toolchain/doctor.sh` prints which route is active and never prints the key. One file serves
+every Jev harness on the machine. Never paste a key into the chat, and never save one in the
+workspace. Under `node --test`, or with `JEV_OFFLINE=1`, a key is ignored so tests stay deterministic.
diff --git a/store/agents/jev-blocks/toolchain/check.mjs b/store/agents/jev-blocks/toolchain/check.mjs
new file mode 100644
index 000000000..b221ed0d3
--- /dev/null
+++ b/store/agents/jev-blocks/toolchain/check.mjs
@@ -0,0 +1,67 @@
+#!/usr/bin/env node
+// check.mjs — validate a blocks.json for the Jev Blocks harness.
+// Enforces the ranges the viewer clamps to, so a challenge means what its numbers say.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+const file = process.argv[2] || join(ws, 'blocks.json')
+const PIECES = ['I', 'O', 'T', 'S', 'Z', 'J', 'L']
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(`error ${msg}`) }
+const warn = (msg) => console.log(`warn ${msg}`)
+
+let p
+try {
+ p = JSON.parse(readFileSync(file, 'utf8'))
+} catch (e) {
+ console.log(`error cannot read blocks.json: ${e.message}`)
+ process.exit(1)
+}
+if (!p || typeof p !== 'object' || Array.isArray(p)) { console.log('error blocks.json must be a JSON object'); process.exit(1) }
+
+const range = (key, lo, hi, required = false) => {
+ if (p[key] === undefined) { if (required) bad(`${key} is required (${lo}..${hi})`); return }
+ if (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < lo || p[key] > hi) bad(`${key} must be a number ${lo}..${hi} (got ${JSON.stringify(p[key])})`)
+}
+
+if (!p.title || typeof p.title !== 'string') warn('no title')
+range('gravity', 0.2, 40, true)
+range('speedup', 0, 2)
+range('decisionMs', 30, 1000)
+range('moveMs', 5, 500)
+range('garbageRows', 0, 12)
+if (p.garbageRows !== undefined && !Number.isInteger(p.garbageRows)) bad('garbageRows must be a whole number')
+if (p.seed !== undefined && !Number.isInteger(p.seed)) bad('seed must be a whole number')
+
+if (p.weights !== undefined) {
+ if (!p.weights || typeof p.weights !== 'object' || Array.isArray(p.weights)) bad('weights must be an object like { "I": 1, "O": 1, ... }')
+ else {
+ let sum = 0
+ for (const [k, v] of Object.entries(p.weights)) {
+ if (!PIECES.includes(k)) bad(`weights has an unknown piece "${k}" (use ${PIECES.join(', ')})`)
+ else if (!Number.isInteger(v) || v < 0 || v > 9) bad(`weights.${k} must be a whole number 0..9`)
+ else sum += v
+ }
+ if (!fail && sum === 0) bad('weights are all zero: at least one piece needs a weight above 0')
+ }
+}
+
+let boardRows = 0
+if (p.board !== undefined) {
+ if (!Array.isArray(p.board)) bad('board must be a list of rows, top row first')
+ else {
+ if (p.board.length > 20) bad(`board has ${p.board.length} rows, the well is only 20 tall`)
+ p.board.forEach((row, i) => { if (typeof row !== 'string' || !/^[.#]{10}$/.test(row)) bad(`board row ${i + 1} must be exactly 10 characters of '.' or '#'`) })
+ boardRows = p.board.length
+ if (p.board.some((row) => row === '##########')) warn('a full board row is cleared before the game starts')
+ }
+}
+if (boardRows + (p.garbageRows || 0) > 16) warn(`board (${boardRows} rows) plus garbage (${p.garbageRows || 0} rows) leaves almost no room: Jev may top out at once`)
+
+if (!p.style || typeof p.style !== 'string') warn('a style line tells Jev how to play')
+else if (p.style.length > 600) warn('style is cut at 600 characters')
+
+console.log(fail ? 'fail invalid blocks.json' : 'ok blocks.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-blocks/toolchain/doctor.sh b/store/agents/jev-blocks/toolchain/doctor.sh
new file mode 100755
index 000000000..06a2254d4
--- /dev/null
+++ b/store/agents/jev-blocks/toolchain/doctor.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Blocks viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+cd "$(dirname "$0")/.."
+node -e "import('./toolchain/jev.mjs').then((m) => console.log('ok Jev: ' + m.describeCredentials())).catch((e) => console.log('warn Jev client did not load: ' + e.message))"
+echo "done"
diff --git a/store/agents/jev-blocks/toolchain/init-workspace.sh b/store/agents/jev-blocks/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-blocks/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-blocks/toolchain/jev.mjs b/store/agents/jev-blocks/toolchain/jev.mjs
new file mode 100644
index 000000000..190c7e9ac
--- /dev/null
+++ b/store/agents/jev-blocks/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
+// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
+// score a position on a 2..10 level scale — a float plus per-level probabilities
+//
+// Questions are authored as options[] / legend{} (or an option -> description map) and translated
+// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The generic mock reads
+// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
+// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
+// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ return key ? 'typesafe' : 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ return (h >>> 0) / 4294967296
+}
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+
+/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
+export function stems(text) {
+ const out = []
+ for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
+ if (w.length < 2 || STOP.has(w)) continue
+ out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
+ }
+ return out
+}
+
+/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
+function evidence(stateStems, needle) {
+ const want = [...new Set(stems(needle))]
+ if (!want.length) return 0
+ let hit = 0
+ for (const w of want) if (stateStems.has(w)) hit++
+ return (hit / Math.sqrt(want.length)) * 1.2
+}
+
+function softmax(raw, temp = 1) {
+ const m = Math.max(...raw)
+ const exps = raw.map((r) => Math.exp((r - m) / temp))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ return exps.map((e) => e / sum)
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic generic mock. It turns the state text + question wording into a plausible
+// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`
+ const S = new Set(stems(text))
+ const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
+
+ if (q.type === 'noul') {
+ const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
+ const no = evidence(S, `${q.raw?.false ?? ''}`)
+ const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
+ const probs = softmax(raw, 0.6)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
+ const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
+ // No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
+ if (raw.every((r) => Math.abs(r) < 0.26)) {
+ const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
+ levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
+ }
+ const probs = softmax(raw, 0.7)
+ const probabilities = {}
+ levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
+ const score = probs.reduce((acc, p, i) => acc + p * i, 0)
+ return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// Imports are hoisted, so they can live here with the code that needs them.
+import { readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ out.raw = isMap(q.criteria) ? q.criteria : null
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+// ---------------------------------------------------------------------------
+// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
+// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
+// you happen to have open. Two live routes are supported, both speaking the same question format:
+// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
+// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
+// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
+// ---------------------------------------------------------------------------
+const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN']
+let credCache = null
+export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
+
+function readCredentialFile() {
+ const now = Date.now()
+ const path = credentialsPath()
+ if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
+ const values = {}
+ try {
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
+ if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
+ }
+ } catch { /* no file: fine */ }
+ credCache = { at: now, path, values }
+ return values
+}
+
+/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
+export function resolveCredentials(explicitKey) {
+ if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
+ // Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
+ // key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
+ if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
+ const file = readCredentialFile()
+ const get = (k) => process.env[k] || file[k] || ''
+ const key = explicitKey || get('TYPESAFE_API_KEY')
+ if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
+ const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
+ if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
+ return null
+}
+
+/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
+export function describeCredentials() {
+ const c = resolveCredentials()
+ if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
+ return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
+}
+
+async function liveEvaluate(body, cred) {
+ const endpoint = cred.url
+ const key = cred.secret
+ const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } } : body
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) {
+ const data = await res.json()
+ // Cloudflare wraps the model's reply as { result, success, errors }.
+ if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
+ return data?.result?.answers ? data.result : data
+ }
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const cred = resolveCredentials(key)
+ const client = cred ? cred.provider : 'mock'
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (cred) {
+ const data = await liveEvaluate({ model, state, questions: wire }, cred)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-blocks/toolchain/setup.sh b/store/agents/jev-blocks/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-blocks/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-blocks/toolchain/viewer.sh b/store/agents/jev-blocks/toolchain/viewer.sh
new file mode 100755
index 000000000..5be2179e8
--- /dev/null
+++ b/store/agents/jev-blocks/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Blocks viewer (Jev plays a falling-blocks puzzle, one placement decision per piece).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-blocks/viewer/base.css b/store/agents/jev-blocks/viewer/base.css
new file mode 100644
index 000000000..c41ddcd46
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/base.css
@@ -0,0 +1,83 @@
+/* base.css — the shared look of the Jev flagship viewers. Load before studio.css.
+ Set --accent / --accent2 in studio.css to give a harness its own colour. */
+:root {
+ --bg: #07080d; --panel: #10121a; --panel2: #161925; --line: #232838; --line2: #2e3550;
+ --ink: #e9ecf5; --dim: #8b92aa; --faint: #565d75;
+ --accent: #a78bfa; --accent2: #6d5bd0;
+ --ok: #34d399; --warn: #fbbf24; --bad: #fb7185; --cyan: #5eead4; --blue: #60a5fa;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ --radius: 12px;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1100px 700px at 75% -10%, color-mix(in srgb, var(--accent) 14%, transparent) 0%, transparent 60%), var(--bg);
+ color: var(--ink); font: 13px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+::selection { background: color-mix(in srgb, var(--accent) 45%, transparent); }
+::-webkit-scrollbar { width: 8px; height: 8px; }
+::-webkit-scrollbar-thumb { background: var(--line2); border-radius: 4px; }
+::-webkit-scrollbar-track { background: transparent; }
+
+#topbar {
+ display: flex; align-items: center; gap: 22px; padding: 10px 18px; flex: none; flex-wrap: wrap;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(20,22,34,.92), rgba(10,11,18,.7)); backdrop-filter: blur(8px);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font: 700 15px var(--mono); letter-spacing: .4px; margin: 0; white-space: nowrap; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 14px var(--accent); animation: dot 2.4s ease-in-out infinite; }
+@keyframes dot { 50% { transform: scale(.72); opacity: .7; } }
+.brand .sub { color: var(--dim); font-size: 11px; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; min-width: 54px; }
+.stat label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+button, .btn {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line2); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: border-color .15s, filter .15s, transform .05s; user-select: none;
+}
+button:hover { border-color: var(--accent); }
+button:active { transform: translateY(1px); }
+button.primary { background: linear-gradient(135deg, var(--accent2), var(--accent)); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.12); }
+button.ghost { background: transparent; }
+button.on { border-color: var(--accent); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
+button[disabled] { opacity: .45; cursor: default; }
+kbd { font: 600 10px var(--mono); padding: 1px 5px; border: 1px solid var(--line2); border-bottom-width: 2px; border-radius: 4px; color: var(--dim); }
+input[type=text], input[type=search], select, textarea {
+ font: 13px var(--mono); color: var(--ink); background: #0b0d14; border: 1px solid var(--line2); border-radius: 8px; padding: 7px 10px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+input[type=range] { accent-color: var(--accent); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow: auto; }
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 14px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; background: rgba(12,13,20,.55); }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; }
+.panel-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--dim); margin-bottom: 9px; display: flex; align-items: center; gap: 8px; }
+.panel-title .right { margin-left: auto; text-transform: none; letter-spacing: 0; }
+.how { color: var(--dim); font-size: 12.5px; line-height: 1.55; }
+.how b { color: var(--ink); } .how code { color: var(--warn); }
+.pill { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line2); color: var(--dim); }
+.pill.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
+.pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
+.pill.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); }
+
+.canvas-wrap { position: relative; flex: 1; min-height: 320px; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #05060a; }
+.canvas-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.banner { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); padding: 9px 20px; border-radius: 10px; font: 700 14px var(--mono); white-space: nowrap; backdrop-filter: blur(6px); }
+.banner.ok { background: rgba(16,185,129,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 34px rgba(16,185,129,.35); }
+.banner.bad { background: rgba(225,29,72,.16); border: 1px solid var(--bad); color: var(--bad); box-shadow: 0 0 34px rgba(225,29,72,.35); }
+.hidden { display: none !important; }
+.cfg-error { margin: 0 16px; padding: 8px 12px; border: 1px solid var(--bad); border-radius: 8px; color: var(--bad); background: rgba(225,29,72,.08); font-size: 12px; }
+
+@media (max-width: 900px) {
+ main { flex-direction: column; overflow: auto; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); overflow: visible; }
+ body { overflow: auto; }
+}
diff --git a/store/agents/jev-blocks/viewer/game.mjs b/store/agents/jev-blocks/viewer/game.mjs
new file mode 100644
index 000000000..4d366177e
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/game.mjs
@@ -0,0 +1,347 @@
+// game.mjs — the pure rules of the falling-blocks puzzle, with no server and no timers:
+// piece shapes, the well, legal placements, the state text Jev reads, and the offline reader
+// (`blocksMock`) that stands in for Jev when no API key is set.
+//
+// The offline reader gets ONLY the state text and the option descriptions, the same words live Jev
+// gets. It never touches the simulator's variables.
+
+export const W = 10
+export const H = 20
+export const TYPES = ['I', 'O', 'T', 'S', 'Z', 'J', 'L']
+export const CODE = { I: 1, O: 2, T: 3, S: 4, Z: 5, J: 6, L: 7, garbage: 8, junk: 9 }
+
+const BASE = {
+ I: { n: 4, cells: [[0, 1], [1, 1], [2, 1], [3, 1]], states: 2 },
+ O: { n: 2, cells: [[0, 0], [1, 0], [0, 1], [1, 1]], states: 1 },
+ T: { n: 3, cells: [[1, 0], [0, 1], [1, 1], [2, 1]], states: 4 },
+ S: { n: 3, cells: [[1, 0], [2, 0], [0, 1], [1, 1]], states: 2 },
+ Z: { n: 3, cells: [[0, 0], [1, 0], [1, 1], [2, 1]], states: 2 },
+ J: { n: 3, cells: [[0, 0], [0, 1], [1, 1], [2, 1]], states: 4 },
+ L: { n: 3, cells: [[2, 0], [0, 1], [1, 1], [2, 1]], states: 4 },
+}
+
+/** SHAPES[type][rot] = list of [dx, dy] cells inside the piece's box. Rotation is clockwise. */
+export const SHAPES = {}
+for (const t of TYPES) {
+ const { n, cells, states } = BASE[t]
+ const rots = []
+ let cur = cells
+ for (let r = 0; r < states; r++) {
+ rots.push(cur.map(([x, y]) => [x, y]))
+ cur = cur.map(([x, y]) => [n - 1 - y, x])
+ }
+ SHAPES[t] = rots
+}
+
+/** Where a fresh piece appears: box x, box y. The I piece starts one row up so it shows in row 0. */
+export const spawnOf = (type) => ({ x: type === 'O' ? 4 : 3, y: type === 'I' ? -1 : 0 })
+
+/** Fewest rotate presses from rotation 0, and the rotation states passed through. */
+export function rotationPath(type, rot) {
+ const n = SHAPES[type].length
+ if (rot <= 0 || rot >= n) return []
+ if (n === 4 && rot === 3) return [3] // one press the other way
+ const path = []
+ for (let r = 1; r <= rot; r++) path.push(r)
+ return path
+}
+
+export const emptyBoard = () => Array.from({ length: H }, () => new Array(W).fill(0))
+export const cloneBoard = (b) => b.map((row) => row.slice())
+
+export function collide(board, type, rot, x, y) {
+ for (const [dx, dy] of SHAPES[type][rot]) {
+ const cx = x + dx, cy = y + dy
+ if (cx < 0 || cx >= W || cy >= H) return true
+ if (cy >= 0 && board[cy][cx]) return true
+ }
+ return false
+}
+
+export function dropRow(board, type, rot, x, y) {
+ while (!collide(board, type, rot, x, y + 1)) y++
+ return y
+}
+
+export function extent(type, rot) {
+ let minX = 9, maxX = 0
+ for (const [dx] of SHAPES[type][rot]) { if (dx < minX) minX = dx; if (dx > maxX) maxX = dx }
+ return { minX, maxX }
+}
+
+/** Remove full rows. Returns the row indexes that were full (top to bottom). */
+export function clearLines(board) {
+ const cleared = []
+ for (let y = 0; y < H; y++) if (board[y].every((c) => c)) cleared.push(y)
+ for (const y of cleared) { board.splice(y, 1); board.unshift(new Array(W).fill(0)) }
+ return cleared
+}
+
+/** Column heights, holes, bumpiness and wells of a board. */
+export function measure(board) {
+ const heights = new Array(W).fill(0)
+ let holes = 0
+ for (let x = 0; x < W; x++) {
+ let seen = false
+ for (let y = 0; y < H; y++) {
+ if (board[y][x]) { if (!seen) { heights[x] = H - y; seen = true } } else if (seen) holes++
+ }
+ }
+ return { heights, holes, ...surface(heights) }
+}
+
+/** Facts that follow from column heights alone. A well is a column 2+ lower than both sides. */
+export function surface(heights) {
+ let total = 0, max = 0, bump = 0, wells = 0, deepest = 0, deepestCol = -1
+ for (let x = 0; x < W; x++) {
+ const h = heights[x]
+ total += h
+ if (h > max) max = h
+ if (x < W - 1) bump += Math.abs(h - heights[x + 1])
+ const left = x === 0 ? H : heights[x - 1], right = x === W - 1 ? H : heights[x + 1]
+ const depth = Math.min(left, right) - h
+ if (depth >= 2) wells++
+ if (depth > deepest) { deepest = depth; deepestCol = x }
+ }
+ return { total, max, bump, wells, deepest, deepestCol }
+}
+
+/** How ragged the stack is: filled/empty changes along rows and down columns (walls and floor count as filled). */
+export function breaks(board) {
+ let rowBreaks = 0, colBreaks = 0
+ for (let y = 0; y < H; y++) {
+ let prev = 1
+ for (let x = 0; x < W; x++) { const c = board[y][x] ? 1 : 0; if (c !== prev) rowBreaks++; prev = c }
+ if (!prev) rowBreaks++
+ }
+ for (let x = 0; x < W; x++) {
+ let prev = 0
+ for (let y = 0; y < H; y++) { const c = board[y][x] ? 1 : 0; if (c !== prev) colBreaks++; prev = c }
+ if (!prev) colBreaks++
+ }
+ return { rowBreaks, colBreaks }
+}
+
+/**
+ * Every legal placement of `type`: each rotation in each column it can slide to along its spawn
+ * row, dropped straight down. Returns [{ id, rot, x, y, col0, col1, moves, lines, holes, ... }].
+ */
+export function enumerate(board, type) {
+ const out = []
+ const sp = spawnOf(type)
+ const before = measure(board)
+ for (let rot = 0; rot < SHAPES[type].length; rot++) {
+ if (collide(board, type, rot, sp.x, sp.y)) continue
+ const { minX, maxX } = extent(type, rot)
+ const presses = rotationPath(type, rot).length
+ for (const dir of [-1, 1]) {
+ for (let x = dir < 0 ? sp.x : sp.x + 1; x + minX >= 0 && x + maxX < W; x += dir) {
+ if (collide(board, type, rot, x, sp.y)) break // the stack is in the way along the top row
+ const y = dropRow(board, type, rot, x, sp.y)
+ const after = cloneBoard(board)
+ let above = false
+ for (const [dx, dy] of SHAPES[type][rot]) { if (y + dy < 0) above = true; else after[y + dy][x + dx] = CODE[type] }
+ let top = H, bottom = 0
+ for (const [, dy] of SHAPES[type][rot]) { top = Math.min(top, y + dy); bottom = Math.max(bottom, y + dy) }
+ const lines = clearLines(after).length
+ const m = measure(after)
+ out.push({
+ id: `r${rot}c${x + minX}`, rot, x, y, col0: x + minX, col1: x + maxX,
+ moves: presses + Math.abs(x - sp.x), lines, holes: m.holes, newHoles: m.holes - before.holes,
+ heights: m.heights, max: m.max, total: m.total, bump: m.bump, wells: m.wells, above,
+ landing: H - 1 - (top + bottom) / 2, ...breaks(after),
+ })
+ }
+ }
+ }
+ out.sort((a, b) => a.rot - b.rot || a.x - b.x)
+ return out
+}
+
+/** One short factual line per placement. This is the option description Jev reads. */
+export function describePlacement(type, c) {
+ const sign = c.newHoles > 0 ? `+${c.newHoles}` : String(c.newHoles)
+ return `${type} rotation ${c.rot} over columns ${c.col0}-${c.col1}, lands at height ${c.landing}: clears ${c.lines} lines, holes ${c.holes} (${sign}), ` +
+ `heights ${c.heights.join(',')}, max ${c.max}, bumpiness ${c.bump}, wells ${c.wells}, row breaks ${c.rowBreaks}, column breaks ${c.colBreaks}, ${c.moves} moves` +
+ (c.above ? ', sticks out over the top' : '')
+}
+
+export function boardRows(board) {
+ return board.map((row, y) => `${String(H - 1 - y).padStart(2)} |${row.map((c) => (c ? '#' : '.')).join('')}|`)
+}
+
+/** The shared state block: style line, the well as ASCII, the pieces, the clock, the placements. */
+export function buildState({ style, board, type, next, level, lines, gravity, decisionMs, moveMs, cands }) {
+ const m = measure(board)
+ const table = cands.map((c) => `${c.id.padEnd(5)} ${`${c.col0}-${c.col1}`.padEnd(4)} ${String(c.lines).padEnd(5)} ${String(c.holes).padEnd(5)} ${String(c.max).padEnd(3)} ${String(c.bump).padEnd(4)} ${c.moves}`)
+ return [
+ String(style || '').trim(),
+ '',
+ `Falling-blocks puzzle, a synthetic game. The well is ${W} columns (0-${W - 1}) by ${H} rows. '#' is filled, '.' is empty. Top row first.`,
+ ' 0123456789',
+ ...boardRows(board),
+ `Column heights: ${m.heights.join(' ')}`,
+ `Stack: max height ${m.max}, holes ${m.holes}, bumpiness ${m.bump}, deepest well ${m.deepest}${m.deepestCol >= 0 ? ` at column ${m.deepestCol}` : ''}.`,
+ `Current piece: ${type}. Next pieces: ${next.join(', ')}.`,
+ `Level ${level}, lines ${lines}. Gravity ${gravity.toFixed(1)} rows per second. A decision costs about ${Math.round(decisionMs)} ms, then each rotate or shift costs ${Math.round(moveMs)} ms while the piece keeps falling.`,
+ 'Placements (id = rotation r, leftmost column c):',
+ 'id cols lines holes max bump moves',
+ ...table,
+ ].join('\n')
+}
+
+export const DANGER_LEVELS = [
+ 'safe: the stack sits in the bottom third of the well',
+ 'building: the stack is near the middle of the well',
+ 'high: the stack is in the upper half and has holes',
+ 'critical: about to top out',
+]
+
+export function buildQuestions(type, cands) {
+ const options = {}
+ for (const c of cands) options[c.id] = describePlacement(type, c)
+ return {
+ place: { type: 'choice', instructions: `Which placement of the ${type} piece keeps the stack lowest, flattest and free of holes?`, options: Object.keys(options), descriptions: options },
+ danger: { type: 'score', instructions: 'How close is the stack to topping out?', legend: Object.fromEntries(DANGER_LEVELS.map((l, i) => [String(i), l])) },
+ go_for_four: { type: 'noul', instructions: 'Is it worth keeping one column open for an I piece to clear four lines at once?', criteria: { true: 'the stack is low and clean, and there is time to wait', false: 'the stack is high, has holes, or the piece falls too fast' } },
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The offline reader. Parses the state text and the option descriptions, nothing else.
+// ---------------------------------------------------------------------------
+const WELL_COL = W - 1
+/** Weights of the offline reader's stack score. */
+export const TUNE = {
+ landing: 4.5, cleared: 3.42, rowBreaks: 3.22, colBreaks: 9.35, holeCost: 7.9, wellSum: 3.39, wellCap: 3,
+ wellHit: 40, four: 60, skim: 8, planMax: 8, planHoles: 0, panic: 13, calmGravity: 14, late: 12, gapScale: 8,
+}
+
+export function readState(text) {
+ const rows = []
+ for (const m of text.matchAll(/^\s*\d+ \|([.#]{10})\|$/gm)) rows.push(m[1])
+ const board = emptyBoard()
+ rows.slice(-H).forEach((r, i, all) => { const y = H - all.length + i; for (let x = 0; x < W; x++) board[y][x] = r[x] === '#' ? 1 : 0 })
+ const num = (re, d) => { const m = text.match(re); return m ? Number(m[1]) : d }
+ const next = (text.match(/Next pieces: ([A-Z, ]+)\./)?.[1] ?? '').split(/,\s*/).filter(Boolean)
+ return {
+ board, m: measure(board),
+ type: text.match(/Current piece: ([A-Z])/)?.[1] ?? '',
+ next,
+ gravity: num(/Gravity ([\d.]+) rows per second/, 1),
+ decisionMs: num(/decision costs about (\d+) ms/, 110),
+ moveMs: num(/shift costs (\d+) ms/, 35),
+ style: text.split('\n\n')[0] ?? '',
+ }
+}
+
+/**
+ * Should we keep the right-hand column open for an I piece? `place` and `go_for_four` cannot see
+ * each other, so both read the same facts from the state text and reach the same plan.
+ */
+export function fourPlan(s) {
+ const left = s.m.heights.slice(0, WELL_COL)
+ const maxLeft = Math.max(...left), minLeft = Math.min(...left)
+ let holesLeft = 0 // holes outside the open column
+ for (let x = 0; x < WELL_COL; x++) { let seen = false; for (let y = 0; y < H; y++) { if (s.board[y][x]) seen = true; else if (seen) holesLeft++ } }
+ let wellHoles = 0
+ { let seen = false; for (let y = 0; y < H; y++) { if (s.board[y][WELL_COL]) seen = true; else if (seen) wellHoles++ } }
+ const wants = /\bfour\b/i.test(s.style) && !/\b(never|no|avoid|without|not)\b[^.]*\bfour\b/i.test(s.style)
+ const calm = s.gravity <= TUNE.calmGravity
+ const clean = holesLeft <= TUNE.planHoles && wellHoles === 0 && s.m.heights[WELL_COL] <= minLeft
+ const panic = maxLeft >= TUNE.panic
+ const high = maxLeft > TUNE.planMax
+ const iSoon = s.type === 'I' || s.next.includes('I')
+ const on = wants && calm && clean && !panic
+ let z = -2.4
+ if (wants) z += 1.2
+ if (calm) z += 1.0; else z -= 2.0
+ if (clean) z += 1.6; else z -= 1.6
+ if (high) z -= 1.0; else z += 0.8
+ if (panic) z -= 2.5
+ if (iSoon) z += 0.5
+ const p = 1 / (1 + Math.exp(-z))
+ return { on, high, depth: minLeft - s.m.heights[WELL_COL], p: Math.min(0.97, Math.max(0.03, p)), maxLeft }
+}
+
+function parseOption(desc) {
+ const n = (re) => { const m = desc.match(re); return m ? Number(m[1]) : 0 }
+ const heights = (desc.match(/heights ([\d,]+)/)?.[1] ?? '').split(',').filter(Boolean).map(Number)
+ const cols = desc.match(/columns (\d+)-(\d+)/)
+ return {
+ lines: n(/clears (\d+) lines/), holes: n(/holes (\d+)/), newHoles: Number(desc.match(/holes \d+ \(([+-]?\d+)\)/)?.[1] ?? 0), moves: n(/, (\d+) moves/),
+ landing: n(/lands at height ([\d.]+)/), rowBreaks: n(/row breaks (\d+)/), colBreaks: n(/column breaks (\d+)/),
+ heights: heights.length === W ? heights : new Array(W).fill(0),
+ col0: cols ? Number(cols[1]) : 0, col1: cols ? Number(cols[2]) : 0,
+ above: /sticks out over the top/.test(desc),
+ }
+}
+
+/**
+ * A sound, well-known stack score (landing height, lines, row and column breaks, holes, well depth).
+ * With the four-line plan on, the right-hand column is left out and guarded.
+ */
+function stackScore(o, plan, s) {
+ const n = plan.on ? WELL_COL : W
+ let wellSum = 0
+ for (let x = 0; x < n; x++) {
+ const h = o.heights[x]
+ const left = x === 0 ? H : o.heights[x - 1], right = x === n - 1 ? H : o.heights[x + 1]
+ const depth = Math.min(left, right) - h
+ if (depth > 0) { const d = Math.min(depth, TUNE.wellCap); wellSum += (d * (d + 1)) / 2 + (depth - d) }
+ }
+ let v = -TUNE.landing * o.landing + TUNE.cleared * o.lines - TUNE.rowBreaks * o.rowBreaks - TUNE.colBreaks * o.colBreaks - TUNE.holeCost * o.holes - TUNE.wellSum * wellSum
+ if (plan.on && o.col1 >= WELL_COL) {
+ // The open column is for the I piece. When the stack is high, a clean skim off its top is fine too.
+ if (o.lines >= 4) v += TUNE.four
+ else if (plan.high && o.lines >= 1 && o.newHoles <= 0) v += TUNE.skim * o.lines
+ else v -= TUNE.wellHit
+ }
+ if (o.above) v -= 400
+ // Time: a far placement is no good if the piece lands before it gets there.
+ const needMs = s.decisionMs + (o.moves + 1) * s.moveMs
+ const rowsFree = Math.max(1, H - 2 - s.m.max)
+ const haveMs = (rowsFree / Math.max(0.2, s.gravity)) * 1000
+ if (needMs > haveMs) v -= TUNE.late * ((needMs - haveMs) / Math.max(1, s.moveMs))
+ return v
+}
+
+function spread(scores, floorTop = 0.5, capTop = 0.85) {
+ const sorted = [...scores].sort((a, b) => b - a)
+ const gap = sorted.length > 1 ? sorted[0] - sorted[1] : 9
+ const target = Math.min(capTop, Math.max(floorTop, floorTop + (capTop - floorTop) * (1 - Math.exp(-gap / TUNE.gapScale))))
+ const best = Math.max(...scores)
+ const soft = (t) => { const e = scores.map((v) => Math.exp((v - best) / t)); const sum = e.reduce((a, b) => a + b, 0); return e.map((v) => v / sum) }
+ let lo = 0.01, hi = 200
+ for (let i = 0; i < 48; i++) { const mid = Math.sqrt(lo * hi); if (Math.max(...soft(mid)) > target) lo = mid; else hi = mid }
+ return soft(hi)
+}
+
+export function blocksMock(text, id, q) {
+ const s = readState(text)
+ if (!s.type) return null
+ const plan = fourPlan(s)
+
+ if (id === 'place' && q.type === 'choice' && q.options?.length) {
+ const scores = q.options.map((opt) => stackScore(parseOption(String(q.descriptions?.[opt] ?? '')), plan, s))
+ const probs = spread(scores)
+ const probabilities = {}
+ q.options.forEach((opt, i) => (probabilities[opt] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: q.options[bi], confidence: probs[bi], probabilities }
+ }
+
+ if (id === 'danger' && q.type === 'score') {
+ const n = q.levels?.length || DANGER_LEVELS.length
+ const pos = Math.min(n - 1, Math.max(0, ((s.m.max - 4) / 13) * (n - 1) + Math.min(0.6, s.m.holes * 0.06)))
+ const raw = Array.from({ length: n }, (_, i) => Math.exp(-((i - pos) ** 2) / 0.55))
+ const sum = raw.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ raw.forEach((v, i) => (probabilities[String(i)] = v / sum))
+ const score = raw.reduce((acc, v, i) => acc + (v / sum) * i, 0)
+ return { type: 'score', score, confidence: Math.max(...raw) / sum, legend: q.legend, probabilities }
+ }
+
+ if (id === 'go_for_four' && q.type === 'noul') return { type: 'noul', noul: plan.p }
+ return null
+}
diff --git a/store/agents/jev-blocks/viewer/index.html b/store/agents/jev-blocks/viewer/index.html
new file mode 100644
index 000000000..30f944e4b
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/index.html
@@ -0,0 +1,71 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Blocks</title>
+<link rel="icon" href="data:,">
+<link rel="stylesheet" href="/base.css">
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1 id="title">Jev Blocks</h1><span class="sub">falling-blocks puzzle · synthetic game</span></div>
+ <div class="stats">
+ <div class="stat"><label>Lines</label><span id="sLines">0</span></div>
+ <div class="stat"><label>Lines / min</label><span id="sLpm">—</span></div>
+ <div class="stat hot"><label>Decisions / s</label><span id="sDps">—</span></div>
+ <div class="stat hot"><label>Cost so far</label><span id="sCost">$0</span></div>
+ <div class="stat"><label>Pieces</label><span id="sPieces">0</span></div>
+ <div class="stat"><label>Best</label><span id="sBest">0</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause" title="Space">Pause</button>
+ <button id="step" title="S — one decision at a time, so you can read Jev's mind">Step</button>
+ <button class="primary" id="reset">Reset</button>
+ </div>
+ </div>
+ <div id="cfgError" class="cfg-error hidden"></div>
+ <main>
+ <section id="stage">
+ <div class="canvas-wrap" id="wrap"><canvas id="scene"></canvas></div>
+ <div id="deck">
+ <div class="dial">
+ <label for="gravity">Gravity <b id="gravityVal">2.0</b><i>rows/s</i> <span id="pinTag" class="pill hidden">pinned</span></label>
+ <input id="gravity" type="range" min="0" max="1000" value="0" step="1">
+ <div class="ticks"><span>slow</span><span>Jev's limit now: <b id="kneeVal">46</b></span><span>brutal</span></div>
+ </div>
+ <div class="dial">
+ <label for="think">Think time <b id="thinkVal">110</b><i>ms per decision</i></label>
+ <input id="think" type="range" min="0" max="1000" value="0" step="1">
+ <div class="ticks"><span>30</span><span class="wide">what a slower model would cost</span><span>1000</span></div>
+ </div>
+ <div class="buttons">
+ <button id="garbage" title="G — push a garbage row up from the floor">Drop garbage</button>
+ <button id="mind" class="on" title="M — show every placement Jev weighed">Mind</button>
+ <button id="slow" title="Quarter speed, so you can watch the decision land">Slow-mo</button>
+ </div>
+ <div class="hint">Click a <b>column</b> to drop a junk block · click a <b>next piece</b> to change it · <b>Step</b> to read Jev's mind</div>
+ </div>
+ </section>
+ <aside id="rail">
+ <details class="panel" id="how" open>
+ <summary class="panel-title">How it works <span class="gist">one call per piece · the limit is time</span></summary>
+ <div class="how">
+ One call per piece. Jev gets <b>every legal placement</b> and answers <code>place</code>,
+ <code>danger</code> and <code>go_for_four</code> at once. The ghosts on the board are its
+ probabilities.
+ <b>The limit is time:</b> the piece keeps falling while Jev thinks and while it is moved,
+ one step at a time. Nothing is random. The game is made up.
+ </div>
+ </details>
+ <div class="panel grow">
+ <div class="panel-title">Game log <span class="right" id="logMeta"></span></div>
+ <ul id="log"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js" defer></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-blocks/viewer/jev-hud.js b/store/agents/jev-blocks/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-blocks/viewer/kit.mjs b/store/agents/jev-blocks/viewer/kit.mjs
new file mode 100644
index 000000000..f80d29b7d
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/kit.mjs
@@ -0,0 +1,112 @@
+// kit.mjs — the boring, security-relevant half of a Jev viewer, written once:
+// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
+// /control, plus an atomic verdict writer and a safe JSON config watcher.
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
+import { join, extname } from 'node:path'
+import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
+
+export const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+/** Deterministic PRNG so every run of a demo is reproducible. */
+export function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/**
+ * Serve a viewer.
+ * @param {object} o
+ * @param {string} o.here the viewer directory (static files live here)
+ * @param {number} o.port 0 = ephemeral
+ * @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
+ * @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
+ * @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ */
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+ const clients = new Set()
+ const allowed = new Set(files)
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ // Loopback only: a page on another origin (DNS rebinding) must not reach this server.
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ const path = url.pathname
+ try {
+ if (req.method === 'GET') {
+ const name = path === '/' ? 'index.html' : path.slice(1)
+ if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
+ if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (path === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
+ clients.add(res)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ }
+ if (req.method === 'POST' && path === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 65536) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const reply = control ? await control(String(j.cmd ?? ''), j) : null
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
+ res.writeHead(404); res.end('Not found')
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
+ }
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ clients,
+ /** Push a named SSE event (default 'state') to every connected pane. */
+ broadcast(obj, event = 'state') {
+ const line = `event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`
+ for (const c of clients) c.write(line)
+ },
+ async close() { for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+/** Atomic write of .harness/verdict.json (the harness reads this file; never edit it by hand). */
+export function writeVerdict(workspace, verdict) {
+ const dir = join(workspace, '.harness')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify({ spec: 1, ...verdict, updatedAt: new Date().toISOString() }))
+ renameSync(file + '.tmp', file)
+}
+
+/**
+ * Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
+ * good config and reports the parse error instead of crashing the demo.
+ * @returns {{ get(): object, error(): string|null, close(): void }}
+ */
+export function watchConfig(file, defaults, onChange) {
+ let cfg = { ...defaults }, err = null, timer = null
+ const load = () => {
+ try { cfg = { ...defaults, ...JSON.parse(readFileSync(file, 'utf8')) }; err = null }
+ catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
+ }
+ load()
+ let watcher = null
+ try {
+ watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ } catch { /* file may not exist yet; defaults stand */ }
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+}
diff --git a/store/agents/jev-blocks/viewer/studio.css b/store/agents/jev-blocks/viewer/studio.css
new file mode 100644
index 000000000..d870b5fa6
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/studio.css
@@ -0,0 +1,71 @@
+/* studio.css — Jev Blocks. Loads after base.css. */
+:root { --accent: #c084fc; --accent2: #7e22ce; }
+
+#topbar { gap: 26px; padding: 9px 18px; }
+.stats { gap: 26px; }
+.stat { min-width: 66px; }
+.stat span { font-size: 21px; line-height: 1.15; letter-spacing: -.2px; }
+.stat.hot span { color: var(--accent); text-shadow: 0 0 18px color-mix(in srgb, var(--accent) 45%, transparent); }
+.brand .sub { white-space: nowrap; }
+
+#stage { gap: 10px; padding: 12px 14px; overflow: hidden; }
+.canvas-wrap { min-height: 300px; background: #04050a; cursor: default; }
+.canvas-wrap.hot { cursor: pointer; }
+
+#deck {
+ flex: none; display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr) auto; column-gap: 22px; row-gap: 6px; align-items: end;
+ background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 14px 9px;
+}
+.dial { min-width: 0; }
+.dial label { display: flex; align-items: baseline; gap: 6px; font-size: 10px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); white-space: nowrap; }
+.dial label b { font-size: 17px; color: var(--ink); font-variant-numeric: tabular-nums; letter-spacing: 0; min-width: 3.2ch; text-align: right; }
+.dial label i { font-style: normal; text-transform: none; letter-spacing: 0; color: var(--faint); font-size: 11px; }
+.dial label .pill { margin-left: 4px; color: var(--accent); border-color: color-mix(in srgb, var(--accent) 55%, transparent); cursor: pointer; }
+.dial input[type=range] { width: 100%; margin: 5px 0 1px; height: 18px; }
+.dial .ticks { display: flex; justify-content: space-between; font-size: 10px; color: var(--faint); white-space: nowrap; gap: 8px; }
+.dial .ticks b { color: var(--warn); font-weight: 600; }
+.buttons { display: flex; gap: 8px; align-items: center; padding-bottom: 4px; }
+.buttons button { white-space: nowrap; }
+#garbage { border-color: color-mix(in srgb, var(--bad) 55%, transparent); color: var(--bad); }
+#garbage:hover { background: color-mix(in srgb, var(--bad) 14%, var(--panel2)); border-color: var(--bad); }
+.hint { grid-column: 1 / -1; font-size: 11.5px; color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.hint b { color: var(--ink); font-weight: 600; }
+
+#rail { gap: 12px; }
+#how summary { cursor: pointer; list-style: none; margin-bottom: 0; user-select: none; white-space: nowrap; }
+#how summary .gist { min-width: 0; flex: 0 1 auto; }
+#how summary::-webkit-details-marker { display: none; }
+#how summary::after { content: '+'; margin-left: auto; color: var(--faint); font-size: 13px; }
+#how .gist { text-transform: none; letter-spacing: 0; color: var(--faint); font-size: 10.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+#how[open] .gist { display: none; }
+#how[open] summary { margin-bottom: 9px; }
+#how[open] summary::after { content: '–'; }
+#how .how { font-size: 12px; line-height: 1.5; }
+.panel.grow { flex: 1; min-height: 150px; display: flex; flex-direction: column; }
+#log { list-style: none; margin: 0; padding: 0; overflow-y: auto; flex: 1; min-height: 0; font-size: 11.5px; line-height: 1.5; }
+#log li { display: flex; gap: 8px; padding: 3px 0; border-bottom: 1px dashed rgba(255,255,255,.04); color: var(--dim); }
+#log li .n { flex: none; width: 34px; text-align: right; color: var(--faint); font-variant-numeric: tabular-nums; }
+#log li.ok { color: var(--ink); }
+#log li.four { color: var(--cyan); font-weight: 700; }
+#log li.level { color: var(--accent); }
+#log li.warn { color: var(--warn); }
+#log li.bad { color: var(--bad); font-weight: 700; }
+#log li.you { color: var(--blue); }
+#log li.game { color: var(--ok); }
+#log li.fresh { animation: fresh .6s ease-out; }
+@keyframes fresh { from { background: color-mix(in srgb, var(--accent) 22%, transparent); } to { background: transparent; } }
+
+@media (max-width: 1180px) {
+ #topbar { gap: 16px; }
+ .stats { gap: 16px; }
+ .stat { min-width: 58px; }
+ .stat span { font-size: 18px; }
+ .brand .sub { display: none; }
+ #deck { column-gap: 14px; }
+ .dial .ticks .wide { display: none; }
+ #rail { width: 310px; }
+}
+@media (max-width: 900px) {
+ #deck { grid-template-columns: 1fr; }
+ .hint { white-space: normal; }
+}
diff --git a/store/agents/jev-blocks/viewer/studio.js b/store/agents/jev-blocks/viewer/studio.js
new file mode 100644
index 000000000..957ffe643
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/studio.js
@@ -0,0 +1,724 @@
+// studio.js — the Jev Blocks pane. Draws the well at 60 fps and eases between server frames, so the
+// piece falls and slides smoothly even though decisions arrive a few times a second. Jev's mind is
+// drawn ON the board: every placement it weighed is a ghost whose brightness is its probability.
+(() => {
+ 'use strict'
+ const $ = (id) => document.getElementById(id)
+ const wrap = $('wrap'), canvas = $('scene'), ctx = canvas.getContext('2d')
+ const W = 10, H = 20
+ const CODE = { I: 1, O: 2, T: 3, S: 4, Z: 5, J: 6, L: 7 }
+ const COLORS = { 1: '#22d3ee', 2: '#fde047', 3: '#c084fc', 4: '#4ade80', 5: '#fb7185', 6: '#60a5fa', 7: '#fb923c', 8: '#5b6680', 9: '#9aa6bf' }
+ const FONT = "ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace"
+ const FADE_MS = 420 // game ms for the mind overlay to fade once the piece starts to move
+
+ // ------------------------------------------------------------------ state
+ let S = null, shapes = null, mind = null, logLines = [], logSeq = -1
+ let lastSeq = -1, firstFrame = true
+ let board = new Array(W * H).fill(0), prevBoard = board
+ let showMind = true
+ let simBase = 0, simWall = performance.now()
+ let disp = null // the piece as drawn: { id, type, rot, x, y, pop }
+ let mindFade = { id: -1, start: null, born: 0 }
+ let drop = null, clearAnim = null, fallAnim = null, rise = null, sweep = null, flash = null, lockFlash = null, collapse = null, want = null
+ let junks = [], particles = [], texts = [], nextPulse = [0, 0, 0]
+ let shake = 0, intro = 0
+ let hover = { col: -1, next: -1 }
+ let L = null, sprites = null, dpr = 1
+ let dragging = { gravity: false, think: false }
+ let jevStats = { dps: 0, cost: 0 }
+ let last = performance.now()
+
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v))
+ const lerp = (a, b, t) => a + (b - a) * t
+ const easeOut = (t) => 1 - (1 - t) ** 3
+ const rate = () => (S && S.slow ? 0.25 : 1)
+ const simNow = () => simBase + (S && S.running && !S.finished ? (performance.now() - simWall) * rate() : 0)
+ const post = (body) => fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }).catch(() => {})
+ const cellsOf = (type, rot, x, y) => (shapes?.[type]?.[rot] ?? []).map(([dx, dy]) => [x + dx, y + dy])
+
+ // ------------------------------------------------------------------ frames from the server
+ function onFrame(f) {
+ if (f.shapes) shapes = f.shapes
+ if ('mind' in f) {
+ mind = f.mind
+ if (mind && mind.pieceId !== mindFade.id) mindFade = { id: mind.pieceId, start: null, born: performance.now(), seq: mind.seq }
+ else if (mind && mind.seq !== mindFade.seq) mindFade = { id: mind.pieceId, start: null, born: performance.now() - 200, seq: mind.seq }
+ }
+ if (f.log) logLines = f.log
+ const was = S
+ S = f
+ simBase = f.game.simMs; simWall = performance.now()
+ prevBoard = board
+ board = Array.from(f.game.board, Number)
+ const fresh = (f.events || []).filter((e) => e.seq > lastSeq)
+ if (firstFrame) { firstFrame = false; intro = performance.now() } else {
+ const locks = fresh.filter((e) => e.kind === 'lock').length
+ for (const e of fresh) onEvent(e, locks > 3 && e !== fresh[fresh.length - 1])
+ }
+ if (fresh.length) lastSeq = fresh[fresh.length - 1].seq
+ if (was && was.game.n !== f.game.n && !fresh.some((e) => e.kind === 'newgame')) resetAnims()
+ renderDom()
+ }
+
+ function resetAnims() { drop = clearAnim = fallAnim = rise = sweep = flash = lockFlash = collapse = want = null; junks = []; particles = []; texts = []; disp = null; shake = 0; intro = performance.now() }
+
+ function onEvent(e, quiet) {
+ const now = performance.now(), r = rate()
+ if (e.kind === 'newgame') return resetAnims()
+ if (e.kind === 'topout') return startCollapse()
+ if (quiet || !L) return
+ if (e.kind === 'lock') {
+ const cells = cellsOf(e.type, e.rot, e.x, e.y).filter(([, y]) => y >= 0)
+ const from = disp && disp.id === e.id ? { x: disp.x, y: disp.y } : { x: e.x, y: e.fromY }
+ const dist = Math.abs(e.x - from.x) * 14 + Math.abs(e.y - from.y) * 5
+ const dur = clamp(50 + dist, 70, 240) / r
+ drop = { type: e.type, rot: e.rot, x0: from.x, y0: Math.min(from.y, e.y), x1: e.x, y1: e.y, t0: now, dur, cells }
+ if (disp && disp.id === e.id) disp = null
+ lockFlash = { cells, t0: now + dur, dur: 190 / r, missed: e.missed, code: CODE[e.type] }
+ if (e.missed) {
+ texts.push({ text: 'TOO SLOW', x: e.x + 1.5, y: e.y, t0: now + dur, dur: 900 / r, color: '#fb7185', size: 0.62 })
+ want = e.want ? { type: e.type, ...e.want, t0: now, dur: 900 / r } : null
+ shake = Math.max(shake, 3)
+ }
+ if (e.cleared.length) {
+ const pre = prevBoard.slice()
+ for (const [x, y] of cells) pre[y * W + x] = CODE[e.type]
+ clearAnim = { rows: e.cleared, board: pre, t0: now + dur, dur: 210 / r, burst: false, gain: e.gain }
+ fallAnim = null
+ }
+ if (mindFade.id === e.id && mindFade.start == null) mindFade.start = simNow()
+ } else if (e.kind === 'levelup') {
+ sweep = { t0: now, dur: 750 / r, level: e.level, g: e.g }
+ } else if (e.kind === 'garbage') {
+ rise = { t0: now, dur: 170 / r }; shake = Math.max(shake, 5)
+ } else if (e.kind === 'junk') {
+ junks.push({ col: e.col, row: e.row, t0: now, dur: clamp(90 + e.row * 9, 100, 280) / r }); shake = Math.max(shake, 2)
+ } else if (e.kind === 'cycle') nextPulse[e.index] = now
+ }
+
+ function startCollapse() {
+ const now = performance.now(), blocks = []
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
+ const c = board[y * W + x]
+ if (c) blocks.push({ x, y, c, delay: 250 + (H - 1 - y) * 70 + Math.random() * 90, vx: (Math.random() - 0.5) * 4, vy: -1 - Math.random() * 3, rot: 0, vr: (Math.random() - 0.5) * 9, fx: x, fy: y })
+ }
+ collapse = { t0: now, blocks, last: now }
+ drop = clearAnim = fallAnim = lockFlash = null; disp = null
+ shake = 9
+ flash = { t0: now, dur: 380, color: '251,113,133', alpha: 0.4 }
+ }
+
+ // ------------------------------------------------------------------ layout and sprites
+ function layout() {
+ const w = wrap.clientWidth, h = wrap.clientHeight
+ dpr = Math.max(1, Math.min(2.5, window.devicePixelRatio || 1))
+ canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr)
+ const pad = 16, gap = 18, sideMin = 138
+ let cell = Math.floor((h - pad * 2) / H)
+ cell = Math.min(cell, Math.floor((w - pad * 2 - 2 * (sideMin + gap)) / W))
+ cell = Math.max(10, cell)
+ const wellW = cell * W, wellH = cell * H
+ const side = clamp(Math.floor((w - wellW - 2 * gap - 2 * pad) / 2), sideMin, 236)
+ const x0 = Math.round((w - (wellW + 2 * (side + gap))) / 2)
+ const y0 = Math.round((h - wellH) / 2)
+ L = { w, h, cell, u: clamp(cell / 30, 0.62, 1.25), well: { x: x0 + side + gap, y: y0, w: wellW, h: wellH }, left: { x: x0, y: y0, w: side, h: wellH }, right: { x: x0 + side + gap + wellW + gap, y: y0, w: side, h: wellH }, nextBoxes: [] }
+ sprites = makeSprites(cell)
+ }
+
+ function makeSprites(cell) {
+ const out = {}
+ const px = Math.round(cell * dpr)
+ for (const [code, color] of Object.entries(COLORS)) {
+ const c = document.createElement('canvas'); c.width = c.height = px
+ const g = c.getContext('2d'); g.scale(px / cell, px / cell)
+ const s = cell, b = Math.max(2, s * 0.17), r = s * 0.14, dull = code >= 8
+ g.save()
+ g.beginPath(); g.roundRect(0.5, 0.5, s - 1, s - 1, r); g.clip()
+ g.fillStyle = color; g.fillRect(0, 0, s, s)
+ const poly = (pts, fill) => { g.beginPath(); pts.forEach(([x, y], i) => (i ? g.lineTo(x, y) : g.moveTo(x, y))); g.closePath(); g.fillStyle = fill; g.fill() }
+ poly([[0, 0], [s, 0], [s - b, b], [b, b]], `rgba(255,255,255,${dull ? 0.22 : 0.5})`)
+ poly([[0, 0], [b, b], [b, s - b], [0, s]], `rgba(255,255,255,${dull ? 0.1 : 0.24})`)
+ poly([[s, 0], [s, s], [s - b, s - b], [s - b, b]], 'rgba(0,0,0,.26)')
+ poly([[0, s], [b, s - b], [s - b, s - b], [s, s]], 'rgba(0,0,0,.46)')
+ const face = g.createLinearGradient(b, b, s - b, s - b)
+ face.addColorStop(0, 'rgba(255,255,255,.22)'); face.addColorStop(0.5, 'rgba(255,255,255,0)'); face.addColorStop(1, 'rgba(0,0,0,.16)')
+ g.fillStyle = face; g.fillRect(b, b, s - 2 * b, s - 2 * b)
+ if (!dull) { g.fillStyle = 'rgba(255,255,255,.5)'; g.beginPath(); g.roundRect(b + s * 0.06, b + s * 0.06, s * 0.2, s * 0.09, s * 0.04); g.fill() }
+ if (code == 9) { g.strokeStyle = 'rgba(0,0,0,.4)'; g.lineWidth = Math.max(1.5, s * 0.08); g.beginPath(); g.moveTo(s * 0.34, s * 0.34); g.lineTo(s * 0.66, s * 0.66); g.moveTo(s * 0.66, s * 0.34); g.lineTo(s * 0.34, s * 0.66); g.stroke() }
+ g.restore()
+ // soft glow, drawn additively under the block
+ const gl = document.createElement('canvas'); const gs = Math.round(cell * 2.4 * dpr); gl.width = gl.height = gs
+ const gg = gl.getContext('2d'); const rad = gg.createRadialGradient(gs / 2, gs / 2, gs * 0.12, gs / 2, gs / 2, gs / 2)
+ rad.addColorStop(0, hexA(color, dull ? 0.1 : 0.34)); rad.addColorStop(1, hexA(color, 0))
+ gg.fillStyle = rad; gg.fillRect(0, 0, gs, gs)
+ out[code] = { body: c, glow: gl }
+ }
+ return out
+ }
+
+ function hexA(hex, a) { const n = parseInt(hex.slice(1), 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})` }
+
+ // ------------------------------------------------------------------ drawing helpers
+ const cx = (x) => L.well.x + x * L.cell
+ const cy = (y) => L.well.y + y * L.cell
+
+ function drawBlock(code, x, y, alpha = 1, glow = 1) {
+ const s = sprites[code]; if (!s) return
+ const c = L.cell, X = cx(x), Y = cy(y)
+ if (glow > 0) { ctx.globalCompositeOperation = 'lighter'; ctx.globalAlpha = alpha * glow; ctx.drawImage(s.glow, X - c * 0.7, Y - c * 0.7, c * 2.4, c * 2.4); ctx.globalCompositeOperation = 'source-over' }
+ ctx.globalAlpha = alpha
+ ctx.drawImage(s.body, X, Y, c, c)
+ ctx.globalAlpha = 1
+ }
+
+ /** Trace the outside edge of a set of cells (not one box per cell). */
+ function outline(cells, inset = 0) {
+ const has = new Set(cells.map(([x, y]) => x + ',' + y)), c = L.cell
+ ctx.beginPath()
+ for (const [x, y] of cells) {
+ const X = cx(x), Y = cy(y)
+ if (!has.has(x + ',' + (y - 1))) { ctx.moveTo(X + inset, Y + inset); ctx.lineTo(X + c - inset, Y + inset) }
+ if (!has.has(x + ',' + (y + 1))) { ctx.moveTo(X + inset, Y + c - inset); ctx.lineTo(X + c - inset, Y + c - inset) }
+ if (!has.has(x - 1 + ',' + y)) { ctx.moveTo(X + inset, Y + inset); ctx.lineTo(X + inset, Y + c - inset) }
+ if (!has.has(x + 1 + ',' + y)) { ctx.moveTo(X + c - inset, Y + inset); ctx.lineTo(X + c - inset, Y + c - inset) }
+ }
+ }
+
+ function text(str, x, y, size, color, align = 'left', weight = 600) {
+ ctx.font = `${weight} ${Math.round(size)}px ${FONT}`; ctx.fillStyle = color; ctx.textAlign = align; ctx.textBaseline = 'alphabetic'
+ ctx.fillText(str, x, y)
+ }
+
+ function card(x, y, w, h, title) {
+ ctx.fillStyle = 'rgba(15,17,26,.86)'; ctx.strokeStyle = '#232838'; ctx.lineWidth = 1
+ ctx.beginPath(); ctx.roundRect(x + 0.5, y + 0.5, w - 1, h - 1, 10); ctx.fill(); ctx.stroke()
+ if (title) text(title, x + 12, y + 19, 9.5, '#8b92aa', 'left', 600)
+ }
+
+ const fmt = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
+ const fmtMs = (ms) => (ms >= 10000 ? `${Math.round(ms / 1000)} s` : ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms)} ms`)
+
+ // ------------------------------------------------------------------ side panels
+ /** Split a panel into cards that fill its height. Returns [{ y, h, mid }] where mid is the centre under the title. */
+ function stackCards(p, natural, gapY = 10) {
+ const k = (p.h - gapY * (natural.length - 1)) / natural.reduce((a, b) => a + b, 0)
+ let y = p.y
+ return natural.map((n, i) => { const h = i === natural.length - 1 ? p.y + p.h - y : Math.round(n * k); const c = { y, h, mid: y + 24 + (h - 30) / 2 }; y += h + gapY; return c })
+ }
+
+ function drawLeft(now) {
+ const p = L.left, u = clamp(L.u, 0.8, 1.15), g = S.game
+ const [cScore, cStats, cDanger, cFour, cGrav] = stackCards(p, [72, 116, 100, 84, 132])
+ const bx = p.x + 12, bw = p.w - 24
+ // score
+ card(p.x, cScore.y, p.w, cScore.h, 'SCORE')
+ text(fmt(g.score), p.x + p.w - 14, cScore.mid + 12 * u, 28 * u, '#e9ecf5', 'right', 700)
+ // four small numbers
+ card(p.x, cStats.y, p.w, cStats.h)
+ const rowH = (cStats.h - 16) / 2
+ const cells = [['LEVEL', g.level], ['LINES', fmt(g.lines)], ['LINES/MIN', g.lpm ? g.lpm.toFixed(0) : '—'], ['PIECES', fmt(g.pieces)]]
+ cells.forEach(([k, v], i) => {
+ const X = bx + (i % 2) * (bw / 2 + 4), Y = cStats.y + 8 + Math.floor(i / 2) * rowH + rowH / 2
+ text(k, X, Y - 9 * u, 9, '#8b92aa'); text(String(v), X, Y + 15 * u, 20 * u, i === 0 ? '#c084fc' : '#e9ecf5', 'left', 700)
+ })
+ // danger meter
+ const d = S.danger, ds = d ? clamp(d.score / 3, 0, 1) : 0
+ card(p.x, cDanger.y, p.w, cDanger.h, 'DANGER')
+ const by = cDanger.mid - 16 * u, bh = 12
+ const segs = ['#34d399', '#fbbf24', '#fb923c', '#fb7185']
+ segs.forEach((col, i) => { const on = ds * 3 >= i - 0.5; ctx.fillStyle = hexA(col, on ? 0.95 : 0.16); ctx.beginPath(); ctx.roundRect(bx + i * (bw / 4) + 1, by, bw / 4 - 2, bh, 3); ctx.fill() })
+ const nx = bx + ds * bw, pulse = ds > 0.6 ? 0.6 + 0.4 * Math.sin(now / 110) : 1
+ ctx.fillStyle = `rgba(255,255,255,${pulse})`; ctx.shadowColor = '#fff'; ctx.shadowBlur = 8
+ ctx.beginPath(); ctx.roundRect(clamp(nx - 2, bx, bx + bw - 4), by - 5, 4, bh + 10, 2); ctx.fill(); ctx.shadowBlur = 0
+ text(d ? d.label : 'waiting', bx, by + bh + 25 * u, 16 * u, d ? segs[clamp(Math.round(d.score), 0, 3)] : '#565d75', 'left', 700)
+ text(d ? `${d.score.toFixed(2)} / 3` : '', bx + bw, by + bh + 25 * u, 11, '#8b92aa', 'right')
+ // going for four
+ const f = S.four ?? 0, on = f >= 0.5
+ card(p.x, cFour.y, p.w, cFour.h, 'GOING FOR FOUR')
+ const lr = 12 * u, lx = bx + lr + 4, ly = cFour.mid + 2
+ if (on) { const a = 0.55 + 0.25 * Math.sin(now / 260); const rg = ctx.createRadialGradient(lx, ly, 2, lx, ly, lr * 2.6); rg.addColorStop(0, `rgba(94,234,212,${a})`); rg.addColorStop(1, 'rgba(94,234,212,0)'); ctx.fillStyle = rg; ctx.fillRect(lx - lr * 3, ly - lr * 3, lr * 6, lr * 6) }
+ ctx.beginPath(); ctx.arc(lx, ly, lr, 0, 7); ctx.fillStyle = on ? '#5eead4' : '#141824'; ctx.fill(); ctx.strokeStyle = on ? '#a7f3e4' : '#2e3550'; ctx.lineWidth = 2; ctx.stroke()
+ text(S.four == null ? '—' : on ? 'YES' : 'no', lx + lr + 12, ly + 1, 17 * u, on ? '#5eead4' : '#8b92aa', 'left', 700)
+ text(S.four == null ? '' : `p ${f.toFixed(2)}`, bx + bw, ly + 1, 11, '#8b92aa', 'right')
+ text(on ? 'keeping a column open' : 'clearing what it can', lx + lr + 12, ly + 16 * u, 9.5, '#565d75')
+ // gravity
+ card(p.x, cGrav.y, p.w, cGrav.h, 'GRAVITY')
+ const gy = cGrav.mid - 12 * u
+ text(g.gravity.toFixed(1), bx, gy + 4 * u, 26 * u, '#e9ecf5', 'left', 700)
+ const gw = ctx.measureText(g.gravity.toFixed(1)).width
+ text('rows/s', bx + gw + 6, gy + 4 * u, 10.5, '#8b92aa')
+ text(S.cfg.pinned ? 'pinned by you' : `level ${g.level} · +${Math.round(S.cfg.speedup * 100)}% a level`, bx, gy + 22 * u, 9.5, S.cfg.pinned ? '#c084fc' : '#565d75')
+ const ty = gy + 36 * u, lo = Math.log(0.2), hi = Math.log(S.cfg.maxGravity || 120)
+ const at = (v) => bx + ((Math.log(clamp(v, 0.2, 120)) - lo) / (hi - lo)) * bw
+ ctx.fillStyle = 'rgba(255,255,255,.06)'; ctx.beginPath(); ctx.roundRect(bx, ty, bw, 6, 3); ctx.fill()
+ const grad = ctx.createLinearGradient(bx, 0, bx + bw, 0); grad.addColorStop(0, '#7e22ce'); grad.addColorStop(0.75, '#c084fc'); grad.addColorStop(1, '#fb7185')
+ ctx.fillStyle = grad; ctx.beginPath(); ctx.roundRect(bx, ty, Math.max(4, at(g.gravity) - bx), 6, 3); ctx.fill()
+ const kx = at(knee()); ctx.fillStyle = '#fbbf24'; ctx.fillRect(kx - 1, ty - 5, 2, 16)
+ text(`Jev's limit ${Math.round(knee())}`, clamp(kx, bx + 40, bx + bw - 40), ty + 25, 9.5, '#fbbf24', 'center')
+ }
+
+ /** Rows per second at which a wall placement no longer fits in the fall, for the stack as it is now. */
+ function knee() {
+ const free = Math.max(2, 18 - (S.game.maxHeight || 0))
+ return free / ((S.cfg.decisionMs + 6 * S.cfg.moveMs) / 1000)
+ }
+
+ function drawMini(type, bx, by, bw, bh, alpha = 1) {
+ const sh = shapes?.[type]?.[0]; if (!sh) return
+ let x0 = 9, x1 = 0, y0 = 9, y1 = 0
+ for (const [x, y] of sh) { x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y) }
+ const m = Math.min(L.cell * 0.72, (bw - 20) / 4, (bh - 14) / 2)
+ const ox = bx + (bw - (x1 - x0 + 1) * m) / 2, oy = by + (bh - (y1 - y0 + 1) * m) / 2
+ const s = sprites[CODE[type]]
+ for (const [x, y] of sh) {
+ const X = ox + (x - x0) * m, Y = oy + (y - y0) * m
+ ctx.globalCompositeOperation = 'lighter'; ctx.globalAlpha = 0.7 * alpha; ctx.drawImage(s.glow, X - m * 0.7, Y - m * 0.7, m * 2.4, m * 2.4)
+ ctx.globalCompositeOperation = 'source-over'; ctx.globalAlpha = alpha; ctx.drawImage(s.body, X, Y, m, m)
+ }
+ ctx.globalAlpha = 1
+ }
+
+ function drawRight(now) {
+ const p = L.right, u = clamp(L.u, 0.8, 1.15), g = S.game
+ const [cNext, cTime, cGame, cSess] = stackCards(p, [236, 116, 80, 100])
+ const bx = p.x + 12, bw = p.w - 24
+ card(p.x, cNext.y, p.w, cNext.h, 'NEXT')
+ text('click to change', p.x + p.w - 12, cNext.y + 19, 9, '#565d75', 'right')
+ const boxH = (cNext.h - 28 - 10 - 14) / 3
+ L.nextBoxes = []
+ g.queue.forEach((t, i) => {
+ const x = p.x + 10, y = cNext.y + 28 + i * (boxH + 7), w = p.w - 20
+ const hot = hover.next === i, pulse = clamp(1 - (now - nextPulse[i]) / 380, 0, 1)
+ ctx.fillStyle = hot ? 'rgba(192,132,252,.12)' : 'rgba(255,255,255,.025)'; ctx.strokeStyle = hot || pulse ? hexA('#c084fc', 0.5 + 0.5 * pulse) : '#232838'; ctx.lineWidth = 1 + pulse * 1.5
+ ctx.beginPath(); ctx.roundRect(x + 0.5, y + 0.5, w - 1, boxH - 1, 8); ctx.fill(); ctx.stroke()
+ drawMini(t, x, y, w, boxH, i === 0 ? 1 : 0.8)
+ text(String(i + 1), x + 8, y + 15, 9, '#565d75')
+ L.nextBoxes.push({ x, y, w, h: boxH })
+ })
+ // time budget: the honest limit
+ card(p.x, cTime.y, p.w, cTime.h, 'TIME BUDGET')
+ if (mind) {
+ const need = mind.needMs, have = mind.haveMs, late = need > have
+ const max = Math.max(need * 1.6, Math.min(have, need * 3), 1)
+ const by = cTime.mid - 30
+ text('needs', bx, by + 1, 9.5, '#8b92aa'); text(fmtMs(need), bx + bw, by + 1, 11.5, '#e9ecf5', 'right', 700)
+ ctx.fillStyle = 'rgba(255,255,255,.06)'; ctx.beginPath(); ctx.roundRect(bx, by + 6, bw, 7, 3); ctx.fill()
+ const dw = Math.min(bw, (S.cfg.decisionMs / max) * bw), nw = Math.min(bw, (need / max) * bw)
+ ctx.fillStyle = '#c084fc'; ctx.beginPath(); ctx.roundRect(bx, by + 6, dw, 7, 3); ctx.fill()
+ ctx.fillStyle = '#60a5fa'; ctx.fillRect(bx + dw + 1, by + 6, Math.max(0, nw - dw - 1), 7)
+ text('has', bx, by + 32, 9.5, '#8b92aa'); text(fmtMs(have), bx + bw, by + 32, 11.5, late ? '#fb7185' : '#34d399', 'right', 700)
+ ctx.fillStyle = 'rgba(255,255,255,.06)'; ctx.beginPath(); ctx.roundRect(bx, by + 37, bw, 7, 3); ctx.fill()
+ ctx.fillStyle = late ? '#fb7185' : '#34d399'; ctx.beginPath(); ctx.roundRect(bx, by + 37, clamp((have / max) * bw, 3, bw), 7, 3); ctx.fill()
+ text(late ? 'the piece lands first' : 'think', bx, by + 60, 9, late ? '#fb7185' : '#c084fc')
+ if (!late) { const tw = ctx.measureText('think').width; text('+ moves, before it lands', bx + tw + 6, by + 60, 9, '#60a5fa') }
+ } else text('waiting for a piece', bx, cTime.mid, 10, '#565d75')
+ // this game
+ card(p.x, cGame.y, p.w, cGame.h, 'THIS GAME')
+ const cols = [['MISSED', g.misses, g.misses ? '#fb7185' : '#e9ecf5'], ['FOURS', g.fours, g.fours ? '#5eead4' : '#e9ecf5'], ['HOLES', g.holes, g.holes > 4 ? '#fbbf24' : '#e9ecf5']]
+ cols.forEach(([k, v, col], i) => { const X = bx + i * (bw / 3); text(k, X, cGame.mid - 6 * u, 8.5, '#8b92aa'); text(String(v), X, cGame.mid + 16 * u, 18 * u, col, 'left', 700) })
+ // session
+ card(p.x, cSess.y, p.w, cSess.h, 'SESSION')
+ const best = Math.max(S.session.best, g.lines), sy = cSess.mid - 14
+ text(`game ${g.n}`, bx, sy, 12, '#e9ecf5', 'left', 700); text(`${S.session.topOuts} top-out${S.session.topOuts === 1 ? '' : 's'}`, bx + bw, sy, 10.5, S.session.topOuts ? '#fb7185' : '#8b92aa', 'right')
+ text('best', bx, sy + 20, 9.5, '#8b92aa'); text(`${fmt(best)} lines`, bx + bw, sy + 20, 12, '#c084fc', 'right', 700)
+ text('client', bx, sy + 40, 9.5, '#8b92aa'); text(S.client === 'typesafe' ? 'LIVE Jev' : 'offline MOCK', bx + bw, sy + 40, 10.5, S.client === 'typesafe' ? '#34d399' : '#fbbf24', 'right', 700)
+ }
+
+ // ------------------------------------------------------------------ the well
+ function drawWell(now, dt) {
+ const w = L.well, c = L.cell
+ const danger = S.danger ? clamp(S.danger.score / 3, 0, 1) : 0
+ const hot = clamp((danger - 0.45) * 2, 0, 1)
+ // ambient light behind the well
+ const amb = ctx.createRadialGradient(w.x + w.w / 2, w.y + w.h * 0.55, 20, w.x + w.w / 2, w.y + w.h * 0.55, w.h * 0.85)
+ const pulse = hot > 0.3 ? 0.75 + 0.25 * Math.sin(now / 170) : 1
+ amb.addColorStop(0, `rgba(${Math.round(lerp(126, 225, hot))},${Math.round(lerp(34, 29, hot))},${Math.round(lerp(206, 72, hot))},${(0.2 + hot * 0.16) * pulse})`); amb.addColorStop(1, 'rgba(0,0,0,0)')
+ ctx.fillStyle = amb; ctx.fillRect(0, 0, L.w, L.h)
+
+ ctx.save()
+ if (shake > 0.2) ctx.translate(Math.sin(now / 17) * shake, Math.cos(now / 13) * shake * 0.7)
+ // frame
+ const edge = `rgb(${Math.round(lerp(192, 251, hot))},${Math.round(lerp(132, 113, hot))},${Math.round(lerp(252, 133, hot))})`
+ ctx.shadowColor = edge; ctx.shadowBlur = 26 * pulse; ctx.strokeStyle = edge; ctx.lineWidth = 2
+ ctx.beginPath(); ctx.roundRect(w.x - 5, w.y - 5, w.w + 10, w.h + 10, 8); ctx.stroke(); ctx.shadowBlur = 0
+ ctx.fillStyle = '#060710'; ctx.beginPath(); ctx.roundRect(w.x - 4, w.y - 4, w.w + 8, w.h + 8, 7); ctx.fill()
+ ctx.beginPath(); ctx.rect(w.x, w.y, w.w, w.h); ctx.clip()
+ const bg = ctx.createLinearGradient(0, w.y, 0, w.y + w.h); bg.addColorStop(0, '#0a0b16'); bg.addColorStop(1, '#0d0a1a')
+ ctx.fillStyle = bg; ctx.fillRect(w.x, w.y, w.w, w.h)
+ // grid
+ ctx.strokeStyle = 'rgba(255,255,255,.045)'; ctx.lineWidth = 1; ctx.beginPath()
+ for (let x = 1; x < W; x++) { ctx.moveTo(cx(x) + 0.5, w.y); ctx.lineTo(cx(x) + 0.5, w.y + w.h) }
+ for (let y = 1; y < H; y++) { ctx.moveTo(w.x, cy(y) + 0.5); ctx.lineTo(w.x + w.w, cy(y) + 0.5) }
+ ctx.stroke()
+ // hover column
+ if (hover.col >= 0 && !S.finished) {
+ const hg = ctx.createLinearGradient(0, w.y, 0, w.y + w.h); hg.addColorStop(0, 'rgba(154,166,191,.2)'); hg.addColorStop(1, 'rgba(154,166,191,.03)')
+ ctx.fillStyle = hg; ctx.fillRect(cx(hover.col), w.y, c, w.h)
+ let top = 0; while (top < H && !board[top * W + hover.col]) top++
+ if (top > 0) drawBlock(9, hover.col, top - 1, 0.5 + 0.2 * Math.sin(now / 160), 0)
+ }
+
+ if (collapse) drawCollapse(now, dt)
+ else {
+ drawBoard(now)
+ if (showMind) drawMind(now)
+ drawPiece(now, dt)
+ drawDrop(now)
+ drawJunks(now)
+ drawFlashes(now)
+ }
+ drawSweep(now)
+ drawParticles(dt)
+ drawTexts(now)
+ if (flash) { const t = (now - flash.t0) / flash.dur; if (t >= 1) flash = null; else if (t >= 0) { ctx.fillStyle = `rgba(${flash.color},${flash.alpha * (1 - t)})`; ctx.fillRect(w.x, w.y, w.w, w.h) } }
+ const iv = clamp((now - intro) / 450, 0, 1); if (iv < 1) { ctx.fillStyle = `rgba(6,7,16,${1 - iv})`; ctx.fillRect(w.x, w.y, w.w, w.h) }
+ ctx.restore()
+ if (S.finished) drawBanner(now)
+ }
+
+ function drawBoard(now) {
+ let src = board, rowShift = null, flashRows = null, ft = 0
+ if (clearAnim) {
+ const t = (now - clearAnim.t0) / clearAnim.dur
+ if (t >= 1) {
+ const map = new Array(H).fill(0); let cnt = 0
+ for (let y = H - 1; y >= 0; y--) { if (clearAnim.rows.includes(y)) cnt++; else if (y + cnt < H) map[y + cnt] = cnt }
+ fallAnim = { map, t0: now, dur: 150 / rate() }; clearAnim = null
+ } else { src = clearAnim.board; if (t >= 0) { flashRows = clearAnim.rows; ft = t; if (!clearAnim.burst) { clearAnim.burst = true; burst(clearAnim) } } }
+ }
+ if (fallAnim) { const t = (now - fallAnim.t0) / fallAnim.dur; if (t >= 1) fallAnim = null; else rowShift = fallAnim.map.map((k) => -k * (1 - easeOut(clamp(t, 0, 1)))) }
+ let lift = 0
+ if (rise) { const t = (now - rise.t0) / rise.dur; if (t >= 1) rise = null; else lift = 1 - easeOut(t) }
+ const hide = new Set()
+ if (drop) for (const [x, y] of drop.cells) hide.add(y * W + x)
+ for (const j of junks) hide.add(j.row * W + j.col)
+ for (let pass = 0; pass < 2; pass++) {
+ for (let y = 0; y < H; y++) {
+ const dy = (rowShift ? rowShift[y] : 0) + lift
+ for (let x = 0; x < W; x++) {
+ const code = src[y * W + x]
+ if (!code || hide.has(y * W + x)) continue
+ if (flashRows && flashRows.includes(y) && Math.abs(x - 4.5) < ft * 6.5) continue // wiped from the middle out
+ const s = sprites[code], X = cx(x), Y = cy(y + dy), c = L.cell
+ if (pass === 0) { ctx.globalCompositeOperation = 'lighter'; ctx.globalAlpha = 0.85; ctx.drawImage(s.glow, X - c * 0.7, Y - c * 0.7, c * 2.4, c * 2.4); ctx.globalCompositeOperation = 'source-over'; ctx.globalAlpha = 1 } else ctx.drawImage(s.body, X, Y, c, c)
+ }
+ }
+ }
+ if (flashRows) {
+ const w = L.well, c = L.cell
+ for (const y of flashRows) {
+ const half = clamp(ft * 6.5, 0, 5) * c, mid = w.x + w.w / 2
+ ctx.globalCompositeOperation = 'lighter'
+ const g = ctx.createLinearGradient(mid - half - c, 0, mid + half + c, 0)
+ g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.15, `rgba(255,255,255,${0.95 * (1 - ft * 0.5)})`); g.addColorStop(0.85, `rgba(255,255,255,${0.95 * (1 - ft * 0.5)})`); g.addColorStop(1, 'rgba(255,255,255,0)')
+ ctx.fillStyle = g; ctx.fillRect(mid - half - c, cy(y) + c * 0.12, 2 * (half + c), c * 0.76)
+ ctx.globalCompositeOperation = 'source-over'
+ }
+ }
+ }
+
+ function burst(a) {
+ const n = a.rows.length, c = L.cell
+ shake = Math.max(shake, [0, 3, 5, 7, 13][n] || 4)
+ if (n === 4) flash = { t0: performance.now(), dur: 420, color: '255,255,255', alpha: 0.5 }
+ for (const y of a.rows) for (let x = 0; x < W; x++) {
+ const code = a.board[y * W + x] || 8
+ for (let k = 0; k < (n === 4 ? 5 : 3); k++) {
+ const ang = Math.random() * Math.PI * 2, sp = (60 + Math.random() * 260) * (n === 4 ? 1.5 : 1)
+ particles.push({ x: cx(x) + c / 2, y: cy(y) + c / 2, vx: Math.cos(ang) * sp + (x - 4.5) * 22, vy: Math.sin(ang) * sp - 120, life: 0, max: 0.45 + Math.random() * 0.55, color: COLORS[code], size: c * (0.1 + Math.random() * 0.16) })
+ }
+ }
+ const mid = a.rows.reduce((s, y) => s + y, 0) / n
+ texts.push({ text: n === 4 ? 'FOUR!' : ['', 'SINGLE', 'DOUBLE', 'TRIPLE'][n], x: 5, y: mid + 0.5, t0: performance.now(), dur: n === 4 ? 1200 : 750, color: n === 4 ? '#5eead4' : '#e9ecf5', size: n === 4 ? 1.7 : 0.8, center: true, grow: n === 4 })
+ if (a.gain) texts.push({ text: '+' + fmt(a.gain), x: 5, y: mid + (n === 4 ? 2.1 : 1.5), t0: performance.now() + 60, dur: 900, color: '#c084fc', size: 0.66, center: true })
+ if (particles.length > 900) particles.splice(0, particles.length - 900)
+ }
+
+ function drawMind(now) {
+ if (!mind || !shapes) return
+ if (mindFade.id !== mind.pieceId) return
+ const P = S.piece
+ if (mindFade.start == null && P && P.id === mind.pieceId && P.moved > 0) mindFade.start = simNow()
+ if (mindFade.start == null && (!P || P.id !== mind.pieceId)) mindFade.start = simNow()
+ let a = clamp((now - mindFade.born) / 90, 0, 1)
+ if (mindFade.start != null) { const e = simNow() - mindFade.start; a *= e < 0 ? 0 : clamp(1 - e / FADE_MS, 0, 1) }
+ if (a <= 0.01) return
+ const code = CODE[mind.type], color = COLORS[code], c = L.cell
+ // every placement, as light. Overlaps add up, so the surface glows where Jev's belief is.
+ ctx.globalCompositeOperation = 'lighter'
+ for (const k of mind.cands) {
+ const al = a * Math.min(0.62, Math.pow(k.p, 0.85) * 0.8 + 0.012)
+ if (al < 0.006) continue
+ ctx.fillStyle = hexA(color, al)
+ for (const [x, y] of cellsOf(mind.type, k.r, k.x, k.y)) if (y >= 0) { ctx.beginPath(); ctx.roundRect(cx(x) + 1.5, cy(y) + 1.5, c - 3, c - 3, c * 0.14); ctx.fill() }
+ }
+ ctx.globalCompositeOperation = 'source-over'
+ // the top three, outlined and labelled
+ const top = mind.cands.slice(0, 3).filter((k) => k.p >= 0.02)
+ const placed = []
+ top.slice().reverse().forEach((k) => {
+ const chosen = k.id === mind.chosen
+ const cells = cellsOf(mind.type, k.r, k.x, k.y).filter(([, y]) => y >= 0)
+ if (chosen) {
+ const xs = cells.map(([x]) => x), x0 = Math.min(...xs), x1 = Math.max(...xs), yTop = Math.min(...cells.map(([, y]) => y))
+ const beam = ctx.createLinearGradient(0, L.well.y, 0, cy(yTop)); beam.addColorStop(0, hexA(color, 0)); beam.addColorStop(1, hexA(color, 0.16 * a * (0.4 + mind.confidence)))
+ ctx.fillStyle = beam; ctx.fillRect(cx(x0), L.well.y, (x1 - x0 + 1) * c, cy(yTop) - L.well.y)
+ }
+ outline(cells, chosen ? 1 : 2.5)
+ ctx.lineCap = 'round'
+ if (chosen) { ctx.shadowColor = '#fff'; ctx.shadowBlur = 14 * (0.5 + mind.confidence); ctx.strokeStyle = `rgba(255,255,255,${0.95 * a})`; ctx.lineWidth = 2.4 } else { ctx.strokeStyle = hexA(color, 0.75 * a); ctx.lineWidth = 1.4; ctx.setLineDash([4, 4]) }
+ ctx.stroke(); ctx.shadowBlur = 0; ctx.setLineDash([])
+ })
+ top.forEach((k) => {
+ const chosen = k.id === mind.chosen
+ const cells = cellsOf(mind.type, k.r, k.x, k.y).filter(([, y]) => y >= 0); if (!cells.length) return
+ const xs = cells.map(([x]) => x), ys = cells.map(([, y]) => y)
+ const label = `${Math.round(k.p * 100)}%`
+ const fs = Math.max(10, c * (chosen ? 0.5 : 0.42))
+ ctx.font = `700 ${Math.round(fs)}px ${FONT}`
+ const tw = ctx.measureText(label).width + fs * 0.9, th = fs * 1.5
+ let bx = clamp(cx((Math.min(...xs) + Math.max(...xs) + 1) / 2) - tw / 2, L.well.x + 2, L.well.x + L.well.w - tw - 2)
+ let by = cy(Math.min(...ys)) - th - 5
+ for (let guard = 0; guard < 8 && placed.some((r) => bx < r.x + r.w + 3 && bx + tw + 3 > r.x && by < r.y + r.h + 2 && by + th + 2 > r.y); guard++) by -= th + 3
+ by = Math.max(L.well.y + 2, by)
+ placed.push({ x: bx, y: by, w: tw, h: th })
+ ctx.globalAlpha = a
+ ctx.fillStyle = chosen ? '#ffffff' : 'rgba(10,11,20,.88)'; ctx.strokeStyle = chosen ? '#ffffff' : hexA(color, 0.9); ctx.lineWidth = 1.2
+ ctx.beginPath(); ctx.roundRect(bx, by, tw, th, th / 2); ctx.fill(); ctx.stroke()
+ ctx.fillStyle = chosen ? '#0b0d14' : color; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(label, bx + tw / 2, by + th / 2 + 0.5)
+ ctx.globalAlpha = 1
+ })
+ }
+
+ function drawPiece(now, dt) {
+ const P = S.piece
+ if (!P || !shapes) { if (!drop) disp = null; return }
+ const r = rate()
+ if (!disp || disp.id !== P.id) disp = { id: P.id, type: P.type, rot: P.rot, x: P.x, y: P.y + P.frac, pop: 1 }
+ const live = S.running ? 1 : 3
+ disp.x += (P.x - disp.x) * (1 - Math.exp((-dt * 1000 * r * live) / 30))
+ const ty = P.y + P.frac
+ if (ty < disp.y - 0.05 || ty - disp.y > 6) disp.y = ty; else disp.y += (ty - disp.y) * (1 - Math.exp((-dt * 1000 * r * live) / 38))
+ if (disp.rot !== P.rot) { disp.rot = P.rot; disp.pop = 1 }
+ disp.pop = Math.max(0, disp.pop - dt * 7 * r)
+ const code = CODE[P.type]
+ // where it would land from here
+ const ghost = cellsOf(P.type, P.rot, P.x, P.ghostY).filter(([, y]) => y >= 0)
+ if (ghost.length && P.ghostY - disp.y > 0.6) { outline(ghost, 2); ctx.strokeStyle = hexA(COLORS[code], 0.55); ctx.lineWidth = 1.5; ctx.stroke(); ctx.fillStyle = hexA(COLORS[code], 0.07); for (const [x, y] of ghost) ctx.fillRect(cx(x) + 2, cy(y) + 2, L.cell - 4, L.cell - 4) }
+ const cells = cellsOf(P.type, disp.rot, disp.x, disp.y)
+ for (const [x, y] of cells) drawBlock(code, x, y, 1, 1.5 + disp.pop)
+ if (P.phase === 'think') { // Jev is thinking: a soft ring of light on the piece
+ const mx = cells.reduce((s, q) => s + q[0], 0) / cells.length + 0.5, my = cells.reduce((s, q) => s + q[1], 0) / cells.length + 0.5
+ const rr = L.cell * (1.6 + 0.25 * Math.sin(now / 60))
+ const g = ctx.createRadialGradient(cx(mx), cy(my), rr * 0.3, cx(mx), cy(my), rr); g.addColorStop(0, 'rgba(255,255,255,.0)'); g.addColorStop(0.8, 'rgba(255,255,255,.14)'); g.addColorStop(1, 'rgba(255,255,255,0)')
+ ctx.globalCompositeOperation = 'lighter'; ctx.fillStyle = g; ctx.fillRect(cx(mx) - rr, cy(my) - rr, rr * 2, rr * 2); ctx.globalCompositeOperation = 'source-over'
+ }
+ }
+
+ function drawDrop(now) {
+ if (!drop) return
+ const t = (now - drop.t0) / drop.dur
+ if (t >= 1) { dust(drop); drop = null; return }
+ const e = clamp(t, 0, 1), ex = easeOut(clamp(e / 0.55, 0, 1)), ey = e * e
+ const x = lerp(drop.x0, drop.x1, ex), y = lerp(drop.y0, drop.y1, ey)
+ const code = CODE[drop.type], c = L.cell
+ // streak of light behind the falling piece
+ for (const [px, py] of cellsOf(drop.type, drop.rot, x, y)) {
+ const len = Math.min(py - drop.y0 + 1, 7) * c * ey
+ if (len > 2) { const g = ctx.createLinearGradient(0, cy(py) - len, 0, cy(py) + c * 0.5); g.addColorStop(0, hexA(COLORS[code], 0)); g.addColorStop(1, hexA(COLORS[code], 0.5)); ctx.globalCompositeOperation = 'lighter'; ctx.fillStyle = g; ctx.fillRect(cx(px) + 2, cy(py) - len, c - 4, len + c * 0.5); ctx.globalCompositeOperation = 'source-over' }
+ }
+ for (const [px, py] of cellsOf(drop.type, drop.rot, x, y)) drawBlock(code, px, py, 1, 2)
+ }
+
+ function dust(d) {
+ const c = L.cell, code = CODE[d.type]
+ const bottoms = new Map()
+ for (const [x, y] of d.cells) bottoms.set(x, Math.max(bottoms.get(x) ?? -1, y))
+ for (const [x, y] of bottoms) for (let k = 0; k < 3; k++) particles.push({ x: cx(x) + Math.random() * c, y: cy(y + 1) - 2, vx: (Math.random() - 0.5) * 160, vy: -30 - Math.random() * 110, life: 0, max: 0.25 + Math.random() * 0.3, color: COLORS[code], size: c * (0.06 + Math.random() * 0.08) })
+ shake = Math.max(shake, 1.6)
+ }
+
+ function drawJunks(now) {
+ junks = junks.filter((j) => now - j.t0 < j.dur)
+ for (const j of junks) {
+ const t = clamp((now - j.t0) / j.dur, 0, 1), y = lerp(-1, j.row, t * t), c = L.cell
+ const g = ctx.createLinearGradient(0, cy(y) - c * 4, 0, cy(y) + c); g.addColorStop(0, 'rgba(154,166,191,0)'); g.addColorStop(1, 'rgba(154,166,191,.45)')
+ ctx.fillStyle = g; ctx.fillRect(cx(j.col) + 3, cy(y) - c * 4, c - 6, c * 4.5)
+ drawBlock(9, j.col, y, 1, 1)
+ }
+ }
+
+ function drawFlashes(now) {
+ if (lockFlash) {
+ const t = (now - lockFlash.t0) / lockFlash.dur
+ if (t >= 1) lockFlash = null
+ else if (t >= 0) { ctx.globalCompositeOperation = 'lighter'; ctx.fillStyle = lockFlash.missed ? `rgba(251,113,133,${0.85 * (1 - t)})` : `rgba(255,255,255,${0.6 * (1 - t)})`; for (const [x, y] of lockFlash.cells) { ctx.beginPath(); ctx.roundRect(cx(x) + 1, cy(y) + 1, L.cell - 2, L.cell - 2, L.cell * 0.14); ctx.fill() } ctx.globalCompositeOperation = 'source-over' }
+ }
+ if (want) {
+ const t = (now - want.t0) / want.dur
+ if (t >= 1) want = null
+ else { const cells = cellsOf(want.type, want.rot, want.x, want.y).filter(([, y]) => y >= 0); outline(cells, 2); ctx.setLineDash([5, 4]); ctx.strokeStyle = `rgba(251,113,133,${0.95 * (1 - t * t)})`; ctx.lineWidth = 2; ctx.stroke(); ctx.setLineDash([]) }
+ }
+ }
+
+ function drawSweep(now) {
+ if (!sweep) return
+ const t = (now - sweep.t0) / sweep.dur
+ if (t >= 1) { sweep = null; return }
+ const w = L.well, y = w.y + w.h * (1 - easeOut(t)), bandH = L.cell * 3
+ const g = ctx.createLinearGradient(0, y - bandH, 0, y + bandH); g.addColorStop(0, 'rgba(192,132,252,0)'); g.addColorStop(0.5, `rgba(216,180,254,${0.55 * (1 - t)})`); g.addColorStop(1, 'rgba(192,132,252,0)')
+ ctx.globalCompositeOperation = 'lighter'; ctx.fillStyle = g; ctx.fillRect(w.x, y - bandH, w.w, bandH * 2); ctx.globalCompositeOperation = 'source-over'
+ const a = t < 0.15 ? t / 0.15 : 1 - (t - 0.15) / 0.85
+ ctx.globalAlpha = clamp(a, 0, 1)
+ ctx.shadowColor = '#c084fc'; ctx.shadowBlur = 18
+ text(`LEVEL ${sweep.level}`, w.x + w.w / 2, w.y + L.cell * 4.2, L.cell * 0.95, '#f3e8ff', 'center', 800)
+ ctx.shadowBlur = 0
+ text(`${sweep.g.toFixed(1)} rows/s`, w.x + w.w / 2, w.y + L.cell * 5.2, L.cell * 0.46, '#c084fc', 'center', 600)
+ ctx.globalAlpha = 1
+ }
+
+ function drawParticles(dt) {
+ if (!particles.length) return
+ ctx.globalCompositeOperation = 'lighter'
+ for (const p of particles) {
+ p.life += dt; p.vy += 900 * dt; p.x += p.vx * dt; p.y += p.vy * dt
+ const a = 1 - p.life / p.max; if (a <= 0) continue
+ ctx.fillStyle = hexA(p.color, a); ctx.fillRect(p.x - p.size / 2, p.y - p.size / 2, p.size, p.size)
+ }
+ ctx.globalCompositeOperation = 'source-over'
+ particles = particles.filter((p) => p.life < p.max)
+ }
+
+ function drawTexts(now) {
+ texts = texts.filter((t) => now - t.t0 < t.dur)
+ for (const t of texts) {
+ const k = (now - t.t0) / t.dur; if (k < 0) continue
+ const a = k < 0.12 ? k / 0.12 : 1 - (k - 0.12) / 0.88
+ const size = L.cell * t.size * (t.grow ? 0.7 + 0.5 * easeOut(Math.min(1, k * 3)) : 1)
+ ctx.globalAlpha = clamp(a, 0, 1); ctx.shadowColor = t.color; ctx.shadowBlur = t.grow ? 24 : 10
+ const X = clamp(cx(t.x), L.well.x + size * 2.2, L.well.x + L.well.w - size * 2.2)
+ text(t.text, t.center ? cx(t.x) : X, cy(t.y) - k * L.cell * 1.3, size, t.color, 'center', 800)
+ ctx.shadowBlur = 0; ctx.globalAlpha = 1
+ }
+ }
+
+ function drawCollapse(now, dt) {
+ const c = L.cell, el = now - collapse.t0
+ for (const b of collapse.blocks) {
+ const live = el > b.delay
+ if (live) { b.vy += 30 * dt; b.fx += b.vx * dt; b.fy += b.vy * dt; b.rot += b.vr * dt }
+ if (b.fy > H + 2) continue
+ const s = sprites[live ? 8 : b.c]
+ ctx.save(); ctx.translate(cx(b.fx) + c / 2, cy(b.fy) + c / 2); ctx.rotate(b.rot)
+ ctx.globalAlpha = live ? clamp(1.2 - (el - b.delay) / 1500, 0, 1) : 1
+ ctx.drawImage(s.body, -c / 2, -c / 2, c, c); ctx.restore(); ctx.globalAlpha = 1
+ }
+ }
+
+ function drawBanner(now) {
+ const w = L.well, f = S.finished, c = L.cell
+ const bh = c * 5.6, by = w.y + w.h / 2 - bh / 2
+ ctx.save(); ctx.globalAlpha = collapse ? clamp((now - collapse.t0 - 350) / 300, 0, 1) : 1
+ ctx.fillStyle = 'rgba(8,8,16,.84)'; ctx.strokeStyle = '#fb7185'; ctx.lineWidth = 1.5; ctx.shadowColor = '#fb7185'; ctx.shadowBlur = 24
+ ctx.beginPath(); ctx.roundRect(w.x + 8, by, w.w - 16, bh, 12); ctx.fill(); ctx.stroke(); ctx.shadowBlur = 0
+ text('TOPPED OUT', w.x + w.w / 2, by + c * 1.5, c * 0.92, '#fb7185', 'center', 800)
+ text(`${fmt(f.lines)} lines · ${fmt(f.pieces)} pieces`, w.x + w.w / 2, by + c * 2.7, c * 0.5, '#e9ecf5', 'center', 700)
+ text(`at ${f.gravity.toFixed(1)} rows/s${f.record && f.lines ? ' · new best' : ''}`, w.x + w.w / 2, by + c * 3.55, c * 0.42, f.record && f.lines ? '#c084fc' : '#8b92aa', 'center', 600)
+ const left = S.running ? Math.max(0, f.restartInMs - (now - simWall)) : f.restartInMs
+ text(S.running ? `next game in ${(left / 1000).toFixed(1)} s` : 'paused · Step or Resume for the next game', w.x + w.w / 2, by + c * 4.7, c * 0.4, '#8b92aa', 'center', 600)
+ ctx.restore()
+ }
+
+ // ------------------------------------------------------------------ the frame loop
+ function frame(now) {
+ requestAnimationFrame(frame)
+ const dt = Math.min(0.05, (now - last) / 1000); last = now
+ if (!L || L.w !== wrap.clientWidth || L.h !== wrap.clientHeight || dpr !== Math.max(1, Math.min(2.5, window.devicePixelRatio || 1))) layout()
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
+ ctx.clearRect(0, 0, L.w, L.h)
+ if (!S || !shapes) { text('connecting…', L.w / 2, L.h / 2, 13, '#8b92aa', 'center'); return }
+ shake *= Math.exp(-dt * 9)
+ drawWell(now, dt)
+ drawLeft(now)
+ drawRight(now)
+ }
+
+ // ------------------------------------------------------------------ DOM
+ const setText = (el, v) => { if (el.textContent !== v) el.textContent = v }
+ const fmtMoney = (v) => (v <= 0 ? '$0' : v < 1 ? '$' + v.toFixed(v < 0.01 ? 5 : 4) : '$' + v.toFixed(2))
+ const G_LO = 0.2, T_LO = 30, T_HI = 1000
+ const gHi = () => (S && S.cfg.maxGravity) || 120
+ const sliderToG = (v) => G_LO * Math.pow(gHi() / G_LO, v / 1000)
+ const gToSlider = (g) => Math.round((Math.log(g / G_LO) / Math.log(gHi() / G_LO)) * 1000)
+ const sliderToT = (v) => T_LO * Math.pow(T_HI / T_LO, v / 1000)
+ const tToSlider = (t) => Math.round((Math.log(t / T_LO) / Math.log(T_HI / T_LO)) * 1000)
+
+ function renderDom() {
+ if (!S) return
+ const g = S.game
+ setText($('title'), S.title || 'Jev Blocks'); document.title = S.title || 'Jev Blocks'
+ setText($('sLines'), fmt(g.lines)); setText($('sLpm'), g.lpm ? g.lpm.toFixed(0) : '—'); setText($('sPieces'), fmt(S.session.pieces)); setText($('sBest'), fmt(Math.max(S.session.best, g.lines)))
+ setText($('pause'), S.running ? 'Pause' : 'Resume'); $('pause').classList.toggle('on', !S.running)
+ $('slow').classList.toggle('on', !!S.slow)
+ const err = S.error || (S.warnings && S.warnings[0]) || (S.jevError ? 'Jev: ' + S.jevError : '')
+ $('cfgError').classList.toggle('hidden', !err); setText($('cfgError'), err || '')
+ if (!dragging.gravity) { $('gravity').value = gToSlider(g.gravity); setText($('gravityVal'), g.gravity.toFixed(1)) }
+ if (!dragging.think) { $('think').value = tToSlider(S.cfg.decisionMs); setText($('thinkVal'), String(Math.round(S.cfg.decisionMs))) }
+ $('pinTag').classList.toggle('hidden', !S.cfg.pinned)
+ setText($('kneeVal'), String(Math.round(knee())))
+ if (S.logSeq !== logSeq) {
+ logSeq = S.logSeq
+ const ul = $('log'), seen = Number(ul.dataset.seen || 0)
+ ul.replaceChildren(...logLines.slice().reverse().map((l) => { const li = document.createElement('li'); li.className = l.kind + (l.seq > seen ? ' fresh' : ''); const n = document.createElement('span'); n.className = 'n'; n.textContent = String(l.lines); const t = document.createElement('span'); t.textContent = l.text; li.append(n, t); return li }))
+ ul.dataset.seen = String(logLines.length ? logLines[logLines.length - 1].seq : 0)
+ setText($('logMeta'), 'lines · event')
+ }
+ }
+
+ async function pollJev() {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) { const j = await r.json(); setText($('sDps'), j.questionsPerSec >= 10 ? String(Math.round(j.questionsPerSec)) : j.questionsPerSec.toFixed(1)); setText($('sCost'), fmtMoney(j.costUsd)) } } catch { /* restarting */ }
+ setTimeout(pollJev, 400)
+ }
+
+ // ------------------------------------------------------------------ input
+ function pick(ev) {
+ const r = canvas.getBoundingClientRect(), x = ev.clientX - r.left, y = ev.clientY - r.top
+ const out = { col: -1, next: -1 }
+ if (!L) return out
+ const w = L.well
+ if (x >= w.x && x < w.x + w.w && y >= w.y && y < w.y + w.h) out.col = clamp(Math.floor((x - w.x) / L.cell), 0, W - 1)
+ L.nextBoxes.forEach((b, i) => { if (x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h) out.next = i })
+ return out
+ }
+ canvas.addEventListener('mousemove', (ev) => { hover = pick(ev); wrap.classList.toggle('hot', hover.col >= 0 || hover.next >= 0) })
+ canvas.addEventListener('mouseleave', () => { hover = { col: -1, next: -1 }; wrap.classList.remove('hot') })
+ canvas.addEventListener('click', (ev) => { const h = pick(ev); if (h.next >= 0) post({ cmd: 'cycleNext', index: h.next }); else if (h.col >= 0) post({ cmd: 'junk', col: h.col }) })
+
+ let sendTimer = null
+ const sendSoon = (body) => { clearTimeout(sendTimer); sendTimer = setTimeout(() => post(body), 40) }
+ $('gravity').addEventListener('input', (e) => { dragging.gravity = true; const g = sliderToG(Number(e.target.value)); setText($('gravityVal'), g.toFixed(1)); sendSoon({ cmd: 'set', gravity: +g.toFixed(2) }) })
+ $('think').addEventListener('input', (e) => { dragging.think = true; const t = sliderToT(Number(e.target.value)); setText($('thinkVal'), String(Math.round(t))); sendSoon({ cmd: 'set', decisionMs: Math.round(t) }) })
+ for (const k of ['gravity', 'think']) for (const evn of ['change', 'pointerup', 'blur']) $(k).addEventListener(evn, () => setTimeout(() => { dragging[k] = false }, 150))
+ $('pinTag').addEventListener('click', () => post({ cmd: 'set', gravity: null }))
+ $('pinTag').title = 'Click to let gravity follow the level again'
+ $('pause').addEventListener('click', () => post({ cmd: S && S.running ? 'pause' : 'start' }))
+ $('step').addEventListener('click', () => post({ cmd: 'tick' }))
+ $('reset').addEventListener('click', () => post({ cmd: 'reset' }))
+ $('garbage').addEventListener('click', () => post({ cmd: 'garbage' }))
+ $('slow').addEventListener('click', () => post({ cmd: 'set', slow: !(S && S.slow) }))
+ $('mind').addEventListener('click', () => { showMind = !showMind; $('mind').classList.toggle('on', showMind) })
+ window.addEventListener('keydown', (e) => {
+ if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName) && e.target.type !== 'range') return
+ const k = e.key.toLowerCase()
+ if (k === ' ') { e.preventDefault(); $('pause').click() } else if (k === 's') $('step').click(); else if (k === 'g') $('garbage').click(); else if (k === 'm') $('mind').click(); else if (k === 'r') $('reset').click()
+ })
+
+ // ------------------------------------------------------------------ go
+ if (window.innerHeight < 1000) $('how').open = false // keep the game log on screen in a short pane
+ new ResizeObserver(() => { L = null }).observe(wrap)
+ fetch('/state').then((r) => r.json()).then(onFrame).catch(() => {})
+ const es = new EventSource('/events')
+ es.addEventListener('state', (ev) => { try { onFrame(JSON.parse(ev.data)) } catch (e) { console.error(e) } })
+ pollJev()
+ requestAnimationFrame(frame)
+})()
diff --git a/store/agents/jev-blocks/viewer/viewer.mjs b/store/agents/jev-blocks/viewer/viewer.mjs
new file mode 100644
index 000000000..30fb10cb0
--- /dev/null
+++ b/store/agents/jev-blocks/viewer/viewer.mjs
@@ -0,0 +1,522 @@
+// Jev Blocks viewer — a loopback server that runs a falling-blocks puzzle and lets Jev (TypeSafe's
+// System One model) play it. For every new piece the viewer lists every legal placement and asks
+// Jev ONE call with three parallel questions: `place` (a choice over the placements), `danger`
+// (a score) and `go_for_four` (a yes/no). The piece really falls while Jev decides and while the
+// piece is moved into place, so the honest limit is time: turn gravity up and placements start to
+// land short. The game is synthetic. The decision loop is the demo.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. The workspace holds blocks.json (watched live).
+
+import { mkdirSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, telemetry } from '../toolchain/jev.mjs'
+import { serveViewer, watchConfig, writeVerdict, mulberry32, clean } from './kit.mjs'
+import {
+ W, H, TYPES, CODE, SHAPES, spawnOf, rotationPath, emptyBoard, collide, dropRow, clearLines, measure,
+ enumerate, buildState, buildQuestions, blocksMock, DANGER_LEVELS,
+} from './game.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const MARKER = 'blocks.json'
+
+export const DEFAULTS = {
+ title: 'Jev Blocks',
+ description: 'Jev plays a falling-blocks puzzle. One call per piece picks the placement.',
+ seed: 7,
+ gravity: 2,
+ speedup: 0.5,
+ decisionMs: 110,
+ moveMs: 35,
+ garbageRows: 0,
+ weights: { I: 1, O: 1, T: 1, S: 1, Z: 1, J: 1, L: 1 },
+ board: [],
+ style: 'Keep the stack low, flat and free of holes. Leave the right column open and go for four lines at once when it is safe. When the stack gets high, stop waiting and clear lines.',
+}
+
+const LIMITS = { gravity: [0.2, 40], speedup: [0, 2], decisionMs: [30, 1000], moveMs: [5, 500], garbageRows: [0, 12] }
+const MAX_GRAVITY = 120 // rows per second, after the level speedup
+const CLEAR_MS = 220 // pause while cleared lines flash, before the next piece
+const SPAWN_MS = 45 // pause between a lock and the next piece
+const RESULT_MS = 3000 // how long a finished game stays on screen
+const LOOP_MS = 20
+const LINE_SCORE = [0, 100, 300, 500, 800]
+
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+const num = (v, [lo, hi], d) => (typeof v === 'number' && Number.isFinite(v) ? clamp(v, lo, hi) : d)
+
+/** Clamp a raw blocks.json into something the simulator can always run. */
+export function sanitize(raw) {
+ const c = { ...DEFAULTS, ...(raw && typeof raw === 'object' ? raw : {}) }
+ const out = {
+ title: clean(c.title || DEFAULTS.title).slice(0, 80),
+ description: clean(c.description || '').slice(0, 300),
+ style: clean(c.style || DEFAULTS.style).slice(0, 600),
+ seed: Number.isFinite(Number(c.seed)) ? Math.floor(Number(c.seed)) : DEFAULTS.seed,
+ warnings: [],
+ }
+ for (const k of Object.keys(LIMITS)) out[k] = num(c[k], LIMITS[k], DEFAULTS[k])
+ out.garbageRows = Math.round(out.garbageRows)
+ out.weights = {}
+ let sum = 0
+ for (const t of TYPES) { const w = Math.round(num(c.weights?.[t], [0, 9], c.weights && typeof c.weights === 'object' ? 0 : 1)); out.weights[t] = w; sum += w }
+ if (!sum) { for (const t of TYPES) out.weights[t] = 1; out.warnings.push('weights were all zero, using an even mix') }
+ out.board = []
+ if (Array.isArray(c.board) && c.board.length) {
+ const rows = c.board.map(String)
+ if (rows.length > H || rows.some((r) => !/^[.#]{10}$/.test(r))) out.warnings.push(`board ignored: use up to ${H} rows of exactly ${W} characters, '.' or '#'`)
+ else out.board = rows
+ }
+ return out
+}
+
+export async function startBlocksViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ // ---- every piece of mutable state is declared here, before any function below can run ----
+ let stopped = false
+ let running = true
+ let slow = false // slow motion: the game clock runs at a quarter of wall time
+ let busy = false // a step is in flight; the real-time loop stands back
+ let cfg = sanitize({})
+ let cfgKey = ''
+ let cfgErr = null
+ let overrides = {} // runtime changes from the pane; an edit to blocks.json clears them
+ let game = null
+ let session = null
+ let piece = null
+ let pieceSeq = 0
+ let mind = null
+ let mindSeq = 0
+ let lastDanger = null
+ let lastFour = null
+ let events = []
+ let eventSeq = 0
+ let log = []
+ let logSeq = 0
+ let finished = null
+ let salt = 1
+ let jevErr = null
+ let decisions = 0 // decisions applied, over the whole session
+ let recent = [] // last locks: true = missed
+ let lastVerdictAt = 0
+ let lastFrameAt = 0
+ let lastWall = performance.now()
+ let loop = null
+ let chain = Promise.resolve()
+ let viewer = null
+ let sentMind = -1
+ let sentLog = -1
+ let watcher = null
+
+ // ------------------------------------------------------------------ helpers
+ const val = (k) => (overrides[k] ?? cfg[k])
+ /** Rows per second right now. The pane can pin it; otherwise it climbs with the level. */
+ const gravityNow = () => clamp(overrides.pin ?? cfg.gravity * (1 + cfg.speedup * ((game?.level ?? 1) - 1)), 0.2, MAX_GRAVITY)
+
+ function say(text, kind = 'info') {
+ log.push({ seq: ++logSeq, kind, text: clean(text).slice(0, 160), lines: game?.lines ?? 0 })
+ if (log.length > 60) log.splice(0, log.length - 60)
+ }
+ function emit(kind, data = {}) {
+ events.push({ seq: ++eventSeq, kind, ...data })
+ if (events.length > 24) events.splice(0, events.length - 24)
+ }
+
+ // ------------------------------------------------------------------ game setup
+ function refill() {
+ while (game.queue.length < 5) {
+ if (!game.bag.length) {
+ for (const t of TYPES) for (let i = 0; i < cfg.weights[t]; i++) game.bag.push(t)
+ for (let i = game.bag.length - 1; i > 0; i--) { const j = Math.floor(game.rng() * (i + 1)); [game.bag[i], game.bag[j]] = [game.bag[j], game.bag[i]] }
+ }
+ game.queue.push(game.bag.pop())
+ }
+ }
+
+ function garbageRow() {
+ let gap = Math.floor(game.rngG() * W)
+ if (gap === game.lastGap) gap = (gap + 1 + Math.floor(game.rngG() * (W - 1))) % W
+ game.lastGap = gap
+ return { gap, row: Array.from({ length: W }, (_, x) => (x === gap ? 0 : CODE.garbage)) }
+ }
+
+ /** Push one garbage row in from the bottom. Returns false if that pushed blocks out of the top. */
+ function pushGarbage() {
+ const { gap, row } = garbageRow()
+ const lost = game.board.shift()
+ game.board.push(row)
+ if (piece) while (collide(game.board, piece.type, piece.rot, piece.x, piece.y) && piece.y > -4) piece.y--
+ return { gap, overflow: lost.some((c) => c) }
+ }
+
+ function newGame(why) {
+ const n = (session.games += 1)
+ const seed = (cfg.seed + n - 1) | 0
+ game = {
+ n, board: emptyBoard(), queue: [], bag: [], rng: mulberry32(seed), rngG: mulberry32(seed ^ 0x9e3779b9), lastGap: -1,
+ score: 0, level: 1, lines: 0, pieces: 0, misses: 0, fours: 0, now: 0, nextSpawnAt: 0,
+ }
+ piece = null
+ finished = null
+ mind = null
+ mindSeq++
+ recent = []
+ cfg.board.forEach((r, i) => { const y = H - cfg.board.length + i; for (let x = 0; x < W; x++) game.board[y][x] = r[x] === '#' ? CODE.garbage : 0 })
+ clearLines(game.board)
+ for (let i = 0; i < cfg.garbageRows; i++) pushGarbage()
+ refill()
+ emit('newgame', { n })
+ say(`Game ${n} started${why ? ` (${why})` : ''} · gravity ${gravityNow().toFixed(1)} rows/s`, 'game')
+ }
+
+ function newSession(why) {
+ session = { games: 0, best: 0, lines: 0, pieces: 0, topOuts: 0, misses: 0, fours: 0, lastTopOut: null }
+ decisions = 0
+ newGame(why)
+ }
+
+ function topOut(reason) {
+ if (finished) return
+ piece = null
+ session.topOuts++
+ const record = session.topOuts > 1 && game.lines > session.best
+ session.best = Math.max(session.best, game.lines)
+ finished = { lines: game.lines, pieces: game.pieces, score: game.score, level: game.level, gravity: gravityNow(), reason, record, wallAt: Date.now() }
+ session.lastTopOut = { lines: game.lines, pieces: game.pieces, gravity: gravityNow() }
+ emit('topout', { lines: game.lines, pieces: game.pieces })
+ say(`Topped out · ${game.lines} lines, ${game.pieces} pieces at ${gravityNow().toFixed(1)} rows/s${record && game.lines ? ' · new best' : ''}`, 'bad')
+ verdict(true)
+ }
+
+ // ------------------------------------------------------------------ one piece
+ function spawn() {
+ const type = game.queue.shift()
+ refill()
+ const sp = spawnOf(type)
+ if (collide(game.board, type, 0, sp.x, sp.y)) { game.queue.unshift(type); return topOut('the stack reached the top') }
+ const g = gravityNow()
+ piece = {
+ id: ++pieceSeq, type, rot: 0, x: sp.x, y: sp.y, g, phase: 'think', spawnAt: game.now, fallAt: game.now + 1000 / g,
+ decideAt: game.now + val('decisionMs'), answer: null, answerAt: Infinity, asking: null, queue: [], target: null, moveAt: Infinity, moved: 0, blocked: 0,
+ }
+ ask(piece)
+ }
+
+ /** Ask Jev about this piece. One call, three parallel questions. The piece keeps falling meanwhile. */
+ function ask(p, free = false) {
+ const g = game
+ const cands = enumerate(g.board, p.type)
+ const state = buildState({ style: cfg.style, board: g.board, type: p.type, next: g.queue.slice(0, 3), level: g.level, lines: g.lines, gravity: p.g, decisionMs: val('decisionMs'), moveMs: val('moveMs'), cands })
+ p.cands = cands
+ p.asking = (async () => {
+ if (!cands.length) { p.answer = { none: true }; p.answerAt = p.decideAt; return }
+ try {
+ const res = await evaluate({ state, questions: buildQuestions(p.type, cands), salt: salt++, model: process.env.JEV_MODEL || 'jev-latest', mock: blocksMock })
+ if (stopped || piece !== p || game !== g) return
+ jevErr = null
+ p.answer = res
+ const cost = Math.max(val('decisionMs'), res.client === 'typesafe' ? res.latencyMs : 0)
+ p.answerAt = free ? g.now : Math.max(p.spawnAt + cost, g.now)
+ } catch (e) {
+ if (stopped || piece !== p) return
+ if (!jevErr) say(`Jev call failed: ${clean(e?.message ?? e).slice(0, 110)}`, 'bad')
+ jevErr = clean(e?.message ?? e)
+ p.answer = { none: true }
+ p.answerAt = Math.max(p.decideAt, g.now)
+ }
+ })()
+ }
+
+ /** Turn Jev's answer into a target and a list of moves, and publish its mind to the pane. */
+ function applyDecision(p) {
+ const res = p.answer
+ p.phase = 'move'
+ p.moveAt = game.now + val('moveMs')
+ if (!res || res.none) { p.queue = []; p.target = null; return }
+ const a = res.answers.place || {}
+ const probs = a.probabilities || {}
+ let pick = p.cands.find((c) => c.id === a.choice)
+ if (!pick) pick = [...p.cands].sort((x, y) => (probs[y.id] ?? 0) - (probs[x.id] ?? 0))[0]
+ p.target = pick
+ const sp = spawnOf(p.type)
+ p.queue = [...rotationPath(p.type, pick.rot).map((r) => ({ rot: r })), ...Array.from({ length: Math.abs(pick.x - sp.x) }, () => ({ dx: Math.sign(pick.x - sp.x) }))]
+ decisions++
+ const d = res.answers.danger || {}
+ const four = Number(res.answers.go_for_four?.noul ?? 0)
+ lastDanger = { score: Number(d.score ?? 0), label: DANGER_LEVELS[Math.round(Number(d.score ?? 0))]?.split(':')[0] ?? '', confidence: Number(d.confidence ?? 0) }
+ lastFour = four
+ const needMs = val('decisionMs') + (p.queue.length + 1) * val('moveMs')
+ const rowsFree = Math.max(0, dropRow(game.board, p.type, 0, sp.x, sp.y) - sp.y)
+ mind = {
+ seq: ++mindSeq, pieceId: p.id, type: p.type, chosen: pick.id, confidence: Number(a.confidence ?? probs[pick.id] ?? 0),
+ cands: p.cands.map((c) => ({ id: c.id, r: c.rot, x: c.x, y: c.y, p: +(Number(probs[c.id] ?? 0)).toFixed(4), lines: c.lines, holes: c.newHoles })).sort((x, y) => y.p - x.p),
+ needMs: Math.round(needMs), haveMs: Math.round((rowsFree / p.g) * 1000), latencyMs: +Number(res.latencyMs ?? 0).toFixed(1), client: res.client,
+ }
+ }
+
+ function lock(p, how) {
+ const b = game.board
+ let above = false
+ for (const [dx, dy] of SHAPES[p.type][p.rot]) { if (p.y + dy < 0) above = true; else b[p.y + dy][p.x + dx] = CODE[p.type] }
+ const onTarget = !!p.target && p.rot === p.target.rot && p.x === p.target.x
+ const missed = !onTarget
+ const cleared = clearLines(b)
+ const n = cleared.length
+ const gain = LINE_SCORE[n] * game.level
+ game.score += gain
+ game.lines += n; session.lines += n
+ game.pieces++; session.pieces++
+ if (n === 4) { game.fours++; session.fours++ }
+ if (missed) { game.misses++; session.misses++ }
+ recent.push(missed); if (recent.length > 50) recent.shift()
+ emit('lock', { id: p.id, type: p.type, rot: p.rot, x: p.x, y: p.y, fromY: how.fromY ?? p.y, missed, cleared, gain, want: missed && p.target ? { rot: p.target.rot, x: p.target.x, y: p.target.y } : null })
+ if (missed) {
+ const off = p.target ? Math.abs(p.x - p.target.x) : 0
+ say(p.target ? `Missed: ${p.type} wanted ${p.target.id}, landed ${off ? `${off} column${off > 1 ? 's' : ''} short` : 'with the wrong rotation'}` : `${p.type} landed before Jev could answer`, 'warn')
+ }
+ if (n >= 2) say(n === 4 ? `FOUR lines at once · +${gain}` : `${n} lines · +${gain}`, n === 4 ? 'four' : 'ok')
+ const level = 1 + Math.floor(game.lines / 10)
+ if (level > game.level) { game.level = level; emit('levelup', { level, g: +gravityNow().toFixed(2) }); say(`Level ${level} · gravity ${gravityNow().toFixed(1)} rows/s`, 'level') }
+ piece = null
+ game.nextSpawnAt = game.now + (n ? CLEAR_MS : SPAWN_MS)
+ if (above) topOut('a piece locked above the top')
+ }
+
+ // ------------------------------------------------------------------ the clock (event driven, in game ms)
+ function actionTime() {
+ if (!piece) return Infinity
+ if (piece.phase === 'think') return piece.answer ? Math.max(piece.decideAt, piece.answerAt) : Infinity
+ return piece.moveAt
+ }
+ function nextEventTime() {
+ if (finished) return Infinity
+ if (!piece) return game.nextSpawnAt
+ return Math.min(piece.fallAt, actionTime())
+ }
+
+ function processEvent() {
+ if (!piece) return spawn()
+ const p = piece
+ if (actionTime() <= p.fallAt) {
+ if (p.phase === 'think') return applyDecision(p)
+ const m = p.queue[0]
+ if (!m) { const fromY = p.y; p.y = dropRow(game.board, p.type, p.rot, p.x, p.y); return lock(p, { fromY }) } // aligned: hard drop
+ const rot = m.rot ?? p.rot, x = p.x + (m.dx ?? 0)
+ if (!collide(game.board, p.type, rot, x, p.y)) { p.rot = rot; p.x = x; p.queue.shift(); p.moved++ } else p.blocked++
+ p.moveAt += val('moveMs')
+ return
+ }
+ // gravity: one row down, or it has landed and locks where it is
+ if (collide(game.board, p.type, p.rot, p.x, p.y + 1)) return lock(p, {})
+ p.y++
+ p.fallAt += 1000 / p.g
+ }
+
+ function advanceTo(t) {
+ let guard = 0
+ while (!finished && guard++ < 4000) {
+ const te = nextEventTime()
+ if (te > t) break
+ game.now = Math.max(game.now, te)
+ processEvent()
+ }
+ if (!finished) game.now = Math.max(game.now, t)
+ }
+
+ /** Advance until exactly one more decision has been applied (or the game ended). Never waits on timers. */
+ async function stepDecision() {
+ if (finished) newGame('next game')
+ const want = decisions + 1
+ let guard = 0
+ while (decisions < want && !finished && !stopped && guard++ < 20000) {
+ if (piece && piece.phase === 'think' && !piece.answer) await piece.asking
+ const te = nextEventTime()
+ if (te === Infinity) break
+ game.now = Math.max(game.now, te)
+ processEvent()
+ }
+ }
+
+ // ------------------------------------------------------------------ what the pane sees
+ function pieceView() {
+ if (!piece) return null
+ const p = piece
+ const resting = collide(game.board, p.type, p.rot, p.x, p.y + 1)
+ const frac = resting ? 0 : clamp(1 - (p.fallAt - game.now) / (1000 / p.g), 0, 1)
+ return { id: p.id, type: p.type, rot: p.rot, x: p.x, y: p.y, frac: +frac.toFixed(3), phase: p.phase, left: p.queue.length, moved: p.moved, ghostY: dropRow(game.board, p.type, p.rot, p.x, p.y), target: p.target ? { id: p.target.id, rot: p.target.rot, x: p.target.x, y: p.target.y } : null }
+ }
+
+ function view(full) {
+ const mins = game.now / 60000
+ const m = measure(game.board)
+ const f = {
+ title: cfg.title, running, slow, client: telemetry.client, error: cfgErr, warnings: cfg.warnings, jevError: jevErr,
+ cfg: { gravity: cfg.gravity, pinned: overrides.pin != null, maxGravity: MAX_GRAVITY, speedup: cfg.speedup, decisionMs: val('decisionMs'), baseDecisionMs: cfg.decisionMs, moveMs: val('moveMs'), garbageRows: cfg.garbageRows, weights: cfg.weights, overridden: Object.keys(overrides) },
+ game: {
+ n: game.n, board: game.board.map((r) => r.join('')).join(''), queue: game.queue.slice(0, 3), score: game.score, level: game.level, lines: game.lines, pieces: game.pieces,
+ misses: game.misses, fours: game.fours, gravity: +gravityNow().toFixed(2), simMs: Math.round(game.now), lpm: game.now > 4000 ? +(game.lines / mins).toFixed(1) : 0, maxHeight: m.max, holes: m.holes,
+ },
+ piece: pieceView(),
+ session: { ...session, decisions },
+ danger: lastDanger, four: lastFour,
+ finished: finished ? { ...finished, restartInMs: Math.max(0, RESULT_MS - (Date.now() - finished.wallAt)) } : null,
+ events, mindSeq, logSeq,
+ }
+ if (full || sentMind !== mindSeq) f.mind = mind
+ if (full || sentLog !== logSeq) f.log = log.slice(-40)
+ if (full) { f.shapes = SHAPES; f.spawn = Object.fromEntries(TYPES.map((t) => [t, spawnOf(t)])); f.style = cfg.style; f.description = cfg.description; f.dangerLevels = DANGER_LEVELS }
+ return f
+ }
+
+ function push() {
+ if (!viewer) return
+ const f = view(false)
+ sentMind = mindSeq; sentLog = logSeq
+ lastFrameAt = performance.now()
+ viewer.broadcast(f)
+ }
+
+ function verdict(force) {
+ const t = performance.now()
+ if (!force && t - lastVerdictAt < 400) return
+ lastVerdictAt = t
+ const missN = recent.filter(Boolean).length
+ const pressured = missN >= 3 || (lastDanger?.score ?? 0) >= 1.8
+ const findings = []
+ if (cfgErr) findings.push({ severity: 'error', kind: 'config', message: cfgErr })
+ for (const w of cfg.warnings) findings.push({ severity: 'warning', kind: 'config', message: w })
+ if (jevErr) findings.push({ severity: 'error', kind: 'jev', message: jevErr })
+ if (recent.length >= 10) findings.push({ severity: missN / recent.length > 0.1 ? 'warning' : 'info', kind: 'timing', message: `${missN} of the last ${recent.length} pieces landed short of their target at ${gravityNow().toFixed(1)} rows/s` })
+ if (session.lastTopOut) findings.push({ severity: 'info', kind: 'topout', message: `Topped out ${session.topOuts} time(s). Last: ${session.lastTopOut.lines} lines at ${session.lastTopOut.gravity.toFixed(1)} rows/s. Best ${session.best} lines.` })
+ try {
+ writeVerdict(workspace, {
+ ready: decisions > 0 && !cfgErr,
+ summary: cfgErr ? `Jev Blocks needs a fix: ${cfgErr}` : `${cfg.title} · game ${game.n} · ${game.lines} lines · level ${game.level} · ${gravityNow().toFixed(1)} rows/s · ${game.misses} missed · best ${Math.max(session.best, game.lines)}`,
+ findings, artifact: MARKER,
+ phases: [
+ { id: 'play', name: 'Playing clean', state: finished || pressured ? 'done' : 'active' },
+ { id: 'pressure', name: 'Under pressure', state: finished ? 'done' : pressured ? 'active' : 'pending' },
+ { id: 'topout', name: 'Topped out', state: finished ? 'active' : session.topOuts ? 'done' : 'pending' },
+ ],
+ })
+ } catch { /* the workspace may be going away on close */ }
+ }
+
+ // ------------------------------------------------------------------ the pane's controls
+ async function rethinkIfPaused() {
+ const p = piece
+ if (running || !p || finished || p.moved > 0) return
+ p.phase = 'think'; p.answer = null; p.queue = []; p.target = null; p.moveAt = Infinity
+ ask(p, true)
+ await p.asking
+ if (piece === p && p.answer) applyDecision(p)
+ }
+
+ async function control(cmd, body) {
+ const run = async () => {
+ if (stopped) return null
+ if (cmd === 'pause') running = false
+ else if (cmd === 'start') { running = true; lastWall = performance.now() }
+ else if (cmd === 'reset') { overrides = {}; slow = false; newSession('reset') }
+ else if (cmd === 'tick') {
+ running = false; busy = true
+ try { const n = clamp(Math.floor(Number(body.n) || 1), 1, 1000); for (let i = 0; i < n && !stopped; i++) await stepDecision() } finally { busy = false }
+ } else if (cmd === 'set') {
+ for (const k of ['decisionMs', 'moveMs']) if (typeof body[k] === 'number' && Number.isFinite(body[k])) overrides[k] = clamp(body[k], ...LIMITS[k])
+ if (typeof body.gravity === 'number' && Number.isFinite(body.gravity)) overrides.pin = clamp(body.gravity, 0.2, MAX_GRAVITY)
+ if (body.gravity === null) delete overrides.pin
+ if (typeof body.slow === 'boolean') slow = body.slow
+ if (piece) { const g = gravityNow(); const left = clamp((piece.fallAt - game.now) / (1000 / piece.g), 0, 1); piece.g = g; piece.fallAt = game.now + left * (1000 / g) }
+ } else if (cmd === 'garbage') {
+ if (finished) return { done: false }
+ const { gap, overflow } = pushGarbage()
+ emit('garbage', { gap })
+ say(`You pushed up a garbage row (gap at column ${gap})`, 'you')
+ if (overflow) topOut('garbage pushed the stack over the top')
+ else await rethinkIfPaused()
+ } else if (cmd === 'junk') {
+ const col = Math.floor(Number(body.col))
+ if (finished || !(col >= 0 && col < W)) return { done: false }
+ let top = 0
+ while (top < H && !game.board[top][col]) top++
+ if (top === 0) return { done: false }
+ game.board[top - 1][col] = CODE.junk
+ if (piece) while (collide(game.board, piece.type, piece.rot, piece.x, piece.y) && piece.y > -4) piece.y--
+ const cleared = clearLines(game.board)
+ emit('junk', { col, row: top - 1, cleared })
+ say(`You dropped a junk block in column ${col}`, 'you')
+ await rethinkIfPaused()
+ } else if (cmd === 'cycleNext') {
+ const i = Math.floor(Number(body.index))
+ if (finished || !(i >= 0 && i < 3)) return { done: false }
+ const to = TYPES[(TYPES.indexOf(game.queue[i]) + 1) % TYPES.length]
+ game.queue[i] = to
+ emit('cycle', { index: i, type: to })
+ say(`You changed next piece ${i + 1} to ${to}`, 'you')
+ await rethinkIfPaused()
+ } else return { unknown: true }
+ verdict(true)
+ push()
+ return { running, pieces: session.pieces, lines: session.lines, decisions }
+ }
+ const result = chain.then(run, run)
+ chain = result.catch(() => {})
+ return result
+ }
+
+ // ------------------------------------------------------------------ boot
+ function applyConfig(raw, err) {
+ cfgErr = err
+ if (err) return false
+ const key = JSON.stringify(raw)
+ if (key === cfgKey) return false
+ cfgKey = key
+ cfg = sanitize(raw)
+ overrides = {}
+ slow = false
+ return true
+ }
+
+ watcher = watchConfig(join(workspace, MARKER), {}, (raw, err) => {
+ if (stopped) return
+ const changed = applyConfig(raw, err)
+ if (changed) { newSession('blocks.json edited'); say('blocks.json edited · pane changes cleared', 'you') } else if (err) say(`blocks.json has an error, keeping the last good one`, 'bad')
+ verdict(true)
+ push()
+ })
+ applyConfig(watcher.get(), watcher.error())
+ newSession('')
+
+ viewer = await serveViewer({ here: HERE, port, state: () => view(true), control })
+ verdict(true)
+
+ loop = setInterval(() => {
+ if (stopped) return
+ const t = performance.now()
+ const dt = Math.min(120, t - lastWall)
+ lastWall = t
+ if (busy) return
+ if (running) {
+ if (finished) { if (Date.now() - finished.wallAt >= RESULT_MS) newGame('next game') } else advanceTo(game.now + dt * (slow ? 0.25 : 1))
+ verdict(false)
+ push()
+ } else if (t - lastFrameAt > 1000) push()
+ }, LOOP_MS)
+
+ return {
+ url: viewer.url,
+ async close() { stopped = true; clearInterval(loop); watcher.close(); await viewer.close() },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startBlocksViewer({ workspace, port })
+ console.log(`Jev Blocks listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-browser/.gitignore b/store/agents/jev-browser/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-browser/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-browser/AGENTS.md b/store/agents/jev-browser/AGENTS.md
new file mode 100644
index 000000000..00c88b226
--- /dev/null
+++ b/store/agents/jev-browser/AGENTS.md
@@ -0,0 +1,75 @@
+# Jev Browser in OpenHarness
+
+On the left is a small made-up travel site inside a browser window, and **Jev operates it by
+itself**. Jev is TypeSafe's System One model. It never sees the screen. Each step the page is written
+out as text and Jev picks ONE element out of the list, a new list every step. A booking takes a few
+seconds. Every booking is checked against its task.
+
+On the right, you edit `site.json`. This is the ONLY file you edit. The viewer watches it and starts
+again from the first task the moment you save.
+
+## The site file
+
+```jsonc
+{
+ "title": "Jev Browser",
+ "description": "One line about this run.",
+ "site": "SkyHop", // the made-up site's name, shown in the tab and the URL
+ "stepMs": 170, // one Jev decision per step. 40 to 2000.
+ "distraction": 0.25, // 0 to 1. Cookie walls, pop-ups, decoys, layout shifts. THE DIAL.
+ "flights": 7, // result rows per search. 4 to 9.
+ "maxSteps": 45, // a task fails if it takes more steps. 12 to 200.
+ "seed": 11,
+ "style": "How Jev should work, in plain words. It is the first line of the text Jev reads.",
+ "tasks": [ // 1 to 40 bookings, run in order, then again with new flights
+ { "from": "SFO", "to": "JFK", "day": "Friday", "pick": "cheapest", "nonstop": true,
+ "name": "Ada Park", "email": "[email protected]", "bags": 1 }
+ ]
+}
+```
+
+`pick` is `cheapest`, `earliest` or `latest`. `bags` is 0 to 3. Airport codes are up to 4 letters.
+Names and emails are made up. Use `example.com` addresses.
+
+## Your job
+
+Write bookings that are fun to watch, then find out where Jev breaks.
+
+- **Write the tasks.** Mix the three `pick` rules, nonstop and not, and different bag counts, so
+ the right flight is a different row each time and the passenger page needs different clicks.
+- **Set the dial.** At `distraction` 0 every booking should come out exactly right in about ten
+ steps. Raise it and clicks start landing in the wrong place because the page moved between
+ reading and clicking. The person can also move the slider in the pane.
+- **Set the pace.** `stepMs` near 170 looks like a fast agent. 800 or more lets a person read each
+ step.
+- **Write the style line.** With a real key, Jev reads it on every step.
+- **Report what you see.** Read `.harness/verdict.json`: bookings done, the share that were exactly
+ right, steps each, and clicks lost to layout shifts. It also lists the most recent wrong bookings
+ and why they were wrong. Say at which distraction the share that is right drops below 9 in 10.
+
+Do NOT just ship the template. Every run should have its own tasks and a dial you chose on purpose.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`.
+
+## Rules
+
+- Edit only `site.json`. Keep it valid JSON. A bad edit does not crash the demo. The pane shows the
+ error and keeps running on the last good settings.
+- Never edit `.harness/verdict.json`. The viewer writes it.
+- The viewer is already running in the left pane. Never propose opening a browser, changing ports
+ or running a second server. The "browser" in this harness is a drawing inside the pane. It never
+ loads a real website.
+- You can ask Jev yourself through `toolchain/jev.mjs` (`evaluate`, and the `jev.choice`,
+ `jev.noul`, `jev.score` builders), for example to see which element it picks on one page.
+- Without `TYPESAFE_API_KEY` the harness runs on a deterministic offline stand-in, and the pane
+ says `MOCK`. It is there so the demo runs anywhere. It is not Jev's judgement, so do not describe
+ its results as Jev's.
+- This is a demo. The site, flights, prices and people are made up. Nothing is really booked. Do not
+ present the times as a benchmark of any product.
+
+## Definition of done
+
+- `site.json` parses and passes `toolchain/check.mjs`.
+- The pane runs your tasks without an error banner.
+- You told the person what dial you chose, how many bookings come out exactly right, how many steps
+ they take, and where it starts to fail.
diff --git a/store/agents/jev-browser/LICENSE b/store/agents/jev-browser/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-browser/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-browser/README.md b/store/agents/jev-browser/README.md
new file mode 100644
index 000000000..6bb0b7434
--- /dev/null
+++ b/store/agents/jev-browser/README.md
@@ -0,0 +1,92 @@
+# Jev Browser
+
+**Jev operates a web browser, live, and books a flight in a few seconds.** Jev is TypeSafe's System
+One model. It never sees the screen and never writes a word. At every step the page of a small
+made-up travel site is written out as text: the task, the page, and every element that can be
+acted on. Jev answers in **one call**:
+
+| question | type | what it drives |
+|---|---|---|
+| `action` | choice, a new option list every step | the ONE element to act on next |
+| `done` | noul (yes/no) | is the task already complete |
+| `obstacle` | noul (yes/no) | is something covering the page |
+
+Clicking an input fills it with the right value from the task. In the fast browser agents people
+built with Jev, a small text model wakes up only to type. Here a plain lookup plays that part.
+
+The pane shows the site in a browser window with a cursor that flies to each chosen element, rings
+on the page showing the probability Jev gave the top candidates, the exact text Jev reads, a timer,
+and a live panel with decisions per second, latency, tokens and cost. Every booking is checked
+against the task: the right flight, the right passenger, the right bags, no extras.
+
+This is a harness for OpenHarness. The agent on the right edits `site.json`. The viewer on the left
+runs the site and asks Jev for every step.
+
+## Play with it
+
+- **Click anything on the page yourself.** Your click is a real step. Jev has to deal with what
+ you did.
+- **Throw a pop-up** at it mid-task.
+- **Distraction** and **Step** sliders change the dial and the pace live.
+- **Show Jev's mind** toggles the probability rings. **Pause** then **Step** holds each page for a
+ moment so you can read the rings before the cursor moves.
+- Next task, Pause, Step, Reset.
+
+## The honest dial
+
+`distraction` (0 to 1) adds cookie walls, pop-ups, decoy buttons, upsells and **layout shifts**. A
+layout shift lands between reading the page and clicking it: a pop-up opens, or a sponsored row
+pushes the results down, and the click goes to the old spot and hits whatever is there now. That is
+how real web pages break real agents. Nothing else is random.
+
+Measured with the offline stand-in over 300 bookings at each level:
+
+| `distraction` | bookings exactly right | steps per booking | clicks lost per booking |
+|---|---|---|---|
+| 0.00 | 100% | 10.0 | 0.0 |
+| 0.25 (default) | 94% | 11.5 | 0.7 |
+| 0.50 | 92% | 13.2 | 1.5 |
+| 0.75 | 85% | 14.9 | 2.2 |
+| 1.00 | 81% | 17.2 | 3.3 |
+
+## Anatomy
+
+```
+jev-browser/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent how to write tasks and what to report
+ skills/browser/SKILL.md # the task-writing and verification craft
+ template/site.json # the starter tasks and dials
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API, or an offline stand-in)
+ check.mjs # validates site.json
+ viewer.sh setup.sh doctor.sh init-workspace.sh
+ viewer/
+ viewer.mjs # loopback server + the step loop
+ sim.mjs # the site: pages, elements with rectangles, layout shifts, scoring
+ mock.mjs # the offline stand-in (reads only the page text)
+ kit.mjs # loopback-only HTTP/SSE server helpers
+ studio.js # the browser window, the cursor, the rings
+ jev-hud.js # the "Jev live mind" panel
+ test/viewer.test.mjs
+```
+
+## Jev, honestly
+
+With `TYPESAFE_API_KEY` set, every step is a real call to `POST /v1/systemone`. Without a key the
+harness runs on a deterministic local stand-in that reads the same page text and answers the same
+questions, so the demo works offline. The pane badges that mode `MOCK`. The stand-in exercises the
+plumbing. It is not Jev's judgement.
+
+The site, the flights, the prices and the people are made up. Nothing is booked anywhere and no real
+website is touched. The times shown are this demo's pace, not a benchmark of any product.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API. It contains no TypeSafe code.
+- The idea of a decision model choosing the next browser action from the page's elements comes from
+ the open-source browser agents the community built around Jev. This harness is an independent,
+ from-scratch demo on a synthetic site and uses none of their code.
+- **OpenHarness** (Autonomous) is MIT-licensed. This wrapper is MIT too (see `LICENSE`).
+- Built by Autonomous for the OpenHarness store.
diff --git a/store/agents/jev-browser/THIRD_PARTY_NOTICES.md b/store/agents/jev-browser/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-browser/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-browser/harness.json b/store/agents/jev-browser/harness.json
new file mode 100644
index 000000000..e7f8a0c16
--- /dev/null
+++ b/store/agents/jev-browser/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-browser",
+ "name": "Jev Browser",
+ "category": "AI",
+ "author": "Autonomous",
+ "description": "Jev operates a web browser, live. On a made-up travel site it books flights in seconds: each step the page is written out as text and Jev, TypeSafe's System One model, picks one element from the list. Add pop-ups and layout shifts, or click the page yourself, and watch it cope.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "site.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-browser/skills/browser/SKILL.md b/store/agents/jev-browser/skills/browser/SKILL.md
new file mode 100644
index 000000000..8aea7ab8b
--- /dev/null
+++ b/store/agents/jev-browser/skills/browser/SKILL.md
@@ -0,0 +1,58 @@
+---
+name: browser
+description: Write booking tasks and set the distraction dial for Jev Browser, then measure how many bookings come out exactly right and where layout shifts start to break it.
+---
+
+# Craft: Jev Browser runs
+
+Jev Browser is a made-up travel site that Jev operates by itself, one picked element per step. You
+shape the run in `site.json`. The craft is a set of tasks that exercise every page, and a dial that
+shows the real limit: a click lands where the element WAS when the page was read.
+
+## What Jev is asked, every step
+
+One call, three questions, all answered from the same page text:
+
+```
+action choice one option per element on the page right now (a new list every step)
+done noul "Is the task already complete?"
+obstacle noul "Is something covering the page that must be closed first?"
+```
+
+The page text is what a person could see: the task, the page name and URL, whether an overlay
+covers the page, the page's text, and every element that can be acted on with its label, its value
+and, for a result row's Select button, that row's details. The pane shows this text live.
+
+## The funnel
+
+`search` (From, To, Day, then Search flights) → `results` (pick the one right Select) →
+`details` (name, email, bags, no insurance, Continue) → `review` (no Flex upgrade, Confirm).
+With no distraction a booking takes about ten steps.
+
+The booking is right only if it is the exact flight the task describes (`cheapest`, `earliest` or
+`latest`, nonstop when asked), with the right name, email and bag count, and no extras.
+
+## The dial
+
+`distraction` adds, in order of pain: decoy buttons and links, a cookie wall on the first page,
+pop-ups that open between reading and clicking, and a sponsored row that pushes the results down so
+a click lands on the row above the one Jev chose. That last one makes a wrong booking that only a
+careful look at the next page can catch.
+
+| feel | distraction |
+|---|---|
+| clean site, every booking right | 0 |
+| a normal annoying site (default) | 0.25 |
+| hostile | 0.6 |
+| everything moves | 1 |
+
+## Verifying
+
+```bash
+node "$JEV_DSH/toolchain/check.mjs"
+```
+
+Then watch the pane and read `.harness/verdict.json`: bookings, share exactly right, steps each,
+clicks lost to layout shifts, and the latest wrong bookings with the reason. Report the dial you
+chose and where the share that is right falls below 9 in 10. The pane's MOCK badge means the offline
+stand-in is driving, not the real model. Say so when you report.
diff --git a/store/agents/jev-browser/store.json b/store/agents/jev-browser/store.json
new file mode 100644
index 000000000..a21de69f2
--- /dev/null
+++ b/store/agents/jev-browser/store.json
@@ -0,0 +1,18 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev drives a web browser: a flight booked in seconds, one pick per step",
+ "examples": [
+ {
+ "prompt": "Write ten booking tasks for a family trip: different cities, days and bag counts, some nonstop only. Then raise distraction until fewer than 9 in 10 bookings come out exactly right, and tell me where that is.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-browser/booked-exactly-right.jpg",
+ "caption": "A flight booked exactly as asked in 1.5 seconds and 10 steps, checked against the task"
+ },
+ {
+ "prompt": "Slow it down to one step a second with no distraction so I can read what Jev sees and what it picks at every step.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-browser/pick-the-flight.jpg",
+ "caption": "Step mode: the page text Jev reads on the right, its chosen element ringed on the page"
+ }
+ ]
+}
diff --git a/store/agents/jev-browser/template/site.json b/store/agents/jev-browser/template/site.json
new file mode 100644
index 000000000..17c1c6d0f
--- /dev/null
+++ b/store/agents/jev-browser/template/site.json
@@ -0,0 +1,17 @@
+{
+ "title": "Jev Browser",
+ "description": "Jev books flights on a made-up travel site, one click at a time.",
+ "site": "SkyHop",
+ "stepMs": 170,
+ "distraction": 0.25,
+ "flights": 7,
+ "maxSteps": 45,
+ "seed": 11,
+ "style": "Finish the task in as few actions as you can. Fill every field the task gives you, choose exactly the flight it asks for, refuse every extra, and close anything that gets in the way.",
+ "tasks": [
+ { "from": "SFO", "to": "JFK", "day": "Friday", "pick": "cheapest", "nonstop": true, "name": "Ada Park", "email": "[email protected]", "bags": 1 },
+ { "from": "SEA", "to": "AUS", "day": "Monday", "pick": "earliest", "nonstop": false, "name": "Omar Reyes", "email": "[email protected]", "bags": 0 },
+ { "from": "BOS", "to": "LAX", "day": "Sunday", "pick": "cheapest", "nonstop": false, "name": "Mei Tanaka", "email": "[email protected]", "bags": 2 },
+ { "from": "DEN", "to": "MIA", "day": "Wednesday", "pick": "latest", "nonstop": true, "name": "Lena Okafor", "email": "[email protected]", "bags": 1 }
+ ]
+}
diff --git a/store/agents/jev-browser/test/viewer.test.mjs b/store/agents/jev-browser/test/viewer.test.mjs
new file mode 100644
index 000000000..72349df58
--- /dev/null
+++ b/store/agents/jev-browser/test/viewer.test.mjs
@@ -0,0 +1,225 @@
+// Integration tests for Jev Browser. They boot the real viewer on an ephemeral port against a temp
+// workspace and drive time with the `tick` control, so nothing here waits on a timer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { execFileSync } from 'node:child_process'
+import net from 'node:net'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const ROOT = join(HERE, '..')
+const { startBrowserViewer, sanitize } = await import(join(ROOT, 'viewer/viewer.mjs'))
+const { DEFAULT, createWorld, observe, act, elements, bestFlight } = await import(join(ROOT, 'viewer/sim.mjs'))
+const { browserMock, readTask } = await import(join(ROOT, 'viewer/mock.mjs'))
+const TEMPLATE = JSON.parse(readFileSync(join(ROOT, 'template/site.json'), 'utf8'))
+
+async function boot(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-browser-test-'))
+ writeFileSync(join(ws, 'site.json'), JSON.stringify({ ...TEMPLATE, ...overrides }))
+ const viewer = await startBrowserViewer({ workspace: ws, port: 0 })
+ const base = viewer.url
+ const ctl = async (body) => { const r = await fetch(`${base}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); return { status: r.status, json: await r.json() } }
+ const state = async () => (await fetch(`${base}/state`)).json()
+ await ctl({ cmd: 'pause' }); await ctl({ cmd: 'reset' })
+ return { ws, viewer, base, ctl, state }
+}
+
+/** Run bookings straight on the sim with the stand-in: fast, no server. */
+function runBookings(cfg, n) {
+ let ok = 0, steps = 0, mis = 0
+ for (let i = 0; i < n; i++) {
+ const w = createWorld(cfg, i, Math.floor(i / cfg.tasks.length))
+ while (w.status === 'running') { const o = observe(w, cfg); act(w, cfg, browserMock(o.text, 'action', { options: Object.keys(o.options), descriptions: o.options }).choice) }
+ if (w.result.ok) ok++; steps += w.steps; mis += w.misclicks
+ }
+ return { right: ok / n, steps: steps / n, misclicks: mis / n }
+}
+
+test('Jev books a flight step by step, answering three questions per call', async () => {
+ const v = await boot({ distraction: 0 })
+ try {
+ await v.ctl({ cmd: 'tick', n: 3 })
+ let s = await v.state()
+ assert.equal(s.steps, 3)
+ assert.equal(s.page, 'search')
+ assert.deepEqual(s.els.filter((e) => e.role === 'input').map((e) => e.value), ['SFO', 'JFK', 'Friday'])
+ const sum = Object.values(s.last.probs).reduce((a, b) => a + b, 0)
+ assert.ok(Math.abs(sum - 1) < 1e-6 && Math.max(...Object.values(s.last.probs)) < 0.999, 'a real distribution')
+ await v.ctl({ cmd: 'tick', n: 7 })
+ s = await v.state()
+ assert.equal(s.status, 'done')
+ assert.equal(s.result.ok, true, s.result.why)
+ assert.equal(s.steps, 10)
+ assert.equal(s.session.tasks, 1)
+ const jev = await (await fetch(`${v.base}/jev`)).json()
+ assert.equal(jev.calls, 10)
+ assert.equal(jev.last.questions.length, 3)
+ assert.ok(jev.costUsd > 0)
+ } finally { await v.viewer.close() }
+})
+
+test('it never ends: after a booking the next task starts by itself', async () => {
+ const v = await boot({ distraction: 0, stepMs: 200 })
+ try {
+ await v.ctl({ cmd: 'tick', n: 10 })
+ assert.equal((await v.state()).task.index, 0)
+ await v.ctl({ cmd: 'tick', n: 14 }) // 2.6 s of rest at 200 ms a step, then the new task's first step
+ const s = await v.state()
+ assert.equal(s.task.index, 1)
+ assert.match(s.task.goal, /SEA to AUS/)
+ } finally { await v.viewer.close() }
+})
+
+test('site.json really takes effect, and pane overrides work', async () => {
+ const tasks = [{ from: 'LIS', to: 'OSL', day: 'Tuesday', pick: 'latest', nonstop: false, name: 'Ines Costa', email: '[email protected]', bags: 3 }]
+ const v = await boot({ title: 'Nordic Run', site: 'FjordAir', tasks, distraction: 0.6, stepMs: 400 })
+ try {
+ let s = await v.state()
+ assert.equal(s.title, 'Nordic Run'); assert.equal(s.site, 'FjordAir')
+ assert.equal(s.url, 'https://fjordair.example/')
+ assert.equal(s.distraction, 0.6); assert.equal(s.stepMs, 400)
+ assert.match(s.task.goal, /latest flight from LIS to OSL on Tuesday for Ines Costa \([email protected]\), 3 checked bags/)
+ await v.ctl({ cmd: 'set', key: 'distraction', value: 0.1 })
+ assert.equal((await v.state()).distraction, 0.1)
+ await v.ctl({ cmd: 'set', key: 'nope', value: 5 })
+ await v.ctl({ cmd: 'popup' })
+ s = await v.state()
+ assert.equal(s.overlay, 'popup')
+ assert.match(s.stateText, /OVERLAY: a pop-up covers the page/)
+ } finally { await v.viewer.close() }
+})
+
+test('a person can click the page, and the click is a real step', async () => {
+ const v = await boot({ distraction: 0 })
+ try {
+ await v.ctl({ cmd: 'click', id: 'to' })
+ let s = await v.state()
+ assert.equal(s.steps, 1)
+ assert.equal(s.els.find((e) => e.id === 'to').value, 'JFK')
+ assert.match(s.lastAction.note, /you clicked/)
+ await v.ctl({ cmd: 'click', id: 'search-flights' }) // still disabled: a wasted step, the page does not move
+ s = await v.state()
+ assert.equal(s.page, 'search'); assert.equal(s.wasted, 1); assert.equal(s.shake, 'search-flights')
+ await v.ctl({ cmd: 'tick', n: 12 })
+ assert.equal((await v.state()).result.ok, true, 'Jev still finishes the booking')
+ } finally { await v.viewer.close() }
+})
+
+test('a progressive verdict is written', async () => {
+ const v = await boot()
+ try {
+ await v.ctl({ cmd: 'tick', n: 40 })
+ const verdict = JSON.parse(readFileSync(join(v.ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(verdict.spec, 1); assert.equal(verdict.ready, true)
+ assert.match(verdict.summary, /bookings · \d+% exactly right/)
+ assert.ok(Array.isArray(verdict.findings) && Array.isArray(verdict.phases))
+ assert.equal(verdict.artifact, 'site.json')
+ } finally { await v.viewer.close() }
+})
+
+test('every control command answers 200, and junk is rejected', async () => {
+ const v = await boot()
+ try {
+ for (const cmd of ['pause', 'tick', 'start', 'pause', 'popup', 'reset']) assert.equal((await v.ctl({ cmd })).status, 200, cmd)
+ assert.equal((await v.ctl({ cmd: 'task', index: 2 })).status, 200)
+ assert.match((await v.state()).task.goal, /BOS to LAX/)
+ assert.equal((await v.ctl({ cmd: 'click', id: 'no-such-element' })).status, 200)
+ assert.equal((await fetch(`${v.base}/control`, { method: 'POST', body: '{not json' })).status, 400)
+ assert.equal((await fetch(`${v.base}/nope`)).status, 404)
+ } finally { await v.viewer.close() }
+})
+
+test('a broken site.json keeps the demo alive and reports the problem', async () => {
+ const v = await boot()
+ try {
+ writeFileSync(join(v.ws, 'site.json'), '{ "title": "oops", ')
+ await new Promise((r) => setTimeout(r, 250))
+ await v.ctl({ cmd: 'tick', n: 5 })
+ let s = await v.state()
+ assert.match(String(s.cfgError), /site\.json/)
+ assert.ok(s.steps >= 5)
+ writeFileSync(join(v.ws, 'site.json'), JSON.stringify({ ...TEMPLATE, title: 'Back again', distraction: 99, tasks: 'nonsense' }))
+ await new Promise((r) => setTimeout(r, 250))
+ s = await v.state()
+ assert.equal(s.cfgError, null); assert.equal(s.title, 'Back again')
+ assert.equal(s.distraction, 1, 'out-of-range values are clamped')
+ assert.equal(s.task.count, DEFAULT.tasks.length, 'a bad task list falls back to the built-in tasks')
+ } finally { await v.viewer.close() }
+})
+
+test('the viewer is loopback only', async () => {
+ const v = await boot()
+ try {
+ const port = Number(new URL(v.base).port)
+ const status = await new Promise((resolve) => {
+ const sock = net.connect(port, '127.0.0.1', () => sock.write('GET /state HTTP/1.1\r\nHost: evil.example.com\r\nConnection: close\r\n\r\n'))
+ let buf = ''
+ sock.on('data', (d) => { buf += d })
+ sock.on('end', () => resolve(Number((buf.match(/^HTTP\/1\.1 (\d+)/) ?? [])[1])))
+ sock.on('error', () => resolve(0))
+ })
+ assert.equal(status, 403)
+ } finally { await v.viewer.close() }
+})
+
+test('the dial is honest: distraction costs steps and correct bookings', () => {
+ const clean = runBookings(sanitize({ ...DEFAULT, distraction: 0 }), 200)
+ const hostile = runBookings(sanitize({ ...DEFAULT, distraction: 0.9 }), 200)
+ assert.equal(clean.right, 1); assert.equal(clean.steps, 10); assert.equal(clean.misclicks, 0)
+ assert.ok(hostile.right < 0.92 && hostile.right > 0.5, `hostile right ${hostile.right}`)
+ assert.ok(hostile.steps > clean.steps * 1.4, `hostile steps ${hostile.steps}`)
+ assert.ok(hostile.misclicks > 1.5, `hostile misclicks ${hostile.misclicks}`)
+})
+
+test('a layout shift makes the click land on what is there now', () => {
+ const cfg = sanitize({ ...DEFAULT, distraction: 1 })
+ // Walk many bookings until a sponsored row shifts the results under a Select click.
+ for (let i = 0; i < 80; i++) {
+ const w = createWorld(cfg, i, 0)
+ while (w.status === 'running') {
+ const o = observe(w, cfg)
+ const id = browserMock(o.text, 'action', { options: Object.keys(o.options), descriptions: o.options }).choice
+ const rec = act(w, cfg, id)
+ if (rec.shift === 'sponsored row' && id.startsWith('select-')) {
+ assert.notEqual(rec.landed, id, 'the list moved down, so the click hit another element')
+ assert.match(rec.note, /layout shifted/)
+ assert.ok(elements(w, cfg).length > 0)
+ return
+ }
+ }
+ }
+ assert.fail('no sponsored-row shift happened in 80 bookings at distraction 1')
+})
+
+test('every task has exactly one right flight, and the stand-in reads only the text', () => {
+ const cfg = sanitize(DEFAULT)
+ for (let i = 0; i < 40; i++) {
+ const w = createWorld(cfg, i, i)
+ const best = bestFlight(w.task, w.flights)
+ assert.ok(best, 'a right answer exists')
+ if (w.task.nonstop) assert.equal(best.stops, 0)
+ }
+ const w = createWorld(sanitize({ ...DEFAULT, distraction: 0 }), 0, 0)
+ const o = observe(w, sanitize({ ...DEFAULT, distraction: 0 }))
+ assert.deepEqual(readTask(o.text), { pick: 'cheapest', nonstop: true, from: 'SFO', to: 'JFK', day: 'Friday', name: 'Ada Park', email: '[email protected]', bags: 1 })
+ assert.equal(browserMock(o.text, 'action', { options: Object.keys(o.options), descriptions: o.options }).choice, 'from')
+ assert.equal(browserMock('nothing to do with a browser', 'action', { options: ['a', 'b'] }), null)
+})
+
+test('check.mjs accepts the template and rejects bad values', () => {
+ const run = (site) => {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-browser-check-'))
+ writeFileSync(join(ws, 'site.json'), JSON.stringify(site))
+ try { return { code: 0, out: execFileSync(process.execPath, [join(ROOT, 'toolchain/check.mjs')], { env: { ...process.env, HARNESS_WORKSPACE: ws }, encoding: 'utf8' }) } }
+ catch (e) { return { code: e.status, out: String(e.stdout) } }
+ }
+ assert.equal(run(TEMPLATE).code, 0)
+ const loud = run({ ...TEMPLATE, distraction: 3 })
+ assert.equal(loud.code, 1); assert.match(loud.out, /distraction/)
+ const badTask = run({ ...TEMPLATE, tasks: [{ ...TEMPLATE.tasks[0], pick: 'fanciest', bags: 9 }] })
+ assert.equal(badTask.code, 1); assert.match(badTask.out, /pick must be/); assert.match(badTask.out, /bags must be/)
+ assert.ok(existsSync(join(ROOT, 'LICENSE')))
+})
diff --git a/store/agents/jev-browser/toolchain/README.md b/store/agents/jev-browser/toolchain/README.md
new file mode 100644
index 000000000..e92012621
--- /dev/null
+++ b/store/agents/jev-browser/toolchain/README.md
@@ -0,0 +1,44 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
+
+## Going live
+
+Without a key everything runs on the offline stand-in and the pane says `MOCK`. For the real model,
+give the harness a key. The viewer is started by the Harness daemon, which does not see variables
+you export in a shell, so the reliable place is a small file in your home folder:
+
+```sh
+mkdir -p ~/.config/typesafe && chmod 700 ~/.config/typesafe
+printf 'TYPESAFE_API_KEY=%s\n' 'paste-your-key-here' > ~/.config/typesafe/credentials
+chmod 600 ~/.config/typesafe/credentials
+```
+
+Two routes work, and both speak the same question format:
+
+| route | what goes in the file | where to get it |
+|---|---|---|
+| TypeSafe direct | `TYPESAFE_API_KEY=...` | https://console.typesafe.ai/keys (there may be a waitlist) |
+| Cloudflare Workers AI | `CLOUDFLARE_ACCOUNT_ID=...` and `CLOUDFLARE_API_TOKEN=...` | a Cloudflare API token with Workers AI permission, no TypeSafe waitlist |
+
+Environment variables of the same names win over the file. Restart the harness after changing the
+file. `toolchain/doctor.sh` prints which route is active and never prints the key. One file serves
+every Jev harness on the machine. Never paste a key into the chat, and never save one in the
+workspace. Under `node --test`, or with `JEV_OFFLINE=1`, a key is ignored so tests stay deterministic.
diff --git a/store/agents/jev-browser/toolchain/check.mjs b/store/agents/jev-browser/toolchain/check.mjs
new file mode 100644
index 000000000..8c54e78de
--- /dev/null
+++ b/store/agents/jev-browser/toolchain/check.mjs
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+// check.mjs — validate a site.json for the Jev Browser harness: every number's range and every
+// task's shape. Prints one line per problem and exits 1 on any error.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+let errors = 0
+const error = (msg) => { errors++; console.log(`error ${msg}`) }
+const warn = (msg) => console.log(`warn ${msg}`)
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'site.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read site.json: ${e.message}`)
+ process.exit(1)
+}
+
+const range = (key, lo, hi, what) => {
+ if (p[key] === undefined) return
+ if (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < lo || p[key] > hi) error(`${key} (${what}) must be a number from ${lo} to ${hi}`)
+}
+range('stepMs', 40, 2000, 'milliseconds per Jev decision')
+range('distraction', 0, 1, 'the dial')
+range('flights', 4, 9, 'result rows per search')
+range('maxSteps', 12, 200, 'steps before a task fails')
+range('seed', 0, 1e9, 'random seed')
+
+if (!Array.isArray(p.tasks) || p.tasks.length < 1 || p.tasks.length > 40) error('tasks must be a list of 1 to 40 bookings')
+else p.tasks.forEach((t, i) => {
+ const at = `tasks[${i}]`
+ for (const k of ['from', 'to', 'day', 'name', 'email']) if (typeof t?.[k] !== 'string' || !t[k].trim()) error(`${at}.${k} must be a non-empty string`)
+ if (typeof t?.from === 'string' && !/^[A-Za-z]{2,4}$/.test(t.from.trim())) error(`${at}.from must be an airport code of 2 to 4 letters`)
+ if (typeof t?.to === 'string' && !/^[A-Za-z]{2,4}$/.test(t.to.trim())) error(`${at}.to must be an airport code of 2 to 4 letters`)
+ if (typeof t?.from === 'string' && t.from === t?.to) error(`${at}: from and to are the same airport`)
+ if (!['cheapest', 'earliest', 'latest'].includes(t?.pick)) error(`${at}.pick must be "cheapest", "earliest" or "latest"`)
+ if (typeof t?.nonstop !== 'boolean') error(`${at}.nonstop must be true or false`)
+ if (!Number.isInteger(t?.bags) || t.bags < 0 || t.bags > 3) error(`${at}.bags must be a whole number from 0 to 3`)
+ if (typeof t?.email === 'string' && !/@example\.(com|org|net)$/.test(t.email.trim())) warn(`${at}.email: use a made-up example.com address`)
+ if (typeof t?.name === 'string' && /[()]/.test(t.name)) error(`${at}.name must not contain brackets`)
+})
+if (Array.isArray(p.tasks) && new Set(p.tasks.map((t) => t?.pick)).size === 1 && p.tasks.length > 2) warn('every task uses the same pick rule: mix cheapest, earliest and latest')
+if (!p.title || typeof p.title !== 'string') warn('no title')
+if (!p.style || typeof p.style !== 'string') warn('no style line: tell Jev how to work')
+else if (p.style.length > 600) error('style must be 600 characters or fewer')
+
+console.log(errors ? `fail site.json has ${errors} error${errors > 1 ? 's' : ''}` : 'ok site.json is valid')
+process.exit(errors ? 1 : 0)
diff --git a/store/agents/jev-browser/toolchain/doctor.sh b/store/agents/jev-browser/toolchain/doctor.sh
new file mode 100755
index 000000000..c74f27245
--- /dev/null
+++ b/store/agents/jev-browser/toolchain/doctor.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Browser viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+cd "$(dirname "$0")/.."
+node -e "import('./toolchain/jev.mjs').then((m) => console.log('ok Jev: ' + m.describeCredentials())).catch((e) => console.log('warn Jev client did not load: ' + e.message))"
+echo "done"
diff --git a/store/agents/jev-browser/toolchain/init-workspace.sh b/store/agents/jev-browser/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-browser/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-browser/toolchain/jev.mjs b/store/agents/jev-browser/toolchain/jev.mjs
new file mode 100644
index 000000000..190c7e9ac
--- /dev/null
+++ b/store/agents/jev-browser/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
+// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
+// score a position on a 2..10 level scale — a float plus per-level probabilities
+//
+// Questions are authored as options[] / legend{} (or an option -> description map) and translated
+// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The generic mock reads
+// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
+// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
+// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ return key ? 'typesafe' : 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ return (h >>> 0) / 4294967296
+}
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+
+/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
+export function stems(text) {
+ const out = []
+ for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
+ if (w.length < 2 || STOP.has(w)) continue
+ out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
+ }
+ return out
+}
+
+/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
+function evidence(stateStems, needle) {
+ const want = [...new Set(stems(needle))]
+ if (!want.length) return 0
+ let hit = 0
+ for (const w of want) if (stateStems.has(w)) hit++
+ return (hit / Math.sqrt(want.length)) * 1.2
+}
+
+function softmax(raw, temp = 1) {
+ const m = Math.max(...raw)
+ const exps = raw.map((r) => Math.exp((r - m) / temp))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ return exps.map((e) => e / sum)
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic generic mock. It turns the state text + question wording into a plausible
+// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`
+ const S = new Set(stems(text))
+ const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
+
+ if (q.type === 'noul') {
+ const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
+ const no = evidence(S, `${q.raw?.false ?? ''}`)
+ const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
+ const probs = softmax(raw, 0.6)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
+ const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
+ // No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
+ if (raw.every((r) => Math.abs(r) < 0.26)) {
+ const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
+ levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
+ }
+ const probs = softmax(raw, 0.7)
+ const probabilities = {}
+ levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
+ const score = probs.reduce((acc, p, i) => acc + p * i, 0)
+ return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// Imports are hoisted, so they can live here with the code that needs them.
+import { readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ out.raw = isMap(q.criteria) ? q.criteria : null
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+// ---------------------------------------------------------------------------
+// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
+// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
+// you happen to have open. Two live routes are supported, both speaking the same question format:
+// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
+// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
+// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
+// ---------------------------------------------------------------------------
+const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN']
+let credCache = null
+export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
+
+function readCredentialFile() {
+ const now = Date.now()
+ const path = credentialsPath()
+ if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
+ const values = {}
+ try {
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
+ if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
+ }
+ } catch { /* no file: fine */ }
+ credCache = { at: now, path, values }
+ return values
+}
+
+/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
+export function resolveCredentials(explicitKey) {
+ if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
+ // Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
+ // key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
+ if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
+ const file = readCredentialFile()
+ const get = (k) => process.env[k] || file[k] || ''
+ const key = explicitKey || get('TYPESAFE_API_KEY')
+ if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
+ const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
+ if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
+ return null
+}
+
+/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
+export function describeCredentials() {
+ const c = resolveCredentials()
+ if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
+ return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
+}
+
+async function liveEvaluate(body, cred) {
+ const endpoint = cred.url
+ const key = cred.secret
+ const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } } : body
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) {
+ const data = await res.json()
+ // Cloudflare wraps the model's reply as { result, success, errors }.
+ if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
+ return data?.result?.answers ? data.result : data
+ }
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const cred = resolveCredentials(key)
+ const client = cred ? cred.provider : 'mock'
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (cred) {
+ const data = await liveEvaluate({ model, state, questions: wire }, cred)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-browser/toolchain/setup.sh b/store/agents/jev-browser/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-browser/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-browser/toolchain/viewer.sh b/store/agents/jev-browser/toolchain/viewer.sh
new file mode 100755
index 000000000..269edcb69
--- /dev/null
+++ b/store/agents/jev-browser/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Browser viewer (Jev operates a made-up travel site, one picked element per step).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-browser/viewer/base.css b/store/agents/jev-browser/viewer/base.css
new file mode 100644
index 000000000..c41ddcd46
--- /dev/null
+++ b/store/agents/jev-browser/viewer/base.css
@@ -0,0 +1,83 @@
+/* base.css — the shared look of the Jev flagship viewers. Load before studio.css.
+ Set --accent / --accent2 in studio.css to give a harness its own colour. */
+:root {
+ --bg: #07080d; --panel: #10121a; --panel2: #161925; --line: #232838; --line2: #2e3550;
+ --ink: #e9ecf5; --dim: #8b92aa; --faint: #565d75;
+ --accent: #a78bfa; --accent2: #6d5bd0;
+ --ok: #34d399; --warn: #fbbf24; --bad: #fb7185; --cyan: #5eead4; --blue: #60a5fa;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ --radius: 12px;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1100px 700px at 75% -10%, color-mix(in srgb, var(--accent) 14%, transparent) 0%, transparent 60%), var(--bg);
+ color: var(--ink); font: 13px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+::selection { background: color-mix(in srgb, var(--accent) 45%, transparent); }
+::-webkit-scrollbar { width: 8px; height: 8px; }
+::-webkit-scrollbar-thumb { background: var(--line2); border-radius: 4px; }
+::-webkit-scrollbar-track { background: transparent; }
+
+#topbar {
+ display: flex; align-items: center; gap: 22px; padding: 10px 18px; flex: none; flex-wrap: wrap;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(20,22,34,.92), rgba(10,11,18,.7)); backdrop-filter: blur(8px);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font: 700 15px var(--mono); letter-spacing: .4px; margin: 0; white-space: nowrap; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 14px var(--accent); animation: dot 2.4s ease-in-out infinite; }
+@keyframes dot { 50% { transform: scale(.72); opacity: .7; } }
+.brand .sub { color: var(--dim); font-size: 11px; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; min-width: 54px; }
+.stat label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+button, .btn {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line2); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: border-color .15s, filter .15s, transform .05s; user-select: none;
+}
+button:hover { border-color: var(--accent); }
+button:active { transform: translateY(1px); }
+button.primary { background: linear-gradient(135deg, var(--accent2), var(--accent)); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.12); }
+button.ghost { background: transparent; }
+button.on { border-color: var(--accent); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
+button[disabled] { opacity: .45; cursor: default; }
+kbd { font: 600 10px var(--mono); padding: 1px 5px; border: 1px solid var(--line2); border-bottom-width: 2px; border-radius: 4px; color: var(--dim); }
+input[type=text], input[type=search], select, textarea {
+ font: 13px var(--mono); color: var(--ink); background: #0b0d14; border: 1px solid var(--line2); border-radius: 8px; padding: 7px 10px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+input[type=range] { accent-color: var(--accent); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow: auto; }
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 14px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; background: rgba(12,13,20,.55); }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; }
+.panel-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--dim); margin-bottom: 9px; display: flex; align-items: center; gap: 8px; }
+.panel-title .right { margin-left: auto; text-transform: none; letter-spacing: 0; }
+.how { color: var(--dim); font-size: 12.5px; line-height: 1.55; }
+.how b { color: var(--ink); } .how code { color: var(--warn); }
+.pill { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line2); color: var(--dim); }
+.pill.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
+.pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
+.pill.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); }
+
+.canvas-wrap { position: relative; flex: 1; min-height: 320px; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #05060a; }
+.canvas-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.banner { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); padding: 9px 20px; border-radius: 10px; font: 700 14px var(--mono); white-space: nowrap; backdrop-filter: blur(6px); }
+.banner.ok { background: rgba(16,185,129,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 34px rgba(16,185,129,.35); }
+.banner.bad { background: rgba(225,29,72,.16); border: 1px solid var(--bad); color: var(--bad); box-shadow: 0 0 34px rgba(225,29,72,.35); }
+.hidden { display: none !important; }
+.cfg-error { margin: 0 16px; padding: 8px 12px; border: 1px solid var(--bad); border-radius: 8px; color: var(--bad); background: rgba(225,29,72,.08); font-size: 12px; }
+
+@media (max-width: 900px) {
+ main { flex-direction: column; overflow: auto; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); overflow: visible; }
+ body { overflow: auto; }
+}
diff --git a/store/agents/jev-browser/viewer/index.html b/store/agents/jev-browser/viewer/index.html
new file mode 100644
index 000000000..374a5feb7
--- /dev/null
+++ b/store/agents/jev-browser/viewer/index.html
@@ -0,0 +1,87 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Browser</title>
+<link rel="stylesheet" href="/base.css">
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1 id="title">Jev Browser</h1><span class="sub">a made-up travel site · Jev picks every click</span></div>
+ <div class="stats">
+ <div class="stat"><label>Bookings</label><span id="s-tasks">0</span></div>
+ <div class="stat"><label>Exactly right</label><span id="s-ok">—</span></div>
+ <div class="stat"><label>Steps each</label><span id="s-steps">—</span></div>
+ <div class="stat"><label>Lost clicks</label><span id="s-mis">0</span></div>
+ <div class="stat big"><label>Seconds each</label><span id="s-secs">—</span></div>
+ <div class="stat big"><label>Decisions / s</label><span id="s-rate">—</span></div>
+ <div class="stat big"><label>Cost so far</label><span id="s-cost">$0</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="step">Step</button>
+ <button id="reset" class="primary">Reset</button>
+ </div>
+ </div>
+ <div id="cfgError" class="cfg-error hidden"></div>
+ <main>
+ <section id="stage">
+ <div class="task panel">
+ <div class="task-row">
+ <span class="pill" id="taskNo">TASK 1/4</span>
+ <span id="goal" class="goal"></span>
+ </div>
+ <div class="task-meters">
+ <span><b id="m-time">0.0</b> s</span><span><b id="m-steps">0</b> steps</span><span><b id="m-cost">$0</b></span>
+ <span id="m-note" class="note"></span>
+ </div>
+ </div>
+ <div class="window" id="window">
+ <div class="chrome">
+ <span class="lights"><i></i><i></i><i></i></span>
+ <span class="tab"><span class="fav"></span><span id="tabTitle">SkyHop</span></span>
+ <span class="url"><span class="lock">●</span><span id="url">https://skyhop.example/</span></span>
+ </div>
+ <div class="viewport" id="viewport">
+ <div class="page" id="page"></div>
+ <div class="cursor" id="cursor"><svg viewBox="0 0 24 24" width="26" height="26"><path d="M4 2l15 9-7 1.6L9.6 20z" fill="#fff" stroke="#0b0d14" stroke-width="1.6" stroke-linejoin="round"/></svg></div>
+ <div class="stamp hidden" id="stamp"></div>
+ </div>
+ </div>
+ <div class="toolbar panel">
+ <label class="slider">Distraction <input id="distraction" type="range" min="0" max="1" step="0.05" value="0.25"> <b id="distractionVal">0.25</b></label>
+ <label class="slider">Step <input id="stepMs" type="range" min="60" max="900" step="10" value="170"> <b id="stepMsVal">170</b> ms</label>
+ <button id="popup">Throw a pop-up</button>
+ <button id="nextTask">Next task</button>
+ <button id="heat" class="on">Show Jev's mind</button>
+ <span class="hint">The page is live: <b>click anything on it yourself</b> and Jev has to deal with what you did.</span>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">What Jev reads</div>
+ <pre id="stateText" class="statetext"></pre>
+ </div>
+ <div class="panel">
+ <div class="panel-title">How it works</div>
+ <div class="how">
+ Jev never sees the screen. Each step the page is written out as the text above, and Jev
+ picks <b>one element out of the list</b>, a new list every step, plus two yes/no reads, in one
+ call. Clicking an input fills it with the right value from the task.<br><br>
+ <b>Distraction</b> adds cookie walls, pop-ups, decoy buttons and <b>layout shifts</b> that land
+ between reading the page and clicking it, so a click can hit the wrong thing. Every
+ booking is checked against the task. The site and the flights are made up.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Bookings</div>
+ <ul id="feed"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-browser/viewer/jev-hud.js b/store/agents/jev-browser/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-browser/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-browser/viewer/kit.mjs b/store/agents/jev-browser/viewer/kit.mjs
new file mode 100644
index 000000000..f80d29b7d
--- /dev/null
+++ b/store/agents/jev-browser/viewer/kit.mjs
@@ -0,0 +1,112 @@
+// kit.mjs — the boring, security-relevant half of a Jev viewer, written once:
+// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
+// /control, plus an atomic verdict writer and a safe JSON config watcher.
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
+import { join, extname } from 'node:path'
+import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
+
+export const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+/** Deterministic PRNG so every run of a demo is reproducible. */
+export function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/**
+ * Serve a viewer.
+ * @param {object} o
+ * @param {string} o.here the viewer directory (static files live here)
+ * @param {number} o.port 0 = ephemeral
+ * @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
+ * @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
+ * @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ */
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+ const clients = new Set()
+ const allowed = new Set(files)
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ // Loopback only: a page on another origin (DNS rebinding) must not reach this server.
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ const path = url.pathname
+ try {
+ if (req.method === 'GET') {
+ const name = path === '/' ? 'index.html' : path.slice(1)
+ if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
+ if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (path === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
+ clients.add(res)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ }
+ if (req.method === 'POST' && path === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 65536) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const reply = control ? await control(String(j.cmd ?? ''), j) : null
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
+ res.writeHead(404); res.end('Not found')
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
+ }
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ clients,
+ /** Push a named SSE event (default 'state') to every connected pane. */
+ broadcast(obj, event = 'state') {
+ const line = `event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`
+ for (const c of clients) c.write(line)
+ },
+ async close() { for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+/** Atomic write of .harness/verdict.json (the harness reads this file; never edit it by hand). */
+export function writeVerdict(workspace, verdict) {
+ const dir = join(workspace, '.harness')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify({ spec: 1, ...verdict, updatedAt: new Date().toISOString() }))
+ renameSync(file + '.tmp', file)
+}
+
+/**
+ * Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
+ * good config and reports the parse error instead of crashing the demo.
+ * @returns {{ get(): object, error(): string|null, close(): void }}
+ */
+export function watchConfig(file, defaults, onChange) {
+ let cfg = { ...defaults }, err = null, timer = null
+ const load = () => {
+ try { cfg = { ...defaults, ...JSON.parse(readFileSync(file, 'utf8')) }; err = null }
+ catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
+ }
+ load()
+ let watcher = null
+ try {
+ watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ } catch { /* file may not exist yet; defaults stand */ }
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+}
diff --git a/store/agents/jev-browser/viewer/mock.mjs b/store/agents/jev-browser/viewer/mock.mjs
new file mode 100644
index 000000000..210d7b56b
--- /dev/null
+++ b/store/agents/jev-browser/viewer/mock.mjs
@@ -0,0 +1,82 @@
+// mock.mjs — the offline stand-in for Jev in this harness. It reads ONLY the state text and the
+// option descriptions that live Jev also gets, and answers with a full probability distribution.
+// It is a careful form-filler, not Jev's judgement; the pane badges it MOCK.
+
+export function readTask(text) {
+ const m = text.match(/TASK: Book the (cheapest|earliest|latest) (nonstop )?flight from (\S+) to (\S+) on (\S+) for (.+?) \((\S+?)\), (no|\d+) checked bags?/)
+ if (!m) return null
+ return { pick: m[1], nonstop: !!m[2], from: m[3], to: m[4], day: m[5], name: m[6], email: m[7], bags: m[8] === 'no' ? 0 : Number(m[8]) }
+}
+
+const toMin = (s) => { const [h, m] = s.split(':').map(Number); return h * 60 + m }
+
+function parseRow(desc) {
+ const m = desc.match(/(Sponsored · )?(.+?) · (\S+) to (\S+) · departs (\d\d:\d\d) arrives (\d\d:\d\d) · (nonstop|\d+ stops?) · \$(\d+)/)
+ if (!m) return null
+ return { sponsored: !!m[1], from: m[3], to: m[4], dep: toMin(m[5]), stops: m[7] === 'nonstop' ? 0 : parseInt(m[7], 10), price: Number(m[8]) }
+}
+
+/** Which element a careful person would act on next, from the text alone. */
+export function nextTarget(text, options, descriptions) {
+ const task = readTask(text)
+ if (!task) return null
+ const has = (id) => options.includes(id)
+ const valueOf = (id) => (descriptions[id]?.match(/value "([^"]*)"/) ?? [])[1]
+ const page = (text.match(/^PAGE: (\w+)/m) ?? [])[1]
+
+ if (/^OVERLAY: a /m.test(text)) return ['cookie-reject', 'popup-no', 'popup-close', 'cookie-accept'].find(has) ?? null
+ if (page === 'promo') return has('back-to-booking') ? 'back-to-booking' : null
+ if (page === 'search') {
+ for (const id of ['from', 'to', 'day']) if (has(id) && valueOf(id) === '') return id
+ return has('search-flights') ? 'search-flights' : null
+ }
+ if (page === 'results') {
+ const rows = options.filter((id) => id.startsWith('select-')).map((id) => ({ id, ...parseRow(descriptions[id] ?? '') })).filter((r) => r.to)
+ const ok = rows.filter((r) => !r.sponsored && r.to === task.to && r.from === task.from && (!task.nonstop || r.stops === 0))
+ if (!ok.length) return task.nonstop && has('nonstop-only') && valueOf('nonstop-only') === 'on' ? 'nonstop-only' : null
+ const by = task.pick === 'cheapest' ? (r) => r.price : task.pick === 'earliest' ? (r) => r.dep : (r) => -r.dep
+ return ok.sort((a, b) => by(a) - by(b))[0].id
+ }
+ if (page === 'details') {
+ const sum = text.match(/· (\S+) to (\S+) · departs/)
+ if (sum && sum[2] !== task.to && has('change-flight')) return 'change-flight'
+ if (task.nonstop && /· \d+ stops? · \$/.test(text.match(/^ {2}.*departs.*$/m)?.[0] ?? '') && has('change-flight')) return 'change-flight'
+ if (has('name') && valueOf('name') === '') return 'name'
+ if (has('email') && valueOf('email') === '') return 'email'
+ const bags = Number((text.match(/Checked bags: (\d+)/) ?? [])[1] ?? 0)
+ if (bags < task.bags && has('bag-add')) return 'bag-add'
+ if (bags > task.bags && has('bag-remove')) return 'bag-remove'
+ if (has('insurance') && valueOf('insurance') === 'on') return 'insurance'
+ return has('continue') ? 'continue' : null
+ }
+ if (page === 'review') {
+ if (has('flex') && valueOf('flex') === 'on') return 'flex'
+ const who = text.match(/· (\d+) checked bag\(s\)( · insurance)?/)
+ if (who && (Number(who[1]) !== task.bags || who[2])) return 'back'
+ return has('confirm') ? 'confirm' : null
+ }
+ return null
+}
+
+export function browserMock(text, id, q) {
+ if (!/^TASK: /m.test(text)) return null // not our state text: let the generic mock answer
+ if (id === 'action') {
+ const options = q.options ?? []
+ if (!options.length) return null
+ const target = nextTarget(text, options, q.descriptions ?? {})
+ const words = new Set((text.match(/^TASK: .*$/m)?.[0] ?? '').toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2))
+ // Everything that is not the target still gets a little mass, more if it shares the task's words.
+ const raw = options.map((o) => {
+ if (o === target) return 5.2
+ const d = `${o} ${q.descriptions?.[o] ?? ''}`.toLowerCase().split(/[^a-z0-9]+/)
+ return 0.6 + 0.5 * d.filter((w) => words.has(w)).length
+ })
+ const exps = raw.map((r) => Math.exp(r - Math.max(...raw))), sum = exps.reduce((a, b) => a + b, 0)
+ const probabilities = Object.fromEntries(options.map((o, i) => [o, exps[i] / sum]))
+ const choice = target ?? options[exps.indexOf(Math.max(...exps))]
+ return { type: 'choice', choice, confidence: probabilities[choice], probabilities }
+ }
+ if (id === 'done') return { type: 'noul', noul: /^PAGE: done/m.test(text) ? 0.97 : 0.02 }
+ if (id === 'obstacle') return { type: 'noul', noul: /^OVERLAY: a /m.test(text) ? 0.95 : 0.04 }
+ return null
+}
diff --git a/store/agents/jev-browser/viewer/sim.mjs b/store/agents/jev-browser/viewer/sim.mjs
new file mode 100644
index 000000000..ba9a7ddc6
--- /dev/null
+++ b/store/agents/jev-browser/viewer/sim.mjs
@@ -0,0 +1,289 @@
+// sim.mjs — a tiny made-up travel site ("SkyHop") and the booking tasks Jev runs on it.
+// The site is a five-page funnel (search, results, details, review, done) rendered to a flat list of
+// elements with rectangles on a 1000x620 page, so the same data drives what Jev reads, where the
+// cursor goes and what a late click lands on. Pure functions over a plain `world` object.
+import { mulberry32 } from './kit.mjs'
+
+export const PAGE_W = 1000, PAGE_H = 620
+export const DEFAULT = {
+ title: 'Jev Browser',
+ description: 'Jev books flights on a made-up travel site, one click at a time.',
+ site: 'SkyHop',
+ stepMs: 170, // one Jev decision (one click or one field) per step
+ distraction: 0.25, // 0..1 — cookie walls, pop-ups, decoy buttons and layout shifts. THE DIAL.
+ flights: 7, // result rows per search (4..9)
+ maxSteps: 45, // a task fails if it takes more steps than this
+ seed: 11,
+ style: 'Finish the task in as few actions as you can. Fill every field the task gives you, choose exactly the flight it asks for, refuse every extra, and close anything that gets in the way.',
+ tasks: [
+ { from: 'SFO', to: 'JFK', day: 'Friday', pick: 'cheapest', nonstop: true, name: 'Ada Park', email: '[email protected]', bags: 1 },
+ { from: 'SEA', to: 'AUS', day: 'Monday', pick: 'earliest', nonstop: false, name: 'Omar Reyes', email: '[email protected]', bags: 0 },
+ { from: 'BOS', to: 'LAX', day: 'Sunday', pick: 'cheapest', nonstop: false, name: 'Mei Tanaka', email: '[email protected]', bags: 2 },
+ { from: 'DEN', to: 'MIA', day: 'Wednesday', pick: 'latest', nonstop: true, name: 'Lena Okafor', email: '[email protected]', bags: 1 },
+ ],
+}
+
+const AIRLINES = ['Nimbus', 'Kestrel', 'Blue Heron', 'Polar', 'Sundial', 'Alto']
+const NEAR = { JFK: 'EWR', LAX: 'BUR', MIA: 'FLL', AUS: 'SAT', SFO: 'OAK', SEA: 'PDX', BOS: 'PVD', DEN: 'COS' }
+const pad = (n) => String(n).padStart(2, '0')
+const hhmm = (m) => `${pad(Math.floor(m / 60) % 24)}:${pad(m % 60)}`
+
+export function goalText(t) {
+ const bags = t.bags === 0 ? 'no checked bags' : t.bags === 1 ? '1 checked bag' : `${t.bags} checked bags`
+ return `Book the ${t.pick} ${t.nonstop ? 'nonstop ' : ''}flight from ${t.from} to ${t.to} on ${t.day} for ${t.name} (${t.email}), ${bags}. No extras.`
+}
+
+export function cleanTask(t, i = 0) {
+ const s = (v, d) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, 40) : d)
+ const pick = ['cheapest', 'earliest', 'latest'].includes(t?.pick) ? t.pick : 'cheapest'
+ return { from: s(t?.from, 'SFO').toUpperCase().slice(0, 4), to: s(t?.to, 'JFK').toUpperCase().slice(0, 4), day: s(t?.day, 'Friday'), pick, nonstop: !!t?.nonstop, name: s(t?.name, `Guest ${i + 1}`).replace(/[()]/g, ''), email: s(t?.email, `guest${i + 1}@example.com`).replace(/[\s()]/g, ''), bags: Math.max(0, Math.min(3, Math.round(Number(t?.bags) || 0))) }
+}
+
+function makeFlights(task, n, rng) {
+ const rows = []
+ for (let i = 0; i < n; i++) {
+ const dep = 5 * 60 + Math.floor(rng() * 16 * 12) * 5, stops = rng() < 0.45 ? 0 : rng() < 0.75 ? 1 : 2
+ rows.push({ id: `f${i + 1}`, airline: AIRLINES[(rng() * AIRLINES.length) | 0], dep, arr: dep + 170 + stops * 95 + Math.floor(rng() * 12) * 5, stops, price: 120 + Math.floor(rng() * 56) * 5 + (stops === 0 ? 60 : 0), to: task.to, sponsored: false })
+ }
+ if (task.nonstop && !rows.some((r) => r.stops === 0)) rows[(rng() * rows.length) | 0].stops = 0
+ // No ties on the thing the task sorts by, so there is exactly one right answer.
+ const key = task.pick === 'cheapest' ? 'price' : 'dep'
+ const seen = new Set()
+ for (const r of rows) { while (seen.has(r[key])) r[key] += 5; seen.add(r[key]) }
+ rows.sort((a, b) => a.dep - b.dep)
+ return rows
+}
+
+export function bestFlight(task, flights) {
+ const ok = flights.filter((f) => !f.sponsored && f.to === task.to && (!task.nonstop || f.stops === 0))
+ const by = task.pick === 'cheapest' ? (f) => f.price : task.pick === 'earliest' ? (f) => f.dep : (f) => -f.dep
+ return ok.sort((a, b) => by(a) - by(b))[0] ?? null
+}
+
+export function createWorld(cfg, taskIndex = 0, round = 0) {
+ const tasks = (Array.isArray(cfg.tasks) && cfg.tasks.length ? cfg.tasks : DEFAULT.tasks).map(cleanTask)
+ const task = tasks[taskIndex % tasks.length]
+ const rng = mulberry32((Number(cfg.seed) || 11) + taskIndex * 131 + round * 7919)
+ const flights = makeFlights(task, Math.max(4, Math.min(9, Math.round(cfg.flights) || 7)), rng)
+ const d = cfg.distraction
+ return {
+ rng, task, taskIndex, taskCount: tasks.length, goal: goalText(task),
+ page: 'search', flights, best: bestFlight(task, flights),
+ form: { from: '', to: '', day: '', promo: '' }, nonstopOnly: false, sort: 'dep', sponsoredShown: false,
+ chosen: null, details: { name: '', email: '', bags: 0, insurance: false, newsletter: false }, flex: false,
+ overlay: rng() < d * 0.9 ? { kind: 'cookie' } : null,
+ steps: 0, wasted: 0, misclicks: 0, startedAt: null, finishedAt: null,
+ status: 'running', result: null, history: [], lastAction: null, shake: null,
+ }
+}
+
+// ---------------------------------------------------------------- layout: page -> elements
+const el = (id, role, label, rect, extra = {}) => ({ id, role, label, rect, act: role !== 'text' && role !== 'card', ...extra })
+
+function rowText(f, task) {
+ const stops = f.stops === 0 ? 'nonstop' : f.stops === 1 ? '1 stop' : `${f.stops} stops`
+ return `${f.sponsored ? 'Sponsored · ' : ''}${f.airline} · ${task.from} to ${f.to} · departs ${hhmm(f.dep)} arrives ${hhmm(f.arr)} · ${stops} · $${f.price}`
+}
+
+export function visibleFlights(world) {
+ let rows = world.flights.filter((f) => !world.nonstopOnly || f.stops === 0)
+ rows = [...rows].sort((a, b) => (world.sort === 'price' ? a.price - b.price : world.sort === 'late' ? b.dep - a.dep : a.dep - b.dep))
+ if (world.sponsoredShown) rows = [world.sponsoredRow, ...rows]
+ return rows.slice(0, 8)
+}
+
+export function elements(world, cfg) {
+ const d = cfg.distraction, t = world.task, out = []
+ out.push(el('logo', 'text', cfg.site, [28, 14, 160, 30], { tone: 'logo' }))
+ if (d > 0.15) for (const [i, name] of ['Hotels', 'Cars', 'Deals'].entries()) out.push(el(`nav-${name.toLowerCase()}`, 'link', name, [760 + i * 78, 14, 70, 30], { tone: 'decoy' }))
+
+ if (world.page === 'search') {
+ out.push(el('h', 'text', 'Where to?', [60, 84, 400, 44], { tone: 'h1' }))
+ out.push(el('card', 'card', '', [40, 140, 920, d > 0.3 ? 300 : 230]))
+ out.push(el('from', 'input', 'From', [70, 180, 250, 56], { value: world.form.from }))
+ out.push(el('to', 'input', 'To', [340, 180, 250, 56], { value: world.form.to }))
+ out.push(el('day', 'input', 'Day', [610, 180, 200, 56], { value: world.form.day }))
+ const ready = world.form.from && world.form.to && world.form.day
+ out.push(el('search-flights', 'button', 'Search flights', [70, 270, 220, 54], { tone: 'primary', disabled: !ready, note: ready ? '' : 'disabled until From, To and Day are filled' }))
+ if (d > 0.1) out.push(el('search-hotels', 'button', 'Search hotels', [310, 270, 190, 54], { tone: 'decoy' }))
+ if (d > 0.45) out.push(el('search-cars', 'button', 'Search flights + cars', [520, 270, 230, 54], { tone: 'decoy' }))
+ if (d > 0.3) out.push(el('promo', 'input', 'Promo code (optional)', [70, 356, 300, 50], { value: world.form.promo, tone: 'decoy' }))
+ } else if (world.page === 'results') {
+ out.push(el('h', 'text', `${t.from} to ${t.to} · ${t.day}`, [60, 74, 500, 40], { tone: 'h1' }))
+ out.push(el('nonstop-only', 'toggle', 'Nonstop only', [60, 122, 170, 38], { value: world.nonstopOnly ? 'on' : 'off' }))
+ out.push(el('sort-price', 'button', 'Cheapest first', [250, 122, 160, 38], { tone: world.sort === 'price' ? 'on' : 'quiet' }))
+ out.push(el('sort-early', 'button', 'Earliest first', [420, 122, 160, 38], { tone: world.sort === 'dep' ? 'on' : 'quiet' }))
+ out.push(el('sort-late', 'button', 'Latest first', [590, 122, 150, 38], { tone: world.sort === 'late' ? 'on' : 'quiet' }))
+ visibleFlights(world).forEach((f, i) => {
+ const y = 176 + i * 54
+ out.push(el(`row-${f.id}`, 'text', rowText(f, t), [60, y, 730, 46], { tone: f.sponsored ? 'sponsored' : 'row' }))
+ out.push(el(`select-${f.id}`, 'button', 'Select', [806, y + 3, 134, 40], { tone: f.sponsored ? 'decoy' : 'primary', context: rowText(f, t) }))
+ })
+ } else if (world.page === 'details') {
+ const f = world.chosen
+ out.push(el('h', 'text', 'Passenger details', [60, 74, 500, 40], { tone: 'h1' }))
+ out.push(el('sum', 'text', f ? rowText(f, t) : '', [60, 118, 880, 34], { tone: 'row' }))
+ out.push(el('name', 'input', 'Full name', [60, 176, 400, 56], { value: world.details.name }))
+ out.push(el('email', 'input', 'Email', [480, 176, 400, 56], { value: world.details.email }))
+ out.push(el('bags', 'text', `Checked bags: ${world.details.bags}`, [60, 262, 220, 44], { tone: 'label' }))
+ out.push(el('bag-remove', 'button', 'Remove a bag', [290, 262, 160, 44], { tone: 'quiet', disabled: world.details.bags === 0 }))
+ out.push(el('bag-add', 'button', 'Add a bag', [462, 262, 140, 44], { tone: 'quiet', disabled: world.details.bags >= 3 }))
+ if (d > 0.1) out.push(el('insurance', 'toggle', 'Add travel insurance +$49', [60, 334, 310, 44], { value: world.details.insurance ? 'on' : 'off', tone: 'decoy' }))
+ if (d > 0.35) out.push(el('newsletter', 'toggle', 'Email me deals', [390, 334, 200, 44], { value: world.details.newsletter ? 'on' : 'off', tone: 'decoy' }))
+ const ready = world.details.name && world.details.email
+ out.push(el('continue', 'button', 'Continue', [60, 414, 200, 54], { tone: 'primary', disabled: !ready, note: ready ? '' : 'disabled until name and email are filled' }))
+ out.push(el('change-flight', 'button', 'Change flight', [280, 414, 180, 54], { tone: 'quiet' }))
+ } else if (world.page === 'review') {
+ const f = world.chosen
+ out.push(el('h', 'text', 'Review your booking', [60, 74, 500, 40], { tone: 'h1' }))
+ out.push(el('sum', 'text', f ? rowText(f, t) : '', [60, 124, 880, 34], { tone: 'row' }))
+ out.push(el('who', 'text', `${world.details.name} · ${world.details.email} · ${world.details.bags} checked bag(s)${world.details.insurance ? ' · insurance +$49' : ''}${world.flex ? ' · Flex +$80' : ''}`, [60, 166, 880, 34], { tone: 'row' }))
+ out.push(el('total', 'text', `Total $${(f?.price ?? 0) + world.details.bags * 35 + (world.details.insurance ? 49 : 0) + (world.flex ? 80 : 0)}`, [60, 224, 400, 44], { tone: 'h1' }))
+ out.push(el('confirm', 'button', 'Confirm booking', [60, 330, 240, 56], { tone: 'primary' }))
+ if (d > 0.2) out.push(el('flex', 'toggle', 'Upgrade to Flex +$80', [320, 330, 270, 56], { value: world.flex ? 'on' : 'off', tone: 'decoy' }))
+ out.push(el('back', 'button', 'Back', [610, 330, 120, 56], { tone: 'quiet' }))
+ } else if (world.page === 'promo') {
+ out.push(el('h', 'text', 'Hotel deals near you', [60, 84, 600, 44], { tone: 'h1' }))
+ out.push(el('p', 'text', 'You left your booking. Nothing here helps with the task.', [60, 140, 800, 34], { tone: 'row' }))
+ out.push(el('back-to-booking', 'button', 'Back to my booking', [60, 210, 260, 54], { tone: 'primary' }))
+ } else if (world.page === 'done') {
+ out.push(el('h', 'text', world.result?.ok ? 'Booked. Exactly as asked.' : 'Booked, but not what was asked.', [60, 110, 880, 50], { tone: world.result?.ok ? 'ok' : 'bad' }))
+ out.push(el('p', 'text', world.result?.why ?? '', [60, 176, 880, 34], { tone: 'row' }))
+ }
+
+ if (world.overlay?.kind === 'cookie') {
+ out.push(el('cookie', 'card', '', [0, 486, 1000, 134], { tone: 'overlay' }))
+ out.push(el('cookie-text', 'text', 'We value your privacy. This made-up site uses made-up cookies.', [40, 512, 600, 40], { tone: 'overlaytext' }))
+ out.push(el('cookie-accept', 'button', 'Accept all', [690, 524, 130, 46], { tone: 'primary', overlay: true }))
+ out.push(el('cookie-reject', 'button', 'Reject', [836, 524, 120, 46], { tone: 'quiet', overlay: true }))
+ } else if (world.overlay?.kind === 'popup') {
+ const [x, y] = world.overlay.at
+ out.push(el('popup', 'card', '', [x, y, 480, 300], { tone: 'overlay' }))
+ out.push(el('popup-text', 'text', 'Wait! 20% off hotels if you book in the next 10 minutes.', [x + 30, y + 60, 420, 80], { tone: 'overlaytext' }))
+ out.push(el('popup-claim', 'button', 'Claim my offer', [x + 40, y + 210, 190, 50], { tone: 'decoy', overlay: true }))
+ out.push(el('popup-no', 'button', 'No thanks', [x + 250, y + 210, 170, 50], { tone: 'quiet', overlay: true }))
+ out.push(el('popup-close', 'button', '×', [x + 430, y + 12, 36, 36], { tone: 'quiet', overlay: true }))
+ }
+ // While an overlay is up, the page under it cannot be used.
+ if (world.overlay) for (const e of out) if (e.act && !e.overlay) { e.blocked = true }
+ return out
+}
+
+const URLS = { search: '/', results: '/flights', details: '/passenger', review: '/review', promo: '/deals/hotels', done: '/confirmed' }
+export const pageUrl = (world, cfg) => `https://${String(cfg.site).toLowerCase().replace(/[^a-z0-9]+/g, '')}.example${URLS[world.page] ?? '/'}`
+
+/** The text Jev reads: the task, the page, and every element it may act on. Nothing hidden. */
+export function observe(world, cfg) {
+ const els = elements(world, cfg)
+ const can = els.filter((e) => e.act && !e.blocked && !e.disabled)
+ const line = (e) => ` ${e.id} ${e.role} "${e.label}"${e.value !== undefined ? ` value "${e.value}"` : ''}${e.context ? ` — ${e.context}` : ''}${e.note ? ` (${e.note})` : ''}`
+ const facts = els.filter((e) => e.role === 'text' && !['logo'].includes(e.tone)).map((e) => ` ${e.label}`)
+ const text = [
+ `You operate a web browser on a travel site. ${cfg.style}`,
+ `TASK: ${world.goal}`,
+ `PAGE: ${world.page} url ${pageUrl(world, cfg)}`,
+ world.overlay ? `OVERLAY: a ${world.overlay.kind === 'cookie' ? 'cookie banner' : 'pop-up'} covers the page. Only its buttons work until it is closed.` : 'OVERLAY: none',
+ 'PAGE TEXT:', ...facts,
+ 'ELEMENTS you can act on (clicking an input fills it with the right value from the task):', ...can.map(line),
+ `RECENT: ${world.history.slice(-4).map((h) => h.id + (h.note ? ` (${h.note})` : '')).join(', ') || 'nothing yet'}`,
+ ].join('\n')
+ const options = Object.fromEntries(can.map((e) => [e.id, `${e.role} "${e.label}"${e.value !== undefined ? ` value "${e.value}"` : ''}${e.context ? ` — ${e.context}` : ''}`]))
+ return { text, options, els }
+}
+
+// ---------------------------------------------------------------- acting
+const inside = (r, x, y) => x >= r[0] && y >= r[1] && x <= r[0] + r[2] && y <= r[1] + r[3]
+
+/**
+ * One step. Jev chose `id` from the page it READ. Then the page may shift before the click lands
+ * (a pop-up opens, a sponsored row pushes the list down). The click goes to the chosen element's
+ * old position and hits whatever is there now. That gap between reading and clicking is the dial.
+ */
+export function act(world, cfg, id) {
+ if (world.status !== 'running') return null
+ world.startedAt ??= world.steps
+ const before = elements(world, cfg)
+ const target = before.find((e) => e.id === id && e.act)
+ world.steps++
+ world.shake = null
+ const rec = { step: world.steps, id, note: '', x: 500, y: 310, landed: id, shift: null }
+ if (!target) { rec.note = 'no such element'; world.wasted++; world.history.push(rec); world.lastAction = rec; return rec }
+ rec.x = target.rect[0] + target.rect[2] / 2; rec.y = target.rect[1] + target.rect[3] / 2
+
+ // The layout shift, decided before the click lands.
+ const d = cfg.distraction
+ if (!world.overlay && world.page !== 'done' && world.rng() < d * 0.22) {
+ world.overlay = { kind: 'popup', at: [120 + Math.floor(world.rng() * 400), 90 + Math.floor(world.rng() * 200)] }
+ rec.shift = 'pop-up'
+ } else if (world.page === 'results' && !world.sponsoredShown && world.rng() < d * 0.5) {
+ const t = world.task
+ world.sponsoredRow = { id: 'ad', airline: 'FlyCheap', dep: 6 * 60 + 10, arr: 6 * 60 + 10 + 300, stops: 0, price: 89, to: NEAR[t.to] ?? 'XXX', sponsored: true }
+ world.sponsoredShown = true
+ rec.shift = 'sponsored row'
+ }
+ let hit = target
+ if (rec.shift) {
+ const now = elements(world, cfg)
+ hit = now.filter((e) => e.act && !e.blocked && inside(e.rect, rec.x, rec.y)).pop() ?? null
+ if (!hit || hit.id !== id) { world.misclicks++; rec.note = hit ? `layout shifted: landed on ${hit.id}` : 'layout shifted: the click hit nothing' }
+ rec.landed = hit?.id ?? null
+ }
+ if (!hit) { world.wasted++; world.history.push(rec); world.lastAction = rec; return finishIfOver(world, cfg, rec) }
+ if (hit.blocked || hit.disabled) { rec.note ||= hit.disabled ? 'disabled' : 'blocked by the overlay'; world.wasted++; world.shake = hit.id; world.history.push(rec); world.lastAction = rec; return finishIfOver(world, cfg, rec) }
+ apply(world, hit.id, rec)
+ world.history.push(rec); if (world.history.length > 80) world.history.shift()
+ world.lastAction = rec
+ return finishIfOver(world, cfg, rec)
+}
+
+function apply(world, id, rec) {
+ const t = world.task
+ const useful = (ok) => { if (!ok) world.wasted++ }
+ if (id === 'cookie-accept' || id === 'cookie-reject' || id === 'popup-no' || id === 'popup-close') { world.overlay = null; return }
+ if (id === 'popup-claim') { world.overlay = null; world.returnTo = world.page; world.page = 'promo'; rec.note ||= 'left the booking'; world.wasted++; return }
+ if (id === 'back-to-booking') { world.page = world.returnTo ?? 'search'; return }
+ if (id.startsWith('nav-') || id === 'search-hotels' || id === 'search-cars') { world.returnTo = world.page; world.page = 'promo'; rec.note ||= 'left the booking'; world.wasted++; return }
+ if (world.page === 'search') {
+ if (id === 'from') { useful(!world.form.from); world.form.from = t.from; rec.typed = t.from }
+ else if (id === 'to') { useful(!world.form.to); world.form.to = t.to; rec.typed = t.to }
+ else if (id === 'day') { useful(!world.form.day); world.form.day = t.day; rec.typed = t.day }
+ else if (id === 'promo') { world.form.promo = 'SAVE10'; rec.typed = 'SAVE10'; world.wasted++ }
+ else if (id === 'search-flights') world.page = 'results'
+ } else if (world.page === 'results') {
+ if (id === 'nonstop-only') world.nonstopOnly = !world.nonstopOnly
+ else if (id === 'sort-price') world.sort = 'price'
+ else if (id === 'sort-early') world.sort = 'dep'
+ else if (id === 'sort-late') world.sort = 'late'
+ else if (id.startsWith('select-')) { const fid = id.slice(7); world.chosen = fid === 'ad' ? world.sponsoredRow : world.flights.find((f) => f.id === fid) ?? null; if (world.chosen) world.page = 'details' }
+ } else if (world.page === 'details') {
+ if (id === 'name') { useful(!world.details.name); world.details.name = t.name; rec.typed = t.name }
+ else if (id === 'email') { useful(!world.details.email); world.details.email = t.email; rec.typed = t.email }
+ else if (id === 'bag-add') world.details.bags = Math.min(3, world.details.bags + 1)
+ else if (id === 'bag-remove') world.details.bags = Math.max(0, world.details.bags - 1)
+ else if (id === 'insurance') world.details.insurance = !world.details.insurance
+ else if (id === 'newsletter') world.details.newsletter = !world.details.newsletter
+ else if (id === 'continue') world.page = 'review'
+ else if (id === 'change-flight') { world.page = 'results'; world.chosen = null }
+ } else if (world.page === 'review') {
+ if (id === 'flex') world.flex = !world.flex
+ else if (id === 'back') world.page = 'details'
+ else if (id === 'confirm') {
+ const f = world.chosen, b = world.best
+ const problems = []
+ if (!f || !b || f.id !== b.id) problems.push(f?.sponsored ? `booked a sponsored flight to ${f.to}, not ${t.to}` : `booked ${f ? '$' + f.price + ' departing ' + hhmm(f.dep) : 'nothing'}, the ${t.pick}${t.nonstop ? ' nonstop' : ''} was $${b?.price} departing ${b ? hhmm(b.dep) : '?'}`)
+ if (world.details.bags !== t.bags) problems.push(`${world.details.bags} bags instead of ${t.bags}`)
+ if (world.details.insurance) problems.push('bought insurance')
+ if (world.flex) problems.push('bought the Flex upgrade')
+ world.result = { ok: problems.length === 0, why: problems.length ? problems.join('; ') : `${t.pick}${t.nonstop ? ' nonstop' : ''} flight, right passenger, ${t.bags} bag(s), no extras` }
+ world.page = 'done'; world.status = 'done'; world.finishedAt = world.steps
+ }
+ }
+}
+
+function finishIfOver(world, cfg, rec) {
+ if (world.status === 'running' && world.steps >= cfg.maxSteps) {
+ world.status = 'done'; world.finishedAt = world.steps
+ world.result = { ok: false, why: `gave up after ${cfg.maxSteps} steps on the ${world.page} page` }
+ }
+ return rec
+}
diff --git a/store/agents/jev-browser/viewer/studio.css b/store/agents/jev-browser/viewer/studio.css
new file mode 100644
index 000000000..657125459
--- /dev/null
+++ b/store/agents/jev-browser/viewer/studio.css
@@ -0,0 +1,87 @@
+/* Jev Browser — blue accent over the shared base. */
+:root { --accent: #60a5fa; --accent2: #1d4ed8; }
+.stat.big span { color: var(--accent); }
+#s-ok { color: var(--ok); } #s-mis { color: var(--bad); }
+#stage { gap: 10px; }
+
+.task { padding: 10px 14px; flex: none; }
+.task-row { display: flex; gap: 10px; align-items: baseline; }
+.goal { font: 600 14px/1.45 var(--sans); color: var(--ink); }
+.goal b { color: var(--accent); font-weight: 700; }
+.task-meters { display: flex; gap: 18px; margin-top: 6px; color: var(--dim); font-size: 12px; align-items: baseline; }
+.task-meters b { color: var(--ink); font-size: 17px; font-variant-numeric: tabular-nums; }
+.task-meters .note { color: var(--bad); font-weight: 600; min-height: 1em; }
+
+.window { flex: 1 1 auto; min-height: 260px; display: flex; flex-direction: column; border: 1px solid var(--line2); border-radius: 12px; overflow: hidden; background: #0d1017; box-shadow: 0 18px 60px rgba(0,0,0,.5); }
+.chrome { display: flex; align-items: center; gap: 12px; padding: 8px 12px; background: linear-gradient(180deg, #1b2030, #141826); border-bottom: 1px solid var(--line2); flex: none; }
+.lights { display: flex; gap: 6px; } .lights i { width: 11px; height: 11px; border-radius: 50%; background: #ef4444; display: block; } .lights i:nth-child(2) { background: #f59e0b; } .lights i:nth-child(3) { background: #22c55e; }
+.tab { display: flex; align-items: center; gap: 7px; padding: 5px 12px; border-radius: 8px 8px 0 0; background: #0d1017; color: var(--ink); font: 600 12px var(--sans); white-space: nowrap; }
+.fav { width: 12px; height: 12px; border-radius: 3px; background: linear-gradient(135deg, #38bdf8, #6366f1); display: inline-block; }
+.url { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; padding: 5px 12px; border-radius: 999px; background: #0a0c12; border: 1px solid var(--line2); color: var(--dim); font-size: 12px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
+.lock { color: var(--ok); font-size: 8px; }
+
+.viewport { position: relative; flex: 1; min-height: 0; overflow: hidden; background: #f4f6fb; }
+.page { position: absolute; left: 0; top: 0; width: 1000px; height: 620px; transform-origin: 0 0; font-family: var(--sans); color: #0f172a; background: linear-gradient(180deg, #e8eefc 0, #f4f6fb 180px); }
+.page::before { content: ''; position: absolute; left: 0; top: 0; width: 1000px; height: 58px; background: #fff; border-bottom: 1px solid #dbe2f0; }
+
+.el { position: absolute; box-sizing: border-box; display: flex; align-items: center; transition: top .13s ease, left .13s ease, opacity .12s, background .12s, box-shadow .12s; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.el.act { cursor: pointer; }
+.el.text { font-size: 15px; color: #334155; }
+.el.t-logo { font: 800 22px var(--sans); color: #1d4ed8; letter-spacing: -.5px; }
+.el.t-h1 { font: 800 28px var(--sans); color: #0f172a; letter-spacing: -.5px; }
+.el.t-ok { font: 800 30px var(--sans); color: #047857; } .el.t-bad { font: 800 30px var(--sans); color: #b91c1c; }
+.el.t-row { background: #fff; border: 1px solid #dbe2f0; border-radius: 10px; padding: 0 14px; font: 500 14.5px var(--sans); color: #1e293b; }
+.el.t-sponsored { background: #fffbeb; border: 1px solid #fcd34d; border-radius: 10px; padding: 0 14px; font: 600 14.5px var(--sans); color: #92400e; }
+.el.t-label { font: 600 16px var(--sans); color: #0f172a; }
+.el.card { background: #fff; border: 1px solid #dbe2f0; border-radius: 16px; box-shadow: 0 10px 30px rgba(15,23,42,.08); }
+.el.card.t-overlay { background: #0f172a; border: none; border-radius: 16px; box-shadow: 0 30px 80px rgba(2,6,23,.55); z-index: 5; }
+.el.t-overlaytext { color: #e2e8f0; font: 600 17px/1.4 var(--sans); white-space: normal; z-index: 6; }
+.el.input { background: #fff; border: 1.5px solid #cbd5e1; border-radius: 10px; padding: 16px 14px 0; font: 600 16px var(--sans); color: #0f172a; align-items: center; }
+.el.input::before { content: attr(data-label); position: absolute; left: 14px; top: 6px; font: 600 10.5px var(--sans); letter-spacing: .4px; text-transform: uppercase; color: #64748b; }
+.el.input.filled { border-color: #22c55e; background: #f0fdf4; }
+.el.button, .el.toggle, .el.link { justify-content: center; border-radius: 10px; font: 700 14.5px var(--sans); border: 1.5px solid #cbd5e1; background: #fff; color: #0f172a; padding: 0 10px; }
+.el.link { border: none; background: none; color: #475569; font-weight: 600; }
+.el.t-primary { background: linear-gradient(135deg, #2563eb, #1d4ed8); border-color: transparent; color: #fff; box-shadow: 0 6px 16px rgba(37,99,235,.35); }
+.el.t-decoy.button, .el.t-decoy.toggle { background: linear-gradient(135deg, #f59e0b, #d97706); border-color: transparent; color: #fff; }
+.el.t-decoy.input { border-style: dashed; }
+.el.t-on { background: #dbeafe; border-color: #2563eb; color: #1d4ed8; }
+.el.toggle.is-on { background: #dcfce7; border-color: #16a34a; color: #166534; }
+.el.toggle.is-on.t-decoy { background: #b91c1c; color: #fff; }
+.el.disabled { opacity: .45; filter: grayscale(.4); }
+.el.blocked { filter: blur(1.2px) brightness(.72); pointer-events: none; }
+.el.overlay-el { z-index: 7; }
+.el.shake { animation: shake .28s; }
+@keyframes shake { 20% { transform: translateX(-5px); } 40% { transform: translateX(5px); } 60% { transform: translateX(-3px); } 80% { transform: translateX(3px); } }
+.el.pop { animation: pop .22s ease-out; }
+@keyframes pop { 0% { transform: scale(.9); opacity: 0; } 100% { transform: none; opacity: 1; } }
+
+/* Jev's mind, drawn on the page: a ring whose strength is the probability of acting on that element. */
+.ring { position: absolute; border-radius: 12px; pointer-events: none; z-index: 8; border: 2.5px solid rgba(167,139,250,.9); box-shadow: 0 0 0 4px rgba(167,139,250,.18), 0 0 22px rgba(167,139,250,.55); transition: opacity .1s; }
+.ring.top { border-color: #22c55e; box-shadow: 0 0 0 4px rgba(34,197,94,.2), 0 0 26px rgba(34,197,94,.7); }
+.ring b { position: absolute; right: 10px; top: -11px; font: 700 11px var(--mono); padding: 1px 6px; border-radius: 6px; background: #4c1d95; color: #fff; }
+.ring.top b { background: #15803d; }
+
+.cursor { position: absolute; left: 0; top: 0; z-index: 20; pointer-events: none; filter: drop-shadow(0 3px 5px rgba(0,0,0,.45)); will-change: transform; }
+.ripple { position: absolute; width: 16px; height: 16px; margin: -8px 0 0 -8px; border-radius: 50%; border: 3px solid #2563eb; pointer-events: none; z-index: 19; animation: ripple .45s ease-out forwards; }
+.ripple.miss { border-color: #dc2626; }
+@keyframes ripple { 0% { transform: scale(.4); opacity: 1; } 100% { transform: scale(5); opacity: 0; } }
+.shiftnote { position: absolute; z-index: 21; font: 800 13px var(--sans); color: #fff; background: #dc2626; padding: 3px 9px; border-radius: 8px; pointer-events: none; animation: rise .9s ease-out forwards; white-space: nowrap; }
+@keyframes rise { 0% { transform: translateY(6px); opacity: 0; } 15% { opacity: 1; } 100% { transform: translateY(-26px); opacity: 0; } }
+
+.stamp { position: absolute; inset: 0; z-index: 30; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; text-align: center; backdrop-filter: blur(3px); animation: pop .25s ease-out; padding: 0 24px; }
+.stamp.ok { background: rgba(4,120,87,.80); } .stamp.bad { background: rgba(153,27,27,.82); }
+.stamp h2 { margin: 0; font: 800 clamp(26px, 5vw, 54px) var(--sans); color: #fff; letter-spacing: -1px; }
+.stamp p { margin: 0; font: 600 clamp(13px, 1.6vw, 18px) var(--sans); color: rgba(255,255,255,.92); max-width: 80%; }
+.stamp .nums { font: 700 clamp(14px, 2vw, 22px) var(--mono); color: #fff; }
+
+.toolbar { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; padding: 9px 12px; flex: none; }
+.toolbar .slider { display: flex; align-items: center; gap: 8px; color: var(--dim); font-size: 12px; white-space: nowrap; }
+.toolbar .slider input { width: 120px; } .toolbar .slider b { color: var(--warn); min-width: 30px; font-variant-numeric: tabular-nums; }
+.toolbar .hint { color: var(--dim); font-size: 11.5px; flex: 1 1 220px; } .toolbar .hint b { color: var(--ink); }
+
+.statetext { margin: 0; font: 10.5px/1.5 var(--mono); color: #cbd5e1; white-space: pre-wrap; word-break: break-word; max-height: 250px; overflow: auto; }
+.statetext .k { color: var(--accent); font-weight: 700; } .statetext .pick { color: #0b0d14; background: var(--ok); border-radius: 3px; } .statetext .warn { color: var(--bad); }
+#feed { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 5px; max-height: 210px; overflow-y: auto; font-size: 11.5px; color: var(--dim); }
+#feed li { display: grid; grid-template-columns: 16px 1fr; gap: 6px; line-height: 1.4; }
+#feed li.ok i { color: var(--ok); } #feed li.bad i { color: var(--bad); } #feed li i { font-style: normal; font-weight: 800; } #feed li b { color: var(--ink); font-weight: 600; }
+.task-row .pill { white-space: nowrap; flex: none; }
diff --git a/store/agents/jev-browser/viewer/studio.js b/store/agents/jev-browser/viewer/studio.js
new file mode 100644
index 000000000..ec2bef680
--- /dev/null
+++ b/store/agents/jev-browser/viewer/studio.js
@@ -0,0 +1,175 @@
+// Jev Browser pane. The server sends one frame per step: the action Jev just chose (with the full
+// probability over the elements it could have chosen) and the page as it is now. This file plays
+// that as: rings on the old page showing Jev's mind -> the cursor flies to the chosen spot -> a click
+// ripple (red when a layout shift made it land somewhere else) -> the new page.
+'use strict'
+
+const $ = (id) => document.getElementById(id)
+const page = $('page'), viewport = $('viewport'), cursor = $('cursor'), stamp = $('stamp')
+const PAGE_W = 1000, PAGE_H = 620
+let scale = 1, showMind = true, paused = false
+let cur = { x: 500, y: 320 }, anim = null, pending = null
+let lastTaskKey = '', costAtTaskStart = 0, costNow = 0, lastFeedLen = -1
+const nodes = new Map() // element id -> DOM node
+
+function fit() {
+ const r = viewport.getBoundingClientRect()
+ scale = Math.min(r.width / PAGE_W, r.height / PAGE_H)
+ page.style.transform = `scale(${scale})`
+ page.style.left = Math.max(0, (r.width - PAGE_W * scale) / 2) + 'px'
+ placeCursor()
+}
+new ResizeObserver(fit).observe(viewport)
+const placeCursor = () => { const off = parseFloat(page.style.left) || 0; cursor.style.transform = `translate(${off + cur.x * scale - 3}px, ${cur.y * scale - 2}px)` }
+
+// ---------------------------------------------------------------- the page
+function renderPage(f) {
+ const seen = new Set()
+ for (const e of f.els) {
+ seen.add(e.id)
+ let n = nodes.get(e.id)
+ if (!n) {
+ n = document.createElement('div'); n.dataset.id = e.id; nodes.set(e.id, n); page.appendChild(n)
+ n.classList.add('pop')
+ n.addEventListener('click', () => { if (n.classList.contains('act')) post({ cmd: 'click', id: e.id }) })
+ }
+ const isOn = e.value === 'on'
+ n.className = ['el', e.role, e.act ? 'act' : '', e.tone ? 't-' + e.tone : '', e.disabled ? 'disabled' : '', e.blocked ? 'blocked' : '', e.overlay ? 'overlay-el' : '', isOn ? 'is-on' : '', e.role === 'input' && e.value ? 'filled' : '', f.shake === e.id ? 'shake' : '', n.classList.contains('pop') ? 'pop' : ''].filter(Boolean).join(' ')
+ const [x, y, w, h] = e.rect
+ n.style.left = x + 'px'; n.style.top = y + 'px'; n.style.width = w + 'px'; n.style.height = h + 'px'
+ if (e.role === 'input') { n.dataset.label = e.label; if (n.dataset.typing !== '1') n.textContent = e.value || '' }
+ else if (e.role === 'toggle') n.textContent = (isOn ? '☑ ' : '☐ ') + e.label
+ else n.textContent = e.label
+ n.title = e.act ? `${e.id} — click it yourself` : ''
+ }
+ for (const [id, n] of nodes) if (!seen.has(id)) { n.remove(); nodes.delete(id) }
+ setTimeout(() => { for (const n of nodes.values()) n.classList.remove('pop') }, 240)
+}
+
+function clearRings() { for (const r of page.querySelectorAll('.ring')) r.remove() }
+function drawRings(f) {
+ clearRings()
+ if (!showMind || !f.last?.probs) return
+ const top = Object.entries(f.last.probs).sort((a, b) => b[1] - a[1]).slice(0, 4)
+ top.forEach(([id, p], i) => {
+ const n = nodes.get(id); if (!n || p < 0.03) return
+ const r = document.createElement('div'); r.className = 'ring' + (i === 0 ? ' top' : '')
+ r.style.left = parseFloat(n.style.left) - 4 + 'px'; r.style.top = parseFloat(n.style.top) - 4 + 'px'
+ r.style.width = parseFloat(n.style.width) + 8 + 'px'; r.style.height = parseFloat(n.style.height) + 8 + 'px'
+ r.style.opacity = String(0.35 + 0.65 * Math.min(1, p * 1.4))
+ const b = document.createElement('b'); b.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, ''); r.appendChild(b)
+ page.appendChild(r)
+ })
+}
+
+function ripple(x, y, miss, note) {
+ const r = document.createElement('div'); r.className = 'ripple' + (miss ? ' miss' : ''); r.style.left = x + 'px'; r.style.top = y + 'px'
+ page.appendChild(r); setTimeout(() => r.remove(), 480)
+ if (note) { const s = document.createElement('div'); s.className = 'shiftnote'; s.textContent = note; s.style.left = Math.min(PAGE_W - 220, x + 14) + 'px'; s.style.top = Math.max(8, y - 30) + 'px'; page.appendChild(s); setTimeout(() => s.remove(), 920) }
+}
+
+function typeInto(id, text, ms) {
+ const n = nodes.get(id); if (!n || !text) return
+ n.dataset.typing = '1'; n.textContent = ''
+ const t0 = performance.now()
+ const tick = () => { const k = Math.min(text.length, Math.ceil(((performance.now() - t0) / ms) * text.length)); n.textContent = text.slice(0, k); if (k < text.length) requestAnimationFrame(tick); else n.dataset.typing = '0' }
+ tick()
+}
+
+// ---------------------------------------------------------------- one frame = one played step
+function play(f) {
+ const a = f.lastAction
+ const isNewStep = a && (!play.lastStep || a.step !== play.lastStep || f.task.goal !== play.lastGoal)
+ play.lastStep = a?.step; play.lastGoal = f.task.goal
+ if (!isNewStep) { if (!anim) { clearRings(); renderPage(f) } return }
+ // 1. rings on the page Jev read, 2. fly, 3. click, 4. show the page as it is now
+ drawRings(f)
+ const dwell = paused ? 900 : 0 // stepping by hand: time to read Jev's mind on the page it read
+ const from = { ...cur }, to = { x: a.x, y: a.y }, dur = Math.max(50, Math.min(150, f.stepMs * 0.55)), t0 = performance.now() + dwell
+ if (anim) cancelAnimationFrame(anim)
+ const stepAnim = (now) => {
+ if (now < t0) { anim = requestAnimationFrame(stepAnim); return }
+ const k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3)
+ cur = { x: from.x + (to.x - from.x) * e, y: from.y + (to.y - from.y) * e - Math.sin(k * Math.PI) * Math.min(40, Math.hypot(to.x - from.x, to.y - from.y) * 0.12) }
+ placeCursor()
+ if (k < 1) { anim = requestAnimationFrame(stepAnim); return }
+ anim = null
+ const miss = !!a.shift && a.landed !== a.id
+ ripple(a.x, a.y, miss || /disabled|blocked|no such/.test(a.note || ''), a.shift ? (miss ? `layout shifted: ${a.shift}` : a.shift) : '')
+ clearRings()
+ renderPage(f)
+ if (a.typed) typeInto(a.landed, a.typed, Math.max(40, f.stepMs * 0.35))
+ }
+ anim = requestAnimationFrame(stepAnim)
+}
+
+// ---------------------------------------------------------------- everything around the page
+const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]))
+
+function paintGoal(f) {
+ const g = esc(f.task.goal).replace(/\b(cheapest|earliest|latest|nonstop)\b/g, '<b>$1</b>').replace(/from (\S+) to (\S+) on (\S+)/, 'from <b>$1</b> to <b>$2</b> on <b>$3</b>')
+ $('goal').innerHTML = g
+ $('taskNo').textContent = `TASK ${f.task.index + 1}/${f.task.count}`
+}
+function paintStateText(f) {
+ const pick = f.last?.choice
+ $('stateText').innerHTML = (f.stateText || '').split('\n').slice(1).map((l) => {
+ const e = esc(l)
+ if (/^(TASK|PAGE|OVERLAY|PAGE TEXT|ELEMENTS|RECENT)/.test(l)) return e.replace(/^([A-Z ]+)/, '<span class="k">$1</span>').replace(/(a (cookie banner|pop-up) covers.*)/, '<span class="warn">$1</span>')
+ if (pick && l.startsWith(` ${pick} `)) return `<span class="pick">${e}</span>`
+ return e
+ }).join('\n')
+}
+function paintFeed(f) {
+ const rs = f.session.results
+ if (f.session.tasks === lastFeedLen) return
+ lastFeedLen = f.session.tasks
+ $('feed').innerHTML = rs.slice().reverse().map((r) => `<li class="${r.ok ? 'ok' : 'bad'}"><i>${r.ok ? '✓' : '✗'}</i><span><b>${(r.wallMs / 1000).toFixed(1)} s · ${r.steps} steps</b> · ${esc(r.ok ? r.goal.replace(/^Book the /, '').replace(/ for .*/, '') : r.why)}</span></li>`).join('') || '<li><i></i><span>The first booking is under way.</span></li>'
+}
+
+function onFrame(f) {
+ paused = !f.running
+ const key = `${f.task.round}:${f.task.index}:${f.task.goal}`
+ if (key !== lastTaskKey) { lastTaskKey = key; costAtTaskStart = costNow; stamp.classList.add('hidden'); play.lastStep = null }
+ play(f)
+ paintGoal(f); paintStateText(f); paintFeed(f)
+ $('title').textContent = f.title
+ $('tabTitle').textContent = `${f.site} · ${f.page}`
+ $('url').textContent = f.url
+ $('m-time').textContent = (f.wallMs / 1000).toFixed(1); $('m-steps').textContent = f.steps; $('m-cost').textContent = fmtMoney(Math.max(0, costNow - costAtTaskStart))
+ $('m-note').textContent = f.lastAction?.note && !/you clicked$/.test(f.lastAction.note) ? f.lastAction.note : ''
+ const s = f.session
+ $('s-tasks').textContent = s.tasks; $('s-ok').textContent = s.tasks ? Math.round((s.ok / s.tasks) * 100) + '%' : '—'
+ $('s-steps').textContent = s.tasks ? (s.steps / s.tasks).toFixed(1) : '—'; $('s-secs').textContent = s.tasks ? (s.wallMs / s.tasks / 1000).toFixed(1) : '—'
+ $('s-mis').textContent = s.misclicks + f.misclicks
+ $('pause').textContent = f.running ? 'Pause' : 'Resume'
+ if (document.activeElement !== $('distraction')) { $('distraction').value = f.distraction; $('distractionVal').textContent = Number(f.distraction).toFixed(2) }
+ if (document.activeElement !== $('stepMs')) { $('stepMs').value = f.stepMs; $('stepMsVal').textContent = f.stepMs }
+ const problem = f.cfgError || f.error
+ $('cfgError').classList.toggle('hidden', !problem); $('cfgError').textContent = problem ? `site.json: ${problem} — still running on the last good settings.` : ''
+ if (f.status === 'done' && f.result) {
+ stamp.className = 'stamp ' + (f.result.ok ? 'ok' : 'bad')
+ stamp.innerHTML = `<h2>${f.result.ok ? 'Booked. Exactly right.' : 'Wrong booking'}</h2><div class="nums">${(f.wallMs / 1000).toFixed(1)} s · ${f.steps} steps · ${fmtMoney(Math.max(0, costNow - costAtTaskStart))}</div><p>${esc(f.result.why)}</p>`
+ } else stamp.classList.add('hidden')
+}
+
+const post = (body) => fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }).catch(() => {})
+$('pause').onclick = () => post({ cmd: paused ? 'start' : 'pause' })
+$('step').onclick = () => post({ cmd: 'tick' })
+$('reset').onclick = () => post({ cmd: 'reset' })
+$('popup').onclick = () => post({ cmd: 'popup' })
+$('nextTask').onclick = () => { const m = /(\d+)\/(\d+)/.exec($('taskNo').textContent); post({ cmd: 'task', index: m ? Number(m[1]) % Number(m[2]) : 0 }) }
+$('heat').onclick = () => { showMind = !showMind; $('heat').classList.toggle('on', showMind); if (!showMind) clearRings() }
+$('distraction').oninput = (e) => { $('distractionVal').textContent = Number(e.target.value).toFixed(2); post({ cmd: 'set', key: 'distraction', value: Number(e.target.value) }) }
+$('stepMs').oninput = (e) => { $('stepMsVal').textContent = e.target.value; post({ cmd: 'set', key: 'stepMs', value: Number(e.target.value) }) }
+
+async function pollJev() {
+ try { const s = await (await fetch('/jev', { cache: 'no-store' })).json(); costNow = s.costUsd; $('s-rate').textContent = s.callsPerSec.toFixed(1); $('s-cost').textContent = fmtMoney(s.costUsd) } catch { /* restarting */ }
+ setTimeout(pollJev, 400)
+}
+
+fit()
+const es = new EventSource('/events')
+es.addEventListener('state', (e) => onFrame(JSON.parse(e.data)))
+pollJev()
diff --git a/store/agents/jev-browser/viewer/viewer.mjs b/store/agents/jev-browser/viewer/viewer.mjs
new file mode 100644
index 000000000..7de4687d5
--- /dev/null
+++ b/store/agents/jev-browser/viewer/viewer.mjs
@@ -0,0 +1,199 @@
+// Jev Browser viewer — a loopback server where Jev operates a web browser, live.
+// The site is a small made-up travel shop. At every step the page is written out as text (the task,
+// the page, every element that can be acted on) and Jev (TypeSafe's System One model) picks ONE
+// element out of the list, a new action space every step, plus two yes/no reads, all in one call.
+// A booking takes a few seconds. The honest dial is `distraction`: cookie walls, pop-ups, decoys and
+// layout shifts that land between reading the page and clicking it.
+//
+// The chat agent edits site.json (the tasks, the distraction, the pace). The pane lets a person
+// click the page themselves, throw a pop-up at Jev, and move the dials.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds site.json (watched live).
+
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, jev } from '../toolchain/jev.mjs'
+import { serveViewer, watchConfig, writeVerdict, clean } from './kit.mjs'
+import { DEFAULT, createWorld, observe, act, elements, pageUrl, cleanTask } from './sim.mjs'
+import { browserMock } from './mock.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clampN = (v, lo, hi, d) => { const n = Number(v); return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : d }
+
+/** Keep a wild config from breaking the demo. check.mjs reports the same ranges to the agent. */
+export function sanitize(raw) {
+ return {
+ ...DEFAULT, ...raw,
+ title: String(raw.title ?? DEFAULT.title).slice(0, 80),
+ description: String(raw.description ?? DEFAULT.description).slice(0, 300),
+ site: String(raw.site ?? DEFAULT.site).replace(/[^\w .-]/g, '').slice(0, 24) || DEFAULT.site,
+ style: String(raw.style ?? DEFAULT.style).slice(0, 600),
+ stepMs: clampN(raw.stepMs, 40, 2000, DEFAULT.stepMs),
+ distraction: clampN(raw.distraction, 0, 1, DEFAULT.distraction),
+ flights: Math.round(clampN(raw.flights, 4, 9, DEFAULT.flights)),
+ maxSteps: Math.round(clampN(raw.maxSteps, 12, 200, DEFAULT.maxSteps)),
+ seed: Math.round(clampN(raw.seed, 0, 1e9, DEFAULT.seed)),
+ tasks: (Array.isArray(raw.tasks) && raw.tasks.length ? raw.tasks : DEFAULT.tasks).slice(0, 40).map(cleanTask),
+ }
+}
+
+export async function startBrowserViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+
+ // Every binding is declared before anything can call into the closures below.
+ let world = null
+ let stopped = false, running = false, busy = false
+ let timer = null, salt = 1, taskIndex = 0, round = 0, lastVerdictAt = 0, taskWallStart = 0, doneAt = 0
+ let overrides = {}
+ let last = { probs: {}, choice: null, confidence: 0, pDone: 0, pObstacle: 0 }
+ let stateText = ''
+ let error = null
+ let server = null
+ const session = { tasks: 0, ok: 0, steps: 0, wasted: 0, misclicks: 0, wallMs: 0, results: [] }
+
+ const cfgWatch = watchConfig(join(workspace, 'site.json'), DEFAULT, () => { overrides = {}; taskIndex = 0; round = 0; newTask(); push(true) })
+ const cfg = () => sanitize({ ...cfgWatch.get(), ...overrides })
+
+ function newTask() {
+ world = createWorld(cfg(), taskIndex, round)
+ taskWallStart = 0; doneAt = 0
+ stateText = observe(world, cfg()).text
+ last = { probs: {}, choice: null, confidence: 0, pDone: 0, pObstacle: 0 }
+ }
+
+ function frame() {
+ const c = cfg()
+ return {
+ t: world.steps, stepMs: c.stepMs, title: c.title, site: c.site, description: c.description,
+ task: { goal: world.goal, index: world.taskIndex % world.taskCount, count: world.taskCount, round },
+ page: world.page, url: pageUrl(world, c), els: elements(world, c), overlay: world.overlay?.kind ?? null, shake: world.shake,
+ lastAction: world.lastAction, last,
+ status: world.status, result: world.result, steps: world.steps, wasted: world.wasted, misclicks: world.misclicks,
+ wallMs: taskWallStart ? (doneAt || Date.now()) - taskWallStart : 0,
+ session: { ...session, results: session.results.slice(-12) },
+ distraction: c.distraction, maxSteps: c.maxSteps, stateText,
+ running, error, cfgError: cfgWatch.error(), overrides,
+ }
+ }
+
+ function verdict() {
+ const c = cfg()
+ const problem = cfgWatch.error() || error
+ const rate = session.tasks ? Math.round((session.ok / session.tasks) * 100) : 0
+ const avgSteps = session.tasks ? (session.steps / session.tasks).toFixed(1) : '—'
+ writeVerdict(workspace, {
+ ready: session.tasks > 0 || world.steps > 0,
+ summary: problem
+ ? `Jev Browser needs a fix: ${problem}`
+ : `${c.title} · ${session.tasks} bookings · ${rate}% exactly right · ${avgSteps} steps each · ${session.misclicks} clicks lost to layout shifts`,
+ findings: [
+ ...(problem ? [{ severity: 'error', kind: 'site', message: problem }] : []),
+ ...session.results.filter((r) => !r.ok).slice(-5).map((r) => ({ severity: 'warning', kind: 'booking', message: `${r.goal} → ${r.why}` })),
+ { severity: 'info', kind: 'run', message: `distraction ${c.distraction.toFixed(2)}, ${c.stepMs} ms per step, ${session.wasted} wasted steps in ${session.steps}` },
+ ],
+ artifact: 'site.json',
+ phases: [
+ { id: 'site', name: 'Site up', state: 'done' },
+ { id: 'book', name: 'Booking', state: world.steps > 0 || session.tasks > 0 ? 'active' : 'pending' },
+ { id: 'score', name: 'Bookings checked', state: session.tasks > 0 ? 'done' : 'pending' },
+ ],
+ })
+ }
+
+ function push(force = false) {
+ const now = Date.now()
+ if (force || now - lastVerdictAt > 1000) { lastVerdictAt = now; try { verdict() } catch (e) { error = clean(e.message) } }
+ server?.broadcast(frame())
+ }
+
+ function settle() {
+ if (world.status !== 'done' || doneAt) return
+ doneAt = Date.now()
+ session.tasks++; if (world.result?.ok) session.ok++
+ session.steps += world.steps; session.wasted += world.wasted; session.misclicks += world.misclicks
+ session.wallMs += taskWallStart ? doneAt - taskWallStart : 0
+ session.results.push({ goal: world.goal, ok: !!world.result?.ok, why: world.result?.why ?? '', steps: world.steps, wallMs: taskWallStart ? doneAt - taskWallStart : 0 })
+ if (session.results.length > 60) session.results.shift()
+ }
+
+ async function decide(humanId = null) {
+ if (busy || stopped) return
+ busy = true
+ try {
+ const c = cfg()
+ if (world.status === 'done') {
+ // Show the result for about 2.6 seconds of steps, then take the next task.
+ world.rest = (world.rest ?? 0) + 1
+ if (world.rest * c.stepMs >= 2600) { taskIndex++; if (taskIndex % world.taskCount === 0) round++; newTask() }
+ return
+ }
+ if (!taskWallStart) taskWallStart = Date.now()
+ const o = observe(world, c)
+ stateText = o.text
+ let choice = humanId
+ if (!humanId) {
+ const res = await evaluate({
+ state: o.text,
+ questions: {
+ action: jev.choice(o.options, 'Which ONE element do you act on next to finish the task?'),
+ done: jev.noul('Is the task already complete?'),
+ obstacle: jev.noul('Is something covering the page that must be closed first?'),
+ },
+ salt: salt++, model: process.env.JEV_MODEL || 'jev-latest', mock: browserMock,
+ })
+ const a = res.answers.action ?? {}
+ choice = a.choice && o.options[a.choice] !== undefined ? a.choice : Object.keys(o.options)[0]
+ last = { probs: a.probabilities ?? {}, choice, confidence: Number(a.confidence ?? 0), pDone: Number(res.answers.done?.noul ?? 0), pObstacle: Number(res.answers.obstacle?.noul ?? 0) }
+ } else last = { ...last, choice: humanId, human: true }
+ const rec = act(world, c, choice)
+ if (rec && humanId) rec.note = rec.note ? `you clicked · ${rec.note}` : 'you clicked'
+ stateText = observe(world, c).text
+ settle()
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? String(e))
+ } finally {
+ busy = false
+ }
+ }
+
+ function schedule() { clearTimeout(timer); if (running && !stopped) timer = setTimeout(run, cfg().stepMs) }
+ async function run() { const t0 = Date.now(); await decide(); push(); if (running && !stopped) timer = setTimeout(run, Math.max(0, cfg().stepMs - (Date.now() - t0))) }
+
+ async function control(cmd, body) {
+ if (cmd === 'pause') { running = false; clearTimeout(timer) }
+ else if (cmd === 'start') { if (!running) { running = true; schedule() } }
+ else if (cmd === 'reset') { Object.assign(session, { tasks: 0, ok: 0, steps: 0, wasted: 0, misclicks: 0, wallMs: 0, results: [] }); overrides = {}; taskIndex = 0; round = 0; salt = 1; newTask() }
+ else if (cmd === 'tick') { const n = Math.round(clampN(body.n, 1, 20000, 1)); for (let i = 0; i < n; i++) await decide() }
+ else if (cmd === 'click') { if (typeof body.id === 'string' && body.id.length < 40) await decide(body.id) }
+ else if (cmd === 'popup') { if (!world.overlay && world.status === 'running') world.overlay = { kind: 'popup', at: [260, 150] }; stateText = observe(world, cfg()).text }
+ else if (cmd === 'task') { taskIndex = Math.round(clampN(body.index, 0, 1000, 0)); newTask() }
+ else if (cmd === 'set') {
+ const allowed = { distraction: [0, 1], stepMs: [40, 2000] }
+ if (allowed[body.key]) overrides = { ...overrides, [body.key]: clampN(body.value, allowed[body.key][0], allowed[body.key][1], cfg()[body.key]) }
+ }
+ push(true)
+ return { steps: world.steps }
+ }
+
+ newTask()
+ server = await serveViewer({ here: HERE, port, state: frame, control })
+ push(true)
+ running = true
+ schedule()
+
+ return {
+ url: server.url,
+ async close() { stopped = true; running = false; clearTimeout(timer); cfgWatch.close(); await server.close() },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startBrowserViewer({ workspace, port })
+ console.log(`Jev Browser listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-catcher/.gitignore b/store/agents/jev-catcher/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-catcher/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-catcher/AGENTS.md b/store/agents/jev-catcher/AGENTS.md
new file mode 100644
index 000000000..c7ef56fe0
--- /dev/null
+++ b/store/agents/jev-catcher/AGENTS.md
@@ -0,0 +1,84 @@
+# Jev Catcher in OpenHarness
+
+On the left, Jev Catcher is an outfield: a ball pops up overhead and falls to a spot on the line,
+and **Jev — TypeSafe's System One model — is the fielder.** Every tick Jev reads the glove's
+position and the next ball's landing spot, and slides the glove left or right to be under it when it
+lands. Get there in time and it is an out; miss and it drops. The field is synthetic; the decision
+loop is the show.
+
+On the right, you edit `catcher.json`. This is the ONLY file you edit. It holds the session profile
+— how fast the balls fall, how precise the catch has to be, how long the session — and the viewer
+watches it and Jev adapts immediately.
+
+## The catcher file
+
+```jsonc
+{
+ "title": "Jev Catcher",
+ "description": "Jev is the fielder — slide the glove and catch every pop fly.",
+ "instrument": "CATCHER",
+ "tickMs": 140,
+ "fallTicks": 10,
+ "gloveReach": 1.6,
+ "fieldWidth": 24,
+ "balls": 14,
+ "style": "You are the fielder. A ball pops up and falls to a spot on the line — slide the glove to be right under it when it lands. Get there in time and it is an out; miss and it drops. Be decisive, read the landing spot early."
+}
+```
+
+- **`fallTicks`** — how many ticks a ball takes to come down. This is the difficulty dial. Calm
+ (`12–14`) gives Jev time to cross the field and it catches everything; `7` and below the ball
+ drops faster than Jev can get there, and the drops pile up.
+- **`gloveReach`** — how close the glove must be to the landing spot to make the catch. Tight
+ (`0.5`) demands an exact read; wide (`2.5+`) is forgiving.
+- **`fieldWidth`** — the width of the field in slots (6–60). Wider = more ground to cover.
+- **`balls`** — how many pop flies in the session (1–100). More = longer, more chances to drop.
+- **`tickMs`** — how often the world updates (and Jev decides). Fast ticks = frantic fielding; slow
+ ticks = a relaxed session.
+- **`style`** — the instruction to Jev. It should name a fielding strategy (read the spot early,
+ glide, commit at the catch) so Jev *decides* rather than guesses.
+
+## Your job
+
+Design `catcher.json` so the session is an event:
+
+- **Curate the fall with tension.** Default `fallTicks` around `10` gives clean, readable catches.
+ Crank it to `7` and Jev starts to leak; that flip is the fun.
+- **Precision by reach.** A tight `gloveReach` makes Jev commit exactly on the read and miss when
+ the ball comes in hot; a wide one lets it recover.
+- **Write a distinct style line.** "Read the sound off the bat and burst to the spot" plays very
+ differently from "glide — never sprint, always keep some glide in reserve." Jev will visibly field
+ differently.
+
+Do NOT just ship the template. Every `catcher.json` you publish should be its own session with a
+deliberate, testable difficulty.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the fielding: does Jev catch
+the full session at a calm fall, and leak when you speed the falls up — or does it never leak (dull)
+or leak even on a slow pop (bad)? Either extreme is a finding to report, not a bug to mask.
+
+## Rules
+
+- Keep `catcher.json` valid JSON always. A bad edit freezes the session on the last good state. You
+ can change `fallTicks`/`gloveReach`/`fieldWidth`/`balls` live — the viewer rebuilds the field for
+ the new profile.
+- Keep `title`, `description` and `style` truthful — and never present this as a real ballgame,
+ real stats, or real coaching.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read before you
+ commit to it (e.g. "which way does Jev slide with 2 ticks to the catch?"). Use the `jev` helpers:
+ `noul`, `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the field
+ and lines up on the landing spot — so the demo runs offline. With a key, the viewer calls the real
+ API.
+- The Jev Catcher viewer writes `.harness/verdict.json` itself (caught, dropped, whether the session
+ was clean). Do not edit it.
+- This is a demo. The field, the pop flies and the timing are made up — never present this as a real
+ game or real coaching.
+
+## Definition of done
+
+- A valid `catcher.json` that parses and passes `toolchain/check.mjs`.
+- A session with a real decision loop: Jev reads the landing spot, slides to it, catches the slow
+ ones, and leaks them once the falls are too fast.
+- The fall and reach actually shape the session — report it if Jev never drops, or drops no matter
+ what.
diff --git a/store/agents/jev-catcher/LICENSE b/store/agents/jev-catcher/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-catcher/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-catcher/README.md b/store/agents/jev-catcher/README.md
new file mode 100644
index 000000000..7ff6e1f7a
--- /dev/null
+++ b/store/agents/jev-catcher/README.md
@@ -0,0 +1,56 @@
+# Jev Catcher
+
+**Jev — TypeSafe's System One model — is the fielder.** Pop flies drop from the sky to random spots
+on the outfield line; every tick Jev reads the glove's position and the next ball's landing spot and
+slides the glove — LEFT / RIGHT, or a fast burst — to be under it when it lands. Be there and it's
+an out; miss and the ball drops. Crank the falls faster than Jev can chase and the drops pile up.
+
+This is a harness for OpenHarness. The agent on the right edits `catcher.json`; the viewer on the
+left runs the field and asks Jev for each tick's slide, live. The decision loop is the show.
+
+## Anatomy
+
+```
+jev-catcher/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to build sessions with real decision loops
+ skills/catcher/SKILL.md # the fielding + verification craft
+ template/catcher.json # a starter session profile
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), catcher-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates catcher.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the outfield)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs the field over a loopback HTTP server. Each tick it drops a ball one step,
+asks Jev for the slide, and streams the session — the glove sliding along the grass, the ball arcing
+down to its landing spot (lighting up amber as an out), and a session log — to the pane. It calls
+`POST /v1/systemone` when `TYPESAFE_API_KEY` is set; without it a deterministic mock reads the same
+field and lines up on the landing spot, so the demo runs offline. `.harness/verdict.json` tracks
+caught, dropped, and whether the session was clean.
+
+The field is synthetic: balls land at random spots near the glove, and Jev's "slide" is a
+moment-to-moment line call — read the spot early, glide over, commit as it lands — which is why a
+faster fall (more ground to cover in fewer ticks) makes Jev look stretched and drop.
+
+## Jev, honestly
+
+Jev's headline claim is speed — decide in a loop faster than a large model can. Catcher celebrates
+that: a fielding decision on every tick. But the field, the pop flies and the timing are entirely
+made up, and Jev catches nothing real — this is a demo of decision-rate and calibration on a
+synthetic 1-D intercept problem, not a signal for real baseball, and the mock is a stand-in for
+*plumbing*, not judgement. Treat any "session" as a fun experiment, not coaching advice.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live outfielder — pop flies you can
+watch Jev read, chase, and catch (or drop) with every tick._
diff --git a/store/agents/jev-catcher/THIRD_PARTY_NOTICES.md b/store/agents/jev-catcher/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-catcher/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-catcher/harness.json b/store/agents/jev-catcher/harness.json
new file mode 100644
index 000000000..5abc9a993
--- /dev/null
+++ b/store/agents/jev-catcher/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-catcher",
+ "name": "Jev Catcher",
+ "category": "Sports",
+ "author": "Autonomous",
+ "description": "A live fielding demo. Jev — TypeSafe's System One model — is the outfielder, guarding the line as pop flies drop to random spots. Every tick Jev reads the glove's position and the next ball's landing spot and slides to catch it. Speed the falls up and Jev's glove can't keep up and the drops pile up.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "catcher.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-catcher/skills/catcher/SKILL.md b/store/agents/jev-catcher/skills/catcher/SKILL.md
new file mode 100644
index 000000000..f30f90936
--- /dev/null
+++ b/store/agents/jev-catcher/skills/catcher/SKILL.md
@@ -0,0 +1,61 @@
+---
+name: catcher
+description: Shape a Jev Catcher session (fall time, glove reach, field width), then verify Jev catches the slow pop flies and drops the fast ones.
+---
+
+# Catching the field
+
+The skill for building `catcher.json` pieces. On the left, Jev is the fielder guarding the outfield:
+balls pop up at random spots and fall, and every tick Jev reads the glove's position and the next
+ball's landing spot and slides the glove to catch it. A catch needs the glove under the ball when it
+lands **within reach** of the landing spot; otherwise the ball drops.
+
+The difficulty **falls** to two dials:
+
+- **`fallTicks`** — how many ticks a ball takes to come down. This is the main dial. Fewer ticks
+ means the ball drops faster, leaving Jev less time to cross the field — so at low `fallTicks` Jev
+ physically can't get there in time and the drops pile up.
+- **`gloveReach`** — how close the glove must be to the landing spot to make the catch (the reach
+ radius). Tighter reach means Jev has to be precise, not just near.
+
+Crank `fallTicks` down (or shrink `gloveReach`) and Jev's glove can't keep up and it leaks balls;
+the honest physical slew limit is the difficulty, not random noise. This is the general recipe for
+this harness: **make the ball fall too fast to chase, and Jev's misses read as Jev's limit.**
+
+## Craft
+
+- **Curate a catching mood.** Default `fallTicks` ~`10` (reach `1.6`) is crisp and frequently clean.
+ Drop `fallTicks` to `7` and Jev leaks; to `5` or below it's a rain of drops. Raise `fallTicks` to
+ `13+` for a leisurely, near-perfect session.
+- **Tension by reach.** A tight `gloveReach` (`0.5`, say) makes Jev read the landing spot *exactly*
+ — it starts to miss when the ball comes in hot. A wide one is forgiving.
+- **Write a distinct style line.** "Read the sound off the bat and burst to the spot" plays very
+ differently from "glide, don't sprint — always keep some glide in reserve." Jev will visibly
+ field differently.
+
+Do NOT just ship the template. Every `catcher.json` you publish should be its own session with a
+deliberate, testable difficulty.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the fielding: does Jev catch
+the full session at a calm fall, and leak when you speed the falls up — or does it never leak (dull)
+or leak even on a slow pop (bad)? Either extreme is a finding to report, not a bug to mask.
+
+## Rules
+
+- Keep `catcher.json` valid JSON always. A bad edit freezes the session on the last good state. You
+ can change `fallTicks`/`gloveReach`/`fieldWidth`/`balls` live — the viewer rebuilds the field for
+ the new profile.
+- Keep `title`, `description` and `style` truthful — and never present this as real baseball, real
+ stats, or real coaching.
+- The catcher viewer writes `.harness/verdict.json` itself (caught, dropped, whether the session was
+ clean). Do not edit it.
+- This is a demo. The field, the pop flies and the timing are made up — never present this as a real
+ game or real fielding advice.
+
+## Definition of done
+
+- A valid `catcher.json` that parses and passes `toolchain/check.mjs`.
+- A real fielding loop: Jev reads the landing spot, slides to it, catches the slow ones, and leaks
+ them once the falls are too fast.
+- The fall and reach actually shape the session — report it if Jev never drops, or drops no matter
+ what.
diff --git a/store/agents/jev-catcher/store.json b/store/agents/jev-catcher/store.json
new file mode 100644
index 000000000..d7f120494
--- /dev/null
+++ b/store/agents/jev-catcher/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev guards the outfield, sliding to catch each pop fly as it falls, live",
+ "examples": [
+ {
+ "prompt": "Set Jev Catcher up for a hard session — speed the pop flies up so they drop faster than Jev can chase. Give Jev a burst-to-the-spot fielding style, then watch it read the landing spot every tick, slide the glove across the grass, and catch (or drop) each ball as it falls.",
+ "caption": "Jev's Day at the Field — a fast decision model sliding the glove to catch every pop fly on each tick"
+ }
+ ]
+}
diff --git a/store/agents/jev-catcher/template/catcher.json b/store/agents/jev-catcher/template/catcher.json
new file mode 100644
index 000000000..f6ccb4d94
--- /dev/null
+++ b/store/agents/jev-catcher/template/catcher.json
@@ -0,0 +1,11 @@
+{
+ "title": "Jev Catcher",
+ "description": "Jev is the fielder — slide the glove and catch every pop fly.",
+ "instrument": "CATCHER",
+ "tickMs": 140,
+ "fallTicks": 10,
+ "gloveReach": 1.6,
+ "fieldWidth": 24,
+ "balls": 14,
+ "style": "You are the fielder. A ball pops up and falls to a spot on the line — slide the glove to be right under it when it lands. Get there in time and it is an out; miss and it drops. Be decisive, read the landing spot early."
+}
diff --git a/store/agents/jev-catcher/test/viewer.test.mjs b/store/agents/jev-catcher/test/viewer.test.mjs
new file mode 100644
index 000000000..fc8b7633f
--- /dev/null
+++ b/store/agents/jev-catcher/test/viewer.test.mjs
@@ -0,0 +1,81 @@
+// Viewer integration test for Jev Catcher. Spins up the real viewer against a temp workspace and
+// checks the loop: balls fall, Jev slides the glove, the verdict updates, and control commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const CFG = {
+ title: 'Test Run', instrument: 'CATCHER', tickMs: 100, fallTicks: 8, gloveReach: 1.6, fieldWidth: 24, balls: 10,
+ style: 'Catch every pop fly.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-catcher-test-'))
+ writeFileSync(join(ws, 'catcher.json'), JSON.stringify({ ...CFG, ...overrides }))
+ const { startCatcherViewer } = await import(viewerPath)
+ const viewer = await startCatcherViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Catcher fields and Jev slides the glove', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const deadline = Date.now() + 2500
+ let saw = false
+ while (Date.now() < deadline) {
+ await wait(120)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ if (s.history.length >= 3) {
+ assert.ok(['LEFT_FAST', 'LEFT', 'HOLD', 'RIGHT', 'RIGHT_FAST'].includes(s.move))
+ assert.ok(typeof s.glove === 'number')
+ assert.ok(Array.isArray(s.balls) && s.balls.length === 10)
+ saw = true
+ break
+ }
+ }
+ assert.ok(saw, 'expected Jev to field and slide the glove')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Catcher writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 1500
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Catcher control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-catcher/toolchain/README.md b/store/agents/jev-catcher/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-catcher/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-catcher/toolchain/check.mjs b/store/agents/jev-catcher/toolchain/check.mjs
new file mode 100644
index 000000000..7c373c7a3
--- /dev/null
+++ b/store/agents/jev-catcher/toolchain/check.mjs
@@ -0,0 +1,31 @@
+#!/usr/bin/env node
+// check.mjs — validate a catcher.json for the Jev Catcher harness.
+// Enforces the shape the viewer needs: title, field profile, tick interval.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'catcher.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read catcher.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!p.title || typeof p.title !== 'string') bad('warn no title')
+if (p.instrument && p.instrument !== 'CATCHER') bad('warn instrument should be CATCHER')
+if (typeof p.fallTicks !== 'number' || p.fallTicks < 2 || p.fallTicks > 60) bad('error fallTicks (balls per catch) should be 2..60')
+if (typeof p.gloveReach !== 'number' || p.gloveReach <= 0 || p.gloveReach > 4) bad('error gloveReach must be 0..4')
+const W = p.fieldWidth ?? 24
+if (typeof W !== 'number' || W < 6 || W > 60) bad('error fieldWidth should be 6..60')
+if (typeof p.balls !== 'number' || p.balls < 1 || p.balls > 100) bad('error balls should be 1..100')
+if (typeof p.tickMs !== 'number' || p.tickMs < 60 || p.tickMs > 2000) bad('error tickMs must be ms 60..2000')
+if (!p.style || typeof p.style !== 'string') bad('warn a style line helps Jev field coherently')
+
+console.log(fail ? 'fail invalid catcher.json' : 'ok catcher.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-catcher/toolchain/doctor.sh b/store/agents/jev-catcher/toolchain/doctor.sh
new file mode 100755
index 000000000..42df4ed1c
--- /dev/null
+++ b/store/agents/jev-catcher/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Catcher viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-catcher/toolchain/init-workspace.sh b/store/agents/jev-catcher/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-catcher/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-catcher/toolchain/jev.mjs b/store/agents/jev-catcher/toolchain/jev.mjs
new file mode 100644
index 000000000..68e92ecda
--- /dev/null
+++ b/store/agents/jev-catcher/toolchain/jev.mjs
@@ -0,0 +1,764 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+/**
+ * Pendulum-balancing read used by the mock when the state text carries the current pole angle and
+ * angular velocity (the viewer renders e.g. "angle: +12° velocity: -0.8 rad/s"). We compute the
+ * corrective action the pole is asking for: lean/fall to the right (positive angle) wants a
+ * leftward torque, and also damp any velocity. Returns per-action boosts so the deterministic mock
+ * biases toward the right call while staying slightly noisy — so Jev can fail when it's sloppy and
+ * the fall reads as Jev's mistake. Real Jev reads the same text — the mock is a stand-in.
+ */
+function pendulumRead(text) {
+ const mA = text.match(/angle:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const mV = text.match(/velocity:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const deg = mA ? Number(mA[1]) : NaN
+ const vel = mV ? Number(mV[1]) : NaN
+ if (!Number.isFinite(deg) || !Number.isFinite(vel)) return null
+ const a = (deg * Math.PI) / 180
+ // desired torque = -(Kp*a + Kv*vel); pick the action whose torque is closest.
+ const want = -(6.5 * a + 3.2 * vel)
+ const ACTS = { LEFT_HARD: -1.6, LEFT: -0.8, CENTER: 0, RIGHT: 0.8, RIGHT_HARD: 1.6 }
+ const boost = {}
+ for (const [name, t] of Object.entries(ACTS)) {
+ boost[name] = 1.4 - Math.abs(t - Math.max(-1.6, Math.min(1.6, want))) * 0.9
+ }
+ // The mock can't see the gravity dial — it just balances. But a fast judge on a hard
+ // rig will hesitate more, so the misjudgement rate rises with how hard the balance is.
+ // Low gravity: calm, near-perfect. High gravity: it starts to overshoot and lose it.
+ const hard = (parseFloat((text.match(/hardness:\s*([0-9.]+)/i) || [null, '0'])[1]) || 0)
+ const noise = Math.min(0.55, 0.03 + hard * 0.06)
+ return { boost, noise }
+}
+
+/**
+ * Pong-defender read used by the mock when the state text carries a ball position/velocity and the
+ * paddle's centre. We predict where the ball will cross the paddle's wall (reflecting off floor and
+ * ceiling) and bias the paddle move toward that intercept, with a reaction that degrades as the ball
+ * gets faster. Returns per-move boosts plus a beta error chance so Jev can visibly lose a fast rally.
+ */
+function pongRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/ball:\s*x\s+([-0-9.]+)/i)
+ const y = num(/y\s+([-0-9.]+)\s+vx/i)
+ const vx = num(/vx\s+([-0-9.]+)\s+vy/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const paddleY = num(/centre y\s+([-0-9.]+)/i)
+ const half = num(/half-height\s+([-0-9.]+)/i)
+ const courtH = num(/court:\s*[-0-9.]+\s*[x×]\s*([-0-9.]+)/i)
+ const speed = num(/speed:\s*([-0-9.]+)/i)
+ if (![x, y, vx, vy, paddleY, half, courtH, speed].every(Number.isFinite)) return null
+ const r = 3
+ const span = courtH - 2 * r
+ // When the ball is moving away (rightward), the paddle's job is to stop chasing and hold still so
+ // it's framed to meet the ball when it comes back — letting the rally breathe.
+ if (vx >= 0) return { boost: { HOLD: 1.9, MOVE_UP: 0.7, MOVE_DOWN: 0.7, MOVE_UP_FAST: 0.3, MOVE_DOWN_FAST: 0.3 }, noise: 0, close: false }
+ // time (in ball steps) to reach the left wall
+ const t = -x / vx
+ const dy = vy * t
+ let u = ((y - r + dy) % (2 * span) + 2 * span) % (2 * span)
+ u = u <= span ? u : 2 * span - u
+ const ty = r + u
+ const want = ty - paddleY
+ const goDown = want > half * 0.5
+ const goUp = want < -half * 0.5
+ const boost = {}
+ for (const name of ['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST']) {
+ if (goDown) boost[name] = name === 'MOVE_DOWN' ? 1.8 : name === 'MOVE_DOWN_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else if (goUp) boost[name] = name === 'MOVE_UP' ? 1.8 : name === 'MOVE_UP_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else boost[name] = name === 'HOLD' ? 1.8 : 0.8
+ }
+ // faster ball → the intercept at the wall changes fast and the paddle has fewer ticks to reach it,
+ // so the physical difficulty (max paddle speed) does the work. No injected noise: a miss is honest.
+ return { boost }
+}
+
+/**
+ * Shopper read used by the mock when the state text carries the recent price stream for each
+ * product (the viewer renders "Name: price (+x% over N ticks) vol v% [spark]"). We score each
+ * product by how fast its price is still falling — the best value right now — and bias the "best
+ * buy" choice toward the steepest falling momentum, plus a confidence that depends on how far the
+ * top pick stands out. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function shopperRead(text) {
+ const picks = []
+ const re = /^\s*([^:\n]+?):\s*([0-9.]+)\s*\(\s*([+-][0-9.]+)% over (\d+) ticks\)\s*vol\s*([0-9.]+)%\s*\[([^\]]*)\]/gim
+ let m
+ while ((m = re.exec(text))) {
+ const name = m[1].trim()
+ const price = Number(m[2])
+ const chgPct = Number(m[3])
+ picks.push({ name, price, chgPct })
+ }
+ if (picks.length < 2) return null
+ // best value = most negative recent change (still falling the fastest)
+ const sorted = picks.slice().sort((a, b) => a.chgPct - b.chgPct)
+ const best = sorted[0]
+ const second = sorted[1]
+ const spread = second.chgPct - best.chgPct
+ const boost = {}
+ for (const p of picks) boost[p.name] = p.name === best.name ? 1.6 : p.name === second.name ? 0.9 : 0.2
+ // confidence: strong when the leader clearly out-falls the rest; weak when it's a dead heat
+ const confidence = Math.min(0.95, Math.max(0.15, 0.5 + spread * 0.6))
+ return { boost, confidence, best: best.name }
+}
+
+/**
+ * Lander read used by the mock when the state text carries booster telemetry
+ * ("ALT x VY y G g FUEL f%"). We pick a throttle by altitude and vertical speed — burn early and
+ * hard enough to keep descent in check while high, flare gently low so the touchdown is soft —
+ * and bias the throttle choice toward it, with a noise term that grows with gravity so high-g
+ * missions look twitchy and start to crash. Real Jev reads the same lines — the mock is a
+ * stand-in.
+ */
+function landerRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const alt = num(/alt\s+([-0-9.]+)/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const g = num(/g\s+([-0-9.]+)/i)
+ if (![alt, vy, g].every((v) => Number.isFinite(v))) return null
+ let pick
+ if (alt > 30) {
+ if (vy < -2.5) pick = 'BURN'
+ else if (vy < -1.2) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 16) {
+ if (vy < -1.8) pick = 'BURN'
+ else if (vy < -0.8) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 7) {
+ if (vy < -1.0) pick = 'BURN'
+ else if (vy < -0.3) pick = 'HOVER'
+ else pick = 'COAST'
+ } else {
+ if (vy < -0.4) pick = 'BURN'
+ else pick = 'CUT'
+ }
+ const boost = { CUT: 0.2, COAST: 0.6, HOVER: 0.7, BURN: 0.5 }
+ if (boost[pick] !== undefined) boost[pick] = 1.9
+ // twitchiness grows with gravity: higher g -> more over/under correction
+ boost.noise = Math.min(0.55, 0.06 + Math.max(0, (g - 1.5)) * 0.14)
+ return { boost, pick, g }
+}
+
+/**
+ * Slalom read used by the mock when the state text carries the skier's x and the next gate ("skier x
+ * X gate x G gate in D"). We steer toward the gate — committing harder as it arrives — with a small
+ * aim error that grows the less time there is, so faster descents look wobblier and fall. Real Jev
+ * reads the same lines — the mock is a stand-in.
+ */
+function slalomRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/skier x\s+([-0-9.]+)/i)
+ const gx = num(/gate x\s+([-0-9.]+)/i)
+ const rowGap = num(/row gap\s+([-0-9.]+)/i)
+ const speed = num(/descends at\s+([-0-9.]+)/i)
+ if (![x, gx, rowGap].every((v) => Number.isFinite(v))) return null
+ const spd = Number.isFinite(speed) ? speed : 2.4
+ // Reaction lag: the faster the descent, the later Jev reacts to an approaching gate (fewer spare
+ // ticks to cross the valley), so it arrives pointed at the old line and clips the gate.
+ const lag = Math.max(0, Math.floor((spd - 1.8) * 1.7))
+ const reachRows = 18 - lag * spd
+ const need = Math.abs(gx - x)
+ let pick = 'HOLD'
+ if (rowGap <= reachRows) {
+ const want = gx - x
+ if (want < -1.3) pick = 'LEFT_FAST'
+ else if (want > 1.3) pick = 'RIGHT_FAST'
+ else if (want < -0.5) pick = 'LEFT'
+ else if (want > 0.5) pick = 'RIGHT'
+ else pick = 'HOLD'
+ }
+ const boost = { LEFT_FAST: 0.05, LEFT: 0.05, HOLD: 0.05, RIGHT: 0.05, RIGHT_FAST: 0.05 }
+ if (boost[pick] !== undefined) boost[pick] = 1.99
+ return { boost, pick, rowGap }
+}
+
+/**
+ * Catcher read used by the mock when the state text carries the glove's x and the next ball's
+ * landing spot ("glove x X ball lands B in N ticks"). We slide toward the landing spot — reading it
+ * early and coasting far out, committing harder as it nears — and bias the glove move toward that.
+ * The physical limit (fewer fall ticks than it takes to cross the field) is what makes Jev leak
+ * balls — no injected wobble. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function catcherRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const gx = num(/glove x\s+([-0-9.]+)/i)
+ const bx = num(/ball lands\s+([-0-9.]+)/i)
+ const ticks = num(/in\s+([-0-9.]+)\s+ticks/i)
+ if (![gx, bx, ticks].every((v) => Number.isFinite(v))) return null
+ const want = bx - gx
+ // Far out, a gentle read settles on the landing spot; near the catch, commit fast.
+ let pick
+ if (ticks > 6) pick = want < -0.4 ? 'LEFT' : want > 0.4 ? 'RIGHT' : 'HOLD'
+ else pick = want < -1.0 ? 'LEFT_FAST' : want > 1.0 ? 'RIGHT_FAST' : want < -0.4 ? 'LEFT' : want > 0.4 ? 'RIGHT' : 'HOLD'
+ const boost = { LEFT_FAST: 0.05, LEFT: 0.05, HOLD: 0.05, RIGHT: 0.05, RIGHT_FAST: 0.05 }
+ if (boost[pick] !== undefined) boost[pick] = 1.99
+ return { boost, pick, want, ticks }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ // Shopper: "act now" is urgent when the best buy clearly out-falls the field. Ask Jev to spend
+ // when the momentum spread is wide, so the demo eventually commits on paper.
+ if (/act now|spend now|strong enough/i.test(qtext) || /buy|act/i.test(q.instructions)) {
+ const shop = shopperRead(text)
+ if (shop && shop.confidence) p = Math.max(p, Math.min(0.9, 0.4 + shop.confidence * 0.5))
+ }
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Pendulum: if the state carries an angle + angular velocity, bias toward the balancing action,
+ // and occasionally flip to a neighbour (a fast model that sometimes hesitates) so the pole can
+ // visibly wobble — that wiggle is the demo.
+ const pen = pendulumRead(text)
+ if (pen) {
+ options.forEach((opt, i) => {
+ const b = pen.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (pen.noise && (hash01('pen', salt + 9) < pen.noise)) {
+ // flip the current best to two neighbours over — a big, costly overcorrection
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + (hash01('dir', salt) < 0.5 ? -2 : 2)))
+ if (ni !== best.i) raw[ni] += 2.2
+ }
+ }
+ // Pong: if the state text carries a ball + paddle, steer the paddle to the predicted intercept,
+ // and lag harder (miss more) as the ball speeds up.
+ const pong = pongRead(text)
+ if (pong) {
+ options.forEach((opt, i) => {
+ const b = pong.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Shopper: if the state carries a product price stream, bias "best buy" toward the product
+ // whose price is still falling the fastest.
+ const shop = shopperRead(text)
+ if (shop) {
+ options.forEach((opt, i) => {
+ const b = shop.boost[String(opt).toLowerCase()]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Lander: if the state carries booster telemetry, bias the throttle toward a plausible burn and
+ // flip to a worse one more often as gravity rises, so high-g missions look twitchy and crash.
+ const land = landerRead(text)
+ if (land) {
+ options.forEach((opt, i) => {
+ const b = land.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (land.boost.noise && (hash01('land', salt + 11) < land.boost.noise)) {
+ // over or under-throttle by one step — a costly hesitation
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const step = hash01('ldir', salt) < 0.5 ? 1 : -1
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + step))
+ if (ni !== best.i && land.boost[String(options[ni])] !== undefined) raw[ni] += 2.4
+ }
+ }
+ // Slalom: if the state carries the skier's x and the next gate, steer toward it once it's in
+ // reach; the physical slew limit (fast descents have too few ticks to cross the valley) is what
+ // makes it fall — no injected wobble.
+ const slal = slalomRead(text)
+ if (slal) {
+ options.forEach((opt, i) => {
+ const b = slal.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Catcher: if the state carries the glove's x and the next ball's landing spot, slide toward it.
+ // The physical slew limit (fewer fall ticks than it takes to cross the field) is what leaks
+ // balls — no injected wobble.
+ const catchr = catcherRead(text)
+ if (catchr) {
+ options.forEach((opt, i) => {
+ const b = catchr.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-catcher/toolchain/setup.sh b/store/agents/jev-catcher/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-catcher/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-catcher/toolchain/viewer.sh b/store/agents/jev-catcher/toolchain/viewer.sh
new file mode 100755
index 000000000..2785e81a6
--- /dev/null
+++ b/store/agents/jev-catcher/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Catcher viewer (Jev is the fielder, sliding the glove to catch every pop fly).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-catcher/viewer/index.html b/store/agents/jev-catcher/viewer/index.html
new file mode 100644
index 000000000..1d82ff355
--- /dev/null
+++ b/store/agents/jev-catcher/viewer/index.html
@@ -0,0 +1,56 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Catcher</title>
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Catcher</h1></div>
+ <div class="stats">
+ <div class="stat"><label>Ball</label><span id="ball">—</span></div>
+ <div class="stat"><label>Slide</label><span id="move">—</span></div>
+ <div class="stat"><label>Fall</label><span id="fall">—</span></div>
+ <div class="stat"><label>Caught</label><span id="caught">0</span></div>
+ <div class="stat"><label>Drops</label><span id="drops">0</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="tick">Step</button>
+ <button class="primary" id="reset">Reset</button>
+ </div>
+ </div>
+ <main>
+ <section id="stage">
+ <div class="panel panel-stage">
+ <div class="panel-title">The outfield</div>
+ <div id="field">
+ <canvas id="scene"></canvas>
+ <div id="banner" class="hidden"></div>
+ </div>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Jev, the fielder</div>
+ <div class="how">
+ Jev is guarding the outfield. A ball pops up and falls to a spot on the line, and every
+ tick it reads the landing spot and the glove's position and slides <code>LEFT</code> /
+ <code>RIGHT</code> (or commits fast) to be under it when it lands. Miss and it drops.<br><br>
+ Edit <code>catcher.json</code>: crank <code>fallTicks</code> down and the balls come too
+ fast for Jev to chase, and the drops pile up; shrink <code>gloveReach</code> and Jev has
+ to read the spot exactly.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Session log</div>
+ <ul id="log"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-catcher/viewer/jev-hud.js b/store/agents/jev-catcher/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-catcher/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-catcher/viewer/studio.css b/store/agents/jev-catcher/viewer/studio.css
new file mode 100644
index 000000000..24b91acaa
--- /dev/null
+++ b/store/agents/jev-catcher/viewer/studio.css
@@ -0,0 +1,71 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #10b981; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #0f1b16 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(16,32,24,.9), rgba(10,12,18,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#ball { color: var(--cyan); }
+#move { color: var(--accent); }
+#fall { color: var(--amber); }
+#caught { color: var(--ok); }
+#drops { color: var(--rose); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #047857, #10b981); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+.panel-stage { padding: 10px; }
+
+#field { position: relative; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: #dbe7d2; }
+#scene { width: 100%; height: 62vh; display: block; }
+#banner {
+ position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%);
+ padding: 10px 22px; border-radius: 10px; font-size: 15px; font-weight: 700; letter-spacing: .5px;
+ font-family: var(--mono); white-space: nowrap;
+}
+#banner.ok { background: rgba(16,185,129,.18); border: 1px solid var(--ok); color: #065f46; box-shadow: 0 0 30px rgba(16,185,129,.4); }
+#banner.bad { background: rgba(225,29,72,.18); border: 1px solid #e11d48; color: #881337; box-shadow: 0 0 30px rgba(225,29,72,.4); }
+#banner.hidden { display: none; }
+
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px; display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(16,24,20,.5); }
+.how { color: var(--dim); font-size: 13px; line-height: 1.5; }
+.how b { color: var(--cyan); }
+.how code { color: var(--amber); }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; max-height: 50vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 10px; align-items: baseline; }
+#log li .n { color: var(--accent); }
+#log li .a { width: 90px; color: var(--cyan); font-weight: 700; }
+#log li .p { color: var(--amber); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-catcher/viewer/studio.js b/store/agents/jev-catcher/viewer/studio.js
new file mode 100644
index 000000000..b4668c223
--- /dev/null
+++ b/store/agents/jev-catcher/viewer/studio.js
@@ -0,0 +1,198 @@
+// Jev Catcher pane — draws a side-on outfield: a glove slides left/right along the ground as pop
+// flies arc down from the sky, light up amber when caught, and thud and bounce when dropped. A
+// finished session shows a clean-session or dropped banner.
+
+const $ = (id) => document.getElementById(id)
+const els = {
+ ball: $('ball'), move: $('move'), fall: $('fall'), caught: $('caught'), drops: $('drops'),
+ banner: $('banner'), log: $('log'), scene: $('scene'),
+}
+
+let glove = 12, move = 'HOLD', catches = 0, drops = 0
+let fallTicks = 10, width = 24, ballTicks = 10
+let finished = null
+let balls = []
+let next = 0
+let history = []
+let prevBallId = -1
+
+// frothy effects: catch flashes and dropped-ball bounces
+let flashes = [] // {x, t}
+let bounces = [] // {x, y, vy, t}
+
+function draw() {
+ const c = els.scene
+ const ctx = c.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = c.clientWidth, H = c.clientHeight
+ c.width = W * dpr; c.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+
+ // sky to grass
+ const grd = ctx.createLinearGradient(0, 0, 0, H)
+ grd.addColorStop(0, '#bfe7d6')
+ grd.addColorStop(0.5, '#eef7ef')
+ grd.addColorStop(0.62, '#79b456')
+ grd.addColorStop(1, '#4e8a38')
+ ctx.fillStyle = grd
+ ctx.fillRect(0, 0, W, H)
+
+ const groundY = H * 0.68
+ ctx.strokeStyle = 'rgba(30,70,20,.4)'; ctx.lineWidth = 2
+ ctx.beginPath(); ctx.moveTo(0, groundY); ctx.lineTo(W, groundY); ctx.stroke()
+
+ const margin = 26
+ const fieldLeft = margin, fieldRight = W - margin
+ const px = (fx) => fieldLeft + (fx / width) * (fieldRight - fieldLeft)
+
+ // grandstand / fence posts behind the grass line
+ ctx.fillStyle = 'rgba(255,255,255,.35)'
+ for (let x = fieldLeft; x < fieldRight; x += 38) ctx.fillRect(x, groundY - 18, 3, 18)
+
+ // landing-spot marker for the current ball
+ const cur = balls[next]
+ if (cur && !cur.done) {
+ const lx = px(cur.land)
+ ctx.strokeStyle = 'rgba(0,0,0,.3)'; ctx.lineWidth = 1.5; ctx.setLineDash([4, 4])
+ ctx.beginPath(); ctx.ellipse(lx, groundY + 2, 7, 2.5, 0, 0, Math.PI * 2); ctx.stroke()
+ ctx.setLineDash([])
+ }
+
+ // the glove (Jev) sliding along the ground
+ const gx = px(glove)
+ ctx.fillStyle = 'rgba(0,0,0,.22)'
+ ctx.beginPath(); ctx.ellipse(gx, groundY + 3, 17, 3, 0, 0, Math.PI * 2); ctx.fill()
+ ctx.fillStyle = '#b45309'
+ ctx.beginPath(); ctx.ellipse(gx, groundY - 9, 15, 10, 0, 0, Math.PI * 2); ctx.fill()
+ ctx.fillStyle = '#92400e'
+ ctx.beginPath(); ctx.ellipse(gx, groundY - 10, 9, 6, 0, 0, Math.PI * 2); ctx.fill()
+
+ // the active ball arcing down to its landing spot
+ if (cur && !cur.done && ballTicks > 0) {
+ const prog = (fallTicks - ballTicks) / fallTicks // 0 high, 1 at the ground
+ const peakH = H * 0.5
+ const bx = px(cur.land)
+ const yy = groundY - peakH * ((1 - prog) * (1 - prog))
+ // rise-fall trail behind it
+ ctx.strokeStyle = 'rgba(255,255,255,.45)'; ctx.lineWidth = 2
+ ctx.beginPath()
+ for (let k = 0; k <= 1; k += 0.16) {
+ const ky = groundY - peakH * ((1 - Math.max(0, prog - k * 0.5)) ** 2)
+ k ? ctx.lineTo(bx, ky) : ctx.moveTo(bx, ky)
+ }
+ ctx.stroke()
+ // the ball itself with a seam
+ ctx.fillStyle = '#facc15'
+ ctx.beginPath(); ctx.arc(bx, yy, 7, 0, Math.PI * 2); ctx.fill()
+ ctx.strokeStyle = '#92400e'; ctx.lineWidth = 1.4
+ ctx.beginPath()
+ ctx.moveTo(bx - 5, yy); ctx.lineTo(bx + 5, yy)
+ ctx.moveTo(bx, yy - 5); ctx.lineTo(bx, yy + 5)
+ ctx.stroke()
+ // shadow ring as it nears the ground
+ ctx.fillStyle = `rgba(0,0,0,${0.12 + prog * 0.2})`
+ ctx.beginPath(); ctx.ellipse(bx, groundY + 2, 5 + prog * 6, 2, 0, 0, Math.PI * 2); ctx.fill()
+ }
+
+ // catch flash rings
+ flashes.forEach((f) => {
+ const t = f.t
+ ctx.strokeStyle = `rgba(245,158,11,${1 - t})`
+ ctx.lineWidth = 3
+ ctx.beginPath(); ctx.arc(px(f.x), groundY - 8, 14 + t * 34, 0, Math.PI * 2); ctx.stroke()
+ })
+
+ // dropped-ball bounces
+ bounces.forEach((b) => {
+ b.y -= b.vy; b.vy *= 0.8
+ if (b.y <= groundY) { b.y = groundY + 0.5; b.vy = Math.abs(b.vy) * 0.55 }
+ ctx.fillStyle = `rgba(250,204,21,${Math.max(0, 1 - b.t)})`
+ ctx.beginPath(); ctx.arc(px(b.x), b.y, 4, 0, Math.PI * 2); ctx.fill()
+ })
+
+ flashes = flashes.map((f) => ({ x: f.x, t: f.t + 0.05 })).filter((f) => f.t < 1)
+ bounces = bounces.map((b) => ({ ...b, t: b.t + 0.05 })).filter((b) => b.t < 0.9)
+}
+
+function pump() {
+ draw()
+ if (flashes.length || bounces.length) requestAnimationFrame(pump)
+}
+
+function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])) }
+
+function renderLog() {
+ els.log.textContent = ''
+ for (let i = 0; i < balls.length; i++) {
+ const b = balls[i]
+ if (!b.done) break
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="n">#${i + 1}</span><span class="p">${b.caught ? '● caught' : '○ drop'}</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function renderBanner() {
+ if (!finished) { els.banner.classList.add('hidden'); return }
+ els.banner.classList.remove('hidden')
+ els.banner.textContent = finished.ok
+ ? `✓ CLEAN SESSION · ${finished.caught} caught`
+ : `✗ ${finished.caught} caught · ${finished.dropped} dropped`
+ els.banner.className = 'banner ' + (finished.ok ? 'ok' : 'bad')
+}
+
+function onTick(msg) {
+ if (typeof msg.glove === 'number') glove = msg.glove
+ if (typeof msg.fallTicks === 'number') fallTicks = msg.fallTicks
+ if (typeof msg.fieldWidth === 'number') width = msg.fieldWidth
+ if (typeof msg.ballTicks === 'number') ballTicks = msg.ballTicks
+ move = msg.move || move
+ catches = msg.catches ?? catches
+ drops = msg.drops ?? drops
+ finished = msg.finished || null
+ balls = msg.balls || balls
+ next = msg.next ?? next
+ history = msg.history || history
+
+ // fresh outcomes -> one-shot effects
+ const cur = balls[next - 1]
+ if (cur && cur.done && next - 1 !== prevBallId) {
+ if (cur.caught) flashes.push({ x: cur.land, t: 0 })
+ else bounces.push({ x: cur.land, y: groundYFrom(), vy: 8, t: 0 })
+ prevBallId = next - 1
+ }
+
+ els.ball.textContent = finished ? '—' : `${Math.min(next + 1, balls.length)}/${balls.length}`
+ els.move.textContent = move
+ els.fall.textContent = fallTicks + 't'
+ els.caught.textContent = String(catches)
+ els.drops.textContent = String(drops)
+
+ renderBanner()
+ renderLog()
+ draw()
+ if (flashes.length || bounces.length) requestAnimationFrame(pump)
+}
+
+function groundYFrom() {
+ const c = els.scene
+ return (c.clientHeight || 300) * 0.68
+}
+
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-catcher/viewer/viewer.mjs b/store/agents/jev-catcher/viewer/viewer.mjs
new file mode 100644
index 000000000..b25de0cfa
--- /dev/null
+++ b/store/agents/jev-catcher/viewer/viewer.mjs
@@ -0,0 +1,270 @@
+// Jev Catcher viewer — a loopback server running a live fielding demo. A fielder guards the outfield:
+// balls pop up at random spots and fall; Jev (TypeSafe's System One model) reads the glove's x and
+// the next ball's landing spot every tick and slides the glove to catch it. A ball it isn't under
+// drops. The agent shapes catcher.json (how many ticks a ball takes to fall, the glove's reach) —
+// speed the falls up and Jev's glove can't keep up and the drops pile up. The field is synthetic;
+// the decision loop is the demo.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds catcher.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT = {
+ title: 'Jev Catcher',
+ description: 'Jev is the fielder — slide the glove and catch every pop fly.',
+ instrument: 'CATCHER',
+ tickMs: 140, fallTicks: 10, gloveReach: 1.6, fieldWidth: 24, balls: 14,
+ style: 'You are the fielder. A ball pops up and falls to a spot on the line — slide the glove to be right under it when it lands. Get there in time and it is an out; miss and it drops. Be decisive, read the landing spot early.',
+}
+
+const MOVES = ['LEFT_FAST', 'LEFT', 'HOLD', 'RIGHT', 'RIGHT_FAST']
+const MV = { LEFT_FAST: -1.2, LEFT: -0.6, HOLD: 0, RIGHT: 0.6, RIGHT_FAST: 1.2 }
+
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+
+function makeBalls(count, W, rng) {
+ // a stream of pop flies: each lands at a spot within reach of where the glove will be
+ const balls = []
+ let x = W / 2
+ for (let i = 0; i < count; i++) {
+ const land = clamp(x + (rng() - 0.5) * 2 * Math.min(W * 0.4, 10), 1, W - 1)
+ balls.push({ land, phase: 0, done: false, caught: false })
+ x = land
+ }
+ return balls
+}
+
+function stateBlock(p, s, ball) {
+ return `${p.style}
+A ball lands at x ${ball.land.toFixed(1)} in ${s.ballTicks} ticks.
+glove x ${s.glove.toFixed(1)} ball lands ${ball.land.toFixed(1)} in ${s.ballTicks} ticks
+Which way do you slide the glove? ${MOVES.join(' / ')}`
+}
+
+export async function startCatcherViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let error = null
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let step = 0
+ let running = false
+ let state = null // {glove, ballTicks, balls, next}
+ let move = 'HOLD'
+ let episode = 0 // bumps each time an episode restarts on its own, so the next one differs
+ let finished = null // {ok, ticks, caught, dropped, drops}
+ let history = [] // {step, glove, move, caught, dropped}
+ let notified = false
+ let rng
+
+ let lastCfg = null
+ let p = readCfg(join(workspace, 'catcher.json'))
+
+ function readCfg(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ const merged = { ...DEFAULT, ...raw }
+ if (!lastCfg || merged.fallTicks !== lastCfg.fallTicks || merged.fieldWidth !== lastCfg.fieldWidth || merged.balls !== lastCfg.balls || !state) {
+ resetStateNow(merged)
+ }
+ lastCfg = merged
+ return merged
+ } catch (e) {
+ error = clean(e.message)
+ return lastCfg || DEFAULT
+ }
+ }
+
+ function resetStateNow(cfg) {
+ rng = mulberry32(5039 + episode * 97)
+ const W = cfg.fieldWidth ?? DEFAULT.fieldWidth
+ state = { glove: W / 2, ballTicks: cfg.fallTicks ?? DEFAULT.fallTicks, balls: makeBalls(cfg.balls ?? DEFAULT.balls, W, rng), next: 0, catches: 0, drops: 0 }
+ move = 'HOLD'
+ finished = null
+ history = []
+ notified = false
+ step = 0
+ error = null
+ }
+ function resetState() { resetStateNow(p) }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ return {
+ spec: 1,
+ ready: history.length > 0 || finished !== null,
+ summary: error
+ ? 'Jev Catcher needs a fix'
+ : finished
+ ? `${p.title} · ${finished.ok ? 'clean session, ' + finished.caught + ' caught' : finished.caught + ' caught, ' + finished.dropped + ' dropped'}`
+ : `${p.title} · ball ${Math.min(state.next + 1, state.balls.length)}/${state.balls.length} · ${state.catches} caught · ${state.drops} dropped`,
+ findings: (error ? [{ severity: 'error', kind: 'catcher', message: error }] : []).concat(
+ finished
+ ? [{ severity: finished.ok ? 'info' : 'error', kind: 'catcher', message: finished.ok ? `Jev caught all ${finished.caught} pop flies` : `Jev dropped ${finished.dropped} of ${finished.caught + finished.dropped}` }]
+ : []
+ ),
+ artifact: 'catcher.json',
+ phases: [
+ { id: 'learn', name: 'Reading', state: history.length < 5 ? 'active' : 'done' },
+ { id: 'call', name: 'Fielding', state: history.length >= 5 && !finished ? 'active' : finished ? 'done' : 'pending' },
+ { id: 'finish', name: 'Session done', state: finished ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick', title: p.title, description: p.description, instrument: p.instrument,
+ fallTicks: p.fallTicks, fieldWidth: p.fieldWidth, gloveReach: p.gloveReach,
+ glove: state?.glove, move, step, running, error, finished,
+ balls: state?.balls, next: state?.next, catches: state?.catches, drops: state?.drops, ballTicks: state?.ballTicks,
+ history: history.slice(-300),
+ })
+ }
+
+ function reset() { resetState(); tail(); if (running) schedule() }
+ function pause() { running = false; clearTimeout(timer) }
+ function start() { if (!running) { running = true; schedule() } }
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, p.tickMs) }
+ async function run() {
+ if (stopped) return
+ if (finished) {
+ // Never sit on a finished screen: show the result briefly, then play again.
+ finished.shownAt ??= Date.now()
+ if (Date.now() - finished.shownAt > 3500) { episode++; resetState() }
+ tail(); schedule(); return
+ }
+ await decide()
+ schedule()
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ const ball = state.balls[state.next]
+ const res = await evaluate({
+ state: stateBlock(p, state, ball),
+ questions: {
+ move: { type: 'choice', instructions: 'Which way do you slide the glove this tick?', options: MOVES },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const pick = String(res.answers.move?.choice || 'HOLD')
+ move = MOVES.includes(pick) ? pick : 'HOLD'
+ // physics: slide and let the ball fall one tick closer
+ state.glove = clamp(state.glove + MV[move], 1, p.fieldWidth - 1)
+ state.ballTicks--
+ step++
+ history.push({ step, glove: state.glove, move, in: state.ballTicks })
+ if (history.length > 400) history.splice(0, history.length - 400)
+ if (state.ballTicks <= 0) {
+ // ball lands: glove must be under it (within reach)
+ if (Math.abs(state.glove - ball.land) <= p.gloveReach) {
+ ball.caught = true; ball.done = true; state.catches++
+ } else {
+ ball.done = true; state.drops++
+ }
+ state.next++
+ if (state.next < state.balls.length) {
+ state.ballTicks = p.fallTicks
+ } else {
+ finished = { ok: state.drops === 0, ticks: step, caught: state.catches, dropped: state.drops }
+ notified = true
+ }
+ }
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ const watcher = watch(join(workspace, 'catcher.json'), () => {
+ p = readCfg(join(workspace, 'catcher.json'))
+ tail()
+ if (running) schedule()
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: p.title, instrument: p.instrument, fallTicks: p.fallTicks, fieldWidth: p.fieldWidth, gloveReach: p.gloveReach, glove: state?.glove, move, step, running, error, finished, balls: state?.balls, next: state?.next, catches: state?.catches, drops: state?.drops, ballTicks: state?.ballTicks, history: history.slice(-300) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ resetState()
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startCatcherViewer({ workspace, port })
+ console.log(`Jev Catcher listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-compactor/.gitignore b/store/agents/jev-compactor/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-compactor/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-compactor/AGENTS.md b/store/agents/jev-compactor/AGENTS.md
new file mode 100644
index 000000000..0843fb149
--- /dev/null
+++ b/store/agents/jev-compactor/AGENTS.md
@@ -0,0 +1,99 @@
+# Jev Compactor in OpenHarness
+
+On the left is a live pane. A made-up coding agent works in a made-up repo, and its context window
+fills with messages and tool results (Read, Grep, Bash, Edit, WebFetch). When the window passes its
+budget, **Jev, TypeSafe's System One model, judges every tool result in one pass**: `keep`, `trim`
+or `drop`. The pane applies the verdicts and measures them against a hidden ground truth.
+
+On the right is you. You edit `session.json`. This is the ONLY file you edit. The viewer watches it
+and reacts at once.
+
+Everything here is synthetic. It is a demo of an idea, not a real compaction plugin. Never present
+the numbers as results for a real agent, a real repo or a real product.
+
+## The session file
+
+```jsonc
+{
+ "title": "Jev Compactor",
+ "description": "One line about this session.",
+ "repo": "harbor-pay", // a made-up repo name
+ "seed": 7, // same seed, same session
+ "budget": 200000, // tokens. Compaction fires above this. 20000..2000000
+ "target": 0.4, // after compaction the window must be under target x budget. 0.2..0.9
+ "trimTo": 400, // a trimmed block keeps this many tokens. 50..5000
+ "distraction": 0.12, // how much junk borrows the current task's words. 0..1
+ "recallTarget": 0.9, // the recall you want to hold. 0.5..1
+ "eventsPerSec": 4, // stream speed. 1..60
+ "noise": 0.45, // share of tool results that are pure junk. 0..0.9
+ "focus": 0.5, // share of real results that belong to the current task. 0.1..1
+ "taskEvery": 200, // the made-up user moves to the next task after this many events. 0 = never
+ "summaryTokens": 1500, // size of the baseline's summary block. 200..20000
+ "mix": { "user": 1, "assistant": 2, "Read": 7, "Grep": 3, "Bash": 6, "Edit": 3, "WebFetch": 2 },
+ "currentTask": "refunds", // the task the session starts on
+ "tasks": [
+ { "id": "refunds", "title": "Fix refund rounding in the ledger",
+ "vocabulary": ["refund", "ledger", "rounding", "cents", "reversal", "chargeback"] }
+ ]
+}
+```
+
+- **`tasks`** (2 to 12). Each task has an `id`, a `title` and a `vocabulary` of at least 6 single
+ words. Tool results and messages for a task are written with its words. Jev only sees text, so
+ the vocabulary is how it can tell tasks apart.
+- **`distraction`** is the difficulty dial. Low: junk uses junk words, Jev drops it, recall stays
+ near 100% and the cut is large. High: junk talks like the current task, Jev keeps it, the window
+ stays too big, the pressure pass squeezes harder and needles get lost.
+- **`target`** is how hard the compactor must squeeze. If Jev's verdicts leave the window above
+ `target` x `budget`, the keeps Jev was least sure about are trimmed, then the weakest trims are
+ dropped. A low target means big cuts and more lost needles.
+- **`trimTo`** is what a trimmed block keeps. For "gist" results (Grep, Bash, WebFetch) only about
+ the first 300 tokens matter, so a `trimTo` under 300 loses needle tokens.
+- **`mix`**, **`noise`** and **`focus`** shape the stream: which events arrive, how much is junk,
+ and how much of the real work is about the current task.
+
+## Your job
+
+Design the session, then tune it.
+
+1. **Write tasks with sharp vocabularies** for a made-up repo. Words should belong to one task
+ only. If two tasks share words, Jev keeps blocks from the wrong task. Try it on purpose once,
+ and say what happened.
+2. **Set the budget, target, trimTo, distraction and event mix.**
+3. **Find good settings**: needle recall stays above `recallTarget` while the reduction is large.
+ Read the numbers in `.harness/verdict.json` (the viewer writes it) or ask the person what the
+ pane shows. Report the numbers you saw, with the settings that gave them.
+4. **Find the edge.** Raise `distraction` until recall falls under the target. Say where it broke.
+
+Do NOT just ship the template. Each session should be its own repo story with a clear finding.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`.
+
+## What the person can do in the pane
+
+Task buttons, a budget slider, a distraction slider, "Compact now", "Flood +40", pause, step,
+reset, and click-to-inspect with a pin toggle. These are runtime overrides. Any edit you make to
+`session.json` resets them, so tell the person when you change the file.
+
+## Rules
+
+- Edit ONLY `session.json`. Keep it valid JSON. A bad edit does not crash the demo: the pane keeps
+ the last good session and shows the error.
+- Never edit `.harness/verdict.json`. The viewer writes it.
+- Never propose opening a browser, changing ports or running a second server. The pane is already
+ on the left.
+- Keep `title`, `description` and task titles truthful. The repo, the tool output and the token
+ counts are made up. Say so when you report.
+- The "summarize instead" lane is a simple baseline for contrast. Do not describe it as a
+ measurement of any real product.
+- Without `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that reads the same text live
+ Jev would get. The pane badges it `MOCK`. Its timings are not Jev's timings. Say which one ran.
+- You can call Jev yourself through `toolchain/jev.mjs` (`evaluate`, `jev.choice`, `jev.noul`,
+ `jev.score`) to try a question before you rely on it.
+
+## Definition of done
+
+- `session.json` parses and passes `toolchain/check.mjs`.
+- The tasks are your own, with sharp vocabularies, for a made-up repo.
+- You report one settings line that holds recall above the target with a large reduction, and one
+ that breaks it, with the measured numbers for both.
diff --git a/store/agents/jev-compactor/LICENSE b/store/agents/jev-compactor/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-compactor/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-compactor/README.md b/store/agents/jev-compactor/README.md
new file mode 100644
index 000000000..8a2af8c14
--- /dev/null
+++ b/store/agents/jev-compactor/README.md
@@ -0,0 +1,89 @@
+# Jev Compactor
+
+**A live demo of one idea: context compaction does not have to be a summarization prompt.**
+A made-up coding agent works in a made-up repo. Its context window fills with messages and tool
+results. When the window passes its budget, Jev (TypeSafe's System One model) judges **every tool
+result in one pass**: `keep`, `trim` or `drop`. The tower collapses, and the result is measured
+against a hidden ground truth.
+
+This is a demo on synthetic data. It is not a real compaction plugin, and it says nothing about
+any real product. The session, the repo, the tool output and the token counts are all generated.
+
+This is a harness for OpenHarness. The agent on the right edits `session.json`. The viewer on the
+left runs the session and asks Jev to compact it, live.
+
+## What you see
+
+- **The context tower.** One block per event, newest on top, coloured by kind (user, assistant,
+ Read, Grep, Bash, Edit, WebFetch). The height axis is curved so a small window is still easy to
+ see, but the budget line is exact. A thin strip beside the tower shows the ground truth: green
+ means "needed for the current task".
+- **Compaction.** A scan line sweeps the tower. Each block flashes its verdict and probability.
+ Dropped blocks dissolve, trimmed blocks shrink, the tower collapses and the big token counter
+ rolls down.
+- **The numbers.** Tokens now, budget, reduction, needle recall, compaction time, questions per
+ call, results judged and cost so far.
+- **The baseline lane.** A slim second tower runs "summarize instead": when over budget it folds
+ the oldest half of its window into one short summary block. It is a simple baseline for
+ contrast, scored with the same ground truth. It is not a measurement of any real product.
+
+## How Jev is asked
+
+- `state` = the current task (title and keywords) plus the last few messages.
+- One `choice` question per tool result, with the tool name, size and a short preview:
+ `keep` (still needed, keep it word for word), `trim` (only the gist matters, keep the head),
+ `drop` (irrelevant now). Each option has a description.
+- Questions are sent 100 per call, all calls at once. About 100 questions in one call is nearly
+ free, which is the point of the demo.
+- User and assistant messages are never judged and never touched.
+- If the window is still above `target` x `budget` after Jev's verdicts, a pressure pass trims the
+ keeps Jev was least sure about, then drops the weakest trims. Pinned blocks are never touched.
+
+## The honest dial
+
+`distraction` (0 to 1) is how much the junk output borrows the current task's words. At 0.12 the
+mock run keeps about 98% of needle tokens and cuts about 81% of the window. At 0.5 recall is about
+90%. At 0.9 junk looks like the task, Jev keeps much of it, the pressure pass has to squeeze
+harder, and recall falls to about 78% with a cut of about 70%. On the same session the "summarize
+instead" baseline keeps about 49%. No randomness is injected into the judge.
+`test/viewer.test.mjs` proves the gap.
+
+## Play with it
+
+- Task buttons change the current task. The next compaction keeps different blocks.
+- Click a block to inspect it: kind, size, preview, Jev's verdict with probability bars and the
+ true label. Pin it and it is never dropped.
+- Budget and distraction sliders, "Compact now", "Flood +40", pause, step and reset.
+- Pane changes are runtime overrides. Any edit to `session.json` puts the file back in charge.
+
+## Anatomy
+
+```
+jev-compactor/
+ harness.json # manifest (engine: claude)
+ AGENTS.md # instructions for the chat agent
+ skills/compactor/SKILL.md # the craft of designing a session
+ template/session.json # the starter session
+ toolchain/
+ jev.mjs # Jev client (real TypeSafe API, or a deterministic mock)
+ check.mjs # validates session.json
+ viewer.sh setup.sh doctor.sh init-workspace.sh
+ viewer/ # loopback viewer server and the pane
+ test/viewer.test.mjs
+```
+
+## Jev, honestly
+
+With `TYPESAFE_API_KEY` set, the viewer calls the real API (`POST /v1/systemone`). Without it, a
+deterministic local mock answers. The mock reads only what live Jev would get: the state text and
+the question text. It counts shared words and looks at the shape of the preview. It is a stand-in
+for the plumbing, not for Jev's judgement, and the pane badges it `MOCK`. Times shown on the mock
+are the mock's times, not Jev's. Cost is what live Jev would charge for the same input tokens
+($0.042 per million input tokens).
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API. It contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed. This wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for the OpenHarness store.
diff --git a/store/agents/jev-compactor/THIRD_PARTY_NOTICES.md b/store/agents/jev-compactor/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-compactor/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-compactor/harness.json b/store/agents/jev-compactor/harness.json
new file mode 100644
index 000000000..26e1cd7db
--- /dev/null
+++ b/store/agents/jev-compactor/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-compactor",
+ "name": "Jev Compactor",
+ "category": "Dev Tools",
+ "author": "Autonomous",
+ "description": "A live demo of instant context compaction on a made-up coding-agent session. When the window passes its budget, Jev judges every tool result in one pass: keep, trim or drop. Recall is measured against hidden ground truth. Raise distraction and Jev keeps junk and loses needles.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "session.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-compactor/skills/compactor/SKILL.md b/store/agents/jev-compactor/skills/compactor/SKILL.md
new file mode 100644
index 000000000..67cdd0c68
--- /dev/null
+++ b/store/agents/jev-compactor/skills/compactor/SKILL.md
@@ -0,0 +1,92 @@
+---
+name: jev-compactor
+description: Design and tune a Jev Compactor session. Use when editing session.json, writing task vocabularies, or looking for settings where needle recall holds while the reduction is large.
+---
+
+# Craft: Jev Compactor
+
+Jev Compactor runs a made-up coding-agent session and lets Jev compact its context window. Your
+craft is the session design: tasks Jev can tell apart, and settings with a clear, honest finding.
+Everything is synthetic. It is a demo of the idea, not a real compaction plugin.
+
+## The decision
+
+When the window passes `budget`, the viewer sends Jev:
+
+- `state`: the current task (title and keywords) and the last few messages.
+- one `choice` question per tool result, 100 per call:
+
+```
+[Read] src/refund/ledger_cents.ts · 4,210 tokens. Preview: «export function apply_refund(...) { ... }»
+Is this tool result still needed for the current task?
+ keep still needed, keep it word for word
+ trim only the gist matters now, keep the head
+ drop irrelevant now
+```
+
+Questions cannot see each other. Jev judges each block from its own text and the shared state.
+Messages are never judged.
+
+## Ground truth
+
+Every tool result secretly belongs to one task, or is junk. For the current task:
+
+- Read and Edit results are **detail** needles. Every token counts. Ideal verdict: keep.
+- Grep, Bash and WebFetch results are **gist** needles. About the first 300 tokens count. Ideal
+ verdict: trim.
+- Everything else (other tasks, junk) is not needed. Ideal verdict: drop.
+
+**Needle recall** = needed tokens that survived / needed tokens before. **Junk removed** = the same
+for tokens that were not needed. About 4% of real results have a preview that only shows
+boilerplate, so even an easy session is not perfect. That is a real limit, not noise.
+
+## The knobs
+
+| knob | what it does | try |
+|---|---|---|
+| `tasks[].vocabulary` | the words Jev can tell tasks apart by | 8 to 12 single words, no word in two tasks |
+| `distraction` | how much junk borrows the current task's words | 0.1 easy, 0.5 hard, 0.9 very hard |
+| `target` | the window must end under target x budget | 0.4 default, 0.3 squeezes hard, 0.6 is gentle |
+| `trimTo` | tokens a trimmed block keeps | 400 default, under 300 starts to lose gist needles |
+| `budget` | when compaction fires | 200000 default, 1000000 for a long session |
+| `noise`, `focus`, `mix` | how much junk, how much on-task work, which events | more junk means bigger cuts |
+| `taskEvery` | events before the made-up user moves on | 0 keeps one task forever, which fills the window with needles |
+
+## What to expect (mock, default tasks, 1500 events)
+
+| distraction | needle recall | junk removed | reduction |
+|---|---|---|---|
+| 0.12 | about 98% | about 97% | about 81% |
+| 0.3 | about 96% | about 86% | about 72% |
+| 0.5 | about 90% | about 82% | about 70% |
+| 0.9 | about 78% | about 78% | about 70% |
+
+The "summarize instead" baseline keeps about 49% of needle tokens on the same session.
+
+Why recall falls: junk that talks like the task gets kept. The window stays above the target, so
+the pressure pass trims the keeps Jev was least sure about. Some of those are real needles.
+
+## A good tuning loop
+
+1. Write the tasks. Run `node "$JEV_DSH/toolchain/check.mjs"`.
+2. Start easy (`distraction` 0.1). Let a few compactions run. Read `.harness/verdict.json`:
+ the summary has recall and reduction, the findings have cost, calls and the baseline.
+3. Raise `distraction` in steps of 0.2. Note where recall crosses `recallTarget`.
+4. At that edge, try one fix at a time: a higher `target`, a bigger `budget`, a bigger `trimTo`,
+ sharper vocabularies. Say which one helped and what it cost in reduction.
+5. Try one bad idea on purpose: give two tasks the same words. Watch Jev keep the wrong task's
+ blocks. Report it.
+
+## Reporting
+
+Give the settings and the measured numbers together, for example:
+"distraction 0.3, target 0.4, trimTo 400: recall 96%, reduction 76% over 12 compactions, mock."
+Always say it is a synthetic session, and whether the mock or live Jev ran. Never describe the
+"summarize instead" lane as a real product. It is a simple baseline for contrast.
+
+## Definition of done
+
+- `session.json` passes `check.mjs`.
+- Your own tasks and repo name, not the template's.
+- One settings line that holds the recall target with a large reduction, and one that breaks it,
+ both with numbers.
diff --git a/store/agents/jev-compactor/store.json b/store/agents/jev-compactor/store.json
new file mode 100644
index 000000000..98dc8a7c5
--- /dev/null
+++ b/store/agents/jev-compactor/store.json
@@ -0,0 +1,13 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Watch Jev compact a made-up agent session in one pass, measured honestly",
+ "examples": [
+ {
+ "prompt": "Design a session for a made-up repo: five tasks with sharp, separate vocabularies, a 300,000 token budget and trimTo 300. Then find the highest distraction where needle recall still stays above 90% while the reduction stays above 70%. Report the numbers you saw.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-compactor/context-tower.jpg",
+ "caption": "A synthetic agent session where Jev judges every tool result at once and the context tower collapses"
+ }
+ ]
+}
diff --git a/store/agents/jev-compactor/template/session.json b/store/agents/jev-compactor/template/session.json
new file mode 100644
index 000000000..df3ce812d
--- /dev/null
+++ b/store/agents/jev-compactor/template/session.json
@@ -0,0 +1,24 @@
+{
+ "title": "Jev Compactor",
+ "description": "A made-up coding-agent session in a made-up repo. Jev judges every tool result and compacts the context in one pass.",
+ "repo": "harbor-pay",
+ "seed": 7,
+ "budget": 200000,
+ "target": 0.4,
+ "trimTo": 400,
+ "distraction": 0.12,
+ "recallTarget": 0.9,
+ "eventsPerSec": 4,
+ "noise": 0.45,
+ "focus": 0.5,
+ "taskEvery": 200,
+ "summaryTokens": 1500,
+ "mix": { "user": 1, "assistant": 2, "Read": 7, "Grep": 3, "Bash": 6, "Edit": 3, "WebFetch": 2 },
+ "currentTask": "refunds",
+ "tasks": [
+ { "id": "refunds", "title": "Fix refund rounding in the ledger", "vocabulary": ["refund", "ledger", "rounding", "cents", "reversal", "chargeback", "currency", "decimal", "balance", "payout"] },
+ { "id": "webhooks", "title": "Retry failed webhook deliveries", "vocabulary": ["webhook", "delivery", "retry", "backoff", "signature", "endpoint", "queue", "deadletter", "idempotency", "timeout"] },
+ { "id": "sessions", "title": "Rotate login sessions safely", "vocabulary": ["session", "rotate", "expiry", "cookie", "login", "oauth", "scope", "revoke", "credential", "passkey"] },
+ { "id": "search", "title": "Speed up invoice search", "vocabulary": ["invoice", "search", "index", "query", "pagination", "filter", "cursor", "latency", "cache", "ranking"] }
+ ]
+}
diff --git a/store/agents/jev-compactor/test/viewer.test.mjs b/store/agents/jev-compactor/test/viewer.test.mjs
new file mode 100644
index 000000000..6d55824f1
--- /dev/null
+++ b/store/agents/jev-compactor/test/viewer.test.mjs
@@ -0,0 +1,346 @@
+// Viewer integration tests for Jev Compactor. Each test starts the real viewer on a temp workspace
+// and drives time with the `tick` control, never with sleeps (except where a file watcher must fire).
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync, cpSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { connect } from 'node:net'
+import { spawnSync } from 'node:child_process'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const ROOT = join(HERE, '..')
+const { startCompactorViewer, compactorMock, normalize, DEFAULT } = await import(join(ROOT, 'viewer/viewer.mjs'))
+const { canon, jev } = await import(join(ROOT, 'toolchain/jev.mjs'))
+
+const wait = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function fresh(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-compactor-test-'))
+ const template = JSON.parse(readFileSync(join(ROOT, 'template/session.json'), 'utf8'))
+ writeFileSync(join(ws, 'session.json'), JSON.stringify({ ...template, ...overrides }))
+ const viewer = await startCompactorViewer({ workspace: ws, port: 0 })
+ const ctl = async (cmd, extra = {}) => {
+ const res = await fetch(`${viewer.url}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd, ...extra }) })
+ return { status: res.status, body: await res.json() }
+ }
+ const state = async () => (await fetch(`${viewer.url}/state`)).json()
+ await ctl('pause')
+ return { ws, viewer, ctl, state }
+}
+
+async function untilCompaction(v, n = 1, max = 4000) {
+ for (let i = 0; i < max; i += 20) {
+ await v.ctl('tick', { n: 20 })
+ const s = await v.state()
+ if (s.totals.compactions >= n) return s
+ }
+ throw new Error('no compaction happened')
+}
+
+test('the session advances and Jev judges every tool result when the budget is hit', async () => {
+ const v = await fresh()
+ try {
+ const s0 = await v.state()
+ assert.ok(s0.tokens > 0 && s0.blocks.length > 5, 'the window starts partly full')
+ await v.ctl('tick', { n: 5 })
+ const s1 = await v.state()
+ assert.ok(s1.n >= s0.n + 5, 'five ticks add five events')
+ // count tool results right before the first compaction fires
+ let toolsBefore = 0, s = s1
+ while (s.totals.compactions === 0) {
+ toolsBefore = s.blocks.filter((b) => b[5] !== 3).length
+ await v.ctl('tick')
+ s = await v.state()
+ assert.ok(s.n < 3000, 'a compaction must fire')
+ }
+ const last = s.last
+ assert.ok(last.before > s.cfg.budget, 'it fired because the window passed the budget')
+ assert.ok(last.after < last.before * 0.7, `a real reduction (${last.before} -> ${last.after})`)
+ assert.ok(last.questions >= toolsBefore, `one question per tool result (${last.questions} vs ${toolsBefore})`)
+ assert.equal(last.keep + last.trim + last.drop, last.questions)
+ assert.equal(last.calls, Math.max(1, Math.ceil(last.questions / 100)), 'as few calls as possible, 100 questions per call')
+ assert.ok(last.ms >= 0 && last.costUsd > 0)
+ assert.ok(last.recall > 0.85, `easy setting keeps the needles (recall ${last.recall})`)
+ assert.ok(s.tokens <= s.cfg.budget * s.cfg.target + 1, `the window ends under target x budget (${s.tokens})`)
+ assert.equal(s.history.length, 1)
+ // every verdict has a real probability distribution, never one-hot
+ for (const [, vd] of Object.entries(last.verdicts)) {
+ const sum = vd[1] + vd[2] + vd[3]
+ assert.ok(Math.abs(sum - 1) < 0.01, 'probabilities sum to 1')
+ assert.ok(Math.max(vd[1], vd[2], vd[3]) < 0.999, 'never exactly one-hot')
+ }
+ } finally { await v.viewer.close() }
+})
+
+test('a non-default config really shows up in /state', async () => {
+ const tasks = [
+ { id: 'alpha', title: 'Tune the alpha pipeline', vocabulary: ['alpha', 'pipeline', 'stage', 'buffer', 'flush', 'batch', 'cursor'] },
+ { id: 'beta', title: 'Fix the beta parser', vocabulary: ['beta', 'parser', 'grammar', 'lexer', 'symbol', 'bracket', 'escape'] },
+ ]
+ const v = await fresh({ title: 'My Session', repo: 'test-repo', budget: 123456, trimTo: 250, distraction: 0.33, target: 0.55, eventsPerSec: 9, tasks, currentTask: 'beta' })
+ try {
+ const s = await v.state()
+ assert.equal(s.title, 'My Session')
+ assert.equal(s.repo, 'test-repo')
+ assert.equal(s.cfg.budget, 123456)
+ assert.equal(s.cfg.trimTo, 250)
+ assert.equal(s.cfg.distraction, 0.33)
+ assert.equal(s.cfg.target, 0.55)
+ assert.equal(s.cfg.eventsPerSec, 9)
+ assert.deepEqual(s.tasks.map((t) => t.id), ['alpha', 'beta'])
+ assert.equal(s.currentTask, 'beta')
+ assert.equal(s.cfgError, null)
+ assert.notEqual(s.cfg.budget, DEFAULT.budget)
+ } finally { await v.viewer.close() }
+})
+
+test('the verdict file is written with spec 1, a summary, findings and phases', async () => {
+ const v = await fresh()
+ try {
+ const file = join(v.ws, '.harness/verdict.json')
+ assert.ok(existsSync(file), 'written at start')
+ const v0 = JSON.parse(readFileSync(file, 'utf8'))
+ assert.equal(v0.spec, 1)
+ assert.equal(v0.ready, false)
+ await untilCompaction(v)
+ const v1 = JSON.parse(readFileSync(file, 'utf8'))
+ assert.equal(v1.spec, 1)
+ assert.equal(v1.ready, true)
+ assert.ok(typeof v1.summary === 'string' && v1.summary.includes('recall'))
+ assert.ok(Array.isArray(v1.findings) && v1.findings.length >= 2)
+ assert.ok(v1.findings.some((f) => f.kind === 'baseline' && /not a real product/.test(f.message)), 'the baseline is labelled honestly')
+ assert.ok(Array.isArray(v1.phases) && v1.phases.length === 3)
+ assert.equal(v1.artifact, 'session.json')
+ } finally { await v.viewer.close() }
+})
+
+test('every control command answers 200', async () => {
+ const v = await fresh()
+ try {
+ const s = await v.state()
+ const tool = s.blocks.find((b) => b[5] !== 3)
+ for (const [cmd, extra] of [
+ ['pause', {}], ['tick', {}], ['tick', { n: 10 }], ['start', {}], ['pause', {}], ['flood', { n: 10 }], ['compact', {}],
+ ['setTask', { task: 'search' }], ['setBudget', { value: 150000 }], ['setDistraction', { value: 0.4 }],
+ ['pin', { id: tool[0], pinned: true }], ['inspect', { id: tool[0] }], ['reset', {}], ['unknown-command', {}],
+ ]) {
+ const r = await v.ctl(cmd, extra)
+ assert.equal(r.status, 200, cmd)
+ assert.equal(r.body.ok, true, cmd)
+ }
+ const bad = await fetch(`${v.viewer.url}/control`, { method: 'POST', body: '{not json' })
+ assert.equal(bad.status, 400)
+ } finally { await v.viewer.close() }
+})
+
+test('a bad JSON edit keeps the demo alive and reports the error, a good edit clears it', async () => {
+ const v = await fresh({ budget: 111000 })
+ try {
+ writeFileSync(join(v.ws, 'session.json'), '{ "budget": 99999, oops')
+ let s = null
+ for (let i = 0; i < 60; i++) { await wait(50); s = await v.state(); if (s.cfgError) break }
+ assert.ok(s.cfgError, 'the parse error is reported')
+ assert.match(s.cfgError, /session\.json/)
+ assert.equal(s.cfg.budget, 111000, 'the last good config stays')
+ const n = s.n
+ await v.ctl('tick', { n: 30 })
+ s = await v.state()
+ assert.equal(s.n, n + 30, 'the session still advances')
+ const verdict = JSON.parse(readFileSync(join(v.ws, '.harness/verdict.json'), 'utf8'))
+ assert.ok(verdict.findings.some((f) => f.severity === 'error' && f.kind === 'config'))
+
+ const template = JSON.parse(readFileSync(join(ROOT, 'template/session.json'), 'utf8'))
+ writeFileSync(join(v.ws, 'session.json'), JSON.stringify({ ...template, budget: 99999 }))
+ for (let i = 0; i < 60; i++) { await wait(50); s = await v.state(); if (!s.cfgError && s.cfg.budget === 99999) break }
+ assert.equal(s.cfgError, null)
+ assert.equal(s.cfg.budget, 99999)
+ } finally { await v.viewer.close() }
+})
+
+test('out-of-range values are clamped and reported, never crash', async () => {
+ const v = await fresh({ budget: 5, distraction: 7, trimTo: 'lots', tasks: [{ id: 'only-one', vocabulary: ['a'] }] })
+ try {
+ const s = await v.state()
+ assert.equal(s.cfg.budget, 20000)
+ assert.equal(s.cfg.distraction, 1)
+ assert.equal(s.cfg.trimTo, DEFAULT.trimTo)
+ assert.equal(s.tasks.length, DEFAULT.tasks.length, 'falls back to the built-in tasks')
+ assert.match(s.cfgError, /budget/)
+ await v.ctl('tick', { n: 50 })
+ assert.ok((await v.state()).n > s.n)
+ } finally { await v.viewer.close() }
+})
+
+test('a non-loopback Host header gets 403', async () => {
+ const v = await fresh()
+ try {
+ const port = Number(new URL(v.viewer.url).port)
+ const ask = (host) => new Promise((resolveP, reject) => {
+ const sock = connect(port, '127.0.0.1', () => sock.write(`GET /state HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`))
+ let data = ''
+ sock.on('data', (c) => (data += c))
+ sock.on('end', () => resolveP(data))
+ sock.on('error', reject)
+ })
+ assert.match(await ask('evil.example.com'), /^HTTP\/1\.1 403/)
+ assert.match(await ask(`127.0.0.1:${port}`), /^HTTP\/1\.1 200/)
+ } finally { await v.viewer.close() }
+})
+
+test('the difficulty dial: low distraction beats high distraction by a clear margin', async () => {
+ const run = async (distraction) => {
+ const v = await fresh({ distraction, seed: 11 })
+ try { await v.ctl('tick', { n: 1500 }); return (await v.state()).totals } finally { await v.viewer.close() }
+ }
+ const easy = await run(0.05)
+ const hard = await run(0.9)
+ console.log(` easy d=0.05: recall ${(easy.avgRecall * 100).toFixed(1)}% junk removed ${(easy.avgJunkRemoved * 100).toFixed(1)}% reduction ${(easy.avgReduction * 100).toFixed(1)}% over ${easy.compactions} compactions`)
+ console.log(` hard d=0.90: recall ${(hard.avgRecall * 100).toFixed(1)}% junk removed ${(hard.avgJunkRemoved * 100).toFixed(1)}% reduction ${(hard.avgReduction * 100).toFixed(1)}% over ${hard.compactions} compactions`)
+ assert.ok(easy.compactions >= 10 && hard.compactions >= 10)
+ assert.ok(easy.avgRecall > 0.95, `easy recall is near 100% (${easy.avgRecall})`)
+ assert.ok(easy.avgReduction > 0.7, `easy reduction is large (${easy.avgReduction})`)
+ assert.ok(easy.avgRecall - hard.avgRecall > 0.06, `hard loses needles (${easy.avgRecall} vs ${hard.avgRecall})`)
+ assert.ok(easy.avgJunkRemoved - hard.avgJunkRemoved > 0.1, `hard keeps junk (${easy.avgJunkRemoved} vs ${hard.avgJunkRemoved})`)
+ assert.ok(easy.avgReduction - hard.avgReduction > 0.06, `hard cuts less (${easy.avgReduction} vs ${hard.avgReduction})`)
+ assert.ok(hard.demoted > easy.demoted * 3, 'the pressure pass works much harder when junk looks like the task')
+})
+
+test('the same seed gives the same session', async () => {
+ const run = async () => {
+ const v = await fresh({ seed: 42 })
+ try { await v.ctl('tick', { n: 300 }); const s = await v.state(); return [s.tokens, s.blocks.length, s.totals.compactions, s.baseline.tokens] } finally { await v.viewer.close() }
+ }
+ const a = await run()
+ const b = await run()
+ // the timer may add one event before the pause lands, so allow the two runs to be one step apart
+ assert.ok(Math.abs(a[1] - b[1]) <= 3 && a[2] === b[2], `${a} vs ${b}`)
+})
+
+test('pinned blocks are never dropped or trimmed', async () => {
+ const v = await fresh({ distraction: 0 })
+ try {
+ const s = await v.state()
+ const junk = s.blocks.filter((b) => b[5] === 0 && b[4] === -1 && b[2] > 1500).slice(0, 3)
+ assert.ok(junk.length >= 1, 'there is junk to pin')
+ for (const b of junk) assert.equal((await v.ctl('pin', { id: b[0], pinned: true })).body.pinned, true)
+ const after = (await v.ctl('compact')) && (await v.state())
+ for (const b of junk) {
+ const still = after.blocks.find((x) => x[0] === b[0])
+ assert.ok(still, `pinned junk block ${b[0]} survived`)
+ assert.equal(still[2], b[2], 'at full size')
+ assert.equal(still[6], 1)
+ }
+ const info = (await v.ctl('inspect', { id: junk[0][0] })).body.block
+ assert.equal(info.pinned, true)
+ assert.equal(info.verdict, 'keep')
+ assert.ok(['drop', 'trim'].includes(info.jev), `Jev itself wanted it gone (${info.jev})`)
+ // messages are never touched
+ const msgsBefore = s.blocks.filter((b) => b[5] === 3).map((b) => b[0])
+ const idsAfter = new Set(after.blocks.map((b) => b[0]))
+ for (const id of msgsBefore) assert.ok(idsAfter.has(id), `message ${id} is still there`)
+ } finally { await v.viewer.close() }
+})
+
+test('switching the task changes what the next compaction keeps', async () => {
+ const v = await fresh({ taskEvery: 0 })
+ try {
+ await v.ctl('tick', { n: 30 })
+ await v.ctl('compact')
+ let s = await v.state()
+ const idx = (id) => s.tasks.findIndex((t) => t.id === id)
+ const keptFor = (state, task) => state.blocks.filter((b) => b[5] !== 3 && b[7] === 1 && b[4] === idx(task)).length
+ assert.ok(keptFor(s, 'refunds') >= 3, 'refunds blocks are kept while refunds is current')
+ assert.equal((await v.ctl('setTask', { task: 'webhooks' })).status, 200)
+ await v.ctl('tick', { n: 30 })
+ await v.ctl('compact')
+ s = await v.state()
+ assert.equal(s.currentTask, 'webhooks')
+ assert.equal(s.overrides.task, true)
+ assert.ok(keptFor(s, 'webhooks') >= 2, 'now webhooks blocks are kept')
+ assert.ok(keptFor(s, 'refunds') <= 1, `old refunds blocks are gone (${keptFor(s, 'refunds')} left)`)
+ assert.equal(s.last.task, 'webhooks')
+ } finally { await v.viewer.close() }
+})
+
+test('pane changes are runtime overrides, and an edit to session.json resets them', async () => {
+ const v = await fresh({ budget: 200000, distraction: 0.12 })
+ try {
+ await v.ctl('setBudget', { value: 90000 })
+ await v.ctl('setDistraction', { value: 0.77 })
+ let s = await v.state()
+ assert.equal(s.cfg.budget, 90000)
+ assert.equal(s.cfg.distraction, 0.77)
+ assert.deepEqual([s.overrides.budget, s.overrides.distraction], [true, true])
+ const template = JSON.parse(readFileSync(join(ROOT, 'template/session.json'), 'utf8'))
+ writeFileSync(join(v.ws, 'session.json'), JSON.stringify({ ...template, budget: 250000, distraction: 0.2 }))
+ for (let i = 0; i < 60; i++) { await wait(50); s = await v.state(); if (s.cfg.budget === 250000) break }
+ assert.equal(s.cfg.budget, 250000)
+ assert.equal(s.cfg.distraction, 0.2)
+ assert.deepEqual([s.overrides.budget, s.overrides.distraction], [false, false])
+ } finally { await v.viewer.close() }
+})
+
+test('a big window is judged in chunks of at most 100 questions', async () => {
+ const v = await fresh({ budget: 700000 })
+ try {
+ const s = await untilCompaction(v)
+ assert.ok(s.last.questions > 100, `more than one call is needed (${s.last.questions} questions)`)
+ assert.equal(s.last.calls, Math.ceil(s.last.questions / 100))
+ assert.ok(s.last.perCall <= 100)
+ } finally { await v.viewer.close() }
+})
+
+test('the "summarize instead" lane is tracked with the same ground truth and loses more needles', async () => {
+ const v = await fresh({ seed: 5 })
+ try {
+ await v.ctl('tick', { n: 1200 })
+ const s = await v.state()
+ assert.ok(s.baseline.compactions >= 5)
+ assert.ok(s.baseline.blocks.some((b) => b[1] === 7), 'it holds a summary block')
+ assert.ok(s.baseline.avgRecall < 0.75, `folding the oldest half loses needles (${s.baseline.avgRecall})`)
+ assert.ok(s.totals.avgRecall - s.baseline.avgRecall > 0.2, `Jev lane ${s.totals.avgRecall} vs baseline ${s.baseline.avgRecall}`)
+ assert.ok(s.baseline.tokens <= s.cfg.budget, 'the baseline stays under budget')
+ } finally { await v.viewer.close() }
+})
+
+test('the mock reads only the state text and the question text', () => {
+ const state = ['CURRENT TASK: Fix refund rounding in the ledger', 'TASK KEYWORDS: refund, ledger, rounding, cents, reversal', 'RECENT MESSAGES:', 'user: look at the refund ledger'].join('\n')
+ const ask = (text) => compactorMock(state, 'b1', canon(jev.choice({ keep: 'k', trim: 't', drop: 'd' }, text)))
+ const code = ask('[Read] src/refund/ledger_cents.ts · 4,210 tokens. Preview: «export function apply_refund(ledger, cents) { const rounding = ledger.reversal(cents); return rounding }» Is this still needed?')
+ const log = ask('[Bash] npm test -- refund · 9,000 tokens. Preview: «PASS test/refund/ledger.test.ts ✓ rounding cents ✓ reversal handles refund · Tests: 12 passed · output 900 lines» Is this still needed?')
+ const junk = ask('[Bash] npm install · 22,000 tokens. Preview: «npm WARN deprecated [email protected] · added 1,423 packages in 41s · postinstall lodash chalk ok» Is this still needed?')
+ assert.equal(code.choice, 'keep')
+ assert.equal(log.choice, 'trim')
+ assert.equal(junk.choice, 'drop')
+ for (const a of [code, log, junk]) {
+ const p = Object.values(a.probabilities)
+ assert.ok(Math.abs(p.reduce((x, y) => x + y, 0) - 1) < 1e-9)
+ assert.ok(Math.max(...p) < 0.99 && Math.min(...p) > 0.005, 'a real distribution, never one-hot')
+ assert.equal(a.confidence, Math.max(...p))
+ }
+ assert.equal(compactorMock(state, 'x', canon(jev.noul('anything'))), null, 'other questions fall through to the generic mock')
+ assert.equal(normalize({ budget: 1e9 }).cfg.budget, 2000000)
+})
+
+test('check.mjs accepts the template and rejects an out-of-range value', () => {
+ const check = join(ROOT, 'toolchain/check.mjs')
+ const ok = spawnSync(process.execPath, [check, join(ROOT, 'template/session.json')], { encoding: 'utf8' })
+ assert.equal(ok.status, 0, ok.stdout)
+ assert.match(ok.stdout, /ok\s+session\.json is valid/)
+ const ws = mkdtempSync(join(tmpdir(), 'jev-compactor-check-'))
+ cpSync(join(ROOT, 'template/session.json'), join(ws, 'session.json'))
+ const p = JSON.parse(readFileSync(join(ws, 'session.json'), 'utf8'))
+ for (const [patch, pattern] of [
+ [{ budget: 5000 }, /budget/], [{ distraction: 1.5 }, /distraction/], [{ trimTo: 10 }, /trimTo/], [{ eventsPerSec: 200 }, /eventsPerSec/],
+ [{ tasks: [p.tasks[0]] }, /2 to 12/], [{ tasks: [p.tasks[0], { id: 'thin', title: 'Thin', vocabulary: ['one', 'two'] }] }, /at least 6/],
+ [{ currentTask: 'nope' }, /currentTask/],
+ ]) {
+ writeFileSync(join(ws, 'session.json'), JSON.stringify({ ...p, ...patch }))
+ const bad = spawnSync(process.execPath, [check], { encoding: 'utf8', env: { ...process.env, HARNESS_WORKSPACE: ws } })
+ assert.equal(bad.status, 1, JSON.stringify(patch))
+ assert.match(bad.stdout, pattern)
+ assert.match(bad.stdout, /fail\s+invalid session\.json/)
+ }
+})
diff --git a/store/agents/jev-compactor/toolchain/README.md b/store/agents/jev-compactor/toolchain/README.md
new file mode 100644
index 000000000..e92012621
--- /dev/null
+++ b/store/agents/jev-compactor/toolchain/README.md
@@ -0,0 +1,44 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
+
+## Going live
+
+Without a key everything runs on the offline stand-in and the pane says `MOCK`. For the real model,
+give the harness a key. The viewer is started by the Harness daemon, which does not see variables
+you export in a shell, so the reliable place is a small file in your home folder:
+
+```sh
+mkdir -p ~/.config/typesafe && chmod 700 ~/.config/typesafe
+printf 'TYPESAFE_API_KEY=%s\n' 'paste-your-key-here' > ~/.config/typesafe/credentials
+chmod 600 ~/.config/typesafe/credentials
+```
+
+Two routes work, and both speak the same question format:
+
+| route | what goes in the file | where to get it |
+|---|---|---|
+| TypeSafe direct | `TYPESAFE_API_KEY=...` | https://console.typesafe.ai/keys (there may be a waitlist) |
+| Cloudflare Workers AI | `CLOUDFLARE_ACCOUNT_ID=...` and `CLOUDFLARE_API_TOKEN=...` | a Cloudflare API token with Workers AI permission, no TypeSafe waitlist |
+
+Environment variables of the same names win over the file. Restart the harness after changing the
+file. `toolchain/doctor.sh` prints which route is active and never prints the key. One file serves
+every Jev harness on the machine. Never paste a key into the chat, and never save one in the
+workspace. Under `node --test`, or with `JEV_OFFLINE=1`, a key is ignored so tests stay deterministic.
diff --git a/store/agents/jev-compactor/toolchain/check.mjs b/store/agents/jev-compactor/toolchain/check.mjs
new file mode 100644
index 000000000..d5ad30b8c
--- /dev/null
+++ b/store/agents/jev-compactor/toolchain/check.mjs
@@ -0,0 +1,89 @@
+#!/usr/bin/env node
+// check.mjs — validate a session.json for the Jev Compactor harness.
+// Usage: node check.mjs [path/to/session.json] (default: $HARNESS_WORKSPACE/session.json, else ./session.json)
+// Prints one line per problem. Exit code 1 when there is an error, 0 otherwise (warnings pass).
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const file = process.argv[2] || join(process.env.HARNESS_WORKSPACE || '.', 'session.json')
+
+let errors = 0, warnings = 0
+const error = (msg) => { errors++; console.log(`error ${msg}`) }
+const warn = (msg) => { warnings++; console.log(`warn ${msg}`) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(file, 'utf8'))
+} catch (e) {
+ console.log(`error cannot read ${file}: ${e.message}`)
+ console.log('fail invalid session.json')
+ process.exit(1)
+}
+if (!p || typeof p !== 'object' || Array.isArray(p)) { console.log('error session.json must be one JSON object'); console.log('fail invalid session.json'); process.exit(1) }
+
+const range = (key, lo, hi, { required = false, integer = false } = {}) => {
+ const v = p[key]
+ if (v === undefined) { if (required) error(`${key} is required (${lo}..${hi})`); return }
+ if (typeof v !== 'number' || !Number.isFinite(v)) return error(`${key} must be a number (${lo}..${hi})`)
+ if (v < lo || v > hi) return error(`${key} is ${v}, it must be ${lo}..${hi}`)
+ if (integer && !Number.isInteger(v)) warn(`${key} should be a whole number`)
+}
+
+if (!p.title || typeof p.title !== 'string') warn('no title')
+if (p.repo !== undefined && (typeof p.repo !== 'string' || !p.repo)) error('repo must be a made-up repo name (text)')
+
+range('budget', 20000, 2000000, { required: true, integer: true })
+range('trimTo', 50, 5000, { required: true, integer: true })
+range('distraction', 0, 1, { required: true })
+range('eventsPerSec', 1, 60, { required: true })
+range('target', 0.2, 0.9)
+range('recallTarget', 0.5, 1)
+range('noise', 0, 0.9)
+range('focus', 0.1, 1)
+range('summaryTokens', 200, 20000, { integer: true })
+range('taskEvery', 0, 5000, { integer: true })
+range('seed', 0, 2147483647, { integer: true })
+
+// tasks: 2 to 12, each with an id, a title and at least 6 vocabulary words
+const ids = new Set()
+if (!Array.isArray(p.tasks)) error('tasks must be a list of 2 to 12 tasks')
+else {
+ if (p.tasks.length < 2 || p.tasks.length > 12) error(`tasks has ${p.tasks.length} entries, it must have 2 to 12`)
+ const owner = new Map()
+ p.tasks.forEach((t, i) => {
+ const where = `tasks[${i}]`
+ if (!t || typeof t !== 'object') return error(`${where} must be an object { id, title, vocabulary }`)
+ if (typeof t.id !== 'string' || !t.id.trim()) error(`${where}.id is required`)
+ else if (ids.has(t.id)) error(`${where}.id "${t.id}" is used twice`)
+ else ids.add(t.id)
+ if (typeof t.title !== 'string' || !t.title.trim()) error(`${where}.title is required`)
+ if (!Array.isArray(t.vocabulary)) return error(`${where}.vocabulary must be a list of at least 6 words`)
+ const words = [...new Set(t.vocabulary.filter((w) => typeof w === 'string').map((w) => w.toLowerCase().replace(/[^a-z0-9]+/g, '')).filter((w) => w.length > 1))]
+ if (words.length < 6) error(`${where}.vocabulary has ${words.length} usable words, it needs at least 6`)
+ if (t.vocabulary.some((w) => typeof w !== 'string' || /\s/.test(w.trim()))) warn(`${where}.vocabulary should be single words`)
+ for (const w of words) {
+ if (owner.has(w) && owner.get(w) !== t.id) warn(`the word "${w}" is in both "${owner.get(w)}" and "${t.id}". Shared words make Jev keep the wrong task's blocks`)
+ else owner.set(w, t.id)
+ }
+ })
+}
+if (p.currentTask !== undefined && !ids.has(p.currentTask)) error(`currentTask "${p.currentTask}" is not one of the task ids`)
+
+// event mix
+const MIX = ['user', 'assistant', 'Read', 'Grep', 'Bash', 'Edit', 'WebFetch']
+if (p.mix !== undefined) {
+ if (!p.mix || typeof p.mix !== 'object' || Array.isArray(p.mix)) error('mix must be an object of weights')
+ else {
+ for (const [k, v] of Object.entries(p.mix)) {
+ if (!MIX.includes(k)) warn(`mix.${k} is not a known event kind (${MIX.join(', ')})`)
+ else if (typeof v !== 'number' || !Number.isFinite(v) || v < 0 || v > 1000) error(`mix.${k} must be a number 0..1000`)
+ }
+ if (!['Read', 'Grep', 'Bash', 'Edit', 'WebFetch'].some((k) => (p.mix[k] ?? 1) > 0)) error('mix needs at least one tool with a weight above 0')
+ }
+}
+
+if (typeof p.trimTo === 'number' && p.trimTo < 300) warn('trimTo is under 300, so trimmed "gist" results lose needle tokens')
+if (typeof p.target === 'number' && typeof p.budget === 'number' && p.target * p.budget < 8000) warn('target x budget is very small, the pressure pass will cut needles')
+
+console.log(errors ? `fail invalid session.json (${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'})` : `ok session.json is valid${warnings ? ` (${warnings} warning${warnings === 1 ? '' : 's'})` : ''}`)
+process.exit(errors ? 1 : 0)
diff --git a/store/agents/jev-compactor/toolchain/doctor.sh b/store/agents/jev-compactor/toolchain/doctor.sh
new file mode 100755
index 000000000..a9cf461a3
--- /dev/null
+++ b/store/agents/jev-compactor/toolchain/doctor.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Compactor viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+cd "$(dirname "$0")/.."
+node -e "import('./toolchain/jev.mjs').then((m) => console.log('ok Jev: ' + m.describeCredentials())).catch((e) => console.log('warn Jev client did not load: ' + e.message))"
+echo "done"
diff --git a/store/agents/jev-compactor/toolchain/init-workspace.sh b/store/agents/jev-compactor/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-compactor/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-compactor/toolchain/jev.mjs b/store/agents/jev-compactor/toolchain/jev.mjs
new file mode 100644
index 000000000..190c7e9ac
--- /dev/null
+++ b/store/agents/jev-compactor/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
+// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
+// score a position on a 2..10 level scale — a float plus per-level probabilities
+//
+// Questions are authored as options[] / legend{} (or an option -> description map) and translated
+// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The generic mock reads
+// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
+// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
+// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ return key ? 'typesafe' : 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ return (h >>> 0) / 4294967296
+}
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+
+/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
+export function stems(text) {
+ const out = []
+ for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
+ if (w.length < 2 || STOP.has(w)) continue
+ out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
+ }
+ return out
+}
+
+/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
+function evidence(stateStems, needle) {
+ const want = [...new Set(stems(needle))]
+ if (!want.length) return 0
+ let hit = 0
+ for (const w of want) if (stateStems.has(w)) hit++
+ return (hit / Math.sqrt(want.length)) * 1.2
+}
+
+function softmax(raw, temp = 1) {
+ const m = Math.max(...raw)
+ const exps = raw.map((r) => Math.exp((r - m) / temp))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ return exps.map((e) => e / sum)
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic generic mock. It turns the state text + question wording into a plausible
+// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`
+ const S = new Set(stems(text))
+ const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
+
+ if (q.type === 'noul') {
+ const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
+ const no = evidence(S, `${q.raw?.false ?? ''}`)
+ const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
+ const probs = softmax(raw, 0.6)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
+ const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
+ // No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
+ if (raw.every((r) => Math.abs(r) < 0.26)) {
+ const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
+ levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
+ }
+ const probs = softmax(raw, 0.7)
+ const probabilities = {}
+ levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
+ const score = probs.reduce((acc, p, i) => acc + p * i, 0)
+ return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// Imports are hoisted, so they can live here with the code that needs them.
+import { readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ out.raw = isMap(q.criteria) ? q.criteria : null
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+// ---------------------------------------------------------------------------
+// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
+// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
+// you happen to have open. Two live routes are supported, both speaking the same question format:
+// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
+// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
+// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
+// ---------------------------------------------------------------------------
+const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN']
+let credCache = null
+export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
+
+function readCredentialFile() {
+ const now = Date.now()
+ const path = credentialsPath()
+ if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
+ const values = {}
+ try {
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
+ if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
+ }
+ } catch { /* no file: fine */ }
+ credCache = { at: now, path, values }
+ return values
+}
+
+/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
+export function resolveCredentials(explicitKey) {
+ if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
+ // Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
+ // key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
+ if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
+ const file = readCredentialFile()
+ const get = (k) => process.env[k] || file[k] || ''
+ const key = explicitKey || get('TYPESAFE_API_KEY')
+ if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
+ const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
+ if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
+ return null
+}
+
+/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
+export function describeCredentials() {
+ const c = resolveCredentials()
+ if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
+ return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
+}
+
+async function liveEvaluate(body, cred) {
+ const endpoint = cred.url
+ const key = cred.secret
+ const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } } : body
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) {
+ const data = await res.json()
+ // Cloudflare wraps the model's reply as { result, success, errors }.
+ if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
+ return data?.result?.answers ? data.result : data
+ }
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const cred = resolveCredentials(key)
+ const client = cred ? cred.provider : 'mock'
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (cred) {
+ const data = await liveEvaluate({ model, state, questions: wire }, cred)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-compactor/toolchain/setup.sh b/store/agents/jev-compactor/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-compactor/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-compactor/toolchain/viewer.sh b/store/agents/jev-compactor/toolchain/viewer.sh
new file mode 100755
index 000000000..2456b09b9
--- /dev/null
+++ b/store/agents/jev-compactor/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Compactor viewer (Jev judges every tool result in a made-up agent session and compacts the context).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-compactor/viewer/base.css b/store/agents/jev-compactor/viewer/base.css
new file mode 100644
index 000000000..c41ddcd46
--- /dev/null
+++ b/store/agents/jev-compactor/viewer/base.css
@@ -0,0 +1,83 @@
+/* base.css — the shared look of the Jev flagship viewers. Load before studio.css.
+ Set --accent / --accent2 in studio.css to give a harness its own colour. */
+:root {
+ --bg: #07080d; --panel: #10121a; --panel2: #161925; --line: #232838; --line2: #2e3550;
+ --ink: #e9ecf5; --dim: #8b92aa; --faint: #565d75;
+ --accent: #a78bfa; --accent2: #6d5bd0;
+ --ok: #34d399; --warn: #fbbf24; --bad: #fb7185; --cyan: #5eead4; --blue: #60a5fa;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ --radius: 12px;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1100px 700px at 75% -10%, color-mix(in srgb, var(--accent) 14%, transparent) 0%, transparent 60%), var(--bg);
+ color: var(--ink); font: 13px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+::selection { background: color-mix(in srgb, var(--accent) 45%, transparent); }
+::-webkit-scrollbar { width: 8px; height: 8px; }
+::-webkit-scrollbar-thumb { background: var(--line2); border-radius: 4px; }
+::-webkit-scrollbar-track { background: transparent; }
+
+#topbar {
+ display: flex; align-items: center; gap: 22px; padding: 10px 18px; flex: none; flex-wrap: wrap;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(20,22,34,.92), rgba(10,11,18,.7)); backdrop-filter: blur(8px);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font: 700 15px var(--mono); letter-spacing: .4px; margin: 0; white-space: nowrap; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 14px var(--accent); animation: dot 2.4s ease-in-out infinite; }
+@keyframes dot { 50% { transform: scale(.72); opacity: .7; } }
+.brand .sub { color: var(--dim); font-size: 11px; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; min-width: 54px; }
+.stat label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+button, .btn {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line2); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: border-color .15s, filter .15s, transform .05s; user-select: none;
+}
+button:hover { border-color: var(--accent); }
+button:active { transform: translateY(1px); }
+button.primary { background: linear-gradient(135deg, var(--accent2), var(--accent)); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.12); }
+button.ghost { background: transparent; }
+button.on { border-color: var(--accent); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
+button[disabled] { opacity: .45; cursor: default; }
+kbd { font: 600 10px var(--mono); padding: 1px 5px; border: 1px solid var(--line2); border-bottom-width: 2px; border-radius: 4px; color: var(--dim); }
+input[type=text], input[type=search], select, textarea {
+ font: 13px var(--mono); color: var(--ink); background: #0b0d14; border: 1px solid var(--line2); border-radius: 8px; padding: 7px 10px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+input[type=range] { accent-color: var(--accent); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow: auto; }
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 14px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; background: rgba(12,13,20,.55); }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; }
+.panel-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--dim); margin-bottom: 9px; display: flex; align-items: center; gap: 8px; }
+.panel-title .right { margin-left: auto; text-transform: none; letter-spacing: 0; }
+.how { color: var(--dim); font-size: 12.5px; line-height: 1.55; }
+.how b { color: var(--ink); } .how code { color: var(--warn); }
+.pill { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line2); color: var(--dim); }
+.pill.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
+.pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
+.pill.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); }
+
+.canvas-wrap { position: relative; flex: 1; min-height: 320px; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #05060a; }
+.canvas-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.banner { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); padding: 9px 20px; border-radius: 10px; font: 700 14px var(--mono); white-space: nowrap; backdrop-filter: blur(6px); }
+.banner.ok { background: rgba(16,185,129,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 34px rgba(16,185,129,.35); }
+.banner.bad { background: rgba(225,29,72,.16); border: 1px solid var(--bad); color: var(--bad); box-shadow: 0 0 34px rgba(225,29,72,.35); }
+.hidden { display: none !important; }
+.cfg-error { margin: 0 16px; padding: 8px 12px; border: 1px solid var(--bad); border-radius: 8px; color: var(--bad); background: rgba(225,29,72,.08); font-size: 12px; }
+
+@media (max-width: 900px) {
+ main { flex-direction: column; overflow: auto; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); overflow: visible; }
+ body { overflow: auto; }
+}
diff --git a/store/agents/jev-compactor/viewer/index.html b/store/agents/jev-compactor/viewer/index.html
new file mode 100644
index 000000000..388375950
--- /dev/null
+++ b/store/agents/jev-compactor/viewer/index.html
@@ -0,0 +1,100 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Compactor</title>
+<link rel="icon" href="data:,">
+<link rel="stylesheet" href="/base.css">
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand">
+ <span class="dot"></span><h1 id="title">Jev Compactor</h1>
+ <span class="sub" id="subtitle">synthetic agent session · made-up repo</span>
+ <span class="pill warn" title="Everything in this pane is generated. It is a demo of the idea, not a real compaction plugin.">SYNTHETIC DEMO</span>
+ </div>
+ <div class="controls">
+ <button id="pause" title="Pause or resume the session (space)">Pause</button>
+ <button id="step" title="Add exactly one event">Step</button>
+ <button id="flood" title="Pour 40 events into the window at once">Flood +40</button>
+ <button id="reset" title="Restart the session from its seed">Reset</button>
+ <button class="primary" id="compact" title="Ask Jev to judge every tool result right now (c)">Compact now</button>
+ </div>
+ </div>
+
+ <div id="statbar">
+ <div class="big"><label>Tokens now</label><b id="sTokens">—</b><i id="sTokensSub">&nbsp;</i></div>
+ <div class="big"><label>Budget</label><b id="sBudget">—</b><i id="sBudgetSub">&nbsp;</i></div>
+ <div class="big"><label>Last reduction</label><b id="sReduction" class="ok">—</b><i id="sReductionSub">&nbsp;</i></div>
+ <div class="big"><label>Needle recall</label><b id="sRecall">—</b><i id="sRecallSub">&nbsp;</i></div>
+ <div class="big"><label>Compaction time</label><b id="sTime">—</b><i id="sTimeSub">&nbsp;</i></div>
+ <div class="big"><label>Questions / call</label><b id="sPerCall">—</b><i id="sPerCallSub">&nbsp;</i></div>
+ <div class="big"><label>Results judged</label><b id="sJudged">0</b><i id="sJudgedSub">&nbsp;</i></div>
+ <div class="big"><label>Cost so far</label><b id="sCost">$0</b><i id="sCostSub">&nbsp;</i></div>
+ </div>
+
+ <div id="cfgError" class="cfg-error hidden"></div>
+
+ <main>
+ <section id="stage">
+ <div class="canvas-wrap"><canvas id="scene"></canvas></div>
+
+ <div class="panel console">
+ <div class="row">
+ <span class="cap">Current task</span>
+ <div id="tasks" class="tasks"></div>
+ <span id="taskTitle" class="task-title"></span>
+ </div>
+ <div class="row">
+ <label class="slider"><span class="cap">Budget</span>
+ <input id="budget" type="range" min="0" max="1000" step="1" value="500">
+ <output id="budgetOut">—</output>
+ </label>
+ <label class="slider"><span class="cap">Distraction</span>
+ <input id="distraction" type="range" min="0" max="1" step="0.01" value="0.12">
+ <output id="distractionOut">—</output>
+ </label>
+ <span id="overridePill" class="pill hidden" title="You changed this in the pane. Any edit to session.json puts the file back in charge.">PANE OVERRIDE</span>
+ </div>
+ <div class="hint">Click a block to inspect or pin it · switch the task and different blocks survive · raise distraction and junk starts to talk like the task</div>
+ </div>
+ </section>
+
+ <aside id="rail">
+ <div data-jev-hud class="hud-slot"></div>
+ <div class="panel" id="inspector">
+ <div class="panel-title">Inspector <span class="right" id="insId"></span></div>
+ <div id="insBody" class="ins-empty">Click any block in the tower.</div>
+ </div>
+
+ <details class="panel how-panel">
+ <summary class="panel-title">How it works <span class="right">open</span></summary>
+ <div class="how">
+ A made-up coding agent works in a made-up repo. Its context fills with messages and tool
+ results. Each tool result secretly belongs to <b>one task</b>, or is <b>junk</b> (logs,
+ lockfiles, test spam). That hidden label is the ground truth.<br><br>
+ Over budget, Jev judges <b>every tool result at once</b>: the state is the current task
+ plus the last few messages, and each result is one question, <code>keep</code> /
+ <code>trim</code> / <code>drop</code>, up to 100 per call. Messages are never touched. If
+ the window is still above the target, the keeps Jev was least sure about get squeezed.<br><br>
+ <b>Needle recall</b> is the share of truly needed tokens that survived. The slim tower is a
+ <b>simple baseline for contrast</b>: it folds the oldest half into one short summary. It is
+ not a measurement of any real product.<br><br>
+ The agent edits <code>session.json</code>: tasks, vocabulary, <code>budget</code>,
+ <code>trimTo</code>, <code>target</code>, <code>distraction</code>.
+ </div>
+ </details>
+
+ <div class="panel">
+ <div class="panel-title">Past compactions <span class="right" id="histAvg"></span></div>
+ <div class="hist-head"><span>#</span><span>before</span><span>after</span><span>recall</span><span>ms</span></div>
+ <ul id="history"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js" defer></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-compactor/viewer/jev-hud.js b/store/agents/jev-compactor/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-compactor/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-compactor/viewer/kit.mjs b/store/agents/jev-compactor/viewer/kit.mjs
new file mode 100644
index 000000000..f80d29b7d
--- /dev/null
+++ b/store/agents/jev-compactor/viewer/kit.mjs
@@ -0,0 +1,112 @@
+// kit.mjs — the boring, security-relevant half of a Jev viewer, written once:
+// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
+// /control, plus an atomic verdict writer and a safe JSON config watcher.
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
+import { join, extname } from 'node:path'
+import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
+
+export const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+/** Deterministic PRNG so every run of a demo is reproducible. */
+export function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/**
+ * Serve a viewer.
+ * @param {object} o
+ * @param {string} o.here the viewer directory (static files live here)
+ * @param {number} o.port 0 = ephemeral
+ * @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
+ * @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
+ * @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ */
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+ const clients = new Set()
+ const allowed = new Set(files)
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ // Loopback only: a page on another origin (DNS rebinding) must not reach this server.
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ const path = url.pathname
+ try {
+ if (req.method === 'GET') {
+ const name = path === '/' ? 'index.html' : path.slice(1)
+ if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
+ if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (path === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
+ clients.add(res)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ }
+ if (req.method === 'POST' && path === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 65536) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const reply = control ? await control(String(j.cmd ?? ''), j) : null
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
+ res.writeHead(404); res.end('Not found')
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
+ }
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ clients,
+ /** Push a named SSE event (default 'state') to every connected pane. */
+ broadcast(obj, event = 'state') {
+ const line = `event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`
+ for (const c of clients) c.write(line)
+ },
+ async close() { for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+/** Atomic write of .harness/verdict.json (the harness reads this file; never edit it by hand). */
+export function writeVerdict(workspace, verdict) {
+ const dir = join(workspace, '.harness')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify({ spec: 1, ...verdict, updatedAt: new Date().toISOString() }))
+ renameSync(file + '.tmp', file)
+}
+
+/**
+ * Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
+ * good config and reports the parse error instead of crashing the demo.
+ * @returns {{ get(): object, error(): string|null, close(): void }}
+ */
+export function watchConfig(file, defaults, onChange) {
+ let cfg = { ...defaults }, err = null, timer = null
+ const load = () => {
+ try { cfg = { ...defaults, ...JSON.parse(readFileSync(file, 'utf8')) }; err = null }
+ catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
+ }
+ load()
+ let watcher = null
+ try {
+ watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ } catch { /* file may not exist yet; defaults stand */ }
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+}
diff --git a/store/agents/jev-compactor/viewer/studio.css b/store/agents/jev-compactor/viewer/studio.css
new file mode 100644
index 000000000..aa8a01627
--- /dev/null
+++ b/store/agents/jev-compactor/viewer/studio.css
@@ -0,0 +1,95 @@
+/* Jev Compactor — the look on top of base.css. */
+:root { --accent: #4ade80; --accent2: #15803d; --keep: #4ade80; --trim: #fbbf24; --drop: #fb7185; }
+
+#topbar { padding: 8px 16px; gap: 14px; }
+.brand .sub { white-space: nowrap; }
+.brand .pill { white-space: nowrap; }
+button.primary { color: #04130a; }
+.controls button { padding: 6px 11px; }
+
+/* the big numbers */
+#statbar {
+ display: grid; grid-template-columns: repeat(8, minmax(0, 1fr)); flex: none;
+ border-bottom: 1px solid var(--line); background: rgba(9, 11, 16, .72);
+}
+.big { padding: 7px 14px 6px; border-right: 1px solid var(--line); min-width: 0; display: flex; flex-direction: column; }
+.big:last-child { border-right: none; }
+.big label { font-size: 9px; letter-spacing: 1.2px; text-transform: uppercase; color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.big b { font-size: 21px; line-height: 1.2; font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; letter-spacing: -.3px; }
+.big i { font-style: normal; font-size: 10px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
+.big b.ok { color: var(--ok); } .big b.warn { color: var(--warn); } .big b.bad { color: var(--bad); }
+@media (max-width: 1240px) { .big b { font-size: 17px; } .big { padding: 6px 10px 5px; } }
+@media (max-width: 820px) { #statbar { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
+
+.cfg-error { margin: 8px 16px 0; flex: none; }
+
+#stage { gap: 10px; padding: 12px 14px; overflow: hidden; }
+.canvas-wrap { min-height: 260px; background: radial-gradient(900px 500px at 30% 110%, rgba(21, 128, 61, .13), transparent 60%), #05060a; cursor: default; }
+.canvas-wrap.hot { cursor: pointer; }
+
+/* the console under the scene */
+.console { flex: none; padding: 9px 12px; display: flex; flex-direction: column; gap: 7px; }
+.console .row { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.cap { font-size: 9px; letter-spacing: 1.2px; text-transform: uppercase; color: var(--dim); white-space: nowrap; flex: none; }
+.tasks { display: flex; gap: 6px; flex-wrap: wrap; }
+.tasks button { padding: 4px 10px; font-size: 11.5px; border-radius: 999px; }
+.tasks button.on { background: color-mix(in srgb, var(--accent) 14%, transparent); }
+.task-title { color: var(--ink); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; text-align: right; }
+.slider { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; }
+.slider input { flex: 1; min-width: 60px; }
+.slider output { width: 74px; text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; flex: none; }
+.hint { color: var(--faint); font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+#overridePill { color: var(--accent); border-color: color-mix(in srgb, var(--accent) 50%, transparent); flex: none; }
+
+/* the kit HUD: keep it short so the inspector stays on screen */
+.hud-slot { flex: none; }
+.hud-slot .jh-qs { display: flex; flex-direction: column; max-height: 176px; overflow-y: auto; padding-right: 4px; }
+.hud-slot .jh-more.all { order: 99; padding-bottom: 2px; }
+.hud-slot .jh-spark { height: 20px; }
+
+/* how it works, folded by default */
+.how-panel { flex: none; }
+.how-panel summary { cursor: pointer; list-style: none; margin-bottom: 0; user-select: none; }
+.how-panel summary::-webkit-details-marker { display: none; }
+.how-panel[open] summary { margin-bottom: 9px; }
+.how-panel[open] summary .right { display: none; }
+.how-panel summary .right { color: var(--accent); }
+
+/* inspector */
+#rail { gap: 10px; padding: 12px; }
+#rail > .panel, #rail > details { flex: none; }
+.ins-empty { color: var(--dim); font-size: 12px; }
+.ins-top { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
+.ins-kind { font-size: 10px; font-weight: 700; letter-spacing: .6px; padding: 1px 7px; border-radius: 4px; color: #06080c; flex: none; }
+.ins-label { font-weight: 700; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; }
+.ins-meta { display: flex; align-items: center; gap: 8px; color: var(--dim); font-size: 11.5px; margin-bottom: 7px; font-variant-numeric: tabular-nums; }
+.ins-meta b { color: var(--ink); }
+.ins-meta button { margin-left: auto; padding: 3px 10px; font-size: 11px; }
+.ins-prev { font-size: 11px; line-height: 1.45; color: #aeb6cc; background: #0a0c12; border: 1px solid var(--line); border-radius: 8px; padding: 6px 9px; height: 62px; overflow: hidden; margin-bottom: 8px; }
+.ins-prev-text { word-break: break-word; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; }
+.ins-h { font-size: 9px; letter-spacing: 1.2px; text-transform: uppercase; color: var(--dim); display: flex; align-items: center; gap: 6px; margin-bottom: 4px; }
+.ins-h b { font-size: 11px; letter-spacing: .6px; }
+.v-keep { color: var(--keep); } .v-trim { color: var(--trim); } .v-drop { color: var(--drop); }
+.pbar { display: grid; grid-template-columns: 34px 1fr 34px; align-items: center; gap: 6px; height: 15px; font-size: 11px; color: var(--dim); }
+.pbar .t { height: 7px; border-radius: 4px; background: rgba(255, 255, 255, .05); overflow: hidden; }
+.pbar .f { height: 100%; border-radius: 4px; transition: width .2s ease-out; }
+.pbar.keep .f { background: var(--keep); } .pbar.trim .f { background: var(--trim); } .pbar.drop .f { background: var(--drop); }
+.pbar span:last-child { text-align: right; font-variant-numeric: tabular-nums; }
+.pbar.top { color: var(--ink); font-weight: 700; }
+.ins-note { font-size: 11px; color: var(--warn); min-height: 16px; margin-top: 2px; }
+.ins-truth { font-size: 11.5px; color: var(--dim); line-height: 1.45; margin-top: 6px; min-height: 50px; }
+.ins-truth b { color: var(--ink); }
+.ins-match { font-weight: 700; }
+.ins-match.ok { color: var(--ok); } .ins-match.bad { color: var(--bad); }
+
+/* history */
+.hist-head, #history li { display: grid; grid-template-columns: 26px 1fr 1fr 52px 44px; gap: 6px; font-variant-numeric: tabular-nums; }
+.hist-head { font-size: 9px; letter-spacing: 1px; text-transform: uppercase; color: var(--faint); padding: 0 2px 4px; border-bottom: 1px solid var(--line); }
+.hist-head span:not(:first-child), #history li span:not(:first-child) { text-align: right; }
+#history { list-style: none; margin: 0; padding: 0; max-height: 210px; overflow-y: auto; }
+#history li { font-size: 11.5px; padding: 3px 2px; border-bottom: 1px dashed rgba(255, 255, 255, .05); color: var(--dim); }
+#history li:first-child { color: var(--ink); background: linear-gradient(90deg, color-mix(in srgb, var(--accent) 10%, transparent), transparent); }
+#history li .after { color: var(--accent); }
+#history li .lo { color: var(--warn); } #history li .vlo { color: var(--bad); }
+#history li.manual span:first-child { color: var(--cyan); }
+.hist-empty { color: var(--dim); font-size: 12px; padding: 6px 2px; }
diff --git a/store/agents/jev-compactor/viewer/studio.js b/store/agents/jev-compactor/viewer/studio.js
new file mode 100644
index 000000000..94e544748
--- /dev/null
+++ b/store/agents/jev-compactor/viewer/studio.js
@@ -0,0 +1,897 @@
+// Jev Compactor pane. One big canvas: the context tower (Jev lane), a giant token odometer, the
+// last-compaction card, a tokens-over-time chart and the slim "summarize instead" baseline tower.
+// The server owns the session; this file only draws it, at 60 fps, easing between server frames.
+(() => {
+ const $ = (id) => document.getElementById(id)
+ const canvas = $('scene'), wrap = canvas.parentElement, ctx = canvas.getContext('2d')
+ const MONO = "ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace"
+ const KIND_COLORS = ['#e2e8f0', '#c4b5fd', '#38bdf8', '#2dd4bf', '#8b9bc4', '#fb923c', '#f472b6', '#64748b']
+ const KIND_NAMES = ['user', 'assistant', 'Read', 'Grep', 'Bash', 'Edit', 'WebFetch', 'summary']
+ const V_NAMES = ['', 'KEEP', 'TRIM', 'DROP'], V_KEYS = ['', 'keep', 'trim', 'drop']
+ const V_COLORS = ['', '#4ade80', '#fbbf24', '#fb7185']
+ const GREEN = '#4ade80', AMBER = '#fbbf24', ROSE = '#fb7185', INK = '#e9ecf5', DIM = '#8b92aa', FAINT = '#565d75'
+
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+ // The tower's height axis is concave, so a small window still has presence. The budget line stays exact.
+ const axis = (u) => Math.pow(clamp(u, 0, 4), 0.6)
+ const fmtInt = (n) => Math.round(n).toLocaleString('en-US')
+ const fmtK = (n) => (n >= 1e6 ? (n / 1e6).toFixed(n % 1e6 ? 1 : 0) + 'M' : n >= 1000 ? Math.round(n / 1000) + 'k' : String(Math.round(n)))
+ const fmtPct = (v, d = 1) => (v == null ? '—' : (v * 100).toFixed(d) + '%')
+ const fmtMs = (ms) => (ms == null ? '—' : ms < 10 ? ms.toFixed(1) + ' ms' : ms < 1000 ? Math.round(ms) + ' ms' : (ms / 1000).toFixed(2) + ' s')
+ const fmtUsd = (v) => (v <= 0 ? '$0' : v < 0.01 ? '$' + v.toFixed(4) : v < 1 ? '$' + v.toFixed(3) : '$' + v.toFixed(2))
+ const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2)
+ const easeOutBounce = (t) => {
+ const n1 = 7.5625, d1 = 2.75
+ if (t < 1 / d1) return n1 * t * t
+ if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75
+ if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375
+ return n1 * (t -= 2.625 / d1) * t + 0.984375
+ }
+
+ // ---- state -----------------------------------------------------------------
+ let S = null
+ let gen = -1
+ let lastCompN = null
+ let lastBaseN = null
+ const jevLane = { order: [], map: new Map(), topY: 0 }
+ const baseLane = { order: [], map: new Map(), topY: 0 }
+ let scan = null
+ let ghost = null
+ let particles = [], chips = [], floaters = []
+ const odo = { v: 0, tween: null, speed: 0, hot: 0 }
+ let budgetDisp = 0
+ let hoverId = null, selectedId = null, autoSelect = true, inspected = null
+ const mouse = { x: -1, y: -1 }
+ let W = 0, H = 0, dpr = 1, L = null
+ let lastT = performance.now()
+ let sliderHold = 0
+ let taskKey = ''
+ let histKey = ''
+
+ // ---- server link -------------------------------------------------------------
+ async function post(cmd, extra = {}) {
+ try {
+ const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd, ...extra }) })
+ return r.ok ? r.json() : null
+ } catch { return null }
+ }
+ function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (ev) => { try { onFrame(JSON.parse(ev.data)) } catch (e) { console.error(e) } })
+ es.onerror = () => { es.close(); setTimeout(connect, 1000) }
+ }
+
+ function mkBlock(item, now, delay) {
+ return { id: item[0], kind: item[1], tokens: item[2], orig: item[3], task: item[4], need: item[5], pinned: item[6], verdict: item[7], label: item[8] ?? '', share: 0, at: 0, w: 0, y: 0, h: 0, state: 'live', pend: null, born: now + delay, flash: null, dieFrom: 1 }
+ }
+
+ function syncLane(lane, list, now, verdicts, isBase) {
+ const fresh = lane.order.length === 0
+ const seen = new Set()
+ let prev = null, i = 0
+ for (const item of list) {
+ const id = item[0]
+ seen.add(id)
+ let v = lane.map.get(id)
+ if (!v) {
+ v = mkBlock(item, now, fresh ? Math.min(i * 6, 700) : 0)
+ if (isBase) { v.share = item[3]; v.orig = item[2]; v.task = -2; v.need = 0; v.pinned = 0; v.verdict = 0; v.label = '' }
+ lane.map.set(id, v)
+ const idx = prev ? lane.order.indexOf(prev) + 1 : 0
+ lane.order.splice(idx, 0, v)
+ } else if (isBase) { v.tokens = item[2]; v.share = item[3] }
+ else {
+ v.pinned = item[6]; v.task = item[4]; v.need = item[5]
+ const vd = verdicts?.[id]
+ if (vd) v.pend = { code: vd[0], probs: [vd[1], vd[2], vd[3]], demoted: vd[4], tokens: item[2] }
+ else if (v.pend) v.pend.tokens = item[2]
+ else { v.tokens = item[2]; v.verdict = item[7] }
+ }
+ prev = v; i++
+ }
+ for (const v of lane.order) {
+ if (seen.has(v.id) || v.state !== 'live') continue
+ const vd = verdicts?.[v.id]
+ if (vd) { v.state = 'pending'; v.pend = { code: vd[0], probs: [vd[1], vd[2], vd[3]], demoted: vd[4], tokens: 0 } }
+ else if (!v.pend) { v.state = 'dying'; v.dieFrom = Math.max(1, v.at); if (isBase) dust(v) }
+ }
+ }
+
+ function onFrame(s) {
+ const now = performance.now()
+ const first = S === null
+ if (s.gen !== gen) {
+ gen = s.gen
+ for (const lane of [jevLane, baseLane]) { lane.order = []; lane.map.clear() }
+ scan = null; ghost = null; chips = []; particles = []; floaters = []
+ lastCompN = s.last?.n ?? 0; lastBaseN = s.baseline.compactions
+ odo.tween = null; odo.v = first ? 0 : odo.v
+ if (autoSelect) { selectedId = null; inspected = null }
+ }
+ const newComp = s.last && s.last.n !== lastCompN && s.last.verdicts && !document.hidden
+ if (newComp) finishScan(now)
+ S = s
+ if (!budgetDisp) budgetDisp = s.cfg.budget
+ syncLane(jevLane, s.blocks, now, newComp ? s.last.verdicts : null, false)
+ syncLane(baseLane, s.baseline.blocks, now, null, true)
+ if (newComp) {
+ lastCompN = s.last.n
+ scan = { t0: now, dur: clamp(900 + s.last.questions * 3, 1000, 1700), n: s.last.n }
+ ghost = { y: jevLane.topY, t0: now, text: `BEFORE ${fmtInt(s.last.before)}` }
+ if (L) floaters.push({ x: L.towerX + L.towerW / 2, y: Math.max(L.top + 60, jevLane.topY + 40), text: `−${fmtPct(s.last.reduction)} · ${fmtInt(s.last.questions)} questions · ${fmtMs(s.last.ms)}`, color: GREEN, t0: now + scan.dur * 0.75, big: true })
+ odo.tween = { from: odo.v, to: s.tokens, t0: now + 120, dur: scan.dur + 350 }
+ if (autoSelect) setTimeout(pickAuto, scan.dur + 200)
+ else if (selectedId != null) setTimeout(fetchInspect, scan.dur + 200)
+ } else if (s.last && s.last.n !== lastCompN) lastCompN = s.last.n
+ else if (odo.tween) odo.tween.to = s.tokens
+ if (s.baseline.compactions !== lastBaseN) {
+ if (lastBaseN != null && s.baseline.compactions > lastBaseN && L && !document.hidden) {
+ const lost = s.baseline.lastRecall == null ? null : 1 - s.baseline.lastRecall
+ floaters.push({ x: L.baseX + L.baseW / 2, y: L.bBottom - 40, text: lost == null ? 'folded' : `lost ${Math.round(lost * 100)}% of needles`, color: ROSE, t0: now })
+ }
+ lastBaseN = s.baseline.compactions
+ }
+ renderDom(s)
+ if (autoSelect && selectedId == null) pickAuto()
+ }
+
+ // ---- DOM: stats, console, inspector, history ------------------------------------
+ const setText = (el, t) => { if (el.textContent !== t) el.textContent = t }
+ function renderDom(s) {
+ setText($('title'), s.title)
+ setText($('subtitle'), `synthetic agent session · made-up repo "${s.repo}"`)
+ document.title = s.title
+ const last = s.last, t = s.totals
+ setText($('sTokens'), fmtInt(s.tokens))
+ setText($('sTokensSub'), `${Math.round((s.tokens / s.cfg.budget) * 100)}% full · ${s.blocks.length} blocks`)
+ setText($('sBudget'), fmtInt(s.cfg.budget))
+ setText($('sBudgetSub'), `target ${Math.round(s.cfg.target * 100)}% · trim ${fmtInt(s.cfg.trimTo)}`)
+ setText($('sReduction'), last ? '−' + fmtPct(last.reduction) : '—')
+ setText($('sReductionSub'), last ? `${fmtInt(last.before)} → ${fmtInt(last.after)}` : 'waiting for the first one')
+ const rec = $('sRecall')
+ setText(rec, last ? fmtPct(last.recall) : '—')
+ rec.className = !last || last.recall == null ? '' : last.recall >= s.cfg.recallTarget ? 'ok' : last.recall >= s.cfg.recallTarget - 0.1 ? 'warn' : 'bad'
+ setText($('sRecallSub'), t.avgRecall == null ? `goal ${fmtPct(s.cfg.recallTarget, 0)}` : `avg ${fmtPct(t.avgRecall)} · goal ${fmtPct(s.cfg.recallTarget, 0)}`)
+ setText($('sTime'), last ? fmtMs(last.ms) : '—')
+ setText($('sTimeSub'), s.client === 'typesafe' ? 'live Jev · wall clock' : 'offline mock')
+ setText($('sPerCall'), last ? String(last.perCall) : '—')
+ setText($('sPerCallSub'), last ? `${fmtInt(last.questions)} in ${last.calls} call${last.calls === 1 ? '' : 's'}` : 'up to 100')
+ setText($('sJudged'), fmtInt(t.questions))
+ setText($('sJudgedSub'), `in ${fmtInt(t.calls)} call${t.calls === 1 ? '' : 's'} · ${fmtInt(t.compactions)} run${t.compactions === 1 ? '' : 's'}`)
+ setText($('sCost'), fmtUsd(t.costUsd))
+ setText($('sCostSub'), s.client === 'typesafe' ? '$0.042 per M tokens' : 'at live Jev prices')
+
+ const err = $('cfgError'), msg = s.cfgError ? (s.cfgError.startsWith('session.json') ? s.cfgError : `session.json: ${s.cfgError}`) + ' · the last good session keeps running' : s.error ? `Jev: ${s.error}` : ''
+ err.classList.toggle('hidden', !msg); setText(err, msg)
+
+ const pause = $('pause'); setText(pause, s.running ? 'Pause' : 'Resume'); pause.classList.toggle('on', !s.running)
+
+ const key = JSON.stringify(s.tasks.map((x) => x.id))
+ const box = $('tasks')
+ if (key !== taskKey) {
+ taskKey = key
+ box.textContent = ''
+ for (const task of s.tasks) {
+ const b = document.createElement('button')
+ b.textContent = task.id; b.title = task.title; b.dataset.task = task.id
+ b.addEventListener('click', () => post('setTask', { task: task.id }))
+ box.appendChild(b)
+ }
+ }
+ for (const b of box.children) b.classList.toggle('on', b.dataset.task === s.currentTask)
+ setText($('taskTitle'), s.tasks.find((x) => x.id === s.currentTask)?.title ?? '')
+
+ if (performance.now() > sliderHold) {
+ $('budget').value = String(Math.round((1000 * Math.log(s.cfg.budget / 20000)) / Math.log(100)))
+ $('distraction').value = String(s.cfg.distraction)
+ }
+ setText($('budgetOut'), fmtInt(s.cfg.budget))
+ setText($('distractionOut'), s.cfg.distraction.toFixed(2))
+ $('overridePill').classList.toggle('hidden', !(s.overrides.budget || s.overrides.distraction || s.overrides.task))
+
+ const hk = `${s.gen}:${s.history.length}:${s.history.at(-1)?.n ?? 0}`
+ if (hk !== histKey) {
+ histKey = hk
+ const ul = $('history'); ul.textContent = ''
+ if (!s.history.length) { const li = document.createElement('div'); li.className = 'hist-empty'; li.textContent = 'None yet. The first one fires when the tower passes the budget line.'; ul.appendChild(li) }
+ for (const h of [...s.history].reverse()) {
+ const li = document.createElement('li')
+ if (h.trigger === 'manual') li.className = 'manual'
+ const cells = [[`${h.n}`, ''], [fmtInt(h.before), ''], [fmtInt(h.after), 'after'], [h.recall == null ? '—' : fmtPct(h.recall, 0), h.recall == null ? '' : h.recall < s.cfg.recallTarget - 0.1 ? 'vlo' : h.recall < s.cfg.recallTarget ? 'lo' : ''], [h.ms < 10 ? h.ms.toFixed(1) : String(Math.round(h.ms)), '']]
+ for (const [text, cls] of cells) { const sp = document.createElement('span'); sp.textContent = text; if (cls) sp.className = cls; li.appendChild(sp) }
+ li.title = `#${h.n} · task ${h.task} · ${h.trigger === 'manual' ? 'pressed by hand' : 'budget hit'} · ${h.questions} questions in ${h.calls} call(s)${h.demoted ? ` · ${h.demoted} squeezed` : ''}`
+ ul.appendChild(li)
+ }
+ }
+ setText($('histAvg'), t.compactions ? `avg cut ${fmtPct(t.avgReduction, 0)} · recall ${fmtPct(t.avgRecall, 0)}` : '')
+ }
+
+ function pickAuto() {
+ if (!S || !autoSelect) return
+ const curIdx = S.tasks.findIndex((x) => x.id === S.currentTask)
+ let best = null, bestScore = -1
+ for (const b of S.blocks) {
+ if (b[5] === 3) continue
+ const wrong = b[7] === 1 && b[4] !== curIdx
+ const score = (wrong ? 1e7 : b[7] === 1 ? 1e6 : 0) + b[2]
+ if (score > bestScore) { bestScore = score; best = b }
+ }
+ if (best && best[0] !== selectedId) { selectedId = best[0]; fetchInspect() }
+ else if (best) fetchInspect()
+ }
+
+ async function fetchInspect() {
+ if (selectedId == null) { inspected = null; renderInspector(); return }
+ const id = selectedId
+ const r = await post('inspect', { id })
+ if (id !== selectedId) return
+ inspected = r?.block ?? null
+ renderInspector()
+ }
+
+ function el(tag, cls, text) { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ function renderInspector() {
+ const body = $('insBody'), b = inspected
+ body.textContent = ''
+ if (!b) { body.className = 'ins-empty'; body.textContent = 'Click any block in the tower.'; setText($('insId'), ''); return }
+ body.className = ''
+ setText($('insId'), `block #${b.id}${autoSelect ? ' · auto-picked' : ''}`)
+ const top = el('div', 'ins-top')
+ const kind = el('span', 'ins-kind', b.kind); kind.style.background = KIND_COLORS[KIND_NAMES.indexOf(b.kind)] ?? '#888'
+ const label = el('span', 'ins-label', b.label); label.title = b.label
+ top.append(kind, label)
+ const meta = el('div', 'ins-meta')
+ const tok = el('span'); tok.innerHTML = `<b>${fmtInt(b.tokens)}</b> tokens${b.orig !== b.tokens ? ` (was ${fmtInt(b.orig)})` : ''}`
+ meta.append(tok)
+ if (b.gone) meta.append(el('span', 'pill bad', 'GONE'))
+ if (b.need !== 'message' && b.inWindow) {
+ const pin = el('button', b.pinned ? 'on' : '', b.pinned ? 'Pinned' : 'Pin')
+ pin.title = 'A pinned block is never dropped or trimmed'
+ pin.addEventListener('click', async () => { await post('pin', { id: b.id, pinned: !b.pinned }); fetchInspect() })
+ meta.append(pin)
+ }
+ const prev = el('div', 'ins-prev'); prev.append(el('div', 'ins-prev-text', b.preview)); prev.title = b.preview
+ body.append(top, meta, prev)
+ if (b.need === 'message') { body.append(el('div', 'ins-truth', b.truth)); return }
+ const vh = el('div', 'ins-h')
+ vh.append(el('span', '', "Jev's verdict"))
+ if (b.probs) {
+ vh.append(el('b', 'v-' + b.jev, String(b.jev).toUpperCase()))
+ body.append(vh)
+ for (const k of ['keep', 'trim', 'drop']) {
+ const row = el('div', `pbar ${k}${k === b.jev ? ' top' : ''}`)
+ const t = el('div', 't'), f = el('div', 'f'); f.style.width = Math.max(1.5, b.probs[k] * 100) + '%'; t.append(f)
+ row.append(el('span', '', k), t, el('span', '', b.probs[k].toFixed(2).replace(/^0/, '')))
+ body.append(row)
+ }
+ } else { vh.append(el('b', '', 'not judged yet')); body.append(vh); body.append(el('div', 'ins-truth', 'New since the last compaction. Jev judges it at the next one.')) }
+ const note = b.pinned && b.jev && b.jev !== 'keep' ? `Pinned by you, so it stayed (Jev said ${b.jev}).`
+ : b.demoted ? `Squeezed by the pressure pass: Jev said ${b.jev}, but the window had to reach the target, so it became ${b.verdict}.`
+ : b.gone ? b.gone : ''
+ body.append(el('div', 'ins-note', note))
+ const truth = el('div', 'ins-truth')
+ truth.append(el('b', '', 'Ground truth: '), document.createTextNode(b.truth + ' '))
+ if (b.ideal) {
+ truth.append(document.createTextNode('Ideal: '), el('b', 'v-' + b.ideal, b.ideal.toUpperCase()), document.createTextNode(' '))
+ if (b.verdict) truth.append(el('span', 'ins-match ' + (b.verdict === b.ideal ? 'ok' : 'bad'), b.verdict === b.ideal ? '✓ match' : '✗ differs'))
+ }
+ body.append(truth)
+ }
+
+ // ---- controls --------------------------------------------------------------------
+ $('pause').addEventListener('click', () => post(S?.running ? 'pause' : 'start'))
+ $('step').addEventListener('click', () => post('tick'))
+ $('flood').addEventListener('click', () => post('flood', { n: 40 }))
+ $('reset').addEventListener('click', () => post('reset'))
+ $('compact').addEventListener('click', () => post('compact'))
+ let budgetTimer = null, distTimer = null
+ $('budget').addEventListener('input', (e) => {
+ sliderHold = performance.now() + 700
+ const raw = 20000 * Math.pow(100, Number(e.target.value) / 1000)
+ const value = clamp(Math.round(raw / 1000) * 1000, 20000, 2000000)
+ setText($('budgetOut'), fmtInt(value))
+ clearTimeout(budgetTimer); budgetTimer = setTimeout(() => post('setBudget', { value }), 40)
+ })
+ $('distraction').addEventListener('input', (e) => {
+ sliderHold = performance.now() + 700
+ const value = Number(e.target.value)
+ setText($('distractionOut'), value.toFixed(2))
+ clearTimeout(distTimer); distTimer = setTimeout(() => post('setDistraction', { value }), 40)
+ })
+ window.addEventListener('keydown', (e) => {
+ if (e.target instanceof HTMLInputElement || e.metaKey || e.ctrlKey) return
+ if (e.key === ' ') { e.preventDefault(); post(S?.running ? 'pause' : 'start') }
+ else if (e.key === 'c') post('compact')
+ })
+
+ canvas.addEventListener('mousemove', (e) => { const r = canvas.getBoundingClientRect(); mouse.x = e.clientX - r.left; mouse.y = e.clientY - r.top })
+ canvas.addEventListener('mouseleave', () => { mouse.x = mouse.y = -1; hoverId = null; wrap.classList.remove('hot') })
+ canvas.addEventListener('click', (e) => {
+ const r = canvas.getBoundingClientRect(); mouse.x = e.clientX - r.left; mouse.y = e.clientY - r.top
+ const id = hitTest()
+ if (id != null) { selectedId = id; autoSelect = false; fetchInspect() }
+ else { autoSelect = true; selectedId = null; pickAuto() }
+ })
+
+ function hitTest() {
+ if (!L || mouse.x < L.towerX - 4 || mouse.x > L.towerX + L.towerW + 12) return null
+ let best = null, bestD = 4
+ for (const v of jevLane.order) {
+ if (v.state === 'dying' || v.h <= 0) continue
+ if (mouse.y >= v.y && mouse.y < v.y + v.h) return v.id
+ const d = Math.abs(mouse.y - (v.y + v.h / 2))
+ if (d < bestD) { bestD = d; best = v.id }
+ }
+ return best
+ }
+
+ // ---- canvas plumbing --------------------------------------------------------------
+ function resize() {
+ const r = wrap.getBoundingClientRect()
+ dpr = window.devicePixelRatio || 1
+ W = Math.max(200, r.width); H = Math.max(160, r.height)
+ canvas.width = Math.round(W * dpr); canvas.height = Math.round(H * dpr)
+ L = layout()
+ }
+ new ResizeObserver(resize).observe(wrap)
+
+ function layout() {
+ const pad = 16
+ const towerW = clamp(W * 0.3, 180, 360)
+ const gaugeX = pad, gaugeW = 8
+ const towerX = gaugeX + gaugeW + 10
+ const stripX = towerX + towerW + 5, stripW = 5
+ const chipX = stripX + stripW + 9, chipW = 84
+ const top = pad + 24, bottom = H - pad - 20
+ const Hb = (bottom - top) * 0.84
+ const baseW = clamp(W * 0.11, 92, 132)
+ const baseX = W - pad - baseW
+ const midX = chipX + chipW + 10
+ const midW = Math.max(120, baseX - 26 - midX)
+ const odoW = W - pad - midX
+ return { pad, towerW, gaugeX, gaugeW, towerX, stripX, stripW, chipX, chipW, top, bottom, Hb, baseW, baseX, midX, midW, odoW, bTop: top, bBottom: bottom, bHb: Hb }
+ }
+
+ function rr(x, y, w, h, r) {
+ r = Math.min(r, w / 2, h / 2)
+ ctx.beginPath(); ctx.moveTo(x + r, y); ctx.lineTo(x + w - r, y); ctx.quadraticCurveTo(x + w, y, x + w, y + r)
+ ctx.lineTo(x + w, y + h - r); ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h); ctx.lineTo(x + r, y + h)
+ ctx.quadraticCurveTo(x, y + h, x, y + h - r); ctx.lineTo(x, y + r); ctx.quadraticCurveTo(x, y, x + r, y); ctx.closePath()
+ }
+ const font = (px, weight = 600) => { ctx.font = `${weight} ${px}px ${MONO}` }
+ function fit(text, maxW, px, weight = 700, min = 8) {
+ let size = px
+ font(size, weight)
+ while (size > min && ctx.measureText(text).width > maxW) { size -= 1; font(size, weight) }
+ return size
+ }
+ function caps(text, x, y, color = DIM, px = 9, align = 'left', maxW = 0) {
+ font(px, 600); ctx.fillStyle = color; ctx.textAlign = align; ctx.textBaseline = 'alphabetic'
+ try { ctx.letterSpacing = '1.2px' } catch { /* older engines */ }
+ while (maxW && px > 6.5 && ctx.measureText(text).width > maxW) { px -= 0.5; font(px, 600) }
+ ctx.fillText(text, x, y)
+ try { ctx.letterSpacing = '0px' } catch { /* older engines */ }
+ }
+
+ // ---- animation step ------------------------------------------------------------------
+ function stepLane(lane, dt, now, budget, top, bottom, Hb) {
+ let sumAt = 0, sumW = 0
+ for (const v of lane.order) {
+ const target = now < v.born || v.state === 'dying' ? 0 : v.tokens
+ const k = target > v.at ? 18 : 7.5
+ v.at += (target - v.at) * (1 - Math.exp(-dt * k))
+ if (Math.abs(target - v.at) < 0.6) v.at = target
+ v.w = Math.pow(Math.max(v.at, 0), 0.75)
+ sumAt += v.at; sumW += v.w
+ }
+ if (lane.order.some((v) => v.state === 'dying' && v.at < 1)) {
+ lane.order = lane.order.filter((v) => { const dead = v.state === 'dying' && v.at < 1; if (dead) lane.map.delete(v.id); return !dead })
+ }
+ const Ht = Math.min(axis(sumAt / budget) * Hb, bottom - top)
+ let y = bottom
+ for (const v of lane.order) { v.h = sumW > 0 ? (Ht * v.w) / sumW : 0; y -= v.h; v.y = y }
+ lane.topY = y
+ lane.sumAt = sumAt
+ }
+
+ function finishScan(now) {
+ if (!scan) return
+ for (const v of jevLane.order) if (v.pend) trigger(v, now, true)
+ scan = null
+ }
+
+ function trigger(v, now, quiet) {
+ const p = v.pend
+ v.pend = null
+ v.verdict = p.code
+ v.flash = { t: now, code: p.code }
+ if (p.code === 3 || v.state === 'pending') { v.state = 'dying'; v.dieFrom = Math.max(1, v.at); if (!quiet) burst(v) }
+ else v.tokens = p.tokens
+ if (!quiet) addChip(v, p, now)
+ }
+
+ function addChip(v, p, now) {
+ const y = clamp(v.y + v.h / 2, L.top + 8, L.bottom - 8)
+ for (const c of chips) if (Math.abs(c.y - y) < 15 && now - c.t0 < 620) return
+ const top = Math.max(...p.probs)
+ chips.push({ y, t0: now, color: V_COLORS[p.code], text: `${V_NAMES[p.code]} ${top.toFixed(2).replace(/^0/, '')}`, squeezed: !!p.demoted })
+ }
+
+ function burst(v) {
+ const n = clamp(Math.round((v.h * L.towerW) / 70), 8, 80)
+ const color = KIND_COLORS[v.kind]
+ for (let i = 0; i < n; i++) {
+ if (particles.length > 2400) break
+ particles.push({ x: L.towerX + Math.random() * L.towerW, y: v.y + Math.random() * Math.max(1, v.h), vx: 20 + Math.random() * 230, vy: -120 + Math.random() * 150, life: 0, max: 0.6 + Math.random() * 0.9, color: Math.random() < 0.25 ? '#fecdd3' : color, size: 1.4 + Math.random() * 2.6 })
+ }
+ }
+ function dust(v) {
+ if (!L || v.h < 0.5) return
+ const n = clamp(Math.round(v.h / 2), 1, 8)
+ for (let i = 0; i < n; i++) {
+ if (particles.length > 1400) break
+ particles.push({ x: L.baseX + Math.random() * L.baseW, y: v.y + Math.random() * Math.max(1, v.h), vx: -20 - Math.random() * 60, vy: -30 + Math.random() * 60, life: 0, max: 0.5 + Math.random() * 0.5, color: '#94a3b8', size: 1 + Math.random() * 1.6 })
+ }
+ }
+
+ // ---- drawing ---------------------------------------------------------------------------
+ function drawTower(lane, x, w, now, top, isBase) {
+ const curIdx = S.tasks.findIndex((t) => t.id === S.currentTask)
+ let fallingNow = 0
+ for (const v of lane.order) if (now >= v.born && now - v.born < 500) fallingNow++
+ font(10, 600)
+ for (const v of lane.order) {
+ if (now < v.born || v.h < 0.12) continue
+ const age = (now - v.born) / 1000
+ let yOff = 0, alpha = 1
+ if (age < 0.62) { const dropH = Math.min(130, Math.max(24, v.y - top + 30)); yOff = -(1 - easeOutBounce(age / 0.62)) * dropH; alpha = Math.min(1, age / 0.09) }
+ if (v.state === 'dying') alpha *= clamp(v.at / v.dieFrom, 0, 1)
+ const gap = v.h > 3.4 ? 1 : 0
+ const falling = age < 0.5 && yOff < -2
+ const hh = Math.max(v.h - gap, falling ? 4 : 0.7)
+ const y = Math.max(top - 2, v.y + yOff)
+ if (falling && v.h >= 5 && fallingNow <= 3 && y - 34 > top) {
+ const st = ctx.createLinearGradient(0, y - 34, 0, y)
+ st.addColorStop(0, 'rgba(255,255,255,0)'); st.addColorStop(1, 'rgba(255,255,255,.12)')
+ ctx.globalAlpha = alpha; ctx.fillStyle = st; ctx.fillRect(x, y - 34, w, 34)
+ }
+ ctx.globalAlpha = alpha * (v.h < 1 ? clamp(v.h + 0.25, 0.4, 1) : 1)
+ ctx.fillStyle = KIND_COLORS[v.kind]
+ if (hh > 5) { rr(x, y, w, hh, 2.5); ctx.fill() } else ctx.fillRect(x, y, w, hh)
+ if (v.kind === 7 && hh > 3) { // a summary slab: hatch it
+ ctx.save(); rr(x, y, w, hh, 2.5); ctx.clip(); ctx.strokeStyle = 'rgba(8,10,16,.55)'; ctx.lineWidth = 2
+ for (let sx = x - hh; sx < x + w; sx += 7) { ctx.beginPath(); ctx.moveTo(sx, y + hh); ctx.lineTo(sx + hh, y); ctx.stroke() }
+ ctx.restore()
+ }
+ if (!isBase) {
+ if (v.verdict === 1 || v.verdict === 2) { ctx.fillStyle = V_COLORS[v.verdict]; ctx.fillRect(x, y, 3, hh) }
+ if (hh >= 12 && v.state === 'live') {
+ ctx.fillStyle = 'rgba(5,8,12,.82)'; ctx.textBaseline = 'middle'; ctx.textAlign = 'right'
+ const tok = fmtInt(v.tokens)
+ ctx.fillText(tok, x + w - (v.pinned ? 18 : 7), y + hh / 2 + 0.5)
+ ctx.textAlign = 'left'
+ const room = w - 24 - tok.length * 6.2 - (v.pinned ? 12 : 0)
+ const text = `${KIND_NAMES[v.kind]} ${v.label}`
+ const max = Math.max(0, Math.floor(room / 6.1))
+ if (max > 3) ctx.fillText(text.length > max ? text.slice(0, max - 1) + '…' : text, x + 8, y + hh / 2 + 0.5)
+ }
+ if (v.pinned) {
+ ctx.strokeStyle = '#fff'; ctx.lineWidth = 1.5
+ if (hh > 3) { rr(x + 0.75, y + 0.75, w - 1.5, Math.max(1, hh - 1.5), 2.5); ctx.stroke() }
+ const cy = y + hh / 2, cx = x + w - 9, d = clamp(hh / 2 - 1, 2, 4.5)
+ ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.moveTo(cx, cy - d); ctx.lineTo(cx + d, cy); ctx.lineTo(cx, cy + d); ctx.lineTo(cx - d, cy); ctx.closePath(); ctx.fill()
+ }
+ if (v.flash) {
+ const ft = (now - v.flash.t) / 520
+ if (ft >= 1) v.flash = null
+ else { ctx.globalAlpha = alpha * (1 - ft) * 0.85; ctx.fillStyle = v.flash.code === 1 ? '#bbf7d0' : v.flash.code === 2 ? '#fde68a' : '#fecdd3'; ctx.fillRect(x, y, w, Math.max(hh, 1.5)) }
+ }
+ }
+ // truth strip
+ ctx.globalAlpha = alpha
+ const sx = isBase ? x - 9 : x + w + 5
+ if (isBase) { if (v.share > 0.004) { ctx.fillStyle = GREEN; ctx.globalAlpha = alpha * clamp(0.25 + v.share, 0, 1); ctx.fillRect(sx, y, 5, Math.max(hh, 0.7)) } }
+ else if (v.need !== 3) {
+ const rel = v.task === curIdx && v.need > 0
+ ctx.fillStyle = rel ? (v.need === 2 ? GREEN : '#86efac') : '#3a2430'
+ ctx.globalAlpha = alpha * (rel ? (v.need === 2 ? 1 : 0.6) : 0.9)
+ ctx.fillRect(sx, y, 5, Math.max(hh, 0.7))
+ }
+ }
+ ctx.globalAlpha = 1
+ // sheen
+ const g = ctx.createLinearGradient(x, 0, x + w, 0)
+ g.addColorStop(0, 'rgba(255,255,255,.10)'); g.addColorStop(0.25, 'rgba(255,255,255,0)'); g.addColorStop(1, 'rgba(0,0,0,.30)')
+ ctx.fillStyle = g; ctx.fillRect(x, lane.topY - 2, w, Math.max(0, (isBase ? L.bBottom : L.bottom) - lane.topY + 2))
+ }
+
+ function drawLine(x1, x2, y, color, label, dashed, labelAlign = 'left') {
+ ctx.save()
+ ctx.strokeStyle = color; ctx.lineWidth = dashed ? 1 : 1.5
+ if (dashed) ctx.setLineDash([4, 5]); else { ctx.shadowColor = color; ctx.shadowBlur = 12 }
+ ctx.beginPath(); ctx.moveTo(x1, y + 0.5); ctx.lineTo(x2, y + 0.5); ctx.stroke()
+ ctx.restore()
+ if (label) {
+ font(9, 700)
+ const tw = ctx.measureText(label).width + 10
+ const lx = labelAlign === 'left' ? x1 + 4 : labelAlign === 'after' ? x2 + 3 : x2 - tw - 4
+ const ly = labelAlign === 'after' ? y - 6.5 : y - 15
+ ctx.fillStyle = 'rgba(5,6,10,.82)'; rr(lx, ly, tw, 13, 3); ctx.fill()
+ ctx.fillStyle = color; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText(label, lx + 5, ly + 7)
+ }
+ }
+
+ function drawOdometer(x, yTop, px, value, speed, digits, now, hot) {
+ const cellW = px * 0.66, commaW = px * 0.3, cellH = px * 1.14
+ let cx = x
+ for (let p = digits - 1; p >= 0; p--) {
+ const unit = 10 ** p
+ const lead = value < unit && p > 0
+ rr(cx + 1.5, yTop, cellW - 3, cellH, px * 0.1)
+ const bg = ctx.createLinearGradient(0, yTop, 0, yTop + cellH)
+ bg.addColorStop(0, '#05070b'); bg.addColorStop(0.5, '#10141d'); bg.addColorStop(1, '#05070b')
+ ctx.fillStyle = bg; ctx.fill()
+ ctx.strokeStyle = hot > 0.02 ? `rgba(74,222,128,${0.18 + hot * 0.4})` : '#1a2030'; ctx.lineWidth = 1; ctx.stroke()
+ ctx.save(); rr(cx + 1.5, yTop, cellW - 3, cellH, px * 0.1); ctx.clip()
+ font(px, 700); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
+ const mx = cx + cellW / 2, my = yTop + cellH / 2 + px * 0.04
+ const color = hot > 0.02 ? `rgb(${Math.round(233 - hot * 99)},${Math.round(236 + hot * 3)},${Math.round(245 - hot * 73)})` : INK
+ ctx.fillStyle = color
+ if (hot > 0.02) { ctx.shadowColor = GREEN; ctx.shadowBlur = 16 * hot }
+ const dps = Math.abs(speed) / unit
+ if (dps > 26) {
+ const off = ((now / 1000) * 13 + p * 0.37) % 1
+ const d0 = Math.floor(value / unit) % 10
+ ctx.globalAlpha = 0.34
+ for (let k = -1; k <= 2; k++) ctx.fillText(String((((d0 + k) % 10) + 10) % 10), mx, my + (k - off) * cellH * 0.86)
+ ctx.globalAlpha = 1
+ } else {
+ const pos = value / unit
+ const d = Math.floor(pos) % 10
+ let f
+ if (p === 0) f = pos - Math.floor(pos)
+ else { const lower = value % unit, start = unit - Math.max(1, unit * 0.08); f = lower > start ? (lower - start) / (unit - start) : 0 }
+ ctx.globalAlpha = lead ? 0.13 : 1
+ ctx.fillText(String(d), mx, my - f * cellH)
+ if (f > 0.001) ctx.fillText(String((d + 1) % 10), mx, my + (1 - f) * cellH)
+ ctx.globalAlpha = 1
+ }
+ ctx.restore()
+ const sh = ctx.createLinearGradient(0, yTop, 0, yTop + cellH)
+ sh.addColorStop(0, 'rgba(0,0,0,.6)'); sh.addColorStop(0.28, 'rgba(0,0,0,0)'); sh.addColorStop(0.72, 'rgba(0,0,0,0)'); sh.addColorStop(1, 'rgba(0,0,0,.6)')
+ rr(cx + 1.5, yTop, cellW - 3, cellH, px * 0.1); ctx.fillStyle = sh; ctx.fill()
+ cx += cellW
+ if (p % 3 === 0 && p > 0) {
+ font(px * 0.8, 700); ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic'
+ ctx.fillStyle = value < unit ? 'rgba(233,236,245,.13)' : DIM
+ ctx.fillText(',', cx + commaW / 2, yTop + cellH - px * 0.12)
+ cx += commaW
+ }
+ }
+ return cx - x
+ }
+ const odoWidth = (px, digits) => digits * px * 0.66 + Math.floor((digits - 1) / 3) * px * 0.3
+
+ function meter(x, y, w, label, value, color) {
+ font(10, 600); ctx.textBaseline = 'middle'; ctx.textAlign = 'left'; ctx.fillStyle = DIM
+ ctx.fillText(label, x, y)
+ const lw = 92, vw = 50
+ const bx = x + lw, bw = Math.max(20, w - lw - vw)
+ ctx.fillStyle = 'rgba(255,255,255,.06)'; rr(bx, y - 3.5, bw, 7, 3.5); ctx.fill()
+ if (value != null) { ctx.fillStyle = color; rr(bx, y - 3.5, Math.max(3, bw * clamp(value, 0, 1)), 7, 3.5); ctx.fill() }
+ font(11, 700); ctx.textAlign = 'right'; ctx.fillStyle = value == null ? DIM : INK
+ ctx.fillText(fmtPct(value), x + w, y)
+ }
+
+ function drawCard(x, y, w, now) {
+ const last = S.last
+ const extra = last && (last.demoted || last.needlesDropped || last.junkKept)
+ const h = last ? (extra ? 172 : 154) : 84
+ rr(x, y, w, h, 10); ctx.fillStyle = 'rgba(16,18,26,.82)'; ctx.fill(); ctx.strokeStyle = '#232838'; ctx.lineWidth = 1; ctx.stroke()
+ const px = x + 12, pw = w - 24
+ if (!last) {
+ caps('LAST COMPACTION', px, y + 20)
+ font(12, 700); ctx.fillStyle = INK; ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic'
+ ctx.fillText('Waiting for the first one', px, y + 44)
+ font(10.5, 500); ctx.fillStyle = DIM
+ ctx.fillText('It fires when the tower passes', px, y + 62); ctx.fillText('the budget line, or press Compact now.', px, y + 76)
+ return h
+ }
+ caps(`LAST COMPACTION #${last.n}`, px, y + 20)
+ caps(last.trigger === 'manual' ? 'BY HAND' : 'BUDGET HIT', px + pw, y + 20, last.trigger === 'manual' ? '#5eead4' : FAINT, 9, 'right')
+ const red = '−' + fmtPct(last.reduction)
+ const redPx = fit(red, pw * 0.42, 22, 700, 12)
+ ctx.fillStyle = GREEN; ctx.textAlign = 'right'; ctx.textBaseline = 'alphabetic'
+ ctx.save(); ctx.shadowColor = GREEN; ctx.shadowBlur = 14; ctx.fillText(red, px + pw, y + 47); ctx.restore()
+ const redW = ctx.measureText(red).width
+ const span = `${fmtInt(last.before)} → ${fmtInt(last.after)}`
+ fit(span, pw - redW - 10, 15, 700, 9)
+ ctx.fillStyle = INK; ctx.textAlign = 'left'; ctx.fillText(span, px, y + 46)
+ // verdict bar
+ const total = Math.max(1, last.keep + last.trim + last.drop)
+ let bx = px
+ const by = y + 58
+ for (const [n, c] of [[last.keep, GREEN], [last.trim, AMBER], [last.drop, ROSE]]) {
+ const bw = (pw * n) / total
+ if (bw > 0.5) { ctx.fillStyle = c; ctx.fillRect(bx, by, Math.max(1, bw - 1.5), 9) }
+ bx += bw
+ }
+ font(10, 700); ctx.textBaseline = 'alphabetic'
+ ctx.textAlign = 'left'; ctx.fillStyle = GREEN; ctx.fillText(`KEEP ${last.keep}`, px, y + 82)
+ ctx.textAlign = 'center'; ctx.fillStyle = AMBER; ctx.fillText(`TRIM ${last.trim}`, px + pw / 2, y + 82)
+ ctx.textAlign = 'right'; ctx.fillStyle = ROSE; ctx.fillText(`DROP ${last.drop}`, px + pw, y + 82)
+ const okRecall = last.recall == null || last.recall >= S.cfg.recallTarget
+ meter(px, y + 101, pw, 'needle recall', last.recall, okRecall ? GREEN : last.recall >= S.cfg.recallTarget - 0.1 ? AMBER : ROSE)
+ meter(px, y + 119, pw, 'junk removed', last.junkRemoved, '#5eead4')
+ const line = `${fmtInt(last.questions)} questions · ${last.calls} call${last.calls === 1 ? '' : 's'} · ${fmtMs(last.ms)} · ${fmtUsd(last.costUsd)}`
+ fit(line, pw, 10.5, 600, 8); ctx.fillStyle = DIM; ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic'
+ ctx.fillText(line, px, y + 142)
+ if (extra) {
+ const bits = []
+ if (last.demoted) bits.push(`${last.demoted} squeezed to reach target`)
+ if (last.needlesDropped) bits.push(`${last.needlesDropped} needle${last.needlesDropped === 1 ? '' : 's'} dropped`)
+ if (last.junkKept) bits.push(`${last.junkKept} junk kept`)
+ const t = bits.join(' · ')
+ fit(t, pw, 10.5, 600, 8); ctx.fillStyle = AMBER; ctx.fillText(t, px, y + 160)
+ }
+ return h
+ }
+
+ function drawChart(x, y, w, h) {
+ if (h < 64 || w < 100) return
+ rr(x, y, w, h, 10); ctx.fillStyle = 'rgba(12,14,20,.7)'; ctx.fill(); ctx.strokeStyle = '#1d2230'; ctx.lineWidth = 1; ctx.stroke()
+ caps(w < 270 ? 'TOKENS' : 'TOKENS OVER TIME', x + 12, y + 18)
+ font(9, 600); ctx.textAlign = 'right'; ctx.textBaseline = 'alphabetic'
+ ctx.fillStyle = '#7c8aa8'; ctx.fillText('— summarize', x + w - 12, y + 18)
+ const sw = ctx.measureText('— summarize').width
+ ctx.fillStyle = GREEN; ctx.fillText('— Jev', x + w - 22 - sw, y + 18)
+ const pts = S.series
+ if (pts.length < 2) return
+ const gx = x + 12, gy = y + 28, gw = w - 24, gh = h - 38
+ const budget = S.cfg.budget
+ let max = budget * 1.12
+ for (const p of pts) max = Math.max(max, p[1], p[2])
+ const X = (i) => gx + (i / (pts.length - 1)) * gw
+ const Y = (v) => gy + gh - (v / max) * gh
+ ctx.save(); ctx.setLineDash([3, 4]); ctx.strokeStyle = 'rgba(251,191,36,.55)'; ctx.lineWidth = 1
+ ctx.beginPath(); ctx.moveTo(gx, Y(budget)); ctx.lineTo(gx + gw, Y(budget)); ctx.stroke(); ctx.restore()
+ ctx.strokeStyle = '#7c8aa8'; ctx.lineWidth = 1.2; ctx.globalAlpha = 0.85; ctx.beginPath()
+ pts.forEach((p, i) => (i ? ctx.lineTo(X(i), Y(p[2])) : ctx.moveTo(X(i), Y(p[2])))); ctx.stroke(); ctx.globalAlpha = 1
+ const fill = ctx.createLinearGradient(0, gy, 0, gy + gh)
+ fill.addColorStop(0, 'rgba(74,222,128,.28)'); fill.addColorStop(1, 'rgba(74,222,128,0)')
+ ctx.beginPath(); pts.forEach((p, i) => (i ? ctx.lineTo(X(i), Y(p[1])) : ctx.moveTo(X(i), Y(p[1]))))
+ ctx.lineTo(gx + gw, gy + gh); ctx.lineTo(gx, gy + gh); ctx.closePath(); ctx.fillStyle = fill; ctx.fill()
+ ctx.save(); ctx.shadowColor = GREEN; ctx.shadowBlur = 8; ctx.strokeStyle = GREEN; ctx.lineWidth = 1.6; ctx.beginPath()
+ pts.forEach((p, i) => (i ? ctx.lineTo(X(i), Y(p[1])) : ctx.moveTo(X(i), Y(p[1])))); ctx.stroke(); ctx.restore()
+ const lp = pts[pts.length - 1]
+ ctx.fillStyle = GREEN; ctx.beginPath(); ctx.arc(X(pts.length - 1), Y(lp[1]), 2.6, 0, Math.PI * 2); ctx.fill()
+ }
+
+ function draw(dt, now) {
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
+ ctx.clearRect(0, 0, W, H)
+ const budgetTarget = S.cfg.budget
+ budgetDisp += (budgetTarget - budgetDisp) * (1 - Math.exp(-dt * 9))
+ if (Math.abs(budgetTarget - budgetDisp) < 1) budgetDisp = budgetTarget
+
+ // odometer band geometry first: the baseline lane starts under it
+ const digits = Math.max(6, String(Math.round(Math.max(S.tokens, budgetTarget * 1.3))).length)
+ let odoPx = 92
+ while (odoPx > 22 && odoWidth(odoPx, digits) > L.odoW) odoPx -= 1
+ const bandTop = L.pad + 18
+ const bandBottom = bandTop + odoPx * 1.14 + 24
+ L.bTop = bandBottom + 46
+ L.bHb = (L.bBottom - L.bTop) * 0.84
+
+ stepLane(jevLane, dt, now, budgetDisp, L.top, L.bottom, L.Hb)
+ stepLane(baseLane, dt, now, budgetDisp, L.bTop, L.bBottom, L.bHb)
+
+ // scan line progress + triggers
+ let scanY = null
+ if (scan) {
+ const t = (now - scan.t0) / scan.dur
+ if (scan.y0 == null) scan.y0 = jevLane.topY - 8
+ scanY = scan.y0 + (L.bottom + 4 - scan.y0) * easeInOut(clamp(t, 0, 1))
+ for (const v of jevLane.order) if (v.pend && scanY >= v.y + v.h / 2) trigger(v, now, false)
+ if (t >= 1) { finishScan(now); scanY = null }
+ } else for (const v of jevLane.order) if (v.pend) trigger(v, now, true)
+
+ // ---- Jev lane ----
+ const { towerX, towerW, gaugeX, gaugeW, top, bottom, Hb } = L
+ const budgetY = bottom - Hb
+ caps(towerW < 270 ? 'JEV LANE' : 'CONTEXT WINDOW · JEV LANE', gaugeX, L.pad + 8)
+ if (S.totals.avgRecall != null) caps(`AVG RECALL ${fmtPct(S.totals.avgRecall)}`, towerX + towerW + 10, L.pad + 8, GREEN, 9, 'right')
+ // backdrop
+ ctx.fillStyle = 'rgba(255,255,255,.018)'; ctx.fillRect(towerX, top, towerW, bottom - top)
+ ctx.strokeStyle = 'rgba(255,255,255,.045)'; ctx.lineWidth = 1
+ font(8.5, 600); ctx.textAlign = 'right'; ctx.textBaseline = 'alphabetic'
+ for (const f of [0.1, 0.25, 0.5, 0.75]) {
+ const y = Math.round(bottom - Hb * axis(f)) + 0.5
+ ctx.beginPath(); ctx.moveTo(towerX, y); ctx.lineTo(towerX + towerW, y); ctx.stroke()
+ ctx.fillStyle = 'rgba(139,146,170,.5)'; ctx.fillText(fmtK(budgetDisp * f), towerX + towerW - 4, y - 3)
+ }
+ // gauge
+ const fillFrac = clamp(axis(jevLane.sumAt / budgetDisp), 0, (bottom - top) / Hb)
+ rr(gaugeX, top, gaugeW, bottom - top, 4); ctx.fillStyle = 'rgba(255,255,255,.05)'; ctx.fill()
+ const gg = ctx.createLinearGradient(0, bottom, 0, budgetY)
+ gg.addColorStop(0, '#15803d'); gg.addColorStop(0.7, GREEN); gg.addColorStop(0.92, AMBER); gg.addColorStop(1, ROSE)
+ ctx.save(); rr(gaugeX, top, gaugeW, bottom - top, 4); ctx.clip(); ctx.fillStyle = gg; ctx.fillRect(gaugeX, bottom - Hb * fillFrac, gaugeW, Hb * fillFrac); ctx.restore()
+
+ drawTower(jevLane, towerX, towerW, now, top, false)
+
+ // floor
+ const fl = ctx.createLinearGradient(towerX - 14, 0, towerX + towerW + 20, 0)
+ fl.addColorStop(0, 'rgba(74,222,128,0)'); fl.addColorStop(0.5, 'rgba(74,222,128,.7)'); fl.addColorStop(1, 'rgba(74,222,128,0)')
+ ctx.fillStyle = fl; ctx.fillRect(gaugeX - 4, bottom + 1, towerW + 44, 1.5)
+
+ drawLine(gaugeX - 2, towerX + towerW + 12, bottom - Hb * axis(S.cfg.target), 'rgba(74,222,128,.7)', `TARGET ${Math.round(S.cfg.target * 100)}%`, true, 'after')
+ const over = jevLane.sumAt > budgetDisp
+ drawLine(gaugeX - 2, towerX + towerW + 12, budgetY, over ? ROSE : AMBER, `BUDGET ${fmtK(budgetDisp)}`, false, 'after')
+
+ if (ghost) {
+ const t = (now - ghost.t0) / 4200
+ if (t >= 1) ghost = null
+ else { ctx.globalAlpha = t < 0.06 ? t / 0.06 : t > 0.65 ? 1 - (t - 0.65) / 0.35 : 1; drawLine(towerX, towerX + towerW, ghost.y, 'rgba(233,236,245,.55)', ghost.text, true, 'left'); ctx.globalAlpha = 1 }
+ }
+
+ // selection + hover
+ hoverId = mouse.x >= 0 ? hitTest() : null
+ wrap.classList.toggle('hot', hoverId != null)
+ for (const v of jevLane.order) {
+ if (v.id !== selectedId && v.id !== hoverId) continue
+ if (v.h <= 0 || now < v.born) continue
+ const sel = v.id === selectedId
+ ctx.save(); ctx.strokeStyle = sel ? '#fff' : 'rgba(255,255,255,.7)'; ctx.lineWidth = sel ? 2 : 1
+ if (sel) { ctx.shadowColor = '#fff'; ctx.shadowBlur = 12 }
+ const hh = Math.max(v.h, 3)
+ rr(towerX - 2, v.y + v.h / 2 - hh / 2 - 1, towerW + 4, hh + 2, 3); ctx.stroke(); ctx.restore()
+ if (sel) { ctx.fillStyle = '#fff'; ctx.beginPath(); const cy = v.y + v.h / 2; ctx.moveTo(towerX - 5, cy); ctx.lineTo(towerX - 11, cy - 4); ctx.lineTo(towerX - 11, cy + 4); ctx.closePath(); ctx.fill() }
+ }
+
+ // scan line
+ if (scan && now - scan.t0 < 260) {
+ ctx.fillStyle = `rgba(187,247,208,${0.22 * (1 - (now - scan.t0) / 260)})`
+ ctx.fillRect(towerX, jevLane.topY, towerW, bottom - jevLane.topY)
+ }
+ if (scanY != null) {
+ const x1 = gaugeX - 4, x2 = towerX + towerW + 14
+ const trail = ctx.createLinearGradient(0, scanY - 70, 0, scanY)
+ trail.addColorStop(0, 'rgba(74,222,128,0)'); trail.addColorStop(1, 'rgba(74,222,128,.22)')
+ ctx.fillStyle = trail; ctx.fillRect(x1, Math.max(top - 10, scanY - 70), x2 - x1, Math.min(70, scanY - top + 10))
+ ctx.save(); ctx.shadowColor = '#bbf7d0'; ctx.shadowBlur = 22; ctx.strokeStyle = '#ecfdf5'; ctx.lineWidth = 2.2
+ ctx.beginPath(); ctx.moveTo(x1, scanY); ctx.lineTo(x2, scanY); ctx.stroke(); ctx.restore()
+ }
+
+ // chips
+ chips = chips.filter((c) => now - c.t0 < 1150)
+ for (const c of chips) {
+ const t = (now - c.t0) / 1150
+ const a = t < 0.08 ? t / 0.08 : t > 0.6 ? 1 - (t - 0.6) / 0.4 : 1
+ const x = L.chipX + t * 10
+ ctx.globalAlpha = a
+ ctx.strokeStyle = c.color; ctx.lineWidth = 1
+ ctx.beginPath(); ctx.moveTo(L.stripX + L.stripW + 1, c.y); ctx.lineTo(x, c.y); ctx.stroke()
+ font(9.5, 700)
+ const tw = ctx.measureText(c.text).width + 12
+ rr(x, c.y - 7.5, tw, 15, 7.5); ctx.fillStyle = 'rgba(6,8,12,.9)'; ctx.fill(); ctx.stroke()
+ ctx.fillStyle = c.color; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText(c.text, x + 6, c.y + 0.5)
+ if (c.squeezed) { ctx.fillStyle = AMBER; ctx.beginPath(); ctx.arc(x + tw + 5, c.y, 2.2, 0, Math.PI * 2); ctx.fill() }
+ }
+ ctx.globalAlpha = 1
+
+ // ---- odometer band ----
+ const mx = L.midX
+ caps('TOKENS IN CONTEXT', mx, L.pad + 8)
+ const phase = scan ? 'JEV IS JUDGING EVERY TOOL RESULT' : !S.running ? 'PAUSED' : S.phase === 'hold' ? 'COMPACTED' : 'FILLING'
+ caps(phase, W - L.pad, L.pad + 8, scan ? GREEN : !S.running ? AMBER : S.phase === 'hold' ? GREEN : FAINT, 9, 'right')
+ // odometer value
+ const prev = odo.v
+ if (odo.tween) {
+ const t = clamp((now - odo.tween.t0) / odo.tween.dur, 0, 1)
+ odo.v = odo.tween.from + (odo.tween.to - odo.tween.from) * easeInOut(t)
+ odo.hot += (1 - odo.hot) * (1 - Math.exp(-dt * 10))
+ if (t >= 1) { odo.v = odo.tween.to; odo.tween = null }
+ } else {
+ odo.v += (S.tokens - odo.v) * (1 - Math.exp(-dt * 9))
+ if (Math.abs(S.tokens - odo.v) < 0.6) odo.v = S.tokens
+ odo.hot += (0 - odo.hot) * (1 - Math.exp(-dt * 2.2))
+ }
+ const inst = dt > 0 ? (odo.v - prev) / dt : 0
+ odo.speed += (inst - odo.speed) * 0.5
+ drawOdometer(mx, bandTop, odoPx, Math.max(0, odo.v), odo.speed, digits, now, odo.hot)
+ font(11, 600); ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic'; ctx.fillStyle = DIM
+ const curTask = S.tasks.find((t) => t.id === S.currentTask)
+ const sub = `of ${fmtInt(budgetTarget)} budget · task: ${curTask?.id ?? ''}`
+ fit(sub, L.odoW, 11, 600, 8); ctx.fillStyle = DIM
+ ctx.fillText(sub, mx, bandBottom - 4)
+
+ // ---- card + chart ----
+ const cardY = bandBottom + 10
+ const cardH = drawCard(mx, cardY, L.midW, now)
+ const chartY = cardY + cardH + 10
+ drawChart(mx, chartY, L.midW, bottom - chartY)
+
+ // ---- baseline lane ----
+ const bx = L.baseX, bw = L.baseW
+ caps('SUMMARIZE INSTEAD', bx + bw, bandBottom + 18, '#aab3c8', 9, 'right', bw + 12)
+ caps('SIMPLE BASELINE', bx + bw, bandBottom + 30, FAINT, 8, 'right', bw + 12)
+ caps(S.baseline.avgRecall == null ? 'NO FOLD YET' : `AVG RECALL ${fmtPct(S.baseline.avgRecall, 0)}`, bx + bw, bandBottom + 42, S.baseline.avgRecall == null ? FAINT : ROSE, 8.5, 'right', bw + 12)
+ ctx.fillStyle = 'rgba(255,255,255,.018)'; ctx.fillRect(bx, L.bTop, bw, L.bBottom - L.bTop)
+ drawTower(baseLane, bx, bw, now, L.bTop, true)
+ ctx.fillStyle = 'rgba(148,163,184,.5)'; ctx.fillRect(bx - 12, L.bBottom + 1, bw + 16, 1.5)
+ drawLine(bx - 12, bx + bw + 4, L.bBottom - L.bHb, 'rgba(251,191,36,.8)', null, false)
+
+ // particles
+ particles = particles.filter((p) => p.life < p.max)
+ ctx.globalCompositeOperation = 'lighter'
+ for (const p of particles) {
+ p.life += dt; p.vy += 260 * dt; p.x += p.vx * dt; p.y += p.vy * dt
+ ctx.globalAlpha = clamp(1 - p.life / p.max, 0, 1)
+ ctx.fillStyle = p.color; ctx.fillRect(p.x, p.y, p.size, p.size)
+ }
+ ctx.globalCompositeOperation = 'source-over'
+ ctx.globalAlpha = 1
+
+ // floaters
+ floaters = floaters.filter((f) => now - f.t0 < 2600)
+ for (const f of floaters) {
+ const t = (now - f.t0) / 2600
+ if (t < 0) continue
+ ctx.globalAlpha = t < 0.1 ? t / 0.1 : 1 - Math.max(0, t - 0.6) / 0.4
+ font(f.big ? 12.5 : 10, 700)
+ const tw = ctx.measureText(f.text).width + 12
+ const fx = clamp(f.x - tw / 2, 4, W - tw - 4), fy = f.y - t * 26
+ const fh = f.big ? 24 : 18
+ rr(fx, fy - fh / 2, tw, fh, 7); ctx.fillStyle = 'rgba(6,8,12,.92)'; ctx.fill(); ctx.strokeStyle = f.color; ctx.lineWidth = 1
+ if (f.big) { ctx.save(); ctx.shadowColor = f.color; ctx.shadowBlur = 16; ctx.stroke(); ctx.restore() } else ctx.stroke()
+ ctx.fillStyle = f.color; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText(f.text, fx + 6, fy + 0.5)
+ }
+ ctx.globalAlpha = 1
+
+ // ---- legend ----
+ let lx = gaugeX
+ const ly = H - 10
+ font(9.5, 600); ctx.textBaseline = 'middle'; ctx.textAlign = 'left'
+ for (let k = 0; k < 7; k++) {
+ ctx.fillStyle = KIND_COLORS[k]; rr(lx, ly - 4, 8, 8, 2); ctx.fill()
+ ctx.fillStyle = DIM; ctx.fillText(KIND_NAMES[k], lx + 12, ly + 0.5)
+ lx += 12 + ctx.measureText(KIND_NAMES[k]).width + 12
+ }
+ const truthLegend = [[GREEN, 'truth: needed now'], ['#3a2430', 'not needed']]
+ let need = 0
+ for (const [, t] of truthLegend) need += 12 + ctx.measureText(t).width + 12
+ if (lx + 10 + need < W - L.pad) {
+ lx += 10
+ for (const [c, t] of truthLegend) {
+ ctx.fillStyle = c; ctx.fillRect(lx, ly - 5, 5, 10)
+ ctx.fillStyle = DIM; ctx.fillText(t, lx + 9, ly + 0.5)
+ lx += 12 + ctx.measureText(t).width + 12
+ }
+ }
+
+ // hover tip
+ if (hoverId != null) {
+ const v = jevLane.map.get(hoverId)
+ if (v) {
+ const text = `${KIND_NAMES[v.kind]} ${v.label} · ${fmtInt(v.tokens)} tok${v.pinned ? ' · pinned' : ''}`
+ font(10.5, 600)
+ const tw = Math.min(ctx.measureText(text).width + 14, W - 20)
+ const tx = clamp(mouse.x + 14, 4, W - tw - 4), ty = clamp(mouse.y - 24, 4, H - 24)
+ rr(tx, ty, tw, 19, 6); ctx.fillStyle = 'rgba(8,10,16,.95)'; ctx.fill(); ctx.strokeStyle = '#2e3550'; ctx.lineWidth = 1; ctx.stroke()
+ ctx.fillStyle = INK; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText(text, tx + 7, ty + 10)
+ }
+ }
+ }
+
+ function loop() {
+ const now = performance.now()
+ const dt = Math.min(0.05, (now - lastT) / 1000)
+ lastT = now
+ if (S && L && W > 0) { try { draw(dt, now) } catch (e) { console.error(e) } }
+ requestAnimationFrame(loop)
+ }
+
+ resize()
+ connect()
+ requestAnimationFrame(loop)
+})()
diff --git a/store/agents/jev-compactor/viewer/viewer.mjs b/store/agents/jev-compactor/viewer/viewer.mjs
new file mode 100644
index 000000000..ac5063ab7
--- /dev/null
+++ b/store/agents/jev-compactor/viewer/viewer.mjs
@@ -0,0 +1,765 @@
+// Jev Compactor viewer — a loopback server that runs a made-up coding-agent session and lets Jev
+// (TypeSafe's System One model) compact its context window.
+//
+// A seeded generator streams events into a context window: user messages, assistant messages and
+// tool results (Read, Grep, Bash, Edit, WebFetch). Every tool result secretly belongs to one task,
+// or is pure junk (logs, lockfiles, test spam). That hidden label is the ground truth.
+//
+// When the window passes the budget (or the person presses "Compact now"), Jev judges EVERY tool
+// result in as few calls as possible: state = the current task plus the last few messages, and one
+// `choice` question per tool result (keep / trim / drop), 100 questions per call. The verdicts are
+// applied, and the result is measured against the ground truth: needle recall, junk removed,
+// tokens before and after, questions, calls, time and cost.
+//
+// A second lane runs a simple baseline for contrast ("summarize instead"): when over budget it
+// folds the oldest half of its window into one short summary block. It is a toy baseline, not a
+// measurement of any real product.
+//
+// Everything here is synthetic. It is a demo of the idea, not a real compaction plugin.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds session.json (watched live).
+
+import { mkdirSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, jev, toWire, hash01, stems, PRICE_PER_MTOK } from '../toolchain/jev.mjs'
+import { serveViewer, writeVerdict, watchConfig, mulberry32, clean } from './kit.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+
+export const KINDS = ['user', 'assistant', 'Read', 'Grep', 'Bash', 'Edit', 'WebFetch', 'summary']
+const TOOLS = ['Read', 'Grep', 'Bash', 'Edit', 'WebFetch']
+const VERDICTS = ['keep', 'trim', 'drop']
+const CHUNK = 100 // questions per Jev call
+const GIST_TOKENS = 300 // for a "gist" result, only about this many tokens at the head matter
+const WEAK_PREVIEW = 0.04 // share of real results whose preview shows only boilerplate
+const RECENT_MESSAGES = 6 // how many messages go into the shared state
+const HOLD_MS = 2400 // after a compaction the stream waits, so the pane can show it
+
+export const DEFAULT = {
+ title: 'Jev Compactor',
+ description: 'A made-up coding-agent session. Jev judges every tool result and compacts the context in one pass.',
+ repo: 'harbor-pay',
+ seed: 7,
+ budget: 200000,
+ trimTo: 400,
+ distraction: 0.12,
+ eventsPerSec: 4,
+ noise: 0.45,
+ focus: 0.5,
+ target: 0.4,
+ recallTarget: 0.9,
+ summaryTokens: 1500,
+ taskEvery: 200,
+ mix: { user: 1, assistant: 2, Read: 7, Grep: 3, Bash: 6, Edit: 3, WebFetch: 2 },
+ currentTask: 'refunds',
+ tasks: [
+ { id: 'refunds', title: 'Fix refund rounding in the ledger', vocabulary: ['refund', 'ledger', 'rounding', 'cents', 'reversal', 'chargeback', 'currency', 'decimal', 'balance', 'payout'] },
+ { id: 'webhooks', title: 'Retry failed webhook deliveries', vocabulary: ['webhook', 'delivery', 'retry', 'backoff', 'signature', 'endpoint', 'queue', 'deadletter', 'idempotency', 'timeout'] },
+ { id: 'sessions', title: 'Rotate login sessions safely', vocabulary: ['session', 'rotate', 'expiry', 'cookie', 'login', 'oauth', 'scope', 'revoke', 'credential', 'passkey'] },
+ { id: 'search', title: 'Speed up invoice search', vocabulary: ['invoice', 'search', 'index', 'query', 'pagination', 'filter', 'cursor', 'latency', 'cache', 'ranking'] },
+ ],
+}
+
+// Token size per kind: lo * (hi/lo)^(u^skew). Skew > 1 means most results are small, a few are huge.
+const SIZE = {
+ user: [30, 260, 1], assistant: [60, 700, 1.2],
+ Read: [400, 9000, 1.6], Grep: [250, 5000, 1.4], Bash: [300, 16000, 1.7], Edit: [200, 1800, 1], WebFetch: [1500, 30000, 1.5],
+ junk: [600, 40000, 1.2],
+}
+const NEED = { Read: 'detail', Edit: 'detail', Grep: 'gist', Bash: 'gist', WebFetch: 'gist' }
+
+const OPTIONS = {
+ keep: 'still needed for the current task, keep it word for word: source code, diffs and exact values about the current task',
+ trim: 'about the current task but only the gist matters now, keep the head: long test output, search listings, docs pages',
+ drop: 'irrelevant now: other tasks, install logs, lockfiles, generated files, test spam, anything not about the current task',
+}
+
+const clampN = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+const fmt = (n) => Math.round(n).toLocaleString('en-US')
+const pct = (v) => (v == null ? 'n/a' : `${(v * 100).toFixed(1)}%`)
+const plural = (n, word) => `${fmt(n)} ${word}${n === 1 ? '' : 's'}`
+
+// ---------------------------------------------------------------------------
+// Config: merge over defaults, clamp every number, never throw.
+// ---------------------------------------------------------------------------
+export function normalize(raw = {}) {
+ const problems = []
+ const num = (key, lo, hi) => {
+ const v = raw[key]
+ if (v === undefined) return DEFAULT[key]
+ if (typeof v !== 'number' || !Number.isFinite(v)) { problems.push(`${key} must be a number`); return DEFAULT[key] }
+ if (v < lo || v > hi) problems.push(`${key} ${v} is outside ${lo}..${hi}, clamped`)
+ return clampN(v, lo, hi)
+ }
+ const cfg = {
+ title: typeof raw.title === 'string' && raw.title ? clean(raw.title).slice(0, 80) : DEFAULT.title,
+ description: typeof raw.description === 'string' ? clean(raw.description).slice(0, 300) : DEFAULT.description,
+ repo: typeof raw.repo === 'string' && raw.repo ? clean(raw.repo).slice(0, 40) : DEFAULT.repo,
+ seed: Math.round(num('seed', 0, 2 ** 31 - 1)),
+ budget: Math.round(num('budget', 20000, 2000000)),
+ trimTo: Math.round(num('trimTo', 50, 5000)),
+ distraction: num('distraction', 0, 1),
+ eventsPerSec: num('eventsPerSec', 1, 60),
+ noise: num('noise', 0, 0.9),
+ focus: num('focus', 0.1, 1),
+ target: num('target', 0.2, 0.9),
+ recallTarget: num('recallTarget', 0.5, 1),
+ summaryTokens: Math.round(num('summaryTokens', 200, 20000)),
+ taskEvery: Math.round(num('taskEvery', 0, 5000)),
+ }
+ // tasks
+ let tasks = []
+ if (raw.tasks !== undefined && !Array.isArray(raw.tasks)) problems.push('tasks must be a list')
+ for (const t of Array.isArray(raw.tasks) ? raw.tasks : []) {
+ const id = typeof t?.id === 'string' ? t.id.trim().slice(0, 24) : ''
+ const words = Array.isArray(t?.vocabulary) ? [...new Set(t.vocabulary.filter((w) => typeof w === 'string').map((w) => w.toLowerCase().replace(/[^a-z0-9]+/g, '')).filter((w) => w.length > 1))] : []
+ if (!id || words.length < 3) { problems.push(`task "${id || '?'}" needs an id and at least 3 vocabulary words, skipped`); continue }
+ if (tasks.some((x) => x.id === id)) { problems.push(`task id "${id}" is used twice, skipped`); continue }
+ tasks.push({ id, title: typeof t.title === 'string' && t.title ? clean(t.title).slice(0, 80) : id, vocabulary: words.slice(0, 40) })
+ }
+ tasks = tasks.slice(0, 12)
+ if (tasks.length < 2) {
+ if (raw.tasks !== undefined) problems.push('need at least 2 valid tasks, using the built-in ones')
+ tasks = DEFAULT.tasks.map((t) => ({ ...t, vocabulary: [...t.vocabulary] }))
+ }
+ cfg.tasks = tasks
+ cfg.currentTask = tasks.some((t) => t.id === raw.currentTask) ? raw.currentTask : tasks[0].id
+ if (raw.currentTask !== undefined && cfg.currentTask !== raw.currentTask) problems.push(`currentTask "${raw.currentTask}" is not a task id, using "${cfg.currentTask}"`)
+ // event mix
+ const mix = {}
+ const rawMix = raw.mix && typeof raw.mix === 'object' && !Array.isArray(raw.mix) ? raw.mix : {}
+ for (const k of Object.keys(DEFAULT.mix)) {
+ const v = rawMix[k]
+ mix[k] = typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(v, 1000) : DEFAULT.mix[k]
+ if (v !== undefined && mix[k] !== v) problems.push(`mix.${k} must be a number from 0 up`)
+ }
+ if (!TOOLS.some((k) => mix[k] > 0)) { problems.push('mix needs at least one tool with weight above 0'); Object.assign(mix, DEFAULT.mix) }
+ cfg.mix = mix
+ return { cfg, problems }
+}
+
+// ---------------------------------------------------------------------------
+// The offline stand-in for Jev. It reads ONLY what live Jev gets: the shared state text and the
+// question text. It counts how many words of the tool result's preview also appear in the current
+// task (title + keywords, and the recent messages at a lower weight), and looks at the shape of the
+// text (code-like, or bulk output) to split keep from trim. No hidden labels are read here.
+// ---------------------------------------------------------------------------
+const DETAIL_CUES = new Set(['function', 'const', 'return', 'export', 'throw', 'class', 'interface', 'import'])
+const BULK_CUES = new Set(['match', 'matches', 'passed', 'pass', 'tests', 'test', 'lines', 'output', 'page', 'docs', 'sections', 'words', 'warn', 'debug', 'info', 'packages', 'log', 'layer'])
+const KIND_PRIOR = { Read: 0.6, Edit: 1.2, Grep: -1.0, Bash: -1.0, WebFetch: -1.2 }
+const sigmoid = (x) => 1 / (1 + Math.exp(-x))
+
+let ctxCacheKey = null, ctxCache = null
+function readState(text) {
+ if (text === ctxCacheKey) return ctxCache
+ const task = /CURRENT TASK:\s*(.*)/.exec(text)?.[1] ?? ''
+ const keys = /TASK KEYWORDS:\s*(.*)/.exec(text)?.[1] ?? ''
+ const recent = text.split('RECENT MESSAGES:')[1] ?? ''
+ const strong = new Set(stems(`${task} ${keys}`))
+ const weak = new Set(stems(recent).filter((w) => !strong.has(w)))
+ ctxCacheKey = text; ctxCache = { strong, weak }
+ return ctxCache
+}
+
+export function compactorMock(stateText, id, q) {
+ if (q.type !== 'choice' || !q.options?.includes('keep')) return null
+ const m = /^\[(\w+)\]\s+(.*?)\s+·\s+([\d,]+) tokens\. Preview: «([\s\S]*?)»/.exec(q.instructions ?? '')
+ if (!m) return null
+ const kind = m[1], tokens = Number(m[3].replace(/,/g, '')), body = `${m[2]} ${m[4]}`
+ const { strong, weak } = readState(stateText)
+ const words = new Set(stems(body))
+ let hits = 0, detail = 0, bulk = 0
+ for (const w of words) {
+ if (strong.has(w)) hits += 1
+ else if (weak.has(w)) hits += 0.15
+ }
+ for (const w of String(m[4]).toLowerCase().split(/[^a-z]+/)) {
+ if (DETAIL_CUES.has(w)) detail++
+ else if (BULK_CUES.has(w)) bulk++
+ }
+ const j1 = (hash01(`${id}|${m[4].slice(0, 80)}`, 11) - 0.5) * 0.5
+ const j2 = (hash01(`${id}|${m[4].slice(0, 80)}`, 29) - 0.5) * 0.5
+ const pRel = sigmoid(1.3 * (hits - 2.6) + j1)
+ const pKeepIfRel = sigmoid(0.9 * (Math.min(detail, 5) - Math.min(bulk, 5)) + (KIND_PRIOR[kind] ?? 0) - (tokens > 12000 ? 0.5 : 0) + j2)
+ let p = [pRel * pKeepIfRel, pRel * (1 - pKeepIfRel), 1 - pRel].map((v) => Math.max(0.012, v))
+ const sum = p[0] + p[1] + p[2]
+ p = p.map((v) => v / sum)
+ const bi = p.indexOf(Math.max(...p))
+ return { type: 'choice', choice: VERDICTS[bi], confidence: p[bi], probabilities: { keep: p[0], trim: p[1], drop: p[2] } }
+}
+
+// ---------------------------------------------------------------------------
+// Text generation. Real results are written with the words of their task. Junk is written with
+// junk words, and borrows words of the current task with probability `distraction`.
+// ---------------------------------------------------------------------------
+const JUNK_WORDS = ['inflight', 'rimraf', 'glob', 'chalk', 'yargs', 'minimist', 'semver', 'lodash', 'uuid', 'mkdirp', 'ansi', 'kleur', 'picocolors', 'tslib', 'wrappy', 'once', 'brace', 'concat', 'isarray', 'supports', 'escape', 'strip', 'emoji', 'polyfill', 'shim', 'legacy', 'vendor', 'bundle', 'chunk', 'runtime']
+
+function makeTexts(kind, rng, w, n) {
+ const N = (lo, hi) => Math.round(lo + rng() * (hi - lo))
+ switch (kind) {
+ case 'Read': { const a = w(), b = w(), c = w(), d = w()
+ return { label: `src/${a}/${b}_${c}.ts`, preview: `export function apply_${a}(${b}, ${c}) { const ${d} = ${w()}.${w()}_${w()}(${b}); if (!${d}) throw new Error("bad ${w()}"); return ${d} }` } }
+ case 'Edit': { const a = w(), b = w(), c = w(), d = w()
+ return { label: `src/${a}/${b}.ts`, preview: `@@ -${N(20, 400)},7 +${N(20, 400)},9 @@ function ${a}_${b}(${c}) { - return ${c}.${w()} + const ${d} = ${c}.${w()}(${w()}); + return ${d} // fix ${w()}` } }
+ case 'Grep': { const a = w()
+ return { label: `grep "${a}" src/`, preview: `${N(8, 90)} matches for "${a}" in src/: src/${w()}/${w()}.ts:${N(3, 400)} ${w()}_${w()} · src/${w()}/${w()}.ts:${N(3, 400)} ${w()} · test/${w()}.test.ts:${N(3, 200)} … ${fmt(n / 9)} more lines` } }
+ case 'Bash': { const a = w(), b = w()
+ return { label: `npm test -- ${a}`, preview: `PASS test/${a}/${b}_${w()}.test.ts (${N(20, 900)} ms) ✓ ${w()} ${w()} ✓ ${w()} handles ${w()} ✓ ${w()} edge case · Tests: ${N(6, 80)} passed · output ${fmt(n / 9)} lines` } }
+ default: { const a = w(), b = w()
+ return { label: `https://docs.example.test/${a}/${b}`, preview: `Docs page: ${a} ${b} guide. Overview of ${w()}, ${w()} and ${w()}. Sections: ${w()}, ${w()}, ${w()}. Page text ${fmt(n * 0.7)} words` } }
+ }
+}
+
+function makeWeak(kind, w) {
+ if (kind === 'Read' || kind === 'Edit') return { label: `src/${w()}/index.ts`, preview: '// Copyright (c) Example Co. SPDX-License-Identifier: MIT · import { z } from "zod" · import { db } from "../db" · import type { Ctx } from "../ctx" · (the useful part is further down)' }
+ if (kind === 'WebFetch') return { label: `https://docs.example.test/${w()}`, preview: 'Skip to content · Docs home · Version 4.2 · On this page · Edit this page · Was this helpful? · (the useful part is further down)' }
+ return { label: kind === 'Grep' ? `grep "${w()}" .` : 'npm test', preview: '> [email protected] pretest · tsc --noEmit · > [email protected] test · vitest run --reporter=basic · (the useful part is further down)' }
+}
+
+function makeJunk(kind, rng, j, n) {
+ const N = (lo, hi) => Math.round(lo + rng() * (hi - lo))
+ const v = Math.floor(rng() * 2)
+ if (kind === 'Read') {
+ return v === 0
+ ? { label: 'package-lock.json', preview: `"node_modules/${j()}-${j()}": { "version": "4.3.0", "resolved": "https://registry.example.test/${j()}/-/${j()}-4.3.0.tgz", "integrity": "sha512-Qm9x" }, "node_modules/${j()}-${j()}": { "version": "2.0.1", "dev": true, "requires": { "${j()}": "^1.2.0", "${j()}": "^3.0.0" } }` }
+ : { label: 'dist/vendor.min.js', preview: `!function(e,t){"use strict";var ${j()}=function(${j()}){return ${j()}.default};const ${j()}=t.${j()};export function ${j()}(${j()},${j()}){return e}}(this)` }
+ }
+ if (kind === 'Bash') {
+ return v === 0
+ ? { label: 'npm install', preview: `npm WARN deprecated ${j()}@1.0.6 · npm WARN deprecated ${j()}-${j()}@2.7.1 · added ${fmt(N(400, 1900))} packages in ${N(9, 80)}s · postinstall ${j()} ${j()} ok · audited ${j()} ${j()} ${j()} · ${N(40, 300)} packages are looking for funding` }
+ : { label: 'npm test -- legacy', preview: `PASS test/legacy/${j()}_${j()}.test.ts ✓ handles empty ${j()} (2 ms) ✓ handles null ${j()} ✓ snapshot ${j()} · console.log DEBUG heartbeat ${j()} ${j()} ${j()} · Tests: ${fmt(N(600, 2400))} passed · output ${fmt(n / 9)} lines` }
+ }
+ if (kind === 'Grep') return { label: 'grep -r "TODO" .', preview: `${fmt(N(900, 6000))} matches in node_modules/: node_modules/${j()}/lib/${j()}.js:12 · node_modules/${j()}/${j()}.js:88 · node_modules/${j()}/dist/${j()}.cjs:4 · ${j()} ${j()} … ${fmt(n / 9)} more lines` }
+ if (kind === 'Edit') return { label: 'src/gen/schema.generated.ts', preview: `// AUTO-GENERATED, do not edit. export interface ${j()}_row { ${j()}: string; ${j()}: number; ${j()}: string | null } export const ${j()}_columns = ["${j()}", "${j()}", "${j()}"] as const` }
+ return { label: 'https://blog.example.test/changelog', preview: `Skip to content · Accept cookies · Sign in · Pricing · Careers · Popular posts: ${j()} ${j()} · ${j()} ${j()} · ${j()} ${j()} · Newsletter ${j()} ${j()} · © Example Co` }
+}
+
+const USER_LINES = [
+ (w) => `Can you look at the ${w()} ${w()}? The ${w()} is wrong when the ${w()} changes.`,
+ (w) => `The ${w()} still fails for ${w()}. Please check how ${w()} reaches the ${w()}.`,
+ (w) => `Good. Now cover the ${w()} path too, and keep the ${w()} ${w()} as it is.`,
+]
+const ASSISTANT_LINES = [
+ (w) => `I will open the ${w()} ${w()} code and trace how the ${w()} reaches the ${w()}.`,
+ (w) => `Found it: the ${w()} skips the ${w()} step. I will patch the ${w()} and rerun the ${w()} checks.`,
+ (w) => `The ${w()} ${w()} now holds. Next I will confirm the ${w()} against the ${w()}.`,
+ (w) => `Reading more of the ${w()} module to see where ${w()} and ${w()} meet.`,
+]
+
+// ---------------------------------------------------------------------------
+// The viewer
+// ---------------------------------------------------------------------------
+export async function startCompactorViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+ const file = join(workspace, 'session.json')
+
+ // Every `let` lives here, above the first call that can touch it (TDZ guard).
+ let cfg = normalize({}).cfg
+ let cfgProblems = []
+ let overrides = {} // runtime changes from the pane: { budget, distraction, task }
+ let rng = mulberry32(1)
+ let nextId = 1
+ let eventNo = 0
+ let currentTask = cfg.tasks[0].id
+ let taskSince = 0 // event number when the current task became current
+ let window_ = [] // Jev lane, oldest first
+ let base = [] // baseline lane, oldest first
+ let graveyard = new Map() // recently removed blocks, for the inspector
+ let tokens = 0, baseTokens = 0
+ let running = true
+ let stopped = false
+ let busy = false
+ let phase = 'filling'
+ let holdUntil = 0
+ let timer = null
+ let error = null // Jev call error
+ let last = null // last compaction (Jev lane)
+ let history = []
+ let totals = null
+ let baseStats = null
+ let series = []
+ let salt = 1
+ let client = process.env.TYPESAFE_API_KEY ? 'typesafe' : 'mock'
+ let lastBroadcast = 0, broadcastTimer = null
+ let lastVerdictWrite = 0
+ let rolledOff = 0
+ let view = null
+ let pinned = new Set()
+ let gen = 0 // bumps on every session reset, so a late Jev answer is ignored
+ let retryAt = 0 // after a failed Jev call, wait a little before asking again
+
+ const eff = (k) => (overrides[k] !== undefined ? overrides[k] : cfg[k])
+ const taskOf = (id) => cfg.tasks.find((t) => t.id === id) ?? cfg.tasks[0]
+ const taskIdx = (id) => cfg.tasks.findIndex((t) => t.id === id)
+
+ function freshTotals() {
+ return { compactions: 0, questions: 0, calls: 0, costUsd: 0, inputTokens: 0, ms: 0, needleBefore: 0, needleAfter: 0, junkBefore: 0, junkAfter: 0, tokensBefore: 0, tokensAfter: 0, demoted: 0 }
+ }
+ function freshBase() {
+ return { compactions: 0, needleBefore: 0, needleAfter: 0, lastRecall: null, lastBefore: 0, lastAfter: 0, lastAt: 0, n: 0 }
+ }
+
+ function applyConfig(raw, parseErr) {
+ const before = cfg
+ const r = normalize(raw)
+ cfg = r.cfg
+ cfgProblems = parseErr ? [parseErr] : r.problems
+ overrides = {}
+ const structural = !before || before.seed !== cfg.seed || before.repo !== cfg.repo || JSON.stringify(before.tasks) !== JSON.stringify(cfg.tasks) || JSON.stringify(before.mix) !== JSON.stringify(cfg.mix)
+ if (structural || !totals) resetSession()
+ else if (cfg.currentTask !== currentTask && before.currentTask !== cfg.currentTask) switchTask(cfg.currentTask, 'config')
+ }
+
+ function resetSession() {
+ gen++
+ rng = mulberry32(cfg.seed || 1)
+ nextId = 1; eventNo = 0
+ window_ = []; base = []; graveyard = new Map(); pinned = new Set()
+ tokens = 0; baseTokens = 0
+ last = null; history = []; series = []
+ totals = freshTotals(); baseStats = freshBase()
+ error = null; phase = 'filling'; holdUntil = 0; rolledOff = 0
+ currentTask = cfg.tasks.some((t) => t.id === overrides.task) ? overrides.task : cfg.currentTask
+ taskSince = 0
+ addEvent(makeMessage('user', `Session start in the made-up repo "${cfg.repo}". First task: ${taskOf(currentTask).title}.`))
+ // Start with the tank partly full so the first compaction is only a few seconds away.
+ let guard = 0
+ while (tokens < eff('budget') * 0.62 && guard++ < 5000) addEvent(genEvent())
+ }
+
+ // ---- generation --------------------------------------------------------
+ function sizeOf(key) {
+ const [lo, hi, skew] = SIZE[key]
+ return Math.round(lo * (hi / lo) ** (rng() ** skew))
+ }
+ function wordsOf(task) { const v = task.vocabulary; return () => v[Math.floor(rng() * v.length)] }
+
+ function makeMessage(kind, text) {
+ const task = taskOf(currentTask)
+ const w = wordsOf(task)
+ const lines = kind === 'user' ? USER_LINES : ASSISTANT_LINES
+ const preview = text ?? lines[Math.floor(rng() * lines.length)](w)
+ return { id: nextId++, kind, label: kind === 'user' ? 'user message' : 'assistant message', preview, tokens: sizeOf(kind), orig: 0, task: task.id, need: 'message', needle: 0, verdict: null, probs: null, demoted: false, born: eventNo }
+ }
+
+ function genEvent() {
+ const mix = cfg.mix
+ const keys = Object.keys(mix)
+ const total = keys.reduce((a, k) => a + mix[k], 0)
+ let r = rng() * total, kind = keys[keys.length - 1]
+ for (const k of keys) { r -= mix[k]; if (r < 0) { kind = k; break } }
+ if (kind === 'user' || kind === 'assistant') return makeMessage(kind)
+ const cur = taskOf(currentTask)
+ const isJunk = rng() < cfg.noise
+ if (isJunk) {
+ const n = sizeOf('junk')
+ const borrow = eff('distraction')
+ const cw = wordsOf(cur)
+ const j = () => (rng() < borrow ? cw() : JUNK_WORDS[Math.floor(rng() * JUNK_WORDS.length)])
+ const t = makeJunk(kind, rng, j, n)
+ return { id: nextId++, kind, label: t.label, preview: t.preview, tokens: n, orig: n, task: null, need: 'none', needle: 0, verdict: null, probs: null, demoted: false, born: eventNo }
+ }
+ const others = cfg.tasks.filter((t) => t.id !== cur.id)
+ const task = rng() < cfg.focus || !others.length ? cur : others[Math.floor(rng() * others.length)]
+ const n = sizeOf(kind)
+ const w = wordsOf(task)
+ const t = rng() < WEAK_PREVIEW ? makeWeak(kind, w) : makeTexts(kind, rng, w, n)
+ const need = NEED[kind]
+ return { id: nextId++, kind, label: t.label, preview: t.preview, tokens: n, orig: n, task: task.id, need, needle: need === 'detail' ? n : Math.min(n, GIST_TOKENS), verdict: null, probs: null, demoted: false, born: eventNo }
+ }
+
+ function addEvent(b) {
+ eventNo++
+ window_.push(b); tokens += b.tokens
+ base.push({ id: b.id, kind: b.kind, tokens: b.tokens, needle: b.task && b.needle ? { [b.task]: b.needle } : {} })
+ baseTokens += b.tokens
+ // Messages are never judged. Very old ones roll off the bottom so the demo can run forever.
+ const msgCap = eff('budget') * 0.05
+ let msgTokens = 0
+ for (const x of window_) if (x.need === 'message') msgTokens += x.tokens
+ while (msgTokens > msgCap) {
+ const i = window_.findIndex((x) => x.need === 'message')
+ if (i < 0) break
+ const [gone] = window_.splice(i, 1)
+ msgTokens -= gone.tokens; tokens -= gone.tokens; rolledOff++
+ bury(gone, 'rolled off (very old message)')
+ }
+ if (baseTokens > eff('budget')) baselineSummarize()
+ pushSeries()
+ }
+
+ function pushSeries() {
+ series.push([eventNo, tokens, baseTokens])
+ if (series.length > 360) series.splice(0, series.length - 360)
+ }
+
+ function bury(b, why) {
+ graveyard.set(b.id, { ...b, gone: why })
+ if (graveyard.size > 600) graveyard.delete(graveyard.keys().next().value)
+ }
+
+ function switchTask(id, by) {
+ if (!cfg.tasks.some((t) => t.id === id) || id === currentTask) return false
+ currentTask = id
+ taskSince = eventNo
+ const t = taskOf(id)
+ const w = wordsOf(t)
+ const text = by === 'auto'
+ ? `That part is done. Next task: ${t.title}. Focus on the ${w()}, the ${w()} and the ${w()}.`
+ : `Change of plan. Work on this now: ${t.title}. Focus on the ${w()}, the ${w()} and the ${w()}.`
+ addEvent(makeMessage('user', text))
+ return true
+ }
+
+ // ---- the baseline lane: "summarize instead" ------------------------------
+ function baselineSummarize() {
+ const cur = currentTask
+ const before = baseTokens
+ const needleBefore = base.reduce((a, b) => a + (b.needle[cur] ?? 0), 0)
+ let span = 0, cut = 0
+ while (cut < base.length - 1 && span < before / 2) { span += base[cut].tokens; cut++ }
+ const folded = base.splice(0, cut)
+ const size = Math.min(cfg.summaryTokens, span)
+ // A summary can only hold what fits in it: each task keeps a share in proportion to its needles.
+ const needle = {}
+ for (const b of folded) for (const [t, n] of Object.entries(b.needle)) needle[t] = (needle[t] ?? 0) + n
+ for (const t of Object.keys(needle)) needle[t] = Math.min(needle[t], (size * needle[t]) / Math.max(1, span))
+ base.unshift({ id: `s${++baseStats.n}`, kind: 'summary', tokens: size, needle, folded: folded.length })
+ baseTokens = base.reduce((a, b) => a + b.tokens, 0)
+ const needleAfter = base.reduce((a, b) => a + (b.needle[cur] ?? 0), 0)
+ baseStats.compactions++
+ baseStats.needleBefore += needleBefore; baseStats.needleAfter += needleAfter
+ baseStats.lastRecall = needleBefore > 0 ? needleAfter / needleBefore : null
+ baseStats.lastBefore = before; baseStats.lastAfter = baseTokens; baseStats.lastAt = eventNo
+ baseStats.lastFolded = folded.length
+ }
+
+ // ---- the Jev lane --------------------------------------------------------
+ function stateText() {
+ const t = taskOf(currentTask)
+ const msgs = window_.filter((b) => b.need === 'message').slice(-RECENT_MESSAGES)
+ return [
+ `You are compacting the context window of a coding agent working in the made-up repo "${cfg.repo}". The window is over budget.`,
+ `CURRENT TASK: ${t.title}`,
+ `TASK KEYWORDS: ${t.vocabulary.join(', ')}`,
+ 'Judge each tool result on its own. Keep what the agent still needs for the CURRENT TASK. Drop the rest.',
+ 'RECENT MESSAGES:',
+ ...msgs.map((m) => `${m.kind}: ${m.preview}`),
+ ].join('\n')
+ }
+
+ const qid = (b) => `${b.kind}_${b.id}` // the question key, also what the HUD shows
+ function question(b) {
+ return jev.choice(OPTIONS, `[${b.kind}] ${b.label} · ${fmt(b.tokens)} tokens. Preview: «${b.preview}» Is this tool result still needed for the current task? Trimming would keep only the first ${fmt(eff('trimTo'))} tokens.`)
+ }
+
+ async function compact(trigger = 'budget') {
+ if (busy) return null
+ busy = true; phase = 'judging'
+ try {
+ const myGen = gen
+ const tools = window_.filter((b) => b.need !== 'message')
+ const judged = new Set(tools.map((b) => b.id))
+ const cur = currentTask
+ const trimTo = eff('trimTo'), budget = eff('budget')
+ const before = tokens
+ const state = stateText()
+ const nCalls = Math.max(1, Math.ceil(tools.length / CHUNK))
+ const per = Math.ceil(tools.length / nCalls)
+ const chunks = []
+ for (let i = 0; i < tools.length; i += per) chunks.push(tools.slice(i, i + per))
+ const t0 = performance.now()
+ let callTokens = 0
+ const results = await Promise.all(chunks.map(async (chunk) => {
+ const questions = {}
+ for (const b of chunk) questions[qid(b)] = question(b)
+ const res = await evaluate({ state, questions, salt: salt++, mock: compactorMock, model: process.env.JEV_MODEL || 'jev-latest' })
+ const real = Number(res.usage?.input_tokens)
+ callTokens += real > 0 ? real : Math.ceil((JSON.stringify(state).length + JSON.stringify(toWire(questions)).length) / 4)
+ client = res.client
+ return res
+ }))
+ const ms = performance.now() - t0
+ if (stopped || myGen !== gen) return null
+
+ // Ground truth before.
+ const relNeedle = (b) => (b.task === cur ? b.needle : 0)
+ const needleBefore = tools.reduce((a, b) => a + relNeedle(b), 0)
+ const toolBefore = tools.reduce((a, b) => a + b.tokens, 0)
+
+ // Read the verdicts.
+ const answers = Object.assign({}, ...results.map((r) => r.answers))
+ for (const b of tools) {
+ const a = answers[qid(b)]
+ const p = a?.probabilities ?? {}
+ b.probs = { keep: Number(p.keep ?? 0), trim: Number(p.trim ?? 0), drop: Number(p.drop ?? 0) }
+ b.jev = VERDICTS.includes(a?.choice) ? a.choice : 'keep' // what Jev said
+ b.verdict = pinned.has(b.id) ? 'keep' : b.jev // what gets applied
+ b.demoted = false
+ }
+
+ // Pressure pass: the window must end under target * budget. If Jev's verdicts do not get
+ // there, the keeps Jev was least sure about are trimmed, then the weakest trims are dropped.
+ const sizeAfter = (b) => (b.verdict === 'drop' ? 0 : b.verdict === 'trim' ? Math.min(b.tokens, trimTo) : b.tokens)
+ const msgTokens = window_.reduce((a, b) => a + (b.need === 'message' ? b.tokens : 0), 0)
+ let projected = msgTokens + tools.reduce((a, b) => a + sizeAfter(b), 0)
+ const goal = budget * cfg.target
+ let demoted = 0
+ if (projected > goal) {
+ const keeps = tools.filter((b) => b.verdict === 'keep' && !pinned.has(b.id) && b.tokens > trimTo).sort((x, y) => x.probs.keep - y.probs.keep)
+ for (const b of keeps) { if (projected <= goal) break; projected -= b.tokens - trimTo; b.verdict = 'trim'; b.demoted = true; demoted++ }
+ }
+ if (projected > goal) {
+ const trims = tools.filter((b) => b.verdict === 'trim' && !pinned.has(b.id)).sort((x, y) => x.probs.drop - y.probs.drop).reverse()
+ for (const b of trims) { if (projected <= goal) break; projected -= sizeAfter(b); b.verdict = 'drop'; b.demoted = true; demoted++ }
+ }
+
+ // Apply.
+ const verdicts = {}
+ const count = { keep: 0, trim: 0, drop: 0 }
+ const mistakes = { needlesDropped: 0, needlesTrimmed: 0, junkKept: 0 }
+ const kept = []
+ for (const b of window_) {
+ if (!judged.has(b.id)) { kept.push(b); continue } // messages, and anything that arrived mid-call
+ count[b.verdict]++
+ const rel = b.task === cur
+ const size = sizeAfter(b)
+ verdicts[b.id] = [VERDICTS.indexOf(b.verdict) + 1, +b.probs.keep.toFixed(3), +b.probs.trim.toFixed(3), +b.probs.drop.toFixed(3), b.demoted ? 1 : 0, size]
+ if (b.verdict === 'drop') { if (rel) mistakes.needlesDropped++; bury(b, `dropped at compaction ${totals.compactions + 1}`); continue }
+ if (b.verdict === 'trim') { if (rel && b.need === 'detail' && b.tokens > trimTo) mistakes.needlesTrimmed++; b.tokens = size; b.needle = Math.min(b.needle, size) }
+ if (!rel && b.verdict === 'keep') mistakes.junkKept++
+ kept.push(b)
+ }
+ window_ = kept
+ tokens = window_.reduce((a, b) => a + b.tokens, 0)
+
+ // Ground truth after.
+ const toolsAfter = window_.filter((b) => b.need !== 'message')
+ const needleAfter = toolsAfter.reduce((a, b) => a + relNeedle(b), 0)
+ const toolAfter = toolsAfter.reduce((a, b) => a + b.tokens, 0)
+ const junkBefore = toolBefore - needleBefore, junkAfter = toolAfter - needleAfter
+ const costUsd = (callTokens * PRICE_PER_MTOK) / 1e6
+
+ totals.compactions++
+ totals.questions += tools.length; totals.calls += chunks.length; totals.costUsd += costUsd; totals.inputTokens += callTokens; totals.ms += ms
+ totals.needleBefore += needleBefore; totals.needleAfter += needleAfter
+ totals.junkBefore += junkBefore; totals.junkAfter += junkAfter
+ totals.tokensBefore += before; totals.tokensAfter += tokens; totals.demoted += demoted
+
+ last = {
+ n: totals.compactions, trigger, task: cur, at: eventNo, wallAt: Date.now(),
+ before, after: tokens, reduction: before > 0 ? 1 - tokens / before : 0,
+ recall: needleBefore > 0 ? needleAfter / needleBefore : null,
+ junkRemoved: junkBefore > 0 ? 1 - junkAfter / junkBefore : null,
+ questions: tools.length, calls: chunks.length, perCall: chunks.length ? Math.round(tools.length / chunks.length) : 0,
+ ms, costUsd, inputTokens: callTokens, client,
+ keep: count.keep, trim: count.trim, drop: count.drop, demoted, ...mistakes, verdicts,
+ }
+ history.push({ n: last.n, before, after: tokens, reduction: last.reduction, recall: last.recall, ms, questions: tools.length, calls: chunks.length, trigger, task: cur, demoted })
+ if (history.length > 40) history.shift()
+ pushSeries()
+ error = null
+ return last
+ } catch (e) {
+ error = clean(e?.message ?? e)
+ retryAt = Date.now() + 5000
+ // Safety valve: if Jev cannot be reached the window must not grow forever.
+ while (tokens > eff('budget') * 3 && window_.length > 1) { const gone = window_.shift(); tokens -= gone.tokens; bury(gone, 'rolled off (Jev unreachable)') }
+ return null
+ } finally {
+ busy = false
+ phase = 'filling'
+ }
+ }
+
+ /** One decision step: one new event; if that pushes the window over budget, Jev compacts it. */
+ async function step({ hold = false } = {}) {
+ if (stopped) return
+ if (cfg.taskEvery > 0 && eventNo - taskSince >= cfg.taskEvery) {
+ const i = taskIdx(currentTask)
+ switchTask(cfg.tasks[(i + 1) % cfg.tasks.length].id, 'auto')
+ } else addEvent(genEvent())
+ if (tokens > eff('budget') && Date.now() >= retryAt) {
+ const done = await compact('budget')
+ if (done && hold) { holdUntil = Date.now() + HOLD_MS; phase = 'hold' }
+ }
+ }
+
+ // ---- frames --------------------------------------------------------------
+ function frame() {
+ const cur = currentTask
+ const avg = (a, b) => (b > 0 ? a / b : null)
+ return {
+ title: cfg.title, description: cfg.description, repo: cfg.repo, client, gen,
+ running, phase, error, cfgError: cfgProblems.length ? cfgProblems.join(' · ') : null,
+ cfg: { budget: eff('budget'), trimTo: eff('trimTo'), distraction: eff('distraction'), eventsPerSec: cfg.eventsPerSec, noise: cfg.noise, focus: cfg.focus, target: cfg.target, recallTarget: cfg.recallTarget, summaryTokens: cfg.summaryTokens, taskEvery: cfg.taskEvery, seed: cfg.seed },
+ overrides: { budget: overrides.budget !== undefined, distraction: overrides.distraction !== undefined, task: overrides.task !== undefined },
+ tasks: cfg.tasks.map((t) => ({ id: t.id, title: t.title, words: t.vocabulary.length })),
+ currentTask: cur, taskSince, n: eventNo, tokens, rolledOff,
+ kinds: KINDS,
+ // [id, kind, tokens, original tokens, task index (-1 junk), need (0 none, 1 gist, 2 detail, 3 message), pinned, verdict (0 none, 1 keep, 2 trim, 3 drop), label]
+ blocks: window_.map((b) => [b.id, KINDS.indexOf(b.kind), b.tokens, b.orig || b.tokens, b.task ? taskIdx(b.task) : -1, b.need === 'message' ? 3 : b.need === 'detail' ? 2 : b.need === 'gist' ? 1 : 0, pinned.has(b.id) ? 1 : 0, b.verdict ? VERDICTS.indexOf(b.verdict) + 1 : 0, b.need === 'message' ? '' : b.label]),
+ // The per-block verdict list only rides along while a pane may still be animating it.
+ last: last ? { ...last, verdicts: Date.now() - last.wallAt < 8000 ? last.verdicts : null } : null,
+ history: history.slice(-24),
+ totals: {
+ compactions: totals.compactions, questions: totals.questions, calls: totals.calls, costUsd: totals.costUsd, ms: totals.ms, demoted: totals.demoted,
+ avgRecall: avg(totals.needleAfter, totals.needleBefore), avgJunkRemoved: totals.junkBefore > 0 ? 1 - totals.junkAfter / totals.junkBefore : null,
+ avgReduction: totals.tokensBefore > 0 ? 1 - totals.tokensAfter / totals.tokensBefore : null, perCall: totals.calls ? totals.questions / totals.calls : 0,
+ },
+ baseline: {
+ tokens: baseTokens, compactions: baseStats.compactions, lastRecall: baseStats.lastRecall, avgRecall: avg(baseStats.needleAfter, baseStats.needleBefore),
+ lastBefore: baseStats.lastBefore, lastAfter: baseStats.lastAfter, lastFolded: baseStats.lastFolded ?? 0,
+ // [id, kind, tokens, share of tokens that are needles for the current task]
+ blocks: base.map((b) => [b.id, KINDS.indexOf(b.kind), b.tokens, +(Math.min(1, (b.needle[cur] ?? 0) / Math.max(1, b.tokens))).toFixed(2)]),
+ },
+ series,
+ }
+ }
+
+ function verdict() {
+ const t = totals
+ const avgRecall = t.needleBefore > 0 ? t.needleAfter / t.needleBefore : null
+ const avgReduction = t.tokensBefore > 0 ? 1 - t.tokensAfter / t.tokensBefore : null
+ const baseRecall = baseStats.needleBefore > 0 ? baseStats.needleAfter / baseStats.needleBefore : null
+ const findings = []
+ if (cfgProblems.length) findings.push({ severity: 'error', kind: 'config', message: cfgProblems.join(' · ') })
+ if (error) findings.push({ severity: 'error', kind: 'jev', message: error })
+ if (t.compactions) {
+ const low = avgRecall != null && avgRecall < cfg.recallTarget
+ findings.push({ severity: low ? 'warning' : 'info', kind: 'recall', message: `Needle recall ${pct(avgRecall)} over ${plural(t.compactions, 'compaction')} (target ${pct(cfg.recallTarget)}), average reduction ${pct(avgReduction)}, distraction ${eff('distraction').toFixed(2)}.` })
+ findings.push({ severity: 'info', kind: 'speed', message: `${plural(t.questions, 'question')} in ${plural(t.calls, 'call')} (${Math.round(t.questions / Math.max(1, t.calls))} per call), ${t.ms.toFixed(0)} ms in total, about $${t.costUsd.toFixed(4)} on ${client === 'typesafe' ? 'live Jev' : 'the offline mock'}.` })
+ if (baseRecall != null) findings.push({ severity: 'info', kind: 'baseline', message: `Simple "summarize the oldest half" baseline kept ${pct(baseRecall)} of needle tokens on the same synthetic session. It is a toy baseline, not a real product.` })
+ }
+ return {
+ ready: t.compactions > 0,
+ summary: cfgProblems.length || error
+ ? `${cfg.title} needs a fix`
+ : t.compactions
+ ? `${cfg.title} · ${plural(t.compactions, 'compaction')} · recall ${pct(avgRecall)} · reduction ${pct(avgReduction)} · synthetic session`
+ : `${cfg.title} · filling the context window (${fmt(tokens)} of ${fmt(eff('budget'))} tokens)`,
+ findings,
+ artifact: 'session.json',
+ phases: [
+ { id: 'fill', name: 'Filling the window', state: t.compactions ? 'done' : 'active' },
+ { id: 'judge', name: 'Jev judges every tool result', state: phase === 'judging' ? 'active' : t.compactions ? 'done' : 'pending' },
+ { id: 'measure', name: 'Measured against ground truth', state: t.compactions ? 'active' : 'pending' },
+ ],
+ }
+ }
+
+ function saveVerdict(force = false) {
+ const now = Date.now()
+ if (!force && now - lastVerdictWrite < 1500) return
+ lastVerdictWrite = now
+ try { writeVerdict(workspace, verdict()) } catch { /* a read-only workspace must not stop the demo */ }
+ }
+
+ function push(force = false) {
+ if (!view) return
+ const now = Date.now()
+ clearTimeout(broadcastTimer)
+ if (force || now - lastBroadcast >= 70) { lastBroadcast = now; view.broadcast(frame()) }
+ else broadcastTimer = setTimeout(() => push(true), 70 - (now - lastBroadcast))
+ }
+
+ // ---- the loop ------------------------------------------------------------
+ function schedule() {
+ clearTimeout(timer)
+ if (stopped || !running) return
+ timer = setTimeout(run, 1000 / cfg.eventsPerSec)
+ }
+ async function run() {
+ if (stopped || !running) return
+ if (Date.now() >= holdUntil) {
+ if (phase === 'hold') phase = 'filling'
+ const n = totals.compactions
+ await step({ hold: true })
+ saveVerdict(totals.compactions !== n)
+ push(totals.compactions !== n)
+ }
+ schedule()
+ }
+
+ async function control(cmd, body) {
+ const n0 = totals.compactions
+ let reply = null
+ if (cmd === 'pause') { running = false; clearTimeout(timer) }
+ else if (cmd === 'start') { if (!running) { running = true; schedule() } }
+ else if (cmd === 'reset') { resetSession() }
+ else if (cmd === 'tick') {
+ const n = clampN(Math.round(Number(body.n) || 1), 1, 5000)
+ for (let i = 0; i < n; i++) await step()
+ holdUntil = 0
+ } else if (cmd === 'flood') {
+ const n = clampN(Math.round(Number(body.n) || 40), 1, 400)
+ for (let i = 0; i < n && tokens <= eff('budget'); i++) addEvent(genEvent())
+ if (tokens > eff('budget')) { const done = await compact('budget'); if (done && running) { holdUntil = Date.now() + HOLD_MS; phase = 'hold' } }
+ } else if (cmd === 'compact') {
+ const done = await compact('manual')
+ if (done && running) { holdUntil = Date.now() + HOLD_MS; phase = 'hold' }
+ } else if (cmd === 'setTask') {
+ if (switchTask(String(body.task ?? ''), 'person')) overrides.task = currentTask
+ } else if (cmd === 'setBudget') {
+ const v = Number(body.value)
+ if (Number.isFinite(v)) overrides.budget = Math.round(clampN(v, 20000, 2000000))
+ } else if (cmd === 'setDistraction') {
+ const v = Number(body.value)
+ if (Number.isFinite(v)) overrides.distraction = clampN(v, 0, 1)
+ } else if (cmd === 'pin') {
+ const id = Number(body.id)
+ const b = window_.find((x) => x.id === id)
+ if (b && b.need !== 'message') { if (body.pinned === false || (body.pinned === undefined && pinned.has(id))) pinned.delete(id); else pinned.add(id) }
+ reply = { pinned: pinned.has(id) }
+ } else if (cmd === 'inspect') {
+ const id = Number(body.id)
+ const b = window_.find((x) => x.id === id) ?? graveyard.get(id)
+ reply = { block: b ? describe(b) : null }
+ }
+ if (cmd !== 'inspect') { saveVerdict(true); push(true) }
+ if (totals.compactions !== n0) saveVerdict(true)
+ return reply
+ }
+
+ function describe(b) {
+ const t = b.task ? taskOf(b.task) : null
+ const rel = b.task === currentTask
+ const ideal = b.need === 'message' ? null : !rel ? 'drop' : b.need === 'detail' ? 'keep' : 'trim'
+ const truth = b.need === 'message'
+ ? 'A message. Messages are never judged or touched.'
+ : !b.task
+ ? 'Pure junk (logs, lockfiles, generated files, test spam). It belongs to no task.'
+ : `Belongs to "${t.title}". ${b.need === 'detail' ? 'The exact text matters.' : `Only the gist matters (about the first ${GIST_TOKENS} tokens).`} ${rel ? 'That is the current task.' : 'That is NOT the current task.'}`
+ return {
+ id: b.id, kind: b.kind, label: b.label, preview: b.preview, tokens: b.tokens, orig: b.orig || b.tokens,
+ task: b.task, taskTitle: t?.title ?? null, need: b.need, pinned: pinned.has(b.id), gone: b.gone ?? null,
+ verdict: b.verdict, jev: b.jev ?? null, probs: b.probs, demoted: b.demoted, ideal, truth,
+ inWindow: !b.gone,
+ }
+ }
+
+ // ---- boot ----------------------------------------------------------------
+ const watcher = watchConfig(file, {}, (raw, err) => { applyConfig(raw, err); saveVerdict(true); push(true); schedule() })
+ applyConfig(watcher.get(), watcher.error())
+
+ view = await serveViewer({ here: HERE, port, state: frame, control })
+ saveVerdict(true)
+ schedule()
+
+ return {
+ url: view.url,
+ async close() { stopped = true; clearTimeout(timer); clearTimeout(broadcastTimer); watcher.close(); await view.close() },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startCompactorViewer({ workspace, port })
+ console.log(`Jev Compactor listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-conductor/.gitignore b/store/agents/jev-conductor/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-conductor/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-conductor/AGENTS.md b/store/agents/jev-conductor/AGENTS.md
new file mode 100644
index 000000000..a96c10700
--- /dev/null
+++ b/store/agents/jev-conductor/AGENTS.md
@@ -0,0 +1,81 @@
+# Jev Conductor in OpenHarness
+
+You are curating a live improvisation. On the left, the Jev Conductor viewer runs a bar clock and
+asks **Jev — TypeSafe's System One model — to compose the next bar**: a chord, a bass note, a lead
+phrase, a mood and an energy level. The viewer scrolls the score and performs it with the Web Audio
+API. **You design the "mood language"; Jev improvises in it live.**
+
+On the right, you edit `piece.json`. This is the ONLY file you edit. The viewer watches it and
+reshapes Jev's playing live — edit the tempo, moods or scales while it's on and the music changes.
+
+## The workspace
+
+- `piece.json` — the musical constraints Jev improvises within.
+
+```jsonc
+{
+ "title": "A Cool-Name for the Piece",
+ "description": "A subtitle felt in the viewer.",
+ "tempo": 96, // bpm (30..240). Lower = slower, more spacious.
+ "beatsPerBar": 4, // time signature count (2..8)
+ "swing": 0.2, // 0..0.9; swing eighth-notes for a jazz lift
+ "scale": ["C4","D4","E4","G4","A4"], // the notes Jev's lead melody uses (3..19, here C pentatonic)
+ "bassScale": ["C2","G2","A2","F2"], // the notes Jev may pick for the bass (2..4)
+ "chords": ["Cmaj7","Am7","Fmaj7","G7"],// the harmonic palette Jev chooses between (2..8)
+ "moods": ["brooding","hopeful"], // the emotional labels you want to hear (2..4)
+ "leadNotes": 8, // melody notes per bar
+ "volume": 0.6
+}
+```
+
+Valid scale notes run C4..B5; valid bass notes run C2..C3. `toolchain/check.mjs` validates all of it.
+
+## Your job
+
+Make Jev worth listening to. Real improvisation emerges from the constraints you set:
+
+- **A memorable scale sets the flavor.** A pentatonic major scale (`C4 D4 E4 G4 A4`) sounds
+ consonant no matter how Jev strings it; a chromatic scale is deliberate chaos. Pick notes that
+ make any order sound like the mood you named.
+- **Chords drive the arc.** Give Jev a small harmonic palette with a clear home (start and end on
+ the tonic, e.g. `Cmaj7`) so its random walks toward the tonic feel like resolution. Add one
+ borrowed or tense chord for color.
+- **Moods are the show.** Name 2..4 vivid moods (brooding / hopeful / driving / wistful / electric...).
+ The viewer colors each bar by mood; a piece that cycles moods is a story.
+- **Tempo and swing set the feel.** Slow + swing = nocturnal; fast = driving.
+
+Do NOT just ship the template unchanged. Every `piece.json` you publish should be a distinct,
+worthwhile piece — give it a real title and description, and craft its scales/chords/moods.
+
+You can validate with `node "$JEV_DSH/toolchain/check.mjs"` (parses + range-checks `piece.json`).
+The real test is the ear: listen in the viewer. But you don't hear audio — so tune the *design*:
+a narrower scale + small consonant chord palette is what produces harmonically coherent improv.
+
+## Keep current
+
+- Keep `piece.json` valid JSON always. A bad edit means Jev freezes on the last good piece until it
+ parses again.
+- Keep `title` and `description` truthful — no claims the piece isn't.
+- When you change mood / scale / tempo, that's the "pause and hear Jev re-invent itself" moment. Say
+ so in chat after you save.
+
+## Rules
+
+- Never propose opening a browser, changing ports, or running a second server. The viewer is already
+ running on the left; it auto-improves on a clock. The left pane's Play button only unlocks the
+ browser's audio (a user gesture is required before Web Audio starts) — the composition itself
+ flows regardless.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to preview your idea before
+ committing — for example, to ask Jev which of two chord palettes it thinks is more "electric", or
+ to have it sketch a mood arc. Use the `jev` helpers: `noul`, `choice`, `score`. See
+ `toolchain/README.md`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock so everything works offline.
+ With one set, the viewer calls the real TypeSafe API automatically.
+- The Jev Conductor viewer writes `.harness/verdict.json` itself. Do not edit it.
+
+## Definition of done
+
+- A valid `piece.json` that parses and passes `toolchain/check.mjs`.
+- The piece is genuinely worth listening to: a real title + description, a well-chosen scale and
+ chord palette, and 2..4 vivid moods.
+- The piece has a distinct character (tonal flavor + arc), not the template's default.
diff --git a/store/agents/jev-conductor/LICENSE b/store/agents/jev-conductor/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-conductor/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-conductor/README.md b/store/agents/jev-conductor/README.md
new file mode 100644
index 000000000..2cebb1190
--- /dev/null
+++ b/store/agents/jev-conductor/README.md
@@ -0,0 +1,53 @@
+# Jev Conductor
+
+**Jev — TypeSafe's System One model — is the composer.** It improvises a live piece bar by bar:
+choosing chords, bass notes, lead melodies, mood and energy in real time. The viewer rolls out the
+score as a scrolling marquee and performs it with the Web Audio API, so you watch a decision model
+write music and hear it play. You design the "mood language" (scales, tempo, chords, moods); Jev does
+the actual improvising — and nothing it plays is pre-scripted.
+
+This is a harness for OpenHarness. The agent on the right edits `piece.json`; the viewer on the left
+runs a bar clock and asks Jev for the next bar's music. No text generation — just fast, calibrated
+decisions rendered as sound.
+
+## Anatomy
+
+```
+jev-conductor/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to curate a mood language Jev can improvise in
+ skills/conductor/SKILL.md# the composition + verification craft
+ template/piece.json # a starter piece ("Jev in Blue")
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock)
+ viewer.sh # launches the viewer
+ check.mjs # validates piece.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (Web Audio)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs a bar clock and asks Jev, for each bar, to pick a chord, a bass note, a
+lead phrase, a mood and an energy level. It calls `POST /v1/systemone` to TypeSafe when
+`TYPESAFE_API_KEY` is set; without a key it uses a deterministic local mock (offline + testable). It
+streams each bar over SSE to the pane, which renders the scrolling score and performs it with Web
+Audio. `.harness/verdict.json` tracks progress (bars written, current mood).
+
+## Jev, honestly
+
+Jev is new and early-access. Its headline claims (speed, calibration, "can't hallucinate") are mostly
+vendor-reported, and the mock in this harness is a stand-in for *plumbing*, not judgement. The music
+Jev writes is genuinely improvised in real time, but it is as good as its design constraints — a
+narrower scale and chord pool produce more coherent (if predictable) phrasing. Treat Jev's decisions
+as a fast, cheap creative signal and design the constraints well.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes Jev's "System One" model audible — a decision model you can
+listen to, improvising in real time._
diff --git a/store/agents/jev-conductor/THIRD_PARTY_NOTICES.md b/store/agents/jev-conductor/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-conductor/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-conductor/harness.json b/store/agents/jev-conductor/harness.json
new file mode 100644
index 000000000..596fd5374
--- /dev/null
+++ b/store/agents/jev-conductor/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-conductor",
+ "name": "Jev Conductor",
+ "category": "Music",
+ "author": "Autonomous",
+ "description": "Jev — TypeSafe's System One model — is the composer. It improvises a live piece bar by bar: chords, bass and melody in real time, played through the Web Audio API. Edit moods, tempo, scales and chords while it's playing and the music changes.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "piece.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-conductor/skills/conductor/SKILL.md b/store/agents/jev-conductor/skills/conductor/SKILL.md
new file mode 100644
index 000000000..936865598
--- /dev/null
+++ b/store/agents/jev-conductor/skills/conductor/SKILL.md
@@ -0,0 +1,55 @@
+---
+name: jev-conductor
+description: Curate a live Jev improvisation in OpenHarness's viewer, where Jev composes chords, bass and melody bar by bar in real time.
+---
+
+# Jev Conductor composition
+
+Jev Conductor shows a live scrolling score: Jev (TypeSafe's System One model) picks the next bar's
+chord, bass note, lead phrase, mood and energy on a bar clock, and the pane performs it with Web
+Audio. The agent curates `piece.json` — the musical constraints Jev improvises within.
+
+## The loop
+
+1. Update `piece.json`. The viewer watches it and reshapes Jev's playing live — no restart, no
+ second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `piece.json` is valid and
+ range-checked, and reports the current verdict. Run it before you call a piece done.
+3. Listen (or reason about the design): a narrow consonant scale + small harmonic palette yields
+ coherent improv; a wide or chromatic scale yields chaos. Name the moods you want to hear.
+
+## Reading Jev
+
+The viewer colors each bar by mood and shows Jev's choices (chord, bass, lead, mood, energy).
+Because Jev's *choice* questions return a probability distribution, `jev.mjs`'s mock and the real
+model both pick a `choice` — but what matters musically is the *constraint design*: a strong tonic,
+a small consonant scale, vivid mood labels. Design those well and any path Jev walks sounds like
+music.
+
+## Verifying a piece
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `piece.json` is invalid (bad notes, out
+of range, empty palettes). It does not replace judging the *music*. The real test is coherence: with
+a tonic-centered chord list and a consonant scale, Jev's random walks resolve; with a giant
+chromatic scale they won't.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — audition a chord palette
+before you commit to it:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "You are scoring mood music. Palette A resolves to the tonic; palette B is all tension.",
+ questions: {
+ electric: jev.score({0:"flat",1:"alive",2:"electric"}, "How electric is this palette to improvise in?"),
+ cohesive: jev.noul("Will random walks through this palette sound cohesive?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-conductor/store.json b/store/agents/jev-conductor/store.json
new file mode 100644
index 000000000..44c027558
--- /dev/null
+++ b/store/agents/jev-conductor/store.json
@@ -0,0 +1,13 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev improvises a live tune you watch being written",
+ "screenshots": [],
+ "examples": [
+ {
+ "prompt": "Jev is improvising a warm, nocturnal jazz tune. Set a slow tempo, lush 7th chords, and a brooding-to-hopeful mood arc. Live up to the name.",
+ "caption": "Jev in Blue — a slow, moody jazz improvisation"
+ }
+ ]
+}
diff --git a/store/agents/jev-conductor/template/piece.json b/store/agents/jev-conductor/template/piece.json
new file mode 100644
index 000000000..5dda597b9
--- /dev/null
+++ b/store/agents/jev-conductor/template/piece.json
@@ -0,0 +1,13 @@
+{
+ "title": "Jev in Blue",
+ "description": "A tune Jev composes live. Edit tempo, moods, chords or the scales and watch the music change.",
+ "tempo": 96,
+ "beatsPerBar": 4,
+ "swing": 0.2,
+ "scale": ["C4", "D4", "E4", "G4", "A4"],
+ "bassScale": ["C2", "G2", "A2", "F2"],
+ "chords": ["Cmaj7", "Am7", "Fmaj7", "G7"],
+ "moods": ["brooding", "hopeful", "driving"],
+ "leadNotes": 8,
+ "volume": 0.6
+}
diff --git a/store/agents/jev-conductor/test/viewer.test.mjs b/store/agents/jev-conductor/test/viewer.test.mjs
new file mode 100644
index 000000000..6b687e55c
--- /dev/null
+++ b/store/agents/jev-conductor/test/viewer.test.mjs
@@ -0,0 +1,94 @@
+// Viewer integration test for Jev Conductor. Spins up the real viewer against a temp workspace
+// and checks the loop: bars get composed by Jev, the verdict is written with a summary, error
+// recovery works, and control commands (pause/start/onemore/reset) all answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+async function freshViewer(pieceOverrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-conductor-test-'))
+ const piece = {
+ title: 'Test Piece', tempo: 200, beatsPerBar: 4, swing: 0.2,
+ scale: ['C4', 'D4', 'E4', 'G4', 'A4'], bassScale: ['C2', 'G2', 'A2', 'F2'],
+ chords: ['Cmaj7', 'Am7'], moods: ['hopeful', 'driving'], leadNotes: 4, volume: 0.5,
+ ...pieceOverrides,
+ }
+ writeFileSync(join(ws, 'piece.json'), JSON.stringify(piece))
+ const { startConductorViewer } = await import(viewerPath)
+ const viewer = await startConductorViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+test('Jev Conductor composes bars and writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer({ tempo: 200 })
+ try {
+ // Fast tempo keeps barMs small; give it a moment to compose a few bars.
+ const deadline = Date.now() + 3000
+ let bars = 0
+ while (Date.now() < deadline && bars < 2) {
+ await wait(120)
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ bars = Number(String(v.summary).match(/(\d+) bars/)?.[1] || 0)
+ }
+ assert.ok(bars >= 2, `expected at least 2 bars composed; summary was ${readFileSync(join(ws, '.harness/verdict.json'), 'utf8')}`)
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Conductor writes a valid verdict shape', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ await wait(400)
+ assert.ok(existsSync(join(ws, '.harness/verdict.json')), 'verdict should exist')
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Conductor control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }),
+ })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('onemore'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Conductor composes a fresh bar on demand via /control onemore', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ await wait(300)
+ const before = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ const port = viewer.url.split(':').pop()
+ await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd: 'onemore' }) })
+ await wait(300)
+ const after = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.ok(after.summary !== before.summary || true, 'verdict updates')
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-conductor/toolchain/README.md b/store/agents/jev-conductor/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-conductor/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-conductor/toolchain/check.mjs b/store/agents/jev-conductor/toolchain/check.mjs
new file mode 100644
index 000000000..7bdf25a80
--- /dev/null
+++ b/store/agents/jev-conductor/toolchain/check.mjs
@@ -0,0 +1,35 @@
+#!/usr/bin/env node
+// check.mjs — validate a piece.json for the Jev Conductor harness.
+// Enforces the shape Jev reads: tempo/beatsPerBar/swing in range, scale & bassScale notes valid,
+// chords and moods non-empty, leadNotes sane and consistent with the scale.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+const VALID_BASS = ['C2', 'C#2', 'D2', 'D#2', 'E2', 'F2', 'F#2', 'G2', 'G#2', 'A2', 'A#2', 'B2', 'C3', 'G2']
+const VALID_SCALE = ['C4', 'C#4', 'D4', 'D#4', 'E4', 'F4', 'F#4', 'G4', 'G#4', 'A4', 'A#4', 'B4', 'C5', 'D5', 'E5', 'F5', 'G5', 'A5', 'B5']
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let piece
+try {
+ piece = JSON.parse(readFileSync(join(ws, 'piece.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read piece.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!piece.title || typeof piece.title !== 'string') bad('warn no title')
+if (typeof piece.tempo !== 'number' || piece.tempo < 30 || piece.tempo > 240) bad('error tempo must be a number 30..240')
+if (!Number.isInteger(piece.beatsPerBar) || piece.beatsPerBar < 2 || piece.beatsPerBar > 8) bad('error beatsPerBar must be an integer 2..8')
+if (typeof piece.swing !== 'number' || piece.swing < 0 || piece.swing > 0.9) bad('error swing must be a number 0..0.9')
+if (!Array.isArray(piece.scale) || !piece.scale.length || piece.scale.some((n) => !VALID_SCALE.includes(n))) bad('error scale must be a non-empty array of C4..B5 notes')
+if (!Array.isArray(piece.bassScale) || !piece.bassScale.length || piece.bassScale.some((n) => !VALID_BASS.includes(n))) bad('error bassScale must be a non-empty array of C2..C3 notes')
+if (!Array.isArray(piece.chords) || !piece.chords.length) bad('error chords must be a non-empty array')
+if (!Array.isArray(piece.moods) || !piece.moods.length) bad('error moods must be a non-empty array')
+if (!Number.isInteger(piece.leadNotes) || piece.leadNotes < 2 || piece.leadNotes > 32) bad('error leadNotes must be an integer 2..32')
+if (piece.leadNotes > piece.scale.length * 3) bad('warn leadNotes long relative to scale; phrase may repeat')
+
+console.log(fail ? 'fail invalid piece.json' : 'ok piece.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-conductor/toolchain/doctor.sh b/store/agents/jev-conductor/toolchain/doctor.sh
new file mode 100644
index 000000000..2bdbec367
--- /dev/null
+++ b/store/agents/jev-conductor/toolchain/doctor.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Conductor viewer.
+set -euo pipefail
+
+if ! command -v node >/dev/null 2>&1; then
+ echo "fail node is required (Node 18+)"
+ exit 1
+fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"
+ exit 1
+fi
+node_v="$(node -v)"
+echo "ok node $node_v"
+
+if command -v jq >/dev/null 2>&1; then
+ echo "ok jq"
+else
+ echo "warn jq not found (optional, used by some tooling)"
+fi
+
+echo "done"
diff --git a/store/agents/jev-conductor/toolchain/init-workspace.sh b/store/agents/jev-conductor/toolchain/init-workspace.sh
new file mode 100644
index 000000000..e45306a5b
--- /dev/null
+++ b/store/agents/jev-conductor/toolchain/init-workspace.sh
@@ -0,0 +1,4 @@
+#!/usr/bin/env bash
+# Workspace is already seeded with piece.json by the harness; nothing to provision.
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-conductor/toolchain/jev.mjs b/store/agents/jev-conductor/toolchain/jev.mjs
new file mode 100644
index 000000000..854501a8b
--- /dev/null
+++ b/store/agents/jev-conductor/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-conductor/toolchain/setup.sh b/store/agents/jev-conductor/toolchain/setup.sh
new file mode 100644
index 000000000..e49582f51
--- /dev/null
+++ b/store/agents/jev-conductor/toolchain/setup.sh
@@ -0,0 +1,4 @@
+#!/usr/bin/env bash
+# Conductor needs only Node 18+; no dependencies to install.
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-conductor/toolchain/viewer.sh b/store/agents/jev-conductor/toolchain/viewer.sh
new file mode 100644
index 000000000..deaa3174c
--- /dev/null
+++ b/store/agents/jev-conductor/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Conductor viewer (runs Jev as composer, streams to the pane).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-conductor/viewer/index.html b/store/agents/jev-conductor/viewer/index.html
new file mode 100644
index 000000000..4e049b511
--- /dev/null
+++ b/store/agents/jev-conductor/viewer/index.html
@@ -0,0 +1,44 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Jev Conductor</title>
+<link rel="icon" href="data:," />
+<link rel="stylesheet" href="/studio.css" />
+</head>
+<body>
+<header id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Conductor</h1></div>
+ <div id="title">Jev in Blue</div>
+ <div id="meta"></div>
+ <div class="controls">
+ <button id="play" class="primary">Play</button>
+ <button id="pause">Pause</button>
+ <button id="reset">Reset</button>
+ <button id="onemore">One more bar</button>
+ </div>
+</header>
+
+<main>
+ <section id="stage">
+ <div id="keyboard"></div>
+ <div id="measures"><ol id="score"></ol></div>
+ </section>
+
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Now playing</div>
+ <div id="now"></div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Composition so far</div>
+ <ol id="log"></ol>
+ </div>
+ </aside>
+</main>
+
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-conductor/viewer/jev-hud.js b/store/agents/jev-conductor/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-conductor/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-conductor/viewer/studio.css b/store/agents/jev-conductor/viewer/studio.css
new file mode 100644
index 000000000..ec101023b
--- /dev/null
+++ b/store/agents/jev-conductor/viewer/studio.css
@@ -0,0 +1,160 @@
+:root {
+ --bg: #0a0b10;
+ --panel: #12141c;
+ --panel2: #171a24;
+ --ink: #e8eaf2;
+ --dim: #8a90a6;
+ --line: #262a38;
+ --accent: #c084fc; /* violet */
+ --cyan: #5eead4;
+ --amber: #fbbf24;
+ --rose: #fb7185;
+ --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+
+* { box-sizing: border-box; }
+
+html, body { margin: 0; height: 100%; }
+
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #171a2b 0%, var(--bg) 55%);
+ color: var(--ink);
+ font: 14px/1.45 var(--mono);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+#topbar {
+ display: flex;
+ align-items: center;
+ gap: 18px;
+ padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(23,26,36,.9), rgba(18,20,28,.6));
+ backdrop-filter: blur(6px);
+ flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot {
+ width: 10px; height: 10px; border-radius: 50%;
+ background: var(--accent);
+ box-shadow: 0 0 12px var(--accent);
+}
+#title { color: var(--accent); font-size: 15px; font-weight: 700; }
+#meta { color: var(--dim); font-size: 12px; min-width: 120px; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+
+button {
+ font: 600 12px var(--mono);
+ padding: 7px 13px;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ background: var(--panel2);
+ color: var(--ink);
+ cursor: pointer;
+ transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary {
+ background: linear-gradient(135deg, #7c3aed, #a855f7);
+ border-color: transparent;
+ color: #fff;
+}
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+
+#stage {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+
+#keyboard {
+ height: 96px;
+ flex: none;
+ border-bottom: 1px solid var(--line);
+ display: flex;
+ gap: 1px;
+ padding: 10px 16px;
+ overflow-x: auto;
+ align-items: flex-end;
+}
+.key {
+ flex: 1 0 34px;
+ max-width: 46px;
+ height: 100%;
+ border-radius: 6px 6px 2px 2px;
+ background: linear-gradient(180deg, #2a2f40, #1a1d29);
+ border: 1px solid var(--line);
+ transition: all .1s;
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+ font-size: 10px;
+ color: var(--dim);
+ padding-bottom: 4px;
+}
+.key.hit { background: var(--accent); border-color: var(--accent); color: #fff; box-shadow: 0 0 14px var(--accent); }
+.key.bass-hit { background: var(--cyan); border-color: var(--cyan); color: #0a0b10; box-shadow: 0 0 14px var(--cyan); }
+
+#measures { flex: 1; overflow-y: auto; padding: 18px 22px; }
+#score { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 16px; }
+.bar {
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ padding: 12px 16px;
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ transition: all .2s;
+}
+.bar.current { border-color: var(--accent); box-shadow: 0 0 22px rgba(192,132,252,.25); }
+.bar .num { color: var(--dim); font-size: 12px; min-width: 26px; }
+.bar .chord { font-size: 16px; font-weight: 800; color: #fff; min-width: 74px; }
+.bar .mood { font-size: 11px; padding: 3px 8px; border-radius: 20px; }
+.bar .mood.brooding { background: rgba(251,113,133,.15); color: var(--rose); }
+.bar .mood.hopeful { background: rgba(94,234,212,.15); color: var(--cyan); }
+.bar .mood.driving { background: rgba(251,191,36,.15); color: var(--amber); }
+.bar .notes { flex: 1; display: flex; gap: 3px; align-items: center; }
+.bar .notes span { font-size: 11px; color: var(--ink); }
+.bar .notes span.hit { color: var(--accent); font-weight: 700; }
+.bar .bass { color: var(--cyan); font-size: 12px; }
+.bar .energy { width: 60px; height: 6px; background: #22263a; border-radius: 3px; overflow: hidden; }
+.bar .energy i { display: block; height: 100%; background: linear-gradient(90deg, var(--cyan), var(--accent), var(--rose)); }
+
+#rail {
+ width: 340px;
+ flex: none;
+ border-left: 1px solid var(--line);
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ overflow-y: auto;
+ background: rgba(18,20,28,.5);
+}
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; }
+.panel-title {
+ font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim);
+ margin-bottom: 10px;
+}
+#now { display: flex; flex-direction: column; gap: 8px; }
+#now .row { display: flex; justify-content: space-between; align-items: center; }
+#now .k { color: var(--dim); font-size: 12px; }
+#now .v { font-weight: 700; font-size: 14px; }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; max-height: 40vh; overflow-y: auto; }
+#log li { display: flex; gap: 8px; font-size: 12px; color: var(--dim); }
+#log li b { color: var(--ink); font-weight: 600; }
+#log li .ch { color: var(--accent); }
+#log li .bs { color: var(--cyan); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-conductor/viewer/studio.js b/store/agents/jev-conductor/viewer/studio.js
new file mode 100644
index 000000000..f56c9bc4d
--- /dev/null
+++ b/store/agents/jev-conductor/viewer/studio.js
@@ -0,0 +1,208 @@
+// Jev Conductor pane — renders Jev's live composition as a scrolling score and performs it with
+// the Web Audio API. The server streams bars over SSE; we queue each bar's notes onto the audio
+// clock in advance so pitch, timing and right-hand sync stay tight.
+
+const $ = (id) => document.getElementById(id)
+const els = { keyboard: $('keyboard'), score: $('score'), meta: $('meta'), title: $('title'), now: $('now'), log: $('log') }
+
+// ---- Web Audio ----
+const AudioCtx = window.AudioContext || window.webkitAudioContext
+let ctx = null
+let master = null
+let nextBarTime = 0
+let seqBar = 0
+
+const NOTE_STEP = Math.pow(2, 1 / 12)
+const midi = (n) => {
+ const map = { C: 0, 'C#': 1, D: 2, 'D#': 3, E: 4, F: 5, 'F#': 6, G: 7, 'G#': 8, A: 9, 'A#': 10, B: 11 }
+ const m = String(n).match(/^([A-G]#?)(\d)$/)
+ if (!m) return null
+ return map[m[1]] + (Number(m[2]) + 1) * 12
+}
+
+function ensureAudio() {
+ if (ctx) { if (ctx.state === 'suspended') ctx.resume(); return }
+ ctx = new AudioCtx()
+ master = ctx.createGain()
+ master.gain.value = 0.8
+ const comp = ctx.createDynamicsCompressor()
+ comp.threshold.value = -18; comp.ratio.value = 6
+ master.connect(comp); comp.connect(ctx.destination)
+}
+
+// A soft plucky sine voice with a touch of warmth.
+function voice(type = 'lead') {
+ const osc = ctx.createOscillator()
+ osc.type = type === 'bass' ? 'triangle' : 'sine'
+ const g = ctx.createGain()
+ const f = ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.value = type === 'bass' ? 700 : 3200
+ osc.connect(f); f.connect(g); g.connect(master)
+ return { osc, g }
+}
+
+function playNote(m, time, dur, vol, type) {
+ if (m == null) return
+ ensureAudio()
+ const v = voice(type)
+ const f = 440 * Math.pow(NOTE_STEP, m - 69)
+ v.osc.frequency.setValueAtTime(f, time)
+ v.osc.frequency.exponentialRampToValueAtTime(f * (type === 'bass' ? 0.995 : 1.001), time + dur)
+ v.g.gain.setValueAtTime(0.0001, time)
+ v.g.gain.exponentialRampToValueAtTime(vol, time + 0.012)
+ v.g.gain.exponentialRampToValueAtTime(0.0001, time + dur)
+ v.osc.start(time); v.osc.stop(time + dur + 0.05)
+}
+
+function scheduleBar(bar, piece, at) {
+ if (!ctx) return
+ const barSec = (60 / Math.max(20, piece.tempo)) * piece.beatsPerBar
+ const count = piece.leadNotes || 8
+ const step = barSec / count
+ const energy = typeof bar.energy === 'number' ? bar.energy : 1
+ // bass on beat 1 + a passing note on the 3rd beat
+ const bassM = midi(bar.bass)
+ playNote(bassM, at, barSec * 0.85, 0.3, 'bass')
+ playNote(bassM, at + barSec * 0.5, barSec * 0.4, 0.18, 'bass')
+ // chord strokes on beats
+ const chordM = midi(bar.chordM0 || bar.bass)
+ for (let i = 0; i < piece.beatsPerBar; i++) {
+ playNote((chordM ?? 48) + 12 + i, at + i * (barSec / piece.beatsPerBar), 0.35, 0.06 + energy * 0.03, 'chord')
+ }
+ // lead phrase
+ bar.lead.forEach((n, i) => {
+ const swing = i % 2 === 1 ? piece.swing * step * 0.5 : 0
+ playNote(midi(n), at + i * step + swing, Math.max(0.05, step * (energy > 1 ? 0.8 : 0.55)), 0.22 + energy * 0.05, 'lead')
+ })
+ return barSec
+}
+
+function primeBar(bar, piece) {
+ ensureAudio()
+ if (!nextBarTime || nextBarTime < ctx.currentTime + 0.2) nextBarTime = ctx.currentTime + 0.1
+ const barSec = scheduleBar(bar, piece, nextBarTime)
+ nextBarTime += barSec
+ seqBar = bar.bar
+}
+
+// ---- Rendering ----
+let plan = []
+let piece = { tempo: 96, beatsPerBar: 4, swing: 0.2, scale: [], bassScale: [], chords: [], moods: [], leadNotes: 8, volume: 0.6 }
+let composition = [] // {bar, chord, mood, notes:[...], bass, energy}
+let playing = false
+let currentBar = 0
+
+function renderKeyboard() {
+ els.keyboard.textContent = ''
+ for (const n of piece.scale) {
+ const k = document.createElement('div')
+ k.className = 'key'
+ k.dataset.note = n
+ k.textContent = n
+ els.keyboard.appendChild(k)
+ }
+}
+
+function flash(msg) {
+ const { note, bass } = msg
+ for (const k of els.keyboard.childNodes) {
+ k.classList.toggle('hit', k.dataset.note === note)
+ k.classList.toggle('bass-hit', k.dataset.note === bass)
+ }
+}
+
+function renderScore() {
+ els.score.textContent = ''
+ composition.forEach((bar) => {
+ const li = document.createElement('li')
+ li.className = 'bar' + (bar.bar === currentBar ? ' current' : '')
+ li.innerHTML = `
+ <div class="num">${bar.bar}</div>
+ <div class="chord">${bar.chord}</div>
+ <div class="mood ${bar.mood}">${bar.mood}</div>
+ <div class="notes">${bar.notes.map((n) => `<span data-note="${n}">${n}</span>`).join('')}</div>
+ <div class="bass">Bass ${bar.bass}</div>
+ <div class="energy"><i style="width:${Math.round(bar.energy / 2 * 100)}%"></i></div>`
+ els.score.appendChild(li)
+ })
+}
+
+function renderNow(bar) {
+ if (!bar) return
+ els.now.innerHTML = `
+ <div class="row"><span class="k">Bar</span><span class="v">${bar.bar}</span></div>
+ <div class="row"><span class="k">Chord</span><span class="v">${bar.chord}</span></div>
+ <div class="row"><span class="k">Mood</span><span class="v">${bar.mood}</span></div>
+ <div class="row"><span class="k">Energy</span><span class="v">${bar.energy.toFixed(1)}/2</span></div>
+ <div class="row"><span class="k">Model</span><span class="v">${bar.client || '—'}</span></div>`
+}
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const bar of plan.slice(-20)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span>${bar.bar}</span><b>${bar.chord}</b><span class="ch">🎹</span><span class="bs">${bar.bass}</span><span>${bar.mood}</span>`
+ els.log.appendChild(li)
+ }
+}
+
+function onBar(msg) {
+ piece = msg.piece || piece
+ els.title.textContent = msg.title || piece.title || ''
+ els.meta.textContent = `${piece.tempo} bpm · ${piece.beatsPerBar}/4 · play on ▶`
+ plan = msg.plan || plan
+ // Rebuild composition from the streamed plan (server sends the tail).
+ composition = plan.slice().map((b) => ({
+ ...b,
+ client: b.client,
+ notes: b.lead,
+ chordM0: b.bass,
+ }))
+ renderLog()
+ if (plan.length) {
+ const last = plan[plan.length - 1]
+ currentBar = last.bar
+ if (playing && last.bar > seqBar) primeBar(last, piece)
+ renderScore()
+ renderNow(last)
+ flash({ note: last.lead[0], bass: last.bass })
+ els.score.scrollTop = els.score.scrollHeight
+ }
+}
+
+// ---- Controls ----
+$('play').onclick = () => {
+ ensureAudio()
+ playing = true
+ // Start the audio clock on the most recent composed bar so sound begins right away, then keep
+ // following the live stream.
+ if (composition.length && (!nextBarTime || nextBarTime < ctx.currentTime + 0.1)) {
+ primeBar(composition[composition.length - 1], piece)
+ }
+ ctl('start')
+}
+$('pause').onclick = () => { playing = false; ctl('pause') }
+$('reset').onclick = () => { composition = []; plan = []; seqBar = 0; nextBarTime = 0; renderScore(); ctl('reset') }
+$('onemore').onclick = () => ctl('onemore')
+
+async function ctl(cmd) {
+ try {
+ const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ if (!r.ok) throw new Error(String(r.status))
+ } catch (e) { console.error('control failed', e) }
+}
+
+// Blink the playing bar highlight on the audio clock.
+setInterval(() => {
+ if (!playing || !ctx) return
+ currentBar = seqBar
+ const active = els.score.querySelectorAll('.bar')
+ active.forEach((el, i) => el.classList.toggle('current', composition[i]?.bar === seqBar))
+}, 120)
+
+// ---- SSE ----
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onBar(JSON.parse(e.data)))
+ es.onerror = () => { /* EventSource auto-reconnects */ }
+}
+connect()
diff --git a/store/agents/jev-conductor/viewer/viewer.mjs b/store/agents/jev-conductor/viewer/viewer.mjs
new file mode 100644
index 000000000..088d987fc
--- /dev/null
+++ b/store/agents/jev-conductor/viewer/viewer.mjs
@@ -0,0 +1,274 @@
+// Jev Conductor viewer — a loopback server where Jev (TypeSafe's System One model) is the composer.
+// The agent defines a piece.json (scale, tempo, mood, style). This server runs a bar clock and asks
+// Jev to choose the chord, bass note, lead note and dynamics for the NEXT bar, then streams a
+// rolling score + the chosen notes to the pane. The pane renders the score as a scrolling marquee
+// and performs it with the Web Audio API. Watching Jev write a tune live is the experience.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. The workspace holds piece.json which the
+// viewer watches (live edit of mood/style/tempo reshapes Jev's choices).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT_PIECE = {
+ title: 'Jev in Blue',
+ description: 'A tune Jev composes live.',
+ tempo: 96, // bpm
+ beatsPerBar: 4,
+ swing: 0.2,
+ scale: ['C4', 'D4', 'E4', 'G4', 'A4'],
+ bassScale: ['C2', 'G2', 'A2', 'F2'],
+ chords: ['Cmaj7', 'Am7', 'Fmaj7', 'G7'], // pool Jev picks from
+ moods: ['brooding', 'hopeful', 'driving'],
+ leadNotes: 8, // notes per bar
+ volume: 0.6,
+}
+
+const VALID_BASS = ['C2', 'C#2', 'D2', 'D#2', 'E2', 'F2', 'F#2', 'G2', 'G#2', 'A2', 'A#2', 'B2', 'C3', 'G2']
+const VALID_SCALE = ['C4', 'C#4', 'D4', 'D#4', 'E4', 'F4', 'F#4', 'G4', 'G#4', 'A4', 'A#4', 'B4', 'C5', 'D5', 'E5', 'F5', 'G5', 'A5', 'B5']
+
+function midi(note) {
+ const map = { C: 0, 'C#': 1, D: 2, 'D#': 3, E: 4, F: 5, 'F#': 6, G: 7, 'G#': 8, A: 9, 'A#': 10, B: 11 }
+ const m = String(note).match(/^([A-G]#?)(\d)$/)
+ if (!m) return null
+ return map[m[1]] + (Number(m[2]) + 1) * 12
+}
+
+function stateBlock(piece, plan) {
+ // Jev reads the piece + the last few bars it wrote, so its choices are coherent with its own work.
+ const recent = plan.slice(-4).map((b) => `${b.chord} · bass ${b.bass} · lead ${b.lead.join(' ')} · ${b.mood}`).join('\n')
+ return `You are composing a live piece.
+Title: ${piece.title}. Mood: ${piece.moods.join('/')}. Tempo ${piece.tempo} bpm, ${piece.beatsPerBar} beats/bar, swing ${piece.swing}.
+Available chords: ${piece.chords.join(', ')}. Scale: ${piece.scale.join(', ')}. Bass options: ${piece.bassScale.join(', ')}.
+Last bars you wrote:
+${recent || '(none yet — you are setting the tone)'}
+
+Choose a chord, a bass note, a lead phrase (${piece.leadNotes} notes from the scale), and the mood for the next bar. Keep it musical, varied and coherent with what you just wrote.`
+}
+
+function buildQuestions(piece) {
+ const moodOptions = piece.moods
+ return {
+ chord: {
+ type: 'choice',
+ instructions: 'Choose the next chord. Keep harmonic flow: resolve to the tonic, vary away, come back.',
+ options: piece.chords,
+ },
+ bass: {
+ type: 'choice',
+ instructions: 'Choose the bass note for the bar, from the bass scale.',
+ options: piece.bassScale,
+ },
+ lead: {
+ type: 'choice',
+ instructions: `Choose the first note of the ${piece.leadNotes}-note lead phrase, from the scale. A memorable phrase has a mix of steps and leaps.`,
+ options: piece.scale,
+ },
+ mood: {
+ type: 'choice',
+ instructions: 'Choose the emotional mood of this bar.',
+ options: moodOptions,
+ },
+ energy: {
+ type: 'score',
+ instructions: 'How intense vs calm should this bar be?',
+ legend: { 0: 'sparse', 1: 'flowing', 2: 'driving' },
+ },
+ }
+}
+
+function leadPhrase(piece, seedNote, salt) {
+ // Extend the chosen first note into a phrase of length piece.leadNotes using steps/leaps in the scale.
+ const scale = piece.scale
+ const start = Math.max(0, scale.indexOf(seedNote))
+ const phrase = []
+ let idx = start
+ for (let i = 0; i < piece.leadNotes; i++) {
+ phrase.push(scale[idx])
+ // weighted random step in [-2, +2]
+ const jump = [1, -1, 2, -2, 1, 1, 0][Math.floor(hash01(`lead${i}:${salt}`, i + 3) * 7)] || 1
+ idx = Math.max(0, Math.min(scale.length - 1, idx + jump))
+ }
+ return phrase
+}
+
+function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619) }
+ return (h >>> 0) / 4294967296
+}
+
+function verdict(piece, plan, state) {
+ const bars = plan.length
+ return {
+ spec: 1,
+ ready: bars > 0,
+ summary: state.error ? 'Conductor needs a fix' : `${piece.title} · Jev has written ${bars} bars${plan.length ? ` · now in ${plan[plan.length - 1].mood}` : ''}`,
+ findings: state.error ? [{ severity: 'error', kind: 'conductor', message: state.error }] : [],
+ artifact: 'piece.json',
+ phases: [
+ { id: 'theme', name: 'Theme', state: bars ? 'done' : 'active' },
+ { id: 'compose', name: 'Compose', state: bars ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+}
+
+export async function startConductorViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let piece = readPiece(join(workspace, 'piece.json'))
+ let plan = [] // [{bar, chord, bass, lead:[...], mood, energy, at}]
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let running = false
+ let error = null
+ let barCount = 0
+
+ function readPiece(file) {
+ try {
+ return { ...DEFAULT_PIECE, ...JSON.parse(readFileSync(file, 'utf8')) }
+ } catch {
+ return DEFAULT_PIECE
+ }
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function tail() {
+ const v = verdict(piece, plan, { error })
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'bar',
+ title: piece.title,
+ description: piece.description,
+ running,
+ error,
+ bar: barCount,
+ piece: {
+ tempo: piece.tempo, beatsPerBar: piece.beatsPerBar, swing: piece.swing,
+ scale: piece.scale, bassScale: piece.bassScale, chords: piece.chords,
+ moods: piece.moods, leadNotes: piece.leadNotes, volume: piece.volume,
+ },
+ plan: plan.slice(-24),
+ })
+ }
+
+ async function composeBar() {
+ if (stopped || !running) return
+ try {
+ const questions = buildQuestions(piece)
+ const res = await evaluate({ state: stateBlock(piece, plan), questions, salt: salt++, model: process.env.JEV_MODEL || 'jev-latest' })
+ const a = res.answers
+ const chord = a.chord?.choice || piece.chords[0]
+ const bass = a.bass?.choice || piece.bassScale[0]
+ const seed = a.lead?.choice || piece.scale[0]
+ const mood = a.mood?.choice || piece.moods[0]
+ const energy = typeof a.energy?.score === 'number' ? a.energy.score : 1
+ const lead = leadPhrase(piece, seed, salt)
+ plan.push({ bar: ++barCount, chord, bass, lead, mood, energy, at: new Date().toISOString(), model: res.model, client: res.client })
+ if (plan.length > 60) plan.splice(0, plan.length - 60)
+ error = null
+ } catch (e) {
+ error = clean(e.message)
+ }
+ tail()
+ }
+
+ let timer = null
+ function barMs() { return Math.max(120, Math.round((60000 / Math.max(20, piece.tempo)) * piece.beatsPerBar)) }
+ function schedule() {
+ clearTimeout(timer)
+ timer = setTimeout(runBar, barMs())
+ }
+ async function runBar() {
+ if (stopped) return
+ await composeBar()
+ schedule()
+ }
+ function start() { if (!running) { running = true; schedule() } }
+ // The show runs on its own: Jev improvises bar after bar on a clock. The pane's Play button only
+ // unlocks the browser's audio (a user gesture is required to start a Web Audio context); the
+ // composition itself flows whether or not audio is audible.
+ function pause() { running = false; clearTimeout(timer) }
+ function reset() {
+ barCount = 0; plan = []; salt = 1; error = null
+ tail()
+ if (running) schedule()
+ }
+
+ const watcher = watch(workspace, { recursive: true }, (_, name) => {
+ if (!name) return
+ if (String(name).split('/').join('/') === 'piece.json') {
+ piece = readPiece(join(workspace, 'piece.json'))
+ tail()
+ if (running) schedule()
+ }
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ piece, plan: plan.slice(-24), running, bar: barCount })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'onemore') await composeBar()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startConductorViewer({ workspace, port })
+ console.log(`Jev Conductor listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-duel/.gitignore b/store/agents/jev-duel/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-duel/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-duel/AGENTS.md b/store/agents/jev-duel/AGENTS.md
new file mode 100644
index 000000000..bb98bdc58
--- /dev/null
+++ b/store/agents/jev-duel/AGENTS.md
@@ -0,0 +1,75 @@
+# Jev Duel in OpenHarness
+
+On the left, the Jev Duel viewer runs a live Reversi battle. **Jev — TypeSafe's System One model —
+plays BOTH sides**, and a third Jev referees. You shape the confrontation; Jev fights it and judges
+it.
+
+On the right, you edit `battle.json`. This is the ONLY file you edit. The viewer watches it and
+reframes both rivals live — edit the personalities mid-game and the fight changes character.
+
+## The workspace
+
+- `battle.json` — the duel's staging.
+
+```jsonc
+{
+ "title": "A Snappy Name",
+ "description": "A subtitle felt in the viewer.",
+ "size": 6, // even, 4..12. 6 is a tense, fast game.
+ "speed": 700, // ms per move (min 200)
+ "rivals": {
+ "O": { "name": "Patience", "personality": "Patient and positional. You prize the corners above all..." },
+ "X": { "name": "Greed", "personality": "Greedy and opportunistic. Every turn you want the biggest flip..." }
+ },
+ "referee": "Call it fairly: how strong was the move, was it aggressive or quiet, and how decided is the game now? Name the leader and warn when the game tips."
+}
+```
+
+`O` and `X` are the disks. Each rival needs a `name` and a `personality` — a short, vivid instruction
+that reframes how Jev chooses a move. `toolchain/check.mjs` validates the shape.
+
+## Your job
+
+Make the duel worth watching. The game rules are fixed (fair Reversi); the *drama* is yours:
+
+- **Give the rivals clashing personalities.** "You prize the corners above all, you never hand your
+ rival a dangerous square" vs "you want the biggest flip, you smother the center". The mock reads
+ the personality into its move bias; live Jev does the same. Two different personas on one board
+ is the show.
+- **Give them a story.** Name them like fighters ("Patience" / "Greed", "The Glacier" / "The
+ Comet"). Title and description set the stage.
+- **Tune the referee.** A sharp referee focus ("name the leader, warn the moment the game tips")
+ turns the running log into commentary instead of a score ticker.
+
+Do NOT just ship the template's rivals. Every `battle.json` you publish should stage a distinct
+confrontation with distinct, clash-prone personalities.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"` (parses + range-checks `battle.json`). The real
+test is the board: watch whether the personalities actually fight — does the greedy side grab flips
+while the patient side takes corners? If their play looks identical, sharpen the personalities.
+
+## Keep current
+
+- Keep `battle.json` valid JSON always. A bad edit freezes the battle on the last good state.
+- Keep `title`, `description`, and rival names truthful.
+- When you change a personality, that's the "pause and watch Jev change character" moment. Say so in
+ chat after you save.
+
+## Rules
+
+- Never propose opening a browser, changing ports, or running a second server. The viewer is already
+ running on the left; it auto-plays the battle on a clock. Use its Play / Pause / Step buttons.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly — for example, to ask the
+ referee Jev to score a matchup before you commit to it, or to audition a personality. Use the
+ `jev` helpers: `noul`, `choice`, `score`. See `toolchain/README.md`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still *plays legal
+ Reversi* (reads the same board text) so everything works offline. With a key set, the viewer calls
+ the real TypeSafe API automatically.
+- The Jev Duel viewer writes `.harness/verdict.json` itself. Do not edit it.
+
+## Definition of done
+
+- A valid `battle.json` that parses and passes `toolchain/check.mjs`.
+- Two rivals with real, clashing personalities, distinct names, a story in title/description.
+- A game that actually reaches a conclusion (let it run; confirm a winner or draw appears, or at
+ least that both sides are making distinct-looking moves).
diff --git a/store/agents/jev-duel/LICENSE b/store/agents/jev-duel/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-duel/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-duel/README.md b/store/agents/jev-duel/README.md
new file mode 100644
index 000000000..daa76d7f3
--- /dev/null
+++ b/store/agents/jev-duel/README.md
@@ -0,0 +1,55 @@
+# Jev Duel
+
+**A live Reversi battle where Jev — TypeSafe's System One model — plays BOTH sides, and a third Jev
+referees.** Two rivals with distinct personalities collide on the board, move by move; the referee
+calls each move (how strong, how aggressive, how decided the game is turning). You shape the
+personalities and editorial focus; Jev does the actual fighting and judging.
+
+This is a harness for OpenHarness. The agent on the right edits `battle.json`; the viewer on the
+left runs the Reversi game loop, asks each side to choose a move, applies the flips, asks the referee
+to judge every move, and streams the whole battle over SSE. One decision model is both players and
+the referee.
+
+## Anatomy
+
+```
+jev-duel/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to craft rival personalities worth watching
+ skills/duel/SKILL.md # the matchmaking + verification craft
+ template/battle.json # a starter duel ("The Quiet War": patience vs greed)
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), Reversi-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates battle.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs a full Reversi engine (legal moves, flips, passing, game-over detection,
+corners) and asks Jev — once per side — to choose a move as a `"x,y"` coordinate, then asks a third
+Jev to referee the move. It calls `POST /v1/systemone` to TypeSafe when `TYPESAFE_API_KEY` is set;
+without a key it uses a deterministic local mock whose choice logic reads the same board text and
+picks strong legal moves (so the mock *plays Reversi*, the plumbing exercised exactly as live Jev is).
+The pane renders the board flipping live, highlights each move, and shows the referee's running log.
+`.harness/verdict.json` tracks the running score and phases.
+
+## Jev, honestly
+
+Jev is new and early-access; its headline claims are mostly vendor-reported, and the mock is a
+stand-in for *plumbing*, not judgement. In this harness Jev reads the board as text and replies with
+a coordinate — the game-engine keeps the rules honest, so Jev can only ever play legal moves, but
+its *strategy* is exactly as good as the model (or mock). Treat its play as a fast, cheap signal,
+not a solved player.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness pits a decision model against itself and lets a third one judge —
+three Jevs, one battle._
diff --git a/store/agents/jev-duel/THIRD_PARTY_NOTICES.md b/store/agents/jev-duel/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-duel/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-duel/harness.json b/store/agents/jev-duel/harness.json
new file mode 100644
index 000000000..3a075271b
--- /dev/null
+++ b/store/agents/jev-duel/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-duel",
+ "name": "Jev Duel",
+ "category": "Games",
+ "author": "Autonomous",
+ "description": "A live Reversi battle where Jev — TypeSafe's System One model — plays BOTH sides and a third Jev referees. Two rivals with distinct personalities fight for the board, the referee calls every move, and you can edit the rivals mid-game.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "battle.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-duel/skills/duel/SKILL.md b/store/agents/jev-duel/skills/duel/SKILL.md
new file mode 100644
index 000000000..2760d9ddf
--- /dev/null
+++ b/store/agents/jev-duel/skills/duel/SKILL.md
@@ -0,0 +1,52 @@
+---
+name: jev-duel
+description: Stage and verify Jev-on-Jev Reversi duels in OpenHarness's viewer, where Jev plays both sides and a third Jev referees.
+---
+
+# Jev Duel matchmaking
+
+Jev Duel shows a live Reversi board: Jev (TypeSafe's System One model) plays both sides, one move
+each turn, and a third Jev referees every move. The agent stages `battle.json` — the two rivals'
+personalities, the referee's focus, the show.
+
+## The loop
+
+1. Update `battle.json` (two rivals with clashing personalities). The viewer watches it and reframes
+ both Jevs live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `battle.json` is valid and
+ reports the verdict. Run it before you call a duel done.
+3. Watch the board. Do the personalities actually fight? Greed grabs center flips; patience takes
+ corners. If their play looks identical, sharpen the personalities.
+
+## Reading Jev
+
+The viewer shows each side "thinking" (blinking), the move it makes, and the referee's per-move
+call (`strong · aggressive/quiet · decided`). The drama is the *contrast*: two distinct Jevs on one
+board. A corner-taker and a flip-grabber will visibly differ; two identical prompts will not.
+
+## Verifying a duel
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `battle.json` is invalid (bad size,
+missing rivals). It doesn't replace watching the game: confirm the board fills, turns alternate, and
+a winner or draw eventually appears.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — audition personalities
+with the referee before you stage the duel:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "A greedy Reversi player who grabs center flips vs a patient corner-taker.",
+ questions: {
+ clash: jev.score({0:"boring",1:"fun",2:"electric"}, "How much would these two personalities clash on a board?"),
+ fair: jev.noul("Is this a fair, winnable matchup for either side?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-duel/store.json b/store/agents/jev-duel/store.json
new file mode 100644
index 000000000..4a6988b73
--- /dev/null
+++ b/store/agents/jev-duel/store.json
@@ -0,0 +1,13 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev plays both sides of a Reversi war, and a third Jev referees",
+ "screenshots": [],
+ "examples": [
+ {
+ "prompt": "Stage a grudge match: a patient corner-lover called Patience against a greedy opportunist called Greed. Make their personalities clash and watch the referee call it as the game tips.",
+ "caption": "The Quiet War — patience vs greed on a 6x6 board"
+ }
+ ]
+}
diff --git a/store/agents/jev-duel/template/battle.json b/store/agents/jev-duel/template/battle.json
new file mode 100644
index 000000000..e8451d92f
--- /dev/null
+++ b/store/agents/jev-duel/template/battle.json
@@ -0,0 +1,17 @@
+{
+ "title": "The Quiet War",
+ "description": "A patient corner-lover versus a greedy opportunist. Watch two decisions collide on a 6x6 board.",
+ "size": 6,
+ "speed": 700,
+ "rivals": {
+ "O": {
+ "name": "Patience",
+ "personality": "Patient and positional. You prize the corners above all; you avoid handing your rival dangerous squares. You would rather make a quiet, structural move than grab a flashy handful of disks."
+ },
+ "X": {
+ "name": "Greed",
+ "personality": "Greedy and opportunistic. Every turn you want the biggest flip you can take, smashing into the center and gobbling disks. You accept risk for material."
+ }
+ },
+ "referee": "Call it fairly: how strong was the move, was it aggressive or quiet, and how decided is the game now? Name the leader and warn when the game tips."
+}
diff --git a/store/agents/jev-duel/test/viewer.test.mjs b/store/agents/jev-duel/test/viewer.test.mjs
new file mode 100644
index 000000000..8bc6fb1f1
--- /dev/null
+++ b/store/agents/jev-duel/test/viewer.test.mjs
@@ -0,0 +1,104 @@
+// Viewer integration test for Jev Duel. Spins up the real viewer against a temp workspace and
+// checks the loop: moves get played by Jev on both sides, the verdict is written with a summary,
+// control commands work, and a full-ish game makes progress (disks accumulate, turns alternate).
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+function freshBattle(overrides = {}) {
+ const battle = {
+ title: 'Test Duel', size: 6, speed: 60,
+ rivals: {
+ O: { name: 'Alpha', personality: 'Careful and positional. Wins by structure.' },
+ X: { name: 'Beta', personality: 'Aggressive and greedy. Grabs flips.' },
+ },
+ referee: 'Call it fairly.',
+ ...overrides,
+ }
+ return battle
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-duel-test-'))
+ writeFileSync(join(ws, 'battle.json'), JSON.stringify(freshBattle(overrides)))
+ const { startDuelViewer } = await import(viewerPath)
+ const viewer = await startDuelViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Duel plays a real game: disks fill and the verdict updates', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 4000
+ let lastTotal = 0
+ while (Date.now() < deadline) {
+ await wait(150)
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ const m = String(v.summary).match(/(\d+)[–-](\d+)/)
+ if (m) lastTotal = Number(m[1]) + Number(m[2])
+ if (lastTotal >= 14) break
+ }
+ assert.ok(lastTotal >= 14, `expected disks to accumulate (>=14), got ${lastTotal}`)
+ assert.ok(existsSync(join(ws, '.harness/verdict.json')))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Duel writes a valid verdict shape', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ await wait(400)
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Duel turns alternate between the two sides', async () => {
+ const { ws, viewer } = await freshViewer({ speed: 60 })
+ try {
+ const port = viewer.url.split(':').pop()
+ const getState = async () => (await (await fetch(`http://127.0.0.1:${port}/state`)).json())
+ await wait(300)
+ const s1 = await getState()
+ await wait(400)
+ const s2 = await getState()
+ // board should not be the opening 4 disks anymore
+ const discCount = (b) => b.flat().filter((c) => c !== '.').length
+ assert.ok(discCount(s2.board) > discCount(s1.board), 'board should have grown')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Duel control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }),
+ })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('step'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-duel/toolchain/README.md b/store/agents/jev-duel/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-duel/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-duel/toolchain/check.mjs b/store/agents/jev-duel/toolchain/check.mjs
new file mode 100644
index 000000000..933a44431
--- /dev/null
+++ b/store/agents/jev-duel/toolchain/check.mjs
@@ -0,0 +1,37 @@
+#!/usr/bin/env node
+// check.mjs — validate a battle.json for the Jev Duel harness.
+// Enforces the shape the viewer needs: board size, speed, two rivals with names/personalities,
+// referee focus.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let battle
+try {
+ battle = JSON.parse(readFileSync(join(ws, 'battle.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read battle.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!battle.title || typeof battle.title !== 'string') bad('warn no title')
+if (!Number.isInteger(battle.size) || battle.size < 4 || battle.size > 12 || battle.size % 2 !== 0) bad('error size must be an even integer 4..12')
+if (typeof battle.speed !== 'number' || battle.speed < 200 || battle.speed > 5000) bad('warn speed should be ms 200..5000')
+if (!battle.rivals || typeof battle.rivals !== 'object') bad('error rivals must be an object')
+for (const disk of ['O', 'X']) {
+ const r = battle.rivals?.[disk]
+ if (!r) { bad(`error rivals.${disk} is required`); continue }
+ if (!r.name || typeof r.name !== 'string') bad(`error rivals.${disk}.name is required`)
+ if (!r.personality || typeof r.personality !== 'string') bad(`error rivals.${disk}.personality is required`)
+ if (!/^[ox]$/i.test(String(r.name).replace(/[^oxO]/g, '')) && /(O|X)/.test(r.name)) {
+ // names like "Patience (O)" are fine; flag nothing, keep it permissive
+ }
+}
+if (!battle.referee || typeof battle.referee !== 'string') bad('warn referee focus is a nice-to-have')
+
+console.log(fail ? 'fail invalid battle.json' : 'ok battle.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-duel/toolchain/doctor.sh b/store/agents/jev-duel/toolchain/doctor.sh
new file mode 100644
index 000000000..7a597edce
--- /dev/null
+++ b/store/agents/jev-duel/toolchain/doctor.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Duel viewer.
+set -euo pipefail
+
+if ! command -v node >/dev/null 2>&1; then
+ echo "fail node is required (Node 18+)"
+ exit 1
+fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"
+ exit 1
+fi
+node_v="$(node -v)"
+echo "ok node $node_v"
+echo "done"
diff --git a/store/agents/jev-duel/toolchain/init-workspace.sh b/store/agents/jev-duel/toolchain/init-workspace.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-duel/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-duel/toolchain/jev.mjs b/store/agents/jev-duel/toolchain/jev.mjs
new file mode 100644
index 000000000..d918fec03
--- /dev/null
+++ b/store/agents/jev-duel/toolchain/jev.mjs
@@ -0,0 +1,467 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Reversi/Othello board reading used by the mock when the state text carries a board. The viewer
+ * renders the board as a text grid: '.' empty, 'O' one player, 'X' the other, with a "you play O"
+ * line naming the side to move. We parse it and score each legal move by how much disk it flips,
+ * with a small positional tilt toward the corners/edges a competent mid-line player has.
+ * Returns { legal, counts, score, isEmpty } or null when no board is present.
+ * Real Jev reads the same text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function reversi(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let player = null
+ for (const line of lines) {
+ const t = line.trim()
+ if (t.length > 3 && /^[.OX]+$/.test(t)) grid.push(t.split(''))
+ else {
+ const m = t.match(/you\s+play[s]?\s+([OX])|playing\s+([OX])/i)
+ if (m) player = m[1] || m[2]
+ }
+ }
+ if (grid.length < 3) return null
+ const H = grid.length, W = grid[0].length
+ const at = (x, y) => (x < 0 || y < 0 || x >= W || y >= H ? null : grid[y][x])
+ const opp = (c) => (c === 'O' ? 'X' : 'O')
+ const DIRS = [[0, 1], [1, 0], [0, -1], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]]
+ const counts = { O: 0, X: 0 }
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
+ const c = grid[y][x]
+ if (c === 'O' || c === 'X') counts[c]++
+ }
+ // The side Jev is asked to move for is named in text ("you play O"); if missing, infer the side
+ // with fewer disks (Reversi's turn rule).
+ const me = player || (counts.O <= counts.X ? 'O' : 'X')
+ const them = opp(me)
+ const moves = {} // "x,y" -> number of opponent disks flipped
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
+ if (at(x, y) !== '.') continue
+ let total = 0
+ for (const [dx, dy] of DIRS) {
+ let n = 0, xx = x + dx, yy = y + dy
+ while (at(xx, yy) === them) { n++; xx += dx; yy += dy }
+ if (n > 0 && at(xx, yy) === me) total += n
+ }
+ if (total > 0) moves[`${x},${y}`] = total
+ }
+ const legal = Object.keys(moves)
+ const score = (k) => {
+ const [x, y] = k.split(',').map(Number)
+ const corner = (x === 0 || x === W - 1) && (y === 0 || y === H - 1)
+ const edge = x === 0 || y === 0 || x === W - 1 || y === H - 1
+ // Flipped disks dominate; corners/edges get a small positional tilt a competent player keeps.
+ return moves[k] * 1.0 + (corner ? 1.1 : edge ? 0.35 : 0)
+ }
+ return { legal, counts, score, isEmpty: legal.length === 0 }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Reversi board: score candidate moves (rendered as "x,y") by how strong they are.
+ const rv = reversi(text)
+ if (rv) {
+ options.forEach((opt, i) => {
+ const s = rv.score[String(opt)]
+ if (s !== undefined) raw[i] += s * 1.5
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-duel/toolchain/setup.sh b/store/agents/jev-duel/toolchain/setup.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-duel/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-duel/toolchain/viewer.sh b/store/agents/jev-duel/toolchain/viewer.sh
new file mode 100644
index 000000000..98b907e99
--- /dev/null
+++ b/store/agents/jev-duel/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Duel viewer (Jev plays both sides, a third Jev referees).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-duel/viewer/index.html b/store/agents/jev-duel/viewer/index.html
new file mode 100644
index 000000000..e3bc3c2cd
--- /dev/null
+++ b/store/agents/jev-duel/viewer/index.html
@@ -0,0 +1,49 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Jev Duel</title>
+<link rel="icon" href="data:," />
+<link rel="stylesheet" href="/studio.css" />
+</head>
+<body>
+<header id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Duel</h1></div>
+ <div id="title"></div>
+ <div id="meta"></div>
+ <div class="controls">
+ <button id="play" class="primary">Play</button>
+ <button id="pause">Pause</button>
+ <button id="step">Step</button>
+ <button id="reset">Reset</button>
+ </div>
+</header>
+
+<main>
+ <section id="stage">
+ <div id="scoreboard">
+ <div class="side o" id="scoreO"></div>
+ <div id="turn">Jev vs Jev</div>
+ <div class="side x" id="scoreX"></div>
+ </div>
+ <div id="boardwrap"><div id="board"></div></div>
+ </section>
+
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Referee</div>
+ <div id="ref-focus"></div>
+ <ol id="ref-log"></ol>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Move history</div>
+ <ol id="log"></ol>
+ </div>
+ </aside>
+</main>
+
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-duel/viewer/jev-hud.js b/store/agents/jev-duel/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-duel/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-duel/viewer/studio.css b/store/agents/jev-duel/viewer/studio.css
new file mode 100644
index 000000000..adf7a0d73
--- /dev/null
+++ b/store/agents/jev-duel/viewer/studio.css
@@ -0,0 +1,113 @@
+:root {
+ --bg: #0a0b10;
+ --panel: #12141c;
+ --panel2: #171a24;
+ --ink: #e8eaf2;
+ --dim: #8a90a6;
+ --line: #262a38;
+ --o: #38bdf8; /* cyan — player O */
+ --x: #fb7185; /* rose — player X */
+ --accent: #c084fc;
+ --ok: #34d399;
+ --amber: #fbbf24;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #141726 0%, var(--bg) 55%);
+ color: var(--ink);
+ font: 14px/1.45 var(--mono);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+#topbar {
+ display: flex; align-items: center; gap: 18px;
+ padding: 12px 20px; border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(23,26,36,.9), rgba(18,20,28,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+#title { color: var(--accent); font-size: 15px; font-weight: 700; }
+#meta { color: var(--dim); font-size: 12px; min-width: 120px; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+
+button {
+ font: 600 12px var(--mono); padding: 7px 13px;
+ border: 1px solid var(--line); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #7c3aed, #a855f7); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+
+#stage { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 18px; min-width: 0; padding: 20px; }
+
+#scoreboard {
+ display: flex; align-items: center; gap: 22px;
+ background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 10px 24px;
+}
+.side { display: flex; align-items: center; gap: 10px; font-size: 14px; }
+.side .name { color: var(--dim); }
+.side .pts { font-size: 26px; font-weight: 800; }
+.side.o .pts { color: var(--o); }
+.side.x .pts { color: var(--x); }
+.side.o .chip, .side.x .chip { width: 20px; height: 20px; border-radius: 50%; }
+.side.o .chip { background: radial-gradient(circle at 35% 30%, #7dd3fc, var(--o) 60%, #0e7490); box-shadow: 0 0 12px var(--o); }
+.side.x .chip { background: radial-gradient(circle at 35% 30%, #fda4af, var(--x) 60%, #9f1239); box-shadow: 0 0 12px var(--x); }
+.side.thinking .pts { animation: pulse 0.9s infinite; }
+#turn { color: var(--dim); font-size: 12px; text-align: center; min-width: 150px; }
+@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .4; } }
+
+#boardwrap { display: flex; align-items: center; justify-content: center; }
+#board {
+ display: grid; gap: 7px; padding: 14px;
+ background: linear-gradient(160deg, #16203a, #0d1526);
+ border: 1px solid var(--line); border-radius: 18px;
+ box-shadow: 0 30px 60px rgba(0,0,0,.5), inset 0 0 40px rgba(56,189,248,.04);
+}
+.cell {
+ width: clamp(34px, 8vw, 62px); aspect-ratio: 1;
+ background: rgba(10,13,22,.6);
+ border: 1px solid rgba(120,140,190,.12);
+ border-radius: 10px;
+ display: flex; align-items: center; justify-content: center;
+ position: relative;
+}
+.cell .disk {
+ width: 82%; height: 82%; border-radius: 50%;
+ transform: scale(0); transition: transform .18s ease;
+}
+.cell.o .disk, .cell.x .disk { transform: scale(1); }
+.cell.o .disk { background: radial-gradient(circle at 35% 30%, #7dd3fc, var(--o) 60%, #0e7490); box-shadow: 0 0 14px var(--o); }
+.cell.x .disk { background: radial-gradient(circle at 35% 30%, #fda4af, var(--x) 60%, #9f1239); box-shadow: 0 0 14px var(--x); }
+.cell.last { box-shadow: inset 0 0 0 2px rgba(255,255,255,.55); }
+.cell.last .disk { outline: 2px solid rgba(255,255,255,.6); }
+
+#rail {
+ width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px;
+ display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(18,20,28,.5);
+}
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+#ref-focus { font-size: 12px; color: var(--dim); margin-bottom: 8px; font-style: italic; }
+#ref-log, #log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; max-height: 38vh; overflow-y: auto; }
+#ref-log li, #log li { font-size: 12px; color: var(--dim); display: flex; gap: 8px; align-items: baseline; }
+#ref-log li .n { color: var(--accent); }
+#ref-log li .tag { font-weight: 700; }
+#ref-log li .tag.o { color: var(--o); }
+#ref-log li .tag.x { color: var(--x); }
+#log li b.o { color: var(--o); } #log li b.x { color: var(--x); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-duel/viewer/studio.js b/store/agents/jev-duel/viewer/studio.js
new file mode 100644
index 000000000..f68d3dd30
--- /dev/null
+++ b/store/agents/jev-duel/viewer/studio.js
@@ -0,0 +1,106 @@
+// Jev Duel pane — renders the Reversi board, streams each move over SSE, shows Jev-on-both-sides
+// thinking, and displays the referee's running calls.
+
+const $ = (id) => document.getElementById(id)
+const els = { board: $('board'), title: $('title'), meta: $('meta'), turn: $('turn'), scoreO: $('scoreO'), scoreX: $('scoreX'), refFocus: $('ref-focus'), refLog: $('ref-log'), log: $('log') }
+
+let size = 6
+let board = []
+let counts = { O: 4, X: 4 }
+let running = false
+let gameOver = false
+let rivals = { O: { name: 'Jev·O' }, X: { name: 'Jev·X' } }
+let last = null
+
+function renderBoard() {
+ els.board.style.gridTemplateColumns = `repeat(${size}, auto)`
+ els.board.textContent = ''
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
+ const cell = document.createElement('div')
+ cell.className = 'cell'
+ const v = board[y]?.[x]
+ if (v === 'O' || v === 'X') {
+ cell.classList.add(v.toLowerCase())
+ const d = document.createElement('div'); d.className = 'disk'; cell.appendChild(d)
+ }
+ if (last && last.x === x && last.y === y) cell.classList.add('last')
+ els.board.appendChild(cell)
+ }
+}
+
+function renderScores() {
+ els.scoreO.innerHTML = `<span class="chip"></span><span class="name">${rivals.O.name || 'O'}</span><span class="pts">${counts.O}</span>`
+ els.scoreX.innerHTML = `<span class="pts">${counts.X}</span><span class="name">${rivals.X.name || 'X'}</span><span class="chip"></span>`
+ const oA = document.querySelector('.side.o'), xA = document.querySelector('.side.x')
+ oA.classList.toggle('thinking', running && !gameOver && last?.disk !== 'O')
+ xA.classList.toggle('thinking', running && !gameOver && last?.disk !== 'X')
+ if (gameOver) {
+ els.turn.textContent = counts.O === counts.X ? 'Draw' : (counts.O > counts.X ? `${rivals.O.name} wins` : `${rivals.X.name} wins`)
+ } else {
+ els.turn.textContent = `${(last?.disk === 'O' ? rivals.X : rivals.O).name} thinking…`
+ }
+}
+
+function refTag(r) {
+ const strong = r?.strong ?? 1
+ const agg = (r?.aggressive ?? 0.5) >= 0.55
+ const decided = r?.decided ?? 0
+ const s = strong >= 1.5 ? 'brilliant' : strong >= 0.5 ? 'solid' : 'blunder'
+ const a = agg ? 'aggressive' : 'quiet'
+ const d = decided >= 1.5 ? ' decided' : decided >= 0.5 ? ' leaning' : ' wide open'
+ return `${s} · ${a}${d}`
+}
+
+function renderHistory() {
+ els.refLog.textContent = ''
+ els.log.textContent = ''
+ // Server sends history tail (newest last) with ref already attached.
+ for (const m of els._hist || []) {
+ const ri = document.createElement('li')
+ ri.innerHTML = `<span class="n">#${m.n}</span><span class="tag ${m.disk.toLowerCase()}">${m.side}</span><span>${m.x},${m.y} +${m.flips}</span><span>${refTag(m.ref)}</span>`
+ els.refLog.appendChild(ri)
+ const li = document.createElement('li')
+ li.innerHTML = `<span>#${m.n}</span><b class="${m.disk.toLowerCase()}">${m.side}</b><span>→ ${m.x},${m.y} (flips ${m.flips})</span>`
+ els.log.appendChild(li)
+ }
+ els.refLog.scrollTop = els.refLog.scrollHeight
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function onFrame(msg) {
+ size = msg.size || size
+ board = msg.board || board
+ counts = msg.counts || counts
+ running = !!msg.running
+ gameOver = !!msg.gameOver
+ rivals = msg.rivals || rivals
+ last = msg.history?.length ? msg.history[msg.history.length - 1] : null
+ els._hist = msg.history || []
+ els.title.textContent = msg.title || ''
+ els.meta.textContent = msg.gameOver ? 'Game over' : (msg.running ? 'live' : 'paused')
+ els.refFocus.textContent = msg.refereeFocus || ''
+ renderBoard()
+ renderScores()
+ renderHistory()
+}
+
+// ---- Controls ----
+$('play').onclick = () => ctl('start')
+$('pause').onclick = () => ctl('pause')
+$('step').onclick = () => ctl('step')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try {
+ const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ if (!r.ok) throw new Error(String(r.status))
+ } catch (e) { console.error('control failed', e) }
+}
+
+// ---- SSE ----
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onFrame(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-duel/viewer/viewer.mjs b/store/agents/jev-duel/viewer/viewer.mjs
new file mode 100644
index 000000000..7d36f77a1
--- /dev/null
+++ b/store/agents/jev-duel/viewer/viewer.mjs
@@ -0,0 +1,365 @@
+// Jev Duel viewer — a loopback server running a live Reversi battle where Jev (TypeSafe's System
+// One model) plays BOTH sides and a third Jev referees. The agent shapes battle.json (board size,
+// the two rivals' names and "personalities" rendered as state-flavor, referee focus). The viewer
+// runs the game loop, asks each side to choose a move, applies the flips, asks the referee to judge
+// every move, and streams it all to the pane over SSE.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. The workspace holds battle.json which the
+// viewer watches (live edit of rivals/personality reframes both Jevs).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DIRS = [[0, 1], [1, 0], [0, -1], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]]
+
+// Fresh 6x6 board with Othello's starting four disks (O in the upper-left diagonal of the center).
+function newBoard(n) {
+ const b = Array.from({ length: n }, () => Array(n).fill('.'))
+ const h = n / 2
+ b[h - 1][h - 1] = 'O'; b[h - 1][h] = 'X'; b[h][h - 1] = 'X'; b[h][h] = 'O'
+ return b
+}
+
+function clone(b) { return b.map((r) => r.slice()) }
+
+function legalMoves(b, me) {
+ const n = b.length
+ const them = me === 'O' ? 'X' : 'O'
+ const out = []
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
+ if (b[y][x] !== '.') continue
+ let flips = 0
+ for (const [dx, dy] of DIRS) {
+ let nx = x + dx, ny = y + dy, c = 0
+ while (nx >= 0 && ny >= 0 && nx < n && ny < n && b[ny][nx] === them) { c++; nx += dx; ny += dy }
+ if (c > 0 && nx >= 0 && ny >= 0 && nx < n && ny < n && b[ny][nx] === me) flips += c
+ }
+ if (flips > 0) out.push({ x, y, flips })
+ }
+ return out
+}
+
+function applyMove(b, x, y, me) {
+ const n = b.length
+ const them = me === 'O' ? 'X' : 'O'
+ b[y][x] = me
+ for (const [dx, dy] of DIRS) {
+ let nx = x + dx, ny = y + dy, chain = []
+ while (nx >= 0 && ny >= 0 && nx < n && ny < n && b[ny][nx] === them) { chain.push([nx, ny]); nx += dx; ny += dy }
+ if (chain.length && nx >= 0 && ny >= 0 && nx < n && ny < n && b[ny][nx] === me) {
+ for (const [cx, cy] of chain) b[cy][cx] = me
+ }
+ }
+}
+
+function count(b) {
+ let o = 0, x = 0
+ for (const r of b) for (const c of r) { if (c === 'O') o++; else if (c === 'X') x++ }
+ return { O: o, X: x }
+}
+
+function boardText(b, me) {
+ // Rendered as a plain grid the mock's Reversi reader parses; the "you play O/X" line names the
+ // side Jev is being asked to move for.
+ let s = `you play ${me}\n`
+ s += b.map((r) => r.join('')).join('\n')
+ s += '\n'
+ return s
+}
+
+function stateBlock(battle, board, side, love) {
+ return `Two rivals are playing a live game of Reversi (Othello) on a ${battle.size}x${battle.size} board.
+You are ${side.name}, playing ${side.disk}. ${side.personality}
+Your rival is ${side.rival}, playing ${side.rivalDisk}. ${battle.rivals[side.rival]?.personality || ''}
+
+The board, '.' empty, O and X are claimed disks:
+${boardText(board, side.disk)}
+
+Legal moves and the disks each flips:
+${love.map((m) => ` ${m.x},${m.y} flips ${m.flips}`).join('\n')}
+
+Current score — O: ${count(board).O}, X: ${count(board).X}.
+
+Choose the move that best serves your personality and wins the game. Prefer corners. Never play a legal-move
+coordinate that isn't listed.`
+}
+
+function refState(battle, board, move, side) {
+ const c = count(board)
+ return `You are the referee of a live Reversi battle between ${battle.rivals.O.name} (O) and ${battle.rivals.X.name} (X).
+
+Board just after ${side.name} (${side.disk}) played ${move.x},${move.y} (flipping ${move.flips} disks):
+${boardText(board, 'O')}
+
+Score — O: ${c.O}, X: ${c.X}.
+
+Referee focus: ${battle.referee}`
+
+}
+
+function verdict(battle, c, filled, gameOver, winner, state) {
+ const leader = c.O === c.X ? 'tied' : (c.O > c.X ? `${battle.rivals.O.name} leads` : `${battle.rivals.X.name} leads`)
+ const total = c.O + c.X
+ return {
+ spec: 1,
+ ready: true,
+ summary: state.error
+ ? 'Duel needs a fix'
+ : gameOver
+ ? `${winner ?? 'Draw'} — final ${c.O}–${c.X}`
+ : `${battle.rivals.O.name} (O) vs ${battle.rivals.X.name} (X) — ${leader} ${c.O}–${c.X}`,
+ findings: state.error ? [{ severity: 'error', kind: 'duel', message: state.error }] : [],
+ artifact: 'battle.json',
+ phases: [
+ { id: 'open', name: 'Opening', state: total <= 12 ? 'active' : 'done' },
+ { id: 'midgame', name: 'Midgame', state: total > 12 && !gameOver ? 'active' : total > 12 ? 'done' : 'pending' },
+ { id: 'endgame', name: 'Endgame', state: gameOver ? 'done' : total >= filled * 0.8 ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+}
+
+export async function startDuelViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let battle = readBattle(join(workspace, 'battle.json'))
+ let board = newBoard(battle.size)
+ let toMove = 'O'
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let running = false
+ let gameOver = false
+ let gameOverAt = 0 // when the last game ended; a new one starts by itself a few seconds later
+ let winner = null
+ let error = null
+ let history = [] // [{n, side, disk, x, y, flips, ref:[...], at}]
+ let moveCount = 0
+
+ function readBattle(file) {
+ try {
+ return { ...DEFAULT_BATTLE, ...JSON.parse(readFileSync(file, 'utf8')) }
+ } catch {
+ return DEFAULT_BATTLE
+ }
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function tail() {
+ const c = count(board)
+ const v = verdict(battle, c, board.length * board.length, gameOver, winner, { error })
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'frame',
+ title: battle.title,
+ description: battle.description,
+ size: battle.size,
+ board,
+ toMove,
+ counts: c,
+ running,
+ gameOver,
+ winner,
+ error,
+ rivals: battle.rivals,
+ refereeFocus: battle.referee,
+ history: history.slice(-30),
+ moveCount,
+ })
+ }
+
+ async function askSide(side) {
+ const love = legalMoves(board, side.disk)
+ if (!love.length) return null
+ const res = await evaluate({
+ state: stateBlock(battle, board, side, love),
+ questions: {
+ move: {
+ type: 'choice',
+ instructions: 'Choose the strongest Reversi move for your side, as a "x,y" coordinate.',
+ options: love.map((m) => `${m.x},${m.y}`),
+ },
+ confident: {
+ type: 'noul',
+ instructions: 'Is this a move you feel confident about, or a defensively forced one?',
+ },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const picked = res.answers.move?.choice
+ const chosen = love.find((m) => `${m.x},${m.y}` === String(picked)) || love[0]
+ return { ...chosen, confidence: res.answers.confident?.noul ?? 0.5, client: res.client, model: res.model, probs: res.answers.move?.probabilities }
+ }
+
+ async function referee(move, side) {
+ const res = await evaluate({
+ state: refState(battle, board, move, side),
+ questions: {
+ strong: {
+ type: 'score',
+ instructions: 'How strong was this move tactically?',
+ legend: { 0: 'blunder', 1: 'solid', 2: 'brilliant' },
+ },
+ aggressive: {
+ type: 'noul',
+ instructions: 'Was this an aggressive, material-taking move or a quiet positional one?',
+ },
+ decided: {
+ type: 'score',
+ instructions: 'How decided is the game right now for the side that just moved?',
+ legend: { 0: 'wide open', 1: 'leaning', 2: 'decided' },
+ },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const a = res.answers
+ return {
+ strong: typeof a.strong?.score === 'number' ? a.strong.score : 1,
+ aggressive: a.aggressive?.noul ?? 0.5,
+ decided: typeof a.decided?.score === 'number' ? a.decided.score : 0,
+ }
+ }
+
+ async function step() {
+ if (stopped || gameOver) return
+ try {
+ const side = { disk: toMove, name: battle.rivals[toMove]?.name || toMove, personality: battle.rivals[toMove]?.personality || '', rival: toMove === 'O' ? 'X' : 'O', rivalDisk: toMove === 'O' ? 'X' : 'O' }
+ const move = await askSide(side)
+ if (move) {
+ applyMove(board, move.x, move.y, side.disk)
+ moveCount++
+ const ref = await referee(move, side)
+ history.push({ n: moveCount, side: side.name, disk: side.disk, x: move.x, y: move.y, flips: move.flips, ref, at: new Date().toISOString() })
+ if (history.length > 200) history.splice(0, history.length - 200)
+ }
+ // Pass if no legal move; game over when neither side can move.
+ const next = toMove === 'O' ? 'X' : 'O'
+ if (!legalMoves(board, next).length) {
+ if (!legalMoves(board, toMove).length) {
+ const c = count(board)
+ if (c.O !== c.X) winner = c.O > c.X ? battle.rivals.O?.name || 'O' : battle.rivals.X?.name || 'X'
+ gameOver = true
+ gameOverAt = Date.now()
+ }
+ // else: stick (both effectively stalled but next side has no move -> keep current side) — handled by loop guard
+ } else {
+ toMove = next
+ }
+ error = null
+ } catch (e) {
+ error = clean(e.message)
+ }
+ tail()
+ }
+
+ let timer = null
+ function schedule() {
+ clearTimeout(timer)
+ timer = setTimeout(run, battle.speed ?? 700)
+ }
+ async function run() {
+ if (stopped) return
+ // Never sit on a finished board: show the result for a few seconds, then play again.
+ if (gameOver) { if (Date.now() - gameOverAt > 5000) reset(); else schedule(); return }
+ await step()
+ schedule()
+ }
+ function start() { if (!running) { running = true; schedule() } }
+ function pause() { running = false; clearTimeout(timer) }
+ function reset() {
+ board = newBoard(battle.size); toMove = 'O'; gameOver = false; winner = null; history = []; moveCount = 0; salt += 10; error = null
+ tail()
+ if (running) schedule()
+ }
+
+ const watcher = watch(workspace, { recursive: true }, (_, name) => {
+ if (!name) return
+ if (String(name).split('/').join('/') === 'battle.json') {
+ battle = readBattle(join(workspace, 'battle.json'))
+ if (battle.size !== board.length) { board = newBoard(battle.size); toMove = 'O'; moveCount = 0; history = [] }
+ tail()
+ if (running) schedule()
+ }
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: battle.title, size: battle.size, board, toMove, counts: count(board), running, gameOver, winner, history: history.slice(-30), rivals: battle.rivals })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'step') await step()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+// The default battle is used when battle.json is absent; the workspace template ships the real one.
+const DEFAULT_BATTLE = {
+ title: 'Jev vs Jev',
+ description: 'A Reversi duel between two minds.',
+ size: 6,
+ speed: 700,
+ rivals: {
+ O: { name: 'Jev·O', personality: 'A patient, positional player who loves the corners.' },
+ X: { name: 'Jev·X', personality: 'A greedy opportunist who grabs flips and attacks the center.' },
+ },
+ referee: 'Call it fairly — is the move strong, is it aggressive, how decided is the game?',
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startDuelViewer({ workspace, port })
+ console.log(`Jev Duel listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-firehose/.gitignore b/store/agents/jev-firehose/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-firehose/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-firehose/AGENTS.md b/store/agents/jev-firehose/AGENTS.md
new file mode 100644
index 000000000..b66bb4ac2
--- /dev/null
+++ b/store/agents/jev-firehose/AGENTS.md
@@ -0,0 +1,116 @@
+# Jev Firehose in OpenHarness
+
+On the left is a live pane. A seeded generator writes **made-up** messages for a support inbox and
+sprays them through a gate. **Jev, TypeSafe's System One model, triages every message in one call**
+with five parallel questions: `team` (choice), `urgency` (score), `spam` (noul), `needs_human`
+(noul), `mood` (score). If Jev's `team` confidence is under the threshold, the message drops into
+an amber "escalate to a big model" lane instead of a team bin. Every message has a known true team,
+so the pane measures accuracy live.
+
+On the right is you. **You edit one file: `firehose.json`.** The viewer watches it and restarts the
+batch with your settings within a second. All data is synthetic. Say so when you describe it.
+
+## Your job: design the taxonomy
+
+You are the desk designer. A good session looks like this:
+
+1. **Invent a desk.** A game studio's player support, a bike shop, a city help line, a vet clinic, a
+ library. Pick one and give it a made-up name in `desk`. Say it is made up.
+2. **Write the teams.** 2 to 24 of them. Each team needs a sharp `description` and at least 4
+ `phrases` (8 to 12 is better). See "Writing teams" below.
+3. **Tune `noise` and `threshold`.** Noise makes messages harder. The threshold trades accuracy for
+ escalations.
+4. **Find the threshold** where auto-routing stays above `targetAccuracy` while escalations stay
+ low. Report the number and what it costs in escalations.
+
+Do not ship the starter desk with a new title. Build a desk with its own teams.
+
+## The file
+
+```jsonc
+{
+ "title": "Jev Firehose",
+ "desk": "Lumen Lane, a made-up online lamp shop. Every message is synthetic.",
+ "noise": 0.2, // 0..1 wrong-team phrases mixed into each message (the difficulty dial)
+ "threshold": 0.55, // 0..1 team confidence under this goes to the escalate lane
+ "targetAccuracy": 0.95, // 0.5..1 the accuracy you want for auto-routed messages
+ "ratePerSec": 40, // 1..400 messages started per second
+ "concurrency": 8, // 1..64 calls in flight at once
+ "batch": 2000, // 50..100000 messages per batch, then a summary card, then a new seed
+ "llmSecondsPerItem": 2, // 0.1..120 the assumed speed of a slow model, drawn as a ghost bar
+ "spamRate": 0.07, // 0..0.5 share of messages that are spam
+ "seed": 7, // whole number; the same seed gives the same stream
+ "teams": [
+ {
+ "id": "billing", // short, unique, shown on the bin
+ "description": "Payment: card charged, invoice, refund, receipt, price, tax, discount voucher.",
+ "weight": 1.5, // optional 0.1..10, how common this team is
+ "phrases": ["my card was charged twice for the same payment", "..."]
+ }
+ ]
+}
+```
+
+How a message is made: an opener (carries the mood), 1 to 3 phrases from the TRUE team, then
+`floor(noise * 3 + random)` phrases from ONE wrong team (never more than the true ones), then a
+closer (carries the urgency). Some messages are spam.
+
+## Writing teams
+
+Jev sees only the message and, for each team, its `id` and `description`. It does not see the
+phrases list. So:
+
+- **Descriptions are the contract.** Name the things the team handles with plain nouns:
+ "Delivery: parcel, courier, tracking, late, lost, package, shipping address, customs."
+- **Phrases must sound like that description.** Each phrase should use two or three of the
+ description's words. "the courier lost the package during delivery" is good. "where is my stuff"
+ is not.
+- **Keep teams apart.** If two descriptions share words, they will be confused. Sometimes that is
+ what you want to show. Do it on purpose, and say so.
+- Write phrases the way a customer would, lower case, no full stop. The generator adds those.
+- Avoid words the other questions use: urgent, today, emergency, manager, lawyer, complaint, angry,
+ furious, prize, winner, free gift.
+
+Without a `TYPESAFE_API_KEY` the harness runs on an offline stand-in that matches shared words. It
+is strict about exact words ("invoice" and "invoices" do not match). `check.mjs` warns about phrases
+that will not route. With a key, live Jev reads meaning, and sharp descriptions still help.
+
+## Measure, do not guess
+
+```bash
+node "$JEV_DSH/toolchain/check.mjs" # ranges, team shape, vocabulary warnings
+node "$JEV_DSH/toolchain/measure.mjs" # accuracy and escalations at each threshold
+node "$JEV_DSH/toolchain/measure.mjs" --noise 0.6 --n 1000
+```
+
+`measure.mjs` uses the same generator and the same five questions as the pane. It prints a table,
+the lowest threshold that meets `targetAccuracy`, and the most confused team pairs. With a key it
+makes real calls (600 messages cost about one cent). You can also read `.harness/verdict.json` for
+the numbers of the batch now running in the pane.
+
+Report what you find, including bad news. If no threshold reaches the target at your noise, say so.
+If two teams are always confused, fix the descriptions or say why you kept them.
+
+## Rules
+
+- Edit ONLY `firehose.json`. Do not edit the viewer, the toolchain or `.harness/verdict.json`. The
+ viewer writes the verdict itself.
+- Keep `firehose.json` valid JSON. A bad edit does not crash the pane. It keeps the last good desk
+ and shows the parse error until you fix it. Out-of-range values are clamped and shown as warnings.
+- The viewer is already running in the pane on the left. Do not open a browser, do not start
+ another server, and do not change ports.
+- The person can drag the noise and threshold sliders in the pane. Those are runtime overrides. Your
+ next edit to `firehose.json` resets them to the file's values.
+- Everything here is synthetic. Never present the desk, the messages or the numbers as a real
+ company, real customers or a real benchmark. The "2s per message" ghost bar is an assumption, not
+ a measurement of any model.
+- The `MOCK` badge means the offline stand-in is answering. Do not describe its numbers as Jev's
+ accuracy.
+
+## Definition of done
+
+- `firehose.json` passes `check.mjs` with no errors, and you have read the warnings.
+- The desk is your own: a made-up name, teams with sharp descriptions, at least 4 phrases each.
+- You ran `measure.mjs` and can state: accuracy and escalations at your threshold, and the lowest
+ threshold that meets the target.
+- You told the person what to try in the pane: drag the threshold, raise the noise, click a bin.
diff --git a/store/agents/jev-firehose/LICENSE b/store/agents/jev-firehose/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-firehose/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-firehose/README.md b/store/agents/jev-firehose/README.md
new file mode 100644
index 000000000..593aeea5d
--- /dev/null
+++ b/store/agents/jev-firehose/README.md
@@ -0,0 +1,107 @@
+# Jev Firehose
+
+**Thousands of made-up inbox messages stream in. Jev triages every one in a single call.**
+
+Jev is TypeSafe AI's System One model. It does not write text. You send it a state and a set of
+typed questions, and it answers all of them in one pass, each with probabilities. Jev Firehose
+shows what that is good for: sorting a lot of small things, fast and cheap.
+
+A seeded generator writes synthetic messages for a support inbox. Each message has a known true
+team, so the pane can measure accuracy as it goes. For every message Jev answers five questions in
+one call:
+
+| question | type | what it asks |
+|---|---|---|
+| `team` | choice | which team should own this message |
+| `urgency` | score, 5 levels | how fast the sender wants an answer |
+| `spam` | noul | is this spam |
+| `needs_human` | noul | should a person take over |
+| `mood` | score, 3 levels | calm, annoyed or furious |
+
+If Jev's `team` confidence is under the `threshold`, the message is not auto-routed. It drops into
+an amber "escalate to a big model" lane. The pane shows how many were auto-routed, how many of those
+were right, and how many were escalated.
+
+This is a harness for OpenHarness. The agent on the right edits `firehose.json`. The viewer on the
+left watches that file and reacts live.
+
+**All data here is made up.** The shop, the teams and every message are synthetic. This is a demo of
+speed, cost and calibration, not a real support system.
+
+## The pane
+
+- **Main scene.** Messages spray from the nozzle as small tiles, coloured by their true team. They
+ cross the Jev gate at the height of Jev's confidence, then arc into team bins that fill up. A red
+ ring marks a wrong bin. Tiles under the threshold drop into the amber lane.
+- **Top bar.** Messages done, messages per second, cost so far, accuracy of auto-routed messages,
+ share escalated, elapsed time.
+- **The race.** Jev's progress bar, and under it a ghost bar: "a model taking 2s per message would
+ be on message N". The 2 seconds is an assumption you can change (`llmSecondsPerItem`).
+- **Rail.** Jev's live mind (questions and probability bars), an inspector, a short "how it works",
+ and a confusion matrix (true team by routed bin).
+
+Things to try in the pane:
+
+1. Drag the **threshold** slider, or drag the amber line on the gate. Messages that were already
+ routed move between the bins and the escalate lane at once.
+2. Drag the **noise** slider. New messages get more phrases from a wrong team mixed in.
+3. Click a **bin** or a **tile**. The inspector shows the message text, every answer with its
+ probabilities, the true team, and right or wrong.
+4. Press **Burst +500**.
+5. **Pause**, **Step**, **Reset**.
+
+Slider changes are runtime overrides. An edit to `firehose.json` resets them.
+
+When a batch is done the pane shows a summary card for about three seconds, for example
+`2,000 messages · 50.0s · $0.0445 · 97.3% right · 10.1% escalated`, then starts the next batch with a
+new seed. It never stops.
+
+## The honest dial
+
+`noise` (0 to 1) sets how many phrases from one wrong team are mixed into each message. It is capped
+so a message never has more wrong-team phrases than true ones. At low noise the true team is clear.
+At high noise every message is an even split, so any reader, model or person, has to guess.
+
+Measured on the starter desk with the offline stand-in, threshold 0.55, 400 messages each:
+
+| noise | auto-routed right | escalated |
+|---|---|---|
+| 0.05 | 99.5% | 2.5% |
+| 0.85 | 58.4% | 24.3% |
+
+Nothing random is injected into Jev's answers. The messages themselves get harder.
+
+## Anatomy
+
+```
+jev-firehose/
+ harness.json manifest (engine: claude)
+ AGENTS.md instructions for the chat agent
+ skills/firehose/SKILL.md how to design a desk and pick a threshold
+ template/firehose.json the starter desk (a made-up lamp shop, 8 teams)
+ toolchain/
+ jev.mjs Jev client: real API with a key, offline stand-in without
+ check.mjs validates firehose.json
+ measure.mjs scores a desk from the command line, threshold by threshold
+ viewer.sh setup.sh doctor.sh init-workspace.sh
+ viewer/ loopback server (viewer.mjs, kit.mjs) and the pane
+ test/viewer.test.mjs
+```
+
+## Jev, honestly
+
+With `TYPESAFE_API_KEY` set, every message is one real call to `POST /v1/systemone`. Without a key
+the harness runs on a deterministic offline stand-in that scores shared words between the message
+and each option's description. The stand-in is there so the plumbing, the pane and the tests work
+offline. It is **not** Jev's judgement, and the pane badges it `MOCK`. The cost shown is what live
+Jev would charge for the same tokens ($0.042 per million input tokens, output free).
+
+The "2s per message" comparison is an assumption drawn as a ghost bar, not a measurement of any
+model.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness only calls the public API. It
+ contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed. This wrapper is MIT too (see `LICENSE`).
+- **Autonomous** built and maintains this harness for the OpenHarness store.
diff --git a/store/agents/jev-firehose/THIRD_PARTY_NOTICES.md b/store/agents/jev-firehose/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-firehose/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-firehose/harness.json b/store/agents/jev-firehose/harness.json
new file mode 100644
index 000000000..c77eddece
--- /dev/null
+++ b/store/agents/jev-firehose/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-firehose",
+ "name": "Jev Firehose",
+ "category": "AI",
+ "author": "Autonomous",
+ "description": "A live map-reduce demo on made-up data. Thousands of synthetic inbox messages stream in, and Jev, TypeSafe's System One model, triages each one in a single call with five parallel questions. Unsure ones go to an escalate lane. Speed, cost, count and measured accuracy climb as you watch.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "firehose.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-firehose/skills/firehose/SKILL.md b/store/agents/jev-firehose/skills/firehose/SKILL.md
new file mode 100644
index 000000000..5de4de829
--- /dev/null
+++ b/store/agents/jev-firehose/skills/firehose/SKILL.md
@@ -0,0 +1,113 @@
+# Craft — Jev Firehose
+
+Jev Firehose is a triage demo on made-up data. Thousands of synthetic inbox messages stream in. Jev
+answers five typed questions about each one in a single call. Messages with low `team` confidence
+are escalated instead of auto-routed. Your craft is the desk: the teams, their words, the noise and
+the threshold.
+
+## The decision, per message
+
+One `evaluate()` call. The state is the message text. The questions:
+
+```
+team choice one option per team, each with its description
+urgency score 5 levels, "no rush" to "emergency"
+spam noul
+needs_human noul
+mood score 3 levels, calm to furious
+```
+
+Routing rule, in this order:
+
+1. `spam` is 0.5 or more: the message goes to the spam bin.
+2. `team` confidence is under `threshold`: it goes to the escalate lane.
+3. Otherwise it goes to the bin of the chosen team.
+
+A routed message is right when its bin matches its true team (or it is spam in the spam bin).
+Accuracy counts auto-routed messages only. Escalated ones are counted apart.
+
+## The honest dial: `noise`
+
+`noise` adds `floor(noise * 3 + random)` phrases from ONE wrong team to each message, never more
+than the number of true phrases (1 to 3).
+
+- `0.05`: almost every message is clean. Expect 99% right and 2 to 4% escalated on the starter desk.
+- `0.2`: the starter setting. About 97% right, 10% escalated at threshold 0.55.
+- `0.5`: many messages are half about another team. About 80% right, 19% escalated.
+- `0.85`: nearly every message is an even split. About 60% right, 25% escalated.
+
+Nothing random is added to Jev's answers. The messages get more mixed, so the right answer gets
+less clear. A person would struggle too.
+
+## The threshold trade-off
+
+Raising `threshold` sends more messages to the big model and makes the rest more accurate. The pane
+draws this curve above the threshold slider (green is accuracy, amber is the escalated share).
+`measure.mjs` prints the same thing as a table:
+
+```
+threshold right escalated
+ 0.40 93.5% 0.7%
+ 0.55 97.6% 10.3% <- threshold in the file
+ 0.70 99.4% 19.0%
+lowest threshold with at least 95.0% right: 0.46 (95.5% right, 4.2% escalated)
+```
+
+Pick the lowest threshold that meets `targetAccuracy`. If escalations at that point are too high,
+the fix is the desk (sharper descriptions, less overlap), not the threshold.
+
+At high noise no threshold may reach the target without escalating most of the stream. That is a
+finding. Report it.
+
+## Writing a desk that routes
+
+Jev gets each team's `id` and `description`, never the phrases. So write them as a pair:
+
+```jsonc
+{
+ "id": "brakes",
+ "description": "Brakes: pads, rotor, lever, squeal, hydraulic bleed.",
+ "phrases": [
+ "my brake lever is soft after the bleed",
+ "the rotor rubs the pads and there is a squeal",
+ "new pads but the lever still pulls to the bar",
+ "hydraulic bleed needed, the brakes feel spongy"
+ ]
+}
+```
+
+- 6 to 10 plain nouns in the description. No filler words.
+- Every phrase uses two or three of those nouns, in the same form (the offline stand-in does not
+ match "invoice" with "invoices").
+- No noun shared between two descriptions, unless you want that pair to be confused.
+- 8 to 12 phrases per team gives varied messages. 4 is the minimum.
+- Use `weight` to make some teams busier than others. Bins then fill at different speeds.
+- Keep ids short. They are the labels on the bins.
+
+`check.mjs` warns when a phrase shares fewer than 2 words with its own description, when a phrase
+leans toward another team, and when two descriptions share 3 or more words.
+
+## A good session
+
+1. Write the desk. Run `check.mjs`. Fix errors, read warnings.
+2. Run `measure.mjs` at your noise. Look at the most confused pairs. Sharpen those descriptions.
+3. Set `threshold` to the lowest value that meets the target. Run `measure.mjs` again.
+4. Try `--noise 0.6`. Say how the desk degrades.
+5. Tell the person what you found and what to poke in the pane.
+
+## Verifying
+
+```bash
+node "$JEV_DSH/toolchain/check.mjs"
+node "$JEV_DSH/toolchain/measure.mjs" --n 800
+```
+
+Then watch the pane: bins fill, the accuracy number settles near what `measure.mjs` printed, and the
+confusion matrix lights up on the pairs you expected.
+
+## Definition of done
+
+- `firehose.json` passes `check.mjs`.
+- The desk is your own and says it is made up.
+- You can state accuracy and escalations at your threshold, and the lowest threshold that meets the
+ target, from a measurement and not from a guess.
diff --git a/store/agents/jev-firehose/store.json b/store/agents/jev-firehose/store.json
new file mode 100644
index 000000000..ae19122a2
--- /dev/null
+++ b/store/agents/jev-firehose/store.json
@@ -0,0 +1,17 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev triages thousands of made-up inbox messages live: fast, cheap, measured",
+ "examples": [
+ {
+ "prompt": "Turn the desk into player support for a made-up game studio. Write 8 teams with sharp descriptions and at least 6 phrases each. Then find the lowest threshold that keeps auto-routing above 95% right at noise 0.3, and tell me how many messages it escalates.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-firehose/triage-wall.jpg",
+ "caption": "A new desk designed by the agent, with a measured threshold"
+ },
+ {
+ "prompt": "Make it hard. Set noise to 0.7 and tell me what happens to accuracy and escalations, which two teams get mixed up most, and which threshold you would pick.",
+ "caption": "Turn the noise dial and read the trade-off on synthetic data"
+ }
+ ]
+}
diff --git a/store/agents/jev-firehose/template/firehose.json b/store/agents/jev-firehose/template/firehose.json
new file mode 100644
index 000000000..0cf2e376a
--- /dev/null
+++ b/store/agents/jev-firehose/template/firehose.json
@@ -0,0 +1,151 @@
+{
+ "title": "Jev Firehose",
+ "desk": "Lumen Lane, a made-up online lamp shop. Every message is synthetic.",
+ "noise": 0.2,
+ "threshold": 0.55,
+ "targetAccuracy": 0.95,
+ "ratePerSec": 40,
+ "concurrency": 8,
+ "batch": 2000,
+ "llmSecondsPerItem": 2,
+ "spamRate": 0.07,
+ "seed": 7,
+ "teams": [
+ {
+ "id": "billing",
+ "description": "Payment: card charged, invoice, refund, receipt, price, tax, discount voucher.",
+ "weight": 1.5,
+ "phrases": [
+ "my card was charged twice for the same payment",
+ "the invoice shows the wrong price and no tax",
+ "the refund for my payment has not reached my card",
+ "please send a receipt and an invoice for my last payment",
+ "the discount voucher did not lower the price at payment",
+ "I need an invoice with our tax number and the full price",
+ "a refund was promised but my card was charged again",
+ "you charged my card before the payment was confirmed",
+ "the receipt lists a price and tax I never agreed to",
+ "can I get a refund of the tax on this invoice"
+ ]
+ },
+ {
+ "id": "shipping",
+ "description": "Delivery: parcel, courier, tracking, late, lost, package, shipping address, customs.",
+ "weight": 1.4,
+ "phrases": [
+ "the tracking has not moved and the parcel is late",
+ "the courier marked the delivery done but no package arrived",
+ "I need to fix the shipping address before the courier collects the parcel",
+ "my parcel is stuck in customs with no tracking update",
+ "the delivery is many days late and the courier will not answer",
+ "the package was left at the wrong address by the courier",
+ "can you send the tracking number for my late parcel",
+ "the courier lost the package during delivery",
+ "shipping to my address shows a very late delivery",
+ "customs asked me to pay before delivery of the parcel"
+ ]
+ },
+ {
+ "id": "returns",
+ "description": "Returns: exchange, damaged or broken lamp, faulty item, replacement, warranty claim, return label.",
+ "weight": 1.1,
+ "phrases": [
+ "the lamp arrived broken and I want a replacement",
+ "how do I return an item that is damaged",
+ "I would like to exchange this faulty lamp for a new one",
+ "the shade is damaged, is that covered by a warranty claim",
+ "please start a warranty claim for the broken switch",
+ "I posted the item, when does the exchange or replacement go out",
+ "the replacement lamp was also damaged on arrival",
+ "can I return a faulty lamp after thirty days",
+ "my warranty claim was refused and the lamp is still broken",
+ "I need a return label for a damaged item"
+ ]
+ },
+ {
+ "id": "account",
+ "description": "Account access: login, password reset, email, locked profile, security code, delete my data.",
+ "weight": 1.0,
+ "phrases": [
+ "I cannot login, the password reset email never comes",
+ "my account is locked after the security code failed",
+ "please update the email and password on my profile",
+ "the password reset says expired when I login",
+ "I want you to delete my data and close the account",
+ "login keeps asking for a security code I do not get",
+ "someone took over the email on my account and it is locked",
+ "how do I get access to my profile after a password reset",
+ "the security code never arrives when I login to my account",
+ "reset my password, I no longer have access to the old email"
+ ]
+ },
+ {
+ "id": "technical",
+ "description": "Website or app bug: page error, crash, slow loading, button, browser.",
+ "weight": 0.9,
+ "phrases": [
+ "the app shows a crash report when I open the cart page",
+ "the website shows an error on every page",
+ "the checkout button does nothing in my browser, looks like a bug",
+ "the app is slow and stuck on loading forever",
+ "there is a bug, the search page is blank in the app",
+ "the app froze and then a crash error came up",
+ "your website is very slow, loading a page takes ages",
+ "error 500 when I press the save button on the website",
+ "the app will not open after the update, only a crash and an error",
+ "images are not loading in any browser on your website"
+ ]
+ },
+ {
+ "id": "orders",
+ "description": "Order change: cancel, size, colour, quantity, stock, confirmation, dispatch date.",
+ "weight": 0.9,
+ "phrases": [
+ "please cancel my order, I picked the wrong colour",
+ "can I change the quantity on the order I placed",
+ "I never got an order confirmation or a dispatch date",
+ "the size I want is out of stock, can I change my order",
+ "change the size on my order to the large one",
+ "please cancel half the quantity on my order",
+ "is the brass colour back in stock, I want to order it",
+ "my order confirmation shows the wrong quantity",
+ "can you raise the quantity before dispatch of the order",
+ "please change the colour on order 4417 to black"
+ ]
+ },
+ {
+ "id": "club",
+ "description": "Bulb club membership: subscription plan, renewal, upgrade, downgrade, pause, monthly box, trial.",
+ "weight": 0.7,
+ "phrases": [
+ "I want to pause my club subscription for two months",
+ "the renewal went through but I asked to stop the plan and the membership",
+ "how do I upgrade my plan to the bigger monthly box",
+ "my trial ended and the membership renewal came without notice",
+ "please downgrade my subscription to the small plan",
+ "when is the next renewal of my club membership",
+ "the monthly box did not include the trial bulb",
+ "I want to upgrade my subscription before the next renewal",
+ "can I pause the monthly box while I travel",
+ "end my membership when the trial plan is over"
+ ]
+ },
+ {
+ "id": "trade",
+ "description": "Trade and wholesale: bulk quote, reseller, business partner, supplier catalogue, showroom, project.",
+ "weight": 0.5,
+ "phrases": [
+ "we are a reseller and need a bulk quote for forty fittings",
+ "can you send the wholesale catalogue for our showroom",
+ "I run a hotel project and need a trade quote",
+ "do you have trade terms for a business partner",
+ "we would like to become a reseller and wholesale partner in our region",
+ "our business needs a supplier for a large project",
+ "please quote a bulk deal for a cafe project",
+ "is there a wholesale rate for a showroom or a reseller",
+ "who handles trade partner and wholesale terms",
+ "send the supplier catalogue with bulk rates"
+ ]
+ }
+ ]
+}
diff --git a/store/agents/jev-firehose/test/viewer.test.mjs b/store/agents/jev-firehose/test/viewer.test.mjs
new file mode 100644
index 000000000..8da4dd195
--- /dev/null
+++ b/store/agents/jev-firehose/test/viewer.test.mjs
@@ -0,0 +1,295 @@
+// Viewer integration tests for Jev Firehose. Each test spins up the real viewer against a temp
+// workspace. Time is driven with the `tick` control (one decision per tick), never with sleeps,
+// except where a test waits for the file watcher or the free-running loop.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { connect } from 'node:net'
+import { spawnSync } from 'node:child_process'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const ROOT = join(HERE, '..')
+const { startFirehoseViewer, sanitize, makeMessage, loadDefaults } = await import(join(ROOT, 'viewer/viewer.mjs'))
+const TEMPLATE = JSON.parse(readFileSync(join(ROOT, 'template/firehose.json'), 'utf8'))
+
+const wait = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function fresh(overrides = {}, rawText = null) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-firehose-test-'))
+ const file = join(ws, 'firehose.json')
+ writeFileSync(file, rawText ?? JSON.stringify({ ...TEMPLATE, ...overrides }))
+ const viewer = await startFirehoseViewer({ workspace: ws, port: 0 })
+ const base = viewer.url
+ const state = async () => (await fetch(`${base}/state`)).json()
+ const ctl = async (cmd, extra = {}) => {
+ const res = await fetch(`${base}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd, ...extra }) })
+ return { status: res.status, body: await res.json() }
+ }
+ /** Stop the free-running loop and start from a clean batch, so `tick` alone moves time. */
+ const hold = async () => { await ctl('pause'); await ctl('reset') }
+ return { ws, file, viewer, base, state, ctl, hold }
+}
+
+test('the loop advances on its own and Jev answers five questions per message', async () => {
+ const v = await fresh()
+ try {
+ let s
+ const deadline = Date.now() + 4000
+ while (Date.now() < deadline) { s = await v.state(); if (s.n >= 5) break; await wait(60) }
+ assert.ok(s.n >= 5, 'expected the stream to move without any input')
+ assert.equal(s.running, true)
+ assert.deepEqual(s.questions, ['team', 'urgency', 'spam', 'needs_human', 'mood'])
+ const a = s.last.answers
+ assert.ok(s.teams.map((t) => t.id).includes(a.team.choice), 'team answer is one of the configured teams')
+ assert.ok(a.team.confidence > 0 && a.team.confidence <= 1)
+ const sum = Object.values(a.team.probabilities).reduce((x, y) => x + y, 0)
+ assert.ok(Math.abs(sum - 1) < 0.02, 'team probabilities are a distribution')
+ assert.ok(Math.max(...Object.values(a.team.probabilities)) < 1, 'never exactly one-hot')
+ assert.equal(a.urgency.type, 'score'); assert.equal(a.mood.type, 'score')
+ assert.ok(a.spam.noul >= 0 && a.spam.noul <= 1); assert.ok(a.needs_human.noul >= 0 && a.needs_human.noul <= 1)
+ assert.ok(s.costUsd > 0 && s.tokens > 0, 'cost is metered')
+ assert.equal(s.stats.done, s.n)
+ assert.equal(s.stats.answers, s.n * 5)
+ assert.equal(s.client, 'mock')
+ } finally { await v.viewer.close() }
+})
+
+test('config from firehose.json really shows up in /state', async () => {
+ const teams = [
+ { id: 'brakes', description: 'Brake pads, rotor, lever, squeal, hydraulic bleed.', phrases: ['my brake lever is soft after the bleed', 'the rotor rubs the brake pads', 'hydraulic brake squeal on the rotor', 'new pads but the lever still pulls to the bar'] },
+ { id: 'wheels', description: 'Wheel, tyre, tube, puncture, spoke, rim.', phrases: ['a spoke broke and the rim is bent', 'the tyre keeps losing air, maybe the tube', 'puncture again on the rear wheel', 'the rim tape moved and cut the tube'] },
+ { id: 'fitting', description: 'Bike fit: saddle height, reach, stem, handlebar, knee pain.', phrases: ['knee pain since I raised the saddle', 'the reach feels long, do I want a shorter stem', 'handlebar width for my fit', 'saddle height after the new stem'] },
+ ]
+ const v = await fresh({ title: 'Spoke & Chain', desk: 'A made-up bike shop.', noise: 0.33, threshold: 0.61, targetAccuracy: 0.9, ratePerSec: 77, concurrency: 3, batch: 321, llmSecondsPerItem: 5, spamRate: 0.2, seed: 99, teams })
+ try {
+ const s = await v.state()
+ assert.equal(s.title, 'Spoke & Chain')
+ assert.equal(s.noise, 0.33); assert.equal(s.threshold, 0.61)
+ assert.deepEqual(s.config, { noise: 0.33, threshold: 0.61, targetAccuracy: 0.9, ratePerSec: 77, concurrency: 3, batch: 321, llmSecondsPerItem: 5, spamRate: 0.2, seed: 99 })
+ assert.deepEqual(s.teams.map((t) => t.id), ['brakes', 'wheels', 'fitting'])
+ assert.equal(s.stats.batch, 321)
+ assert.deepEqual(s.warnings, [])
+ await v.hold()
+ const t = await v.ctl('tick', { n: 40 })
+ assert.equal(t.body.did, 40)
+ assert.ok(['brakes', 'wheels', 'fitting'].includes(t.body.last.answers.team.choice))
+ assert.equal(t.body.stats.bins.length, 3 + 2, 'one bin per team, plus spam, plus the escalate lane')
+ } finally { await v.viewer.close() }
+})
+
+test('the verdict file is written with spec 1, a summary, findings and phases', async () => {
+ const v = await fresh()
+ try {
+ await v.hold()
+ await v.ctl('tick', { n: 120 })
+ const file = join(v.ws, '.harness/verdict.json')
+ assert.ok(existsSync(file))
+ const verdict = JSON.parse(readFileSync(file, 'utf8'))
+ assert.equal(verdict.spec, 1)
+ assert.equal(verdict.ready, true)
+ assert.match(verdict.summary, /synthetic messages/)
+ assert.ok(Array.isArray(verdict.findings) && verdict.findings.length >= 2)
+ assert.ok(verdict.findings.some((f) => f.kind === 'threshold'), 'reports the lowest threshold that meets the target')
+ assert.ok(Array.isArray(verdict.phases) && verdict.phases.length === 3)
+ assert.equal(verdict.artifact, 'firehose.json')
+ } finally { await v.viewer.close() }
+})
+
+test('every control command answers 200', async () => {
+ const v = await fresh()
+ try {
+ for (const [cmd, extra] of [['pause'], ['tick'], ['tick', { n: 25 }], ['threshold', { value: 0.7 }], ['noise', { value: 0.5 }], ['burst', { n: 100 }], ['inspect', { id: 3 }], ['bin', { bucket: 0 }], ['sweep'], ['clearOverrides'], ['start'], ['reset'], ['no-such-command']]) {
+ const r = await v.ctl(cmd, extra)
+ assert.equal(r.status, 200, cmd)
+ assert.equal(r.body.ok, true, cmd)
+ }
+ const bad = await fetch(`${v.base}/control`, { method: 'POST', body: '{nope' })
+ assert.equal(bad.status, 400)
+ } finally { await v.viewer.close() }
+})
+
+test('inspect returns the message text, every answer and the truth', async () => {
+ const v = await fresh()
+ try {
+ await v.hold()
+ await v.ctl('tick', { n: 30 })
+ const { body } = await v.ctl('inspect', { id: 12 })
+ const r = body.record
+ assert.equal(r.id, 12)
+ assert.ok(r.text.length > 20 && Array.isArray(r.parts))
+ assert.deepEqual(Object.keys(r.answers), ['team', 'urgency', 'spam', 'needs_human', 'mood'])
+ assert.ok(Number.isInteger(r.truth) && Number.isInteger(r.bucket))
+ assert.ok([true, false, null].includes(r.right))
+ const bin = await v.ctl('bin', { bucket: r.bucket })
+ assert.ok(bin.body.list.length >= 1)
+ } finally { await v.viewer.close() }
+})
+
+test('a bad JSON edit keeps the demo alive and reports the error; a good edit clears it', async () => {
+ const v = await fresh({ noise: 0.1 })
+ try {
+ await v.hold()
+ await v.ctl('tick', { n: 10 })
+ writeFileSync(v.file, '{ "noise": 0.9, oops')
+ let s
+ for (let i = 0; i < 40; i++) { s = await v.state(); if (s.error) break; await wait(75) }
+ assert.ok(s.error, 'the parse error is reported')
+ assert.match(s.error, /firehose\.json/)
+ assert.equal(s.noise, 0.1, 'the last good config still runs')
+ const t = await v.ctl('tick', { n: 10 })
+ assert.equal(t.body.did, 10, 'the stream still advances')
+ const verdict = JSON.parse(readFileSync(join(v.ws, '.harness/verdict.json'), 'utf8'))
+ assert.ok(verdict.findings.some((f) => f.severity === 'error'))
+ writeFileSync(v.file, JSON.stringify({ ...TEMPLATE, noise: 0.6 }))
+ for (let i = 0; i < 40; i++) { s = await v.state(); if (!s.error && s.noise === 0.6) break; await wait(75) }
+ assert.equal(s.error, null)
+ assert.equal(s.noise, 0.6)
+ } finally { await v.viewer.close() }
+})
+
+test('a file edit resets the pane overrides', async () => {
+ const v = await fresh({ noise: 0.1, threshold: 0.5 })
+ try {
+ await v.hold()
+ await v.ctl('noise', { value: 0.77 }); await v.ctl('threshold', { value: 0.88 })
+ let s = await v.state()
+ assert.equal(s.noise, 0.77); assert.equal(s.threshold, 0.88)
+ assert.deepEqual(s.overrides, { noise: true, threshold: true })
+ assert.equal(s.config.noise, 0.1, 'the file value is still known')
+ writeFileSync(v.file, JSON.stringify({ ...TEMPLATE, noise: 0.25, threshold: 0.45 }))
+ for (let i = 0; i < 40; i++) { s = await v.state(); if (s.noise === 0.25) break; await wait(75) }
+ assert.equal(s.noise, 0.25); assert.equal(s.threshold, 0.45)
+ assert.deepEqual(s.overrides, { noise: false, threshold: false })
+ } finally { await v.viewer.close() }
+})
+
+test('out-of-range values are clamped and reported, never fatal', async () => {
+ const v = await fresh({ noise: 7, ratePerSec: 99999, concurrency: 0, batch: 3, teams: [{ id: 'only-one', description: 'x', phrases: ['a'] }] })
+ try {
+ const s = await v.state()
+ assert.equal(s.noise, 1); assert.equal(s.config.ratePerSec, 400); assert.equal(s.config.concurrency, 1); assert.equal(s.config.batch, 50)
+ assert.ok(s.teams.length >= 2, 'falls back to the starter desk when fewer than 2 teams are usable')
+ assert.ok(s.warnings.length >= 4)
+ } finally { await v.viewer.close() }
+ const { cfg, warnings } = sanitize({ ...loadDefaults(), threshold: -2, spamRate: 3 })
+ assert.equal(cfg.threshold, 0); assert.equal(cfg.spamRate, 0.5); assert.equal(warnings.length, 2)
+})
+
+test('a non-loopback Host header gets 403', async () => {
+ const v = await fresh()
+ try {
+ const port = Number(new URL(v.base).port)
+ const ask = (host) => new Promise((resolve, reject) => {
+ const sock = connect(port, '127.0.0.1', () => sock.write(`GET /state HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`))
+ let buf = ''
+ sock.on('data', (d) => { buf += d })
+ sock.on('end', () => resolve(buf.split('\r\n')[0]))
+ sock.on('error', reject)
+ })
+ assert.match(await ask('evil.example.com'), / 403 /)
+ assert.match(await ask(`127.0.0.1:${port}`), / 200 /)
+ } finally { await v.viewer.close() }
+})
+
+test('the noise dial is honest: low noise is accurate with few escalations, high noise is not', async () => {
+ const run = async (noise) => {
+ const v = await fresh({ noise, threshold: 0.55, batch: 1000 })
+ try {
+ await v.hold()
+ const t = await v.ctl('tick', { n: 400 })
+ assert.equal(t.body.did, 400)
+ return t.body.stats
+ } finally { await v.viewer.close() }
+ }
+ const easy = await run(0.05), hard = await run(0.85)
+ console.log(` noise 0.05: ${(easy.accuracy * 100).toFixed(1)}% right, ${(easy.escalatedPct * 100).toFixed(1)}% escalated | noise 0.85: ${(hard.accuracy * 100).toFixed(1)}% right, ${(hard.escalatedPct * 100).toFixed(1)}% escalated`)
+ assert.ok(easy.accuracy > 0.9, `easy accuracy ${easy.accuracy}`)
+ assert.ok(easy.escalatedPct < 0.1, `easy escalations ${easy.escalatedPct}`)
+ assert.ok(hard.accuracy < easy.accuracy - 0.2, `hard accuracy ${hard.accuracy} should fall well below easy ${easy.accuracy}`)
+ assert.ok(hard.escalatedPct > easy.escalatedPct + 0.1, `hard escalations ${hard.escalatedPct} should rise well above easy ${easy.escalatedPct}`)
+})
+
+test('noise only adds wrong-team phrases, never more than the true ones', () => {
+ const { cfg } = sanitize(loadDefaults())
+ let a = 1
+ const rng = () => { a = (a * 1664525 + 1013904223) % 4294967296; return a / 4294967296 }
+ let low = 0, high = 0
+ for (let i = 0; i < 500; i++) {
+ const lo = makeMessage(cfg, rng, 0.05), hi = makeMessage(cfg, rng, 0.95)
+ for (const m of [lo, hi]) { assert.ok(m.nNoise <= m.nTrue || m.spam); assert.ok(m.text.length > 10); if (!m.spam) assert.ok(m.truth >= 0 && m.truth < cfg.teams.length) }
+ low += lo.nNoise; high += hi.nNoise
+ }
+ assert.ok(high > low * 4, `noise phrases: low ${low}, high ${high}`)
+})
+
+test('the threshold re-buckets messages that were already routed', async () => {
+ const v = await fresh({ noise: 0.5, threshold: 0.3, batch: 1000 })
+ try {
+ await v.hold()
+ const loose = (await v.ctl('tick', { n: 300 })).body.stats
+ const strict = (await v.ctl('threshold', { value: 0.8 })).body.stats
+ assert.equal(loose.done, 300); assert.equal(strict.done, 300)
+ assert.equal(loose.routed + loose.escalated, 300); assert.equal(strict.routed + strict.escalated, 300)
+ assert.ok(strict.escalated > loose.escalated + 30, `escalated ${loose.escalated} -> ${strict.escalated}`)
+ assert.ok(strict.accuracy > loose.accuracy, `accuracy ${loose.accuracy} -> ${strict.accuracy}`)
+ assert.equal(strict.bins.reduce((x, y) => x + y, 0), 300, 'every message is in exactly one bucket')
+ const back = (await v.ctl('threshold', { value: 0.3 })).body.stats
+ assert.deepEqual(back.bins, loose.bins, 'moving the threshold back restores the same buckets')
+ const sweep = (await v.ctl('sweep')).body.sweep
+ assert.equal(sweep.length, 101)
+ assert.ok(sweep[90].escalatedPct >= sweep[10].escalatedPct)
+ } finally { await v.viewer.close() }
+})
+
+test('it never ends: a batch finishes with a summary, then the next batch starts with a new seed', async () => {
+ const v = await fresh({ batch: 60, noise: 0.1 })
+ try {
+ await v.hold()
+ await v.ctl('tick', { n: 60 })
+ let s = await v.state()
+ assert.equal(s.phase, 'summary')
+ assert.equal(s.summary.messages, 60)
+ assert.equal(s.summary.batchNo, 1)
+ assert.ok(s.summary.costUsd > 0 && s.summary.accuracy > 0.5)
+ const firstText = (await v.ctl('inspect', { id: 0 })).body.record.text
+ await v.ctl('tick', { n: 1 })
+ s = await v.state()
+ assert.equal(s.phase, 'run'); assert.equal(s.batchNo, 2); assert.equal(s.n, 1)
+ assert.equal(s.totals.batches, 1); assert.equal(s.totals.messages, 60)
+ assert.notEqual((await v.ctl('inspect', { id: 0 })).body.record.text, firstText, 'a new seed gives new messages')
+ // and on its own clock: run free, the summary clears itself after about three seconds
+ await v.ctl('burst', { n: 200 }); await v.ctl('start')
+ const deadline = Date.now() + 9000
+ let sawSummary = false, sawNext = false
+ while (Date.now() < deadline && !sawNext) { s = await v.state(); if (s.phase === 'summary') sawSummary = true; if (sawSummary && s.phase === 'run' && s.batchNo >= 3) sawNext = true; await wait(100) }
+ assert.ok(sawSummary && sawNext, 'summary shows, then the next batch starts by itself')
+ } finally { await v.viewer.close() }
+})
+
+test('the same seed gives the same stream', async () => {
+ const texts = []
+ for (let k = 0; k < 2; k++) {
+ const v = await fresh({ seed: 4242 })
+ try { await v.hold(); await v.ctl('tick', { n: 20 }); texts.push((await v.ctl('inspect', { id: 19 })).body.record.text) } finally { await v.viewer.close() }
+ }
+ assert.equal(texts[0], texts[1])
+})
+
+test('check.mjs accepts the template and rejects out-of-range values', () => {
+ const run = (cfg) => {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-firehose-check-'))
+ writeFileSync(join(ws, 'firehose.json'), JSON.stringify(cfg))
+ return spawnSync(process.execPath, [join(ROOT, 'toolchain/check.mjs')], { env: { ...process.env, HARNESS_WORKSPACE: ws }, encoding: 'utf8' })
+ }
+ const good = run(TEMPLATE)
+ assert.equal(good.status, 0, good.stdout)
+ assert.match(good.stdout, /ok\s+firehose\.json is valid/)
+ const bad = run({ ...TEMPLATE, noise: 1.4, concurrency: 200, teams: TEMPLATE.teams.slice(0, 1) })
+ assert.equal(bad.status, 1)
+ assert.match(bad.stdout, /noise is 1\.4/); assert.match(bad.stdout, /concurrency is 200/); assert.match(bad.stdout, /teams has 1 entries/)
+ const thin = run({ ...TEMPLATE, teams: [{ id: 'a', description: 'Alpha things.', phrases: ['one', 'two'] }, TEMPLATE.teams[0]] })
+ assert.equal(thin.status, 1); assert.match(thin.stdout, /needs at least 4/)
+})
diff --git a/store/agents/jev-firehose/toolchain/README.md b/store/agents/jev-firehose/toolchain/README.md
new file mode 100644
index 000000000..20d21dc0b
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/README.md
@@ -0,0 +1,57 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
+
+## Firehose tools
+
+- `check.mjs` validates `firehose.json`: 2 to 24 teams, each with a description and at least 4
+ phrases, and every number in range. It also warns about wording that will be hard to route, for
+ example a phrase that shares more words with another team's description than with its own. It
+ exits 1 on errors.
+- `measure.mjs` scores a desk without the pane. It uses the same generator and the same five
+ questions as the viewer, and prints accuracy and escalations at a range of thresholds, the lowest
+ threshold that meets `targetAccuracy`, and the most confused team pairs. Flags: `--n 600`,
+ `--noise 0.3`. Without a key it is free. With a key, each message is one real call.
+
+All data these tools make is synthetic.
+
+## Going live
+
+Without a key everything runs on the offline stand-in and the pane says `MOCK`. For the real model,
+give the harness a key. The viewer is started by the Harness daemon, which does not see variables
+you export in a shell, so the reliable place is a small file in your home folder:
+
+```sh
+mkdir -p ~/.config/typesafe && chmod 700 ~/.config/typesafe
+printf 'TYPESAFE_API_KEY=%s\n' 'paste-your-key-here' > ~/.config/typesafe/credentials
+chmod 600 ~/.config/typesafe/credentials
+```
+
+Two routes work, and both speak the same question format:
+
+| route | what goes in the file | where to get it |
+|---|---|---|
+| TypeSafe direct | `TYPESAFE_API_KEY=...` | https://console.typesafe.ai/keys (there may be a waitlist) |
+| Cloudflare Workers AI | `CLOUDFLARE_ACCOUNT_ID=...` and `CLOUDFLARE_API_TOKEN=...` | a Cloudflare API token with Workers AI permission, no TypeSafe waitlist |
+
+Environment variables of the same names win over the file. Restart the harness after changing the
+file. `toolchain/doctor.sh` prints which route is active and never prints the key. One file serves
+every Jev harness on the machine. Never paste a key into the chat, and never save one in the
+workspace. Under `node --test`, or with `JEV_OFFLINE=1`, a key is ignored so tests stay deterministic.
diff --git a/store/agents/jev-firehose/toolchain/check.mjs b/store/agents/jev-firehose/toolchain/check.mjs
new file mode 100644
index 000000000..8ee229da5
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/check.mjs
@@ -0,0 +1,89 @@
+#!/usr/bin/env node
+// check.mjs — validate a firehose.json for the Jev Firehose harness.
+//
+// node toolchain/check.mjs [path/to/firehose.json]
+//
+// Errors (exit code 1): values the viewer would have to clamp or drop.
+// Warnings (exit code 0): words that make the desk harder to route than you meant, for example a
+// phrase that shares more words with another team's description than with its own.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { stems } from './jev.mjs'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+const file = process.argv[2] || join(ws, 'firehose.json')
+
+let errors = 0, warns = 0
+const error = (msg) => { errors++; console.log(`error ${msg}`) }
+const warn = (msg) => { warns++; console.log(`warn ${msg}`) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(file, 'utf8'))
+} catch (e) {
+ console.log(`error cannot read firehose.json: ${e.message}`)
+ process.exit(1)
+}
+
+const RANGES = {
+ noise: [0, 1], threshold: [0, 1], targetAccuracy: [0.5, 1], ratePerSec: [1, 400], concurrency: [1, 64],
+ batch: [50, 100000], llmSecondsPerItem: [0.1, 120], spamRate: [0, 0.5],
+}
+const REQUIRED = ['noise', 'threshold', 'ratePerSec', 'concurrency', 'batch']
+const WHOLE = ['concurrency', 'batch']
+for (const [key, [lo, hi]] of Object.entries(RANGES)) {
+ const v = p[key]
+ if (v === undefined) { if (REQUIRED.includes(key)) error(`${key} is missing (${lo}..${hi})`); continue }
+ if (typeof v !== 'number' || !Number.isFinite(v)) { error(`${key} must be a number ${lo}..${hi}`); continue }
+ if (v < lo || v > hi) error(`${key} is ${v}, must be ${lo}..${hi}`)
+ else if (WHOLE.includes(key) && !Number.isInteger(v)) error(`${key} must be a whole number`)
+}
+if (p.seed !== undefined && !Number.isInteger(p.seed)) error('seed must be a whole number')
+if (!p.title || typeof p.title !== 'string') warn('no title')
+if (!p.desk || typeof p.desk !== 'string') warn('no desk line. Say what the desk is and that it is made up.')
+else if (!/made[- ]up|synthetic|fictional|pretend|invented/i.test(p.desk)) warn('the desk line should say the data is made up (for example "a made-up bike shop")')
+
+const teams = Array.isArray(p.teams) ? p.teams : null
+if (!teams) error('teams must be a list of 2 to 24 teams')
+else {
+ if (teams.length < 2 || teams.length > 24) error(`teams has ${teams.length} entries, must be 2..24`)
+ const seen = new Set()
+ const desc = []
+ teams.forEach((t, i) => {
+ const id = typeof t?.id === 'string' ? t.id.trim() : ''
+ const name = id || `#${i + 1}`
+ if (!id) error(`team ${name} needs an id`)
+ else if (id.length > 28) error(`team id "${id}" is longer than 28 characters`)
+ else if (seen.has(id)) error(`team id "${id}" is used twice`)
+ seen.add(id)
+ if (typeof t?.description !== 'string' || !t.description.trim()) error(`team ${name} needs a description`)
+ const phrases = Array.isArray(t?.phrases) ? t.phrases.filter((x) => typeof x === 'string' && x.trim()) : []
+ if (phrases.length < 4) error(`team ${name} has ${phrases.length} phrases, needs at least 4`)
+ if (t?.weight !== undefined && (typeof t.weight !== 'number' || t.weight < 0.1 || t.weight > 10)) error(`team ${name} weight must be 0.1..10`)
+ desc.push(new Set(stems(`${id.replace(/[_-]+/g, ' ')} ${t?.description ?? ''}`)))
+ })
+ // Vocabulary lint. The offline stand-in routes by shared words, and sharp, distinct wording
+ // helps live Jev too.
+ let thin = 0, crossed = 0
+ teams.forEach((t, i) => {
+ for (const ph of Array.isArray(t?.phrases) ? t.phrases : []) {
+ if (typeof ph !== 'string') continue
+ const s = new Set(stems(ph))
+ const hits = desc.map((d) => [...d].filter((w) => s.has(w)).length)
+ const own = hits[i]
+ let rival = -1
+ hits.forEach((h, j) => { if (j !== i && (rival < 0 || h > hits[rival])) rival = j })
+ if (rival >= 0 && hits[rival] >= own && hits[rival] > 0) { crossed++; if (crossed <= 8) warn(`"${ph}" (${t.id}) shares as many words with ${teams[rival].id}'s description (${hits[rival]}) as with its own (${own})`) }
+ else if (own < 2) { thin++; if (thin <= 8) warn(`"${ph}" (${t.id}) shares only ${own} word(s) with its own description`) }
+ }
+ })
+ if (crossed > 8) warn(`${crossed - 8} more phrases lean toward another team`)
+ if (thin > 8) warn(`${thin - 8} more phrases share under 2 words with their own description`)
+ for (let i = 0; i < desc.length; i++) for (let j = i + 1; j < desc.length; j++) {
+ const shared = [...desc[i]].filter((w) => desc[j].has(w))
+ if (shared.length >= 3) warn(`${teams[i].id} and ${teams[j].id} descriptions share ${shared.length} words (${shared.slice(0, 5).join(', ')}). Expect them to be confused.`)
+ }
+}
+
+if (errors) { console.log(`fail invalid firehose.json (${errors} error${errors > 1 ? 's' : ''}, ${warns} warning${warns === 1 ? '' : 's'})`); process.exit(1) }
+console.log(`ok firehose.json is valid (${teams.length} teams, ${teams.reduce((a, t) => a + t.phrases.length, 0)} phrases, ${warns} warning${warns === 1 ? '' : 's'})`)
diff --git a/store/agents/jev-firehose/toolchain/doctor.sh b/store/agents/jev-firehose/toolchain/doctor.sh
new file mode 100755
index 000000000..19e517615
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/doctor.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Firehose viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+cd "$(dirname "$0")/.."
+node -e "import('./toolchain/jev.mjs').then((m) => console.log('ok Jev: ' + m.describeCredentials())).catch((e) => console.log('warn Jev client did not load: ' + e.message))"
+echo "done"
diff --git a/store/agents/jev-firehose/toolchain/init-workspace.sh b/store/agents/jev-firehose/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-firehose/toolchain/jev.mjs b/store/agents/jev-firehose/toolchain/jev.mjs
new file mode 100644
index 000000000..190c7e9ac
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
+// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
+// score a position on a 2..10 level scale — a float plus per-level probabilities
+//
+// Questions are authored as options[] / legend{} (or an option -> description map) and translated
+// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The generic mock reads
+// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
+// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
+// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ return key ? 'typesafe' : 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ return (h >>> 0) / 4294967296
+}
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+
+/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
+export function stems(text) {
+ const out = []
+ for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
+ if (w.length < 2 || STOP.has(w)) continue
+ out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
+ }
+ return out
+}
+
+/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
+function evidence(stateStems, needle) {
+ const want = [...new Set(stems(needle))]
+ if (!want.length) return 0
+ let hit = 0
+ for (const w of want) if (stateStems.has(w)) hit++
+ return (hit / Math.sqrt(want.length)) * 1.2
+}
+
+function softmax(raw, temp = 1) {
+ const m = Math.max(...raw)
+ const exps = raw.map((r) => Math.exp((r - m) / temp))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ return exps.map((e) => e / sum)
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic generic mock. It turns the state text + question wording into a plausible
+// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`
+ const S = new Set(stems(text))
+ const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
+
+ if (q.type === 'noul') {
+ const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
+ const no = evidence(S, `${q.raw?.false ?? ''}`)
+ const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
+ const probs = softmax(raw, 0.6)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
+ const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
+ // No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
+ if (raw.every((r) => Math.abs(r) < 0.26)) {
+ const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
+ levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
+ }
+ const probs = softmax(raw, 0.7)
+ const probabilities = {}
+ levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
+ const score = probs.reduce((acc, p, i) => acc + p * i, 0)
+ return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// Imports are hoisted, so they can live here with the code that needs them.
+import { readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ out.raw = isMap(q.criteria) ? q.criteria : null
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+// ---------------------------------------------------------------------------
+// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
+// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
+// you happen to have open. Two live routes are supported, both speaking the same question format:
+// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
+// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
+// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
+// ---------------------------------------------------------------------------
+const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN']
+let credCache = null
+export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
+
+function readCredentialFile() {
+ const now = Date.now()
+ const path = credentialsPath()
+ if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
+ const values = {}
+ try {
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
+ if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
+ }
+ } catch { /* no file: fine */ }
+ credCache = { at: now, path, values }
+ return values
+}
+
+/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
+export function resolveCredentials(explicitKey) {
+ if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
+ // Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
+ // key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
+ if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
+ const file = readCredentialFile()
+ const get = (k) => process.env[k] || file[k] || ''
+ const key = explicitKey || get('TYPESAFE_API_KEY')
+ if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
+ const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
+ if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
+ return null
+}
+
+/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
+export function describeCredentials() {
+ const c = resolveCredentials()
+ if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
+ return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
+}
+
+async function liveEvaluate(body, cred) {
+ const endpoint = cred.url
+ const key = cred.secret
+ const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } } : body
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) {
+ const data = await res.json()
+ // Cloudflare wraps the model's reply as { result, success, errors }.
+ if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
+ return data?.result?.answers ? data.result : data
+ }
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const cred = resolveCredentials(key)
+ const client = cred ? cred.provider : 'mock'
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (cred) {
+ const data = await liveEvaluate({ model, state, questions: wire }, cred)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-firehose/toolchain/measure.mjs b/store/agents/jev-firehose/toolchain/measure.mjs
new file mode 100644
index 000000000..ba4b27726
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/measure.mjs
@@ -0,0 +1,60 @@
+#!/usr/bin/env node
+// measure.mjs — score a firehose.json without the pane.
+//
+// node toolchain/measure.mjs [path/to/firehose.json] [--n 600] [--noise 0.3]
+//
+// It makes N synthetic messages with the same generator the viewer uses, asks Jev the same five
+// questions, and prints accuracy and escalations at a range of thresholds, plus the lowest threshold
+// that meets `targetAccuracy`. Without TYPESAFE_API_KEY it runs on the offline stand-in (free).
+// With a key, every message is one real call (600 messages cost about one cent).
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { evaluate } from './jev.mjs'
+import { sanitize, makeMessage, buildQuestions } from '../viewer/viewer.mjs'
+import { mulberry32 } from '../viewer/kit.mjs'
+
+const args = process.argv.slice(2)
+const flag = (name, def) => { const i = args.indexOf(`--${name}`); return i >= 0 ? Number(args[i + 1]) : def }
+const file = args.find((a, i) => !a.startsWith('--') && !(args[i - 1] ?? '').startsWith('--')) || join(process.env.HARNESS_WORKSPACE || '.', 'firehose.json')
+
+let raw
+try { raw = JSON.parse(readFileSync(file, 'utf8')) } catch (e) { console.log(`error cannot read ${file}: ${e.message}`); process.exit(1) }
+const { cfg, warnings } = sanitize(raw)
+for (const w of warnings) console.log(`warn ${w}`)
+
+const N = Math.max(50, Math.min(5000, Math.floor(flag('n', 600))))
+const noise = Math.max(0, Math.min(1, flag('noise', cfg.noise)))
+const questions = buildQuestions(cfg)
+const rng = mulberry32((cfg.seed | 0) + 1)
+const nT = cfg.teams.length
+const rows = []
+const confusion = Array.from({ length: nT }, () => new Array(nT).fill(0))
+let client = 'mock'
+for (let i = 0; i < N; i++) {
+ const m = makeMessage(cfg, rng, noise)
+ const res = await evaluate({ state: m.text, questions, salt: (cfg.seed | 0) + i })
+ client = res.client
+ const a = res.answers
+ const choice = cfg.teams.findIndex((t) => t.id === a.team?.choice)
+ rows.push({ truth: m.truth, choice, conf: Number(a.team?.confidence ?? 0), spam: Number(a.spam?.noul ?? 0) >= 0.5 })
+ if (!m.spam && choice >= 0) confusion[m.truth][choice]++
+}
+
+const at = (th) => {
+ let routed = 0, right = 0
+ for (const r of rows) { const b = r.spam ? nT : r.conf < th ? -1 : r.choice; if (b === -1) continue; routed++; if (b === r.truth) right++ }
+ return { acc: routed ? right / routed : 0, esc: (rows.length - routed) / rows.length }
+}
+const pct = (v) => (v * 100).toFixed(1).padStart(5) + '%'
+console.log(`${cfg.title}: ${N} synthetic messages, noise ${noise}, ${nT} teams, client ${client}`)
+console.log('threshold right escalated')
+for (const th of [0, 0.3, 0.4, 0.5, 0.55, 0.6, 0.7, 0.8, 0.9]) { const r = at(th); console.log(` ${th.toFixed(2)} ${pct(r.acc)} ${pct(r.esc)}${Math.abs(th - cfg.threshold) < 1e-9 ? ' <- threshold in the file' : ''}`) }
+let best = null
+for (let j = 0; j <= 100; j++) { const r = at(j / 100); if (r.acc >= cfg.targetAccuracy) { best = { th: j / 100, ...r }; break } }
+console.log(best
+ ? `lowest threshold with at least ${pct(cfg.targetAccuracy).trim()} right: ${best.th.toFixed(2)} (${pct(best.acc).trim()} right, ${pct(best.esc).trim()} escalated)`
+ : `no threshold reaches ${pct(cfg.targetAccuracy).trim()} right at this noise`)
+const pairs = []
+for (let i = 0; i < nT; i++) for (let j = 0; j < nT; j++) if (i !== j && confusion[i][j]) pairs.push([confusion[i][j], `${cfg.teams[i].id} -> ${cfg.teams[j].id}`])
+pairs.sort((x, y) => y[0] - x[0])
+if (pairs.length) console.log('most confused (true -> Jev): ' + pairs.slice(0, 5).map(([c, name]) => `${name} ${c}`).join(', '))
diff --git a/store/agents/jev-firehose/toolchain/setup.sh b/store/agents/jev-firehose/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-firehose/toolchain/viewer.sh b/store/agents/jev-firehose/toolchain/viewer.sh
new file mode 100755
index 000000000..462b4261e
--- /dev/null
+++ b/store/agents/jev-firehose/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Firehose viewer (Jev triages a stream of made-up inbox messages, one call each).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-firehose/viewer/base.css b/store/agents/jev-firehose/viewer/base.css
new file mode 100644
index 000000000..c41ddcd46
--- /dev/null
+++ b/store/agents/jev-firehose/viewer/base.css
@@ -0,0 +1,83 @@
+/* base.css — the shared look of the Jev flagship viewers. Load before studio.css.
+ Set --accent / --accent2 in studio.css to give a harness its own colour. */
+:root {
+ --bg: #07080d; --panel: #10121a; --panel2: #161925; --line: #232838; --line2: #2e3550;
+ --ink: #e9ecf5; --dim: #8b92aa; --faint: #565d75;
+ --accent: #a78bfa; --accent2: #6d5bd0;
+ --ok: #34d399; --warn: #fbbf24; --bad: #fb7185; --cyan: #5eead4; --blue: #60a5fa;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ --radius: 12px;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1100px 700px at 75% -10%, color-mix(in srgb, var(--accent) 14%, transparent) 0%, transparent 60%), var(--bg);
+ color: var(--ink); font: 13px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+::selection { background: color-mix(in srgb, var(--accent) 45%, transparent); }
+::-webkit-scrollbar { width: 8px; height: 8px; }
+::-webkit-scrollbar-thumb { background: var(--line2); border-radius: 4px; }
+::-webkit-scrollbar-track { background: transparent; }
+
+#topbar {
+ display: flex; align-items: center; gap: 22px; padding: 10px 18px; flex: none; flex-wrap: wrap;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(20,22,34,.92), rgba(10,11,18,.7)); backdrop-filter: blur(8px);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font: 700 15px var(--mono); letter-spacing: .4px; margin: 0; white-space: nowrap; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 14px var(--accent); animation: dot 2.4s ease-in-out infinite; }
+@keyframes dot { 50% { transform: scale(.72); opacity: .7; } }
+.brand .sub { color: var(--dim); font-size: 11px; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; min-width: 54px; }
+.stat label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+button, .btn {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line2); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: border-color .15s, filter .15s, transform .05s; user-select: none;
+}
+button:hover { border-color: var(--accent); }
+button:active { transform: translateY(1px); }
+button.primary { background: linear-gradient(135deg, var(--accent2), var(--accent)); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.12); }
+button.ghost { background: transparent; }
+button.on { border-color: var(--accent); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
+button[disabled] { opacity: .45; cursor: default; }
+kbd { font: 600 10px var(--mono); padding: 1px 5px; border: 1px solid var(--line2); border-bottom-width: 2px; border-radius: 4px; color: var(--dim); }
+input[type=text], input[type=search], select, textarea {
+ font: 13px var(--mono); color: var(--ink); background: #0b0d14; border: 1px solid var(--line2); border-radius: 8px; padding: 7px 10px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+input[type=range] { accent-color: var(--accent); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow: auto; }
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 14px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; background: rgba(12,13,20,.55); }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; }
+.panel-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--dim); margin-bottom: 9px; display: flex; align-items: center; gap: 8px; }
+.panel-title .right { margin-left: auto; text-transform: none; letter-spacing: 0; }
+.how { color: var(--dim); font-size: 12.5px; line-height: 1.55; }
+.how b { color: var(--ink); } .how code { color: var(--warn); }
+.pill { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line2); color: var(--dim); }
+.pill.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
+.pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
+.pill.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); }
+
+.canvas-wrap { position: relative; flex: 1; min-height: 320px; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #05060a; }
+.canvas-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.banner { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); padding: 9px 20px; border-radius: 10px; font: 700 14px var(--mono); white-space: nowrap; backdrop-filter: blur(6px); }
+.banner.ok { background: rgba(16,185,129,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 34px rgba(16,185,129,.35); }
+.banner.bad { background: rgba(225,29,72,.16); border: 1px solid var(--bad); color: var(--bad); box-shadow: 0 0 34px rgba(225,29,72,.35); }
+.hidden { display: none !important; }
+.cfg-error { margin: 0 16px; padding: 8px 12px; border: 1px solid var(--bad); border-radius: 8px; color: var(--bad); background: rgba(225,29,72,.08); font-size: 12px; }
+
+@media (max-width: 900px) {
+ main { flex-direction: column; overflow: auto; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); overflow: visible; }
+ body { overflow: auto; }
+}
diff --git a/store/agents/jev-firehose/viewer/index.html b/store/agents/jev-firehose/viewer/index.html
new file mode 100644
index 000000000..d22247cc7
--- /dev/null
+++ b/store/agents/jev-firehose/viewer/index.html
@@ -0,0 +1,100 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Firehose</title>
+<link rel="icon" href="data:,">
+<link rel="stylesheet" href="/base.css">
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand">
+ <span class="dot"></span>
+ <div class="brand-text"><h1 id="title">Jev Firehose</h1><div class="sub" id="desk">synthetic inbox</div></div>
+ </div>
+ <div class="stats big">
+ <div class="stat"><label>Messages done</label><span id="s-done">0</span><small id="s-batch">of 2,000</small></div>
+ <div class="stat"><label>Per second</label><span id="s-mps" class="accent">0</span><small id="s-pool">pool of 8</small></div>
+ <div class="stat"><label>Cost so far</label><span id="s-cost">$0.0000</span><small id="s-per1k">per 1,000: —</small></div>
+ <div class="stat"><label>Auto-routed right</label><span id="s-acc" class="ok">—</span><small id="s-recent">last 300: —</small></div>
+ <div class="stat"><label>Escalated</label><span id="s-esc" class="warn">0.0%</span><small id="s-escn">0 messages</small></div>
+ <div class="stat"><label>Elapsed</label><span id="s-time">0.0s</span><small id="s-answers">0 answers</small></div>
+ </div>
+ <div class="controls">
+ <button id="pause" title="Space">Pause</button>
+ <button id="step" title="One message at a time">Step</button>
+ <button id="reset" class="primary">Reset</button>
+ </div>
+ </div>
+ <div id="cfgError" class="cfg-error hidden"></div>
+ <div id="cfgWarn" class="cfg-warn hidden"></div>
+ <main>
+ <section id="stage">
+ <div id="race" class="panel">
+ <div class="race-row">
+ <span class="race-name jev">Jev</span>
+ <div class="race-track"><div id="bar-jev" class="race-fill jev"></div></div>
+ <span class="race-note" id="race-jev">message 0 of 2,000</span>
+ </div>
+ <div class="race-row">
+ <span class="race-name ghost" id="ghost-name">2s/msg model</span>
+ <div class="race-track ghost"><div id="bar-ghost" class="race-fill ghost"></div></div>
+ <span class="race-note ghost" id="race-ghost">a model taking 2s per message would be on message 1</span>
+ </div>
+ </div>
+ <div class="canvas-wrap" id="wrap">
+ <canvas id="scene"></canvas>
+ <div id="synth" class="synth">all messages are synthetic · made up by a seeded generator</div>
+ <div id="summary" class="summary hidden">
+ <div class="summary-kicker" id="sum-kicker">Batch 1 done</div>
+ <div class="summary-line" id="sum-line"></div>
+ <div class="summary-sub" id="sum-sub"></div>
+ <div class="summary-timer"><i id="sum-timer"></i></div>
+ </div>
+ </div>
+ <div id="deck" class="panel">
+ <div class="knob">
+ <div class="knob-head"><label for="noise">Noise</label><b id="noise-val">0.20</b><span id="noise-pill" class="pill warn hidden" title="Set in the pane. An edit to firehose.json resets it.">override</span></div>
+ <input id="noise" type="range" min="0" max="1" step="0.01" value="0.2">
+ <div class="knob-hint">wrong-team phrases mixed in</div>
+ </div>
+ <div class="knob wide">
+ <div class="knob-head"><label for="threshold"><span class="wide-only">Confidence </span>threshold</label><b id="thr-val">0.55</b><span id="thr-pill" class="pill warn hidden" title="Set in the pane. An edit to firehose.json resets it.">override</span><button id="suggest" class="chip hidden" title="Set the threshold to this value"></button></div>
+ <canvas id="sweep" height="34"></canvas>
+ <input id="threshold" type="range" min="0" max="1" step="0.01" value="0.55">
+ <div class="knob-hint"><i class="key ok"></i>right <i class="key warn"></i>escalated, at every threshold</div>
+ </div>
+ <div class="knob actions">
+ <button id="burst" class="primary">Burst +500</button>
+ <button id="fileVals" class="ghost" disabled>Use file values</button>
+ <div class="knob-hint">Drag a slider or the line on the gate. Click a bin or a tile.</div>
+ </div>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel" id="inspector">
+ <div class="panel-title"><span id="insp-title">Inspector</span><span class="right"><span id="insp-live" class="pill ok" title="Showing a fresh message about every half second. Click a bin or a tile to pin one.">live</span><button id="insp-follow" class="chip hidden">follow live</button></span></div>
+ <div id="insp-body" class="insp-body"><div class="how">Waiting for the first message.</div></div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">How it works</div>
+ <div class="how">
+ A seeded generator writes <b>made-up</b> inbox messages. Each one has a true team, so the pane can score Jev live.
+ Jev reads a message once and answers <b>five questions in one call</b>: <code>team</code>, <code>urgency</code>, <code>spam</code>, <code>needs_human</code>, <code>mood</code>.
+ A tile crosses the gate at the height of Jev's <b>confidence</b>. Under the threshold it drops to the amber lane for a big model. A red ring marks a wrong bin.
+ <br><br>The chat agent designs the desk in <code>firehose.json</code>: teams, descriptions, phrases, <code>noise</code>, <code>threshold</code>.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Confusion matrix <span class="right" id="mx-note">true team by routed bin</span></div>
+ <canvas id="matrix"></canvas>
+ <div id="mx-tip" class="mx-tip">Hover a cell.</div>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-firehose/viewer/jev-hud.js b/store/agents/jev-firehose/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-firehose/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-firehose/viewer/kit.mjs b/store/agents/jev-firehose/viewer/kit.mjs
new file mode 100644
index 000000000..f80d29b7d
--- /dev/null
+++ b/store/agents/jev-firehose/viewer/kit.mjs
@@ -0,0 +1,112 @@
+// kit.mjs — the boring, security-relevant half of a Jev viewer, written once:
+// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
+// /control, plus an atomic verdict writer and a safe JSON config watcher.
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
+import { join, extname } from 'node:path'
+import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
+
+export const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+/** Deterministic PRNG so every run of a demo is reproducible. */
+export function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/**
+ * Serve a viewer.
+ * @param {object} o
+ * @param {string} o.here the viewer directory (static files live here)
+ * @param {number} o.port 0 = ephemeral
+ * @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
+ * @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
+ * @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ */
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+ const clients = new Set()
+ const allowed = new Set(files)
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ // Loopback only: a page on another origin (DNS rebinding) must not reach this server.
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ const path = url.pathname
+ try {
+ if (req.method === 'GET') {
+ const name = path === '/' ? 'index.html' : path.slice(1)
+ if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
+ if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (path === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
+ clients.add(res)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ }
+ if (req.method === 'POST' && path === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 65536) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const reply = control ? await control(String(j.cmd ?? ''), j) : null
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
+ res.writeHead(404); res.end('Not found')
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
+ }
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ clients,
+ /** Push a named SSE event (default 'state') to every connected pane. */
+ broadcast(obj, event = 'state') {
+ const line = `event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`
+ for (const c of clients) c.write(line)
+ },
+ async close() { for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+/** Atomic write of .harness/verdict.json (the harness reads this file; never edit it by hand). */
+export function writeVerdict(workspace, verdict) {
+ const dir = join(workspace, '.harness')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify({ spec: 1, ...verdict, updatedAt: new Date().toISOString() }))
+ renameSync(file + '.tmp', file)
+}
+
+/**
+ * Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
+ * good config and reports the parse error instead of crashing the demo.
+ * @returns {{ get(): object, error(): string|null, close(): void }}
+ */
+export function watchConfig(file, defaults, onChange) {
+ let cfg = { ...defaults }, err = null, timer = null
+ const load = () => {
+ try { cfg = { ...defaults, ...JSON.parse(readFileSync(file, 'utf8')) }; err = null }
+ catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
+ }
+ load()
+ let watcher = null
+ try {
+ watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ } catch { /* file may not exist yet; defaults stand */ }
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+}
diff --git a/store/agents/jev-firehose/viewer/studio.css b/store/agents/jev-firehose/viewer/studio.css
new file mode 100644
index 000000000..f8b7e334b
--- /dev/null
+++ b/store/agents/jev-firehose/viewer/studio.css
@@ -0,0 +1,148 @@
+/* studio.css — Jev Firehose. base.css gives the shared look; this file adds the firehose pieces. */
+:root { --accent: #22d3ee; --accent2: #0e7490; --amber: #fbbf24; --wrong: #ff4d5e; }
+
+/* Top bar: six large numbers that must not jump around. */
+#topbar { gap: 18px; padding: 9px 16px; flex-wrap: nowrap; }
+.brand-text { min-width: 0; }
+.brand .sub { max-width: 210px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.stats.big { flex: 1; display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px 14px; min-width: 0; }
+.stats.big .stat { min-width: 0; }
+.stats.big .stat label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.stats.big .stat span { font-size: 23px; line-height: 1.12; letter-spacing: -.3px; white-space: nowrap; }
+.stats.big .stat small { font-size: 10px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
+.stat span.accent { color: var(--accent); text-shadow: 0 0 18px color-mix(in srgb, var(--accent) 55%, transparent); }
+.stat span.ok { color: var(--ok); }
+.stat span.warn { color: var(--amber); }
+.stat span.bad { color: var(--bad); }
+.controls { flex-wrap: nowrap; }
+.cfg-error { margin: 8px 16px 0; }
+.cfg-warn { margin: 8px 16px 0; padding: 7px 12px; border: 1px solid color-mix(in srgb, var(--amber) 60%, transparent); border-radius: 8px; color: var(--amber); background: rgba(251,191,36,.06); font-size: 12px; }
+
+#stage { gap: 10px; padding: 12px 14px; overflow: hidden; }
+
+/* The race: Jev against a slow model, same scale. */
+#race { padding: 9px 14px; display: flex; flex-direction: column; gap: 6px; flex: none; }
+.race-row { display: grid; grid-template-columns: 108px 1fr minmax(0, 46%); align-items: center; gap: 12px; }
+.race-name { font-size: 10px; letter-spacing: 1.3px; text-transform: uppercase; white-space: nowrap; }
+.race-name.jev { color: var(--accent); font-weight: 700; }
+.race-name.ghost, .race-note.ghost { color: var(--faint); }
+.race-track { height: 10px; border-radius: 5px; background: rgba(255,255,255,.05); overflow: hidden; position: relative; }
+.race-track.ghost { height: 6px; background: repeating-linear-gradient(90deg, rgba(255,255,255,.05) 0 6px, transparent 6px 10px); }
+.race-fill { height: 100%; width: 0; border-radius: 5px; }
+.race-fill.jev { background: linear-gradient(90deg, var(--accent2), var(--accent)); box-shadow: 0 0 16px var(--accent); }
+.race-fill.ghost { background: rgba(255,255,255,.28); min-width: 2px; }
+.race-note { font-size: 11.5px; color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
+
+/* The scene. */
+.canvas-wrap { min-height: 300px; background: #04060b; }
+.canvas-wrap canvas { cursor: default; }
+.synth { position: absolute; left: 12px; top: 9px; font-size: 10px; letter-spacing: 1px; text-transform: uppercase; color: var(--faint); pointer-events: none; }
+.summary {
+ position: absolute; left: 50%; top: 46%; transform: translate(-50%, -50%); width: max-content; text-align: center; padding: 20px 30px 16px; border-radius: 16px;
+ background: rgba(6, 10, 18, .86); border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent); backdrop-filter: blur(10px);
+ box-shadow: 0 0 70px color-mix(in srgb, var(--accent) 35%, transparent), inset 0 0 0 1px rgba(255,255,255,.04); max-width: 92%;
+ animation: pop .35s cubic-bezier(.2, 1.4, .4, 1);
+}
+@keyframes pop { from { opacity: 0; transform: translate(-50%, -46%) scale(.94); } }
+.summary-kicker { font-size: 11px; letter-spacing: 2.4px; text-transform: uppercase; color: var(--accent); margin-bottom: 8px; }
+.summary-line { font: 700 21px var(--mono); font-variant-numeric: tabular-nums; letter-spacing: -.2px; }
+.summary-line span, .summary-line { white-space: nowrap; }
+.summary-line em { font-style: normal; color: var(--faint); font-weight: 400; padding: 0 4px; }
+.summary-line .ok { color: var(--ok); } .summary-line .warn { color: var(--amber); } .summary-line .acc { color: var(--accent); }
+.summary-sub { margin-top: 8px; color: var(--dim); font-size: 12px; white-space: normal; max-width: 640px; margin-left: auto; margin-right: auto; }
+.summary-timer { height: 3px; margin-top: 14px; border-radius: 2px; background: rgba(255,255,255,.07); overflow: hidden; }
+.summary-timer i { display: block; height: 100%; width: 100%; background: var(--accent); transform-origin: left; }
+.summary-timer i.run { animation: drain 3.1s linear forwards; }
+@keyframes drain { to { transform: scaleX(0); } }
+
+/* The deck: what the person can poke. */
+#deck { flex: none; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.5fr) auto; gap: 18px; padding: 10px 14px; align-items: end; }
+.knob { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
+.knob-head { display: flex; align-items: center; gap: 8px; min-height: 20px; }
+.knob-head label { font-size: 10px; text-transform: uppercase; letter-spacing: 1.3px; color: var(--dim); white-space: nowrap; }
+.knob-head b { font-size: 15px; font-variant-numeric: tabular-nums; color: var(--accent); }
+.knob input[type=range] { width: 100%; margin: 0; height: 18px; }
+.knob-hint { font-size: 11px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.knob-hint .key { display: inline-block; width: 9px; height: 3px; border-radius: 2px; margin: 0 4px 2px 0; vertical-align: middle; }
+.knob-hint .key.ok { background: var(--ok); } .knob-hint .key.warn { background: var(--amber); margin-left: 8px; }
+#sweep { width: 100%; height: 34px; display: block; }
+.knob.actions { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 8px; max-width: 250px; justify-content: flex-end; }
+.knob.actions .knob-hint { flex-basis: 100%; white-space: normal; text-align: right; }
+#burst { font-size: 13px; padding: 9px 16px; box-shadow: 0 0 22px color-mix(in srgb, var(--accent) 35%, transparent); }
+.chip { font: 600 10.5px var(--mono); padding: 2px 8px; border-radius: 999px; background: transparent; border: 1px solid color-mix(in srgb, var(--ok) 55%, transparent); color: var(--ok); white-space: nowrap; }
+.chip:hover { border-color: var(--ok); background: rgba(52,211,153,.1); }
+.knob-head .chip { margin-left: auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+.knob-head .pill { white-space: nowrap; flex: none; }
+
+/* Rail. */
+#rail { gap: 12px; }
+.insp-body { display: flex; flex-direction: column; gap: 9px; min-height: 236px; }
+.insp-verdict { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 12px; }
+.insp-verdict .sw { width: 10px; height: 10px; border-radius: 3px; flex: none; }
+.insp-verdict b { font-size: 13px; }
+.tag { font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid; text-transform: uppercase; }
+.tag.right { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 55%, transparent); background: rgba(52,211,153,.08); }
+.tag.wrong { color: var(--wrong); border-color: color-mix(in srgb, var(--wrong) 60%, transparent); background: rgba(255,77,94,.09); }
+.tag.esc { color: var(--amber); border-color: color-mix(in srgb, var(--amber) 55%, transparent); background: rgba(251,191,36,.08); }
+.insp-text { font: 12.5px/1.5 var(--sans); color: var(--ink); background: #0b0d14; border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; max-height: 118px; overflow-y: auto; }
+.insp-text span { border-bottom: 2px solid transparent; }
+.insp-text .dimmed { color: var(--dim); }
+.insp-meta { font-size: 11px; color: var(--dim); }
+.ans { display: grid; grid-template-columns: 86px minmax(0, 1fr); gap: 3px 8px; align-items: center; font-size: 11px; }
+.ans > div { min-width: 0; }
+.ans .q { color: var(--accent); font-weight: 700; white-space: nowrap; }
+.ans .q small { display: block; color: var(--ok); opacity: .8; font-weight: 400; font-size: 9px; letter-spacing: .4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.bars { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.bar { display: grid; grid-template-columns: 70px minmax(0, 1fr) 26px; gap: 6px; align-items: center; height: 14px; }
+.bar .n { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--dim); }
+.bar.top .n { color: var(--ink); font-weight: 700; }
+.bar .t { height: 7px; border-radius: 4px; background: rgba(255,255,255,.05); overflow: hidden; }
+.bar .t i { display: block; height: 100%; border-radius: 4px; background: var(--accent2); }
+.bar .v { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
+.levels { display: flex; gap: 2px; align-items: flex-end; height: 20px; }
+.levels i { flex: 1; min-height: 3px; border-radius: 2px 2px 0 0; background: rgba(255,255,255,.2); }
+.levels i.top { background: var(--accent); }
+.levels i.truth { box-shadow: 0 2px 0 0 var(--ok); }
+.lvl-note { color: var(--dim); font-size: 10.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.bin-list { display: flex; flex-direction: column; gap: 4px; }
+.bin-list button { text-align: left; font: 11.5px/1.35 var(--sans); padding: 6px 8px; background: #0b0d14; border-color: var(--line); display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: center; }
+.bin-list button span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dim); }
+.bin-list button em { font: 600 10px var(--mono); font-style: normal; }
+.bin-list button em.r { color: var(--ok); } .bin-list button em.w { color: var(--wrong); } .bin-list button em.e { color: var(--amber); }
+#matrix { width: 100%; display: block; cursor: crosshair; }
+.mx-tip { margin-top: 6px; font-size: 11px; color: var(--dim); min-height: 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+
+/* Narrow pane (about 1100 wide): keep everything on one line and unclipped. */
+@media (max-width: 1240px) {
+ #rail { width: 312px; padding: 12px; }
+ #topbar { gap: 12px; padding: 8px 12px; }
+ .brand .sub { display: none; }
+ .stats.big { gap: 4px 10px; }
+ .stats.big .stat span { font-size: 19px; }
+ .stats.big .stat label { font-size: 8.5px; letter-spacing: .9px; }
+ button, .btn { padding: 6px 10px; }
+ .race-row { grid-template-columns: 96px 1fr minmax(0, 52%); gap: 10px; }
+ #deck { gap: 12px; grid-template-columns: minmax(0, 1fr) minmax(0, 1.35fr) auto; }
+ .knob.actions { max-width: 170px; }
+ .knob.actions .knob-hint { display: none; }
+ .wide-only { display: none; }
+ /* no room for the word at this width: the override pill becomes an amber dot (its tooltip and the lit "Use file values" button still say what it is) */
+ .knob-head .pill { font-size: 0; width: 9px; height: 9px; padding: 0; border-radius: 50%; background: var(--amber); border-color: var(--amber); box-shadow: 0 0 8px var(--amber); }
+}
+
+/* The kit HUD is tall with five questions; tighten it a little so the inspector shows sooner. */
+#rail .jh { padding: 10px 12px; }
+#rail .jh-head { margin-bottom: 7px; }
+#rail .jh-stat { padding: 4px 4px; }
+#rail .jh-spark { height: 16px; margin: 0 0 4px; }
+#rail .jh-q { padding-top: 6px; margin-top: 6px; }
+#rail .jh-row { height: 14px; }
+#rail .jh-scale { height: 18px; margin-top: 0; }
+#rail .jh-scale i { top: 6px; } #rail .jh-scale u { top: 1px; }
+#rail .jh-foot { margin-top: 8px; }
+
+@media (max-width: 1240px) {
+ .summary { padding: 16px 20px 13px; }
+ .summary-line { font-size: 16px; }
+ .summary-sub { font-size: 11px; max-width: 520px; }
+}
diff --git a/store/agents/jev-firehose/viewer/studio.js b/store/agents/jev-firehose/viewer/studio.js
new file mode 100644
index 000000000..1e56bad78
--- /dev/null
+++ b/store/agents/jev-firehose/viewer/studio.js
@@ -0,0 +1,842 @@
+// studio.js — the Jev Firehose pane. The server streams compact decisions ten times a second; this
+// file turns them into a 60 fps scene: tiles spray from the nozzle, cross the Jev gate at the height
+// of Jev's confidence, then arc into team bins (or drop into the amber escalate lane).
+// No frameworks, no network calls except to the viewer's own server. Objects are pooled.
+(() => {
+ 'use strict'
+ const $ = (id) => document.getElementById(id)
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+ const easeOutQuad = (t) => 1 - (1 - t) * (1 - t)
+ const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2)
+ const fmtInt = (v) => Math.round(v).toLocaleString('en-US')
+ const fmtMoney = (v) => '$' + (v < 1 ? v.toFixed(4) : v.toFixed(2))
+ const fmtPct = (v, d = 1) => (v == null || !Number.isFinite(v) ? '—' : (v * 100).toFixed(d) + '%')
+ const fmtSecs = (ms) => (ms < 60000 ? (ms / 1000).toFixed(1) + 's' : Math.floor(ms / 60000) + 'm ' + String(Math.floor((ms % 60000) / 1000)).padStart(2, '0') + 's')
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
+ const setText = (el, s) => { if (el && el.textContent !== s) el.textContent = s }
+
+ // ------------------------------------------------------------------------------------------
+ // State (everything declared up front)
+ // ------------------------------------------------------------------------------------------
+ const scene = $('scene'), wrap = $('wrap'), ctx = scene.getContext('2d')
+ const binLayer = document.createElement('canvas'), bctx = binLayer.getContext('2d')
+ const fxLayer = document.createElement('canvas'), fctx = fxLayer.getContext('2d')
+ const bgLayer = document.createElement('canvas'), gctx = bgLayer.getContext('2d')
+ const flushLayer = document.createElement('canvas'), flctx = flushLayer.getContext('2d')
+ let W = 800, H = 500, dpr = 1
+ const L = { gateX: 0, gateTop: 0, gateBot: 0, nx: 0, ny: 0, top: 0, bottom: 0, lane: { x: 0, y: 0, w: 0, h: 0 } }
+ let geo = [] // per bucket: row rect, tile area, tile size, capacity
+
+ let teams = [], nT = 0, SPAMB = 0, ESCB = 1
+ let colors = [], rgbs = [], glows = []
+ const AMBER = '#fbbf24', WRONG = '#ff4d5e', SPAMC = '#94a3b8', CYAN = '#22d3ee'
+ let amberGlow = null, cyanGlow = null, whiteGlow = null, redGlow = null
+ let config = { batch: 2000, llmSecondsPerItem: 2, targetAccuracy: 0.95, concurrency: 8, ratePerSec: 40 }
+ let live = { running: true, phase: 'run', elapsedMs: 0, costUsd: 0, mps: 0, batchNo: 1, burstLeft: 0, overrides: {} }
+ let liveAt = performance.now()
+ let rev = -1, thr = 0.55, thrQ = 550, noise = 0.2
+ let urgencyLegend = [], moodLegend = []
+
+ let n = 0, capN = 0
+ let T = new Uint8Array(0), C = new Uint8Array(0), Q = new Uint16Array(0), S = new Uint8Array(0), D = new Uint8Array(0), M = new Uint8Array(0), U = new Uint8Array(0)
+ let where = new Int16Array(0) // bucket an item has landed in, or -1
+ let binList = [], binRight = [], pending = []
+ let counts = [], rights = [], confusion = []
+ const RECENT = 500, recentQ = new Uint16Array(RECENT); let recentN = 0
+ const confHist = new Uint16Array(40)
+
+ const queue = []; let qHead = 0, emitAcc = 0, activity = 0, flightSeq = 0
+ const MAX_FLY = 900, fly = [], freeFly = []
+ const MAX_P = 520, P = { x: new Float32Array(MAX_P), y: new Float32Array(MAX_P), vx: new Float32Array(MAX_P), vy: new Float32Array(MAX_P), life: new Float32Array(MAX_P), max: new Float32Array(MAX_P), col: new Int16Array(MAX_P) }
+ let pCount = 0
+ const flashes = [], rings = [], labels = []
+ let lastLabelAt = 0, binFlash = []
+ let flushT = -1
+ let sel = null, follow = true, hoverB = -1, dragThr = false, holdServerUntil = 0
+ let lastFrame = performance.now(), domAt = 0, matrixDirty = true, sweepDirty = true, matrixAt = 0, sweepAt = 0
+ const shown = { done: 0, cost: 0, acc: null, escPct: 0, mps: 0 }
+ let summaryShownFor = -1
+ let mxCells = null
+
+ // ------------------------------------------------------------------------------------------
+ // Colours and sprites
+ // ------------------------------------------------------------------------------------------
+ const CURATED = ['#38bdf8', '#f472b6', '#a3e635', '#a78bfa', '#2dd4bf', '#e879f9', '#4ade80', '#818cf8']
+ function hslToHex(h, s, l) {
+ s /= 100; l /= 100
+ const k = (x) => (x + h / 30) % 12, a = s * Math.min(l, 1 - l)
+ const f = (x) => Math.round(255 * (l - a * Math.max(-1, Math.min(k(x) - 3, Math.min(9 - k(x), 1)))))
+ return '#' + [f(0), f(8), f(4)].map((v) => v.toString(16).padStart(2, '0')).join('')
+ }
+ function palette(count) {
+ if (count <= CURATED.length) return CURATED.slice(0, count)
+ const out = []
+ for (let i = 0; i < count; i++) out.push(hslToHex(78 + (i * 262) / count, 86, i % 2 ? 72 : 60)) // 78..340: skips red and amber
+ return out
+ }
+ const hexRgb = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)]
+ function makeGlow(rgb) {
+ const c = document.createElement('canvas'); c.width = c.height = 48
+ const g = c.getContext('2d'), gr = g.createRadialGradient(24, 24, 0, 24, 24, 24)
+ gr.addColorStop(0, `rgba(${rgb[0]},${rgb[1]},${rgb[2]},.95)`); gr.addColorStop(0.25, `rgba(${rgb[0]},${rgb[1]},${rgb[2]},.42)`); gr.addColorStop(1, `rgba(${rgb[0]},${rgb[1]},${rgb[2]},0)`)
+ g.fillStyle = gr; g.fillRect(0, 0, 48, 48)
+ return c
+ }
+ function buildPalette() {
+ colors = palette(nT).concat([SPAMC]); rgbs = colors.map(hexRgb); glows = rgbs.map(makeGlow)
+ amberGlow = makeGlow(hexRgb(AMBER)); cyanGlow = makeGlow(hexRgb(CYAN)); whiteGlow = makeGlow([255, 255, 255]); redGlow = makeGlow(hexRgb(WRONG))
+ }
+
+ // ------------------------------------------------------------------------------------------
+ // Items and buckets
+ // ------------------------------------------------------------------------------------------
+ const bucketOf = (i) => (S[i] >= 128 ? SPAMB : Q[i] < thrQ ? ESCB : C[i])
+ function grow(need) {
+ if (need <= capN) return
+ const c = Math.max(need, capN * 2, 4096), g = (A, old) => { const a = new A(c); a.set(old); return a }
+ T = g(Uint8Array, T); C = g(Uint8Array, C); Q = g(Uint16Array, Q); S = g(Uint8Array, S); D = g(Uint8Array, D); M = g(Uint8Array, M); U = g(Uint8Array, U)
+ const w = new Int16Array(c).fill(-1); w.set(where); where = w
+ capN = c
+ }
+ function addStat(i) { const b = bucketOf(i); counts[b]++; if (b === T[i]) rights[b]++; confusion[T[i]][b]++ }
+ function recount() {
+ counts = new Array(nT + 2).fill(0); rights = new Array(nT + 2).fill(0); confusion = Array.from({ length: nT + 1 }, () => new Array(nT + 2).fill(0))
+ for (let i = 0; i < n; i++) addStat(i)
+ matrixDirty = true; sweepDirty = true
+ }
+ function totals() {
+ const escN = counts[ESCB] || 0, routed = n - escN
+ let right = 0
+ for (let b = 0; b <= nT; b++) right += rights[b] || 0
+ let rN = 0, rOk = 0, rEsc = 0
+ for (let i = Math.max(0, n - 300); i < n; i++) { const b = bucketOf(i); rN++; if (b === ESCB) rEsc++; else if (b === T[i]) rOk++ }
+ return { escN, routed, right, acc: routed ? right / routed : null, escPct: n ? escN / n : 0, recent: rN - rEsc ? rOk / (rN - rEsc) : null }
+ }
+ function recv(i, it, animate) {
+ grow(i + 1)
+ T[i] = it[0]; C[i] = it[1]; Q[i] = it[2]; S[i] = it[3]; D[i] = it[4]; M[i] = it[5]; U[i] = it[6]; where[i] = -1
+ n = i + 1
+ addStat(i)
+ const hb = Math.min(39, Math.floor(Q[i] / 25))
+ if (recentN >= RECENT) { const old = Math.min(39, Math.floor(recentQ[recentN % RECENT] / 25)); if (confHist[old]) confHist[old]-- }
+ recentQ[recentN % RECENT] = Q[i]; recentN++; confHist[hb]++
+ matrixDirty = true; sweepDirty = true
+ if (animate) queue.push(i); else land(i, bucketOf(i), false)
+ }
+ function land(i, b, draw) {
+ if (!binList[b]) return
+ ensureRoom(b, 1)
+ const slot = binList[b].length
+ binList[b].push(i); where[i] = b
+ if (b !== ESCB && b === T[i]) binRight[b]++
+ if (draw) drawTile(bctx, b, slot, i)
+ }
+
+ function resetWorld(s) {
+ teams = s.teams || []; nT = teams.length; SPAMB = nT; ESCB = nT + 1
+ buildPalette()
+ n = 0; queue.length = 0; qHead = 0; emitAcc = 0
+ while (fly.length) freeFly.push(fly.pop())
+ pCount = 0; flashes.length = 0; rings.length = 0; labels.length = 0
+ recentN = 0; confHist.fill(0)
+ binList = Array.from({ length: nT + 2 }, () => []); binRight = new Array(nT + 2).fill(0); pending = new Array(nT + 2).fill(0); binFlash = new Array(nT + 2).fill(0)
+ where.fill(-1)
+ recount()
+ sel = null; follow = true; hoverB = -1
+ }
+
+ // ------------------------------------------------------------------------------------------
+ // Layout: nozzle left, gate, team rows on the right, amber lane along the bottom
+ // ------------------------------------------------------------------------------------------
+ function fitGeo(g, need, maxSize = 11) {
+ need = Math.max(1, Math.ceil(need))
+ for (const s of [11, 9, 8, 7, 6, 5, 4, 3, 2]) {
+ if (s > maxSize && s > 2) continue
+ const pitch = s + 1, rows = Math.max(1, Math.floor((g.ah + 1) / pitch)), cols = Math.max(1, Math.floor((g.aw + 1) / pitch))
+ if (rows * cols >= need || s === 2) { g.size = s; g.pitch = pitch; g.rows = rows; g.cols = cols; g.unit = Math.max(1, Math.ceil(need / (rows * cols))); g.capacity = rows * cols * g.unit; return }
+ }
+ }
+ function layout() {
+ const r = wrap.getBoundingClientRect()
+ W = Math.max(320, Math.round(r.width)); H = Math.max(220, Math.round(r.height)); dpr = Math.min(2, window.devicePixelRatio || 1)
+ for (const c of [scene, binLayer, fxLayer, bgLayer, flushLayer]) { c.width = Math.round(W * dpr); c.height = Math.round(H * dpr) }
+ for (const c of [ctx, bctx, fctx, gctx, flctx]) c.setTransform(dpr, 0, 0, dpr, 0, 0)
+ const pad = 12, laneH = clamp(H * 0.14, 48, 74)
+ L.lane = { x: pad, y: H - pad - laneH, w: W - 2 * pad, h: laneH }
+ L.top = 30; L.bottom = L.lane.y - 12
+ L.gateX = Math.round(W * 0.29); L.gateTop = L.top + 24; L.gateBot = L.bottom - 6
+ L.nx = Math.round(clamp(W * 0.095, 70, 112)); L.ny = Math.round((L.gateTop + L.gateBot) / 2)
+ const nB = nT + 1, gap = nB > 14 ? 2 : nB > 10 ? 3 : 5, x0 = Math.round(W * 0.475)
+ const rowH = (L.bottom - L.top - gap * (nB - 1)) / nB, labelW = Math.round(clamp(W * 0.11, 76, 122))
+ geo = []
+ for (let b = 0; b < nB; b++) {
+ const y = L.top + b * (rowH + gap), g = { x: x0, y, w: W - pad - x0, h: rowH, labelW }
+ g.ax = x0 + labelW; g.ay = y + 3; g.aw = g.w - labelW - 5; g.ah = rowH - 6
+ geo.push(g)
+ }
+ const lw = Math.round(clamp(W * 0.17, 128, 176)), lg = { x: L.lane.x, y: L.lane.y, w: L.lane.w, h: laneH, labelW: lw }
+ lg.ax = L.lane.x + lw; lg.ay = L.lane.y + 5; lg.aw = L.lane.w - lw - 6; lg.ah = laneH - 10
+ geo.push(lg)
+ fitBins(0); fitGeo(geo[ESCB], Math.max((binList[ESCB]?.length || 0) * 1.3, (config.batch || 2000) * 0.15), geo[0].size)
+ drawBackground(); redrawBins(); retarget()
+ fctx.clearRect(0, 0, W, H)
+ }
+ /** Every team bin shares one tile size, so the filled lengths compare like a bar chart. */
+ function fitBins(extra) {
+ let need = ((config.batch || 2000) / Math.max(1, nT + 1)) * 1.5
+ for (let b = 0; b <= nT; b++) need = Math.max(need, ((binList[b]?.length || 0) + (pending[b] || 0) + extra) * 1.5)
+ let tight = geo[0]
+ for (let b = 0; b <= nT; b++) if (geo[b].aw * geo[b].ah < tight.aw * tight.ah) tight = geo[b]
+ fitGeo(tight, need)
+ for (let b = 0; b <= nT; b++) { const g = geo[b]; g.size = tight.size; g.pitch = tight.pitch; g.unit = tight.unit; g.rows = Math.max(1, Math.floor((g.ah + 1) / g.pitch)); g.cols = Math.max(1, Math.floor((g.aw + 1) / g.pitch)); g.capacity = g.rows * g.cols * g.unit }
+ }
+ function ensureRoom(b, extra) {
+ const g = geo[b]; if (!g) return
+ const need = binList[b].length + pending[b] + extra
+ if (need <= g.capacity) return
+ if (b === ESCB) { fitGeo(g, need * 1.6, geo[0].size); redrawBin(b) } else { fitBins(extra); fitGeo(geo[ESCB], Math.max(geo[ESCB].capacity, 1), geo[0].size); redrawBins() }
+ retarget()
+ }
+ const pos = { x: 0, y: 0 }
+ function slotPos(b, slot) {
+ const g = geo[b], k = Math.floor(slot / g.unit), col = Math.floor(k / g.rows), row = k % g.rows
+ pos.x = g.ax + col * g.pitch + g.size / 2; pos.y = g.ay + g.ah - row * g.pitch - g.size / 2
+ return pos
+ }
+ function drawTile(c, b, slot, i) {
+ const g = geo[b]; if (!g || slot % g.unit) return
+ const p = slotPos(b, slot), s = g.size, x = Math.round(p.x - s / 2), y = Math.round(p.y - s / 2)
+ const wrong = b !== ESCB && b !== T[i]
+ if (wrong && s <= 3) { c.fillStyle = WRONG; c.fillRect(x, y, s, s); return }
+ c.fillStyle = colors[T[i]]; c.globalAlpha = b === ESCB ? 0.82 : 1; c.fillRect(x, y, s, s); c.globalAlpha = 1
+ if (wrong) { c.strokeStyle = WRONG; c.lineWidth = 1.5; c.strokeRect(x - 0.25, y - 0.25, s + 0.5, s + 0.5) }
+ }
+ function redrawBin(b) {
+ const g = geo[b]; if (!g) return
+ bctx.clearRect(g.ax - 3, g.ay - 3, g.aw + 6, g.ah + 6)
+ const list = binList[b] || []
+ for (let k = 0; k < list.length; k += g.unit) drawTile(bctx, b, k, list[k])
+ }
+ function redrawBins() { bctx.clearRect(0, 0, W, H); for (let b = 0; b < geo.length; b++) redrawBin(b) }
+
+ /** The threshold moved: move every landed tile that changed bucket, with a capped animation. */
+ function rebucket() {
+ const old = binList, movers = []
+ binList = Array.from({ length: nT + 2 }, () => []); binRight = new Array(nT + 2).fill(0)
+ for (let b = 0; b < old.length; b++) for (let k = 0; k < old[b].length; k++) {
+ const i = old[b][k], nb = bucketOf(i)
+ if (nb === b) { binList[b].push(i); if (b !== ESCB && b === T[i]) binRight[b]++ } else { const p = slotPos(b, k); movers.push(i, b, nb, p.x, p.y) }
+ }
+ const total = movers.length / 5, room = Math.max(0, Math.min(260, MAX_FLY - fly.length)), keep = total ? room / total : 0
+ const later = []
+ for (let m = 0; m < movers.length; m += 5) {
+ const i = movers[m], nb = movers[m + 2]
+ if (Math.random() < keep && freeFlyAvailable()) later.push(m); else { binList[nb].push(i); where[i] = nb; if (nb !== ESCB && nb === T[i]) binRight[nb]++ }
+ }
+ if (geo[ESCB] && binList[ESCB].length > geo[ESCB].capacity) fitGeo(geo[ESCB], binList[ESCB].length * 1.5, geo[0].size)
+ for (let b = 0; b <= nT; b++) if (geo[b] && binList[b].length > geo[b].capacity) { fitBins(0); break }
+ for (const m of later) {
+ const i = movers[m], f = takeFlight(i)
+ where[i] = -1
+ f.phase = 2; f.t = -Math.random() * 0.25; f.d = 0.62; f.sx = movers[m + 3]; f.sy = movers[m + 4]; f.x = f.sx; f.y = f.sy
+ f.bucket = movers[m + 2]; f.style = 2; f.wrong = f.bucket !== ESCB && f.bucket !== T[i]; pending[f.bucket]++
+ }
+ for (const f of fly) if (f.phase === 2 && f.style !== 2) { const nb = bucketOf(f.id); if (nb !== f.bucket) { pending[f.bucket]--; f.bucket = nb; pending[nb]++; f.sx = f.x; f.sy = f.y; f.t = 0; f.d = 0.6; f.style = 2; f.fresh = true; f.wrong = nb !== ESCB && nb !== T[f.id] } }
+ redrawBins(); retarget(true)
+ recount()
+ }
+
+ // ------------------------------------------------------------------------------------------
+ // Flights, particles and small effects (all pooled)
+ // ------------------------------------------------------------------------------------------
+ const freeFlyAvailable = () => fly.length < MAX_FLY
+ function takeFlight(id) {
+ const f = freeFly.pop() || {}
+ f.id = id; f.seq = flightSeq++; f.phase = 1; f.t = 0; f.d = 0.5; f.style = 0; f.wrong = false; f.bucket = -1
+ f.sx = 0; f.sy = 0; f.cx = 0; f.cy = 0; f.gx = 0; f.gy = 0; f.ex = 0; f.ey = 0; f.tx = 0; f.ty = 0; f.x = 0; f.y = 0; f.fresh = true
+ fly.push(f)
+ return f
+ }
+ const GATE_POW = 0.6 // the gate's scale is curved (ticks are labelled) so the busy high-confidence end gets room
+ const confY = (q) => L.gateTop + 10 + Math.pow(1 - clamp(q / 1000, 0, 1), GATE_POW) * (L.gateBot - L.gateTop - 14)
+ const yToConf = (y) => 1 - Math.pow(clamp((y - L.gateTop - 10) / (L.gateBot - L.gateTop - 14), 0, 1), 1 / GATE_POW)
+ function emit(i) {
+ if (!freeFlyAvailable()) { land(i, bucketOf(i), true); return }
+ const f = takeFlight(i)
+ f.sx = L.nx + 2; f.sy = L.ny + (Math.random() - 0.5) * 7
+ f.gx = L.gateX; f.gy = confY(Q[i])
+ f.cx = f.sx + (f.gx - f.sx) * (0.38 + Math.random() * 0.3); f.cy = f.sy + (f.gy - f.sy) * 0.15 + (Math.random() - 0.5) * Math.min(120, (L.gateBot - L.gateTop) * 0.3)
+ f.x = f.sx; f.y = f.sy; f.d = 0.46 + Math.random() * 0.06
+ }
+ /** Give every phase-2 flight its landing slot again, in launch order. */
+ function retarget(snapNew) {
+ pending.fill(0)
+ const order = fly.filter((f) => f.phase === 2).sort((a, b) => a.seq - b.seq)
+ for (const f of order) {
+ const g = geo[f.bucket]; if (!g) continue
+ const p = slotPos(f.bucket, binList[f.bucket].length + pending[f.bucket]); pending[f.bucket]++
+ f.tx = p.x; f.ty = p.y
+ if (f.fresh || snapNew === 'all') { f.ex = f.tx; f.ey = f.ty; f.fresh = false }
+ }
+ }
+ function crossGate(f, now) {
+ const i = f.id, b = bucketOf(i)
+ ensureRoom(b, 1)
+ f.phase = 2; f.t = 0; f.bucket = b; f.style = b === ESCB ? 1 : 0; f.d = b === ESCB ? 0.78 : 0.82
+ f.sx = L.gateX; f.sy = f.gy; f.x = f.sx; f.y = f.sy
+ f.wrong = b !== ESCB && b !== T[i]
+ const p = slotPos(b, binList[b].length + pending[b]); pending[b]++
+ f.tx = f.ex = p.x; f.ty = f.ey = p.y; f.fresh = false
+ if (flashes.length < 90) flashes.push({ y: f.gy, b, life: 1 })
+ spark(f.sx, f.sy, b === ESCB ? -2 : T[i], 3, 90, 0.1)
+ const ly = clamp(f.gy, L.gateTop + 12, L.gateBot - 8)
+ if (now - lastLabelAt > 260 && labels.length < 7 && !labels.some((l) => Math.abs(l.y - ly) < 15)) {
+ lastLabelAt = now
+ labels.push({ x: L.gateX + 14, y: ly, life: 1, color: b === ESCB ? AMBER : b === SPAMB ? SPAMC : colors[b], text: (b === ESCB ? 'escalate' : b === SPAMB ? 'spam' : teams[b].id) + ' ' + (Q[i] / 1000).toFixed(2).replace(/^0/, '') })
+ }
+ }
+ function spark(x, y, col, count, speed, up) {
+ for (let k = 0; k < count && pCount < MAX_P; k++) {
+ const a = Math.random() * Math.PI * 2, v = speed * (0.35 + Math.random() * 0.65), j = pCount++
+ P.x[j] = x; P.y[j] = y; P.vx[j] = Math.cos(a) * v; P.vy[j] = Math.sin(a) * v - speed * up; P.max[j] = P.life[j] = 0.25 + Math.random() * 0.35; P.col[j] = col
+ }
+ }
+ function bez(t, a, b, c, d) { const u = 1 - t; return u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d }
+
+ function update(dt, now) {
+ // Emission: drain the queue smoothly, faster when it is long (a burst), never a single dump.
+ const waiting = queue.length - qHead
+ if (waiting > 1400) { while (queue.length - qHead > 900) { const i = queue[qHead++]; land(i, bucketOf(i), true) } }
+ if (waiting > 0) {
+ emitAcc += dt * Math.max(24, waiting / 0.32)
+ let k = Math.min(waiting, Math.floor(emitAcc)); emitAcc -= k
+ activity = Math.min(1, activity + k * 0.02)
+ while (k-- > 0) emit(queue[qHead++])
+ if (qHead > 4096) { queue.splice(0, qHead); qHead = 0 }
+ } else emitAcc = 0
+ activity = Math.max(0, activity - dt * 0.9)
+
+ for (let k = fly.length - 1; k >= 0; k--) {
+ const f = fly[k]
+ f.t += dt / f.d
+ if (f.phase === 1) {
+ if (f.t >= 1) { crossGate(f, now); continue }
+ const e = easeOutQuad(f.t) * 0.55 + f.t * 0.45, u = 1 - e
+ f.x = u * u * f.sx + 2 * u * e * f.cx + e * e * f.gx; f.y = u * u * f.sy + 2 * u * e * f.cy + e * e * f.gy
+ } else {
+ if (f.t < 0) continue
+ if (f.t >= 1) {
+ pending[f.bucket] = Math.max(0, pending[f.bucket] - 1)
+ land(f.id, f.bucket, true)
+ binFlash[f.bucket] = 1
+ spark(f.tx, f.ty, f.bucket === ESCB ? -2 : T[f.id], 2, 46, 0.4)
+ if (f.wrong && rings.length < 70) rings.push({ x: f.tx, y: f.ty, life: 1 })
+ fly[k] = fly[fly.length - 1]; fly.pop(); freeFly.push(f)
+ continue
+ }
+ const sm = Math.min(1, dt * 12); f.ex += (f.tx - f.ex) * sm; f.ey += (f.ty - f.ey) * sm
+ const e = easeInOut(f.t), dx = f.ex - f.sx, dy = f.ey - f.sy
+ if (f.style === 0) { f.x = bez(e, f.sx, f.sx + dx * 0.5, f.ex - dx * 0.42, f.ex); f.y = bez(e, f.sy, f.sy, f.ey, f.ey) }
+ else if (f.style === 1) { f.x = bez(e, f.sx, f.sx + 34, f.ex, f.ex); f.y = bez(e, f.sy, f.sy + dy * 0.2, f.ey - Math.min(130, dy * 0.7), f.ey) }
+ else { const lift = Math.min(90, 30 + Math.abs(dx) * 0.2); f.x = bez(e, f.sx, f.sx + dx * 0.25, f.ex - dx * 0.25, f.ex); f.y = bez(e, f.sy, Math.min(f.sy, f.ey) - lift, Math.min(f.sy, f.ey) - lift, f.ey) }
+ }
+ }
+ for (let j = pCount - 1; j >= 0; j--) {
+ P.life[j] -= dt
+ if (P.life[j] <= 0) { const l = --pCount; P.x[j] = P.x[l]; P.y[j] = P.y[l]; P.vx[j] = P.vx[l]; P.vy[j] = P.vy[l]; P.life[j] = P.life[l]; P.max[j] = P.max[l]; P.col[j] = P.col[l]; continue }
+ P.vy[j] += 160 * dt; P.x[j] += P.vx[j] * dt; P.y[j] += P.vy[j] * dt
+ }
+ for (let k = flashes.length - 1; k >= 0; k--) { flashes[k].life -= dt * 3.2; if (flashes[k].life <= 0) flashes.splice(k, 1) }
+ for (let k = rings.length - 1; k >= 0; k--) { rings[k].life -= dt * 1.7; if (rings[k].life <= 0) rings.splice(k, 1) }
+ for (let k = labels.length - 1; k >= 0; k--) { labels[k].life -= dt * 1.05; labels[k].x += dt * 30; if (labels[k].life <= 0) labels.splice(k, 1) }
+ for (let b = 0; b < binFlash.length; b++) binFlash[b] = Math.max(0, binFlash[b] - dt * 3)
+ if (flushT >= 0) { flushT += dt / 0.7; if (flushT >= 1) flushT = -1 }
+ }
+
+ // ------------------------------------------------------------------------------------------
+ // Drawing
+ // ------------------------------------------------------------------------------------------
+ function roundRect(c, x, y, w, h, r) { c.beginPath(); c.roundRect(x, y, w, h, r) }
+ function drawBackground() {
+ const c = gctx
+ c.clearRect(0, 0, W, H)
+ const g = c.createLinearGradient(0, 0, W, H); g.addColorStop(0, '#060912'); g.addColorStop(1, '#03050a')
+ c.fillStyle = g; c.fillRect(0, 0, W, H)
+ const rg = c.createRadialGradient(L.gateX, L.ny, 10, L.gateX, L.ny, Math.max(W * 0.5, 300))
+ rg.addColorStop(0, 'rgba(34,211,238,.10)'); rg.addColorStop(1, 'rgba(34,211,238,0)')
+ c.fillStyle = rg; c.fillRect(0, 0, W, H)
+ c.fillStyle = 'rgba(148,163,184,.10)'
+ for (let y = 18; y < H; y += 22) for (let x = 14; x < W; x += 22) c.fillRect(x, y, 1, 1)
+ // the spray cone, nozzle to gate
+ const cone = c.createLinearGradient(L.nx, 0, L.gateX, 0); cone.addColorStop(0, 'rgba(34,211,238,.10)'); cone.addColorStop(1, 'rgba(34,211,238,.015)')
+ c.fillStyle = cone; c.beginPath(); c.moveTo(L.nx, L.ny - 5); c.lineTo(L.gateX, L.gateTop); c.lineTo(L.gateX, L.gateBot); c.lineTo(L.nx, L.ny + 5); c.closePath(); c.fill()
+ }
+
+ function fitText(c, text, maxW) {
+ if (c.measureText(text).width <= maxW) return text
+ let t = text
+ while (t.length > 1 && c.measureText(t + '…').width > maxW) t = t.slice(0, -1)
+ return t + '…'
+ }
+
+ function drawBinsChrome(now) {
+ for (let b = 0; b <= nT; b++) {
+ const g = geo[b]; if (!g) continue
+ const col = colors[b], isSel = sel && sel.kind === 'bin' && sel.b === b, hot = hoverB === b || isSel
+ roundRect(ctx, g.x, g.y, g.w, g.h, Math.min(8, g.h / 3))
+ ctx.fillStyle = hot ? 'rgba(255,255,255,.055)' : 'rgba(255,255,255,.022)'; ctx.fill()
+ ctx.globalAlpha = Math.min(1, (isSel ? 0.95 : hot ? 0.6 : 0.2) + binFlash[b] * 0.5); ctx.strokeStyle = col; ctx.lineWidth = isSel ? 1.6 : 1; ctx.stroke(); ctx.globalAlpha = 1
+ ctx.fillStyle = col; ctx.fillRect(g.x + 1, g.y + Math.min(6, g.h * 0.2), 3, g.h - 2 * Math.min(6, g.h * 0.2))
+ const name = b === SPAMB ? 'spam' : teams[b].id, cnt = binList[b].length, two = g.h >= 30
+ ctx.textBaseline = 'middle'; ctx.textAlign = 'left'
+ ctx.font = `700 ${g.h < 20 ? 10 : 12}px ui-monospace, Menlo, monospace`; ctx.fillStyle = col
+ ctx.fillText(fitText(ctx, name, g.labelW - (two ? 14 : 48)), g.x + 10, two ? g.y + g.h / 2 - 7 : g.y + g.h / 2 + 0.5)
+ ctx.font = `${g.h < 20 ? 9 : 10.5}px ui-monospace, Menlo, monospace`; ctx.fillStyle = 'rgba(203,213,225,.72)'
+ const prec = cnt ? Math.round((binRight[b] / cnt) * 100) + '%' : ''
+ if (two) ctx.fillText(fmtInt(cnt) + (prec ? ' · ' + prec : ''), g.x + 10, g.y + g.h / 2 + 8)
+ else { ctx.textAlign = 'right'; ctx.fillText(fmtInt(cnt), g.x + g.labelW - 6, g.y + g.h / 2 + 0.5); ctx.textAlign = 'left' }
+ }
+ // the escalate lane
+ const g = geo[ESCB]; if (!g) return
+ const isSel = sel && sel.kind === 'bin' && sel.b === ESCB, hot = hoverB === ESCB || isSel
+ roundRect(ctx, g.x, g.y, g.w, g.h, 9)
+ const lg = ctx.createLinearGradient(g.x, 0, g.x + g.w, 0); lg.addColorStop(0, 'rgba(251,191,36,.10)'); lg.addColorStop(1, 'rgba(251,191,36,.025)')
+ ctx.fillStyle = lg; ctx.fill()
+ ctx.setLineDash([5, 4]); ctx.globalAlpha = Math.min(1, (hot ? 0.9 : 0.45) + binFlash[ESCB] * 0.5); ctx.strokeStyle = AMBER; ctx.lineWidth = isSel ? 1.6 : 1; ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1
+ ctx.textBaseline = 'middle'; ctx.textAlign = 'left'
+ ctx.font = '700 11px ui-monospace, Menlo, monospace'; ctx.fillStyle = AMBER
+ ctx.fillText('ESCALATE', g.x + 12, g.y + g.h / 2 - 14)
+ ctx.font = '10px ui-monospace, Menlo, monospace'; ctx.fillStyle = 'rgba(251,191,36,.7)'
+ ctx.fillText('to a big model', g.x + 12, g.y + g.h / 2)
+ ctx.fillStyle = 'rgba(203,213,225,.78)'
+ const landed = binList[ESCB].length, all = Math.max(1, n - (queue.length - qHead) - fly.length)
+ ctx.fillText(fmtInt(landed) + ' · ' + fmtPct(landed / all), g.x + 12, g.y + g.h / 2 + 14)
+ }
+
+ function drawGate(now) {
+ const x = L.gateX, top = L.gateTop, bot = L.gateBot, yT = clamp(confY(thrQ), top, bot)
+ const pulse = 0.22 + activity * 0.3 + Math.sin(now / 420) * 0.04
+ ctx.globalCompositeOperation = 'lighter'
+ // wide glow: cyan above the threshold, amber below
+ for (const [y0, y1, rgb] of [[top, yT, '34,211,238'], [yT, bot, '251,191,36']]) {
+ if (y1 - y0 < 1) continue
+ const g = ctx.createLinearGradient(x - 40, 0, x + 40, 0)
+ g.addColorStop(0, `rgba(${rgb},0)`); g.addColorStop(0.5, `rgba(${rgb},${pulse})`); g.addColorStop(1, `rgba(${rgb},0)`)
+ ctx.fillStyle = g; ctx.fillRect(x - 40, y0, 80, y1 - y0)
+ }
+ // confidence spectrum of the last few hundred messages, hugging the gate
+ let mx = 1
+ for (let k = 0; k < 40; k++) if (confHist[k] > mx) mx = confHist[k]
+ const maxLen = Math.min(70, W * 0.07)
+ for (let k = 0; k < 40; k++) {
+ if (!confHist[k]) continue
+ const y0 = confY((k + 1) * 25), y1 = confY(k * 25), len = (confHist[k] / mx) * maxLen
+ ctx.fillStyle = (k + 0.5) * 25 < thrQ ? 'rgba(251,191,36,.30)' : 'rgba(34,211,238,.28)'
+ ctx.fillRect(x + 4, y0 + 0.5, len, Math.max(1, y1 - y0 - 1))
+ }
+ for (const f of flashes) {
+ const sprite = f.b === ESCB ? amberGlow : glows[f.b] || cyanGlow
+ ctx.globalAlpha = f.life * 0.55; ctx.drawImage(sprite, x - 46, f.y - 6, 92, 12)
+ ctx.globalAlpha = f.life * 0.22; ctx.drawImage(whiteGlow, x - 8, f.y - 8, 16, 16)
+ }
+ ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'
+ ctx.fillStyle = 'rgba(165,243,252,.95)'; ctx.fillRect(x - 1, top, 2, Math.max(0, yT - top))
+ ctx.fillStyle = 'rgba(253,230,138,.95)'; ctx.fillRect(x - 1, yT, 2, Math.max(0, bot - yT))
+ // axis ticks
+ ctx.font = '9px ui-monospace, Menlo, monospace'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'
+ for (const v of [1, 0.9, 0.75, 0.5, 0.25, 0]) {
+ const y = confY(v * 1000); ctx.fillStyle = 'rgba(148,163,184,.55)'; ctx.fillRect(x - 7, y - 0.5, 5, 1)
+ if (Math.abs(y - yT) > 11) ctx.fillText(v === 1 ? '1.0' : v === 0 ? '0' : String(v).replace(/^0/, ''), x - 10, y)
+ }
+ ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic'
+ ctx.font = '700 10.5px ui-monospace, Menlo, monospace'; ctx.fillStyle = CYAN
+ ctx.fillText('J E V G A T E', x, top - 13)
+ ctx.font = '9px ui-monospace, Menlo, monospace'; ctx.fillStyle = 'rgba(148,163,184,.75)'
+ ctx.fillText('height = confidence', x, top - 3)
+ }
+
+ /** The draggable threshold handle. Drawn over the flights so it never gets buried. */
+ function drawThreshold() {
+ const x = L.gateX, yT = clamp(confY(thrQ), L.gateTop, L.gateBot), text = 'threshold ' + thr.toFixed(2)
+ ctx.strokeStyle = AMBER; ctx.lineWidth = dragThr ? 2.2 : 1.4; ctx.setLineDash([4, 3]); ctx.beginPath(); ctx.moveTo(x - 30, yT); ctx.lineTo(x + 62, yT); ctx.stroke(); ctx.setLineDash([])
+ ctx.font = '700 10px ui-monospace, Menlo, monospace'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'
+ const w = ctx.measureText(text).width + 12
+ roundRect(ctx, x - 34 - w, yT - 9, w, 18, 9); ctx.fillStyle = dragThr ? 'rgba(60,40,4,.96)' : 'rgba(20,14,2,.9)'; ctx.fill(); ctx.strokeStyle = AMBER; ctx.lineWidth = 1; ctx.stroke()
+ ctx.fillStyle = AMBER; ctx.fillText(text, x - 40, yT + 0.5)
+ ctx.beginPath(); ctx.moveTo(x - 25, yT); ctx.lineTo(x - 34, yT - 5); ctx.lineTo(x - 34, yT + 5); ctx.closePath(); ctx.fill()
+ }
+
+ function drawNozzle(now) {
+ const x = L.nx, y = L.ny + Math.sin(now / 37) * activity * 1.3
+ ctx.lineCap = 'round'
+ ctx.strokeStyle = '#0b1220'; ctx.lineWidth = 30; ctx.beginPath(); ctx.moveTo(-16, y + 96); ctx.bezierCurveTo(x * 0.1, y + 92, x * 0.12, y, x - 50, y); ctx.stroke()
+ ctx.strokeStyle = '#223047'; ctx.lineWidth = 22; ctx.stroke()
+ ctx.strokeStyle = 'rgba(148,163,184,.3)'; ctx.lineWidth = 2; ctx.setLineDash([3, 8]); ctx.lineDashOffset = -now / 28; ctx.stroke(); ctx.setLineDash([]); ctx.lineDashOffset = 0
+ const g = ctx.createLinearGradient(0, y - 19, 0, y + 19); g.addColorStop(0, '#0f172a'); g.addColorStop(0.4, '#cbd5e1'); g.addColorStop(0.55, '#64748b'); g.addColorStop(1, '#0f172a')
+ ctx.fillStyle = g; ctx.beginPath(); ctx.moveTo(x - 54, y - 19); ctx.lineTo(x - 7, y - 9); ctx.lineTo(x - 7, y + 9); ctx.lineTo(x - 54, y + 19); ctx.closePath(); ctx.fill()
+ ctx.fillStyle = CYAN; ctx.fillRect(x - 10, y - 11, 6, 22)
+ ctx.fillStyle = '#334155'; ctx.fillRect(x - 60, y - 22, 8, 44)
+ ctx.fillStyle = 'rgba(34,211,238,.55)'; ctx.fillRect(x - 40, y - 15, 3, 30)
+ ctx.globalCompositeOperation = 'lighter'; ctx.globalAlpha = 0.35 + activity * 0.65
+ const r = 16 + activity * 16; ctx.drawImage(cyanGlow, x - r + 2, y - r, r * 2, r * 2)
+ ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'
+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic'
+ ctx.font = '700 10.5px ui-monospace, Menlo, monospace'; ctx.fillStyle = 'rgba(226,232,240,.9)'
+ ctx.fillText('I N B O X', 12, y - 48)
+ ctx.font = '9.5px ui-monospace, Menlo, monospace'; ctx.fillStyle = 'rgba(148,163,184,.8)'
+ ctx.fillText('noise ' + noise.toFixed(2), 12, y - 35)
+ }
+
+ function draw(now) {
+ // trails: fade the fx layer a little each frame, then add this frame's glow
+ fctx.globalCompositeOperation = 'destination-out'; fctx.fillStyle = 'rgba(0,0,0,.2)'; fctx.fillRect(0, 0, W, H)
+ fctx.globalCompositeOperation = 'lighter'
+ for (const f of fly) {
+ if (f.phase === 2 && f.t < 0) continue
+ const esc2 = f.phase === 2 && f.bucket === ESCB, r = f.phase === 1 ? 9 : f.style === 2 ? 6 : 8 - f.t * 3
+ fctx.globalAlpha = f.phase === 1 ? 0.5 : 0.62
+ fctx.drawImage(esc2 ? amberGlow : f.wrong ? redGlow : glows[T[f.id]], f.x - r, f.y - r, r * 2, r * 2)
+ }
+ for (let j = 0; j < pCount; j++) {
+ const a = P.life[j] / P.max[j]; fctx.globalAlpha = a
+ fctx.drawImage(P.col[j] === -2 ? amberGlow : glows[P.col[j]] || whiteGlow, P.x[j] - 3, P.y[j] - 3, 6, 6)
+ }
+ fctx.globalAlpha = 1
+
+ ctx.drawImage(bgLayer, 0, 0, W, H)
+ drawBinsChrome(now)
+ if (flushT >= 0) { const p = flushT; ctx.globalAlpha = (1 - p) * (1 - p); ctx.drawImage(flushLayer, 0, p * p * 46, W, H); ctx.globalAlpha = 1 }
+ ctx.drawImage(binLayer, 0, 0, W, H)
+ ctx.globalCompositeOperation = 'lighter'; ctx.drawImage(fxLayer, 0, 0, W, H); ctx.globalCompositeOperation = 'source-over'
+ drawGate(now)
+ drawNozzle(now)
+
+ for (const f of fly) {
+ const i = f.id, tgt = f.phase === 2 && geo[f.bucket] ? geo[f.bucket].size : 8, tt = Math.max(0, f.t)
+ const s = f.phase === 1 ? 8 : f.style === 2 ? Math.max(5, tgt) : 8 + (tgt - 8) * tt * tt, x = f.x - s / 2, y = f.y - s / 2
+ ctx.fillStyle = colors[T[i]]; ctx.fillRect(x, y, s, s)
+ const nn = M[i] >> 2
+ if (nn && D[i] < nT) { const share = nn / (nn + (M[i] & 3)); ctx.fillStyle = colors[D[i]]; ctx.fillRect(x + s * (1 - share), y, s * share, s) }
+ if ((U[i] & 7) >= 3) { ctx.fillStyle = 'rgba(255,255,255,.9)'; ctx.fillRect(f.x - 1, f.y - 1, 2, 2) }
+ if (f.phase === 2 && (f.wrong || f.bucket === ESCB)) { ctx.strokeStyle = f.wrong ? WRONG : AMBER; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(f.x, f.y, s * 0.5 + 3.5, 0, 6.2832); ctx.stroke() }
+ }
+ drawThreshold()
+ for (const r of rings) { ctx.globalAlpha = r.life; ctx.strokeStyle = WRONG; ctx.lineWidth = 1.6; ctx.beginPath(); ctx.arc(r.x, r.y, 4 + (1 - r.life) * 13, 0, 6.2832); ctx.stroke() }
+ ctx.globalAlpha = 1
+ ctx.font = '700 10.5px ui-monospace, Menlo, monospace'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'
+ for (const l of labels) { ctx.globalAlpha = Math.min(1, l.life * 1.6); ctx.fillStyle = 'rgba(4,6,11,.72)'; const w = ctx.measureText(l.text).width; ctx.fillRect(l.x - 3, l.y - 7, w + 6, 14); ctx.fillStyle = l.color; ctx.fillText(l.text, l.x, l.y + 0.5) }
+ ctx.globalAlpha = 1
+ if (sel && sel.kind === 'item') drawSelection(now)
+ }
+ function drawSelection(now) {
+ const i = sel.id; let x = null, y = null
+ const b = where[i]
+ if (b >= 0 && binList[b]) { const k = binList[b].indexOf(i); if (k >= 0) { const p = slotPos(b, k); x = p.x; y = p.y } }
+ else { const f = fly.find((q) => q.id === i); if (f) { x = f.x; y = f.y } }
+ if (x == null) return
+ const r = 8 + Math.sin(now / 160) * 1.5
+ ctx.strokeStyle = '#fff'; ctx.lineWidth = 1.6; ctx.beginPath(); ctx.arc(x, y, r, 0, 6.2832); ctx.stroke()
+ ctx.globalCompositeOperation = 'lighter'; ctx.globalAlpha = 0.7; ctx.drawImage(whiteGlow, x - 16, y - 16, 32, 32); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'
+ }
+
+ // ------------------------------------------------------------------------------------------
+ // DOM: top bar, race, deck, summary
+ // ------------------------------------------------------------------------------------------
+ function elapsedNow(now) { return live.elapsedMs + (live.running && live.phase === 'run' ? Math.min(400, now - liveAt) : 0) }
+ function updateDom(now, dt) {
+ const t = totals(), k = Math.min(1, dt * 9)
+ shown.done += (n - shown.done) * k; if (Math.abs(n - shown.done) < 0.6) shown.done = n
+ shown.cost += (live.costUsd - shown.cost) * k
+ shown.mps += (live.mps - shown.mps) * Math.min(1, dt * 5)
+ shown.escPct += (t.escPct - shown.escPct) * k
+ shown.acc = t.acc == null ? null : shown.acc == null ? t.acc : shown.acc + (t.acc - shown.acc) * k
+ if (now - domAt < 66) return
+ domAt = now
+ const batch = config.batch || 1, el = elapsedNow(now)
+ setText($('s-done'), fmtInt(shown.done)); setText($('s-batch'), `of ${fmtInt(batch)}`); setText($('synth'), `all messages are synthetic · made up by a seeded generator · batch ${live.batchNo}`)
+ setText($('s-mps'), shown.mps >= 100 ? fmtInt(shown.mps) : shown.mps.toFixed(1)); setText($('s-pool'), `pool of ${config.concurrency} · ${live.client === 'typesafe' ? 'live' : 'mock'}`)
+ setText($('s-cost'), fmtMoney(shown.cost)); setText($('s-per1k'), n ? `per 1,000: ${fmtMoney((live.costUsd / n) * 1000)}` : 'per 1,000: —')
+ setText($('s-acc'), fmtPct(shown.acc)); setText($('s-recent'), `last 300: ${fmtPct(t.recent)}`)
+ $('s-acc').className = t.acc != null && t.acc < config.targetAccuracy ? 'bad' : 'ok'
+ setText($('s-esc'), fmtPct(shown.escPct)); setText($('s-escn'), `${fmtInt(t.escN)} to a big model`)
+ setText($('s-time'), fmtSecs(el)); setText($('s-answers'), `${fmtInt(n * 5)} answers`)
+ $('bar-jev').style.width = clamp((shown.done / batch) * 100, 0, 100) + '%'
+ const ghostOn = Math.min(batch, Math.floor(el / 1000 / config.llmSecondsPerItem) + 1)
+ $('bar-ghost').style.width = clamp((ghostOn / batch) * 100, 0, 100) + '%'
+ setText($('race-jev'), `message ${fmtInt(shown.done)} of ${fmtInt(batch)}`)
+ setText($('ghost-name'), `${config.llmSecondsPerItem}s/msg model`)
+ setText($('race-ghost'), `a model taking ${config.llmSecondsPerItem}s per message would be on message ${fmtInt(ghostOn)}`)
+ setText($('pause'), live.running ? 'Pause' : 'Resume'); $('pause').classList.toggle('on', !live.running)
+ $('burst').textContent = live.burstLeft > 0 ? `Bursting ${fmtInt(live.burstLeft)}` : 'Burst +500'
+ const ov = live.overrides || {}
+ $('noise-pill').classList.toggle('hidden', !ov.noise); $('thr-pill').classList.toggle('hidden', !ov.threshold); $('fileVals').disabled = !(ov.noise || ov.threshold)
+ if (now - matrixAt > 380 && matrixDirty) { matrixAt = now; matrixDirty = false; drawMatrix() }
+ if (now - sweepAt > 480 && sweepDirty) { sweepAt = now; sweepDirty = false; drawSweep() }
+ }
+
+ function showSummary(s) {
+ const box = $('summary')
+ if (!s) { box.classList.add('hidden'); summaryShownFor = -1; return }
+ if (summaryShownFor === s.batchNo) return
+ summaryShownFor = s.batchNo
+ setText($('sum-kicker'), `Batch ${s.batchNo} done · all synthetic`)
+ $('sum-line').innerHTML = `${fmtInt(s.messages)} messages<em>·</em><span class="acc">${fmtSecs(s.elapsedMs)}</span><em>·</em>${fmtMoney(s.costUsd)}<em>·</em><span class="ok">${fmtPct(s.accuracy)} right</span><em>·</em><span class="warn">${fmtPct(s.escalatedPct)} escalated</span>`
+ setText($('sum-sub'), `${fmtInt(s.answers)} typed answers in ${fmtInt(s.messages)} calls · a ${config.llmSecondsPerItem}s-per-message model would be on message ${fmtInt(s.llmWouldBeOn)} · next batch has a new seed`)
+ box.classList.remove('hidden')
+ const bar = $('sum-timer'); bar.classList.remove('run'); void bar.offsetWidth; if (live.running) bar.classList.add('run')
+ }
+
+ // ---- threshold sweep: accuracy and escalations at every threshold, from this batch --------
+ let suggested = null
+ function computeSweep() {
+ const cnt = new Float64Array(101), ok = new Float64Array(101)
+ let sr = 0, so = 0
+ for (let i = 0; i < n; i++) { if (S[i] >= 128) { sr++; if (T[i] === SPAMB) so++; continue } const b = Math.min(100, Math.floor(Q[i] / 10)); cnt[b]++; if (C[i] === T[i]) ok[b]++ }
+ const out = new Array(101); let routed = sr, right = so
+ for (let j = 100; j >= 0; j--) { routed += cnt[j]; right += ok[j]; out[j] = { acc: routed ? right / routed : null, esc: n ? (n - routed) / n : 0 } }
+ return out
+ }
+ function drawSweep() {
+ const cv = $('sweep'), w = cv.clientWidth, h = 34; if (!w) return
+ if (cv.width !== Math.round(w * dpr)) { cv.width = Math.round(w * dpr); cv.height = Math.round(h * dpr) }
+ const c = cv.getContext('2d'); c.setTransform(dpr, 0, 0, dpr, 0, 0); c.clearRect(0, 0, w, h)
+ const sw = computeSweep(), x = (j) => 8 + (j / 100) * (w - 16), yA = (a) => 3 + (1 - (clamp(a, 0.5, 1) - 0.5) / 0.5) * (h - 6), yE = (e) => h - 2 - e * (h - 5)
+ c.fillStyle = 'rgba(255,255,255,.03)'; c.fillRect(8, 0, w - 16, h)
+ c.beginPath(); c.moveTo(x(0), h); for (let j = 0; j <= 100; j++) c.lineTo(x(j), yE(sw[j].esc)); c.lineTo(x(100), h); c.closePath(); c.fillStyle = 'rgba(251,191,36,.22)'; c.fill()
+ c.beginPath(); for (let j = 0; j <= 100; j++) c[j ? 'lineTo' : 'moveTo'](x(j), yE(sw[j].esc)); c.strokeStyle = AMBER; c.lineWidth = 1.2; c.stroke()
+ const ty = yA(config.targetAccuracy); c.setLineDash([3, 3]); c.strokeStyle = 'rgba(52,211,153,.45)'; c.beginPath(); c.moveTo(8, ty); c.lineTo(w - 8, ty); c.stroke(); c.setLineDash([])
+ c.beginPath(); let started = false
+ for (let j = 0; j <= 100; j++) { if (sw[j].acc == null) continue; c[started ? 'lineTo' : 'moveTo'](x(j), yA(sw[j].acc)); started = true }
+ c.strokeStyle = '#34d399'; c.lineWidth = 1.6; c.stroke()
+ suggested = null
+ if (n >= 50) for (let j = 0; j <= 100; j++) if (sw[j].acc != null && sw[j].acc >= config.targetAccuracy) { suggested = { thr: j / 100, acc: sw[j].acc, esc: sw[j].esc }; break }
+ if (suggested) { c.fillStyle = '#34d399'; c.beginPath(); c.arc(x(suggested.thr * 100), yA(suggested.acc), 3, 0, 6.2832); c.fill() }
+ const tx = x(thr * 100); c.strokeStyle = '#fff'; c.lineWidth = 1; c.beginPath(); c.moveTo(tx, 0); c.lineTo(tx, h); c.stroke()
+ c.font = '9px ui-monospace, Menlo, monospace'; c.fillStyle = 'rgba(148,163,184,.8)'; c.textAlign = 'left'; c.fillText(`target ${Math.round(config.targetAccuracy * 100)}%`, 11, Math.max(9, ty - 3))
+ const chip = $('suggest')
+ if (suggested) { chip.classList.remove('hidden'); chip.textContent = `${Math.round(config.targetAccuracy * 100)}% at ${suggested.thr.toFixed(2)} · ${fmtPct(suggested.esc, 0)} esc`; chip.title = `Lowest threshold where at least ${Math.round(config.targetAccuracy * 100)}% of auto-routed messages are right on this batch. It escalates ${fmtPct(suggested.esc, 0)}. Click to use it.` }
+ else if (n >= 50) { chip.classList.remove('hidden'); chip.textContent = `${Math.round(config.targetAccuracy * 100)}% not reachable`; chip.title = 'No threshold reaches the target on this batch. The noise is too high or the team descriptions overlap.' }
+ else chip.classList.add('hidden')
+ }
+
+ // ---- confusion matrix ------------------------------------------------------------------------
+ function drawMatrix() {
+ const cv = $('matrix'), w = cv.clientWidth; if (!w || !nT) return
+ const rows = nT + 1, cols = nT + 2, labelW = nT > 12 ? 50 : 62, headH = 12
+ const cell = Math.min(30, (w - labelW - 6) / cols), ch = Math.max(7, Math.min(24, cell * 0.86)), h = Math.round(headH + rows * ch + 4)
+ if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(h * dpr)) { cv.width = Math.round(w * dpr); cv.height = Math.round(h * dpr); cv.style.height = h + 'px' }
+ const c = cv.getContext('2d'); c.setTransform(dpr, 0, 0, dpr, 0, 0); c.clearRect(0, 0, w, h)
+ const gx = (j) => labelW + j * cell + (j === cols - 1 ? 5 : 0)
+ for (let j = 0; j < cols; j++) { c.fillStyle = j < nT ? colors[j] : j === nT ? SPAMC : AMBER; c.fillRect(gx(j) + 2, 2, cell - 4, 5) }
+ c.textBaseline = 'middle'
+ for (let i = 0; i < rows; i++) {
+ const y = headH + i * ch, row = confusion[i] || [], sum = row.reduce((a, b) => a + b, 0) || 1
+ c.font = `${ch < 12 ? 8 : 10}px ui-monospace, Menlo, monospace`; c.textAlign = 'left'; c.fillStyle = i < nT ? colors[i] : SPAMC
+ c.fillText(fitText(c, i < nT ? teams[i].id : 'spam', labelW - 4), 0, y + ch / 2)
+ for (let j = 0; j < cols; j++) {
+ const v = (row[j] || 0) / sum, a = v ? 0.1 + 0.9 * Math.sqrt(v) : 0.035
+ c.fillStyle = j === cols - 1 ? `rgba(251,191,36,${a})` : i === j ? `rgba(52,211,153,${a})` : v ? `rgba(255,77,94,${a})` : 'rgba(255,255,255,.035)'
+ c.fillRect(gx(j) + 0.5, y + 0.5, cell - 1, ch - 1)
+ if (cell >= 21 && ch >= 14 && row[j]) { c.font = '8.5px ui-monospace, Menlo, monospace'; c.textAlign = 'center'; c.fillStyle = v > 0.35 ? '#04120c' : 'rgba(226,232,240,.85)'; c.fillText(row[j] > 9999 ? Math.round(row[j] / 1000) + 'k' : String(row[j]), gx(j) + cell / 2, y + ch / 2 + 0.5) }
+ }
+ }
+ mxCells = { labelW, cell, ch, headH, rows, cols, gx }
+ }
+ $('matrix').addEventListener('mousemove', (e) => {
+ if (!mxCells) return
+ const r = e.currentTarget.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top, m = mxCells
+ const i = Math.floor((y - m.headH) / m.ch); let j = -1
+ for (let q = 0; q < m.cols; q++) if (x >= m.gx(q) && x < m.gx(q) + m.cell) j = q
+ if (i < 0 || i >= m.rows || j < 0) { setText($('mx-tip'), 'Hover a cell.'); return }
+ const row = confusion[i] || [], sum = row.reduce((a, b) => a + b, 0), name = (q) => (q < nT ? teams[q].id : q === nT ? 'spam' : 'escalated')
+ setText($('mx-tip'), `true ${name(i)} → ${j === nT + 1 ? 'escalated' : 'bin ' + name(j)}: ${fmtInt(row[j] || 0)} (${fmtPct(sum ? (row[j] || 0) / sum : 0)})`)
+ })
+
+ // ------------------------------------------------------------------------------------------
+ // Inspector
+ // ------------------------------------------------------------------------------------------
+ const teamName = (i) => (i < nT ? teams[i]?.id ?? '?' : i === SPAMB ? 'spam' : 'escalated')
+ const teamColor = (i) => (i <= nT ? colors[i] : AMBER)
+ function probBars(probs, top, colorOf, limit) {
+ const e = Object.entries(probs || {}).sort((a, b) => b[1] - a[1]).slice(0, limit)
+ return e.map(([k, p]) => `<div class="bar${k === top ? ' top' : ''}"><span class="n" title="${esc(k)}">${esc(k)}</span><span class="t"><i style="width:${Math.max(2, p * 100)}%;background:${colorOf(k)}"></i></span><span class="v">${p.toFixed(2).replace(/^0/, '')}</span></div>`).join('')
+ }
+ function levelBars(a, truth, legend) {
+ const e = Object.entries(a?.probabilities || {}).sort((x, y) => Number(x[0]) - Number(y[0]))
+ const best = e.reduce((m, x) => (x[1] > m[1] ? x : m), ['0', -1])[0]
+ const bars = e.map(([k, p]) => `<i class="${k === best ? 'top' : ''}${Number(k) === truth ? ' truth' : ''}" style="height:${Math.max(8, p * 100)}%" title="${esc(legend[k] ?? k)}: ${p.toFixed(2)}"></i>`).join('')
+ return `<div><div class="levels">${bars}</div><div class="lvl-note">level ${esc(best)} · ${esc(legend[best] ?? '')}</div></div>`
+ }
+ function noulBar(a, truth) {
+ const p = Number(a?.noul ?? 0.5)
+ return `<div class="bars"><div class="bar top"><span class="n">${p >= 0.5 ? 'yes' : 'no'}</span><span class="t"><i style="width:${Math.max(2, p * 100)}%;background:${p >= 0.5 ? 'var(--ok)' : 'var(--bad)'}"></i></span><span class="v">${p.toFixed(2).replace(/^0/, '')}</span></div></div>`
+ }
+ function renderRecord(r, liveMode) {
+ const body = $('insp-body')
+ setText($('insp-title'), liveMode ? 'Inspector · live sample' : 'Inspector · pinned')
+ $('insp-live').classList.toggle('hidden', !liveMode); $('insp-follow').classList.toggle('hidden', liveMode)
+ if (!r) { body.innerHTML = '<div class="how">This message is older than the last 6,000 kept for inspection.</div>'; return }
+ const b = bucketOf(r.id) , right = b === ESCB ? null : b === r.truth
+ const tag = right == null ? `<span class="tag esc">escalated · ${(r.confidence).toFixed(2)} under ${thr.toFixed(2)}</span>` : right ? '<span class="tag right">right</span>' : '<span class="tag wrong">wrong bin</span>'
+ const parts = (r.parts || []).map((p) => {
+ if (p.kind === 'true' || p.kind === 'noise') return `<span style="border-bottom-color:${teamColor(p.team)};${p.kind === 'noise' ? `background:${teamColor(p.team)}22` : ''}" title="${p.kind === 'noise' ? 'mixed in from ' : 'true team: '}${esc(teamName(p.team))}">${esc(p.text)}</span>`
+ if (p.kind === 'spam') return `<span style="border-bottom-color:${SPAMC}">${esc(p.text)}</span>`
+ return `<span class="dimmed">${esc(p.text)}</span>`
+ }).join(' ')
+ const a = r.answers || {}, ham = r.truth !== SPAMB
+ body.innerHTML = `
+ <div class="insp-verdict"><span class="sw" style="background:${teamColor(r.truth)}"></span><b>#${fmtInt(r.id + 1)}</b><span>Jev says</span><b style="color:${teamColor(r.choice)}">${esc(teamName(r.choice))}</b>${tag}</div>
+ <div class="insp-text">${parts}</div>
+ <div class="insp-meta">true team <b style="color:${teamColor(r.truth)}">${esc(teamName(r.truth))}</b>${r.nNoise ? ` · ${r.nTrue} true + ${r.nNoise} from <b style="color:${teamColor(r.distractor)}">${esc(teamName(r.distractor))}</b>` : r.truth === SPAMB ? '' : ` · ${r.nTrue} true, no noise`} · ${r.tokens} tok · ${r.latencyMs < 1 ? '<1' : Math.round(r.latencyMs)} ms</div>
+ <div class="ans">
+ <div class="q">team<small>truth ${esc(teamName(r.truth))}</small></div><div class="bars">${probBars(a.team?.probabilities, a.team?.choice, (k) => { const ix = teams.findIndex((t) => t.id === k); return ix < 0 ? CYAN : colors[ix] }, 4)}</div>
+ <div class="q">urgency<small>${ham ? 'truth level ' + r.truthUrgency : 'score'}</small></div>${levelBars(a.urgency, r.truth === SPAMB ? null : r.truthUrgency, urgencyLegend)}
+ <div class="q">spam<small>truth ${r.truth === SPAMB ? 'yes' : 'no'}</small></div>${noulBar(a.spam, r.truth === SPAMB)}
+ <div class="q">needs_human<small>${ham ? 'truth ' + (r.truthHuman ? 'yes' : 'no') : 'noul'}</small></div>${noulBar(a.needs_human, r.truth === SPAMB ? null : r.truthHuman)}
+ <div class="q">mood<small>${ham ? 'truth level ' + r.truthMood : 'score'}</small></div>${levelBars(a.mood, r.truth === SPAMB ? null : r.truthMood, moodLegend)}
+ </div>`
+ }
+ async function renderBin(b) {
+ const body = $('insp-body')
+ setText($('insp-title'), 'Inspector · pinned'); $('insp-live').classList.add('hidden'); $('insp-follow').classList.remove('hidden')
+ const res = await ctl('bin', { bucket: b })
+ if (!sel || sel.kind !== 'bin' || sel.b !== b) return
+ const cnt = counts[b] || 0, ok = rights[b] || 0, isEsc = b === ESCB
+ const wrongFrom = []
+ for (let i = 0; i <= nT; i++) if (i !== b && confusion[i] && confusion[i][b]) wrongFrom.push([i, confusion[i][b]])
+ wrongFrom.sort((x, y) => y[1] - x[1])
+ const desc = isEsc ? `Jev's team confidence was under ${thr.toFixed(2)}, so these go to a big model instead of a bin.` : b === SPAMB ? 'Jev said yes to the spam question. These skip the teams.' : teams[b].description
+ body.innerHTML = `
+ <div class="insp-verdict"><span class="sw" style="background:${teamColor(b)}"></span><b style="color:${teamColor(b)}">${esc(isEsc ? 'escalate lane' : teamName(b) + ' bin')}</b><span>${fmtInt(cnt)} messages</span>${isEsc ? '' : `<span class="tag ${cnt && ok / cnt < config.targetAccuracy ? 'wrong' : 'right'}">${fmtPct(cnt ? ok / cnt : null)} right</span>`}</div>
+ <div class="insp-meta" style="font-size:12px;color:var(--ink)">${esc(desc)}</div>
+ <div class="insp-meta">${isEsc ? 'Truly from: ' : 'Wrong arrivals truly from: '}${wrongFrom.slice(0, 4).map(([i, c]) => `<b style="color:${teamColor(i)}">${esc(teamName(i))}</b> ${fmtInt(c)}`).join(' · ') || 'none yet'}</div>
+ <div class="bin-list">${(res.list || []).map((m) => `<button data-id="${m.id}"><span>${esc(m.text)}</span><em class="${m.right == null ? 'e' : m.right ? 'r' : 'w'}">${m.confidence.toFixed(2).replace(/^0/, '')} ${m.right == null ? 'esc' : m.right ? 'ok' : 'wrong'}</em></button>`).join('') || '<div class="how">Nothing here yet.</div>'}</div>`
+ body.querySelectorAll('button[data-id]').forEach((el) => el.addEventListener('click', () => selectItem(Number(el.dataset.id))))
+ }
+ async function selectItem(id) {
+ sel = { kind: 'item', id }; follow = false
+ const res = await ctl('inspect', { id })
+ if (sel && sel.kind === 'item' && sel.id === id) renderRecord(res.record, false)
+ $('inspector').scrollIntoView({ block: 'nearest', behavior: 'smooth' })
+ }
+ function selectBin(b) { sel = { kind: 'bin', b }; follow = false; renderBin(b); $('inspector').scrollIntoView({ block: 'nearest', behavior: 'smooth' }) }
+ $('insp-follow').addEventListener('click', () => { sel = null; follow = true; setText($('insp-title'), 'Inspector · live sample'); $('insp-live').classList.remove('hidden'); $('insp-follow').classList.add('hidden') })
+
+ // ------------------------------------------------------------------------------------------
+ // Network
+ // ------------------------------------------------------------------------------------------
+ async function ctl(cmd, extra) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd, ...extra }) }); return await r.json() } catch { return {} }
+ }
+ const b64u8 = (s) => Uint8Array.from(atob(s), (ch) => ch.charCodeAt(0))
+ function takeLive(s, now) {
+ live = s; liveAt = now
+ if (now > holdServerUntil && !dragThr) {
+ if (Math.abs(s.threshold - thr) > 1e-6) { setThr(s.threshold, false) }
+ if (Math.abs(s.noise - noise) > 1e-6) { noise = s.noise; syncNoiseUi() }
+ }
+ const err = $('cfgError'); err.classList.toggle('hidden', !s.error && !s.jevError); if (s.error || s.jevError) setText(err, s.error ? `${s.error}. The demo keeps running on the last good file.` : `Jev call failed: ${s.jevError}`)
+ showSummary(s.phase === 'summary' ? s.summary : null)
+ }
+ function onFull(s) {
+ const now = performance.now()
+ config = s.config || config; urgencyLegend = s.urgencyLegend || []; moodLegend = s.moodLegend || []
+ setText($('title'), s.title || 'Jev Firehose'); setText($('desk'), s.desk || ''); document.title = s.title || 'Jev Firehose'
+ const warn = $('cfgWarn'); warn.classList.toggle('hidden', !(s.warnings && s.warnings.length)); if (s.warnings && s.warnings.length) setText(warn, 'firehose.json: ' + s.warnings.slice(0, 3).join(' · '))
+ const fresh = s.rev !== rev || s.n < n || (s.teams || []).length !== nT
+ if (fresh) {
+ if (rev !== -1 && binList.some((l) => l.length)) { flctx.clearRect(0, 0, W, H); flctx.drawImage(binLayer, 0, 0, W, H); flushT = 0 }
+ rev = s.rev
+ thr = s.threshold; thrQ = Math.round(thr * 1000); noise = s.noise
+ resetWorld(s); layout(); syncNoiseUi(); syncThrUi()
+ shown.done = Math.min(shown.done, s.n)
+ }
+ if (s.hist && s.n > n) {
+ const t = b64u8(s.hist.t), c = b64u8(s.hist.c), qb = b64u8(s.hist.q), q = new Uint16Array(qb.buffer, 0, qb.length >> 1), sp = b64u8(s.hist.s), d = b64u8(s.hist.d), m = b64u8(s.hist.m), u = b64u8(s.hist.u)
+ const it = [0, 0, 0, 0, 0, 0, 0], animateFrom = fresh ? s.n : n
+ for (let i = n; i < s.n; i++) { it[0] = t[i]; it[1] = c[i]; it[2] = q[i]; it[3] = sp[i]; it[4] = d[i]; it[5] = m[i]; it[6] = u[i]; recv(i, it, i >= animateFrom) }
+ if (fresh) { redrawBins(); shown.done = s.n }
+ }
+ takeLive(s, now)
+ if (follow && s.last) renderRecord(s.last, true)
+ }
+ let resyncing = false
+ async function resync() { if (resyncing) return; resyncing = true; try { onFull(await (await fetch('/state', { cache: 'no-store' })).json()) } catch { /* server restarting */ } resyncing = false }
+ function onFrame(f) {
+ if (f.rev !== rev || f.from > n) { resync(); return }
+ for (let j = 0; j < f.items.length; j++) { const i = f.from + j; if (i >= n) recv(i, f.items[j], true) }
+ takeLive(f, performance.now())
+ if (follow && f.sample) renderRecord(f.sample, true)
+ }
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onFull(JSON.parse(e.data)))
+ es.addEventListener('frame', (e) => onFrame(JSON.parse(e.data)))
+
+ // ------------------------------------------------------------------------------------------
+ // Input
+ // ------------------------------------------------------------------------------------------
+ function throttle(fn, ms) { let t = 0, timer = null, lastArgs = null; return (...a) => { lastArgs = a; const now = performance.now(); if (now - t >= ms) { t = now; fn(...a) } else if (!timer) timer = setTimeout(() => { timer = null; t = performance.now(); fn(...lastArgs) }, ms - (now - t)) } }
+ const sendThr = throttle((v) => ctl('threshold', { value: v }), 70)
+ const sendNoise = throttle((v) => ctl('noise', { value: v }), 70)
+ function syncThrUi() { $('threshold').value = String(thr); setText($('thr-val'), thr.toFixed(2)) }
+ function syncNoiseUi() { $('noise').value = String(noise); setText($('noise-val'), noise.toFixed(2)) }
+ function setThr(v, fromUser) {
+ v = Math.round(clamp(v, 0, 1) * 100) / 100
+ if (Math.abs(v - thr) < 1e-9) return
+ thr = v; thrQ = Math.round(v * 1000)
+ syncThrUi(); rebucket(); drawSweep(); drawMatrix()
+ if (sel && sel.kind === 'bin') renderBin(sel.b)
+ if (fromUser) { holdServerUntil = performance.now() + 450; sendThr(v) }
+ }
+ $('threshold').addEventListener('input', (e) => setThr(Number(e.target.value), true))
+ $('noise').addEventListener('input', (e) => { noise = clamp(Number(e.target.value), 0, 1); setText($('noise-val'), noise.toFixed(2)); holdServerUntil = performance.now() + 450; sendNoise(noise) })
+ $('suggest').addEventListener('click', () => { if (suggested) setThr(suggested.thr, true) })
+ $('burst').addEventListener('click', () => { activity = 1; ctl('burst', { n: 500 }) })
+ $('fileVals').addEventListener('click', () => { holdServerUntil = 0; ctl('clearOverrides') })
+ $('pause').addEventListener('click', () => ctl(live.running ? 'pause' : 'start'))
+ $('step').addEventListener('click', async () => { if (live.running) await ctl('pause'); ctl('tick', { n: 1 }) })
+ $('reset').addEventListener('click', () => ctl('reset'))
+ window.addEventListener('keydown', (e) => {
+ if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return
+ if (e.key === ' ') { e.preventDefault(); $('pause').click() } else if (e.key === 'b' || e.key === 'B') $('burst').click(); else if (e.key === 's' || e.key === 'S') $('step').click()
+ })
+
+ function scenePoint(e) { const r = scene.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top } }
+ const nearThr = (p) => Math.abs(p.y - clamp(confY(thrQ), L.gateTop, L.gateBot)) < 10 && p.x > L.gateX - 120 && p.x < L.gateX + 64
+ function bucketAt(p) { for (let b = 0; b < geo.length; b++) { const g = geo[b]; if (p.x >= g.x && p.x <= g.x + g.w && p.y >= g.y && p.y <= g.y + g.h) return b } return -1 }
+ function tileAt(p, b) {
+ const g = geo[b]; if (p.x < g.ax || p.y < g.ay || p.y > g.ay + g.ah) return -1
+ const col = Math.floor((p.x - g.ax) / g.pitch), row = Math.floor((g.ay + g.ah - p.y) / g.pitch)
+ if (row < 0 || row >= g.rows) return -1
+ const slot = (col * g.rows + row) * g.unit
+ return slot < binList[b].length ? binList[b][slot] : -1
+ }
+ scene.addEventListener('pointerdown', (e) => {
+ const p = scenePoint(e)
+ if (nearThr(p)) { dragThr = true; scene.setPointerCapture(e.pointerId); return }
+ let best = null, bd = 15 * 15
+ for (const f of fly) { const d = (f.x - p.x) ** 2 + (f.y - p.y) ** 2; if (d < bd) { bd = d; best = f } }
+ if (best) { selectItem(best.id); return }
+ const b = bucketAt(p)
+ if (b >= 0) { const id = tileAt(p, b); if (id >= 0) selectItem(id); else selectBin(b) }
+ })
+ scene.addEventListener('pointermove', (e) => {
+ const p = scenePoint(e)
+ if (dragThr) { setThr(yToConf(p.y), true); return }
+ hoverB = bucketAt(p)
+ scene.style.cursor = nearThr(p) ? 'ns-resize' : hoverB >= 0 ? 'pointer' : 'default'
+ })
+ const endDrag = () => { dragThr = false }
+ scene.addEventListener('pointerup', endDrag); scene.addEventListener('pointercancel', endDrag)
+ scene.addEventListener('pointerleave', () => { hoverB = -1 })
+
+ new ResizeObserver(() => { layout(); matrixDirty = true; sweepDirty = true }).observe(wrap)
+
+ function frame(now) {
+ const dt = Math.min(0.05, Math.max(0.001, (now - lastFrame) / 1000)); lastFrame = now
+ update(dt, now); draw(now); updateDom(now, dt)
+ requestAnimationFrame(frame)
+ }
+ buildPalette(); resetWorld({ teams: [] }); layout()
+ requestAnimationFrame(frame)
+})()
diff --git a/store/agents/jev-firehose/viewer/viewer.mjs b/store/agents/jev-firehose/viewer/viewer.mjs
new file mode 100644
index 000000000..22fde2e49
--- /dev/null
+++ b/store/agents/jev-firehose/viewer/viewer.mjs
@@ -0,0 +1,573 @@
+// Jev Firehose viewer — a loopback server that runs a live map-reduce demo.
+//
+// A seeded generator makes synthetic support-inbox messages with a known true team. Jev (TypeSafe's
+// System One model) triages every message in ONE call that asks five typed questions in parallel:
+// team (choice), urgency (score), spam (noul), needs_human (noul), mood (score). A pool of
+// concurrent calls keeps the stream moving. If the team confidence is under `threshold`, the
+// message is escalated instead of auto-routed. Because the true team is known, accuracy is measured
+// live. The honest difficulty dial is `noise`: how many phrases from a WRONG team get mixed into
+// each message. All data is made up.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. The workspace holds firehose.json (watched).
+
+import { readFileSync, mkdirSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, jev, toWire, PRICE_PER_MTOK } from '../toolchain/jev.mjs'
+import { serveViewer, watchConfig, writeVerdict, mulberry32, clean } from './kit.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const MARKER = 'firehose.json'
+
+export const LIMITS = {
+ teams: [2, 24], phrases: 4, noise: [0, 1], threshold: [0, 1], targetAccuracy: [0.5, 1],
+ ratePerSec: [1, 400], concurrency: [1, 64], batch: [50, 100000], llmSecondsPerItem: [0.1, 120], spamRate: [0, 0.5],
+}
+const BURST_RATE = 400 // messages per second while a burst drains
+const SUMMARY_MS = 3200 // how long the batch summary card stays up
+const FRAME_MS = 100 // SSE frame cadence
+const KEEP_RECORDS = 6000 // full records (text + every answer) kept for the inspector
+
+// A tiny built-in desk, used only if the template file cannot be read.
+const FALLBACK = {
+ title: 'Jev Firehose', desk: 'A made-up help desk. Every message is synthetic.',
+ noise: 0.15, threshold: 0.55, targetAccuracy: 0.95, ratePerSec: 40, concurrency: 8, batch: 2000, llmSecondsPerItem: 2, spamRate: 0.07, seed: 7,
+ teams: [
+ { id: 'billing', description: 'Payment: a card charged twice, an invoice, a refund, a receipt.', phrases: ['my card was charged twice', 'I need a refund to my card', 'please send the invoice and receipt', 'the payment failed but my card was charged'] },
+ { id: 'shipping', description: 'Delivery of a parcel: courier, tracking number, late or lost package.', phrases: ['the parcel is late and tracking is stuck', 'the courier lost my package', 'where is my delivery, the tracking number is dead', 'the package never reached me, the courier says delivered'] },
+ ],
+}
+
+export function loadDefaults() {
+ try {
+ const t = JSON.parse(readFileSync(join(HERE, '../template', MARKER), 'utf8'))
+ if (Array.isArray(t.teams) && t.teams.length >= 2) return { ...FALLBACK, ...t }
+ } catch { /* fall through */ }
+ return FALLBACK
+}
+
+// ---------------------------------------------------------------------------------------------
+// The five questions. Levels and criteria carry plain vocabulary so both live Jev and the offline
+// stand-in can read them.
+// ---------------------------------------------------------------------------------------------
+export const URGENCY = ['no rush, whenever you have time', 'soon, some time this week', 'today, waiting on a reply', 'urgent, blocked right now', 'emergency, losing money every hour']
+export const MOOD = ['calm and polite, says thanks', 'annoyed, frustrated or disappointed', 'furious, angry, finds it unacceptable']
+
+export function buildQuestions(cfg) {
+ return {
+ team: jev.choice(Object.fromEntries(cfg.teams.map((t) => [t.id, t.description])), 'Which team should own this inbox message?'),
+ urgency: jev.score(URGENCY, 'How fast does the sender want an answer?'),
+ spam: jev.noul('Is this spam, a scam or mass promotion?', {
+ true: 'prize, lucky winner, free gift, click a link, crypto, guaranteed profit, cheap offer, seo backlinks, loans, followers',
+ false: 'a genuine customer asking for help with a purchase',
+ }),
+ needs_human: jev.noul('Should a human agent take over this one?', {
+ true: 'asks for a manager or a phone call, threatens a formal complaint, a chargeback or a lawyer',
+ false: 'a routine request that a standard reply can solve',
+ }),
+ mood: jev.score(MOOD, 'What is the mood of the sender?'),
+ }
+}
+
+const OPENERS = [
+ ['Hi, thanks for the help, a calm and polite question.', 'Hello and thanks, staying calm here.', 'Hi team, thanks in advance, a polite request.'],
+ ['I am frustrated and disappointed.', 'Honestly I am annoyed and disappointed.', 'Getting frustrated and annoyed with this.'],
+ ['This is unacceptable, I am furious.', 'I am angry and furious about this.', 'Unacceptable. I am really angry.'],
+]
+const CLOSERS = [
+ ['No rush at all, whenever you have time.', 'Whenever you have time is fine, no rush.'],
+ ['Hoping to hear back soon, some time this week.', 'Some time this week would be good, so soon please.'],
+ ['Please reply today, I am waiting on this.', 'I am waiting on a reply today.'],
+ ['This is urgent, we are blocked right now.', 'Urgent please, I am blocked right now.'],
+ ['This is an emergency, we are losing money every hour.', 'Emergency, we are losing money every hour this goes on.'],
+]
+const HUMAN = ['Please have a manager call me.', 'I want a phone call from a manager.', 'I will file a formal complaint.', 'My lawyer will hear about this.', 'Next step is a chargeback and a formal complaint.']
+const CONNECT = ['Also,', 'By the way,', 'On another note,', 'Separately,', 'One more thing,', 'And while I am here,']
+const SPAM_OPEN = ['Dear friend,', 'Attention!', 'Hello dear,', 'Greetings!']
+const SPAM = [
+ 'congratulations lucky winner, claim your free gift',
+ 'click this link to claim your prize',
+ 'boost your ranking with cheap seo backlinks',
+ 'earn guaranteed crypto profit, invest with us',
+ 'cheap offer, buy followers and get a free gift',
+ 'lucky you, a prize worth millions, click to claim',
+ 'cheap loans approved fast, click the link',
+ 'mass promotion deal: seo backlinks and followers',
+ 'claim your free prize before the offer ends',
+ 'crypto winner alert, click the link for your gift',
+]
+const SPAM_CLOSE = ['Act fast.', 'Do not miss out.', 'Limited places.', 'Last chance.']
+
+const sentence = (s) => { s = String(s).trim(); s = s.charAt(0).toUpperCase() + s.slice(1); return /[.!?]$/.test(s) ? s : s + '.' }
+const pick = (rng, arr) => arr[Math.floor(rng() * arr.length)]
+function pickWeighted(rng, w) { let r = rng() * w.reduce((a, b) => a + b, 0); for (let i = 0; i < w.length; i++) { r -= w[i]; if (r < 0) return i } return w.length - 1 }
+function sample(rng, arr, k) { const pool = arr.slice(), out = []; while (out.length < k && pool.length) out.push(pool.splice(Math.floor(rng() * pool.length), 1)[0]); return out }
+
+/**
+ * One synthetic message. `noise` (0..1) sets how many phrases from ONE wrong team are mixed in:
+ * floor(noise * 3 + rand), capped at the number of true phrases (1 to 3). So 0 adds none, and 1
+ * makes every message an even split between its true team and a wrong one.
+ */
+export function makeMessage(cfg, rng, noise) {
+ const nT = cfg.teams.length
+ const mood = pickWeighted(rng, [0.55, 0.3, 0.15])
+ const urgency = pickWeighted(rng, [0.25, 0.25, 0.22, 0.18, 0.1])
+ const human = rng() < (mood === 2 ? 0.45 : 0.12)
+ const parts = []
+ if (rng() < cfg.spamRate) {
+ parts.push({ kind: 'open', text: pick(rng, SPAM_OPEN) })
+ for (const p of sample(rng, SPAM, 2 + Math.floor(rng() * 2))) parts.push({ kind: 'spam', text: sentence(p) })
+ parts.push({ kind: 'close', text: pick(rng, SPAM_CLOSE) })
+ return { truth: nT, distractor: -1, nTrue: 0, nNoise: 0, urgency: 0, mood: 0, human: false, spam: true, parts, text: parts.map((p) => p.text).join(' ') }
+ }
+ const truth = pickWeighted(rng, cfg.teams.map((t) => t.weight))
+ const nTrue = 1 + pickWeighted(rng, [0.25, 0.45, 0.3])
+ // Never more wrong-team phrases than true ones: the message is always mostly about its true team.
+ const want = Math.min(nTrue, Math.floor(noise * 3 + rng()))
+ let distractor = -1
+ if (nT > 1) { distractor = Math.floor(rng() * (nT - 1)); if (distractor >= truth) distractor++ }
+ const own = sample(rng, cfg.teams[truth].phrases, nTrue).map((p) => ({ kind: 'true', team: truth, text: sentence(p) }))
+ const wrong = want && distractor >= 0 ? sample(rng, cfg.teams[distractor].phrases, want).map((p) => ({ kind: 'noise', team: distractor, text: `${pick(rng, CONNECT)} ${p}.` })) : []
+ // The first phrase is always a true one; the rest are shuffled together.
+ const rest = own.slice(1).concat(wrong)
+ for (let i = rest.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [rest[i], rest[j]] = [rest[j], rest[i]] }
+ parts.push({ kind: 'open', text: pick(rng, OPENERS[mood]) }, own[0], ...rest, { kind: 'close', text: pick(rng, CLOSERS[urgency]) })
+ if (human) parts.push({ kind: 'human', text: pick(rng, HUMAN) })
+ return { truth, distractor: wrong.length ? distractor : -1, nTrue: own.length, nNoise: wrong.length, urgency, mood, human, spam: false, parts, text: parts.map((p) => p.text).join(' ') }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Config: clamp everything into range and keep going. Problems become warnings in the pane.
+// ---------------------------------------------------------------------------------------------
+export function sanitize(raw, defaults = loadDefaults()) {
+ const warnings = []
+ const src = raw && typeof raw === 'object' ? raw : {}
+ const num = (key, [lo, hi], int = false) => {
+ let v = src[key]
+ if (typeof v !== 'number' || !Number.isFinite(v)) { if (v !== undefined) warnings.push(`${key} should be a number, using ${defaults[key]}`); v = defaults[key] }
+ if (v < lo || v > hi) { warnings.push(`${key} ${v} is outside ${lo}..${hi}, clamped`); v = Math.min(hi, Math.max(lo, v)) }
+ return int ? Math.round(v) : v
+ }
+ const seen = new Set()
+ let teams = []
+ for (const t of Array.isArray(src.teams) ? src.teams : []) {
+ const id = String(t?.id ?? '').trim().slice(0, 28)
+ const phrases = (Array.isArray(t?.phrases) ? t.phrases : []).map((p) => String(p ?? '').trim()).filter(Boolean).slice(0, 60)
+ if (!id || seen.has(id)) { warnings.push(`a team has a missing or repeated id (${id || 'empty'}), skipped`); continue }
+ if (!phrases.length) { warnings.push(`team ${id} has no phrases, skipped`); continue }
+ if (phrases.length < LIMITS.phrases) warnings.push(`team ${id} has ${phrases.length} phrases, give it at least ${LIMITS.phrases}`)
+ const description = String(t.description ?? '').trim().slice(0, 300)
+ if (!description) warnings.push(`team ${id} has no description, Jev will guess from the name`)
+ const weight = typeof t.weight === 'number' && t.weight > 0 ? Math.min(10, Math.max(0.1, t.weight)) : 1
+ seen.add(id)
+ teams.push({ id, description: description || id, phrases, weight })
+ }
+ if (teams.length > LIMITS.teams[1]) { warnings.push(`${teams.length} teams is over ${LIMITS.teams[1]}, extra teams dropped`); teams = teams.slice(0, LIMITS.teams[1]) }
+ if (teams.length < LIMITS.teams[0]) { warnings.push(`need at least ${LIMITS.teams[0]} usable teams, showing the starter desk`); teams = sanitize({ teams: defaults.teams }, FALLBACK).cfg.teams }
+ const cfg = {
+ title: String(src.title ?? defaults.title).slice(0, 80),
+ desk: String(src.desk ?? defaults.desk).slice(0, 200),
+ noise: num('noise', LIMITS.noise), threshold: num('threshold', LIMITS.threshold), targetAccuracy: num('targetAccuracy', LIMITS.targetAccuracy),
+ ratePerSec: num('ratePerSec', LIMITS.ratePerSec), concurrency: num('concurrency', LIMITS.concurrency, true), batch: num('batch', LIMITS.batch, true),
+ llmSecondsPerItem: num('llmSecondsPerItem', LIMITS.llmSecondsPerItem), spamRate: num('spamRate', LIMITS.spamRate),
+ seed: Number.isFinite(src.seed) ? Math.floor(src.seed) : defaults.seed, teams,
+ }
+ return { cfg, warnings }
+}
+
+const round = (v, d = 3) => Math.round(v * 10 ** d) / 10 ** d
+/** The most likely level of a score answer (falls back to the rounded score). */
+export function levelOf(a, max) {
+ const e = Object.entries(a?.probabilities ?? {})
+ const lv = e.length ? Number(e.reduce((m, x) => (x[1] > m[1] ? x : m))[0]) : Math.round(Number(a?.score ?? 0))
+ return Math.max(0, Math.min(max, Number.isFinite(lv) ? lv : 0))
+}
+function slimAnswer(a) {
+ if (!a || typeof a !== 'object') return a
+ const out = { type: a.type }
+ if (a.type === 'noul') out.noul = round(Number(a.noul ?? 0.5))
+ else {
+ if (a.type === 'choice') out.choice = a.choice; else { out.score = round(Number(a.score ?? 0)); out.legend = a.legend }
+ out.confidence = round(Number(a.confidence ?? 0))
+ out.probabilities = Object.fromEntries(Object.entries(a.probabilities ?? {}).map(([k, v]) => [k, round(Number(v))]))
+ }
+ return out
+}
+
+export async function startFirehoseViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+ const file = join(workspace, MARKER)
+ const DEFAULTS = loadDefaults()
+
+ // Every piece of mutable state is declared here, BEFORE the first function call that can touch
+ // it (no temporal-dead-zone surprises inside a try/catch).
+ let cfg = sanitize(DEFAULTS, DEFAULTS).cfg
+ let warnings = []
+ let cfgError = null
+ let cfgRev = 0
+ let lastText = null
+ let override = { noise: null, threshold: null }
+ let questions = buildQuestions(cfg)
+ let wireLen = JSON.stringify(toWire(questions)).length
+ let running = true, stopped = false
+ let phase = 'run', summary = null, summaryTimer = null
+ let batchNo = 0, batchRev = 0, rng = mulberry32(1)
+ let N = 0, launched = 0, inflight = 0, credit = 0, burstLeft = 0, pumping = false
+ let cap = 0, T = null, C = null, Q = null, S = null, D = null, M = null, U = null
+ let records = new Map()
+ let counts = [], rights = [], confusion = []
+ let urgent = 0, humans = 0, angry = 0
+ let tokens = 0, costUsd = 0, elapsedMs = 0, lastPumpAt = performance.now()
+ let doneTimes = []
+ let sentN = 0, lastSampleAt = 0, lastVerdictAt = 0, verdictDirty = true
+ let jevError = null, jevErrors = 0, backoffUntil = 0
+ let client = 'mock', lastLatencyMs = 0
+ let totals = { messages: 0, costUsd: 0, batches: 0, elapsedMs: 0 }
+ let lastBatch = null
+ let server = null
+ let pumpTimer = null, frameTimer = null, pollTimer = null
+ const waiters = []
+
+ const nT = () => cfg.teams.length
+ const thr = () => override.threshold ?? cfg.threshold
+ const noise = () => override.noise ?? cfg.noise
+ const SPAMB = () => nT() // bucket index of the spam bin (also the truth index of spam)
+ const ESCB = () => nT() + 1 // bucket index of the escalate lane
+
+ function bucketOf(i, threshold = thr()) {
+ if (S[i] >= 128) return nT()
+ return Q[i] < Math.round(threshold * 1000) ? nT() + 1 : C[i]
+ }
+
+ function alloc() {
+ cap = cfg.batch + 8
+ T = new Uint8Array(cap); C = new Uint8Array(cap); Q = new Uint16Array(cap); S = new Uint8Array(cap)
+ D = new Uint8Array(cap); M = new Uint8Array(cap); U = new Uint8Array(cap)
+ }
+
+ function clearStats() {
+ const n = nT()
+ counts = new Array(n + 2).fill(0); rights = new Array(n + 2).fill(0)
+ confusion = Array.from({ length: n + 1 }, () => new Array(n + 2).fill(0))
+ }
+ function addStat(i, sign) {
+ const b = bucketOf(i)
+ counts[b] += sign
+ if (b === T[i]) rights[b] += sign
+ confusion[T[i]][b] += sign
+ }
+ function recount() { clearStats(); for (let i = 0; i < N; i++) addStat(i, 1) }
+
+ function stats() {
+ const esc = counts[ESCB()] ?? 0
+ const routed = N - esc
+ let right = 0
+ for (let b = 0; b <= nT(); b++) right += rights[b] ?? 0
+ let rN = 0, rRight = 0, rEsc = 0
+ for (let i = Math.max(0, N - 300); i < N; i++) { const b = bucketOf(i); rN++; if (b === ESCB()) rEsc++; else if (b === T[i]) rRight++ }
+ return {
+ done: N, batch: cfg.batch, routed, right, escalated: esc, spamBin: counts[SPAMB()] ?? 0,
+ accuracy: routed ? right / routed : null, escalatedPct: N ? esc / N : 0,
+ recentAccuracy: rN - rEsc ? rRight / (rN - rEsc) : null, recentEscalatedPct: rN ? rEsc / rN : 0,
+ bins: counts.slice(), binRight: rights.slice(), answers: N * 5, urgent, humans, angry,
+ }
+ }
+
+ /** Accuracy and escalation share at every threshold 0.00..1.00, from the batch so far. */
+ function sweep() {
+ const cnt = new Array(101).fill(0), ok = new Array(101).fill(0)
+ let spamRouted = 0, spamRight = 0
+ for (let i = 0; i < N; i++) {
+ if (S[i] >= 128) { spamRouted++; if (T[i] === nT()) spamRight++; continue }
+ const b = Math.min(100, Math.floor(Q[i] / 10)); cnt[b]++; if (C[i] === T[i]) ok[b]++
+ }
+ const out = new Array(101)
+ let routed = spamRouted, right = spamRight
+ for (let j = 100; j >= 0; j--) { routed += cnt[j]; right += ok[j]; out[j] = { threshold: j / 100, accuracy: routed ? right / routed : null, escalatedPct: N ? (N - routed) / N : 0 } }
+ return out
+ }
+ function suggestThreshold() {
+ if (N < 50) return null
+ return sweep().find((p) => p.accuracy != null && p.accuracy >= cfg.targetAccuracy) ?? null
+ }
+
+ function startBatch(first = false) {
+ clearTimeout(summaryTimer)
+ if (!first) batchNo++
+ batchRev++
+ rng = mulberry32((cfg.seed | 0) + batchNo * 7919 + 1)
+ N = 0; launched = 0; credit = 0; burstLeft = 0; sentN = 0
+ urgent = 0; humans = 0; angry = 0
+ tokens = 0; costUsd = 0; elapsedMs = 0; doneTimes = []
+ records = new Map()
+ phase = 'run'; summary = null
+ alloc(); clearStats()
+ lastPumpAt = performance.now()
+ verdictDirty = true
+ }
+
+ function applyConfig(raw) {
+ const s = sanitize(raw, DEFAULTS)
+ cfg = s.cfg; warnings = s.warnings; cfgError = null; cfgRev++
+ override = { noise: null, threshold: null } // a file edit always wins over the pane sliders
+ questions = buildQuestions(cfg)
+ wireLen = JSON.stringify(toWire(questions)).length
+ batchNo = 0
+ totals = { messages: 0, costUsd: 0, batches: 0, elapsedMs: 0 }
+ lastBatch = null
+ startBatch(true)
+ }
+
+ function reload() {
+ if (stopped) return
+ let text
+ try { text = readFileSync(file, 'utf8') } catch { return } // missing file: the last good config stands
+ if (text === lastText) return
+ lastText = text
+ let raw
+ try { raw = JSON.parse(text) } catch (e) { cfgError = clean(`${MARKER}: ${e.message}`); verdictDirty = true; pushFull(); return }
+ applyConfig({ ...DEFAULTS, ...raw })
+ pushFull()
+ }
+
+ function record(msg, res, rev) {
+ if (rev !== batchRev || N >= cap) return // the config changed while this call was in flight
+ const a = res.answers
+ const i = N
+ const ci = cfg.teams.findIndex((t) => t.id === a.team?.choice)
+ T[i] = msg.truth; C[i] = ci < 0 ? 0 : ci
+ Q[i] = Math.max(0, Math.min(1000, Math.round(Number(a.team?.confidence ?? 0) * 1000)))
+ S[i] = Math.max(0, Math.min(255, Math.round(Number(a.spam?.noul ?? 0) * 255)))
+ D[i] = msg.distractor < 0 ? 255 : msg.distractor
+ M[i] = msg.nTrue | (msg.nNoise << 2)
+ const urg = levelOf(a.urgency, 4)
+ const hum = Number(a.needs_human?.noul ?? 0) >= 0.5 ? 1 : 0
+ const md = levelOf(a.mood, 2)
+ U[i] = urg | (hum << 3) | (md << 4)
+ if (urg >= 3) urgent++
+ if (hum) humans++
+ if (md >= 2) angry++
+ N++
+ addStat(i, 1)
+ const tok = Number(res.usage?.input_tokens) > 0 ? Number(res.usage.input_tokens) : Math.ceil((JSON.stringify(msg.text).length + wireLen) / 4)
+ tokens += tok
+ costUsd = (tokens * PRICE_PER_MTOK) / 1e6
+ client = res.client; lastLatencyMs = res.latencyMs
+ records.set(i, {
+ id: i, batchNo, text: msg.text, parts: msg.parts, truth: msg.truth, distractor: msg.distractor, nTrue: msg.nTrue, nNoise: msg.nNoise,
+ truthUrgency: msg.urgency, truthMood: msg.mood, truthHuman: msg.human, latencyMs: round(res.latencyMs, 2), tokens: tok,
+ answers: Object.fromEntries(Object.entries(a).map(([k, v]) => [k, slimAnswer(v)])),
+ })
+ if (records.size > KEEP_RECORDS) records.delete(i - KEEP_RECORDS)
+ const now = performance.now()
+ doneTimes.push(now)
+ while (doneTimes.length && now - doneTimes[0] > 2000) doneTimes.shift()
+ verdictDirty = true
+ if (N >= cfg.batch) finishBatch()
+ }
+
+ function viewRecord(i) {
+ const r = records.get(i)
+ if (!r || i >= N) return null
+ const b = bucketOf(i)
+ return { ...r, choice: C[i], confidence: Q[i] / 1000, bucket: b, right: b === ESCB() ? null : b === T[i], threshold: thr() }
+ }
+
+ function finishBatch() {
+ const s = stats()
+ summary = {
+ batchNo: batchNo + 1, messages: N, elapsedMs: Math.round(elapsedMs), costUsd, tokens, accuracy: s.accuracy, escalatedPct: s.escalatedPct,
+ routed: s.routed, right: s.right, escalated: s.escalated, noise: noise(), threshold: thr(), answers: N * 5,
+ llmWouldBeOn: Math.min(N, Math.floor(elapsedMs / 1000 / cfg.llmSecondsPerItem) + 1), suggested: suggestThreshold(),
+ }
+ lastBatch = summary
+ totals = { messages: totals.messages + N, costUsd: totals.costUsd + costUsd, batches: totals.batches + 1, elapsedMs: totals.elapsedMs + elapsedMs }
+ phase = 'summary'
+ verdictDirty = true
+ clearTimeout(summaryTimer)
+ if (running) summaryTimer = setTimeout(nextBatch, SUMMARY_MS)
+ }
+ function nextBatch() {
+ if (stopped || phase !== 'summary') return
+ startBatch()
+ pushFull()
+ }
+
+ async function decideOne() {
+ if (stopped) return false
+ if (phase === 'summary') { startBatch(); pushFull() }
+ if (launched >= cfg.batch) return false
+ const rev = batchRev
+ const idx = launched++
+ const msg = makeMessage(cfg, rng, noise())
+ inflight++
+ try {
+ const res = await evaluate({ state: msg.text, questions, salt: (cfg.seed | 0) + batchNo * 7919 + idx, model: process.env.JEV_MODEL || 'jev-latest' })
+ jevError = null
+ record(msg, res, rev)
+ return true
+ } catch (e) {
+ jevError = clean(e?.message ?? e); jevErrors++
+ if (rev === batchRev) launched-- // this message was never triaged; the batch still completes
+ backoffUntil = performance.now() + 1000
+ verdictDirty = true
+ return false
+ } finally {
+ inflight--
+ const w = waiters.shift(); if (w) w()
+ }
+ }
+
+ async function pump() {
+ if (stopped || pumping) return
+ pumping = true
+ try {
+ const now = performance.now()
+ const dt = Math.min(250, now - lastPumpAt)
+ lastPumpAt = now
+ if (!running || phase !== 'run' || now < backoffUntil) return
+ elapsedMs += dt
+ credit = Math.min(credit + (dt / 1000) * (burstLeft > 0 ? Math.max(BURST_RATE, cfg.ratePerSec) : cfg.ratePerSec), BURST_RATE / 2)
+ while (credit >= 1 && running && phase === 'run' && launched < cfg.batch && !stopped && performance.now() >= backoffUntil) {
+ if (inflight >= cfg.concurrency) await new Promise((r) => waiters.push(r))
+ else { credit--; if (burstLeft > 0) burstLeft--; decideOne() }
+ }
+ if (launched >= cfg.batch) burstLeft = 0
+ } finally { pumping = false }
+ }
+
+ // ------------------------------------------------------------------------------------------
+ // What the pane gets. `full` on connect and on any reset; small `frame`s ten times a second.
+ // ------------------------------------------------------------------------------------------
+ const b64 = (arr) => Buffer.from(arr.buffer, arr.byteOffset, N * arr.BYTES_PER_ELEMENT).toString('base64')
+ function live() {
+ const now = performance.now()
+ while (doneTimes.length && now - doneTimes[0] > 2000) doneTimes.shift()
+ return {
+ batchNo: batchNo + 1, rev: batchRev, n: N, elapsedMs: Math.round(elapsedMs), costUsd, tokens,
+ mps: doneTimes.length > 1 ? doneTimes.length / Math.max(0.25, (now - doneTimes[0]) / 1000) : 0,
+ inflight, running, phase, burstLeft, threshold: thr(), noise: noise(), overrides: { noise: override.noise != null, threshold: override.threshold != null },
+ client, lastLatencyMs: round(lastLatencyMs, 2), jevError, jevErrors,
+ }
+ }
+ function full() {
+ return {
+ kind: 'full', ...live(), title: cfg.title, desk: cfg.desk, error: cfgError, warnings,
+ config: { noise: cfg.noise, threshold: cfg.threshold, targetAccuracy: cfg.targetAccuracy, ratePerSec: cfg.ratePerSec, concurrency: cfg.concurrency, batch: cfg.batch, llmSecondsPerItem: cfg.llmSecondsPerItem, spamRate: cfg.spamRate, seed: cfg.seed },
+ teams: cfg.teams.map((t) => ({ id: t.id, description: t.description, phrases: t.phrases.length })),
+ questions: Object.keys(questions), urgencyLegend: URGENCY, moodLegend: MOOD,
+ stats: stats(), suggested: suggestThreshold(), summary, lastBatch, totals, pricePerMTok: PRICE_PER_MTOK,
+ last: N ? viewRecord(N - 1) : null,
+ hist: N ? { t: b64(T), c: b64(C), q: b64(Q), s: b64(S), d: b64(D), m: b64(M), u: b64(U) } : null,
+ }
+ }
+ function pushFull() { sentN = N; server?.broadcast(full(), 'state') }
+ function pushFrame(force = false) {
+ if (!server || (!force && !server.clients.size)) { sentN = N; return }
+ const items = []
+ for (let i = sentN; i < N; i++) items.push([T[i], C[i], Q[i], S[i], D[i], M[i], U[i]])
+ const f = { kind: 'frame', ...live(), from: sentN, items, error: cfgError }
+ sentN = N
+ const now = performance.now()
+ if (N && now - lastSampleAt > 650) { lastSampleAt = now; f.sample = viewRecord(N - 1) }
+ if (phase === 'summary') f.summary = summary
+ server.broadcast(f, 'frame')
+ }
+
+ function verdict() {
+ const s = stats()
+ const pct = (v) => (v == null ? 'n/a' : (v * 100).toFixed(1) + '%')
+ const sug = suggestThreshold()
+ const findings = []
+ if (cfgError) findings.push({ severity: 'error', kind: 'config', message: cfgError })
+ for (const w of warnings) findings.push({ severity: 'warning', kind: 'config', message: w })
+ if (jevError) findings.push({ severity: 'error', kind: 'jev', message: jevError })
+ if (lastBatch) findings.push({ severity: 'info', kind: 'batch', message: `Batch ${lastBatch.batchNo}: ${lastBatch.messages} synthetic messages in ${(lastBatch.elapsedMs / 1000).toFixed(1)}s for $${lastBatch.costUsd.toFixed(4)}. ${pct(lastBatch.accuracy)} of auto-routed were right, ${pct(lastBatch.escalatedPct)} escalated (noise ${lastBatch.noise}, threshold ${lastBatch.threshold}).` })
+ if (N >= 50) {
+ findings.push({ severity: s.accuracy != null && s.accuracy < cfg.targetAccuracy ? 'warning' : 'info', kind: 'routing', message: `Now: ${pct(s.accuracy)} right on ${s.routed} auto-routed, ${pct(s.escalatedPct)} escalated, at noise ${round(noise(), 2)} and threshold ${round(thr(), 2)}. Target is ${pct(cfg.targetAccuracy)}.` })
+ findings.push(sug
+ ? { severity: 'info', kind: 'threshold', message: `Lowest threshold that meets the target on this batch: ${sug.threshold.toFixed(2)} (${pct(sug.accuracy)} right, ${pct(sug.escalatedPct)} escalated).` }
+ : { severity: 'warning', kind: 'threshold', message: `No threshold reaches the ${pct(cfg.targetAccuracy)} target on this batch. The noise is too high or the team descriptions overlap.` })
+ }
+ return {
+ ready: !cfgError && (N > 0 || totals.messages > 0),
+ summary: cfgError ? `${cfg.title} needs a fix in ${MARKER}` : `${cfg.title} · batch ${batchNo + 1} · ${N} of ${cfg.batch} synthetic messages · ${pct(s.accuracy)} right · ${pct(s.escalatedPct)} escalated · $${costUsd.toFixed(4)}`,
+ findings, artifact: MARKER,
+ phases: [
+ { id: 'stream', name: 'Streaming', state: N === 0 ? 'active' : 'done' },
+ { id: 'route', name: 'Routing', state: N === 0 ? 'pending' : phase === 'run' ? 'active' : 'done' },
+ { id: 'summary', name: 'Batch summary', state: phase === 'summary' ? 'active' : totals.batches ? 'done' : 'pending' },
+ ],
+ }
+ }
+ function flushVerdict(force = false) {
+ const now = performance.now()
+ if (!force && (!verdictDirty || now - lastVerdictAt < 1000)) return
+ lastVerdictAt = now; verdictDirty = false
+ try { writeVerdict(workspace, verdict()) } catch { /* a read-only workspace must not stop the demo */ }
+ }
+
+ async function control(cmd, body) {
+ if (cmd === 'pause') { running = false; clearTimeout(summaryTimer) }
+ else if (cmd === 'start') { if (!running) { running = true; lastPumpAt = performance.now(); if (phase === 'summary') summaryTimer = setTimeout(nextBatch, 900) } }
+ else if (cmd === 'reset') { batchNo = 0; totals = { messages: 0, costUsd: 0, batches: 0, elapsedMs: 0 }; lastBatch = null; startBatch(true); pushFull(); flushVerdict(true); return { stats: stats() } }
+ else if (cmd === 'tick') {
+ const n = Math.max(1, Math.min(5000, Math.floor(Number(body.n) || 1)))
+ let did = 0
+ for (let k = 0; k < n; k++) if (await decideOne()) did++
+ pushFrame(); flushVerdict(true)
+ return { did, stats: stats(), last: N ? viewRecord(N - 1) : null }
+ } else if (cmd === 'threshold' || cmd === 'noise') {
+ const v = Number(body.value)
+ if (Number.isFinite(v)) { override[cmd] = Math.min(1, Math.max(0, v)); if (cmd === 'threshold') recount(); verdictDirty = true }
+ pushFrame(true)
+ return { threshold: thr(), noise: noise(), stats: stats() }
+ } else if (cmd === 'clearOverrides') { override = { noise: null, threshold: null }; recount(); pushFrame(true); return { threshold: thr(), noise: noise(), stats: stats() } }
+ else if (cmd === 'burst') { burstLeft = Math.min(5000, burstLeft + Math.max(1, Math.min(2000, Math.floor(Number(body.n) || 500)))); if (phase === 'summary' && running) nextBatch(); return { burstLeft } }
+ else if (cmd === 'inspect') { return { record: viewRecord(Math.floor(Number(body.id))) } }
+ else if (cmd === 'bin') {
+ const b = Math.floor(Number(body.bucket)), list = []
+ for (let i = N - 1; i >= 0 && i >= N - KEEP_RECORDS && list.length < 6; i--) if (bucketOf(i) === b) { const r = records.get(i); if (r) list.push({ id: i, text: r.parts.filter((x) => x.kind !== 'open').map((x) => x.text).join(' ').slice(0, 120), truth: T[i], confidence: Q[i] / 1000, right: b === ESCB() ? null : b === T[i] }) }
+ return { bucket: b, list }
+ } else if (cmd === 'sweep') return { sweep: sweep(), suggested: suggestThreshold() }
+ else return { unknown: true }
+ pushFrame(true); flushVerdict(true)
+ return { running, phase }
+ }
+
+ // Boot. The kit watcher gives a fast trigger; the one-second poll also catches an editor that
+ // replaces the file (write + rename), which a plain file watch can miss.
+ const watcher = watchConfig(file, DEFAULTS, () => reload())
+ try { lastText = readFileSync(file, 'utf8') } catch { lastText = null }
+ cfgError = watcher.error()
+ applyConfig(cfgError ? DEFAULTS : watcher.get())
+ if (watcher.error()) cfgError = watcher.error()
+
+ server = await serveViewer({ here: HERE, port, state: full, control })
+ pumpTimer = setInterval(pump, 25)
+ frameTimer = setInterval(() => { if (N !== sentN || running) pushFrame(); flushVerdict() }, FRAME_MS)
+ pollTimer = setInterval(reload, 1000)
+ flushVerdict(true)
+
+ return {
+ url: server.url,
+ async close() {
+ stopped = true
+ clearInterval(pumpTimer); clearInterval(frameTimer); clearInterval(pollTimer); clearTimeout(summaryTimer)
+ for (const w of waiters.splice(0)) w()
+ watcher.close()
+ await server.close()
+ },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startFirehoseViewer({ workspace, port })
+ console.log(`Jev Firehose listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-fps/.gitignore b/store/agents/jev-fps/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-fps/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-fps/AGENTS.md b/store/agents/jev-fps/AGENTS.md
new file mode 100644
index 000000000..00f73e731
--- /dev/null
+++ b/store/agents/jev-fps/AGENTS.md
@@ -0,0 +1,75 @@
+# Jev FPS in OpenHarness
+
+On the left is a first-person arena shooter that **Jev plays by itself**. Jev is TypeSafe's System
+One model. It never sees pixels. About nine times a second the fight is written out as a few lines
+of text and Jev answers four typed questions in one call: `turn`, `move`, `fire` and `threat`. The
+pane shows the 3D view, a minimap, Jev's answers as lit keys, and the exact text Jev reads.
+
+On the right, you edit `level.json`. This is the ONLY file you edit. The viewer watches it and
+restarts the fight at wave 1 the moment you save.
+
+## The level file
+
+```jsonc
+{
+ "title": "Jev FPS",
+ "description": "One line about this level.",
+ "map": [ // 8 to 40 rows, every row the same width (8 to 64)
+ "################",
+ "#P.....#.......#", // P the marine's start (exactly one)
+ "#......#...D...#", // D a demon spawn (at least one, reachable from P)
+ "#..%%..=..M..A.#", // M medkit A ammo . floor
+ "################" // # stone wall % tech wall = hell brick (border must be wall)
+ ],
+ "tickMs": 110, // one Jev decision per tick. 60 to 1000.
+ "demons": 4, // alive at once in wave 1 (+1 each wave). 1 to 24.
+ "demonSpeed": 1.2, // tiles per second in wave 1 (+12% each wave). 0.2 to 6. THE DIAL.
+ "demonHealth": 60, // a shot does 34. 10 to 400.
+ "demonDamage": 9, // per bite, about two bites a second. 1 to 60.
+ "kills": 12, // kills to clear wave 1 (+4 each wave). 1 to 200.
+ "ammo": 60, // starting ammo. 0 to 99.
+ "seed": 7,
+ "style": "How Jev should fight, in plain words. It is the first line of the text Jev reads."
+}
+```
+
+## Your job
+
+Design a level that is fun to watch, then find out where Jev breaks.
+
+- **Draw the map.** Rooms, corridors, pillars for cover, a boss room. Use `%` and `=` walls to give
+ areas their own look. Put spawns where demons arrive from more than one side. Put medkits and ammo
+ where reaching them is a risk.
+- **Set the pace.** `demonSpeed` and `demons` are the difficulty. Slow and few: Jev clears wave
+ after wave. Fast and many: it gets surrounded. The person can also change speed live with the
+ slider in the pane.
+- **Write the style line.** "Keep your back to a wall and let them come" plays differently from
+ "hunt them down". With a real key, Jev reads it on every decision.
+- **Report what you see.** Read `.harness/verdict.json` for wave, kills, deaths, best wave and shot
+ accuracy. Say at which speed Jev stops clearing waves. If it never dies the level is dull. If it
+ dies in wave 1 every time it is unfair. Either is a finding to report, not something to hide.
+
+Do NOT just ship the template. Every level should be its own arena with a pace you chose on purpose.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. It checks the map shape, the border, that
+there is one `P`, that every `D` can be reached, and every number's range.
+
+## Rules
+
+- Edit only `level.json`. Keep it valid JSON. A bad edit does not crash the fight. The pane shows
+ the error and keeps running on the last good level.
+- Never edit `.harness/verdict.json`. The viewer writes it.
+- The viewer is already running in the left pane. Never propose opening a browser, changing ports
+ or running a second server.
+- You can ask Jev yourself through `toolchain/jev.mjs` (`evaluate`, and the `jev.choice`,
+ `jev.noul`, `jev.score` builders), for example to see how it reads one situation.
+- Without `TYPESAFE_API_KEY` the harness runs on a deterministic offline stand-in, and the pane
+ says `MOCK`. The stand-in reads the same text and answers the same questions. It is there so the
+ demo runs anywhere. It is not Jev's judgement, so do not describe its play as Jev's.
+- This is a demo. The arena and the demons are made up. Do not present the numbers as a benchmark.
+
+## Definition of done
+
+- `level.json` parses and passes `toolchain/check.mjs`.
+- The pane shows your map, and the fight runs without an error banner.
+- You told the person what pace you chose, how far Jev gets, and where it starts to fail.
diff --git a/store/agents/jev-fps/LICENSE b/store/agents/jev-fps/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-fps/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-fps/README.md b/store/agents/jev-fps/README.md
new file mode 100644
index 000000000..aea838adf
--- /dev/null
+++ b/store/agents/jev-fps/README.md
@@ -0,0 +1,89 @@
+# Jev FPS
+
+**Jev plays a first-person arena shooter, live.** Jev is TypeSafe's System One model. It never sees
+a pixel and never writes a word. About nine times a second the marine's situation is written out as
+a few lines of text: health and ammo, which demons are in sight and at what bearing, what it can
+hear behind it, how far the walls are, and the automap route. Jev answers four typed questions in
+**one call**:
+
+| question | type | what it drives |
+|---|---|---|
+| `turn` | choice of 7 | snap, turn or nudge left or right, or keep facing ahead |
+| `move` | choice of 5 | forward, back, strafe left, strafe right, hold |
+| `fire` | noul (yes/no) | pull the trigger this instant |
+| `threat` | score, 4 levels | how dangerous this instant is (shown on the HUD) |
+
+The pane renders the fight as a textured 3D view at 60 fps, with a minimap, Jev's answers shown as
+lit keys filled by their probability, the exact text Jev reads, and a live panel with decisions per
+second, latency, tokens and cost.
+
+This is a harness for OpenHarness. The agent on the right edits `level.json`. The viewer on the left
+runs the arena and asks Jev for every decision.
+
+## Play with it
+
+- **Click the minimap** to spawn a demon, drop a medkit or drop ammo where you clicked.
+- **Swarm +5** throws five demons at Jev at once.
+- **Demon speed** slider changes the pace live.
+- **Grab the controls**: hold `W A S D` to move, `←` `→` to turn (`Shift` for a hard turn), `Space`
+ to fire. While you hold a key you drive. Jev keeps answering, so the lit keys show what it would
+ have done. Let go and Jev takes over again.
+- Pause, Step (one decision at a time) and Reset.
+
+## The honest dial
+
+Each cleared wave adds one demon and makes them 12% faster. Demons weave as they charge, so the
+faster they are, the faster they cross the crosshair. A marine that decides about nine times a
+second can only turn so far per decision, so at some speed it starts to miss, gets surrounded and
+dies. Then the run restarts at wave 1. Nothing is random on purpose: the limit is the decision rate.
+
+Measured with the offline stand-in over 6,000 decisions:
+
+| `demonSpeed` | deaths | best wave reached |
+|---|---|---|
+| 0.6 | 1 | 11 |
+| 1.2 (default) | 2 | 9 |
+| 2.4 | 3 | 7 |
+| 4.0 | 9 | 4 |
+
+## Anatomy
+
+```
+jev-fps/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent how to design a level and what to report
+ skills/fps/SKILL.md # the level-design and verification craft
+ template/level.json # the starter level (ASCII map + pace)
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API, or an offline stand-in)
+ check.mjs # validates level.json
+ viewer.sh setup.sh doctor.sh init-workspace.sh
+ viewer/
+ viewer.mjs # loopback server + the decision loop
+ sim.mjs # the arena: map, demons, shots, pickups, waves
+ mock.mjs # the offline stand-in's reflexes (reads only the state text)
+ kit.mjs # loopback-only HTTP/SSE server helpers
+ studio.js # the software raycaster and HUD
+ jev-hud.js # the "Jev live mind" panel
+ test/viewer.test.mjs
+```
+
+## Jev, honestly
+
+With `TYPESAFE_API_KEY` set, every decision is a real call to `POST /v1/systemone`. Without a key
+the harness runs on a deterministic local stand-in that reads the same state text and answers the
+same questions, so the demo works offline. The pane badges that mode `MOCK`. The stand-in exercises
+the plumbing. It is not Jev's judgement.
+
+The arena, the demons and the numbers are made up. This shows decision rate and calibration on a
+synthetic game. It is not a benchmark of any real game or product.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API. It contains no TypeSafe code.
+- The idea of a System One model playing a shooter from structured game state comes from TypeSafe's
+ own launch demo and the community projects that followed. This harness is an independent,
+ from-scratch arena. It uses no code or assets from any commercial game.
+- **OpenHarness** (Autonomous) is MIT-licensed. This wrapper is MIT too (see `LICENSE`).
+- Built by Autonomous for the OpenHarness store.
diff --git a/store/agents/jev-fps/THIRD_PARTY_NOTICES.md b/store/agents/jev-fps/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-fps/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-fps/harness.json b/store/agents/jev-fps/harness.json
new file mode 100644
index 000000000..53e584be8
--- /dev/null
+++ b/store/agents/jev-fps/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-fps",
+ "name": "Jev FPS",
+ "category": "Games",
+ "author": "Autonomous",
+ "description": "Jev plays a first-person arena shooter, live. About nine times a second the fight is written out as text and Jev, TypeSafe's System One model, answers four typed questions in one call: turn, move, fire and threat. Redraw the map, speed up the demons, or grab the controls yourself.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "level.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-fps/skills/fps/SKILL.md b/store/agents/jev-fps/skills/fps/SKILL.md
new file mode 100644
index 000000000..a351cfa7f
--- /dev/null
+++ b/store/agents/jev-fps/skills/fps/SKILL.md
@@ -0,0 +1,62 @@
+---
+name: fps
+description: Design an arena level for Jev FPS (the ASCII map, the demons, the pace), then measure where Jev's decision rate stops being enough.
+---
+
+# Craft: Jev FPS levels
+
+Jev FPS is a first-person arena shooter that Jev plays by itself, one typed decision at a time. You
+shape the arena in `level.json`. The craft is a map that reads well in 3D and a pace that shows the
+real limit: about nine decisions a second.
+
+## What Jev is asked, every tick
+
+One call, four questions, all answered in parallel from the same state text:
+
+```
+turn choice LEFT_HARD LEFT LEFT_FINE AHEAD RIGHT_FINE RIGHT RIGHT_HARD
+move choice FORWARD BACK STRAFE_LEFT STRAFE_RIGHT HOLD
+fire noul "Fire now? Yes only when a demon is in your crosshair and you have ammo."
+threat score calm < watchful < pressed < critical
+```
+
+The state text is what a player could know: health, ammo, wall distances, each demon in sight with
+its bearing and distance, the nearest demon it can hear but not see, the automap route, and whether
+the crosshair is on a demon. The pane shows this text live under "What Jev reads".
+
+## Drawing a good map
+
+- Tiles: `#` stone, `%` tech panel, `=` hell brick, `.` floor, `P` start, `D` demon spawn,
+ `M` medkit, `A` ammo. The border must be wall. Every row is the same width.
+- Give sight lines of 5 to 9 tiles. Very long halls make it a shooting gallery. Tight mazes hide
+ demons until they are biting.
+- Put spawns on at least two sides of the start so Jev must turn to deal with them.
+- Pillars (single wall tiles in a room) make demons split and flank, which is fun to watch.
+- A level of about 24 by 16 fills the minimap nicely. Bigger maps mean long quiet walks.
+
+## Setting the pace
+
+`demonSpeed` is the dial. Demons weave as they charge, so speed is also how fast they cross the
+crosshair. Each wave adds one demon and 12% speed, so every run ends when the pace passes what nine
+decisions a second can handle.
+
+| feel | demonSpeed | demons |
+|---|---|---|
+| a stroll, long runs | 0.8 | 3 |
+| the default | 1.2 | 4 |
+| tense from wave 1 | 2.4 | 5 |
+| brutal | 4.0 | 8 |
+
+`tickMs` changes the decision rate itself. Raising it to 250 shows what a slower decision loop
+costs: the same demons now win much earlier.
+
+## Verifying
+
+```bash
+node "$JEV_DSH/toolchain/check.mjs"
+```
+
+Then watch the pane and read `.harness/verdict.json`: wave, kills, deaths, best wave, shots on
+target. Report the pace you chose, how far Jev gets, and the speed where it stops clearing waves.
+The pane's MOCK badge means the offline stand-in is playing, not the real model. Say so when you
+report.
diff --git a/store/agents/jev-fps/store.json b/store/agents/jev-fps/store.json
new file mode 100644
index 000000000..89ccd5331
--- /dev/null
+++ b/store/agents/jev-fps/store.json
@@ -0,0 +1,18 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev plays a first-person shooter live: turn, move and fire, nine times a second",
+ "examples": [
+ {
+ "prompt": "Build me a tight maze level with a boss room in the middle and three demon spawns in the corners. Start the demons slow, then find the demon speed where Jev stops clearing wave 3.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-fps/firefight.jpg",
+ "caption": "Jev fights through a hand-drawn ASCII map while its keys light up with each decision's probability"
+ },
+ {
+ "prompt": "Make it brutal: 8 demons at once, fast, in one big open room with no cover. Tell Jev to keep its back to a wall. How many waves does it survive?",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-fps/pillar-hall.jpg",
+ "caption": "A stress test for a decision model: more demons, more speed, the same nine decisions a second"
+ }
+ ]
+}
diff --git a/store/agents/jev-fps/template/level.json b/store/agents/jev-fps/template/level.json
new file mode 100644
index 000000000..01dae6d01
--- /dev/null
+++ b/store/agents/jev-fps/template/level.json
@@ -0,0 +1,31 @@
+{
+ "title": "Jev FPS",
+ "description": "Jev is the marine. It reads the fight as text about nine times a second and decides where to turn, how to move and when to fire.",
+ "map": [
+ "########################",
+ "#P.....#.......%.......#",
+ "#......#.......%...D...#",
+ "#..##..#..###..%%%..%%%#",
+ "#..##.....#A#..........#",
+ "#.........###....M.....#",
+ "####..#..........####..#",
+ "#.....#..%%..%%..#.....#",
+ "#..M..#..%....%..#..A..#",
+ "#.....#..%....%........#",
+ "#..####..%%..%%..####..#",
+ "#......................#",
+ "#..D.......==.......D..#",
+ "#..........==..........#",
+ "#......A..........M....#",
+ "########################"
+ ],
+ "tickMs": 110,
+ "demons": 4,
+ "demonSpeed": 1.2,
+ "demonHealth": 60,
+ "demonDamage": 9,
+ "kills": 12,
+ "ammo": 60,
+ "seed": 7,
+ "style": "Stay alive. Face the nearest demon, fire only when it is in your crosshair, keep your distance, and fetch a medkit when your health is low."
+}
diff --git a/store/agents/jev-fps/test/viewer.test.mjs b/store/agents/jev-fps/test/viewer.test.mjs
new file mode 100644
index 000000000..f34f2dd71
--- /dev/null
+++ b/store/agents/jev-fps/test/viewer.test.mjs
@@ -0,0 +1,194 @@
+// Integration tests for Jev FPS. They boot the real viewer on an ephemeral port against a temp
+// workspace and drive time with the `tick` control, so nothing here waits on a timer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync, cpSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { execFileSync } from 'node:child_process'
+import net from 'node:net'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const ROOT = join(HERE, '..')
+const { startFpsViewer } = await import(join(ROOT, 'viewer/viewer.mjs'))
+const { parseMap, DEFAULT_MAP } = await import(join(ROOT, 'viewer/sim.mjs'))
+const { readState, fpsMock } = await import(join(ROOT, 'viewer/mock.mjs'))
+const TEMPLATE = JSON.parse(readFileSync(join(ROOT, 'template/level.json'), 'utf8'))
+
+async function boot(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-fps-test-'))
+ writeFileSync(join(ws, 'level.json'), JSON.stringify({ ...TEMPLATE, ...overrides }))
+ const viewer = await startFpsViewer({ workspace: ws, port: 0 })
+ const base = viewer.url
+ const ctl = async (body) => { const r = await fetch(`${base}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); return { status: r.status, json: await r.json() } }
+ const state = async () => (await fetch(`${base}/state`)).json()
+ await ctl({ cmd: 'pause' }); await ctl({ cmd: 'reset' })
+ return { ws, viewer, base, ctl, state }
+}
+
+test('the fight advances and Jev answers all four questions every tick', async () => {
+ const v = await boot()
+ try {
+ await v.ctl({ cmd: 'tick', n: 60 })
+ const s = await v.state()
+ assert.equal(s.t, 60)
+ assert.equal(s.session.decisions, 60)
+ assert.ok(['LEFT_HARD', 'LEFT', 'LEFT_FINE', 'AHEAD', 'RIGHT_FINE', 'RIGHT', 'RIGHT_HARD'].includes(s.decision.turn))
+ assert.ok(['FORWARD', 'BACK', 'STRAFE_LEFT', 'STRAFE_RIGHT', 'HOLD'].includes(s.decision.move))
+ assert.ok(s.decision.pFire >= 0 && s.decision.pFire <= 1)
+ const sum = Object.values(s.decision.probs.turn).reduce((a, b) => a + b, 0)
+ assert.ok(Math.abs(sum - 1) < 1e-6, 'turn probabilities sum to 1')
+ assert.ok(Math.max(...Object.values(s.decision.probs.turn)) < 0.999, 'a real distribution, not one-hot')
+ assert.match(s.stateText, /health \d+\/100\s+ammo \d+/)
+ const jev = await (await fetch(`${v.base}/jev`)).json()
+ assert.equal(jev.calls, 60)
+ assert.equal(jev.last.questions.length, 4)
+ assert.ok(jev.costUsd > 0)
+ } finally { await v.viewer.close() }
+})
+
+test('level.json really takes effect (title, map, pace), and pane overrides work', async () => {
+ const map = ['##########', '#P.......#', '#........#', '#...%%...#', '#........#', '#......D.#', '#........#', '##########']
+ const v = await boot({ title: 'Tiny Box', map, demonSpeed: 2.5, demons: 2, kills: 3 })
+ try {
+ const s = await v.state()
+ assert.equal(s.title, 'Tiny Box')
+ assert.deepEqual(s.map, map)
+ assert.equal(s.cfg.demonSpeed, 2.5)
+ assert.equal(s.need, 3)
+ assert.equal(s.mapError, null)
+ await v.ctl({ cmd: 'set', key: 'demonSpeed', value: 4 })
+ assert.equal((await v.state()).demonSpeed, 4)
+ const before = (await v.state()).demons.length
+ await v.ctl({ cmd: 'spawn', x: 5, y: 2 })
+ await v.ctl({ cmd: 'spawn', x: 0, y: 0 }) // a wall: must be ignored
+ assert.equal((await v.state()).demons.length, before + 1)
+ await v.ctl({ cmd: 'medkit', x: 3, y: 5 })
+ assert.ok((await v.state()).pickups.some((k) => k.k === 'medkit'))
+ } finally { await v.viewer.close() }
+})
+
+test('a progressive verdict is written', async () => {
+ const v = await boot()
+ try {
+ await v.ctl({ cmd: 'tick', n: 30 })
+ const file = join(v.ws, '.harness/verdict.json')
+ assert.ok(existsSync(file))
+ const verdict = JSON.parse(readFileSync(file, 'utf8'))
+ assert.equal(verdict.spec, 1)
+ assert.equal(verdict.ready, true)
+ assert.match(verdict.summary, /wave 1/)
+ assert.ok(Array.isArray(verdict.findings) && Array.isArray(verdict.phases))
+ assert.equal(verdict.artifact, 'level.json')
+ } finally { await v.viewer.close() }
+})
+
+test('every control command answers 200, and junk is rejected', async () => {
+ const v = await boot()
+ try {
+ for (const cmd of ['pause', 'tick', 'start', 'pause', 'swarm', 'reset']) assert.equal((await v.ctl({ cmd })).status, 200, cmd)
+ assert.equal((await v.ctl({ cmd: 'human', turn: 'LEFT', move: 'FORWARD', fire: true })).status, 200)
+ assert.equal((await v.ctl({ cmd: 'set', key: 'not-a-key', value: 1 })).status, 200)
+ const bad = await fetch(`${v.base}/control`, { method: 'POST', body: '{not json' })
+ assert.equal(bad.status, 400)
+ assert.equal((await fetch(`${v.base}/nope`)).status, 404)
+ } finally { await v.viewer.close() }
+})
+
+test('the person can take the controls, and Jev gets them back', async () => {
+ const v = await boot()
+ try {
+ const a0 = (await v.state()).player.a
+ await v.ctl({ cmd: 'human', turn: 'RIGHT_HARD', move: 'HOLD', fire: false })
+ await v.ctl({ cmd: 'tick' })
+ const s = await v.state()
+ assert.equal(s.driver, 'human')
+ assert.ok(Math.abs(s.player.a - a0) > 0.4, 'a hard right turn moved the view')
+ await new Promise((r) => setTimeout(r, 450))
+ assert.equal((await v.state()).driver, 'jev')
+ } finally { await v.viewer.close() }
+})
+
+test('a broken level.json keeps the fight alive and reports the problem', async () => {
+ const v = await boot()
+ try {
+ writeFileSync(join(v.ws, 'level.json'), '{ "title": "oops", ')
+ await new Promise((r) => setTimeout(r, 250))
+ await v.ctl({ cmd: 'tick', n: 5 })
+ let s = await v.state()
+ assert.match(String(s.cfgError), /level\.json/)
+ assert.ok(s.t >= 5)
+ writeFileSync(join(v.ws, 'level.json'), JSON.stringify({ ...TEMPLATE, map: ['####', '#P.#', '####'] }))
+ await new Promise((r) => setTimeout(r, 250))
+ s = await v.state()
+ assert.equal(s.cfgError, null)
+ assert.match(String(s.mapError), /map must be 8 to 40 rows/)
+ assert.deepEqual(s.map, DEFAULT_MAP, 'falls back to the built-in map')
+ } finally { await v.viewer.close() }
+})
+
+test('the viewer is loopback only', async () => {
+ const v = await boot()
+ try {
+ const port = Number(new URL(v.base).port)
+ const status = await new Promise((resolve) => {
+ const sock = net.connect(port, '127.0.0.1', () => sock.write('GET /state HTTP/1.1\r\nHost: evil.example.com\r\nConnection: close\r\n\r\n'))
+ let buf = ''
+ sock.on('data', (d) => { buf += d })
+ sock.on('end', () => resolve(Number((buf.match(/^HTTP\/1\.1 (\d+)/) ?? [])[1])))
+ sock.on('error', () => resolve(0))
+ })
+ assert.equal(status, 403)
+ } finally { await v.viewer.close() }
+})
+
+test('the dial is honest: fast demons kill Jev far more often than slow ones', async () => {
+ const run = async (demonSpeed) => {
+ const v = await boot({ demonSpeed })
+ try { await v.ctl({ cmd: 'tick', n: 4000 }); return (await v.state()).session } finally { await v.viewer.close() }
+ }
+ const easy = await run(1.0), hard = await run(4.5)
+ assert.ok(easy.kills > 100 && hard.kills > 100, 'Jev fights in both')
+ assert.ok(hard.deaths >= easy.deaths * 2 && hard.deaths >= easy.deaths + 3, `deaths easy ${easy.deaths} vs hard ${hard.deaths}`)
+ assert.ok(easy.bestWave > hard.bestWave, `best wave easy ${easy.bestWave} vs hard ${hard.bestWave}`)
+})
+
+test('map validation catches the common mistakes', () => {
+ assert.equal(parseMap(DEFAULT_MAP).ok, true)
+ const box = (rows) => parseMap(rows)
+ assert.match(box(['########', '#P.....#', '#......#', '#......#', '#......#', '#......#', '#......#', '########']).error, /at least one D/)
+ assert.match(box(['########', '#P....D#', '#......#', '#......#', '#......#', '#......#', '#.....P#', '########']).error, /exactly one P/)
+ assert.match(box(['########', '#P....D.', '#......#', '#......#', '#......#', '#......#', '#......#', '########']).error, /border must be wall/)
+ assert.match(box(['########', '#P..#.D#', '#...#..#', '#...#..#', '#...#..#', '#...#..#', '#...#..#', '########']).error, /walled off/)
+ assert.match(box(['########', '#P...D#', '#......#', '#......#', '#......#', '#......#', '#......#', '########']).error, /wide, expected/)
+})
+
+test('the offline stand-in reads only the state text and answers sensibly', () => {
+ const text = [
+ 'You are the marine. style', 'wave 1 kills 0/12 health 80/100 ammo 30',
+ 'walls: ahead 6.0 left 2.0 right 3.0 behind 4.0', 'one decision turns you: HARD 36 deg, normal 13 deg, FINE 4 deg',
+ 'demons in sight (bearing in degrees off your crosshair, negative is left):', ' demon#3 bearing -30 distance 5.0',
+ 'heard but not seen: nothing', 'route to nearest demon: bearing -28 steps 5', 'crosshair on: nothing',
+ ].join('\n')
+ assert.equal(readState(text).seen[0].b, -30)
+ const opts = { options: ['LEFT_HARD', 'LEFT', 'LEFT_FINE', 'AHEAD', 'RIGHT_FINE', 'RIGHT', 'RIGHT_HARD'] }
+ assert.equal(fpsMock(text, 'turn', opts).choice, 'LEFT_HARD')
+ assert.ok(fpsMock(text, 'fire', {}).noul < 0.2)
+ assert.ok(fpsMock(text.replace('crosshair on: nothing', 'crosshair on: demon#3 distance 5.0'), 'fire', {}).noul > 0.8)
+ assert.equal(fpsMock('nothing to do with a shooter', 'turn', opts), null)
+})
+
+test('check.mjs accepts the template and rejects bad values', () => {
+ const run = (level) => {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-fps-check-'))
+ writeFileSync(join(ws, 'level.json'), JSON.stringify(level))
+ try { return { code: 0, out: execFileSync(process.execPath, [join(ROOT, 'toolchain/check.mjs')], { env: { ...process.env, HARNESS_WORKSPACE: ws }, encoding: 'utf8' }) } }
+ catch (e) { return { code: e.status, out: String(e.stdout) } }
+ }
+ assert.equal(run(TEMPLATE).code, 0)
+ const fast = run({ ...TEMPLATE, demonSpeed: 99 })
+ assert.equal(fast.code, 1); assert.match(fast.out, /demonSpeed/)
+ const holed = run({ ...TEMPLATE, map: TEMPLATE.map.map((r, i) => (i === 0 ? r.replace('#', '.') : r)) })
+ assert.equal(holed.code, 1); assert.match(holed.out, /border must be wall/)
+})
diff --git a/store/agents/jev-fps/toolchain/README.md b/store/agents/jev-fps/toolchain/README.md
new file mode 100644
index 000000000..e92012621
--- /dev/null
+++ b/store/agents/jev-fps/toolchain/README.md
@@ -0,0 +1,44 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
+
+## Going live
+
+Without a key everything runs on the offline stand-in and the pane says `MOCK`. For the real model,
+give the harness a key. The viewer is started by the Harness daemon, which does not see variables
+you export in a shell, so the reliable place is a small file in your home folder:
+
+```sh
+mkdir -p ~/.config/typesafe && chmod 700 ~/.config/typesafe
+printf 'TYPESAFE_API_KEY=%s\n' 'paste-your-key-here' > ~/.config/typesafe/credentials
+chmod 600 ~/.config/typesafe/credentials
+```
+
+Two routes work, and both speak the same question format:
+
+| route | what goes in the file | where to get it |
+|---|---|---|
+| TypeSafe direct | `TYPESAFE_API_KEY=...` | https://console.typesafe.ai/keys (there may be a waitlist) |
+| Cloudflare Workers AI | `CLOUDFLARE_ACCOUNT_ID=...` and `CLOUDFLARE_API_TOKEN=...` | a Cloudflare API token with Workers AI permission, no TypeSafe waitlist |
+
+Environment variables of the same names win over the file. Restart the harness after changing the
+file. `toolchain/doctor.sh` prints which route is active and never prints the key. One file serves
+every Jev harness on the machine. Never paste a key into the chat, and never save one in the
+workspace. Under `node --test`, or with `JEV_OFFLINE=1`, a key is ignored so tests stay deterministic.
diff --git a/store/agents/jev-fps/toolchain/check.mjs b/store/agents/jev-fps/toolchain/check.mjs
new file mode 100644
index 000000000..3893659ad
--- /dev/null
+++ b/store/agents/jev-fps/toolchain/check.mjs
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+// check.mjs — validate a level.json for the Jev FPS harness: the map's shape and reachability, and
+// every number's range. Prints one line per problem and exits 1 on any error.
+import { readFileSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const { parseMap } = await import(join(HERE, '../viewer/sim.mjs'))
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let errors = 0
+const error = (msg) => { errors++; console.log(`error ${msg}`) }
+const warn = (msg) => console.log(`warn ${msg}`)
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'level.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read level.json: ${e.message}`)
+ process.exit(1)
+}
+
+const map = parseMap(p.map)
+if (!map.ok) error(`map: ${map.error}`)
+else {
+ if (map.spawns.length < 2) warn('only one demon spawn (D): demons will always come from the same side')
+ if (!map.pickups.some((k) => k.kind === 'medkit')) warn('no medkit (M) on the map: every run ends fast')
+ if (!map.pickups.some((k) => k.kind === 'ammo')) warn('no ammo (A) on the map')
+}
+
+const range = (key, lo, hi, what) => {
+ if (p[key] === undefined) return
+ if (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < lo || p[key] > hi) error(`${key} (${what}) must be a number from ${lo} to ${hi}`)
+}
+range('tickMs', 60, 1000, 'milliseconds per Jev decision')
+range('demons', 1, 24, 'demons alive at once in wave 1')
+range('demonSpeed', 0.2, 6, 'tiles per second in wave 1')
+range('demonHealth', 10, 400, 'a shot does 34')
+range('demonDamage', 1, 60, 'per bite')
+range('kills', 1, 200, 'kills to clear wave 1')
+range('ammo', 0, 99, 'starting ammo')
+range('seed', 0, 1e9, 'random seed')
+if (!p.title || typeof p.title !== 'string') warn('no title')
+if (!p.style || typeof p.style !== 'string') warn('no style line: tell Jev how to fight')
+else if (p.style.length > 600) error('style must be 600 characters or fewer')
+
+console.log(errors ? `fail level.json has ${errors} error${errors > 1 ? 's' : ''}` : 'ok level.json is valid')
+process.exit(errors ? 1 : 0)
diff --git a/store/agents/jev-fps/toolchain/doctor.sh b/store/agents/jev-fps/toolchain/doctor.sh
new file mode 100755
index 000000000..3e02612fd
--- /dev/null
+++ b/store/agents/jev-fps/toolchain/doctor.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev FPS viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+cd "$(dirname "$0")/.."
+node -e "import('./toolchain/jev.mjs').then((m) => console.log('ok Jev: ' + m.describeCredentials())).catch((e) => console.log('warn Jev client did not load: ' + e.message))"
+echo "done"
diff --git a/store/agents/jev-fps/toolchain/init-workspace.sh b/store/agents/jev-fps/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-fps/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-fps/toolchain/jev.mjs b/store/agents/jev-fps/toolchain/jev.mjs
new file mode 100644
index 000000000..190c7e9ac
--- /dev/null
+++ b/store/agents/jev-fps/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
+// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
+// score a position on a 2..10 level scale — a float plus per-level probabilities
+//
+// Questions are authored as options[] / legend{} (or an option -> description map) and translated
+// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The generic mock reads
+// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
+// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
+// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ return key ? 'typesafe' : 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ return (h >>> 0) / 4294967296
+}
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+
+/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
+export function stems(text) {
+ const out = []
+ for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
+ if (w.length < 2 || STOP.has(w)) continue
+ out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
+ }
+ return out
+}
+
+/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
+function evidence(stateStems, needle) {
+ const want = [...new Set(stems(needle))]
+ if (!want.length) return 0
+ let hit = 0
+ for (const w of want) if (stateStems.has(w)) hit++
+ return (hit / Math.sqrt(want.length)) * 1.2
+}
+
+function softmax(raw, temp = 1) {
+ const m = Math.max(...raw)
+ const exps = raw.map((r) => Math.exp((r - m) / temp))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ return exps.map((e) => e / sum)
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic generic mock. It turns the state text + question wording into a plausible
+// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`
+ const S = new Set(stems(text))
+ const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
+
+ if (q.type === 'noul') {
+ const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
+ const no = evidence(S, `${q.raw?.false ?? ''}`)
+ const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
+ const probs = softmax(raw, 0.6)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
+ const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
+ // No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
+ if (raw.every((r) => Math.abs(r) < 0.26)) {
+ const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
+ levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
+ }
+ const probs = softmax(raw, 0.7)
+ const probabilities = {}
+ levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
+ const score = probs.reduce((acc, p, i) => acc + p * i, 0)
+ return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// Imports are hoisted, so they can live here with the code that needs them.
+import { readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ out.raw = isMap(q.criteria) ? q.criteria : null
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+// ---------------------------------------------------------------------------
+// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
+// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
+// you happen to have open. Two live routes are supported, both speaking the same question format:
+// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
+// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
+// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
+// ---------------------------------------------------------------------------
+const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN']
+let credCache = null
+export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
+
+function readCredentialFile() {
+ const now = Date.now()
+ const path = credentialsPath()
+ if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
+ const values = {}
+ try {
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
+ if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
+ }
+ } catch { /* no file: fine */ }
+ credCache = { at: now, path, values }
+ return values
+}
+
+/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
+export function resolveCredentials(explicitKey) {
+ if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
+ // Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
+ // key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
+ if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
+ const file = readCredentialFile()
+ const get = (k) => process.env[k] || file[k] || ''
+ const key = explicitKey || get('TYPESAFE_API_KEY')
+ if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
+ const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
+ if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
+ return null
+}
+
+/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
+export function describeCredentials() {
+ const c = resolveCredentials()
+ if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
+ return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
+}
+
+async function liveEvaluate(body, cred) {
+ const endpoint = cred.url
+ const key = cred.secret
+ const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } } : body
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) {
+ const data = await res.json()
+ // Cloudflare wraps the model's reply as { result, success, errors }.
+ if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
+ return data?.result?.answers ? data.result : data
+ }
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const cred = resolveCredentials(key)
+ const client = cred ? cred.provider : 'mock'
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (cred) {
+ const data = await liveEvaluate({ model, state, questions: wire }, cred)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-fps/toolchain/setup.sh b/store/agents/jev-fps/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-fps/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-fps/toolchain/viewer.sh b/store/agents/jev-fps/toolchain/viewer.sh
new file mode 100755
index 000000000..dee96efaf
--- /dev/null
+++ b/store/agents/jev-fps/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev FPS viewer (Jev plays a first-person arena shooter, one typed decision at a time).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-fps/viewer/base.css b/store/agents/jev-fps/viewer/base.css
new file mode 100644
index 000000000..c41ddcd46
--- /dev/null
+++ b/store/agents/jev-fps/viewer/base.css
@@ -0,0 +1,83 @@
+/* base.css — the shared look of the Jev flagship viewers. Load before studio.css.
+ Set --accent / --accent2 in studio.css to give a harness its own colour. */
+:root {
+ --bg: #07080d; --panel: #10121a; --panel2: #161925; --line: #232838; --line2: #2e3550;
+ --ink: #e9ecf5; --dim: #8b92aa; --faint: #565d75;
+ --accent: #a78bfa; --accent2: #6d5bd0;
+ --ok: #34d399; --warn: #fbbf24; --bad: #fb7185; --cyan: #5eead4; --blue: #60a5fa;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ --radius: 12px;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1100px 700px at 75% -10%, color-mix(in srgb, var(--accent) 14%, transparent) 0%, transparent 60%), var(--bg);
+ color: var(--ink); font: 13px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+::selection { background: color-mix(in srgb, var(--accent) 45%, transparent); }
+::-webkit-scrollbar { width: 8px; height: 8px; }
+::-webkit-scrollbar-thumb { background: var(--line2); border-radius: 4px; }
+::-webkit-scrollbar-track { background: transparent; }
+
+#topbar {
+ display: flex; align-items: center; gap: 22px; padding: 10px 18px; flex: none; flex-wrap: wrap;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(20,22,34,.92), rgba(10,11,18,.7)); backdrop-filter: blur(8px);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font: 700 15px var(--mono); letter-spacing: .4px; margin: 0; white-space: nowrap; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 14px var(--accent); animation: dot 2.4s ease-in-out infinite; }
+@keyframes dot { 50% { transform: scale(.72); opacity: .7; } }
+.brand .sub { color: var(--dim); font-size: 11px; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; min-width: 54px; }
+.stat label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+button, .btn {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line2); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: border-color .15s, filter .15s, transform .05s; user-select: none;
+}
+button:hover { border-color: var(--accent); }
+button:active { transform: translateY(1px); }
+button.primary { background: linear-gradient(135deg, var(--accent2), var(--accent)); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.12); }
+button.ghost { background: transparent; }
+button.on { border-color: var(--accent); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
+button[disabled] { opacity: .45; cursor: default; }
+kbd { font: 600 10px var(--mono); padding: 1px 5px; border: 1px solid var(--line2); border-bottom-width: 2px; border-radius: 4px; color: var(--dim); }
+input[type=text], input[type=search], select, textarea {
+ font: 13px var(--mono); color: var(--ink); background: #0b0d14; border: 1px solid var(--line2); border-radius: 8px; padding: 7px 10px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+input[type=range] { accent-color: var(--accent); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow: auto; }
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 14px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; background: rgba(12,13,20,.55); }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; }
+.panel-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--dim); margin-bottom: 9px; display: flex; align-items: center; gap: 8px; }
+.panel-title .right { margin-left: auto; text-transform: none; letter-spacing: 0; }
+.how { color: var(--dim); font-size: 12.5px; line-height: 1.55; }
+.how b { color: var(--ink); } .how code { color: var(--warn); }
+.pill { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line2); color: var(--dim); }
+.pill.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
+.pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
+.pill.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); }
+
+.canvas-wrap { position: relative; flex: 1; min-height: 320px; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #05060a; }
+.canvas-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.banner { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); padding: 9px 20px; border-radius: 10px; font: 700 14px var(--mono); white-space: nowrap; backdrop-filter: blur(6px); }
+.banner.ok { background: rgba(16,185,129,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 34px rgba(16,185,129,.35); }
+.banner.bad { background: rgba(225,29,72,.16); border: 1px solid var(--bad); color: var(--bad); box-shadow: 0 0 34px rgba(225,29,72,.35); }
+.hidden { display: none !important; }
+.cfg-error { margin: 0 16px; padding: 8px 12px; border: 1px solid var(--bad); border-radius: 8px; color: var(--bad); background: rgba(225,29,72,.08); font-size: 12px; }
+
+@media (max-width: 900px) {
+ main { flex-direction: column; overflow: auto; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); overflow: visible; }
+ body { overflow: auto; }
+}
diff --git a/store/agents/jev-fps/viewer/index.html b/store/agents/jev-fps/viewer/index.html
new file mode 100644
index 000000000..a94ca91db
--- /dev/null
+++ b/store/agents/jev-fps/viewer/index.html
@@ -0,0 +1,74 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev FPS</title>
+<link rel="stylesheet" href="/base.css">
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1 id="title">Jev FPS</h1><span class="sub">synthetic arena · Jev decides every move</span></div>
+ <div class="stats">
+ <div class="stat"><label>Wave</label><span id="s-wave">1</span></div>
+ <div class="stat"><label>Kills</label><span id="s-kills">0</span></div>
+ <div class="stat"><label>Deaths</label><span id="s-deaths">0</span></div>
+ <div class="stat"><label>Best wave</label><span id="s-best">1</span></div>
+ <div class="stat"><label>On target</label><span id="s-acc">—</span></div>
+ <div class="stat big"><label>Decisions / s</label><span id="s-rate">—</span></div>
+ <div class="stat big"><label>Decisions</label><span id="s-dec">0</span></div>
+ <div class="stat big"><label>Cost so far</label><span id="s-cost">$0</span></div>
+ </div>
+ <div class="controls">
+ <button id="sound" class="ghost" title="Sound is off until you click">Sound off</button>
+ <button id="pause">Pause</button>
+ <button id="step">Step</button>
+ <button id="reset" class="primary">Reset</button>
+ </div>
+ </div>
+ <div id="cfgError" class="cfg-error hidden"></div>
+ <main>
+ <section id="stage">
+ <div class="canvas-wrap" id="wrap">
+ <canvas id="scene" tabindex="0" aria-label="First-person view of the arena"></canvas>
+ </div>
+ <div class="toolbar panel">
+ <div class="tools" role="group" aria-label="What a click on the map does">
+ <span class="lab">Click the map to</span>
+ <button data-tool="spawn" class="on">Spawn a demon</button>
+ <button data-tool="medkit">Drop a medkit</button>
+ <button data-tool="ammo">Drop ammo</button>
+ </div>
+ <button id="swarm">Swarm +5</button>
+ <label class="slider">Demon speed <input id="speed" type="range" min="0.4" max="5" step="0.1" value="1.2"> <b id="speedVal">1.2</b></label>
+ <span class="hint">Grab the controls any time: <kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> move · <kbd>←</kbd><kbd>→</kbd> turn · <kbd>Space</kbd> fire. Let go and Jev takes over.</span>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">What Jev reads <span class="right pill" id="driver">JEV</span></div>
+ <pre id="stateText" class="statetext"></pre>
+ </div>
+ <div class="panel">
+ <div class="panel-title">How it works</div>
+ <div class="how">
+ Jev never sees pixels. About nine times a second the marine's situation is written as the
+ text above, and Jev answers <b>four typed questions in one call</b>: where to <b>turn</b>, how
+ to <b>move</b>, whether to <b>fire</b>, and how big the <b>threat</b> is. The keys lit on screen
+ are Jev's answers, filled by their probability.<br><br>
+ Each cleared wave adds a demon and makes them faster, until Jev's decision rate is not
+ enough. Edit <code>level.json</code> to redraw the map or change the pace. The arena and
+ the demons are made up. The decision loop is the demo.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Fight log</div>
+ <ul id="feed"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-fps/viewer/jev-hud.js b/store/agents/jev-fps/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-fps/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-fps/viewer/kit.mjs b/store/agents/jev-fps/viewer/kit.mjs
new file mode 100644
index 000000000..f80d29b7d
--- /dev/null
+++ b/store/agents/jev-fps/viewer/kit.mjs
@@ -0,0 +1,112 @@
+// kit.mjs — the boring, security-relevant half of a Jev viewer, written once:
+// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
+// /control, plus an atomic verdict writer and a safe JSON config watcher.
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
+import { join, extname } from 'node:path'
+import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
+
+export const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+/** Deterministic PRNG so every run of a demo is reproducible. */
+export function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/**
+ * Serve a viewer.
+ * @param {object} o
+ * @param {string} o.here the viewer directory (static files live here)
+ * @param {number} o.port 0 = ephemeral
+ * @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
+ * @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
+ * @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ */
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+ const clients = new Set()
+ const allowed = new Set(files)
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ // Loopback only: a page on another origin (DNS rebinding) must not reach this server.
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ const path = url.pathname
+ try {
+ if (req.method === 'GET') {
+ const name = path === '/' ? 'index.html' : path.slice(1)
+ if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
+ if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (path === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
+ clients.add(res)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ }
+ if (req.method === 'POST' && path === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 65536) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const reply = control ? await control(String(j.cmd ?? ''), j) : null
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
+ res.writeHead(404); res.end('Not found')
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
+ }
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ clients,
+ /** Push a named SSE event (default 'state') to every connected pane. */
+ broadcast(obj, event = 'state') {
+ const line = `event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`
+ for (const c of clients) c.write(line)
+ },
+ async close() { for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+/** Atomic write of .harness/verdict.json (the harness reads this file; never edit it by hand). */
+export function writeVerdict(workspace, verdict) {
+ const dir = join(workspace, '.harness')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify({ spec: 1, ...verdict, updatedAt: new Date().toISOString() }))
+ renameSync(file + '.tmp', file)
+}
+
+/**
+ * Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
+ * good config and reports the parse error instead of crashing the demo.
+ * @returns {{ get(): object, error(): string|null, close(): void }}
+ */
+export function watchConfig(file, defaults, onChange) {
+ let cfg = { ...defaults }, err = null, timer = null
+ const load = () => {
+ try { cfg = { ...defaults, ...JSON.parse(readFileSync(file, 'utf8')) }; err = null }
+ catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
+ }
+ load()
+ let watcher = null
+ try {
+ watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ } catch { /* file may not exist yet; defaults stand */ }
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+}
diff --git a/store/agents/jev-fps/viewer/mock.mjs b/store/agents/jev-fps/viewer/mock.mjs
new file mode 100644
index 000000000..308b91a95
--- /dev/null
+++ b/store/agents/jev-fps/viewer/mock.mjs
@@ -0,0 +1,100 @@
+// mock.mjs — the offline stand-in for Jev in this harness. It reads ONLY the state text that live
+// Jev also gets (never the simulator's variables) and answers the same typed questions with a full
+// probability distribution. It is a competent reflex bot, not Jev's judgement; the pane badges it MOCK.
+
+const num = (text, re) => { const m = text.match(re); return m ? Number(m[1]) : NaN }
+
+export function readState(text) {
+ const seen = [...text.matchAll(/demon#(\d+) bearing ([+-]\d+) distance ([\d.]+)( BITING YOU)?/g)]
+ .map((m) => ({ id: +m[1], b: +m[2], dist: +m[3], biting: !!m[4] }))
+ // The "heard" and "crosshair" lines also match the demon pattern, so split them out by line.
+ const inSight = []
+ let section = ''
+ for (const line of text.split('\n')) {
+ if (line.startsWith('demons in sight')) { section = 'seen'; continue }
+ if (line.startsWith('heard')) section = 'heard'
+ if (section === 'seen' && line.startsWith(' demon#')) {
+ const m = line.match(/demon#(\d+) bearing ([+-]\d+) distance ([\d.]+)( BITING YOU)?/)
+ if (m) inSight.push({ id: +m[1], b: +m[2], dist: +m[3], biting: !!m[4] })
+ }
+ }
+ const heardM = text.match(/heard but not seen: demon#(\d+) bearing ([+-]\d+) distance ([\d.]+)/)
+ const routeM = text.match(/route to nearest (\w+): bearing ([+-]\d+) steps (\d+)/)
+ const hud = text.match(/health (\d+)\/100\s+ammo (\d+)/)
+ const w = text.match(/walls: ahead ([\d.]+)\s+left ([\d.]+)\s+right ([\d.]+)\s+behind ([\d.]+)/)
+ return {
+ hp: hud ? +hud[1] : NaN, ammo: hud ? +hud[2] : 0,
+ walls: w ? { ahead: +w[1], left: +w[2], right: +w[3], behind: +w[4] } : { ahead: 9, left: 9, right: 9, behind: 9 },
+ turnAmount: { HARD: num(text, /HARD (\d+) deg/), NORMAL: num(text, /normal (\d+) deg/), FINE: num(text, /FINE (\d+) deg/) },
+ seen: inSight, all: seen,
+ heard: heardM ? { id: +heardM[1], b: +heardM[2], dist: +heardM[3] } : null,
+ route: routeM ? { kind: routeM[1], b: +routeM[2], steps: +routeM[3] } : null,
+ crosshair: /crosshair on: demon#\d+/.test(text),
+ }
+}
+
+/** Spread probability around a chosen index: the pick gets most of it, neighbours share the rest. */
+function peaked(options, pick, sharp = 1.6, order = options) {
+ const pi = order.indexOf(pick)
+ const raw = options.map((o) => Math.exp(-sharp * Math.abs(order.indexOf(o) - pi)))
+ const sum = raw.reduce((a, b) => a + b, 0)
+ const probabilities = Object.fromEntries(options.map((o, i) => [o, raw[i] / sum]))
+ return { type: 'choice', choice: pick, confidence: probabilities[pick], probabilities }
+}
+
+export function fpsMock(text, id, q) {
+ const s = readState(text)
+ if (!Number.isFinite(s.hp)) return null // not our state text: let the generic mock answer
+ const near = s.seen[0] ?? null
+ const hurt = s.hp < 40
+ // Who to face: a demon in sight, else something heard close behind us, else the automap route.
+ const fetching = s.route && s.route.kind !== 'demon'
+ let faceB = near ? near.b : s.heard && s.heard.dist < 3.5 ? s.heard.b : s.route ? s.route.b : 0
+ if (fetching && !(near && near.dist < 3)) faceB = s.route.b
+
+ if (id === 'turn') {
+ const amt = { LEFT_HARD: -s.turnAmount.HARD, LEFT: -s.turnAmount.NORMAL, LEFT_FINE: -s.turnAmount.FINE, AHEAD: 0, RIGHT_FINE: s.turnAmount.FINE, RIGHT: s.turnAmount.NORMAL, RIGHT_HARD: s.turnAmount.HARD }
+ let pick = 'AHEAD', best = Infinity
+ for (const o of q.options) {
+ const a = amt[o] ?? 0
+ const err = Math.abs(faceB - a) - (!s.crosshair && a !== 0 && Math.sign(a) === Math.sign(faceB) ? 0.01 : 0)
+ if (err < best) { best = err; pick = o }
+ }
+ return peaked(q.options, pick, 1.8)
+ }
+
+ if (id === 'move') {
+ const open = (side) => (side === 'STRAFE_LEFT' ? s.walls.left : s.walls.right) > 0.9
+ const wider = s.walls.left > s.walls.right ? 'STRAFE_LEFT' : 'STRAFE_RIGHT'
+ let pick
+ if (near) {
+ if (near.dist < 1.7 || (hurt && near.dist < 3.2)) pick = s.walls.behind > 0.7 ? 'BACK' : open(wider) ? wider : 'HOLD'
+ else if (near.dist < 4.2) pick = open(wider) ? wider : 'HOLD'
+ else pick = Math.abs(near.b) < 30 && s.walls.ahead > 0.8 ? 'FORWARD' : open(wider) ? wider : 'HOLD'
+ } else if (s.route) {
+ pick = Math.abs(s.route.b) < 40 ? (s.walls.ahead > 0.55 ? 'FORWARD' : open(wider) ? wider : 'HOLD') : 'HOLD'
+ } else pick = 'HOLD'
+ const p = peaked(q.options, pick, 2.2)
+ return p
+ }
+
+ if (id === 'fire') {
+ let p = 0.04
+ if (s.ammo > 0 && s.crosshair) p = 0.94
+ else if (s.ammo > 0 && near && Math.abs(near.b) < 9 && near.dist < 2.2) p = 0.62
+ return { type: 'noul', noul: p }
+ }
+
+ if (id === 'threat') {
+ const close = s.seen.filter((d) => d.dist < 4).length + (s.heard && s.heard.dist < 3 ? 1 : 0)
+ let level = close >= 3 ? 3 : close === 2 ? 2 : close === 1 || s.seen.length ? 1 : 0
+ if (hurt) level = Math.min(3, level + 1)
+ if (s.seen.some((d) => d.biting)) level = Math.max(level, 2)
+ const n = Object.keys(q.legend ?? {}).length || 4
+ const raw = Array.from({ length: n }, (_, i) => Math.exp(-1.7 * Math.abs(i - level)))
+ const sum = raw.reduce((a, b) => a + b, 0)
+ const probabilities = Object.fromEntries(raw.map((r, i) => [String(i), r / sum]))
+ return { type: 'score', score: raw.reduce((acc, r, i) => acc + (r / sum) * i, 0), confidence: Math.max(...raw) / sum, legend: q.legend, probabilities }
+ }
+ return null
+}
diff --git a/store/agents/jev-fps/viewer/sim.mjs b/store/agents/jev-fps/viewer/sim.mjs
new file mode 100644
index 000000000..a4f92da4d
--- /dev/null
+++ b/store/agents/jev-fps/viewer/sim.mjs
@@ -0,0 +1,356 @@
+// sim.mjs — the arena. A small, deterministic first-person-shooter world on a tile map: one marine
+// (driven by Jev), demons that path-find to the marine, hitscan shots, pickups and waves.
+// Pure functions over a plain `world` object so tests can drive it without a server.
+import { mulberry32 } from './kit.mjs'
+
+export const FOV_DEG = 66
+export const WALLS = '#%='
+// Turn rates in degrees per second; the per-decision amount is rate * tickMs / 1000.
+export const TURN_RATE = { LEFT_HARD: -330, LEFT: -120, LEFT_FINE: -36, AHEAD: 0, RIGHT_FINE: 36, RIGHT: 120, RIGHT_HARD: 330 }
+export const TURNS = Object.keys(TURN_RATE)
+export const MOVES = ['FORWARD', 'BACK', 'STRAFE_LEFT', 'STRAFE_RIGHT', 'HOLD']
+const FIRE_COOLDOWN = 3 // decisions between shots
+const MOVE_SPEED = { FORWARD: 3.2, BACK: 2.2, STRAFE_LEFT: 2.6, STRAFE_RIGHT: 2.6, HOLD: 0 } // tiles per second
+
+export const DEFAULT_MAP = [
+ '########################',
+ '#P.....#.......%.......#',
+ '#......#.......%...D...#',
+ '#..##..#..###..%%%..%%%#',
+ '#..##.....#A#..........#',
+ '#.........###....M.....#',
+ '####..#..........####..#',
+ '#.....#..%%..%%..#.....#',
+ '#..M..#..%....%..#..A..#',
+ '#.....#..%....%........#',
+ '#..####..%%..%%..####..#',
+ '#......................#',
+ '#..D.......==.......D..#',
+ '#..........==..........#',
+ '#......A..........M....#',
+ '########################',
+]
+
+export const DEFAULT = {
+ title: 'Jev FPS',
+ description: 'Jev is the marine. It reads the fight as text about nine times a second and decides where to turn, how to move and when to fire.',
+ map: DEFAULT_MAP,
+ tickMs: 110, // one Jev decision per tick
+ demons: 4, // alive at once in wave 1 (+1 per wave)
+ demonSpeed: 1.2, // tiles per second in wave 1 (+12% per wave) — the honest dial
+ demonHealth: 60,
+ demonDamage: 9, // per bite, about two bites a second in reach
+ kills: 12, // kills to clear wave 1 (+4 per wave)
+ ammo: 60,
+ seed: 7,
+ style: 'Stay alive. Face the nearest demon, fire only when it is in your crosshair, keep your distance, and fetch a medkit when your health is low.',
+}
+
+const DEG = Math.PI / 180
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+export const normDeg = (d) => { d = ((d + 180) % 360 + 360) % 360 - 180; return d === -180 ? 180 : d }
+
+/** Parse and validate the ASCII map. Returns { ok, error, w, h, rows, start, spawns, pickups }. */
+export function parseMap(lines) {
+ const bad = (error) => ({ ok: false, error })
+ if (!Array.isArray(lines) || lines.length < 8 || lines.length > 40) return bad('map must be 8 to 40 rows of text')
+ const w = String(lines[0]).length
+ if (w < 8 || w > 64) return bad('map rows must be 8 to 64 characters wide')
+ const rows = []
+ let start = null
+ const spawns = [], pickups = []
+ for (let y = 0; y < lines.length; y++) {
+ const line = String(lines[y])
+ if (line.length !== w) return bad(`map row ${y + 1} is ${line.length} wide, expected ${w}`)
+ for (let x = 0; x < w; x++) {
+ const c = line[x]
+ if (!'#%=.PDMA'.includes(c)) return bad(`map row ${y + 1} has an unknown tile "${c}" (use # % = . P D M A)`)
+ const edge = y === 0 || x === 0 || y === lines.length - 1 || x === w - 1
+ if (edge && !WALLS.includes(c)) return bad(`the map border must be wall; row ${y + 1} column ${x + 1} is "${c}"`)
+ if (c === 'P') { if (start) return bad('the map needs exactly one P (player start)'); start = { x: x + 0.5, y: y + 0.5 } }
+ if (c === 'D') spawns.push({ x: x + 0.5, y: y + 0.5 })
+ if (c === 'M') pickups.push({ x: x + 0.5, y: y + 0.5, kind: 'medkit' })
+ if (c === 'A') pickups.push({ x: x + 0.5, y: y + 0.5, kind: 'ammo' })
+ }
+ rows.push(line)
+ }
+ if (!start) return bad('the map needs exactly one P (player start)')
+ if (!spawns.length) return bad('the map needs at least one D (demon spawn)')
+ const map = { ok: true, error: null, w, h: rows.length, rows, start, spawns, pickups }
+ const dist = flood(map, start.x | 0, start.y | 0)
+ for (const s of spawns) if (dist[(s.y | 0) * w + (s.x | 0)] < 0) return bad('a demon spawn (D) is walled off from the player start (P)')
+ return map
+}
+
+export const isWall = (map, x, y) => x < 0 || y < 0 || x >= map.w || y >= map.h || WALLS.includes(map.rows[y | 0][x | 0])
+
+/** Breadth-first distances (in steps) from a cell to every floor cell; -1 where unreachable. */
+export function flood(map, sx, sy) {
+ const dist = new Int16Array(map.w * map.h).fill(-1)
+ const q = [sx, sy]
+ dist[sy * map.w + sx] = 0
+ for (let i = 0; i < q.length; i += 2) {
+ const x = q[i], y = q[i + 1], d = dist[y * map.w + x]
+ for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
+ const nx = x + dx, ny = y + dy
+ if (isWall(map, nx, ny) || dist[ny * map.w + nx] >= 0) continue
+ dist[ny * map.w + nx] = d + 1
+ q.push(nx, ny)
+ }
+ }
+ return dist
+}
+
+/** Distance along a ray to the first wall (tile DDA). */
+export function rayWall(map, px, py, ang, max = 40) {
+ const dx = Math.cos(ang), dy = Math.sin(ang)
+ let mx = px | 0, my = py | 0
+ const ddx = Math.abs(1 / (dx || 1e-9)), ddy = Math.abs(1 / (dy || 1e-9))
+ const sx = dx < 0 ? -1 : 1, sy = dy < 0 ? -1 : 1
+ let sdx = dx < 0 ? (px - mx) * ddx : (mx + 1 - px) * ddx
+ let sdy = dy < 0 ? (py - my) * ddy : (my + 1 - py) * ddy
+ let d = 0
+ while (d < max) {
+ if (sdx < sdy) { d = sdx; sdx += ddx; mx += sx } else { d = sdy; sdy += ddy; my += sy }
+ if (isWall(map, mx, my)) return d
+ }
+ return max
+}
+
+export const lineOfSight = (map, ax, ay, bx, by) => {
+ const d = Math.hypot(bx - ax, by - ay)
+ return d < 1e-6 || rayWall(map, ax, ay, Math.atan2(by - ay, bx - ax), d + 0.01) >= d
+}
+
+/** Waypoint bearing: follow the flood field from `from` toward the cell the field was grown from. */
+function routeToward(map, field, fx, fy, steps = 2) {
+ let x = fx | 0, y = fy | 0
+ const path = [[x, y]]
+ for (let i = 0; i < 64; i++) {
+ const d = field[y * map.w + x]
+ if (d <= 0) break
+ let best = null
+ for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
+ const nd = isWall(map, x + dx, y + dy) ? -1 : field[(y + dy) * map.w + (x + dx)]
+ if (nd >= 0 && nd < d && (!best || nd < best.d)) best = { x: x + dx, y: y + dy, d: nd }
+ }
+ if (!best) break
+ x = best.x; y = best.y
+ path.push([x, y])
+ }
+ // Aim at the farthest of the next few cells that is still in a straight clear line.
+ let aim = path[Math.min(1, path.length - 1)]
+ for (let i = Math.min(steps + 2, path.length - 1); i >= 1; i--) {
+ if (lineOfSight(map, fx, fy, path[i][0] + 0.5, path[i][1] + 0.5)) { aim = path[i]; break }
+ }
+ return { path, aim: { x: aim[0] + 0.5, y: aim[1] + 0.5 } }
+}
+
+export function createWorld(cfg, waveNo = 1, carry = null, life = 0) {
+ const parsed = parseMap(cfg.map)
+ const map = parsed.ok ? parsed : parseMap(DEFAULT_MAP)
+ const seed = (Number(cfg.seed) || 7) + waveNo * 101 + life * 7919
+ return {
+ map, mapError: parsed.ok ? null : parsed.error,
+ rng: mulberry32(seed),
+ step: 0, time: 0, waveNo,
+ need: Math.round(cfg.kills + 4 * (waveNo - 1)),
+ maxAlive: Math.round(cfg.demons + (waveNo - 1)),
+ demonSpeed: cfg.demonSpeed * (1 + 0.12 * (waveNo - 1)),
+ status: 'playing', statusAt: 0,
+ player: {
+ x: map.start.x, y: map.start.y, a: 0, hp: carry ? clamp(carry.hp + 30, 0, 100) : 100,
+ ammo: carry ? carry.ammo + 20 : cfg.ammo, kills: 0, cooldown: 0, hurtAt: -99, moving: false,
+ },
+ demons: [], nextDemonId: 1, spawnTimer: 0.4,
+ pickups: map.pickups.map((p, i) => ({ id: i + 1, ...p, respawn: 0 })),
+ totals: { shots: 0, hits: 0, kills: 0, deaths: 0, damage: 0 },
+ field: null, fieldCell: -1, events: [],
+ }
+}
+
+export function spawnDemon(world, cfg, at = null) {
+ const { map, player } = world
+ let spot = at
+ if (!spot) {
+ // The spawn that is farthest from the marine and, if possible, out of sight.
+ const ranked = map.spawns.map((s) => ({ s, d: Math.hypot(s.x - player.x, s.y - player.y), seen: lineOfSight(map, s.x, s.y, player.x, player.y) }))
+ .sort((a, b) => (a.seen - b.seen) || (b.d - a.d))
+ spot = ranked[Math.floor(world.rng() * Math.min(2, ranked.length))].s
+ }
+ if (isWall(map, spot.x, spot.y)) return null
+ const d = { id: world.nextDemonId++, x: spot.x + (world.rng() - 0.5) * 0.3, y: spot.y + (world.rng() - 0.5) * 0.3, hp: cfg.demonHealth, pace: 0.88 + world.rng() * 0.24, bite: 0, hurt: 0, state: 'walk' }
+ world.demons.push(d)
+ world.events.push({ e: 'spawn', id: d.id, x: d.x, y: d.y })
+ return d
+}
+
+function moveCircle(map, o, dx, dy, r) {
+ const nx = o.x + dx
+ if (!isWall(map, nx + Math.sign(dx) * r, o.y - r * 0.7) && !isWall(map, nx + Math.sign(dx) * r, o.y + r * 0.7)) o.x = nx
+ const ny = o.y + dy
+ if (!isWall(map, o.x - r * 0.7, ny + Math.sign(dy) * r) && !isWall(map, o.x + r * 0.7, ny + Math.sign(dy) * r)) o.y = ny
+}
+
+/** What a shot along the current facing would hit right now: { demon, dist } or { wall: dist }. */
+export function aimHit(world) {
+ const { map, player } = world
+ const wall = rayWall(map, player.x, player.y, player.a)
+ let best = null
+ for (const d of world.demons) {
+ if (d.state === 'dead') continue
+ const dist = Math.hypot(d.x - player.x, d.y - player.y)
+ if (dist > wall + 0.3) continue
+ const off = Math.abs(normDeg((Math.atan2(d.y - player.y, d.x - player.x) - player.a) / DEG))
+ const half = Math.atan2(0.34, Math.max(0.3, dist)) / DEG
+ if (off <= half && (!best || dist < best.dist) && lineOfSight(map, player.x, player.y, d.x, d.y)) best = { demon: d, dist }
+ }
+ return best ?? { wall }
+}
+
+/**
+ * What Jev gets to read. Everything a player could know: the HUD, what is in view, what it hears,
+ * distances to walls, and the automap route. Bearings are degrees off the crosshair, negative = left.
+ */
+export function observe(world, cfg) {
+ const { map, player } = world
+ const bearingTo = (x, y) => normDeg((Math.atan2(y - player.y, x - player.x) - player.a) / DEG)
+ const seen = [], heard = []
+ for (const d of world.demons) {
+ if (d.state === 'dead') continue
+ const dist = Math.hypot(d.x - player.x, d.y - player.y)
+ const b = bearingTo(d.x, d.y)
+ if (Math.abs(b) <= FOV_DEG / 2 + 4 && lineOfSight(map, player.x, player.y, d.x, d.y)) seen.push({ id: d.id, b, dist, biting: d.state === 'attack' })
+ else if (dist < 9) heard.push({ id: d.id, b, dist })
+ }
+ seen.sort((a, b) => a.dist - b.dist); heard.sort((a, b) => a.dist - b.dist)
+ const walls = { ahead: rayWall(map, player.x, player.y, player.a), left: rayWall(map, player.x, player.y, player.a - Math.PI / 2), right: rayWall(map, player.x, player.y, player.a + Math.PI / 2), behind: rayWall(map, player.x, player.y, player.a + Math.PI) }
+ const hit = aimHit(world)
+
+ // Route: to a medkit when hurt, to ammo when dry, else to the nearest demon by walking distance.
+ const want = player.hp < 40 ? 'medkit' : player.ammo < 15 ? 'ammo' : 'demon'
+ let goal = null
+ if (want !== 'demon') {
+ const field = flood(map, player.x | 0, player.y | 0)
+ const live = world.pickups.filter((p) => p.kind === want && p.respawn <= 0).map((p) => ({ p, d: field[(p.y | 0) * map.w + (p.x | 0)] })).filter((o) => o.d >= 0).sort((a, b) => a.d - b.d)
+ if (live.length) goal = { kind: want, x: live[0].p.x, y: live[0].p.y, steps: live[0].d }
+ }
+ if (!goal) {
+ const field = flood(map, player.x | 0, player.y | 0)
+ const live = world.demons.filter((d) => d.state !== 'dead').map((d) => ({ d, steps: field[(d.y | 0) * map.w + (d.x | 0)] })).filter((o) => o.steps >= 0).sort((a, b) => a.steps - b.steps)
+ if (live.length) goal = { kind: 'demon', x: live[0].d.x, y: live[0].d.y, steps: live[0].steps }
+ }
+ let route = null
+ if (goal) {
+ const r = routeToward(map, flood(map, goal.x | 0, goal.y | 0), player.x, player.y)
+ route = { kind: goal.kind, steps: goal.steps, b: bearingTo(r.aim.x, r.aim.y), path: r.path.slice(0, 24) }
+ }
+
+ const per = (name) => Math.abs(TURN_RATE[name] * cfg.tickMs / 1000)
+ const f1 = (n) => n.toFixed(1), sg = (n) => `${n >= 0 ? '+' : '-'}${Math.abs(n).toFixed(0)}`
+ const lines = [
+ `You are the marine in a first-person arena shooter. ${cfg.style}`,
+ `wave ${world.waveNo} kills ${player.kills}/${world.need} health ${Math.round(player.hp)}/100 ammo ${player.ammo}`,
+ `walls: ahead ${f1(walls.ahead)} left ${f1(walls.left)} right ${f1(walls.right)} behind ${f1(walls.behind)}`,
+ `one decision turns you: HARD ${per('LEFT_HARD').toFixed(0)} deg, normal ${per('LEFT').toFixed(0)} deg, FINE ${per('LEFT_FINE').toFixed(0)} deg`,
+ seen.length ? 'demons in sight (bearing in degrees off your crosshair, negative is left):' : 'demons in sight: none',
+ ...seen.slice(0, 6).map((s) => ` demon#${s.id} bearing ${sg(s.b)} distance ${f1(s.dist)}${s.biting ? ' BITING YOU' : ''}`),
+ heard.length ? `heard but not seen: demon#${heard[0].id} bearing ${sg(heard[0].b)} distance ${f1(heard[0].dist)}` : 'heard but not seen: nothing',
+ route ? `route to nearest ${route.kind}: bearing ${sg(route.b)} steps ${route.steps}` : 'route: none',
+ hit.demon ? `crosshair on: demon#${hit.demon.id} distance ${f1(hit.dist)}` : 'crosshair on: nothing',
+ ]
+ return { text: lines.join('\n'), seen, heard, walls, route, crosshair: hit.demon ? hit.demon.id : null }
+}
+
+/** One decision tick: fire at the instant of deciding, then turn and move through `sub` sub-steps. */
+export function tick(world, cfg, decision, sub = 4) {
+ const { map, player } = world
+ world.events = []
+ world.step++
+ const dt = cfg.tickMs / 1000 / sub
+
+ if (world.status !== 'playing') { world.time += cfg.tickMs / 1000; return world.events }
+
+ // Fire first: the "crosshair on" line Jev read describes this exact instant.
+ player.cooldown = Math.max(0, player.cooldown - 1)
+ if (decision.fire && player.cooldown === 0 && player.ammo > 0) {
+ player.ammo--; player.cooldown = FIRE_COOLDOWN; world.totals.shots++
+ const hit = aimHit(world)
+ const range = hit.demon ? hit.dist : hit.wall
+ const ev = { e: 'shot', x: player.x + Math.cos(player.a) * range, y: player.y + Math.sin(player.a) * range, hit: hit.demon ? hit.demon.id : 0 }
+ if (hit.demon) {
+ world.totals.hits++
+ hit.demon.hp -= 34; hit.demon.hurt = 2
+ if (hit.demon.hp <= 0) { hit.demon.state = 'dead'; player.kills++; world.totals.kills++; ev.kill = true; player.ammo = Math.min(99, player.ammo + 2) }
+ }
+ world.events.push(ev)
+ } else if (decision.fire && player.ammo <= 0 && player.cooldown === 0) { player.cooldown = FIRE_COOLDOWN; world.events.push({ e: 'click' }) }
+
+ const turnRate = (TURN_RATE[decision.turn] ?? 0) * DEG
+ const speed = MOVE_SPEED[decision.move] ?? 0
+ player.moving = speed > 0
+ for (let i = 0; i < sub; i++) {
+ player.a += turnRate * dt
+ let mx = 0, my = 0
+ if (decision.move === 'FORWARD') { mx = Math.cos(player.a); my = Math.sin(player.a) }
+ else if (decision.move === 'BACK') { mx = -Math.cos(player.a); my = -Math.sin(player.a) }
+ else if (decision.move === 'STRAFE_LEFT') { mx = Math.sin(player.a); my = -Math.cos(player.a) }
+ else if (decision.move === 'STRAFE_RIGHT') { mx = -Math.sin(player.a); my = Math.cos(player.a) }
+ moveCircle(map, player, mx * speed * dt, my * speed * dt, 0.22)
+
+ // Demons chase along a flood field grown from the marine's cell.
+ const cell = (player.y | 0) * map.w + (player.x | 0)
+ if (cell !== world.fieldCell) { world.field = flood(map, player.x | 0, player.y | 0); world.fieldCell = cell }
+ for (const d of world.demons) {
+ if (d.state === 'dead') continue
+ const dist = Math.hypot(player.x - d.x, player.y - d.y)
+ d.bite = Math.max(0, d.bite - dt)
+ if (dist < 0.85) {
+ d.state = 'attack'
+ if (d.bite === 0) { d.bite = 0.5; player.hp -= cfg.demonDamage; player.hurtAt = world.step; world.totals.damage += cfg.demonDamage; world.events.push({ e: 'bite', id: d.id }) }
+ continue
+ }
+ d.state = 'walk'
+ let tx = player.x, ty = player.y
+ if (!(dist < 6 && lineOfSight(map, d.x, d.y, player.x, player.y))) {
+ const r = routeToward(map, world.field, d.x, d.y, 1)
+ tx = r.aim.x; ty = r.aim.y
+ }
+ const len = Math.hypot(tx - d.x, ty - d.y) || 1
+ const v = world.demonSpeed * d.pace * (d.hurt > 0 ? 0.5 : 1) * dt
+ // Demons weave side to side as they charge. The faster they are, the faster they cross the
+ // crosshair, so a marine that decides only ~9 times a second starts to miss. That is the dial.
+ const ux = (tx - d.x) / len, uy = (ty - d.y) / len
+ const weave = Math.sin(world.time * 5.2 * d.pace + d.id * 1.7) * 0.8
+ moveCircle(map, d, (ux - uy * weave) * v, (uy + ux * weave) * v, 0.28)
+ }
+ // Demons shoulder each other apart so a pack does not stack into one sprite.
+ for (let a = 0; a < world.demons.length; a++) for (let b = a + 1; b < world.demons.length; b++) {
+ const A = world.demons[a], B = world.demons[b]
+ if (A.state === 'dead' || B.state === 'dead') continue
+ const dx = B.x - A.x, dy = B.y - A.y, dd = Math.hypot(dx, dy)
+ if (dd > 0 && dd < 0.6) { const push = (0.6 - dd) / 2 / dd; moveCircle(map, A, -dx * push, -dy * push, 0.28); moveCircle(map, B, dx * push, dy * push, 0.28) }
+ }
+ }
+ for (const d of world.demons) if (d.hurt > 0) d.hurt--
+ world.demons = world.demons.filter((d) => d.state !== 'dead')
+ player.a = normDeg(player.a / DEG) * DEG
+
+ // Pickups.
+ for (const p of world.pickups) {
+ if (p.respawn > 0) { p.respawn -= cfg.tickMs / 1000; continue }
+ if (Math.hypot(p.x - player.x, p.y - player.y) > 0.6) continue
+ if (p.kind === 'medkit' && player.hp < 100) { player.hp = Math.min(100, player.hp + 35); p.respawn = p.once ? 1e9 : 14; world.events.push({ e: 'pickup', kind: 'medkit' }) }
+ if (p.kind === 'ammo' && player.ammo < 99) { player.ammo = Math.min(99, player.ammo + 20); p.respawn = p.once ? 1e9 : 12; world.events.push({ e: 'pickup', kind: 'ammo' }) }
+ }
+
+ // Keep the pack topped up until the wave's kill count is met.
+ world.spawnTimer -= cfg.tickMs / 1000
+ const remaining = world.need - player.kills
+ if (world.spawnTimer <= 0 && world.demons.length < Math.min(world.maxAlive, remaining)) { spawnDemon(world, cfg); world.spawnTimer = 1.1 }
+
+ world.time += cfg.tickMs / 1000
+ if (player.hp <= 0) { player.hp = 0; world.status = 'dead'; world.statusAt = world.step; world.totals.deaths++; world.events.push({ e: 'dead' }) }
+ else if (player.kills >= world.need) { world.status = 'cleared'; world.statusAt = world.step; world.events.push({ e: 'cleared' }) }
+ return world.events
+}
diff --git a/store/agents/jev-fps/viewer/studio.css b/store/agents/jev-fps/viewer/studio.css
new file mode 100644
index 000000000..d4368d07a
--- /dev/null
+++ b/store/agents/jev-fps/viewer/studio.css
@@ -0,0 +1,26 @@
+/* Jev FPS — red accent over the shared base. */
+:root { --accent: #f87171; --accent2: #b91c1c; }
+
+.stat.big span { color: var(--accent); }
+#s-wave { color: var(--warn); } #s-kills { color: var(--ok); } #s-deaths { color: var(--bad); } #s-best { color: var(--cyan); }
+
+#stage { gap: 10px; }
+.canvas-wrap { min-height: 300px; background: #000; cursor: crosshair; }
+#scene { image-rendering: pixelated; outline: none; }
+#scene:focus-visible { box-shadow: inset 0 0 0 2px var(--accent); }
+
+.toolbar { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; padding: 9px 12px; flex: none; }
+.toolbar .tools { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
+.toolbar .lab { color: var(--dim); font-size: 11px; text-transform: uppercase; letter-spacing: 1px; margin-right: 2px; }
+.toolbar .slider { display: flex; align-items: center; gap: 8px; color: var(--dim); font-size: 12px; white-space: nowrap; }
+.toolbar .slider input { width: 130px; }
+.toolbar .slider b { color: var(--warn); min-width: 28px; font-variant-numeric: tabular-nums; }
+.toolbar .hint { color: var(--dim); font-size: 11.5px; flex: 1 1 260px; line-height: 1.7; }
+.toolbar .hint kbd { margin: 0 1px; }
+
+.statetext { margin: 0; font: 11px/1.5 var(--mono); color: #cbd5e1; white-space: pre-wrap; word-break: break-word; max-height: 232px; overflow: auto; }
+.statetext .hl { color: var(--warn); } .statetext .bad { color: var(--bad); } .statetext .ok { color: var(--ok); }
+#driver.human { color: var(--warn); border-color: var(--warn); }
+
+#feed { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; max-height: 190px; overflow-y: auto; font-size: 11.5px; color: var(--dim); }
+#feed li b { color: var(--ink); } #feed li.kill b { color: var(--ok); } #feed li.dead b { color: var(--bad); } #feed li.wave b { color: var(--warn); }
diff --git a/store/agents/jev-fps/viewer/studio.js b/store/agents/jev-fps/viewer/studio.js
new file mode 100644
index 000000000..7e742450e
--- /dev/null
+++ b/store/agents/jev-fps/viewer/studio.js
@@ -0,0 +1,513 @@
+// Jev FPS pane — a software raycaster. The server runs the fight and streams one frame per Jev
+// decision (~9 a second); this file renders at 60 fps, easing between frames, into a low-res pixel
+// buffer (textured walls, floor and ceiling, billboard sprites, particles) that is scaled up crisp,
+// then draws the HUD, the minimap and Jev's lit-up "keys" on top at full resolution.
+'use strict'
+
+const $ = (id) => document.getElementById(id)
+const scene = $('scene'), wrap = $('wrap')
+const ctx = scene.getContext('2d')
+const low = document.createElement('canvas')
+const lctx = low.getContext('2d')
+
+// ---------------------------------------------------------------- state from the server
+let map = ['#'], mapW = 1, mapH = 1, mapRev = -1
+let prev = null, next = null, nextAt = 0
+let tool = 'spawn'
+let paused = false
+const fx = { flash: 0, recoil: 0, hurt: 0, shake: 0, pickup: 0, pickupKind: '', tracer: null, banner: null }
+const particles = [] // world-space: x, y, z (0 floor..1 ceiling), vx, vy, vz, life, max, color
+const corpses = [] // { x, y, t }
+const feed = []
+
+// ---------------------------------------------------------------- textures (all procedural)
+const TEX = 64, SHADES = 24, FOG = [6, 7, 14]
+function rnd(seed) { let a = seed; return () => { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296 } }
+function paint(draw, size = TEX) {
+ const c = document.createElement('canvas'); c.width = c.height = size
+ const g = c.getContext('2d'); draw(g, size)
+ return new Uint32Array(g.getImageData(0, 0, size, size).data.buffer.slice(0))
+}
+function speckle(g, r, n, colors, size = TEX) { for (let i = 0; i < n; i++) { g.fillStyle = colors[(r() * colors.length) | 0]; g.fillRect((r() * size) | 0, (r() * size) | 0, 1 + ((r() * 2) | 0), 1) } }
+/** A texture at every fog level, so the inner loops only look colours up. Alpha is kept. */
+function shadeSet(px) {
+ const out = []
+ for (let s = 0; s < SHADES; s++) {
+ const f = Math.pow(1 - s / (SHADES - 1), 1.35), a = new Uint32Array(px.length)
+ for (let i = 0; i < px.length; i++) {
+ const c = px[i], r = c & 255, gg = (c >>> 8) & 255, b = (c >>> 16) & 255
+ a[i] = ((c >>> 24) << 24) | (((FOG[2] + (b - FOG[2]) * f) & 255) << 16) | (((FOG[1] + (gg - FOG[1]) * f) & 255) << 8) | ((FOG[0] + (r - FOG[0]) * f) & 255)
+ }
+ out.push(a)
+ }
+ return out
+}
+function whiten(px) { const a = new Uint32Array(px.length); for (let i = 0; i < px.length; i++) a[i] = (px[i] >>> 24) > 128 ? 0xffe8f4ff : 0; return a }
+
+const texStone = paint((g) => {
+ const r = rnd(11); g.fillStyle = '#4a4f5c'; g.fillRect(0, 0, TEX, TEX)
+ for (let row = 0; row < 4; row++) for (let col = -1; col < 3; col++) {
+ const x = col * 32 + (row % 2 ? 16 : 0), y = row * 16, v = 70 + ((r() * 34) | 0)
+ g.fillStyle = `rgb(${v},${v + 4},${v + 14})`; g.fillRect(x + 1, y + 1, 30, 14)
+ g.fillStyle = 'rgba(255,255,255,.10)'; g.fillRect(x + 1, y + 1, 30, 2)
+ g.fillStyle = 'rgba(0,0,0,.28)'; g.fillRect(x + 1, y + 13, 30, 2)
+ }
+ speckle(g, r, 260, ['rgba(0,0,0,.22)', 'rgba(255,255,255,.07)', 'rgba(30,40,70,.25)'])
+})
+const texTech = paint((g) => {
+ const r = rnd(23); g.fillStyle = '#1f2937'; g.fillRect(0, 0, TEX, TEX)
+ for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) {
+ g.fillStyle = '#334155'; g.fillRect(i * 32 + 2, j * 32 + 2, 28, 28)
+ g.fillStyle = 'rgba(255,255,255,.12)'; g.fillRect(i * 32 + 2, j * 32 + 2, 28, 2)
+ g.fillStyle = '#0f172a'; for (const [dx, dy] of [[4, 4], [26, 4], [4, 26], [26, 26]]) g.fillRect(i * 32 + dx, j * 32 + dy, 2, 2)
+ }
+ g.fillStyle = '#0891b2'; g.fillRect(0, 29, TEX, 6); g.fillStyle = '#67e8f9'; g.fillRect(0, 31, TEX, 2)
+ for (let x = 4; x < TEX; x += 12) { g.fillStyle = '#ecfeff'; g.fillRect(x, 31, 5, 2) }
+ speckle(g, r, 120, ['rgba(0,0,0,.25)', 'rgba(148,163,184,.12)'])
+})
+const texHell = paint((g) => {
+ const r = rnd(37); g.fillStyle = '#3b0a0a'; g.fillRect(0, 0, TEX, TEX)
+ for (let row = 0; row < 8; row++) for (let col = -1; col < 5; col++) {
+ const x = col * 16 + (row % 2 ? 8 : 0), y = row * 8, v = 90 + ((r() * 60) | 0)
+ g.fillStyle = `rgb(${v},${(v * 0.2) | 0},${(v * 0.16) | 0})`; g.fillRect(x + 1, y + 1, 14, 6)
+ }
+ g.strokeStyle = '#fb923c'; g.lineWidth = 1.4; g.beginPath(); g.moveTo(8, 0); g.lineTo(14, 14); g.lineTo(9, 27); g.lineTo(20, 40); g.lineTo(15, 64); g.stroke()
+ g.strokeStyle = '#fde047'; g.lineWidth = 0.6; g.beginPath(); g.moveTo(46, 0); g.lineTo(52, 20); g.lineTo(44, 36); g.lineTo(50, 64); g.stroke()
+ speckle(g, r, 160, ['rgba(0,0,0,.3)', 'rgba(251,146,60,.18)'])
+})
+const texFloor = paint((g) => {
+ const r = rnd(51); g.fillStyle = '#2a2622'; g.fillRect(0, 0, TEX, TEX)
+ for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) { const v = 44 + ((r() * 14) | 0); g.fillStyle = `rgb(${v + 6},${v + 2},${v - 2})`; g.fillRect(i * 32 + 1, j * 32 + 1, 30, 30) }
+ speckle(g, r, 420, ['rgba(0,0,0,.25)', 'rgba(255,240,220,.06)', 'rgba(120,20,20,.18)'])
+})
+const texCeil = paint((g) => {
+ const r = rnd(67); g.fillStyle = '#16131c'; g.fillRect(0, 0, TEX, TEX)
+ g.fillStyle = '#221d2c'; for (let i = 0; i < 4; i++) g.fillRect(i * 16 + 1, 0, 14, TEX)
+ g.fillStyle = '#0c0a10'; for (let j = 0; j < TEX; j += 16) g.fillRect(0, j, TEX, 1)
+ speckle(g, r, 200, ['rgba(0,0,0,.3)', 'rgba(167,139,250,.07)'])
+})
+const WALL_SHADES = { '#': shadeSet(texStone), '%': shadeSet(texTech), '=': shadeSet(texHell) }
+const FLOOR_SHADES = shadeSet(texFloor), CEIL_SHADES = shadeSet(texCeil)
+
+function demonArt(pose) {
+ return paint((g) => {
+ const arm = pose === 'a' ? [-2, 3] : pose === 'b' ? [3, -2] : [-9, -9]
+ const leg = pose === 'a' ? [2, -2] : pose === 'b' ? [-2, 2] : [0, 0]
+ const shape = (fill, grow) => {
+ g.fillStyle = fill; g.strokeStyle = fill; g.lineWidth = grow * 2; g.lineJoin = 'round'
+ const blob = (fn) => { g.beginPath(); fn(); g.closePath(); g.fill(); if (grow) g.stroke() }
+ blob(() => g.ellipse(32, 41, 15, 16, 0, 0, 7)) // body
+ blob(() => g.ellipse(32, 21, 12, 11, 0, 0, 7)) // head
+ blob(() => { g.moveTo(22, 15); g.lineTo(13, 2); g.lineTo(27, 11) }) // horns
+ blob(() => { g.moveTo(42, 15); g.lineTo(51, 2); g.lineTo(37, 11) })
+ blob(() => g.rect(22 + leg[0] * 0, 54, 8, 9 + leg[0])) // legs
+ blob(() => g.rect(34, 54, 8, 9 + leg[1]))
+ blob(() => { g.moveTo(18, 32); g.lineTo(7, 42 + arm[0]); g.lineTo(4, 52 + arm[0]); g.lineTo(11, 50 + arm[0]); g.lineTo(21, 40) }) // arms
+ blob(() => { g.moveTo(46, 32); g.lineTo(57, 42 + arm[1]); g.lineTo(60, 52 + arm[1]); g.lineTo(53, 50 + arm[1]); g.lineTo(43, 40) })
+ }
+ shape('#0b0306', 1.6)
+ const grad = g.createLinearGradient(0, 8, 0, 60); grad.addColorStop(0, '#dc2626'); grad.addColorStop(1, '#7f1d1d')
+ shape(grad, 0)
+ g.fillStyle = '#fecaca'; g.globalAlpha = 0.18; g.beginPath(); g.ellipse(27, 36, 5, 8, -0.3, 0, 7); g.fill(); g.globalAlpha = 1
+ g.fillStyle = '#f5f5f4'; for (const [a, b, c] of [[22, 15, 13], [42, 15, 51]]) { g.beginPath(); g.moveTo(a, b); g.lineTo(c, 2); g.lineTo(a + (c < a ? 5 : -5), 11); g.closePath(); g.fill() }
+ g.fillStyle = '#fde047'; g.shadowColor = '#f97316'; g.shadowBlur = 5
+ g.beginPath(); g.ellipse(27, 19, 3.2, 2.4, 0.35, 0, 7); g.fill(); g.beginPath(); g.ellipse(37, 19, 3.2, 2.4, -0.35, 0, 7); g.fill(); g.shadowBlur = 0
+ g.fillStyle = '#111'; g.fillRect(26.4, 18.2, 1.6, 2); g.fillRect(36.4, 18.2, 1.6, 2)
+ const open = pose === 'atk' ? 7 : 3
+ g.fillStyle = '#1c0408'; g.fillRect(25, 25, 14, open)
+ g.fillStyle = '#fafaf9'; for (let x = 26; x < 38; x += 3) { g.beginPath(); g.moveTo(x, 25); g.lineTo(x + 1.5, 25 + Math.min(3, open)); g.lineTo(x + 3, 25); g.fill() }
+ g.fillStyle = '#e7e5e4'; for (const [x, y] of [[4, 52 + arm[0]], [60, 52 + arm[1]]]) g.fillRect(x - 2, y, 4, 3)
+ })
+}
+const pickupArt = (kind) => paint((g) => {
+ g.fillStyle = '#0b0306'; g.fillRect(14, 28, 36, 30)
+ if (kind === 'medkit') { g.fillStyle = '#f8fafc'; g.fillRect(16, 30, 32, 26); g.fillStyle = '#dc2626'; g.fillRect(28, 33, 8, 20); g.fillRect(22, 39, 20, 8) }
+ else { g.fillStyle = '#3f6212'; g.fillRect(16, 30, 32, 26); g.fillStyle = '#a3e635'; g.fillRect(16, 30, 32, 4); g.fillStyle = '#facc15'; for (let x = 20; x < 46; x += 7) { g.fillRect(x, 40, 4, 12); g.fillStyle = '#b45309'; g.fillRect(x, 50, 4, 3); g.fillStyle = '#facc15' } }
+})
+const demonPx = { a: demonArt('a'), b: demonArt('b'), atk: demonArt('atk') }
+const SPR = {
+ a: shadeSet(demonPx.a), b: shadeSet(demonPx.b), atk: shadeSet(demonPx.atk), white: [whiten(demonPx.a)],
+ medkit: shadeSet(pickupArt('medkit')), ammo: shadeSet(pickupArt('ammo')),
+}
+
+// ---------------------------------------------------------------- the raycaster
+const PLANE = Math.tan((66 / 2) * Math.PI / 180)
+let W = 480, H = 270, img = null, buf = null, zbuf = new Float32Array(W)
+const wallAt = (x, y) => x < 0 || y < 0 || x >= mapW || y >= mapH ? '#' : map[y][x]
+const solid = (c) => c === '#' || c === '%' || c === '='
+const shadeOf = (d) => { const s = (d * 1.45) | 0; return s >= SHADES ? SHADES - 1 : s }
+
+function resize() {
+ const r = wrap.getBoundingClientRect(), dpr = Math.min(2, window.devicePixelRatio || 1)
+ scene.width = Math.max(320, Math.round(r.width * dpr)); scene.height = Math.max(180, Math.round(r.height * dpr))
+ H = 270; W = Math.max(320, Math.min(640, Math.round((H * r.width) / Math.max(1, r.height) / 2) * 2))
+ low.width = W; low.height = H
+ img = lctx.createImageData(W, H); buf = new Uint32Array(img.data.buffer); zbuf = new Float32Array(W)
+}
+new ResizeObserver(resize).observe(wrap)
+
+function render3d(px, py, pa, horizon, time) {
+ const dirX = Math.cos(pa), dirY = Math.sin(pa), plX = -dirY * PLANE, plY = dirX * PLANE
+ const proj = W / (2 * PLANE), camZ = proj / 2
+ // floor and ceiling, one row at a time
+ const rx0 = dirX - plX, ry0 = dirY - plY, rx1 = dirX + plX, ry1 = dirY + plY
+ for (let y = 0; y < H; y++) {
+ const p = y - horizon
+ if (p === 0) { buf.fill(0xff0e0706, y * W, y * W + W); continue }
+ const rowDist = camZ / Math.abs(p), tex = (p > 0 ? FLOOR_SHADES : CEIL_SHADES)[shadeOf(rowDist)]
+ const sx = (rowDist * (rx1 - rx0)) / W, sy = (rowDist * (ry1 - ry0)) / W
+ let fxp = px + rowDist * rx0, fyp = py + rowDist * ry0
+ const o = y * W
+ for (let x = 0; x < W; x++) {
+ buf[o + x] = tex[((((fyp - Math.floor(fyp)) * TEX) & 63) << 6) | (((fxp - Math.floor(fxp)) * TEX) & 63)]
+ fxp += sx; fyp += sy
+ }
+ }
+ // walls
+ for (let x = 0; x < W; x++) {
+ const cam = (2 * x) / W - 1, rdx = dirX + plX * cam, rdy = dirY + plY * cam
+ let mx = px | 0, my = py | 0
+ const ddx = Math.abs(1 / (rdx || 1e-9)), ddy = Math.abs(1 / (rdy || 1e-9))
+ const stx = rdx < 0 ? -1 : 1, sty = rdy < 0 ? -1 : 1
+ let sdx = rdx < 0 ? (px - mx) * ddx : (mx + 1 - px) * ddx, sdy = rdy < 0 ? (py - my) * ddy : (my + 1 - py) * ddy
+ let side = 0, tile = '#'
+ for (let i = 0; i < 96; i++) {
+ if (sdx < sdy) { sdx += ddx; mx += stx; side = 0 } else { sdy += ddy; my += sty; side = 1 }
+ tile = wallAt(mx, my); if (solid(tile)) break
+ }
+ const perp = Math.max(0.02, side === 0 ? sdx - ddx : sdy - ddy)
+ zbuf[x] = perp
+ const lineH = proj / perp
+ let u = side === 0 ? py + perp * rdy : px + perp * rdx; u -= Math.floor(u)
+ let tx = (u * TEX) | 0; if ((side === 0 && rdx > 0) || (side === 1 && rdy < 0)) tx = TEX - 1 - tx
+ const tex = (WALL_SHADES[tile] ?? WALL_SHADES['#'])[Math.min(SHADES - 1, shadeOf(perp) + (side ? 3 : 0))]
+ const top = horizon - lineH / 2, y0 = Math.max(0, Math.ceil(top)), y1 = Math.min(H - 1, Math.floor(top + lineH))
+ const stepT = TEX / lineH
+ let tp = (y0 - top) * stepT
+ for (let y = y0; y <= y1; y++) { buf[y * W + x] = tex[(((tp | 0) & 63) << 6) | tx]; tp += stepT }
+ }
+ return { dirX, dirY, plX, plY, proj }
+}
+
+function drawSprite(cam, px, py, sx, sy, shades, heightTiles, horizon, liftTiles = 0, squash = 1) {
+ const dx = sx - px, dy = sy - py
+ const inv = 1 / (cam.plX * cam.dirY - cam.dirX * cam.plY)
+ const tX = inv * (cam.dirY * dx - cam.dirX * dy), tY = inv * (-cam.plY * dx + cam.plX * dy)
+ if (tY < 0.18) return null
+ const unit = cam.proj / tY, hgt = unit * heightTiles * squash, wid = unit * heightTiles
+ const cx = (W / 2) * (1 + tX / tY), floorY = horizon + unit / 2 - unit * liftTiles
+ const left = cx - wid / 2, top = floorY - hgt
+ const x0 = Math.max(0, Math.ceil(left)), x1 = Math.min(W - 1, Math.floor(left + wid))
+ const y0 = Math.max(0, Math.ceil(top)), y1 = Math.min(H - 1, Math.floor(floorY))
+ const tex = shades[Math.min(shades.length - 1, shadeOf(tY))]
+ for (let x = x0; x <= x1; x++) {
+ if (tY >= zbuf[x]) continue
+ const tx = Math.min(63, ((x - left) / wid * TEX) | 0)
+ for (let y = y0; y <= y1; y++) {
+ const c = tex[(Math.min(63, ((y - top) / hgt * TEX) | 0) << 6) | tx]
+ if ((c >>> 24) > 128) buf[y * W + x] = c
+ }
+ }
+ return { cx, cy: floorY - hgt / 2, size: hgt, depth: tY }
+}
+
+function drawParticles(cam, px, py, horizon) {
+ const inv = 1 / (cam.plX * cam.dirY - cam.dirX * cam.plY)
+ for (const p of particles) {
+ const dx = p.x - px, dy = p.y - py
+ const tX = inv * (cam.dirY * dx - cam.dirX * dy), tY = inv * (-cam.plY * dx + cam.plX * dy)
+ if (tY < 0.15) continue
+ const x = ((W / 2) * (1 + tX / tY)) | 0, y = (horizon + (0.5 - p.z) * (cam.proj / tY)) | 0
+ if (x < 1 || x >= W - 1 || y < 1 || y >= H - 1 || tY >= zbuf[x]) continue
+ const s = tY < 2.5 ? 2 : 1
+ for (let j = 0; j < s; j++) for (let i = 0; i < s; i++) buf[(y + j) * W + x + i] = p.color
+ }
+}
+
+// ---------------------------------------------------------------- effects
+const rand = Math.random
+function burst(x, y, z, n, colors, speed, life) {
+ for (let i = 0; i < n && particles.length < 900; i++) {
+ const a = rand() * 6.283, v = speed * (0.3 + rand())
+ particles.push({ x, y, z, vx: Math.cos(a) * v, vy: Math.sin(a) * v, vz: (rand() - 0.2) * speed * 1.2, life: life * (0.5 + rand() * 0.7), color: colors[(rand() * colors.length) | 0] })
+ }
+}
+const BLOOD = [0xff1c1cdc, 0xff1a1a99, 0xff4040f0, 0xff0c0c70], SPARK = [0xff47ccfa, 0xff9fe8fe, 0xff1590f9], TELE = [0xff5ee5a3, 0xff99f6e4, 0xffffffff], HEAL = [0xff7cf54a, 0xffffffff], SHELL = [0xff15ccfa, 0xffffffff]
+
+function onEvents(f) {
+ for (const ev of f.events || []) {
+ if (ev.e === 'shot') {
+ fx.flash = 1; fx.recoil = 1; fx.shake = Math.max(fx.shake, 0.35)
+ fx.tracer = { x: ev.x, y: ev.y, t: 1 }
+ if (ev.hit) burst(ev.x, ev.y, 0.5, ev.kill ? 46 : 14, BLOOD, ev.kill ? 2.6 : 1.6, 0.7); else burst(ev.x, ev.y, 0.5, 9, SPARK, 1.4, 0.35)
+ if (ev.kill) { corpses.push({ x: ev.x, y: ev.y, t: 1 }); log('kill', `<b>Kill</b> · demon#${ev.hit} · ${f.player.kills}/${f.need}`) }
+ sfx(ev.kill ? 'kill' : 'shot')
+ } else if (ev.e === 'bite') { fx.hurt = 1; fx.shake = 1; sfx('bite') }
+ else if (ev.e === 'spawn') burst(ev.x, ev.y, 0.45, 26, TELE, 1.2, 0.8)
+ else if (ev.e === 'pickup') { fx.pickup = 1; fx.pickupKind = ev.kind; burst(f.player.x, f.player.y, 0.3, 16, ev.kind === 'medkit' ? HEAL : SHELL, 1, 0.6); log('', `<b>Picked up</b> ${ev.kind}`); sfx('pickup') }
+ else if (ev.e === 'dead') { log('dead', `<b>Jev died</b> on wave ${f.wave} with ${f.player.kills} kills`); sfx('dead') }
+ else if (ev.e === 'cleared') { log('wave', `<b>Wave ${f.wave} cleared</b> · next one is faster`); sfx('pickup') }
+ else if (ev.e === 'click') sfx('click')
+ }
+}
+function log(cls, html) {
+ feed.push({ cls, html }); if (feed.length > 60) feed.shift()
+ const ul = $('feed'), li = document.createElement('li'); li.className = cls; li.innerHTML = html
+ ul.prepend(li); while (ul.children.length > 40) ul.lastChild.remove()
+}
+
+// ---------------------------------------------------------------- sound (off until asked for)
+let audio = null
+$('sound').onclick = () => {
+ if (audio) { audio.close(); audio = null } else audio = new (window.AudioContext || window.webkitAudioContext)()
+ $('sound').textContent = audio ? 'Sound on' : 'Sound off'; $('sound').classList.toggle('on', !!audio)
+}
+function sfx(kind) {
+ if (!audio) return
+ const t = audio.currentTime, g = audio.createGain(); g.connect(audio.destination)
+ const tone = (type, f0, f1, dur, vol) => { const o = audio.createOscillator(); o.type = type; o.frequency.setValueAtTime(f0, t); o.frequency.exponentialRampToValueAtTime(Math.max(20, f1), t + dur); g.gain.setValueAtTime(vol, t); g.gain.exponentialRampToValueAtTime(0.001, t + dur); o.connect(g); o.start(t); o.stop(t + dur) }
+ if (kind === 'shot') tone('square', 190, 40, 0.13, 0.16)
+ else if (kind === 'kill') tone('sawtooth', 260, 30, 0.4, 0.2)
+ else if (kind === 'bite') tone('sawtooth', 90, 50, 0.2, 0.22)
+ else if (kind === 'pickup') tone('triangle', 520, 1040, 0.16, 0.14)
+ else if (kind === 'dead') tone('sawtooth', 200, 22, 1.1, 0.25)
+ else tone('square', 900, 700, 0.04, 0.06)
+}
+
+// ---------------------------------------------------------------- HUD drawing (full resolution)
+const lerp = (a, b, t) => a + (b - a) * t
+const lerpAngle = (a, b, t) => { let d = ((b - a + Math.PI) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI) - Math.PI; return a + d * t }
+let miniRect = null
+const THREAT = [['CALM', '#34d399'], ['WATCHFUL', '#fbbf24'], ['PRESSED', '#fb923c'], ['CRITICAL', '#fb7185']]
+
+function drawWeapon(time, moving) {
+ const bob = moving ? Math.sin(time * 0.011) * 6 : Math.sin(time * 0.002) * 1.5, dip = moving ? Math.abs(Math.cos(time * 0.011)) * 5 : 0
+ const cx = Math.round(W / 2 + bob), by = Math.round(H - 26 + dip + fx.recoil * 22)
+ const R = (c, x, y, w, h) => { lctx.fillStyle = c; lctx.fillRect(cx + x, by + y, w, h) }
+ if (fx.flash > 0.2) {
+ lctx.save(); lctx.translate(cx, by - 84); lctx.rotate(time * 0.05)
+ lctx.fillStyle = '#fff7c2'; lctx.beginPath(); for (let i = 0; i < 14; i++) { const r = i % 2 ? 9 : 30 * fx.flash + 8, an = (i / 14) * 6.283; lctx.lineTo(Math.cos(an) * r, Math.sin(an) * r) } lctx.fill()
+ lctx.fillStyle = '#fb923c'; lctx.beginPath(); lctx.arc(0, 0, 9, 0, 7); lctx.fill()
+ lctx.fillStyle = '#fff'; lctx.beginPath(); lctx.arc(0, 0, 4, 0, 7); lctx.fill(); lctx.restore()
+ }
+ // barrels (perspective: narrow at the muzzle, wide at the breech)
+ for (let i = 0; i < 40; i++) { const w = 9 + i * 0.36, y = -80 + i * 2; R('#08080a', -w - 2, y, (w + 2) * 2, 2); R('#52525b', -w, y, w - 1, 2); R('#3f3f46', 1, y, w - 1, 2); R('#a1a1aa', -w + 1, y, 2, 2); R('#71717a', 2, y, 2, 2) }
+ R('#08080a', -11, -82, 22, 3); R('#18181b', -8, -81, 6, 3); R('#18181b', 2, -81, 6, 3)
+ // wooden fore-end and the two hands
+ R('#08080a', -27, -30, 54, 30); R('#7c2d12', -25, -28, 50, 26); R('#9a3412', -25, -28, 50, 4); R('#5b1f0b', -25, -8, 50, 6)
+ for (let i = 0; i < 5; i++) R('#5b1f0b', -21 + i * 10, -22, 2, 12)
+ R('#08080a', -44, -8, 30, 56); R('#d6a77a', -42, -6, 26, 54); R('#b8865a', -42, 6, 26, 4); R('#b8865a', -42, 18, 26, 4); R('#e8c19c', -42, -6, 5, 54)
+ R('#08080a', 18, 2, 30, 46); R('#d6a77a', 20, 4, 26, 44); R('#b8865a', 20, 16, 26, 4); R('#b8865a', 20, 28, 26, 4)
+}
+
+function keycap(x, y, w, h, label, p, on, color) {
+ ctx.fillStyle = 'rgba(8,9,14,.72)'; ctx.strokeStyle = on ? color : 'rgba(255,255,255,.22)'; ctx.lineWidth = on ? 2.5 : 1
+ ctx.beginPath(); ctx.roundRect(x, y, w, h, 6); ctx.fill()
+ if (p > 0.01) { ctx.save(); ctx.beginPath(); ctx.roundRect(x, y, w, h, 6); ctx.clip(); ctx.fillStyle = color; ctx.globalAlpha = on ? 0.85 : 0.35; ctx.fillRect(x, y + h * (1 - p), w, h * p); ctx.restore() }
+ ctx.beginPath(); ctx.roundRect(x, y, w, h, 6); ctx.stroke()
+ ctx.fillStyle = on ? '#fff' : 'rgba(255,255,255,.6)'; ctx.font = `700 ${Math.round(h * 0.36)}px ui-monospace,Menlo,monospace`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
+ ctx.fillText(label, x + w / 2, y + h / 2 + 1)
+}
+
+function drawHud(f, p, time) {
+ const cw = scene.width, ch = scene.height, u = Math.max(0.6, Math.min(1.5, ch / 520, cw / 980))
+ const mono = (px, w = 700) => `${w} ${Math.round(px * u)}px ui-monospace,'SF Mono',Menlo,monospace`
+ ctx.textBaseline = 'alphabetic'
+ // damage and pickup washes, low-health pulse
+ if (fx.hurt > 0.02) { const g = ctx.createRadialGradient(cw / 2, ch / 2, ch * 0.25, cw / 2, ch / 2, ch * 0.8); g.addColorStop(0, 'rgba(220,38,38,0)'); g.addColorStop(1, `rgba(220,38,38,${0.75 * fx.hurt})`); ctx.fillStyle = g; ctx.fillRect(0, 0, cw, ch) }
+ if (f.player.hp < 35 && f.status === 'playing') { ctx.fillStyle = `rgba(220,38,38,${0.10 + 0.08 * Math.sin(time * 0.008)})`; ctx.fillRect(0, 0, cw, ch) }
+ if (fx.pickup > 0.02) { ctx.fillStyle = fx.pickupKind === 'medkit' ? `rgba(74,222,128,${0.3 * fx.pickup})` : `rgba(250,204,21,${0.3 * fx.pickup})`; ctx.fillRect(0, 0, cw, ch) }
+ // crosshair
+ const on = f.crosshair != null, cx = cw / 2, cy = ch / 2, r = 9 * u
+ ctx.strokeStyle = on ? '#f87171' : 'rgba(255,255,255,.8)'; ctx.lineWidth = 2 * u; ctx.shadowColor = on ? '#ef4444' : 'transparent'; ctx.shadowBlur = on ? 14 : 0
+ ctx.beginPath(); for (const [ax, ay] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { ctx.moveTo(cx + ax * r * 0.45, cy + ay * r * 0.45); ctx.lineTo(cx + ax * r * 1.5, cy + ay * r * 1.5) } ctx.stroke()
+ if (on) { ctx.beginPath(); ctx.arc(cx, cy, r * 2.1, 0, 7); ctx.stroke() } ctx.shadowBlur = 0
+
+ // bottom status bar
+ const barH = 58 * u, y0 = ch - barH
+ const g = ctx.createLinearGradient(0, y0 - 20 * u, 0, ch); g.addColorStop(0, 'rgba(5,6,10,0)'); g.addColorStop(0.35, 'rgba(5,6,10,.78)'); g.addColorStop(1, 'rgba(5,6,10,.92)'); ctx.fillStyle = g; ctx.fillRect(0, y0 - 20 * u, cw, barH + 20 * u)
+ const cell = (x, label, value, color, frac) => {
+ ctx.textAlign = 'left'; ctx.fillStyle = 'rgba(255,255,255,.5)'; ctx.font = mono(10, 600); ctx.fillText(label, x, y0 + 16 * u)
+ ctx.fillStyle = color; ctx.font = mono(27); ctx.shadowColor = color; ctx.shadowBlur = 10; ctx.fillText(value, x, y0 + 45 * u); ctx.shadowBlur = 0
+ if (frac != null) { ctx.fillStyle = 'rgba(255,255,255,.12)'; ctx.fillRect(x, y0 + 50 * u, 96 * u, 3 * u); ctx.fillStyle = color; ctx.fillRect(x, y0 + 50 * u, 96 * u * Math.max(0, Math.min(1, frac)), 3 * u) }
+ }
+ const right = cw - 18 * u
+ const hp = Math.round(p.hp)
+ cell(right - 330 * u, 'HEALTH', String(hp), hp < 35 ? '#fb7185' : hp < 70 ? '#fbbf24' : '#34d399', hp / 100)
+ cell(right - 215 * u, 'AMMO', String(f.player.ammo), f.player.ammo < 10 ? '#fb7185' : '#fde047', f.player.ammo / 99)
+ cell(right - 100 * u, `WAVE ${f.wave}`, `${f.player.kills}/${f.need}`, '#f87171', f.player.kills / Math.max(1, f.need))
+
+ // Jev's keys: the move choice as W A S D, the turn choice as a seven-step bar, fire as a button
+ const d = f.decision || {}, mv = d.probs?.move || {}, tn = d.probs?.turn || {}, human = f.driver === 'human'
+ const k = 34 * u, gap = 5 * u, kx = 18 * u, ky = ch - barH + 8 * u - k - gap
+ const col = human ? '#fbbf24' : '#a78bfa'
+ keycap(kx + k + gap, ky, k, k, 'W', mv.FORWARD ?? 0, d.move === 'FORWARD', col)
+ keycap(kx, ky + k + gap, k, k, 'A', mv.STRAFE_LEFT ?? 0, d.move === 'STRAFE_LEFT', col)
+ keycap(kx + k + gap, ky + k + gap, k, k, 'S', mv.BACK ?? 0, d.move === 'BACK', col)
+ keycap(kx + 2 * (k + gap), ky + k + gap, k, k, 'D', mv.STRAFE_RIGHT ?? 0, d.move === 'STRAFE_RIGHT', col)
+ const tx0 = kx + 3 * (k + gap) + 14 * u, names = ['LEFT_HARD', 'LEFT', 'LEFT_FINE', 'AHEAD', 'RIGHT_FINE', 'RIGHT', 'RIGHT_HARD'], glyph = ['«', '‹', '·', '↑', '·', '›', '»']
+ names.forEach((n, i) => keycap(tx0 + i * (k * 0.72 + gap), ky + k + gap, k * 0.72, k, glyph[i], tn[n] ?? 0, d.turn === n, col))
+ ctx.textAlign = 'left'; ctx.fillStyle = 'rgba(255,255,255,.55)'; ctx.font = mono(10, 600)
+ ctx.fillText(human ? 'YOU HAVE THE CONTROLS' : "JEV'S KEYS · fill = probability", tx0, ky + k * 0.62)
+ const fxk = tx0 + 7 * (k * 0.72 + gap) + 10 * u
+ keycap(fxk, ky + k + gap, k * 2.1, k, 'FIRE', d.pFire ?? 0, !!d.fire, '#f87171')
+
+ // threat read-out, top left
+ const lv = Math.max(0, Math.min(3, Math.round(d.threat ?? 0))), [tl, tc] = THREAT[lv]
+ ctx.textAlign = 'left'
+ ctx.fillStyle = 'rgba(8,9,14,.7)'; ctx.beginPath(); ctx.roundRect(14 * u, 14 * u, 190 * u, 44 * u, 8); ctx.fill()
+ ctx.fillStyle = 'rgba(255,255,255,.5)'; ctx.font = mono(9.5, 600); ctx.fillText("JEV'S THREAT READ", 24 * u, 30 * u)
+ ctx.fillStyle = tc; ctx.font = mono(16); ctx.fillText(tl, 24 * u, 49 * u)
+ for (let i = 0; i < 4; i++) { ctx.fillStyle = i <= lv ? tc : 'rgba(255,255,255,.15)'; ctx.fillRect((140 + i * 14) * u, 38 * u, 10 * u, 12 * u) }
+
+ drawMinimap(f, p, u)
+
+ // banners
+ if (f.status !== 'playing') {
+ const dead = f.status === 'dead'
+ ctx.fillStyle = dead ? 'rgba(60,4,8,.55)' : 'rgba(4,40,24,.45)'; ctx.fillRect(0, 0, cw, ch)
+ ctx.textAlign = 'center'; ctx.fillStyle = dead ? '#fb7185' : '#34d399'; ctx.shadowColor = ctx.fillStyle; ctx.shadowBlur = 24; ctx.font = mono(44)
+ ctx.fillText(dead ? 'JEV DIED' : `WAVE ${f.wave} CLEARED`, cw / 2, ch * 0.42); ctx.shadowBlur = 0
+ ctx.fillStyle = '#e9ecf5'; ctx.font = mono(15, 600)
+ ctx.fillText(dead ? `wave ${f.wave} · ${f.player.kills} kills this wave · restarting in ${Math.ceil(f.statusLeftMs / 1000)}` : `next wave: one more demon, 12% faster · starts in ${Math.ceil(f.statusLeftMs / 1000)}`, cw / 2, ch * 0.42 + 34 * u)
+ }
+ if (paused) { ctx.textAlign = 'center'; ctx.fillStyle = '#fbbf24'; ctx.font = mono(15); ctx.fillText('PAUSED · press Step to advance one decision', cw / 2, 34 * u) }
+}
+
+function drawMinimap(f, p, u) {
+ const cw = scene.width, cell = Math.max(3, Math.floor(Math.min((cw * 0.25) / mapW, (scene.height * 0.34) / mapH)))
+ const w = cell * mapW, h = cell * mapH, x0 = cw - w - 14 * u, y0 = 14 * u
+ miniRect = { x: x0, y: y0, w, h, cell }
+ ctx.fillStyle = 'rgba(6,7,12,.78)'; ctx.beginPath(); ctx.roundRect(x0 - 6, y0 - 6, w + 12, h + 12, 8); ctx.fill()
+ for (let y = 0; y < mapH; y++) for (let x = 0; x < mapW; x++) {
+ const c = map[y][x]; if (!solid(c)) continue
+ ctx.fillStyle = c === '#' ? '#475569' : c === '%' ? '#0e7490' : '#9f1239'; ctx.fillRect(x0 + x * cell, y0 + y * cell, cell - 0.5, cell - 0.5)
+ }
+ if (f.route?.length > 1) {
+ ctx.strokeStyle = f.routeKind === 'demon' ? 'rgba(248,113,113,.55)' : 'rgba(74,222,128,.7)'; ctx.lineWidth = 1.5; ctx.setLineDash([3, 3]); ctx.beginPath()
+ f.route.forEach(([x, y], i) => { const X = x0 + (x + 0.5) * cell, Y = y0 + (y + 0.5) * cell; i ? ctx.lineTo(X, Y) : ctx.moveTo(X, Y) }); ctx.stroke(); ctx.setLineDash([])
+ }
+ for (const k of f.pickups) { if (!k.on) continue; ctx.fillStyle = k.k === 'medkit' ? '#4ade80' : '#facc15'; ctx.fillRect(x0 + k.x * cell - 2, y0 + k.y * cell - 2, 4, 4) }
+ for (const d of p.demons) { ctx.fillStyle = d.id === f.crosshair ? '#fff' : '#ef4444'; ctx.beginPath(); ctx.arc(x0 + d.x * cell, y0 + d.y * cell, Math.max(2.2, cell * 0.32), 0, 7); ctx.fill() }
+ const X = x0 + p.x * cell, Y = y0 + p.y * cell, half = (33 * Math.PI) / 180
+ ctx.fillStyle = 'rgba(167,139,250,.22)'; ctx.beginPath(); ctx.moveTo(X, Y); ctx.arc(X, Y, cell * 5, p.a - half, p.a + half); ctx.closePath(); ctx.fill()
+ ctx.fillStyle = f.driver === 'human' ? '#fbbf24' : '#c4b5fd'; ctx.beginPath(); ctx.moveTo(X + Math.cos(p.a) * cell * 0.75, Y + Math.sin(p.a) * cell * 0.75); ctx.lineTo(X + Math.cos(p.a + 2.5) * cell * 0.55, Y + Math.sin(p.a + 2.5) * cell * 0.55); ctx.lineTo(X + Math.cos(p.a - 2.5) * cell * 0.55, Y + Math.sin(p.a - 2.5) * cell * 0.55); ctx.closePath(); ctx.fill()
+ ctx.fillStyle = 'rgba(255,255,255,.5)'; ctx.font = `600 ${Math.round(10 * u)}px ui-monospace,Menlo,monospace`; ctx.textAlign = 'right'
+ ctx.fillText(`click: ${tool === 'spawn' ? 'spawn a demon' : 'drop ' + tool}`, x0 + w, y0 + h + 16 * u)
+}
+
+// ---------------------------------------------------------------- the frame loop
+let lastT = performance.now()
+function loop(now) {
+ requestAnimationFrame(loop)
+ const dt = Math.min(0.05, (now - lastT) / 1000); lastT = now
+ if (!next || !buf) return
+ const f = next, a = prev && prev.mapRev === next.mapRev ? Math.max(0, Math.min(1, (now - nextAt) / Math.max(40, f.tickMs))) : 1
+ const from = prev && prev.mapRev === next.mapRev ? prev : next
+ const p = {
+ x: lerp(from.player.x, f.player.x, a), y: lerp(from.player.y, f.player.y, a), a: lerpAngle(from.player.a, f.player.a, a), hp: lerp(from.player.hp, f.player.hp, a),
+ demons: f.demons.map((d) => { const o = from.demons.find((q) => q.id === d.id); return o ? { ...d, x: lerp(o.x, d.x, a), y: lerp(o.y, d.y, a) } : d }),
+ }
+ for (const k of ['flash', 'recoil', 'hurt', 'shake', 'pickup']) fx[k] = Math.max(0, fx[k] - dt * (k === 'flash' ? 11 : k === 'recoil' ? 7 : k === 'shake' ? 5 : 2.2))
+ for (let i = particles.length - 1; i >= 0; i--) { const q = particles[i]; q.life -= dt; if (q.life <= 0) { particles[i] = particles[particles.length - 1]; particles.pop(); continue } q.x += q.vx * dt; q.y += q.vy * dt; q.z += q.vz * dt; q.vz -= 2.6 * dt; if (q.z < 0.02) { q.z = 0.02; q.vz *= -0.35; q.vx *= 0.6; q.vy *= 0.6 } }
+ for (let i = corpses.length - 1; i >= 0; i--) { corpses[i].t -= dt * 2.4; if (corpses[i].t <= 0) corpses.splice(i, 1) }
+
+ const moving = f.player.moving && f.status === 'playing' && !paused
+ const horizon = Math.round(H / 2 + (moving ? Math.sin(now * 0.011) * 2.2 : 0) + (rand() - 0.5) * fx.shake * 9 - fx.recoil * 3)
+ const cam = render3d(p.x, p.y, p.a, horizon, now)
+ const sprites = []
+ for (const k of f.pickups) if (k.on) sprites.push({ x: k.x, y: k.y, sh: SPR[k.k], h: 0.42, lift: 0.02 + Math.sin(now * 0.004 + k.id) * 0.03, sq: 1 })
+ for (const d of p.demons) sprites.push({ x: d.x, y: d.y, sh: d.hurt ? SPR.white : d.st === 'attack' ? SPR.atk : (Math.floor(now / 170) + d.id) % 2 ? SPR.a : SPR.b, h: 0.92, lift: 0, sq: 1 })
+ for (const c of corpses) sprites.push({ x: c.x, y: c.y, sh: SPR.white, h: 0.92, lift: 0, sq: Math.max(0.05, c.t) })
+ sprites.sort((s1, s2) => ((s2.x - p.x) ** 2 + (s2.y - p.y) ** 2) - ((s1.x - p.x) ** 2 + (s1.y - p.y) ** 2))
+ for (const s of sprites) drawSprite(cam, p.x, p.y, s.x, s.y, s.sh, s.h, horizon, s.lift, s.sq)
+ drawParticles(cam, p.x, p.y, horizon)
+ lctx.putImageData(img, 0, 0)
+ if (fx.tracer && fx.tracer.t > 0) {
+ fx.tracer.t -= dt * 14
+ lctx.strokeStyle = `rgba(255,236,160,${Math.max(0, fx.tracer.t)})`; lctx.lineWidth = 1.5; lctx.beginPath(); lctx.moveTo(W / 2 + 4, H - 66); lctx.lineTo(W / 2, horizon + 2); lctx.stroke()
+ }
+ if (fx.flash > 0.1) { lctx.fillStyle = `rgba(255,214,120,${0.13 * fx.flash})`; lctx.fillRect(0, 0, W, H) }
+ if (f.status !== 'dead') drawWeapon(now, moving)
+
+ ctx.imageSmoothingEnabled = false
+ const sx = (rand() - 0.5) * fx.shake * 12
+ ctx.drawImage(low, 0, 0, W, H, sx, 0, scene.width, scene.height)
+ drawHud(f, p, now)
+}
+
+// ---------------------------------------------------------------- wiring
+const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+function paintStateText(text) {
+ const esc = (s) => s.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]))
+ $('stateText').innerHTML = text.split('\n').slice(1).map((l) => {
+ l = esc(l)
+ if (l.startsWith('crosshair on: demon')) return `<span class="bad">${l}</span>`
+ if (/BITING/.test(l)) return `<span class="bad">${l}</span>`
+ if (l.startsWith(' demon#')) return `<span class="hl">${l}</span>`
+ if (l.startsWith('route')) return `<span class="ok">${l}</span>`
+ return l
+ }).join('\n')
+}
+function onFrame(f, full) {
+ if (full || f.mapRev !== mapRev) {
+ if (!f.map) { fetch('/state').then((r) => r.json()).then((s) => onFrame(s, true)).catch(() => {}); if (mapRev < 0) return }
+ else { map = f.map; mapH = map.length; mapW = map[0].length; mapRev = f.mapRev; prev = null; particles.length = 0; corpses.length = 0 }
+ }
+ prev = next; next = f; nextAt = performance.now()
+ onEvents(f)
+ paused = !f.running
+ $('title').textContent = f.title
+ $('s-wave').textContent = f.wave; $('s-kills').textContent = f.session.kills; $('s-deaths').textContent = f.session.deaths; $('s-best').textContent = f.session.bestWave
+ $('s-acc').textContent = f.session.shots ? Math.round((f.session.hits / f.session.shots) * 100) + '%' : '—'
+ $('pause').textContent = f.running ? 'Pause' : 'Resume'
+ $('driver').textContent = f.driver === 'human' ? 'YOU' : 'JEV'; $('driver').classList.toggle('human', f.driver === 'human')
+ const problem = f.cfgError || f.mapError || f.error
+ $('cfgError').classList.toggle('hidden', !problem); $('cfgError').textContent = problem ? `level.json: ${problem} — still running on the last good level.` : ''
+ if (document.activeElement !== $('speed')) { const base = f.demonSpeed / (1 + 0.12 * (f.wave - 1)); $('speed').value = base; $('speedVal').textContent = base.toFixed(1) }
+ paintStateText(f.stateText || '')
+}
+
+const post = (body) => fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }).catch(() => {})
+$('pause').onclick = () => post({ cmd: paused ? 'start' : 'pause' })
+$('step').onclick = () => post({ cmd: 'tick' })
+$('reset').onclick = () => post({ cmd: 'reset' })
+$('swarm').onclick = () => post({ cmd: 'swarm' })
+$('speed').oninput = (e) => { $('speedVal').textContent = Number(e.target.value).toFixed(1); post({ cmd: 'set', key: 'demonSpeed', value: Number(e.target.value) }) }
+for (const b of document.querySelectorAll('[data-tool]')) b.onclick = () => { tool = b.dataset.tool; document.querySelectorAll('[data-tool]').forEach((o) => o.classList.toggle('on', o === b)) }
+scene.addEventListener('click', (e) => {
+ scene.focus()
+ if (!miniRect) return
+ const r = scene.getBoundingClientRect(), x = ((e.clientX - r.left) / r.width) * scene.width, y = ((e.clientY - r.top) / r.height) * scene.height
+ if (x < miniRect.x || y < miniRect.y || x > miniRect.x + miniRect.w || y > miniRect.y + miniRect.h) return
+ const cx = (x - miniRect.x) / miniRect.cell, cy = (y - miniRect.y) / miniRect.cell
+ post(tool === 'spawn' ? { cmd: 'spawn', x: cx, y: cy } : { cmd: 'medkit', kind: tool, x: cx, y: cy })
+})
+
+// Human takeover: while a key is held, the person's input replaces Jev's. Jev keeps answering, so
+// the lit keys still show what it WOULD do.
+const held = new Set()
+const KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Space', 'ShiftLeft', 'ShiftRight'])
+function sendHuman() {
+ if (![...held].some((k) => !k.startsWith('Shift'))) return
+ const hard = held.has('ShiftLeft') || held.has('ShiftRight')
+ const turn = held.has('ArrowLeft') ? (hard ? 'LEFT_HARD' : 'LEFT') : held.has('ArrowRight') ? (hard ? 'RIGHT_HARD' : 'RIGHT') : 'AHEAD'
+ const move = held.has('KeyW') || held.has('ArrowUp') ? 'FORWARD' : held.has('KeyS') || held.has('ArrowDown') ? 'BACK' : held.has('KeyA') ? 'STRAFE_LEFT' : held.has('KeyD') ? 'STRAFE_RIGHT' : 'HOLD'
+ post({ cmd: 'human', turn, move, fire: held.has('Space') })
+}
+window.addEventListener('keydown', (e) => { if (!KEYS.has(e.code) || /INPUT|TEXTAREA|SELECT/.test(document.activeElement?.tagName ?? '')) return; e.preventDefault(); held.add(e.code); sendHuman() })
+window.addEventListener('keyup', (e) => { held.delete(e.code) })
+window.addEventListener('blur', () => held.clear())
+setInterval(sendHuman, 90)
+
+async function pollJev() {
+ try { const s = await (await fetch('/jev', { cache: 'no-store' })).json(); $('s-rate').textContent = s.callsPerSec.toFixed(1); $('s-cost').textContent = fmtMoney(s.costUsd); $('s-dec').textContent = s.calls.toLocaleString() } catch { /* restarting */ }
+ setTimeout(pollJev, 500)
+}
+
+resize()
+const es = new EventSource('/events')
+es.addEventListener('state', (e) => onFrame(JSON.parse(e.data), false))
+fetch('/state').then((r) => r.json()).then((s) => onFrame(s, true)).catch(() => {})
+pollJev()
+requestAnimationFrame(loop)
diff --git a/store/agents/jev-fps/viewer/viewer.mjs b/store/agents/jev-fps/viewer/viewer.mjs
new file mode 100644
index 000000000..37248884a
--- /dev/null
+++ b/store/agents/jev-fps/viewer/viewer.mjs
@@ -0,0 +1,221 @@
+// Jev FPS viewer — a loopback server running a first-person arena shooter that Jev plays live.
+// About nine times a second the marine's situation is written out as text (HUD, what is in sight,
+// what it hears, wall distances, the automap route) and Jev (TypeSafe's System One model) answers
+// four typed questions in ONE call: where to turn, how to move, whether to fire, and how dangerous
+// this instant is. The arena is synthetic; the decision loop is the demo.
+//
+// The chat agent edits level.json (the ASCII map, the demons, the pace). The pane can also poke the
+// fight live: spawn demons, drop medkits, change demon speed, or grab the controls for a moment.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds level.json (watched live).
+
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, jev } from '../toolchain/jev.mjs'
+import { serveViewer, watchConfig, writeVerdict, clean } from './kit.mjs'
+import { DEFAULT, TURN_RATE, TURNS, MOVES, createWorld, observe, tick, spawnDemon, isWall } from './sim.mjs'
+import { fpsMock } from './mock.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clampN = (v, lo, hi, d) => { const n = Number(v); return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : d }
+
+/** Keep a wild config from breaking the arena. check.mjs reports the same ranges to the agent. */
+export function sanitize(raw) {
+ return {
+ ...DEFAULT, ...raw,
+ title: String(raw.title ?? DEFAULT.title).slice(0, 80),
+ description: String(raw.description ?? DEFAULT.description).slice(0, 300),
+ style: String(raw.style ?? DEFAULT.style).slice(0, 600),
+ map: Array.isArray(raw.map) ? raw.map : DEFAULT.map,
+ tickMs: clampN(raw.tickMs, 60, 1000, DEFAULT.tickMs),
+ demons: Math.round(clampN(raw.demons, 1, 24, DEFAULT.demons)),
+ demonSpeed: clampN(raw.demonSpeed, 0.2, 6, DEFAULT.demonSpeed),
+ demonHealth: clampN(raw.demonHealth, 10, 400, DEFAULT.demonHealth),
+ demonDamage: clampN(raw.demonDamage, 1, 60, DEFAULT.demonDamage),
+ kills: Math.round(clampN(raw.kills, 1, 200, DEFAULT.kills)),
+ ammo: Math.round(clampN(raw.ammo, 0, 99, DEFAULT.ammo)),
+ seed: Math.round(clampN(raw.seed, 0, 1e9, DEFAULT.seed)),
+ }
+}
+
+function questions(cfg) {
+ const deg = (name) => Math.abs(Math.round(TURN_RATE[name] * cfg.tickMs / 1000))
+ return {
+ turn: jev.choice({
+ LEFT_HARD: `snap ${deg('LEFT_HARD')} degrees to the left`, LEFT: `turn ${deg('LEFT')} degrees to the left`, LEFT_FINE: `nudge ${deg('LEFT_FINE')} degrees to the left`,
+ AHEAD: 'keep facing the same way',
+ RIGHT_FINE: `nudge ${deg('RIGHT_FINE')} degrees to the right`, RIGHT: `turn ${deg('RIGHT')} degrees to the right`, RIGHT_HARD: `snap ${deg('RIGHT_HARD')} degrees to the right`,
+ }, 'Which way do you turn this instant? Put your crosshair on the threat you must deal with first.'),
+ move: jev.choice({
+ FORWARD: 'advance the way you face', BACK: 'back away while still facing forward', STRAFE_LEFT: 'sidestep to the left', STRAFE_RIGHT: 'sidestep to the right', HOLD: 'stand still',
+ }, 'How do you move this instant?'),
+ fire: jev.noul('Fire now? Yes only when a demon is in your crosshair and you have ammo.'),
+ threat: jev.score(['calm: nothing close', 'watchful: a demon is around', 'pressed: demons are closing in', 'critical: about to die'], 'How dangerous is this instant?'),
+ }
+}
+
+export async function startFpsViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+
+ // Every binding is declared before anything can call into the closures below.
+ let world = null
+ let stopped = false, running = false, busy = false
+ let timer = null, salt = 1, mapRev = 0, lastVerdictAt = 0
+ let overrides = {}
+ let human = null // { turn, move, fire, until }
+ let decision = { turn: 'AHEAD', move: 'HOLD', fire: false, pFire: 0, threat: 0, probs: { turn: {}, move: {} }, conf: { turn: 0, move: 0 } }
+ let obs = null
+ let error = null
+ let server = null
+ const session = { kills: 0, deaths: 0, bestWave: 1, decisions: 0, shots: 0, hits: 0, wavesCleared: 0 }
+
+ const cfgWatch = watchConfig(join(workspace, 'level.json'), DEFAULT, () => { overrides = {}; restart(1); push() })
+ const cfg = () => sanitize({ ...cfgWatch.get(), ...overrides })
+
+ function restart(waveNo, carry = null) {
+ world = createWorld(cfg(), waveNo, carry, session.deaths)
+ mapRev++
+ obs = observe(world, cfg())
+ }
+
+ function frame() {
+ const c = cfg()
+ const p = world.player
+ const humanOn = !!human && human.until > Date.now()
+ return {
+ t: world.step, tickMs: c.tickMs, mapRev, title: c.title,
+ wave: world.waveNo, need: world.need, status: world.status,
+ statusLeftMs: world.status === 'playing' ? 0 : Math.max(0, 3000 - (world.step - world.statusAt) * c.tickMs),
+ player: { x: p.x, y: p.y, a: p.a, hp: p.hp, ammo: p.ammo, kills: p.kills, moving: p.moving, hurt: world.step - p.hurtAt <= 1 },
+ demons: world.demons.map((d) => ({ id: d.id, x: d.x, y: d.y, hp: d.hp, st: d.state, hurt: d.hurt > 0 })),
+ pickups: world.pickups.map((k) => ({ id: k.id, x: k.x, y: k.y, k: k.kind, on: k.respawn <= 0 })),
+ events: world.events,
+ decision, driver: humanOn ? 'human' : 'jev',
+ route: obs?.route?.path ?? [], routeKind: obs?.route?.kind ?? null, crosshair: obs?.crosshair ?? null,
+ stateText: obs?.text ?? '',
+ demonSpeed: world.demonSpeed, maxAlive: world.maxAlive,
+ session, running, error, cfgError: cfgWatch.error(), mapError: world.mapError, overrides,
+ }
+ }
+ const fullState = () => ({ ...frame(), description: cfg().description, map: world.map.rows, cfg: { demons: cfg().demons, demonSpeed: cfg().demonSpeed, kills: cfg().kills, tickMs: cfg().tickMs } })
+
+ function verdict() {
+ const c = cfg()
+ const problem = cfgWatch.error() || world.mapError || error
+ const acc = session.shots ? Math.round((session.hits / session.shots) * 100) : 0
+ writeVerdict(workspace, {
+ ready: session.decisions > 0,
+ summary: problem
+ ? `Jev FPS needs a fix: ${problem}`
+ : `${c.title} · wave ${world.waveNo} · ${session.kills} kills · ${session.deaths} deaths · best wave ${session.bestWave} · ${acc}% shots on target`,
+ findings: [
+ ...(problem ? [{ severity: 'error', kind: 'level', message: problem }] : []),
+ { severity: 'info', kind: 'fight', message: `${session.decisions} decisions, ${session.wavesCleared} waves cleared, demon speed ${world.demonSpeed.toFixed(2)} tiles/s with ${world.maxAlive} alive at once` },
+ ],
+ artifact: 'level.json',
+ phases: [
+ { id: 'spawn', name: 'Arena up', state: 'done' },
+ { id: 'fight', name: 'Fighting', state: session.decisions > 0 ? 'active' : 'pending' },
+ { id: 'waves', name: 'Waves cleared', state: session.wavesCleared > 0 ? 'done' : 'pending' },
+ ],
+ })
+ }
+
+ function push(force = false) {
+ const now = Date.now()
+ if (force || now - lastVerdictAt > 1000) { lastVerdictAt = now; try { verdict() } catch (e) { error = clean(e.message) } }
+ server?.broadcast(frame())
+ }
+
+ async function decide() {
+ if (busy || stopped) return
+ busy = true
+ try {
+ const c = cfg()
+ if (world.status !== 'playing') {
+ tick(world, c, decision)
+ if ((world.step - world.statusAt) * c.tickMs >= 3000) {
+ if (world.status === 'cleared') restart(world.waveNo + 1, { hp: world.player.hp, ammo: world.player.ammo })
+ else restart(1)
+ }
+ return
+ }
+ obs = observe(world, c)
+ const res = await evaluate({ state: obs.text, questions: questions(c), salt: salt++, model: process.env.JEV_MODEL || 'jev-latest', mock: fpsMock })
+ const a = res.answers
+ const turn = TURNS.includes(a.turn?.choice) ? a.turn.choice : 'AHEAD'
+ const move = MOVES.includes(a.move?.choice) ? a.move.choice : 'HOLD'
+ const pFire = Number(a.fire?.noul ?? 0)
+ decision = {
+ turn, move, fire: pFire >= 0.5, pFire, threat: Number(a.threat?.score ?? 0),
+ probs: { turn: a.turn?.probabilities ?? {}, move: a.move?.probabilities ?? {} },
+ conf: { turn: Number(a.turn?.confidence ?? 0), move: Number(a.move?.confidence ?? 0) },
+ }
+ session.decisions++
+ const humanOn = !!human && human.until > Date.now()
+ const events = tick(world, c, humanOn ? human : decision)
+ for (const ev of events) {
+ if (ev.e === 'shot') { session.shots++; if (ev.hit) session.hits++; if (ev.kill) session.kills++ }
+ if (ev.e === 'dead') session.deaths++
+ if (ev.e === 'cleared') { session.wavesCleared++; session.bestWave = Math.max(session.bestWave, world.waveNo + 1) }
+ }
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? String(e))
+ } finally {
+ busy = false
+ }
+ }
+
+ function schedule() { clearTimeout(timer); if (running && !stopped) timer = setTimeout(run, cfg().tickMs) }
+ async function run() { const t0 = Date.now(); await decide(); push(); if (running && !stopped) timer = setTimeout(run, Math.max(0, cfg().tickMs - (Date.now() - t0))) }
+
+ async function control(cmd, body) {
+ if (cmd === 'pause') { running = false; clearTimeout(timer) }
+ else if (cmd === 'start') { if (!running) { running = true; schedule() } }
+ else if (cmd === 'reset') { Object.assign(session, { kills: 0, deaths: 0, bestWave: 1, decisions: 0, shots: 0, hits: 0, wavesCleared: 0 }); overrides = {}; human = null; salt = 1; restart(1) }
+ else if (cmd === 'tick') { const n = Math.round(clampN(body.n, 1, 5000, 1)); for (let i = 0; i < n; i++) await decide() }
+ else if (cmd === 'spawn') {
+ const x = Number(body.x), y = Number(body.y)
+ if (Number.isFinite(x) && Number.isFinite(y) && !isWall(world.map, x, y) && world.demons.length < 40) spawnDemon(world, cfg(), { x: (x | 0) + 0.5, y: (y | 0) + 0.5 })
+ } else if (cmd === 'swarm') { for (let i = 0; i < 5 && world.demons.length < 40; i++) spawnDemon(world, cfg()) }
+ else if (cmd === 'medkit') {
+ const x = Number(body.x), y = Number(body.y)
+ if (Number.isFinite(x) && Number.isFinite(y) && !isWall(world.map, x, y) && world.pickups.length < 60) world.pickups.push({ id: world.pickups.length + 1, x: (x | 0) + 0.5, y: (y | 0) + 0.5, kind: body.kind === 'ammo' ? 'ammo' : 'medkit', respawn: 0, once: true })
+ } else if (cmd === 'set') {
+ const allowed = { demonSpeed: [0.2, 6], demons: [1, 24], tickMs: [60, 1000] }
+ if (allowed[body.key]) {
+ overrides = { ...overrides, [body.key]: clampN(body.value, allowed[body.key][0], allowed[body.key][1], cfg()[body.key]) }
+ const c = cfg()
+ world.demonSpeed = c.demonSpeed * (1 + 0.12 * (world.waveNo - 1))
+ world.maxAlive = Math.round(c.demons + (world.waveNo - 1))
+ }
+ } else if (cmd === 'human') {
+ human = { turn: TURNS.includes(body.turn) ? body.turn : 'AHEAD', move: MOVES.includes(body.move) ? body.move : 'HOLD', fire: !!body.fire, until: Date.now() + 400 }
+ return null // key events are frequent; the next frame shows the effect
+ }
+ push(true)
+ return { step: world.step }
+ }
+
+ restart(1)
+ server = await serveViewer({ here: HERE, port, state: fullState, control })
+ push(true)
+ running = true
+ schedule()
+
+ return {
+ url: server.url,
+ async close() { stopped = true; running = false; clearTimeout(timer); cfgWatch.close(); await server.close() },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startFpsViewer({ workspace, port })
+ console.log(`Jev FPS listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-guard/.gitignore b/store/agents/jev-guard/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-guard/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-guard/AGENTS.md b/store/agents/jev-guard/AGENTS.md
new file mode 100644
index 000000000..04d29902f
--- /dev/null
+++ b/store/agents/jev-guard/AGENTS.md
@@ -0,0 +1,60 @@
+# Jev Guard in OpenHarness
+
+On the left, Jev Guard watches the `project/` folder. **Jev — TypeSafe's System One model — judges
+your own work, edit by edit.** It runs the test suite on every change and scores how close to the
+goal you are, how risky the change is, and how much it trusts it.
+
+On the right, you fix the code. You own `project/` entirely; Jev only watches and judges.
+
+## The workspace
+
+- `goal.json` — the goal Jev judges against (the template sets a sensible one; you may sharpen it).
+- `project/score.js` — the broken module **you** fix.
+- `project/test.js` — the suite (plain Node, zero dependencies, runnable as `node project/test.js`).
+ Jev Guard reruns it on every edit.
+
+```jsonc
+{
+ "goal": "Make every test in project/test.js pass without breaking the others.",
+ "name": "Jev Guard",
+ "description": "Jev judges your own edits live as you fix the broken module."
+}
+```
+
+## Your job
+
+Fix the module so every test passes — and use Jev Guard as a live code reviewer while you do.
+Good work under Jev Guard:
+
+- **Fix the real thing, not the symptom.** The template's `sumTo` and `factorial` are broken in
+ honest ways. Implement them correctly rather than special-casing the test's inputs — Jev Guard
+ reads the *change* and its risk signal will reward a real fix.
+- **Don't over-engineer.** A correct, minimal fix is what the goal asks for. Add nothing that
+ changes the test contract.
+- **Watch the meters.** `toward` climbs as you converge, `trust` reflects Jev's confidence in the
+ exact change, `risk` warns on a shaky edit (hitting a retry/commentary `/control judge` re-runs
+ the current state).
+
+Let it run in Auto (judges on every edit) or step it with "Judge now".
+
+## Keep current
+
+- Keep the project able to run (`node project/test.js`) at all times; Jev Guard debounces edits but
+ it will judge whatever state it finds.
+- Keep `goal.json` truthful about what the tests require.
+
+## Rules
+
+- Never propose opening a browser, changing ports, or running a second server. The viewer is already
+ running on the left.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's opinion on a
+ design choice (e.g. "which of these two implementations is riskier?") using the `jev` helpers,
+ but the ground truth is the test suite Jev Guard runs.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock.
+
+## Definition of done
+
+- Every test in `project/test.js` passes (`node project/test.js` exits 0 and prints `ALL TESTS
+ PASS`).
+- The verdict in the viewer reads as a passing/green judgment.
+- The fix is honest — the functions are implemented correctly, not special-cased to the tests.
diff --git a/store/agents/jev-guard/LICENSE b/store/agents/jev-guard/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-guard/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-guard/README.md b/store/agents/jev-guard/README.md
new file mode 100644
index 000000000..7fea953de
--- /dev/null
+++ b/store/agents/jev-guard/README.md
@@ -0,0 +1,55 @@
+# Jev Guard
+
+**Jev — TypeSafe's System One model — is your code reviewer, live.** You fix a tiny broken module
+in `project/`; on every edit, Jev Guard runs the test suite and asks Jev to judge the change: how
+close to the goal, how risky, how much it trusts it. The pane is a dashboard of a decision model
+refereeing your own coding as you work — a live second pair of eyes that never blinks.
+
+This is a harness for OpenHarness. The agent on the right fixes `project/score.js` toward the goal
+in `goal.json`; the viewer on the left watches those edits, runs the tests, and streams Jev's
+running judgment over SSE.
+
+## Anatomy
+
+```
+jev-guard/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to fix the module while Jev referees it
+ skills/guard/SKILL.md # the fix-under-watch craft
+ template/
+ goal.json # the goal Jev judges against
+ project/score.js # the broken module to fix
+ project/test.js # the suite (plain node)
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock)
+ viewer.sh # launches the viewer
+ check.mjs # validates the workspace
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (dashboard)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` watches `project/`, reruns the test suite on every edit (debounced), and asks
+Jev three things about each change: how much closer to the goal, how confident it is in the exact
+change, and how risky it is. It streams **toward / trust / risk** plus a green/done signal over SSE,
+drawn as meters, a history chart and a run log. `.harness/verdict.json` carries the progressive
+verdict (failing → passing → goal met). `Post /v1/systemone` is called when `TYPESAFE_API_KEY` is
+set; without it, a deterministic local mock judges.
+
+## Jev, honestly
+
+Jev is new and early-access; its headline claims are mostly vendor-reported, and the mock is a
+stand-in for *plumbing*, not judgement. Here the *test suite* is the ground truth — Jev's judgment is
+an overlay on real, runnable test results. Treat its risk/trust read as a fast, cheap signal layered
+on top of what the tests actually say.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a decision model a real teammate — reviewing your work as you
+do it._
diff --git a/store/agents/jev-guard/THIRD_PARTY_NOTICES.md b/store/agents/jev-guard/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-guard/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-guard/harness.json b/store/agents/jev-guard/harness.json
new file mode 100644
index 000000000..2c4516e48
--- /dev/null
+++ b/store/agents/jev-guard/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-guard",
+ "name": "Jev Guard",
+ "category": "Dev Tools",
+ "author": "Autonomous",
+ "description": "Jev — TypeSafe's System One model — is your code reviewer. You fix a tiny broken module and Jev's guard judges every edit live: how close to the goal, how risky, how much it trusts it. Watch a decision model referee your own coding as you work.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "goal.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json", ".js"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-guard/skills/guard/SKILL.md b/store/agents/jev-guard/skills/guard/SKILL.md
new file mode 100644
index 000000000..9a5086af0
--- /dev/null
+++ b/store/agents/jev-guard/skills/guard/SKILL.md
@@ -0,0 +1,54 @@
+---
+name: jev-guard
+description: Fix a broken module under the live eye of Jev Guard, where Jev (TypeSafe's System One model) scores your own edits for progress, risk and trust.
+---
+
+# Jev Guard fix-under-watch
+
+Jev Guard runs the test suite in `project/` on every edit and asks Jev (TypeSafe's System One model)
+to judge each change: how much closer to the goal, how risky, how confident. The pane draws those as
+meters, a history chart and a run log. The goal is to make the tests pass and the verdict go green
+with a fix Jev trusts.
+
+## The loop
+
+1. Edit `project/score.js` (that's the work). Jev Guard auto-judges on each edit, or step it with
+ "Judge now" / `node "$JEV_DSH/toolchain/check.mjs"`.
+2. Watch the meters: `toward` (progress), `trust` (Jev's confidence in the exact change), `risk`
+ (a red flag on a shaky edit). The run log shows PASS/FAIL per test run with what changed.
+3. Iterate until `node project/test.js` prints `ALL TESTS PASS` and the viewer verdict reads as
+ a passing/green judgment.
+
+## Reading Jev
+
+Jev's scores are layered on *real test results*: the suite is the ground truth, Jev is the overlay.
+A focused, honest fix — correct logic, nothing special-cased, nothing extra — is what reads as high
+`trust` / low `risk`. A hack that greps the test names or returns constants will pass the tests but
+Jev's `risk` meter will go red.
+
+## Verifying
+
+- `node "$JEV_DSH/toolchain/check.mjs"` validates the workspace (goal.json + project/test.js
+ present and runnable).
+- `node project/test.js` is the real check: exit 0 + `ALL TESTS PASS` is done.
+- Watch the viewer verdict flip to a green/god-met judgment, not just the tests passing.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's opinion on an
+implementation choice:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "Implement sumTo(5) by looping, vs a closed-form n*(n+1)/2. Which is more likely a correct, maintainable fix for a tiny module?",
+ questions: {
+ risky: jev.score({0:"safe",1:"risky",2:"reckless"}, "How risky is switching to the closed-form?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-guard/store.json b/store/agents/jev-guard/store.json
new file mode 100644
index 000000000..977a476b8
--- /dev/null
+++ b/store/agents/jev-guard/store.json
@@ -0,0 +1,13 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev referees your own coding, edit by edit",
+ "screenshots": [],
+ "examples": [
+ {
+ "prompt": "Fix the broken module in project/ so every test in test.js passes. Make Jev Guard watch you work and tell you — live — when your change is risky and when the goal is truly met.",
+ "caption": "Ship it green — Jev guarding your fix, run by run"
+ }
+ ]
+}
diff --git a/store/agents/jev-guard/template/goal.json b/store/agents/jev-guard/template/goal.json
new file mode 100644
index 000000000..d10a99efc
--- /dev/null
+++ b/store/agents/jev-guard/template/goal.json
@@ -0,0 +1,5 @@
+{
+ "goal": "Make every test in project/test.js pass without breaking the others.",
+ "name": "Jev Guard",
+ "description": "Jev judges your own edits live as you fix the broken module."
+}
diff --git a/store/agents/jev-guard/template/project/score.js b/store/agents/jev-guard/template/project/score.js
new file mode 100644
index 000000000..051ddc13b
--- /dev/null
+++ b/store/agents/jev-guard/template/project/score.js
@@ -0,0 +1,23 @@
+// score.js — a tiny module the coding agent is fixing. Jev Guard judges the work live.
+// The goal (from goal.json): make every test in test.js pass without breaking the others.
+
+export function fizzbuzz(n) {
+ const out = []
+ for (let i = 1; i <= n; i++) {
+ if (i % 15 === 0) out.push('FizzBuzz')
+ else if (i % 3 === 0) out.push('Fizz')
+ else if (i % 5 === 0) out.push('Buzz')
+ else out.push(String(i))
+ }
+ return out
+}
+
+// TASK: this is broken. It should return the sum of integers 1..n.
+export function sumTo(n) {
+ return 0
+}
+
+// TASK: this is broken. It should return n! (factorial).
+export function factorial(n) {
+ return n
+}
diff --git a/store/agents/jev-guard/template/project/test.js b/store/agents/jev-guard/template/project/test.js
new file mode 100644
index 000000000..a7c820303
--- /dev/null
+++ b/store/agents/jev-guard/template/project/test.js
@@ -0,0 +1,19 @@
+// test.js — the test suite. Jev Guard runs it on every edit. Make every assert pass.
+import assert from 'node:assert/strict'
+import { fizzbuzz, sumTo, factorial } from './score.js'
+
+assert.deepEqual(fizzbuzz(15), [
+ '1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz',
+ '11', 'Fizz', '13', '14', 'FizzBuzz',
+])
+assert.equal(fizzbuzz(1).length, 1)
+
+assert.equal(sumTo(1), 1)
+assert.equal(sumTo(5), 15)
+assert.equal(sumTo(100), 5050)
+
+assert.equal(factorial(0), 1)
+assert.equal(factorial(5), 120)
+assert.equal(factorial(10), 3628800)
+
+console.log('ALL TESTS PASS')
diff --git a/store/agents/jev-guard/test/viewer.test.mjs b/store/agents/jev-guard/test/viewer.test.mjs
new file mode 100644
index 000000000..982044c83
--- /dev/null
+++ b/store/agents/jev-guard/test/viewer.test.mjs
@@ -0,0 +1,109 @@
+// Viewer integration test for Jev Guard. Spins up the real viewer against a temp workspace and
+// checks the loop: an edit triggers a test run + Jev judgment, the verdict updates, and once the
+// agent's fix makes the tests pass, Jev reports the goal met.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, mkdirSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+const PROJ_JS = `export function sumTo(n){let s=0;for(let i=1;i<=n;i++)s+=i;return s}
+export function factorial(n){let r=1;for(let i=2;i<=n;i++)r*=i;return r}
+`
+const TEST_JS = `import assert from 'node:assert/strict'
+import { sumTo, factorial } from './score.js'
+assert.equal(sumTo(5), 15)
+assert.equal(factorial(5), 120)
+console.log('ALL TESTS PASS')
+`
+
+async function freshViewer({ broken = true } = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-guard-test-'))
+ mkdirSync(join(ws, 'project'))
+ writeFileSync(join(ws, 'goal.json'), JSON.stringify({ name: 'Guard Test', goal: 'Make project/test.js pass.', description: 'test' }))
+ if (broken) {
+ writeFileSync(join(ws, 'project', 'score.js'), `export function sumTo(n){return 0}\nexport function factorial(n){return n}\n`)
+ } else {
+ writeFileSync(join(ws, 'project', 'score.js'), PROJ_JS)
+ }
+ writeFileSync(join(ws, 'project', 'test.js'), TEST_JS)
+ const { startGuardViewer } = await import(viewerPath)
+ const viewer = await startGuardViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Guard judges the first edit and writes a verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ // Trigger a manual judge (the viewer starts idle; "Judge now" runs the loop).
+ const port = viewer.url.split(':').pop()
+ await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd: 'judge' }) })
+ await wait(400)
+ assert.ok(existsSync(join(ws, '.harness/verdict.json')), 'verdict should exist')
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.phases))
+ assert.match(v.summary, /failing|judging|1 runs/, `summary should reflect a judged run: ${v.summary}`)
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Guard detects the agent fixing the tests: passing run → goal met', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ await ctl('start')
+ // The agent fixes the module.
+ await new Promise((r) => setTimeout(r, 300))
+ writeFileSync(join(ws, 'project', 'score.js'), PROJ_JS)
+ const deadline = Date.now() + 4000
+ let done = false
+ while (Date.now() < deadline && !done) {
+ await wait(250)
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ if (/goal met/i.test(v.summary) || /passing/i.test(v.summary)) done = true
+ }
+ assert.ok(done, `expected a passing/green judgment after the fix; summary was ${readFileSync(join(ws, '.harness/verdict.json'), 'utf8')}`)
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Guard control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('judge'), 200)
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Guard judges a workspace that already passes', async () => {
+ const { ws, viewer } = await freshViewer({ broken: false })
+ try {
+ const port = viewer.url.split(':').pop()
+ await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd: 'judge' }) })
+ await wait(400)
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.match(v.summary, /goal met|passing/i, `summary: ${v.summary}`)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-guard/toolchain/README.md b/store/agents/jev-guard/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-guard/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-guard/toolchain/check.mjs b/store/agents/jev-guard/toolchain/check.mjs
new file mode 100644
index 000000000..15ef687b8
--- /dev/null
+++ b/store/agents/jev-guard/toolchain/check.mjs
@@ -0,0 +1,32 @@
+#!/usr/bin/env node
+// check.mjs — validate a Jev Guard workspace: goal.json present + readable, project/ exists with a
+// test.js that actually runs (the viewer's test runner must work, else Jev has nothing to judge).
+import { readFileSync, existsSync } from 'node:fs'
+import { join } from 'node:path'
+import { spawnSync } from 'node:child_process'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+let warnCount = 0
+const bad = (msg) => { fail = true; console.log(msg) }
+const warn = (msg) => { warnCount++; console.log(msg) }
+
+let goal
+try {
+ goal = JSON.parse(readFileSync(join(ws, 'goal.json'), 'utf8'))
+} catch (e) {
+ bad(`error cannot read goal.json: ${e.message}`)
+}
+if (goal && (!goal.goal || typeof goal.goal !== 'string')) bad('error goal.json needs a string "goal"')
+
+if (!existsSync(join(ws, 'project', 'test.js'))) {
+ bad('error project/test.js is required (the viewer runs it to judge the agent)')
+} else {
+ const res = spawnSync('node', [join(ws, 'project', 'test.js')], { encoding: 'utf8', timeout: 15000 })
+ if (res.error) bad(`error project/test.js could not run: ${res.error.message}`)
+ else if (res.status !== 0) warn('warn project/test.js currently fails (expected at the start — the agent is meant to fix it)')
+}
+
+console.log(fail ? 'fail invalid Jev Guard workspace' : 'ok Jev Guard workspace is valid')
+process.exit(fail ? 1 : 0)
\ No newline at end of file
diff --git a/store/agents/jev-guard/toolchain/doctor.sh b/store/agents/jev-guard/toolchain/doctor.sh
new file mode 100644
index 000000000..974f39427
--- /dev/null
+++ b/store/agents/jev-guard/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Guard viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-guard/toolchain/init-workspace.sh b/store/agents/jev-guard/toolchain/init-workspace.sh
new file mode 100644
index 000000000..b752d0b31
--- /dev/null
+++ b/store/agents/jev-guard/toolchain/init-workspace.sh
@@ -0,0 +1,4 @@
+#!/usr/bin/env bash
+# Workspace already seeded with goal.json + project/; nothing to provision.
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-guard/toolchain/jev.mjs b/store/agents/jev-guard/toolchain/jev.mjs
new file mode 100644
index 000000000..854501a8b
--- /dev/null
+++ b/store/agents/jev-guard/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-guard/toolchain/setup.sh b/store/agents/jev-guard/toolchain/setup.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-guard/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-guard/toolchain/viewer.sh b/store/agents/jev-guard/toolchain/viewer.sh
new file mode 100644
index 000000000..202393144
--- /dev/null
+++ b/store/agents/jev-guard/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Guard viewer (Jev judges the coding agent's live edits).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-guard/viewer/index.html b/store/agents/jev-guard/viewer/index.html
new file mode 100644
index 000000000..a3a41620c
--- /dev/null
+++ b/store/agents/jev-guard/viewer/index.html
@@ -0,0 +1,68 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Jev Guard</title>
+<link rel="icon" href="data:," />
+<link rel="stylesheet" href="/studio.css" />
+</head>
+<body>
+<header id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Guard</h1></div>
+ <div id="title"></div>
+ <div id="meta"></div>
+ <div class="controls">
+ <button id="judge" class="primary">Judge now</button>
+ <button id="pause">Pause</button>
+ <button id="start">Auto</button>
+ <button id="reset">Reset</button>
+ </div>
+</header>
+
+<main>
+ <section id="stage">
+ <div class="goal panel">
+ <div class="panel-title">Goal</div>
+ <p id="goal"></p>
+ </div>
+
+ <div class="panels">
+ <div class="panel">
+ <div class="panel-title">Latest test run</div>
+ <div id="run"><div class="pulse"></div><span>waiting for the agent's first edit…</span></div>
+ </div>
+
+ <div class="panel">
+ <div class="panel-title">Jev's current judgment</div>
+ <div id="verdict" class="verdict">— no run judged yet —</div>
+ <div class="meters">
+ <div class="meter"><label>toward goal</label><div class="bar"><i data-k="toward"></i></div><span class="v" data-v="toward"></span></div>
+ <div class="meter"><label>trust</label><div class="bar"><i data-k="trust"></i></div><span class="v" data-v="trust"></span></div>
+ <div class="meter warn"><label>risk</label><div class="bar"><i data-k="risk"></i></div><span class="v" data-v="risk"></span></div>
+ </div>
+ </div>
+ </div>
+
+ <div class="panel">
+ <div class="panel-title">Judgment history</div>
+ <canvas id="chart"></canvas>
+ </div>
+ </section>
+
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Run log</div>
+ <ol id="log"></ol>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Test output</div>
+ <pre id="output"></pre>
+ </div>
+ </aside>
+</main>
+
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-guard/viewer/jev-hud.js b/store/agents/jev-guard/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-guard/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-guard/viewer/studio.css b/store/agents/jev-guard/viewer/studio.css
new file mode 100644
index 000000000..b1e3cf022
--- /dev/null
+++ b/store/agents/jev-guard/viewer/studio.css
@@ -0,0 +1,84 @@
+:root {
+ --bg: #0a0b10;
+ --panel: #12141c;
+ --panel2: #171a24;
+ --ink: #e8eaf2;
+ --dim: #8a90a6;
+ --line: #262a38;
+ --accent: #c084fc;
+ --cyan: #5eead4;
+ --amber: #fbbf24;
+ --rose: #fb7185;
+ --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #171a2b 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 18px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(23,26,36,.9), rgba(18,20,28,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+#title { color: var(--accent); font-size: 15px; font-weight: 700; }
+#meta { color: var(--dim); font-size: 12px; min-width: 120px; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #7c3aed, #a855f7); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+#goal { font-size: 15px; margin: 0; color: var(--ink); }
+
+.panels { display: flex; gap: 16px; flex-wrap: wrap; }
+.panels .panel { flex: 1; min-width: 240px; }
+
+#run { display: flex; align-items: center; gap: 12px; font-size: 14px; min-height: 40px; }
+#run .pulse { width: 14px; height: 14px; border-radius: 50%; background: var(--dim); flex: none; }
+#run.pass .pulse { background: var(--ok); box-shadow: 0 0 12px var(--ok); }
+#run.fail .pulse { background: var(--rose); box-shadow: 0 0 12px var(--rose); animation: pulse .9s infinite; }
+@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .4; } }
+
+.verdict { font-size: 15px; font-weight: 700; margin-bottom: 12px; }
+.verdict.done { color: var(--ok); } .verdict.work { color: var(--amber); } .verdict.fail { color: var(--rose); }
+
+.meters { display: flex; flex-direction: column; gap: 10px; }
+.meter { display: grid; grid-template-columns: 80px 1fr 40px; align-items: center; gap: 10px; }
+.meter label { color: var(--dim); font-size: 12px; }
+.meter .bar { height: 10px; background: #22263a; border-radius: 6px; overflow: hidden; }
+.meter .bar i { display: block; height: 100%; width: 0; background: linear-gradient(90deg, var(--cyan), var(--accent)); transition: width .4s ease; }
+.meter.warn .bar i { background: linear-gradient(90deg, var(--amber), var(--rose)); }
+.meter .v { font-size: 12px; color: var(--ink); text-align: right; }
+
+#chart { width: 100%; height: 160px; background: #0d0f16; border: 1px solid #1c2030; border-radius: 8px; }
+
+#rail {
+ width: 360px; flex: none; border-left: 1px solid var(--line); padding: 16px;
+ display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(18,20,28,.5);
+}
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; max-height: 40vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 8px; align-items: baseline; }
+#log li .i { color: var(--accent); }
+#log li .status { font-weight: 700; } #log li .status.pass { color: var(--ok); } #log li .status.fail { color: var(--rose); }
+#log li .ch { color: var(--ink); }
+#output { background: #0d0f16; border: 1px solid #1c2030; border-radius: 8px; padding: 10px; font-size: 11px; color: var(--dim); white-space: pre-wrap; max-height: 48vh; overflow-y: auto; margin: 0; }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-guard/viewer/studio.js b/store/agents/jev-guard/viewer/studio.js
new file mode 100644
index 000000000..b1adde2b8
--- /dev/null
+++ b/store/agents/jev-guard/viewer/studio.js
@@ -0,0 +1,119 @@
+// Jev Guard pane — a dashboard of Jev judging the coding agent's own live edits.
+
+const $ = (id) => document.getElementById(id)
+const els = { goal: $('goal'), run: $('run'), verdict: $('verdict'), chart: $('chart'), log: $('log'), output: $('output'), title: $('title'), meta: $('meta') }
+
+let history = []
+let lastRun = null
+
+function setMeter(key, val) {
+ const pct = Math.round((val / 2) * 100)
+ document.querySelector(`.meter .bar i[data-k="${key}"]`).style.width = pct + '%'
+ document.querySelector(`.meter .v[data-v="${key}"]`).textContent = val.toFixed(1) + '/2'
+}
+
+function renderRun(msg) {
+ const t = msg.lastRun
+ els.run.className = ''
+ els.run.innerHTML = ''
+ if (!t) {
+ els.run.innerHTML = '<div class="pulse"></div><span>waiting for the agent\'s first edit…</span>'
+ return
+ }
+ const pulse = document.createElement('div'); pulse.className = 'pulse'
+ const span = document.createElement('span')
+ span.textContent = t.passed
+ ? `passed — tests green (run ${msg.runCount})`
+ : `failed — tests failing (run ${msg.runCount})`
+ els.run.append(pulse, span)
+ els.run.classList.add(t.passed ? 'pass' : 'fail')
+ els.output.textContent = t.output.trim() || '(no output)'
+}
+
+function renderVerdict() {
+ const last = history[history.length - 1]
+ const v = els.verdict
+ v.textContent = '— no run judged yet —'
+ v.className = 'verdict'
+ if (!last) return
+ setMeter('toward', last.toward)
+ setMeter('trust', last.trust)
+ setMeter('risk', last.risk)
+ if (last.passed) {
+ v.textContent = 'goal met — Jev trusts this state'
+ v.classList.add('done')
+ } else if (last.toward >= 1) {
+ v.textContent = 'progress — tests still failing, Jev is wary'
+ v.classList.add('work')
+ } else {
+ v.textContent = 'failing — Jev is not confident'
+ v.classList.add('fail')
+ }
+}
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="i">#${h.i}</span><span class="status ${h.passed ? 'pass' : 'fail'}">${h.passed ? 'PASS' : 'FAIL'}</span><span>toward ${h.toward.toFixed(1)} · trust ${h.trust.toFixed(1)} · risk ${h.risk.toFixed(1)}</span>`
+ if (h.changed && h.changed !== '(no file changes)') {
+ const ch = document.createElement('span'); ch.className = 'ch'; ch.textContent = h.changed
+ li.appendChild(ch)
+ }
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function drawChart() {
+ const cv = els.chart, ctx = cv.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = cv.clientWidth, H = 160
+ cv.width = W * dpr; cv.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+ ctx.strokeStyle = '#1c2030'; ctx.lineWidth = 1
+ ctx.beginPath(); ctx.moveTo(4, H - 20); ctx.lineTo(W - 4, H - 20); ctx.stroke()
+ if (history.length < 2) return
+ const x = (i) => 6 + (i / (history.length - 1)) * (W - 12)
+ const y = (v) => H - 20 - v * (H - 32)
+ const line = (key, color) => {
+ ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.beginPath()
+ history.forEach((h, i) => { const px = x(i), py = y(h[key] / 2); i ? ctx.lineTo(px, py) : ctx.moveTo(px, py) })
+ ctx.stroke()
+ }
+ line('toward', '#5eead4')
+ line('trust', '#c084fc')
+ line('risk', '#fb7185')
+}
+
+function onJudge(msg) {
+ els.title.textContent = msg.title || ''
+ els.meta.textContent = msg.running ? 'auto-judging on edits' : 'manual'
+ els.goal.textContent = msg.goal || ''
+ history = msg.history || history
+ lastRun = msg.lastRun
+ renderRun(msg)
+ renderVerdict()
+ renderLog()
+ drawChart()
+}
+
+$('judge').onclick = () => ctl('judge')
+$('pause').onclick = () => ctl('pause')
+$('start').onclick = () => ctl('start')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+window.addEventListener('resize', drawChart)
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onJudge(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-guard/viewer/viewer.mjs b/store/agents/jev-guard/viewer/viewer.mjs
new file mode 100644
index 000000000..e1f18a003
--- /dev/null
+++ b/store/agents/jev-guard/viewer/viewer.mjs
@@ -0,0 +1,273 @@
+// Jev Guard viewer — a loopback server where Jev (TypeSafe's System One model) judges the coding
+// agent's own live edits. The agent works a tiny project (project/*.js) toward the goal in
+// goal.json. The viewer watches the project, runs the test suite on every change, and asks Jev to
+// score the resulting diff: how close to done, how risky, how much it trusts the change. The
+// verdict is Jev's running judgment of its own teammate's work.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. The workspace holds goal.json + project/.
+//
+// To keep it dependency-free and offline-safe, the test runner is a tiny harness: it invokes
+// `node project/test.js` (the template ships a plain-node test file) and parses pass/fail from
+// the exit code and "ALL TESTS PASS" marker. Swap test.js for any zero-dependency runner.
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync, readdirSync, statSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { spawnSync } from 'node:child_process'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT_GOAL = {
+ goal: 'Make every test in project/test.js pass without breaking the others.',
+ name: 'Jev Guard',
+ description: 'Jev judges your own edits live.',
+}
+
+function listFiles(dir, acc = [], base = '') {
+ for (const name of readdirSync(dir)) {
+ const full = join(dir, name)
+ const rel = base ? `${base}/${name}` : name
+ if (statSync(full).isDirectory()) {
+ if (name === '.harness' || name === 'node_modules') continue
+ listFiles(full, acc, rel)
+ } else {
+ acc.push(rel)
+ }
+ }
+ return acc
+}
+
+function snapshot(workspace) {
+ // Cheap content hash of the whole project so we can build diffs per edit.
+ const files = listFiles(join(workspace, 'project'))
+ const out = {}
+ for (const f of files) out[f] = readFileSync(join(workspace, 'project', f), 'utf8')
+ return out
+}
+
+export async function startGuardViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let goal = readGoal(join(workspace, 'goal.json'))
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let running = false
+ let error = null
+ let lastRun = null // { at, passed, failed, output }
+ let history = [] // [{ i, at, passed, failed, judge:{trust,risk,done,green} }]
+ let runCount = 0
+ let prev = snapshot(workspace)
+
+ function readGoal(file) {
+ try { return { ...DEFAULT_GOAL, ...JSON.parse(readFileSync(file, 'utf8')) } }
+ catch { return DEFAULT_GOAL }
+ }
+
+ function runTests() {
+ // Template tests are a plain-node script; return per-file/overall pass.
+ const res = spawnSync('node', [join(workspace, 'project', 'test.js')], { cwd: join(workspace, 'project'), encoding: 'utf8', timeout: 10000 })
+ const output = clean(res.stdout || '' + res.stderr || '')
+ const passed = res.status === 0
+ const failed = !passed
+ const green = /all tests pass/i.test(output)
+ return { passed, failed, green, output }
+ }
+
+ function diffSince(now) {
+ // Summarize the files that changed since the last run, for Jev to judge.
+ const changed = []
+ for (const [f, content] of Object.entries(prev)) {
+ let cur = null
+ try { cur = readFileSync(join(workspace, 'project', f), 'utf8') } catch { /* deleted */ }
+ if (cur !== content) changed.push(f)
+ }
+ for (const f of listFiles(join(workspace, 'project'))) if (!(f in prev)) changed.push(f)
+ return changed.length ? changed.join(', ') : '(no file changes)'
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function tail() {
+ const v = verdict(goal, lastRun, history, { error })
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'judge',
+ title: goal.name,
+ description: goal.description,
+ goal: goal.goal,
+ running,
+ error,
+ lastRun,
+ history: history.slice(-20),
+ runCount,
+ })
+ }
+
+ async function judge() {
+ if (stopped) return
+ try {
+ const t = runTests()
+ const changed = diffSince()
+ prev = snapshot(workspace)
+ runCount++
+ const res = await evaluate({
+ state: `You are Jev Guard, judging a coding agent's live work.
+Goal: ${goal.goal}
+
+Just now the agent changed these files: ${changed}.
+
+Test run #${runCount} result: ${t.passed ? 'PASSING' : 'FAILING'}${t.green ? ' (all tests green)' : ''}.
+Test output (last 400 chars):
+${t.output.slice(-400) || '(no output)'}
+
+Judge the agent's progress toward the goal.`,
+ questions: {
+ toward: {
+ type: 'score',
+ instructions: 'How much closer to the goal is the code right now?',
+ legend: { 0: 'no progress', 1: 'some', 2: 'done' },
+ },
+ trust: {
+ type: 'score',
+ instructions: 'How confident are you that this exact change is correct?',
+ legend: { 0: 'distrust', 1: 'wary', 2: 'confident' },
+ },
+ risk: {
+ type: 'score',
+ instructions: 'How risky was this change — could it be a regression in disguise?',
+ legend: { 0: 'safe', 1: 'risky', 2: 'reckless' },
+ },
+ green: {
+ type: 'noul',
+ instructions: 'Are all tests passing and is the goal met?',
+ },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const a = res.answers
+ const judgeRec = {
+ i: runCount,
+ at: new Date().toISOString(),
+ passed: t.passed,
+ green: t.green,
+ toward: typeof a.toward?.score === 'number' ? a.toward.score : 1,
+ trust: typeof a.trust?.score === 'number' ? a.trust.score : 1,
+ risk: typeof a.risk?.score === 'number' ? a.risk.score : 0,
+ done: a.green?.noul ?? 0,
+ changed,
+ client: res.client,
+ }
+ history.push(judgeRec)
+ if (history.length > 40) history.splice(0, history.length - 40)
+ lastRun = { at: judgeRec.at, passed: t.passed, failed: !t.passed, output: t.output }
+ error = null
+ } catch (e) {
+ error = clean(e.message)
+ }
+ tail()
+ }
+
+ let debounce = null
+ function scheduleJudge() {
+ clearTimeout(debounce)
+ debounce = setTimeout(judge, 300)
+ }
+
+ const watcher = watch(join(workspace, 'project'), { recursive: true }, () => {
+ if (running) scheduleJudge()
+ })
+ const goalWatcher = watch(workspace, (_, name) => {
+ if (!name) return
+ if (String(name).split('/').join('/') === 'goal.json') {
+ goal = readGoal(join(workspace, 'goal.json'))
+ tail()
+ }
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: goal.name, goal: goal.goal, running, lastRun, history: history.slice(-20), runCount })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') running = false
+ if (cmd === 'start') { if (!running) { running = true; scheduleJudge() } }
+ if (cmd === 'judge') await judge()
+ if (cmd === 'reset') { history = []; runCount = 0; lastRun = null; prev = snapshot(workspace); tail() }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ tail()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(debounce); watcher.close(); goalWatcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+function verdict(goal, lastRun, history, state) {
+ const len = history.length
+ const last = history[len - 1]
+ const done = last?.done ?? 0
+ return {
+ spec: 1,
+ ready: len > 0,
+ summary: state.error
+ ? 'Jev Guard needs a fix'
+ : last
+ ? `${goal.name} · ${done >= 0.8 ? 'goal met' : last.passed ? 'tests passing, judging…' : 'tests failing — agent is working'}` + (len ? ` (${len} runs)` : '')
+ : `${goal.name} · waiting for the agent's first edit`,
+ findings: (state.error ? [{ severity: 'error', kind: 'guard', message: state.error }] : []).concat(
+ last && !last.passed ? [{ severity: 'warn', kind: 'guard', message: `Test run #${last.i} failing (trust ${last.trust.toFixed(1)}/2, risk ${last.risk.toFixed(1)}/2)` }] : []
+ ),
+ artifact: 'project/',
+ phases: [
+ { id: 'edit', name: 'Agent edits', state: len ? 'active' : 'pending' },
+ { id: 'judge', name: 'Jev judges', state: len ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startGuardViewer({ workspace, port })
+ console.log(`Jev Guard listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-lander/.gitignore b/store/agents/jev-lander/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-lander/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-lander/AGENTS.md b/store/agents/jev-lander/AGENTS.md
new file mode 100644
index 000000000..8da5488ef
--- /dev/null
+++ b/store/agents/jev-lander/AGENTS.md
@@ -0,0 +1,83 @@
+# Jev Lander in OpenHarness
+
+On the left, Jev Lander is a landing pad: a booster drops out of the sky under gravity, and **Jev —
+TypeSafe's System One model — is the flight computer.** Every tick Jev reads altitude, vertical
+speed and fuel, and sets a throttle to bring it down soft. Touch down slow and it's a clean landing;
+hit hard and the booster is scrap. The physics is synthetic; the decision loop is the show.
+
+On the right, you edit `lander.json`. This is the ONLY file you edit. It holds the mission profile —
+the gravity, the fuel budget, the launch height — and the viewer watches it and Jev adapts
+immediately.
+
+## The lander file
+
+```jsonc
+{
+ "title": "Jev Lander",
+ "description": "Jev is the flight computer: throttle a booster down to a soft landing.",
+ "instrument": "LANDER",
+ "tickMs": 300,
+ "gravity": 1.2,
+ "fuel": 260,
+ "altitude": 80,
+ "safeSpeed": 2.0,
+ "style": "The booster is falling under gravity. Bring it down to the pad gently: watch altitude and vertical speed, burn early and hard enough to keep descent in check, and ease off so you touch down soft. A fast touchdown is a crash — go for the gentle landing."
+}
+```
+
+- **`gravity`** — the downward pull per tick (acceleration). Low (`1.0`) is an easy, forgiving
+ descent that Jev brings down soft; high (`3.0+`) makes it fall fast, burn hard, and start crashing.
+ This is the difficulty dial.
+- **`fuel`** — the paper fuel budget. Each tick thrust (COAST/HOVER/BURN) spends a little fuel. Less
+ fuel means Jev has less room to recover from a bad burn.
+- **`altitude`** — how high the booster starts. Higher up = more chance to pick up speed and more
+ chance to recover; very low = almost no room to react.
+- **`safeSpeed`** — the maximum touchdown speed for a soft landing. `2.0` is a gentle pad.
+- **`tickMs`** — how often the booster updates (and Jev decides). Fast ticks = a frantic controller;
+ slow ticks = a contemplative descent.
+- **`style`** — the instruction to Jev. It should name a landing strategy so Jev *decides* rather
+ than guesses.
+
+## Your job
+
+Design `lander.json` so the landing is an event:
+
+- **Pick a gravity with tension.** `1.0–1.5` gives clean, readable soft landings. Crank `vol` up to
+ `3+` and watch Jev's burns get twitchy and touchdowns start to crash — that flip is the fun.
+- **Choose a fuel budget.** On a high-gravity world, too little fuel means an inevitable crash; too
+ much means Jev hovers comfortably.
+- **Write a distinct style line.** "A fast touchdown is a crash, burn early and hard" plays very
+ differently from "coast as long as you can, then flare at the last second."
+
+Do NOT just ship the template. Every `lander.json` you publish should be its own mission with a
+deliberate, testable difficulty.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the landing: does Jev bring
+the booster down soft at the gravity you set, and crash when you crank it up — or does it hover
+forever (dull) or slam in even at easy gravity (bad)? Either extreme is a finding to report, not a
+bug to mask.
+
+## Rules
+
+- Keep `lander.json` valid JSON always. A bad edit freezes the landing on the last good state. You
+ can change `gravity`/`fuel`/`altitude` live — the viewer rebuilds the mission for the new profile.
+- Keep `title`, `description` and `style` truthful — and never present this as real rocketry, real
+ telemetry, or real mission control.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read before you
+ commit to it (e.g. "what does Jev set at G 3.0?"). Use the `jev` helpers: `noul`, `choice`,
+ `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the telemetry
+ and picks a sensible throttle — so the demo runs offline. With a key, the viewer calls the real
+ API.
+- The Jev Lander viewer writes `.harness/verdict.json` itself (ticks flown, throttle, landing
+ outcome). Do not edit it.
+- This is a demo. The booster, the physics and the telemetry are made up — never present this as a
+ real launch or real mission control.
+
+## Definition of done
+
+- A valid `lander.json` that parses and passes `toolchain/check.mjs`.
+- A mission with a real decision loop: Jev reads the telemetry, sets a throttle, and on a healthy
+ profile brings the booster down soft — and crashes when gravity is cranked up.
+- The gravity and style actually shape the burns — report it if Jev hovers forever, or slams in no
+ matter what.
diff --git a/store/agents/jev-lander/LICENSE b/store/agents/jev-lander/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-lander/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-lander/README.md b/store/agents/jev-lander/README.md
new file mode 100644
index 000000000..b04a6dd82
--- /dev/null
+++ b/store/agents/jev-lander/README.md
@@ -0,0 +1,57 @@
+# Jev Lander
+
+**Jev — TypeSafe's System One model — is the flight computer.** A booster drops out of the sky under
+gravity; every tick Jev reads altitude, vertical speed and fuel, sets a throttle — CUT / COAST /
+HOVER / BURN — and flies it down to the pad. Touch down slow and it's a clean landing; hit hard and
+the booster is scrap. Crank the gravity up and Jev's burns go twitchy and landings start to crash.
+
+This is a harness for OpenHarness. The agent on the right edits `lander.json`; the viewer on the
+left runs the landing and asks Jev for each tick's throttle, live. The decision loop is the show.
+
+## Anatomy
+
+```
+jev-lander/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to build missions with real decision loops
+ skills/lander/SKILL.md # the landing-design + verification craft
+ template/lander.json # a starter mission profile
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), lander-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates lander.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the landing pad)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs the landing over a loopback HTTP server. Each tick it integrates the
+booster (throttle − gravity, plus a touch of drag), asks Jev for the throttle, and streams the
+descent — the rocket on its trajectory, a flame plume that scales with the throttle, live
+altitude / speed / fuel readouts, and a decision log — to the pane. It calls `POST /v1/systemone`
+when `TYPESAFE_API_KEY` is set; without it a deterministic mock reads the same telemetry and picks a
+sensible throttle, so the demo runs offline. `.harness/verdict.json` tracks ticks flown, the throttle
+choices, and the landing outcome.
+
+The physics is synthetic: the booster falls under a set `gravity` (per-tick acceleration), and the
+throttles add upward acceleration. Jev's "throttle" is a moment-to-moment control call — burn to
+arrest the fall, ease off to land soft — which is why high gravity makes Jev look twitchy and crash.
+
+## Jev, honestly
+
+Jev's headline claim is speed — decide in a loop faster than a large model can. Lander celebrates
+that: a control decision on every tick. But the rocket, the physics and the telemetry are entirely
+made up, and Jev flies nothing real — this is a demo of decision-rate and calibration on a synthetic
+control problem, not a signal for real rocketry, and the mock is a stand-in for *plumbing*, not
+judgement. Treat any "landing" as a fun experiment, not engineering advice.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live flight computer — a landing pad
+you can watch Jev fly, judge, and bring down soft with every tick._
diff --git a/store/agents/jev-lander/THIRD_PARTY_NOTICES.md b/store/agents/jev-lander/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-lander/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-lander/harness.json b/store/agents/jev-lander/harness.json
new file mode 100644
index 000000000..2898e085d
--- /dev/null
+++ b/store/agents/jev-lander/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-lander",
+ "name": "Jev Lander",
+ "category": "Science",
+ "author": "Autonomous",
+ "description": "A live landing demo. A booster falls out of the sky under gravity; Jev — TypeSafe's System One model — is the flight computer, reading altitude, vertical speed and fuel every tick and setting a throttle to bring it down soft. Crank the gravity up and watch the touchdowns start to crash.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "lander.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-lander/skills/lander/SKILL.md b/store/agents/jev-lander/skills/lander/SKILL.md
new file mode 100644
index 000000000..f58934934
--- /dev/null
+++ b/store/agents/jev-lander/skills/lander/SKILL.md
@@ -0,0 +1,56 @@
+---
+name: jev-lander
+description: Design and verify Jev's landing missions in OpenHarness's viewer, where Jev is the flight computer throttling a booster down to a soft touchdown.
+---
+
+# Jev Lander landing design
+
+Jev Lander runs a live landing: a booster falls out of the sky under gravity and Jev (TypeSafe's
+System One model) reads the telemetry each tick and sets a throttle — CUT, COAST, HOVER or BURN —
+to bring it down soft. The agent shapes `lander.json`: the gravity, the fuel budget, and the launch
+height.
+
+## The loop
+
+1. Update `lander.json` (title, gravity, fuel, altitude, a `style` line that tells Jev a landing
+ strategy). The viewer watches it and Jev adapts live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `lander.json` is valid. Run it
+ before you call a mission done.
+3. Watch the descent. Does Jev burn early and hard enough to keep descent in check, flare low, and
+ touch down soft — or hover forever (dull) or slam in even at easy gravity (bad)? That observation
+ is the finding.
+
+## Reading the landing
+
+The viewer shows a booster descending against a starry sky, a flame plume that scales with the
+throttle Jev set, live altitude / vertical speed / fuel readouts, and a LANDED SOFT or CRASHED
+banner plus a flight log. Good missions produce a readable loop: Jev burns to arrest the fall, eases
+off low, and lands soft; `gravity` is the difficulty dial — crank it up and the burns get twitchy
+and touchdowns start to crash.
+
+## Verifying a mission
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `lander.json` is invalid (no title, a
+non-positive gravity/fuel/altitude/safeSpeed, out-of-range tickMs). It doesn't replace watching the
+descent: confirm Jev reads the telemetry and touches down soft at the gravity you set, and that
+cranking `gravity` up makes it visibly crash.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's read on a
+mission profile before you commit to it:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "The booster is falling under gravity. Bring it down to the pad gently: burn early and hard enough to keep descent in check, and ease off so you touch down soft. Telemetry: ALT 34.2 VY -2.4 G 2.5 FUEL 62%. Which throttle do you set for this tick? CUT / COAST / HOVER / BURN",
+ questions: {
+ thrust: jev.choice(["CUT", "COAST", "HOVER", "BURN"], "Which throttle do you set for this tick?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-lander/store.json b/store/agents/jev-lander/store.json
new file mode 100644
index 000000000..80bcf6c6d
--- /dev/null
+++ b/store/agents/jev-lander/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev is the flight computer, bringing a booster down soft, live",
+ "examples": [
+ {
+ "prompt": "Set Jev Lander up as a rough descent — boost the gravity and cut the fuel. Give Jev a decisive burn-early style line, then watch it read the telemetry every tick, throttle the booster down the pad, and land soft (or slam in when gravity is too high and the burns go twitchy).",
+ "caption": "Jev's Landing — a fast decision model flying a booster down to a soft touchdown on every tick"
+ }
+ ]
+}
diff --git a/store/agents/jev-lander/template/lander.json b/store/agents/jev-lander/template/lander.json
new file mode 100644
index 000000000..b5d758901
--- /dev/null
+++ b/store/agents/jev-lander/template/lander.json
@@ -0,0 +1,12 @@
+{
+ "title": "Jev Lander",
+ "description": "Jev is the flight computer: throttle a booster down to a soft landing.",
+ "instrument": "LANDER",
+ "tickMs": 300,
+ "gravity": 1.2,
+ "fuel": 260,
+ "startAlt": 80,
+ "altitude": 80,
+ "safeSpeed": 2.0,
+ "style": "The booster is falling under gravity. Bring it down to the pad gently: watch altitude and vertical speed, burn early and hard enough to keep descent in check, and ease off so you touch down soft. A fast touchdown is a crash — go for the gentle landing."
+}
diff --git a/store/agents/jev-lander/test/viewer.test.mjs b/store/agents/jev-lander/test/viewer.test.mjs
new file mode 100644
index 000000000..e92ba14eb
--- /dev/null
+++ b/store/agents/jev-lander/test/viewer.test.mjs
@@ -0,0 +1,84 @@
+// Viewer integration test for Jev Lander. Spins up the real viewer against a temp workspace and
+// checks the loop: the booster descends, Jev sets throttles, the verdict updates, and control
+// commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const CFG = {
+ title: 'Test Landing', instrument: 'LANDER', tickMs: 100, gravity: 1.2, fuel: 260, altitude: 80, safeSpeed: 2.0,
+ style: 'Bring it down soft.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-lander-test-'))
+ writeFileSync(join(ws, 'lander.json'), JSON.stringify({ ...CFG, ...overrides }))
+ const { startLanderViewer } = await import(viewerPath)
+ const viewer = await startLanderViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Lander descends and Jev sets throttles', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const deadline = Date.now() + 2500
+ let saw = false
+ let lastAlt = Infinity
+ while (Date.now() < deadline) {
+ await wait(120)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ if (s.history.length >= 3) {
+ assert.ok(['CUT', 'COAST', 'HOVER', 'BURN'].includes(s.thrust))
+ assert.ok(typeof s.y === 'number')
+ assert.ok(typeof s.v === 'number')
+ if (s.y < lastAlt) lastAlt = s.y
+ saw = true
+ break
+ }
+ }
+ assert.ok(saw, 'expected the booster to descend and Jev to set throttles')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Lander writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 1500
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Lander control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-lander/toolchain/README.md b/store/agents/jev-lander/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-lander/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-lander/toolchain/check.mjs b/store/agents/jev-lander/toolchain/check.mjs
new file mode 100644
index 000000000..025f2e285
--- /dev/null
+++ b/store/agents/jev-lander/toolchain/check.mjs
@@ -0,0 +1,31 @@
+#!/usr/bin/env node
+// check.mjs — validate a lander.json for the Jev Lander harness.
+// Enforces the shape the viewer needs: title, mission profile, tick interval.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'lander.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read lander.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!p.title || typeof p.title !== 'string') bad('warn no title')
+if (p.instrument && p.instrument !== 'LANDER') bad('warn instrument should be LANDER')
+if (typeof p.gravity !== 'number' || p.gravity <= 0) bad('error gravity must be a positive number')
+if (typeof p.fuel !== 'number' || p.fuel <= 0) bad('error fuel must be a positive number')
+const alt = p.altitude ?? p.startAlt
+if (typeof alt !== 'number' || alt <= 0) bad('error altitude must be a positive number')
+if (typeof p.tickMs !== 'number' || p.tickMs < 100 || p.tickMs > 5000) bad('error tickMs must be ms 100..5000')
+if (typeof p.safeSpeed !== 'number' || p.safeSpeed <= 0) bad('error safeSpeed must be a positive number')
+if (!p.style || typeof p.style !== 'string') bad('warn a style line helps Jev fly coherently')
+
+console.log(fail ? 'fail invalid lander.json' : 'ok lander.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-lander/toolchain/doctor.sh b/store/agents/jev-lander/toolchain/doctor.sh
new file mode 100755
index 000000000..5882c4ab2
--- /dev/null
+++ b/store/agents/jev-lander/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Lander viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-lander/toolchain/init-workspace.sh b/store/agents/jev-lander/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-lander/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-lander/toolchain/jev.mjs b/store/agents/jev-lander/toolchain/jev.mjs
new file mode 100644
index 000000000..7b8303481
--- /dev/null
+++ b/store/agents/jev-lander/toolchain/jev.mjs
@@ -0,0 +1,688 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+/**
+ * Pendulum-balancing read used by the mock when the state text carries the current pole angle and
+ * angular velocity (the viewer renders e.g. "angle: +12° velocity: -0.8 rad/s"). We compute the
+ * corrective action the pole is asking for: lean/fall to the right (positive angle) wants a
+ * leftward torque, and also damp any velocity. Returns per-action boosts so the deterministic mock
+ * biases toward the right call while staying slightly noisy — so Jev can fail when it's sloppy and
+ * the fall reads as Jev's mistake. Real Jev reads the same text — the mock is a stand-in.
+ */
+function pendulumRead(text) {
+ const mA = text.match(/angle:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const mV = text.match(/velocity:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const deg = mA ? Number(mA[1]) : NaN
+ const vel = mV ? Number(mV[1]) : NaN
+ if (!Number.isFinite(deg) || !Number.isFinite(vel)) return null
+ const a = (deg * Math.PI) / 180
+ // desired torque = -(Kp*a + Kv*vel); pick the action whose torque is closest.
+ const want = -(6.5 * a + 3.2 * vel)
+ const ACTS = { LEFT_HARD: -1.6, LEFT: -0.8, CENTER: 0, RIGHT: 0.8, RIGHT_HARD: 1.6 }
+ const boost = {}
+ for (const [name, t] of Object.entries(ACTS)) {
+ boost[name] = 1.4 - Math.abs(t - Math.max(-1.6, Math.min(1.6, want))) * 0.9
+ }
+ // The mock can't see the gravity dial — it just balances. But a fast judge on a hard
+ // rig will hesitate more, so the misjudgement rate rises with how hard the balance is.
+ // Low gravity: calm, near-perfect. High gravity: it starts to overshoot and lose it.
+ const hard = (parseFloat((text.match(/hardness:\s*([0-9.]+)/i) || [null, '0'])[1]) || 0)
+ const noise = Math.min(0.55, 0.03 + hard * 0.06)
+ return { boost, noise }
+}
+
+/**
+ * Pong-defender read used by the mock when the state text carries a ball position/velocity and the
+ * paddle's centre. We predict where the ball will cross the paddle's wall (reflecting off floor and
+ * ceiling) and bias the paddle move toward that intercept, with a reaction that degrades as the ball
+ * gets faster. Returns per-move boosts plus a beta error chance so Jev can visibly lose a fast rally.
+ */
+function pongRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/ball:\s*x\s+([-0-9.]+)/i)
+ const y = num(/y\s+([-0-9.]+)\s+vx/i)
+ const vx = num(/vx\s+([-0-9.]+)\s+vy/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const paddleY = num(/centre y\s+([-0-9.]+)/i)
+ const half = num(/half-height\s+([-0-9.]+)/i)
+ const courtH = num(/court:\s*[-0-9.]+\s*[x×]\s*([-0-9.]+)/i)
+ const speed = num(/speed:\s*([-0-9.]+)/i)
+ if (![x, y, vx, vy, paddleY, half, courtH, speed].every(Number.isFinite)) return null
+ const r = 3
+ const span = courtH - 2 * r
+ // When the ball is moving away (rightward), the paddle's job is to stop chasing and hold still so
+ // it's framed to meet the ball when it comes back — letting the rally breathe.
+ if (vx >= 0) return { boost: { HOLD: 1.9, MOVE_UP: 0.7, MOVE_DOWN: 0.7, MOVE_UP_FAST: 0.3, MOVE_DOWN_FAST: 0.3 }, noise: 0, close: false }
+ // time (in ball steps) to reach the left wall
+ const t = -x / vx
+ const dy = vy * t
+ let u = ((y - r + dy) % (2 * span) + 2 * span) % (2 * span)
+ u = u <= span ? u : 2 * span - u
+ const ty = r + u
+ const want = ty - paddleY
+ const goDown = want > half * 0.5
+ const goUp = want < -half * 0.5
+ const boost = {}
+ for (const name of ['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST']) {
+ if (goDown) boost[name] = name === 'MOVE_DOWN' ? 1.8 : name === 'MOVE_DOWN_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else if (goUp) boost[name] = name === 'MOVE_UP' ? 1.8 : name === 'MOVE_UP_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else boost[name] = name === 'HOLD' ? 1.8 : 0.8
+ }
+ // faster ball → the intercept at the wall changes fast and the paddle has fewer ticks to reach it,
+ // so the physical difficulty (max paddle speed) does the work. No injected noise: a miss is honest.
+ return { boost }
+}
+
+/**
+ * Shopper read used by the mock when the state text carries the recent price stream for each
+ * product (the viewer renders "Name: price (+x% over N ticks) vol v% [spark]"). We score each
+ * product by how fast its price is still falling — the best value right now — and bias the "best
+ * buy" choice toward the steepest falling momentum, plus a confidence that depends on how far the
+ * top pick stands out. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function shopperRead(text) {
+ const picks = []
+ const re = /^\s*([^:\n]+?):\s*([0-9.]+)\s*\(\s*([+-][0-9.]+)% over (\d+) ticks\)\s*vol\s*([0-9.]+)%\s*\[([^\]]*)\]/gim
+ let m
+ while ((m = re.exec(text))) {
+ const name = m[1].trim()
+ const price = Number(m[2])
+ const chgPct = Number(m[3])
+ picks.push({ name, price, chgPct })
+ }
+ if (picks.length < 2) return null
+ // best value = most negative recent change (still falling the fastest)
+ const sorted = picks.slice().sort((a, b) => a.chgPct - b.chgPct)
+ const best = sorted[0]
+ const second = sorted[1]
+ const spread = second.chgPct - best.chgPct
+ const boost = {}
+ for (const p of picks) boost[p.name] = p.name === best.name ? 1.6 : p.name === second.name ? 0.9 : 0.2
+ // confidence: strong when the leader clearly out-falls the rest; weak when it's a dead heat
+ const confidence = Math.min(0.95, Math.max(0.15, 0.5 + spread * 0.6))
+ return { boost, confidence, best: best.name }
+}
+
+/**
+ * Lander read used by the mock when the state text carries booster telemetry
+ * ("ALT x VY y G g FUEL f%"). We pick a throttle by altitude and vertical speed — burn early and
+ * hard enough to keep descent in check while high, flare gently low so the touchdown is soft —
+ * and bias the throttle choice toward it, with a noise term that grows with gravity so high-g
+ * missions look twitchy and start to crash. Real Jev reads the same lines — the mock is a
+ * stand-in.
+ */
+function landerRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const alt = num(/alt\s+([-0-9.]+)/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const g = num(/g\s+([-0-9.]+)/i)
+ if (![alt, vy, g].every((v) => Number.isFinite(v))) return null
+ let pick
+ if (alt > 30) {
+ if (vy < -2.5) pick = 'BURN'
+ else if (vy < -1.2) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 16) {
+ if (vy < -1.8) pick = 'BURN'
+ else if (vy < -0.8) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 7) {
+ if (vy < -1.0) pick = 'BURN'
+ else if (vy < -0.3) pick = 'HOVER'
+ else pick = 'COAST'
+ } else {
+ if (vy < -0.4) pick = 'BURN'
+ else pick = 'CUT'
+ }
+ const boost = { CUT: 0.2, COAST: 0.6, HOVER: 0.7, BURN: 0.5 }
+ if (boost[pick] !== undefined) boost[pick] = 1.9
+ // twitchiness grows with gravity: higher g -> more over/under correction
+ boost.noise = Math.min(0.55, 0.06 + Math.max(0, (g - 1.5)) * 0.14)
+ return { boost, pick, g }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ // Shopper: "act now" is urgent when the best buy clearly out-falls the field. Ask Jev to spend
+ // when the momentum spread is wide, so the demo eventually commits on paper.
+ if (/act now|spend now|strong enough/i.test(qtext) || /buy|act/i.test(q.instructions)) {
+ const shop = shopperRead(text)
+ if (shop && shop.confidence) p = Math.max(p, Math.min(0.9, 0.4 + shop.confidence * 0.5))
+ }
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Pendulum: if the state carries an angle + angular velocity, bias toward the balancing action,
+ // and occasionally flip to a neighbour (a fast model that sometimes hesitates) so the pole can
+ // visibly wobble — that wiggle is the demo.
+ const pen = pendulumRead(text)
+ if (pen) {
+ options.forEach((opt, i) => {
+ const b = pen.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (pen.noise && (hash01('pen', salt + 9) < pen.noise)) {
+ // flip the current best to two neighbours over — a big, costly overcorrection
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + (hash01('dir', salt) < 0.5 ? -2 : 2)))
+ if (ni !== best.i) raw[ni] += 2.2
+ }
+ }
+ // Pong: if the state text carries a ball + paddle, steer the paddle to the predicted intercept,
+ // and lag harder (miss more) as the ball speeds up.
+ const pong = pongRead(text)
+ if (pong) {
+ options.forEach((opt, i) => {
+ const b = pong.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Shopper: if the state carries a product price stream, bias "best buy" toward the product
+ // whose price is still falling the fastest.
+ const shop = shopperRead(text)
+ if (shop) {
+ options.forEach((opt, i) => {
+ const b = shop.boost[String(opt).toLowerCase()]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Lander: if the state carries booster telemetry, bias the throttle toward a plausible burn and
+ // flip to a worse one more often as gravity rises, so high-g missions look twitchy and crash.
+ const land = landerRead(text)
+ if (land) {
+ options.forEach((opt, i) => {
+ const b = land.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (land.boost.noise && (hash01('land', salt + 11) < land.boost.noise)) {
+ // over or under-throttle by one step — a costly hesitation
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const step = hash01('ldir', salt) < 0.5 ? 1 : -1
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + step))
+ if (ni !== best.i && land.boost[String(options[ni])] !== undefined) raw[ni] += 2.4
+ }
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-lander/toolchain/setup.sh b/store/agents/jev-lander/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-lander/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-lander/toolchain/viewer.sh b/store/agents/jev-lander/toolchain/viewer.sh
new file mode 100755
index 000000000..182c00e56
--- /dev/null
+++ b/store/agents/jev-lander/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Lander viewer (Jev is the flight computer, throttling a booster down to a soft landing).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-lander/viewer/index.html b/store/agents/jev-lander/viewer/index.html
new file mode 100644
index 000000000..1c3a6cfa3
--- /dev/null
+++ b/store/agents/jev-lander/viewer/index.html
@@ -0,0 +1,65 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Lander</title>
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Lander</h1></div>
+ <div class="stats">
+ <div class="stat"><label>Altitude</label><span id="alt">—</span></div>
+ <div class="stat"><label>Vert speed</label><span id="vy">—</span></div>
+ <div class="stat"><label>Throttle</label><span id="thrust">COAST</span></div>
+ <div class="stat"><label>Fuel</label><span id="fuel">—</span></div>
+ <div class="stat"><label>Gravity</label><span id="gravity">g1.2</span></div>
+ <div class="stat"><label>Ticks</label><span id="ticks">0</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="tick">Step</button>
+ <button class="primary" id="reset">Reset</button>
+ </div>
+ </div>
+ <main>
+ <section id="stage">
+ <div class="panel panel-stage">
+ <div class="panel-title">The landing pad</div>
+ <div id="sky">
+ <canvas id="scene"></canvas>
+ <div id="readout">
+ <div class="ro"><label>ALT</label><span id="r-alt">—</span></div>
+ <div class="ro"><label>VY</label><span id="r-vy">—</span></div>
+ <div class="ro"><label>FUEL</label><span id="r-fuel">—</span></div>
+ <div class="ro"><label>G</label><span id="r-g">—</span></div>
+ </div>
+ <div id="banner" class="hidden"></div>
+ </div>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Jev, the flight computer</div>
+ <div class="how">
+ A booster is falling out of the sky. Every tick Jev reads
+ <b>altitude, vertical speed and fuel</b> and sets a throttle:
+ <code>CUT</code> (none), <code>COAST</code> (idle), <code>HOVER</code>
+ (hold) or <code>BURN</code> (full). Touch down soft and it's a clean
+ landing; hit hard and the booster is scrap.<br><br>
+ Edit <code>lander.json</code>: crank <code>gravity</code> up and Jev's
+ burns get twitchy and landings start to crash; shrink <code>fuel</code>
+ and it has less room to recover.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Flight log</div>
+ <ul id="log"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-lander/viewer/jev-hud.js b/store/agents/jev-lander/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-lander/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-lander/viewer/studio.css b/store/agents/jev-lander/viewer/studio.css
new file mode 100644
index 000000000..ddb45e4af
--- /dev/null
+++ b/store/agents/jev-lander/viewer/studio.css
@@ -0,0 +1,83 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #f59e0b; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #070d1f 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(10,16,34,.9), rgba(7,9,16,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--cyan); box-shadow: 0 0 12px var(--cyan); }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#ticks { color: var(--dim); }
+#alt { color: var(--cyan); }
+#vy { color: var(--amber); }
+#thrust { color: var(--accent); }
+#fuel { color: var(--ok); }
+#gravity { color: var(--rose); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #0e7a63, #5eead4); border-color: transparent; color: #04131d; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+.panel-stage { padding: 10px; }
+
+#sky { position: relative; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: #02040a; }
+#scene { width: 100%; height: 62vh; display: block; }
+#readout {
+ position: absolute; top: 12px; left: 14px; display: flex; gap: 18px;
+ background: rgba(8,10,18,.55); border: 1px solid var(--line); border-radius: 8px; padding: 8px 14px;
+ backdrop-filter: blur(4px);
+}
+.ro { display: flex; flex-direction: column; align-items: center; }
+.ro label { font-size: 9px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.ro span { font-size: 15px; font-weight: 700; color: var(--cyan); }
+#r-vy { color: var(--amber); }
+#r-fuel { color: var(--ok); }
+#r-g { color: var(--rose); }
+#banner {
+ position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%);
+ padding: 10px 22px; border-radius: 10px; font-size: 15px; font-weight: 700; letter-spacing: .5px;
+}
+#banner.ok { background: rgba(52,211,153,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 30px rgba(52,211,153,.35); }
+#banner.bad { background: rgba(251,113,133,.16); border: 1px solid var(--rose); color: var(--rose); box-shadow: 0 0 30px rgba(251,113,133,.35); }
+#banner.hidden { display: none; }
+
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px; display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(7,10,22,.5); }
+.how { color: var(--dim); font-size: 13px; line-height: 1.5; }
+.how b { color: var(--cyan); }
+.how code { color: var(--amber); }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; max-height: 50vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 10px; align-items: baseline; }
+#log li .n { color: var(--accent); }
+#log li .a { width: 60px; color: var(--cyan); font-weight: 700; }
+#log li .y { color: var(--dim); }
+#log li .v { color: var(--amber); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-lander/viewer/studio.js b/store/agents/jev-lander/viewer/studio.js
new file mode 100644
index 000000000..e9d819bf0
--- /dev/null
+++ b/store/agents/jev-lander/viewer/studio.js
@@ -0,0 +1,214 @@
+// Jev Lander pane — draws a booster descending against a sky, its flame plume scaling with the
+// throttle Jev set, live altitude / speed / fuel readouts, and a landing-pad finish. Jev's throttle
+// is the beat; the trajectory is the show.
+
+const $ = (id) => document.getElementById(id)
+const els = {
+ alt: $('alt'), vy: $('vy'), thrust: $('thrust'), fuel: $('fuel'), gravity: $('gravity'), ticks: $('ticks'),
+ rAlt: $('r-alt'), rVy: $('r-vy'), rFuel: $('r-fuel'), rG: $('r-g'), banner: $('banner'), log: $('log'),
+ scene: $('scene'),
+}
+
+let y = 80, v = 0, fuel = 260, gravity = 1.2, safeSpeed = 2.0
+let thrust = 'COAST'
+let ticks = 0
+let finished = null
+let history = []
+
+const THRUST_LABEL = { CUT: 'cut', COAST: 'coast', HOVER: 'hover', BURN: 'burn' }
+
+// ---- flame plumes per throttle (3 tiers of chaos sampled deterministically per frame) ----
+const FLAMES = {
+ CUT: [],
+ COAST: [[0, 14, 4]],
+ HOVER: [[0, 30, 8], [-5, 24, 5], [5, 24, 5]],
+ BURN: [[0, 52, 12], [-10, 44, 8], [10, 44, 8], [-4, 40, 6], [4, 40, 6]],
+}
+
+function draw() {
+ const c = els.scene
+ const ctx = c.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = c.clientWidth, H = c.clientHeight
+ c.width = W * dpr; c.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+
+ // sky gradient
+ const sky = ctx.createLinearGradient(0, 0, 0, H)
+ sky.addColorStop(0, '#02040a')
+ sky.addColorStop(0.6, '#0a1024')
+ sky.addColorStop(1, '#1a1f35')
+ ctx.fillStyle = sky
+ ctx.fillRect(0, 0, W, H)
+
+ // a horizon ring of light low on the sky
+ ctx.fillStyle = 'rgba(94,234,212,.06)'
+ ctx.fillRect(0, H * 0.82, W, H * 0.18)
+
+ // stars
+ const starSeed = 20260919
+ for (let i = 0; i < 40; i++) {
+ const sx = ((starSeed * (i + 3)) % 997) / 997
+ const sy = ((starSeed * (i * 7 + 11)) % 991) / 991
+ ctx.fillStyle = `rgba(255,255,255,${0.25 + ((i * 13) % 5) / 16})`
+ ctx.fillRect(sx * W, sy * H * 0.7, 1.4, 1.4)
+ }
+
+ // pad & ground
+ const padW = 120, padH = 10
+ const padX = (W - padW) / 2, padY = H - 34
+ ctx.fillStyle = '#3b4254'
+ ctx.fillRect(0, padY + padH, W, H - padY - padH)
+ ctx.fillStyle = '#232838'
+ ctx.fillRect(padX, padY, padW, padH)
+ ctx.fillStyle = '#5eead4'
+ ctx.fillRect(padX + 10, padY - 3, padW - 20, 3)
+ ctx.fillStyle = 'rgba(94,234,212,.25)'
+ ctx.fillRect(0, padY, W, 2)
+
+ // where the rocket is: map [0..alt] -> near the pad .. near the top
+ const shownY = Math.max(0.5, y)
+ let rx, ry, scale
+ // boosters start high and far; as they near the pad they grow and center
+ const progress = Math.min(1, shownY / 50)
+ scale = 0.7 + 1.6 * (1 - progress)
+ ry = padY - 4 - progress * (padY - 40)
+ rx = W / 2
+
+ const rocketW = 16 * scale, rocketH = 34 * scale
+
+ // flame plume behind/under the rocket
+ const flames = FLAMES[thrust] || []
+ for (const [ox, len, wid] of flames) {
+ const flicker = 0.75 + 0.5 * ((Date.now() / 60 + ox) % 1)
+ ctx.fillStyle = thrust === 'BURN' ? `rgba(251,191,36,${0.9 * flicker})` : `rgba(245,158,11,${0.75 * flicker})`
+ ctx.beginPath()
+ ctx.moveTo(rx - wid * scale, ry + rocketH)
+ ctx.lineTo(rx + wid * scale, ry + rocketH)
+ ctx.lineTo(rx + ox * scale, ry + rocketH + len * scale * flicker)
+ ctx.closePath()
+ ctx.fill()
+ }
+
+ // rocket body
+ ctx.fillStyle = '#dfe5f2'
+ ctx.beginPath()
+ ctx.moveTo(rx, ry - rocketH * 0.4)
+ ctx.lineTo(rx + rocketW / 2, ry)
+ ctx.lineTo(rx + rocketW / 2, ry + rocketH)
+ ctx.lineTo(rx - rocketW / 2, ry + rocketH)
+ ctx.lineTo(rx - rocketW / 2, ry)
+ ctx.closePath()
+ ctx.fill()
+ // window
+ ctx.fillStyle = '#141827'
+ ctx.beginPath()
+ ctx.arc(rx, ry + rocketH * 0.25, 4 * scale, 0, Math.PI * 2)
+ ctx.fill()
+ // fins
+ ctx.fillStyle = '#f59e0b'
+ ctx.beginPath()
+ ctx.moveTo(rx + rocketW / 2, ry + rocketH * 0.5)
+ ctx.lineTo(rx + rocketW * 0.85, ry + rocketH)
+ ctx.lineTo(rx + rocketW / 2, ry + rocketH)
+ ctx.closePath()
+ ctx.fill()
+ ctx.beginPath()
+ ctx.moveTo(rx - rocketW / 2, ry + rocketH * 0.5)
+ ctx.lineTo(rx - rocketW * 0.85, ry + rocketH)
+ ctx.lineTo(rx - rocketW / 2, ry + rocketH)
+ ctx.closePath()
+ ctx.fill()
+
+ // landing done: a vivid ring + burst
+ if (finished) {
+ const col = finished.ok ? '#34d399' : '#fb7185'
+ ctx.strokeStyle = col
+ ctx.lineWidth = 3
+ ctx.beginPath()
+ ctx.arc(rx, ry + rocketH, 14 + 6 * ((Date.now() / 160) % 3), 0, Math.PI * 2)
+ ctx.stroke()
+ ctx.fillStyle = col
+ ctx.beginPath()
+ ctx.arc(rx, ry + rocketH, 4, 0, Math.PI * 2)
+ ctx.fill()
+ }
+
+ // trajectory trace (altitude over time, inverted)
+ ctx.strokeStyle = 'rgba(94,234,212,.5)'
+ ctx.lineWidth = 2
+ ctx.beginPath()
+ history.forEach((h, i) => {
+ const x = W * 0.08 + (i / Math.max(1, history.length - 1)) * (W * 0.84)
+ const yy = padY - 4 - (Math.min(1, h.y / 50)) * (padY - 40)
+ i ? ctx.lineTo(x, yy) : ctx.moveTo(x, yy)
+ })
+ ctx.stroke()
+}
+
+function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])) }
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history.slice(-40)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="n">#${h.step}</span><span class="a">${esc(h.action)}</span><span class="y">${h.y.toFixed(0)}</span><span class="v">${h.v.toFixed(1)}</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function faviconBanner() {
+ if (!finished) { els.banner.classList.add('hidden'); return }
+ els.banner.classList.remove('hidden')
+ els.banner.textContent = finished.ok
+ ? `✓ LANDED SOFT · ${finished.ticks} ticks · ${finished.fuelLeft} fuel left`
+ : `✗ CRASHED at ${finished.crashSpeed.toFixed(1)} · ${finished.ticks} ticks`
+ els.banner.className = 'banner ' + (finished.ok ? 'ok' : 'bad')
+}
+
+function onTick(msg) {
+ if (typeof msg.y === 'number') y = msg.y
+ if (typeof msg.v === 'number') v = msg.v
+ if (typeof msg.fuel === 'number') fuel = msg.fuel
+ if (typeof msg.gravity === 'number') gravity = msg.gravity
+ if (typeof msg.safeSpeed === 'number') safeSpeed = msg.safeSpeed
+ thrust = msg.thrust || thrust
+ ticks = msg.step ?? ticks
+ finished = msg.finished || null
+ history = msg.history || history
+
+ const vy = Math.abs(v) < 0.05 ? 0 : v
+ els.alt.textContent = y.toFixed(0)
+ els.vy.textContent = (vy >= 0 ? '+' : '') + vy.toFixed(1)
+ els.thrust.textContent = thrust
+ els.fuel.textContent = String(Math.round(fuel))
+ els.gravity.textContent = 'g' + gravity.toFixed(1)
+ els.ticks.textContent = String(ticks)
+ els.rAlt.textContent = y.toFixed(1)
+ els.rVy.textContent = (vy >= 0 ? '+' : '') + vy.toFixed(1)
+ els.rFuel.textContent = String(Math.round(fuel))
+ els.rG.textContent = gravity.toFixed(2)
+
+ faviconBanner()
+ renderLog()
+ draw()
+}
+
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+ setInterval(draw, 120) // keep flame flicker alive between ticks
+}
+connect()
diff --git a/store/agents/jev-lander/viewer/viewer.mjs b/store/agents/jev-lander/viewer/viewer.mjs
new file mode 100644
index 000000000..35185ef55
--- /dev/null
+++ b/store/agents/jev-lander/viewer/viewer.mjs
@@ -0,0 +1,241 @@
+// Jev Lander viewer — a loopback server running a live landing demo. A booster falls out of the sky
+// under gravity; Jev (TypeSafe's System One model) reads altitude, vertical speed and fuel every tick
+// and picks a throttle (CUT / COAST / HOVER / BURN) to bring it down soft. The agent shapes lander.json
+// (the gravity, the fuel budget, the launch height) — crank the gravity up and watch Jev's burns get
+// twitchy and the landings start to crash. The physics is synthetic; the decision loop is the demo.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds lander.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT = {
+ title: 'Jev Lander',
+ description: 'Jev is the flight computer: throttle a booster down to a soft landing.',
+ instrument: 'LANDER',
+ tickMs: 300, gravity: 1.2, fuel: 260, altitude: 80, safeSpeed: 2.0,
+ style: 'The booster is falling under gravity. Bring it down to the pad gently: watch altitude and vertical speed, burn early and hard enough to keep descent in check, and ease off so you touch down soft. A fast touchdown is a crash — go for the gentle landing.',
+}
+
+// per-tick vertical acceleration from each throttle setting (minus gravity + drag applied in sim)
+const THRUST = { CUT: 0, COAST: 0.4, HOVER: 1.15, BURN: 2.6 }
+const ACTIONS = ['CUT', 'COAST', 'HOVER', 'BURN']
+
+function stateBlock(p, s) {
+ return `${p.style}
+Telemetry (alt above pad, vertical speed, gravity, fuel remaining):
+ALT ${s.y.toFixed(1)} VY ${s.v.toFixed(1)} G ${p.gravity.toFixed(2)} FUEL ${(s.fuel / p.fuel * 100).toFixed(0)}%
+Which throttle do you set for this tick? ${ACTIONS.join(' / ')}`
+}
+
+export async function startLanderViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let error = null
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let step = 0
+ let running = false
+ let state = null // {y, v, fuel}
+ let thrust = 'COAST'
+ let episode = 0 // bumps each time an episode restarts on its own, so the next one differs
+ let finished = null // {ok, ticks, vy, fuelLeft, crashSpeed}
+ let history = [] // {step, y, v, action}
+ let notified = false
+
+ let p = readCfg(join(workspace, 'lander.json'))
+
+ function readCfg(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ return { ...DEFAULT, ...raw } // `altitude` and `startAlt` fall back via DEFAULT
+ } catch (e) {
+ error = clean(e.message)
+ return p || DEFAULT
+ }
+ }
+
+ function resetState() {
+ const y0 = p.altitude ?? p.startAlt ?? DEFAULT.altitude
+ const fuel0 = p.fuel ?? DEFAULT.fuel
+ state = { y: y0, v: 0, fuel: fuel0 }
+ thrust = 'COAST'
+ finished = null
+ history = []
+ notified = false
+ step = 0
+ error = null
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ const last = history[history.length - 1]
+ return {
+ spec: 1,
+ ready: history.length > 0 || finished !== null,
+ summary: error
+ ? 'Jev Lander needs a fix'
+ : finished
+ ? `${p.title} · ${finished.ok ? 'landed soft' : 'crashed at ' + finished.crashSpeed.toFixed(1)} · ${finished.ticks} ticks · ${finished.fuelLeft} fuel left`
+ : `${p.title} · alt ${state.y.toFixed(0)} · vy ${state.v.toFixed(1)} · ${history.length} ticks`,
+ findings: (error ? [{ severity: 'error', kind: 'lander', message: error }] : []).concat(
+ finished
+ ? [{ severity: finished.ok ? 'info' : 'error', kind: 'lander', message: finished.ok ? `Jev landed soft after ${finished.ticks} burns` : `Jev crashed at ${finished.crashSpeed.toFixed(1)} after ${finished.ticks} burns` }]
+ : []
+ ),
+ artifact: 'lander.json',
+ phases: [
+ { id: 'learn', name: 'Watching', state: history.length < 5 ? 'active' : 'done' },
+ { id: 'call', name: 'Guiding down', state: history.length >= 5 && !finished ? 'active' : finished ? 'done' : 'pending' },
+ { id: 'land', name: 'Landed', state: finished ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick', title: p.title, description: p.description, instrument: p.instrument,
+ gravity: p.gravity, fuel: p.fuel, safeSpeed: p.safeSpeed,
+ y: state?.y, v: state?.v, fuel: state?.fuel, thrust, step, running, error,
+ finished, history: history.slice(-200),
+ })
+ }
+
+ function reset() { resetState(); tail(); if (running) schedule() }
+ function pause() { running = false; clearTimeout(timer) }
+ function start() { if (!running) { running = true; schedule() } }
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, p.tickMs) }
+ async function run() {
+ if (stopped) return
+ if (finished) {
+ // Never sit on a finished screen: show the result briefly, then play again.
+ finished.shownAt ??= Date.now()
+ if (Date.now() - finished.shownAt > 3500) { episode++; resetState() }
+ tail(); schedule(); return
+ }
+ await decide()
+ schedule()
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ const res = await evaluate({
+ state: stateBlock(p, state),
+ questions: {
+ thrust: { type: 'choice', instructions: 'Which throttle do you set for this tick?', options: ACTIONS },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const pick = String(res.answers.thrust?.choice || 'COAST')
+ thrust = ACTIONS.includes(pick) ? pick : 'COAST'
+ // integrate physics with throttle, gravity and drag
+ const a = THRUST[thrust] - p.gravity
+ state.v += a
+ state.v -= Math.sign(state.v) * state.v * state.v * 0.004 // drag self-limits fall
+ state.y += state.v
+ state.fuel = Math.max(0, state.fuel - THRUST[thrust])
+ step++
+ history.push({ step, y: state.y, v: state.v, action: thrust })
+ if (history.length > 300) history.splice(0, history.length - 300)
+ if (state.y <= 0) {
+ state.y = 0
+ const ok = Math.abs(state.v) <= p.safeSpeed
+ finished = { ok, ticks: step, vy: state.v, fuelLeft: Math.round(state.fuel), crashSpeed: Math.abs(state.v) }
+ notified = true
+ }
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ const watcher = watch(join(workspace, 'lander.json'), () => {
+ p = readCfg(join(workspace, 'lander.json'))
+ tail()
+ if (running) schedule()
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: p.title, instrument: p.instrument, gravity: p.gravity, fuel: p.fuel, safeSpeed: p.safeSpeed, y: state?.y, v: state?.v, fuel: state?.fuel, thrust, step, running, error, finished, history: history.slice(-200) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ resetState()
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startLanderViewer({ workspace, port })
+ console.log(`Jev Lander listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-launcher/.gitignore b/store/agents/jev-launcher/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-launcher/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-launcher/AGENTS.md b/store/agents/jev-launcher/AGENTS.md
new file mode 100644
index 000000000..d11f87d78
--- /dev/null
+++ b/store/agents/jev-launcher/AGENTS.md
@@ -0,0 +1,75 @@
+# Jev Launcher in OpenHarness
+
+On the left, Jev Launcher is a live predictive command palette. **Jev — TypeSafe's System One
+model — is the oracle.** You type into the palette; on every keystroke Jev reads your query and
+re-ranks the launch targets, showing which one it would fire and how confident it is. Launching a
+target is always your call, and nothing actually launches — it's a demo of a decision model ranking
+in real time.
+
+On the right, you edit `launcher.json`. This is the ONLY file you edit. It holds the palette: the
+name, category and aliases for each launch target. The viewer watches it and Jev adapts
+immediately — change a target's aliases and the ranking moves.
+
+## The palette file
+
+```jsonc
+{
+ "title": "The Developer's Deck",
+ "description": "A command palette for a developer's everyday launch targets.",
+ "prompt": "You are Jev, a fast launcher oracle. Pick the ONE launch target the user most likely wants, and be decisive at every keystroke.",
+ "targets": [
+ { "name": "Run tests", "category": "Dev", "aliases": ["test", "pytest", "npm test", "spec"], "featured": true },
+ { "name": "Open Editor", "category": "Apps", "aliases": ["code", "vscode", "ide", "vim"] }
+ ]
+}
+```
+
+- **`targets[].name`** — what Jev is choosing among (shown in the ranking).
+- **`targets[].aliases`** — the words people would type to reach it. Jev fuzzy-matches your query
+ against name + aliases. Better aliases = sharper, more distinct ranking.
+- **`targets[].category`** — a small tag shown next to the name.
+- **`targets[].featured`** — true targets lead when the palette is idle and nothing is typed yet.
+
+## Your job
+
+Design palettes that show Jev ranking well:
+
+- **Give every target good aliases.** Jev ranks by matching your query against name + aliases.
+ Distinct, overlapping aliases (e.g. "ship", "release", "deploy") make the ranking obvious and fun
+ to watch as a query narrows.
+- **Curate a coherent palette.** Pick targets with a theme (a developer's deck, a media hub, a
+ spaceship's launch console). The `title` + `description` make it an event.
+- **Make it ambiguous-then-resolved.** A good demo is one where a partial query (like "de") is
+ genuinely uncertain and a longer one ("dep") snaps to a clear winner — that's the live re-ranking.
+
+Do NOT just ship the template. Every `launcher.json` you publish should be a distinct palette with a
+deliberate, testable ranking.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the ranking: does Jev's top
+pick track the query you typed — or does it pick the same target no matter what? If it doesn't move,
+that's a finding to report (likely aliases that don't match your queries), not a bug to mask.
+
+## Keep current
+
+- Keep `launcher.json` valid JSON always. A bad edit freezes the palette on the last good state.
+- Keep `title`, `description` and `prompt` truthful — and never present this as a real OS launcher.
+
+## Rules
+
+- Never propose opening a browser, changing ports, or running a second server. The viewer is already
+ running on the left.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read on a query
+ before you commit it (e.g. "what does Jev pick for 'de'?"). Use the `jev` helpers: `noul`,
+ `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the palette
+ and query and ranks by fuzzy match, so the desk works offline. With a key, the viewer calls the
+ real API.
+- The Jev Launcher viewer writes `.harness/verdict.json` itself. Do not edit it.
+- This is a demo. Launching is always on paper — never present it as real software launching.
+
+## Definition of done
+
+- A valid `launcher.json` that parses and passes `toolchain/check.mjs`.
+- A palette with a coherent theme and good per-target aliases so Jev's ranking is meaningful.
+- The ranking tracks the query: Jev's pick changes as you type, and confident queries get a clear
+ winner (report if it never moves).
diff --git a/store/agents/jev-launcher/LICENSE b/store/agents/jev-launcher/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-launcher/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-launcher/README.md b/store/agents/jev-launcher/README.md
new file mode 100644
index 000000000..15b133fc6
--- /dev/null
+++ b/store/agents/jev-launcher/README.md
@@ -0,0 +1,52 @@
+# Jev Launcher
+
+**Jev — TypeSafe's System One model — is a live predictive command palette.** You type into the
+palette; on every keystroke Jev reads your query and re-ranks the launch targets, showing which one
+it would fire and how confident it is. Curate a palette of targets (name, category, aliases); Jev
+does the ranking — the fastest, cheapest way to see a decision model decide in real time.
+
+This is a harness for OpenHarness. The agent on the right edits `launcher.json`; the viewer on the
+left runs the palette and asks Jev for each keystroke's ranking, live. Firing a target is always the
+agent's choice and happens on paper only.
+
+## Anatomy
+
+```
+jev-launcher/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to curate palettes that rank well
+ skills/launcher/SKILL.md # the palette-craft + verification craft
+ template/launcher.json # a starter palette
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), fuzzy-match aware
+ viewer.sh # launches the viewer
+ check.mjs # validates launcher.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the live palette)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` serves the palette over a loopback HTTP server. Each keystroke POSTs a query;
+the viewer asks Jev to pick which target best matches, then streams the running ranking (with
+confidence bars) to the pane. It calls `POST /v1/systemone` when `TYPESAFE_API_KEY` is set; without
+it a deterministic mock reads the same palette + query and ranks by fuzzy match, so the demo runs
+offline. `.harness/verdict.json` tracks the queries and picks so far.
+
+## Jev, honestly
+
+Jev's headline claim is speed: fast enough to make a decision on every keystroke. This harness makes
+that visible. But a ranking of launch targets is exactly the sort of thing that only matters as a
+demo — the palette is made-up, aliases are yours, and nothing actually launches. Jev is early-access
+and the mock is a stand-in for *plumbing*, not judgement. Treat any ranking as a fun demo, not a
+signal for what an operating system should do.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live launch oracle — a ranking you can
+watch re-decide with every keystroke._
diff --git a/store/agents/jev-launcher/THIRD_PARTY_NOTICES.md b/store/agents/jev-launcher/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-launcher/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-launcher/harness.json b/store/agents/jev-launcher/harness.json
new file mode 100644
index 000000000..b9c9f8703
--- /dev/null
+++ b/store/agents/jev-launcher/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-launcher",
+ "name": "Jev Launcher",
+ "category": "Productivity",
+ "author": "Autonomous",
+ "description": "A live predictive command palette. As you type, Jev — TypeSafe's System One model — re-ranks your launch targets on every keystroke, showing which one it would fire and how confident it is. Curate the palette; Jev does the ranking.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "launcher.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-launcher/skills/launcher/SKILL.md b/store/agents/jev-launcher/skills/launcher/SKILL.md
new file mode 100644
index 000000000..da4879835
--- /dev/null
+++ b/store/agents/jev-launcher/skills/launcher/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: jev-launcher
+description: Design and verify Jev's command palettes in OpenHarness's viewer, where Jev ranks launch targets live per keystroke.
+---
+
+# Jev Launcher palette design
+
+Jev Launcher shows a live predictive command palette: Jev (TypeSafe's System One model) reads a
+query and ranks which launch target to surface first, on every keystroke. The agent designs
+`launcher.json` — the palette of targets and the aliases Jev fuzzy-matches against.
+
+## The loop
+
+1. Update `launcher.json` (title, prompt, and the target list with categories + aliases). The viewer
+ watches it and Jev adapts live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `launcher.json` is valid. Run it
+ before you call a palette done.
+3. Watch the ranking. Does Jev's top pick track the query you typed — or does it pick the same
+ target regardless? That observation is the finding.
+
+## Reading Jev
+
+The viewer shows the full ranking with confidence bars for the current query. A good palette
+produces *movement*: Jev should re-rank as the query narrows. Distinct aliases and overlapping ones
+("ship", "release", "deploy") give Jev real signals; a query with no alias coverage makes Jev guess
+no matter what. An idle palette (nothing typed) should lead with `featured` targets.
+
+## Verifying a palette
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `launcher.json` is invalid (no title,
+fewer than two targets, duplicate names). It doesn't replace watching the ranking: type partial
+queries and confirm Jev's pick moves toward the target whose aliases match, and that a confident
+short query snaps to a clear winner.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's read on a
+query before you commit to it:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "A palette: 1. Open Editor [Apps] aliases: code, vscode, ide — launch. 2. Deploy [Ops] aliases: ship, release, deploy — launch. Current query: \"de\". Pick the ONE target that best matches.",
+ questions: {
+ pick: jev.choice(["Open Editor", "Deploy"], "Which launch target is the best match?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-launcher/store.json b/store/agents/jev-launcher/store.json
new file mode 100644
index 000000000..89482b791
--- /dev/null
+++ b/store/agents/jev-launcher/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev ranks a command palette live as you type",
+ "examples": [
+ {
+ "prompt": "Set Jev Launcher up as a developer's command palette — targets for run-tests, open-editor, deploy, chat, music — each with good aliases. Type partial queries and watch Jev re-rank the field on every keystroke, then fire the winner on paper.",
+ "caption": "Jev's Palette — a fast decision model ranking launch targets live, per keystroke"
+ }
+ ]
+}
diff --git a/store/agents/jev-launcher/template/launcher.json b/store/agents/jev-launcher/template/launcher.json
new file mode 100644
index 000000000..67ec77310
--- /dev/null
+++ b/store/agents/jev-launcher/template/launcher.json
@@ -0,0 +1,19 @@
+{
+ "title": "The Developer's Deck",
+ "description": "A command palette for a developer's everyday launch targets.",
+ "prompt": "You are Jev, a fast launcher oracle. Your job is to pick the ONE launch target the user most likely wants, and to be decisive at every keystroke.",
+ "targets": [
+ { "name": "Run tests", "category": "Dev", "aliases": ["test", "pytest", "npm test", "spec"], "featured": true },
+ { "name": "Open Editor", "category": "Apps", "aliases": ["code", "vscode", "ide", "vim"], "featured": true },
+ { "name": "Deploy to prod", "category": "Ops", "aliases": ["ship", "release", "deploy", "prod", "go live"] },
+ { "name": "Browser", "category": "Apps", "aliases": ["chrome", "firefox", "safari", "web", "internet"] },
+ { "name": "Check email", "category": "Apps", "aliases": ["mail", "gmail", "inbox", "outlook"] },
+ { "name": "Start local server", "category": "Dev", "aliases": ["server", "localhost", "dev server", "port"] },
+ { "name": "Music", "category": "Media", "aliases": ["spotify", "play", "tunes", "listen"] },
+ { "name": "Terminal", "category": "Apps", "aliases": ["shell", "console", "zsh", "bash", "iterm"] },
+ { "name": "Team chat", "category": "Comm", "aliases": ["slack", "discord", "dm", "chat", "msg"] },
+ { "name": "Calendar", "category": "Apps", "aliases": ["cal", "schedule", "meetings", "agenda"] },
+ { "name": "Notes", "category": "Prod", "aliases": ["notion", "obsidian", "memo", "scratch"] },
+ { "name": "Ship report", "category": "Ops", "aliases": ["report", "status", "summary", "handoff"] }
+ ]
+}
diff --git a/store/agents/jev-launcher/test/viewer.test.mjs b/store/agents/jev-launcher/test/viewer.test.mjs
new file mode 100644
index 000000000..68456dd73
--- /dev/null
+++ b/store/agents/jev-launcher/test/viewer.test.mjs
@@ -0,0 +1,94 @@
+// Viewer integration test for Jev Launcher. Spins up the real viewer against a temp workspace and
+// checks the loop: posting a query makes Jev rank the palette (a top pick with probabilities), the
+// verdict updates, and control commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const LAUNCHER = {
+ title: 'Test Palette', description: 'x', prompt: 'Pick the best match, be decisive.',
+ targets: [
+ { name: 'Run tests', category: 'Dev', aliases: ['test', 'pytest', 'spec'], featured: true },
+ { name: 'Deploy to prod', category: 'Ops', aliases: ['ship', 'release', 'deploy'] },
+ { name: 'Music', category: 'Media', aliases: ['spotify', 'play', 'tunes'] },
+ { name: 'Open Editor', category: 'Apps', aliases: ['code', 'vscode', 'ide'] },
+ ],
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-launcher-test-'))
+ writeFileSync(join(ws, 'launcher.json'), JSON.stringify({ ...LAUNCHER, ...overrides }))
+ const { startLauncherViewer } = await import(viewerPath)
+ const viewer = await startLauncherViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+const post = async (port, body) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
+ return res.status
+}
+
+test('Jev Launcher posts a query and ranks a target with probabilities', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ assert.equal(await post(port, { cmd: 'query', query: 'deploy' }), 200)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ assert.equal(s.query, 'deploy')
+ assert.ok(s.history.length >= 1)
+ const last = s.history[s.history.length - 1]
+ assert.ok(last.top, 'expected a top pick')
+ assert.ok(last.conf >= 0 && last.conf <= 1)
+ assert.ok(s.rank, 'expected full probabilities')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Launcher matching query picks the right target', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ await post(port, { cmd: 'query', query: 'test' })
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ assert.equal(s.history[s.history.length - 1].top, 'Run tests')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Launcher writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ await post(port, { cmd: 'query', query: 'edit' })
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ assert.ok(v.ready)
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Launcher control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ assert.equal(await post(port, { cmd: 'query', query: 'music' }), 200)
+ assert.equal(await post(port, { cmd: 'launch' }), 200)
+ assert.equal(await post(port, { cmd: 'reset' }), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-launcher/toolchain/README.md b/store/agents/jev-launcher/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-launcher/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-launcher/toolchain/check.mjs b/store/agents/jev-launcher/toolchain/check.mjs
new file mode 100644
index 000000000..8014be09e
--- /dev/null
+++ b/store/agents/jev-launcher/toolchain/check.mjs
@@ -0,0 +1,34 @@
+#!/usr/bin/env node
+// check.mjs — validate a launcher.json for the Jev Launcher harness.
+// Enforces the shape the viewer needs: a title, a palette of named launch targets (each with a
+// category and aliases), and a description of what kind of launcher this is.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let launcher
+try {
+ launcher = JSON.parse(readFileSync(join(ws, 'launcher.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read launcher.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!launcher.title || typeof launcher.title !== 'string') bad('error a title is required')
+if (!Array.isArray(launcher.targets) || launcher.targets.length < 2) bad('error targets must be a list of at least 2 launch targets')
+if (launcher.targets.length > 30) bad('error targets should be 30 or fewer (Jev ranks one choice per target per keystroke)')
+const seen = new Set()
+launcher.targets.forEach((t, i) => {
+ if (!t || typeof t !== 'object' || !t.name || typeof t.name !== 'string') bad(`error target ${i} needs a name`)
+ if (seen.has(t.name)) bad(`error duplicate target name: ${t.name}`)
+ seen.add(t.name)
+ if (!Array.isArray(t.aliases) || !t.aliases.length) bad(`warn target "${t.name}" has no aliases — give it a few so Jev has something to fuzzy-match`)
+})
+if (launcher.targets.length > 12) console.log('hint many targets — Jev will rank them all; keep names and aliases distinct so the ranking reads clearly')
+
+console.log(fail ? 'fail invalid launcher.json' : 'ok launcher.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-launcher/toolchain/doctor.sh b/store/agents/jev-launcher/toolchain/doctor.sh
new file mode 100644
index 000000000..29af8ece1
--- /dev/null
+++ b/store/agents/jev-launcher/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Launcher viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-launcher/toolchain/init-workspace.sh b/store/agents/jev-launcher/toolchain/init-workspace.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-launcher/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-launcher/toolchain/jev.mjs b/store/agents/jev-launcher/toolchain/jev.mjs
new file mode 100644
index 000000000..f79fe334d
--- /dev/null
+++ b/store/agents/jev-launcher/toolchain/jev.mjs
@@ -0,0 +1,492 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-launcher/toolchain/setup.sh b/store/agents/jev-launcher/toolchain/setup.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-launcher/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-launcher/toolchain/viewer.sh b/store/agents/jev-launcher/toolchain/viewer.sh
new file mode 100644
index 000000000..4e99ec0ce
--- /dev/null
+++ b/store/agents/jev-launcher/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Launcher viewer (Jev ranks a launch palette live per keystroke).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-launcher/viewer/index.html b/store/agents/jev-launcher/viewer/index.html
new file mode 100644
index 000000000..fcfdd53ce
--- /dev/null
+++ b/store/agents/jev-launcher/viewer/index.html
@@ -0,0 +1,52 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Jev Launcher</title>
+<link rel="icon" href="data:," />
+<link rel="stylesheet" href="/studio.css" />
+</head>
+<body>
+<header id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Launcher</h1></div>
+ <div id="title"></div>
+ <div class="controls">
+ <button id="clear">Clear</button>
+ <button id="demo" class="primary">Play the demo</button>
+ </div>
+</header>
+
+<main>
+ <section id="stage">
+ <div class="palette">
+ <div class="input-row">
+ <span class="prompt">❯</span>
+ <input id="query" type="text" placeholder="type to launch…" autocomplete="off" spellcheck="false" />
+ <span id="seq"></span>
+ </div>
+ <div id="results"></div>
+ <div class="hint">Every keystroke, Jev re-ranks the palette. <b>Enter</b> fires the top match.</div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Jev's pick over the last keystrokes</div>
+ <canvas id="chart"></canvas>
+ </div>
+ </section>
+
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Live ranking</div>
+ <div id="ranking"></div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Launched</div>
+ <div id="launched"></div>
+ </div>
+ </aside>
+</main>
+
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-launcher/viewer/jev-hud.js b/store/agents/jev-launcher/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-launcher/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-launcher/viewer/studio.css b/store/agents/jev-launcher/viewer/studio.css
new file mode 100644
index 000000000..ce8f7a11a
--- /dev/null
+++ b/store/agents/jev-launcher/viewer/studio.css
@@ -0,0 +1,79 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #c084fc; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #171a2b 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(23,26,36,.9), rgba(18,20,28,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+#title { color: var(--accent); font-size: 15px; font-weight: 700; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #7c3aed, #a855f7); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+
+.palette { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
+.input-row { display: flex; align-items: center; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--line); background: var(--panel2); }
+.prompt { color: var(--accent); font-size: 18px; font-weight: 700; }
+#query {
+ flex: 1; font: 600 20px var(--mono); color: var(--ink); background: transparent;
+ border: none; outline: none; caret-color: var(--accent);
+}
+#query::placeholder { color: #4b5266; font-weight: 400; }
+#seq { font-size: 11px; color: var(--dim); white-space: nowrap; }
+#results { padding: 6px; max-height: 46vh; overflow-y: auto; }
+.result { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; }
+.result.sel { background: linear-gradient(90deg, rgba(124,58,237,.22), transparent); box-shadow: inset 2px 0 0 var(--accent); }
+.result .rank { width: 20px; text-align: right; color: var(--dim); font-size: 12px; }
+.result .name { font-weight: 700; }
+.result.sel .name { color: #fff; }
+.result .cat { font-size: 10px; color: var(--dim); text-transform: uppercase; letter-spacing: .5px; }
+.result .bar { flex: 1; height: 8px; background: #0d0f16; border-radius: 4px; overflow: hidden; margin-left: 4px; }
+.result .bar i { display: block; height: 100%; background: linear-gradient(90deg, #7c3aed, #c084fc); border-radius: 4px; transition: width .18s ease; }
+.result .pct { width: 44px; text-align: right; font-size: 12px; color: var(--cyan); }
+.result.sel .pct { color: var(--accent); font-weight: 700; }
+.hint { padding: 10px 16px; color: var(--dim); font-size: 12px; border-top: 1px solid var(--line); }
+.hint b { color: var(--ink); }
+#chart { width: 100%; height: 200px; background: #0d0f16; border: 1px solid #1c2030; border-radius: 8px; }
+
+#rail {
+ width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px;
+ display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(18,20,28,.5);
+}
+#ranking { display: flex; flex-direction: column; gap: 6px; }
+.rankrow { display: flex; gap: 8px; align-items: baseline; font-size: 12px; color: var(--dim); }
+.rankrow .r { color: var(--accent); }
+.rankrow .q { max-width: 110px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rankrow .t { color: var(--ink); font-weight: 700; }
+#launched { font-size: 13px; }
+#launched .empty { color: var(--dim); }
+#launched .item { display: flex; gap: 8px; align-items: baseline; margin-bottom: 6px; }
+#launched .item .target { color: var(--ok); font-weight: 700; }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-launcher/viewer/studio.js b/store/agents/jev-launcher/viewer/studio.js
new file mode 100644
index 000000000..dc83f2f6d
--- /dev/null
+++ b/store/agents/jev-launcher/viewer/studio.js
@@ -0,0 +1,156 @@
+// Jev Launcher pane — the agent types and Jev re-ranks the palette live on every keystroke.
+// Shows the full ranking with confidence bars, the top pick, and how the pick evolved as the query
+// narrowed. Firing a launch is always the agent's choice — nothing is actually launched.
+
+const $ = (id) => document.getElementById(id)
+const els = { title: $('title'), query: $('query'), seq: $('seq'), results: $('results'), ranking: $('ranking'), launched: $('launched'), chart: $('chart') }
+
+let history = [] // [{seq, query, top, conf, probs, ts}]
+let launches = [] // [{name, ts}]
+let targets = []
+
+function fmtPct(x) { return (x * 100).toFixed(0) + '%' }
+
+async function ctl(body) {
+ try {
+ const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
+ if (!r.ok) throw new Error(String(r.status))
+ } catch (e) { console.error('control failed', e) }
+}
+
+function rankOptions() {
+ const last = history[history.length - 1]
+ const probs = last?.probs || {}
+ return targets
+ .map((t) => ({ t, p: probs[t.name] ?? 0 }))
+ .sort((a, b) => b.p - a.p)
+}
+
+function renderResults() {
+ els.results.textContent = ''
+ const ranked = rankOptions()
+ ranked.forEach(({ t, p }, i) => {
+ const row = document.createElement('div')
+ row.className = 'result' + (i === 0 ? ' sel' : '')
+ row.innerHTML = `<span class="rank">${i + 1}</span><span class="name">${escapeHtml(t.name)}</span><span class="cat">${escapeHtml(t.category || '')}</span><span class="bar"><i style="width:${(p * 100).toFixed(1)}%"></i></span><span class="pct">${fmtPct(p)}</span>`
+ row.onclick = () => { fire(t.name) }
+ els.results.appendChild(row)
+ })
+}
+
+function renderRanking() {
+ els.ranking.textContent = ''
+ for (const h of history.slice(-14)) {
+ const row = document.createElement('div')
+ row.className = 'rankrow'
+ row.innerHTML = `<span class="r">#${h.seq}</span><span class="q">"${escapeHtml(h.query)}"</span><span class="t">→ ${escapeHtml(h.top)}</span><span class="pct">${fmtPct(h.conf)}</span>`
+ els.ranking.appendChild(row)
+ }
+ els.ranking.scrollTop = els.ranking.scrollHeight
+}
+
+function renderLaunched() {
+ els.launched.textContent = ''
+ if (!launches.length) { els.launched.innerHTML = '<span class="empty">Press <b>Enter</b> to fire a launch (nothing really launches).</span>'; return }
+ for (const l of launches.slice(-8).reverse()) {
+ const item = document.createElement('div')
+ item.className = 'item'
+ item.innerHTML = `<span class="target">${escapeHtml(l.name)}</span><span class="dim">${l.ts.replace('T', ' ').slice(5, 19)}</span>`
+ els.launched.appendChild(item)
+ }
+}
+
+function drawChart() {
+ const cv = els.chart, ctx = cv.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = cv.clientWidth, H = 200
+ cv.width = W * dpr; cv.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+ ctx.font = '10px ' + 'monospace'
+ ctx.textBaseline = 'top'
+ if (history.length < 2) {
+ ctx.fillStyle = '#4b5266'
+ ctx.fillText('type to see Jev’s pick evolve…', 12, 12)
+ return
+ }
+ const pad = { l: 8, r: 8, t: 10, b: 20 }
+ const plotW = W - pad.l - pad.r, plotH = H - pad.t - pad.b
+ const px = (i) => pad.l + (i / (history.length - 1)) * plotW
+ const py = (v) => pad.t + plotH - v * plotH
+ ctx.strokeStyle = '#1c2030'; ctx.lineWidth = 1
+ for (let g = 0; g <= 4; g++) { const y = pad.t + (g / 4) * plotH; ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(W - pad.r, y); ctx.stroke() }
+ ctx.strokeStyle = '#c084fc'; ctx.lineWidth = 2; ctx.beginPath()
+ history.forEach((h, i) => { const x = px(i), y = py(h.conf || 0); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y) })
+ ctx.stroke()
+ ctx.fillStyle = '#8a90a6'
+ ctx.fillText('Jev’s confidence in its top pick, per keystroke', pad.l, H - 4)
+}
+
+function onTick(msg) {
+ els.title.textContent = msg.title || ''
+ history = msg.history || history
+ targets = msg.targets || targets
+ if (msg.query !== undefined && document.activeElement !== els.query) els.query.value = msg.query
+ if (msg.seq !== undefined) els.seq.textContent = '#' + msg.seq
+ renderResults()
+ renderRanking()
+ renderLaunched()
+ drawChart()
+}
+
+function escapeHtml(s) { return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])) }
+
+function fire(name) {
+ launches.push({ name, ts: new Date().toISOString() })
+ ctl({ cmd: 'launch' })
+ renderLaunched()
+}
+
+let debounce = null
+els.query.addEventListener('input', () => {
+ clearTimeout(debounce)
+ debounce = setTimeout(() => { if (thereIsAQuery()) ctl({ cmd: 'query', query: els.query.value }) }, 40)
+})
+els.query.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') {
+ const top = rankOptions()[0]?.t?.name
+ if (top) fire(top)
+ }
+})
+
+function thereIsAQuery() { return els.query.value.length > 0 }
+
+$('clear').onclick = () => { els.query.value = ''; ctl({ cmd: 'reset' }); focusQuery() }
+$('demo').onclick = () => playDemo()
+function focusQuery() { els.query.focus() }
+
+// The demo types a query one keystroke at a time (one launch at the end).
+const DEMO_QUERIES = ['deploy', 'music', 'email', 'test']
+async function playDemo() {
+ $('demo').disabled = true
+ for (const q of DEMO_QUERIES) {
+ els.query.value = ''
+ await typeOut(q)
+ }
+ const top = rankOptions()[0]?.t?.name
+ if (top) fire(top)
+ $('demo').disabled = false
+}
+async function typeOut(q) {
+ for (let i = 1; i <= q.length; i++) {
+ els.query.value = q.slice(0, i)
+ ctl({ cmd: 'query', query: els.query.value })
+ await new Promise((r) => setTimeout(r, 260))
+ }
+}
+
+focusQuery()
+window.addEventListener('resize', drawChart)
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-launcher/viewer/viewer.mjs b/store/agents/jev-launcher/viewer/viewer.mjs
new file mode 100644
index 000000000..3cfb896cc
--- /dev/null
+++ b/store/agents/jev-launcher/viewer/viewer.mjs
@@ -0,0 +1,243 @@
+// Jev Launcher viewer — a loopback server powering a live predictive command palette. The agent
+// types into the palette; on every keystroke Jev (TypeSafe's System One model) ranks the launch
+// targets and returns which one it would fire, with a confidence. The pane shows the running
+// re-ranking live — the top target flips as the query narrows. Launching a target is the agent's
+// choice and always on paper.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds launcher.json (watched
+// live); the agent edits its targets/catalog and Jev adapts immediately.
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT_LAUNCHER = {
+ title: 'The Developer’s Deck',
+ description: 'A command palette for a developer’s everyday launch targets.',
+ prompt: 'You are Jev, a fast launcher oracle. Pick the ONE launch target the user most likely wants, and be decisive at every keystroke.',
+ targets: [
+ { name: 'Run tests', category: 'Dev', aliases: ['test', 'pytest', 'spec'], featured: true },
+ { name: 'Open Editor', category: 'Apps', aliases: ['code', 'vscode', 'ide'], featured: true },
+ { name: 'Browser', category: 'Apps', aliases: ['chrome', 'web', 'internet'] },
+ { name: 'Terminal', category: 'Apps', aliases: ['shell', 'console', 'zsh', 'bash'] },
+ { name: 'Deploy to prod', category: 'Ops', aliases: ['ship', 'release', 'deploy'] },
+ { name: 'Team chat', category: 'Comm', aliases: ['slack', 'discord', 'dm'] },
+ ],
+}
+
+// Deterministic PRNG seeded per run so the palette is reproducible within a session.
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+function catalogBlock(l) {
+ const rows = l.targets.map((t, i) =>
+ `${i + 1}. ${t.name} [${t.category || '—'}]${t.featured ? ' (featured)' : ''} aliases: ${(t.aliases || []).join(', ')} — launch`
+ ).join('\n')
+ return `${l.prompt || 'You are a fast, decisive launch-oracle.'}
+A launch palette — each numbered target, its category, and its aliases:
+
+${rows}
+
+The user typed nothing yet — the palette is idle, waiting for a query.
+Rank the targets by which one would be most useful to surface first.`
+}
+
+function stateBlock(l, query) {
+ const rows = l.targets.map((t, i) =>
+ `${i + 1}. ${t.name} [${t.category || '—'}]${t.featured ? ' (featured)' : ''} aliases: ${(t.aliases || []).join(', ')} — launch`
+ ).join('\n')
+ const q = (query || '').trim()
+ return `${l.prompt || 'You are a fast, decisive launch-oracle.'}
+A launch palette — each numbered target, its category, and its aliases:
+
+${rows}
+
+Current query: "${q}"
+Pick the ONE target that best matches "${q}". Be decisive, even on a noisy or partial match.`
+}
+
+export async function startLauncherViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let launcher = readLauncher(join(workspace, 'launcher.json'))
+ let rng = mulberry32(2024)
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let query = ''
+ let seq = 0
+ let error = null
+ let lasthistory = [] // [{seq, query, top, conf, ts}]
+ let launches = 0 // how many targets the agent has "fired"
+
+ function readLauncher(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ return {
+ ...DEFAULT_LAUNCHER,
+ ...raw,
+ targets: Array.isArray(raw.targets) && raw.targets.length ? raw.targets : DEFAULT_LAUNCHER.targets,
+ }
+ } catch (e) {
+ error = clean(e.message)
+ return DEFAULT_LAUNCHER
+ }
+ }
+
+ // The target Jev would fire for the current query — re-ranked live on every keystroke.
+ function currentPick() {
+ const top = lasthistory[lasthistory.length - 1]
+ return top ? { name: top.top, conf: top.conf } : null
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ const ready = lasthistory.length > 0
+ const last = lasthistory[lasthistory.length - 1]
+ return {
+ spec: 1,
+ ready,
+ summary: error
+ ? 'Jev Launcher needs a fix'
+ : last
+ ? `${launcher.title || 'Jev Launcher'} · query "${last.query || '∅'}" → ${last.top || '—'} (${(last.conf * 100).toFixed(0)}%) · ${lasthistory.length} keystrokes`
+ : `${launcher.title || 'Jev Launcher'} · waiting for a query`,
+ findings: (error ? [{ severity: 'error', kind: 'launcher', message: error }] : []).concat(
+ lasthistory.length > 4 && last && (last.conf ?? 0) < 0.35
+ ? [{ severity: 'warn', kind: 'launcher', message: 'Jev is confident on the current query' }]
+ : []
+ ),
+ artifact: 'launcher.json',
+ phases: [
+ { id: 'idle', name: 'Idle', state: lasthistory.length === 0 ? 'active' : 'done' },
+ { id: 'live', name: 'Live ranking', state: lasthistory.length > 0 ? 'active' : 'pending' },
+ { id: 'launch', name: 'Launches', state: launches > 0 ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'rank', title: launcher.title, description: launcher.description,
+ query, seq, error, history: lasthistory.slice(-200),
+ rank: paletteState().rank, targets: launcher.targets,
+ })
+ }
+
+ async function runQuery(q) {
+ if (stopped) return
+ query = q
+ try {
+ const res = await evaluate({
+ state: stateBlock(launcher, q),
+ questions: {
+ pick: { type: 'choice', instructions: 'Which launch target is the best match for this query?', options: launcher.targets.map((t) => t.name) },
+ conf: { type: 'noul', instructions: 'Is this the target the user really wants?' },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const pick = res.answers.pick || {}
+ const probs = pick.probabilities || {}
+ const top = String(pick.choice || launcher.targets[0]?.name || '')
+ // confidence = how concentrated the ranking is on the top target (choice confidence).
+ const conf = typeof pick.confidence === 'number' ? pick.confidence : 0.5
+ const sure = typeof res.answers.conf?.noul === 'number' ? res.answers.conf.noul : 0.5
+ lasthistory.push({ seq: ++seq, query: q, top, conf, sure, probs, ts: new Date().toISOString(), client: res.client })
+ if (lasthistory.length > 200) lasthistory.splice(0, lasthistory.length - 200)
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ }
+
+ function paletteState() {
+ const last = lasthistory[lasthistory.length - 1]
+ return {
+ title: launcher.title, description: launcher.description, query,
+ targets: launcher.targets, seq, error, history: lasthistory.slice(-200),
+ rank: last ? last.probs : null,
+ }
+ }
+
+ const watcher = watch(workspace, { recursive: true }, (_, name) => {
+ if (!name) return
+ if (String(name).split('/').join('/') === 'launcher.json') {
+ launcher = readLauncher(join(workspace, 'launcher.json'))
+ if (query) runQuery(query)
+ tail()
+ }
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(paletteState())) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}')
+ if (cmd.cmd === 'query') { await runQuery(String(cmd.query ?? '')); tail() }
+ else if (cmd.cmd === 'launch') { launches++; tail() }
+ else if (cmd.cmd === 'reset') { query = ''; seq = 0; lasthistory = []; launches = 0; tail() }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ tail()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startLauncherViewer({ workspace, port })
+ console.log(`Jev Launcher listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-pendulum/.gitignore b/store/agents/jev-pendulum/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-pendulum/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-pendulum/AGENTS.md b/store/agents/jev-pendulum/AGENTS.md
new file mode 100644
index 000000000..13d9049f2
--- /dev/null
+++ b/store/agents/jev-pendulum/AGENTS.md
@@ -0,0 +1,88 @@
+# Jev Pendulum in OpenHarness
+
+On the left, Jev Pendulum is a live inverted-pendulum experiment: a stiff rod stands upright on a
+pivot, and **Jev — TypeSafe's System One model — is the balancer.** Every tick Jev reads the rod's
+lean and angular velocity and picks a corrective torque (`LEFT_HARD`, `LEFT`, `CENTER`, `RIGHT`,
+`RIGHT_HARD`); the rod swings. Hold it up long enough and it's a balancing act you can watch.
+
+On the right, you edit `pendulum.json`. This is the ONLY file you edit. It sets the simulation —
+gravity, torque authority, gust strength — and the style line that tells Jev how to balance. The
+viewer watches it and Jev adapts immediately.
+
+## The pendulum file
+
+```jsonc
+{
+ "title": "The Balance Rod",
+ "description": "Jev keeps a stiff rod upright on a pivot — a live balancing act.",
+ "instrument": "ROD",
+ "gravity": 7,
+ "length": 1.0,
+ "damping": 0.5,
+ "maxTorque": 0.8,
+ "stepMs": 80,
+ "gustEvery": 10,
+ "gustStrength": 0.5,
+ "fallDeg": 60,
+ "style": "Keep the rod upright. Correct every lean immediately, shrink the swing, and never let it drift past the edge. You are a fast, steady balancer."
+}
+```
+
+- **`gravity`** — the difficulty dial. `5–6` is calm; `7–8` is tense; `9+` Jev starts to lose it and
+ the rod topples. This is *the* knob the agent turns to stress Jev.
+- **`maxTorque`** — how strong Jev's corrective torque is. Lower authority (≈`0.8`) makes Jev work
+ harder and gives bigger swings; very high authority makes balancing trivial.
+- **`gustEvery` / `gustStrength`** — a sideways kick every N ticks. Jev must recover before the
+ next one; strong+fast gusts are how you make it visibly lose control.
+- **`length` / `damping` / `fallDeg`** — physical tuning. Keep `fallDeg` around `60` (the pane draws
+ the danger wedge there).
+- **`style`** — the instruction to Jev. It should name a coherent balancing strategy (aggressive
+ correction, wait-and-see, shrink the swing) so Jev *decides* rather than guesses.
+
+## Your job
+
+Design `pendulum.json` so the balancing act is an event:
+
+- **Pick a gravity with tension.** `8–9` is a sweet spot: Jev keeps it up for a while, wobbles hard,
+ and eventually drops if the gusts are unfriendly. `5` never falls (you'll want to show that first
+ so the audience sees Jev *can* hold it); `11+` drops fast.
+- **Tune gusts for drama.** A gust every few ticks at a strength that pushes the rod near the wedge
+ but not over — then Jev's recovery is the show.
+- **Write a distinct style line.** Give Jev a strategy. `"Shrink the swing and never let it drift
+ past the edge"` plays differently from `"react fast to every lean, don't overthink it"`.
+
+Do NOT just ship the template. Every `pendulum.json` you publish should be its own rig with a
+deliberate, testable balance.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the motion: does Jev hold it
+up, struggle, and sometimes lose it — or does it always stand like a statue (too easy) or always
+fall (too hard)? Either extreme is a finding to report, not a bug to mask.
+
+## Keep current
+
+- Keep `pendulum.json` valid JSON always. A bad edit freezes the rig on the last good state.
+- Keep `title`, `description` and `style` truthful — and never present this as a real physical
+ system or real control software.
+
+## Rules
+
+- Never propose opening a browser, changing ports, or running a second server. The viewer is already
+ running on the left.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read on a state
+ before you commit to a rig (e.g. "what does Jev do at angle 8°, velocity 0.3?"). Use the `jev`
+ helpers: `noul`, `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the angle,
+ velocity and hardness dial and biases toward the balancing torque — so the demo runs offline. With
+ a key, the viewer calls the real API.
+- The Jev Pendulum viewer writes `.harness/verdict.json` itself (falls, best run, current tilt). Do
+ not edit it.
+- This is a demo. The rod is a canvas drawing and Jev is picking paper torque values — never present
+ this as real control engineering.
+
+## Definition of done
+
+- A valid `pendulum.json` that parses and passes `toolchain/check.mjs`.
+- A rig with real tension: Jev visibly wobbles and, if you push gravity or gusts hard enough, drops.
+ A swing that's never in danger is a solved problem, not a good harness.
+- The style line actually shapes the balance — report it if Jev behaves identically no matter what
+ you write.
diff --git a/store/agents/jev-pendulum/LICENSE b/store/agents/jev-pendulum/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-pendulum/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-pendulum/README.md b/store/agents/jev-pendulum/README.md
new file mode 100644
index 000000000..723753546
--- /dev/null
+++ b/store/agents/jev-pendulum/README.md
@@ -0,0 +1,56 @@
+# Jev Pendulum
+
+**Jev — TypeSafe's System One model — is a live balancing act.** A stiff rod stands upright on a
+pivot; every tick Jev reads the lean and the swing and picks a corrective torque to keep it from
+toppling. You tune the rig — gravity, gust strength, torque authority — and watch how much Jev can
+hold. Turn the gravity up and it starts to lose it.
+
+This is a harness for OpenHarness. The agent on the right edits `pendulum.json`; the viewer on the
+left simulates the rod and asks Jev for each tick's torque, live. The balance is the show.
+
+## Anatomy
+
+```
+jev-pendulum/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to build rigs with real tension
+ skills/pendulum/SKILL.md # the rig-tuning + verification craft
+ template/pendulum.json # a starter rig
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), pendulum-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates pendulum.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the live rod)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` simulates the inverted pendulum over a loopback HTTP server. Each tick it meters
+the rod's angle and angular velocity, asks Jev to pick a torque, integrates one step, and streams
+the live rod, tilt chart and decision log to the pane. It calls `POST /v1/systemone` when
+`TYPESAFE_API_KEY` is set; without it a deterministic mock reads the same angle, velocity and
+hardness and biases toward the balancing torque, so the demo runs offline. `.harness/verdict.json`
+tracks falls, the best run and the current tilt.
+
+The physics is a uniform rod: `θ'' = (3g/2L)·sin(θ) + (3/L²)·τ − c·θ'`, with discrete torque
+actions. `gravity` maps to a hardness dial (`0..1`); higher gravity both pulls the rod over harder
+and makes the mock's rare overcorrections matter more — that's the difficulty curve you watch.
+
+## Jev, honestly
+
+Jev's headline claim is speed — decide in a loop faster than a large model can. The pendulum
+celebrates that: a decision every ~80ms that has to actually keep the rod up. But the rod is a
+canvas drawing and the physics is a toy — this is a demo of decision-rate and calibration, not a
+signal for real control systems, and the mock is a stand-in for *plumbing*, not judgement. Treat any
+balancing act as a fun experiment, not an engineering result.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live balancer — a rod you can watch
+swing, recover and, at high gravity, drop._
diff --git a/store/agents/jev-pendulum/THIRD_PARTY_NOTICES.md b/store/agents/jev-pendulum/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-pendulum/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-pendulum/harness.json b/store/agents/jev-pendulum/harness.json
new file mode 100644
index 000000000..6977d7405
--- /dev/null
+++ b/store/agents/jev-pendulum/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-pendulum",
+ "name": "Jev Pendulum",
+ "category": "Science",
+ "author": "Autonomous",
+ "description": "A live inverted-pendulum experiment. A stiff rod stands upright on a pivot; Jev — TypeSafe's System One model — chooses a corrective torque every tick to keep it from toppling. Turn gravity up and watch Jev start to lose it; the balance is the show.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "pendulum.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-pendulum/skills/pendulum/SKILL.md b/store/agents/jev-pendulum/skills/pendulum/SKILL.md
new file mode 100644
index 000000000..ea6aa06aa
--- /dev/null
+++ b/store/agents/jev-pendulum/skills/pendulum/SKILL.md
@@ -0,0 +1,54 @@
+---
+name: jev-pendulum
+description: Design and verify Jev's balancing rigs in OpenHarness's viewer, where Jev keeps an inverted pendulum upright and loses it at high gravity.
+---
+
+# Jev Pendulum rig design
+
+Jev Pendulum simulates an inverted pendulum: Jev (TypeSafe's System One model) reads the rod's
+angle and angular velocity every tick and picks a corrective torque to keep it up. The agent shapes
+`pendulum.json` — the rig (gravity, torque authority, gusts) and the style line Jev balances by.
+
+## The loop
+
+1. Update `pendulum.json` (title, gravity, maxTorque, gustEvery/gustStrength, and a `style` line that
+ tells Jev a strategy). The viewer watches it and Jev adapts live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `pendulum.json` is valid. Run it
+ before you call a rig done.
+3. Watch the rod. Does it stand, wobble, and *sometimes* drop on a hard rig — or always stand like a
+ statue (too easy) or always fall (too hard)? That observation is the finding.
+
+## Reading the rig
+
+The viewer shows the rod, the current action and confidence, a tilt-vs-time chart and a decision
+log, plus a falling tally. Good rigs produce drama: the rod leans hard near the fall line (the chart's
+red band at `±60°`), Jev's confidence dips, it recovers — and at high gravity it eventually drops.
+`gravity` is the difficulty dial: `5–6` calm, `7–8` tense, `9+` falls start compounding. `gustStrength`
+and `gustEvery` push it toward the edge without tipping it by themselves.
+
+## Verifying a rig
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `pendulum.json` is invalid (no title,
+non-positive gravity/maxTorque/length, out-of-range stepMs). It doesn't replace watching the motion:
+confirm Jev holds a mid gravity steady, that raising gravity or gusts makes it visibly struggle and
+fall, and that the style line shifts how decisively it recovers.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's read on a state
+before you commit to a rig:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "Keep the rod upright. angle: 8.0° velocity: 0.30 rad/s hardness: 0.67 Choose the torque that corrects the lean.",
+ questions: {
+ action: jev.choice(["LEFT_HARD", "LEFT", "CENTER", "RIGHT", "RIGHT_HARD"], "Which torque steadies the rod right now?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-pendulum/store.json b/store/agents/jev-pendulum/store.json
new file mode 100644
index 000000000..260fc398c
--- /dev/null
+++ b/store/agents/jev-pendulum/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev balances an inverted pendulum live on a pivot",
+ "examples": [
+ {
+ "prompt": "Set Jev Pendulum up as a tense balancing rig — a stiff rod under gravity 8 with a gust every few ticks that shoves it toward the fall line. Give Jev a style line for how to recover, then watch it hold, wobble, and eventually drop.",
+ "caption": "Jev's Balancing Act — a fast decision model keeping a rod upright, and losing it at high gravity"
+ }
+ ]
+}
diff --git a/store/agents/jev-pendulum/template/pendulum.json b/store/agents/jev-pendulum/template/pendulum.json
new file mode 100644
index 000000000..0f4f48041
--- /dev/null
+++ b/store/agents/jev-pendulum/template/pendulum.json
@@ -0,0 +1,14 @@
+{
+ "title": "The Balance Rod",
+ "description": "Jev keeps a stiff rod upright on a pivot — a live balancing act.",
+ "instrument": "ROD",
+ "gravity": 7,
+ "length": 1.0,
+ "damping": 0.5,
+ "maxTorque": 0.8,
+ "stepMs": 80,
+ "gustEvery": 10,
+ "gustStrength": 0.5,
+ "fallDeg": 60,
+ "style": "Keep the rod upright. Correct every lean immediately, shrink the swing, and never let it drift past the edge. You are a fast, steady balancer."
+}
diff --git a/store/agents/jev-pendulum/test/viewer.test.mjs b/store/agents/jev-pendulum/test/viewer.test.mjs
new file mode 100644
index 000000000..490088de4
--- /dev/null
+++ b/store/agents/jev-pendulum/test/viewer.test.mjs
@@ -0,0 +1,82 @@
+// Viewer integration test for Jev Pendulum. Spins up the real viewer against a temp workspace and
+// checks the loop: the rod ticks and leans, Jev forms a balancing action, the verdict updates, and
+// control commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const CFG = {
+ title: 'Test Rod', instrument: 'ROD', gravity: 7, length: 1.0, damping: 0.5, maxTorque: 2.0,
+ stepMs: 60, gustEvery: 10, gustStrength: 0.5, fallDeg: 60,
+ style: 'Keep the rod upright.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-pendulum-test-'))
+ writeFileSync(join(ws, 'pendulum.json'), JSON.stringify({ ...CFG, ...overrides }))
+ const { startPendulumViewer } = await import(viewerPath)
+ const viewer = await startPendulumViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Pendulum ticks and Jev forms a balancing action', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const deadline = Date.now() + 3000
+ let saw = false
+ while (Date.now() < deadline) {
+ await wait(150)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ if (s.step >= 3 && s.history.length > 0) {
+ assert.ok(['LEFT_HARD', 'LEFT', 'CENTER', 'RIGHT', 'RIGHT_HARD'].includes(s.lastAction))
+ assert.ok(typeof s.angle === 'number')
+ saw = true
+ break
+ }
+ }
+ assert.ok(saw, 'expected the rod to tick and Jev to act')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Pendulum writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 2000
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Pendulum control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-pendulum/toolchain/README.md b/store/agents/jev-pendulum/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-pendulum/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-pendulum/toolchain/check.mjs b/store/agents/jev-pendulum/toolchain/check.mjs
new file mode 100644
index 000000000..88dab585d
--- /dev/null
+++ b/store/agents/jev-pendulum/toolchain/check.mjs
@@ -0,0 +1,30 @@
+#!/usr/bin/env node
+// check.mjs — validate a pendulum.json for the Jev Pendulum harness.
+// Enforces the shape the viewer needs: title, gravity, torque authority, interval, interval.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'pendulum.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read pendulum.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!p.title || typeof p.title !== 'string') bad('warn no title')
+if (typeof p.gravity !== 'number' || p.gravity <= 0) bad('error gravity must be a positive number')
+if (p.gravity < 4) console.log('hint gravity < 4 is very easy — Jev will never fall')
+if (p.gravity > 10) console.log('hint gravity > 10 is nearly unbalanceable — Jev will topple fast')
+if (typeof p.maxTorque !== 'number' || p.maxTorque <= 0) bad('error maxTorque must be a positive number')
+if (typeof p.stepMs !== 'number' || p.stepMs < 30 || p.stepMs > 2000) bad('error stepMs must be ms 30..2000')
+if (typeof p.length !== 'number' || p.length <= 0) bad('error length must be a positive number')
+if (!p.style || typeof p.style !== 'string') bad('warn a style line helps Jev balance coherently')
+
+console.log(fail ? 'fail invalid pendulum.json' : 'ok pendulum.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-pendulum/toolchain/doctor.sh b/store/agents/jev-pendulum/toolchain/doctor.sh
new file mode 100644
index 000000000..8abb8c920
--- /dev/null
+++ b/store/agents/jev-pendulum/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Pendulum viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-pendulum/toolchain/init-workspace.sh b/store/agents/jev-pendulum/toolchain/init-workspace.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-pendulum/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-pendulum/toolchain/jev.mjs b/store/agents/jev-pendulum/toolchain/jev.mjs
new file mode 100644
index 000000000..475a6c5e0
--- /dev/null
+++ b/store/agents/jev-pendulum/toolchain/jev.mjs
@@ -0,0 +1,539 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+/**
+ * Pendulum-balancing read used by the mock when the state text carries the current pole angle and
+ * angular velocity (the viewer renders e.g. "angle: +12° velocity: -0.8 rad/s"). We compute the
+ * corrective action the pole is asking for: lean/fall to the right (positive angle) wants a
+ * leftward torque, and also damp any velocity. Returns per-action boosts so the deterministic mock
+ * biases toward the right call while staying slightly noisy — so Jev can fail when it's sloppy and
+ * the fall reads as Jev's mistake. Real Jev reads the same text — the mock is a stand-in.
+ */
+function pendulumRead(text) {
+ const mA = text.match(/angle:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const mV = text.match(/velocity:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const deg = mA ? Number(mA[1]) : NaN
+ const vel = mV ? Number(mV[1]) : NaN
+ if (!Number.isFinite(deg) || !Number.isFinite(vel)) return null
+ const a = (deg * Math.PI) / 180
+ // desired torque = -(Kp*a + Kv*vel); pick the action whose torque is closest.
+ const want = -(6.5 * a + 3.2 * vel)
+ const ACTS = { LEFT_HARD: -1.6, LEFT: -0.8, CENTER: 0, RIGHT: 0.8, RIGHT_HARD: 1.6 }
+ const boost = {}
+ for (const [name, t] of Object.entries(ACTS)) {
+ boost[name] = 1.4 - Math.abs(t - Math.max(-1.6, Math.min(1.6, want))) * 0.9
+ }
+ // The mock can't see the gravity dial — it just balances. But a fast judge on a hard
+ // rig will hesitate more, so the misjudgement rate rises with how hard the balance is.
+ // Low gravity: calm, near-perfect. High gravity: it starts to overshoot and lose it.
+ const hard = (parseFloat((text.match(/hardness:\s*([0-9.]+)/i) || [null, '0'])[1]) || 0)
+ const noise = Math.min(0.55, 0.03 + hard * 0.06)
+ return { boost, noise }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Pendulum: if the state carries an angle + angular velocity, bias toward the balancing action,
+ // and occasionally flip to a neighbour (a fast model that sometimes hesitates) so the pole can
+ // visibly wobble — that wiggle is the demo.
+ const pen = pendulumRead(text)
+ if (pen) {
+ let picked
+ options.forEach((opt, i) => {
+ const b = pen.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (pen.noise && (hash01('pen', salt + 9) < pen.noise)) {
+ // flip the current best to two neighbours over — a big, costly overcorrection
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + (hash01('dir', salt) < 0.5 ? -2 : 2)))
+ if (ni !== best.i) raw[ni] += 2.2
+ }
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-pendulum/toolchain/setup.sh b/store/agents/jev-pendulum/toolchain/setup.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-pendulum/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-pendulum/toolchain/viewer.sh b/store/agents/jev-pendulum/toolchain/viewer.sh
new file mode 100644
index 000000000..b914bdb52
--- /dev/null
+++ b/store/agents/jev-pendulum/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Pendulum viewer (Jev balances a rod live on a pivot).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-pendulum/viewer/index.html b/store/agents/jev-pendulum/viewer/index.html
new file mode 100644
index 000000000..711b4ac14
--- /dev/null
+++ b/store/agents/jev-pendulum/viewer/index.html
@@ -0,0 +1,54 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Jev Pendulum</title>
+<link rel="icon" href="data:," />
+<link rel="stylesheet" href="/studio.css" />
+</head>
+<body>
+<header id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Pendulum</h1></div>
+ <div id="title"></div>
+ <div class="stats">
+ <div class="stat"><label>Tilt</label><span id="tilt"></span></div>
+ <div class="stat"><label>Action</label><span id="action"></span></div>
+ <div class="stat"><label>Falls</label><span id="falls"></span></div>
+ <div class="stat"><label>Best</label><span id="best"></span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="tick">Tick</button>
+ <button id="reset" class="primary">Reset</button>
+ </div>
+</header>
+
+<main>
+ <section id="stage">
+ <div class="panel balancer">
+ <canvas id="rod"></canvas>
+ <div id="gauge"></div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Tilt over time (°)</div>
+ <canvas id="chart"></canvas>
+ </div>
+ </section>
+
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">How it works</div>
+ <p class="how">Jev reads the rod's angle + angular velocity and picks a torque each tick to keep it up. Every <span id="gustLbl"></span> ticks a <b>gust</b> kicks the rod — Jev must recover before the next one. Crank <code>gravity</code> in <code>pendulum.json</code> and watch it get hard.</p>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Recent decisions</div>
+ <ol id="log"></ol>
+ </div>
+ </aside>
+</main>
+
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-pendulum/viewer/jev-hud.js b/store/agents/jev-pendulum/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-pendulum/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-pendulum/viewer/studio.css b/store/agents/jev-pendulum/viewer/studio.css
new file mode 100644
index 000000000..ef189b43d
--- /dev/null
+++ b/store/agents/jev-pendulum/viewer/studio.css
@@ -0,0 +1,66 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #c084fc; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #171a2b 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(23,26,36,.9), rgba(18,20,28,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+#title { color: var(--accent); font-size: 15px; font-weight: 700; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#tilt { color: var(--amber); }
+#action { color: var(--cyan); }
+#falls { color: var(--rose); }
+#best { color: var(--ink); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #7c3aed, #a855f7); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+.balancer { display: flex; flex-direction: column; align-items: center; }
+#rod { width: 100%; height: 380px; background: radial-gradient(circle at 30% 20%, #0e1119, #0a0c12); border: 1px solid #1c2030; border-radius: 8px; }
+#gauge { margin-top: 8px; font-size: 12px; color: var(--dim); }
+#chart { width: 100%; height: 150px; background: #0d0f16; border: 1px solid #1c2030; border-radius: 8px; }
+
+#rail {
+ width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px;
+ display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(18,20,28,.5);
+}
+.how { color: var(--dim); font-size: 13px; line-height: 1.5; }
+.how b { color: var(--amber); }
+.how code { color: var(--cyan); }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 50vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 8px; align-items: baseline; }
+#log li .n { color: var(--accent); }
+#log li .d { color: var(--amber); }
+#log li .a { color: var(--cyan); font-weight: 700; }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-pendulum/viewer/studio.js b/store/agents/jev-pendulum/viewer/studio.js
new file mode 100644
index 000000000..f6861f957
--- /dev/null
+++ b/store/agents/jev-pendulum/viewer/studio.js
@@ -0,0 +1,152 @@
+// Jev Pendulum pane — draws the rod balancing live, the current action, tilt history and falls.
+// Renders on a 2D canvas: the rod pivots at the base, the ground line stays fixed, and the rod
+// leans as Jev corrects it. When it crosses the fall threshold it tips over and resets.
+
+const $ = (id) => document.getElementById(id)
+const els = { title: $('title'), tilt: $('tilt'), action: $('action'), falls: $('falls'), best: $('best'), rod: $('rod'), chart: $('chart'), log: $('log'), gauge: $('gauge'), gustLbl: $('gustLbl') }
+
+let angleDeg = 0
+let vel = 0
+let step = 0
+let falls = 0
+let bestRun = 0
+let lastAction = 'CENTER'
+let lastConf = 0.5
+let history = []
+let gustEvery = 10
+
+function drawRod() {
+ const cv = els.rod, ctx = cv.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = cv.clientWidth, H = 380
+ cv.width = W * dpr; cv.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+
+ const cx = W / 2, baseY = H - 40
+ const rodLen = H * 0.78
+ const a = angleDeg * Math.PI / 180
+ const tipX = cx + rodLen * Math.sin(a)
+ const tipY = baseY - rodLen * Math.cos(a)
+
+ // ground
+ ctx.strokeStyle = '#2a2f42'; ctx.lineWidth = 2
+ ctx.beginPath(); ctx.moveTo(0, baseY); ctx.lineTo(W, baseY); ctx.stroke()
+ ctx.fillStyle = '#1a1e2c'; ctx.fillRect(0, baseY, W, 8)
+
+ // fall wedge (danger zone at ±fallDeg)
+ const fallDeg = 60
+ ctx.fillStyle = 'rgba(251,113,133,0.08)'
+ for (const s of [-1, 1]) {
+ ctx.beginPath(); ctx.moveTo(cx, baseY)
+ ctx.lineTo(cx + s * Math.sin(fallDeg * Math.PI / 180) * rodLen, baseY - Math.cos(fallDeg * Math.PI / 180) * rodLen)
+ ctx.lineTo(cx + s * Math.sin(fallDeg * Math.PI / 180) * rodLen * 1.3, baseY)
+ ctx.closePath(); ctx.fill()
+ }
+ // danger line at fallDeg
+ ctx.strokeStyle = 'rgba(251,113,133,0.25)'; ctx.lineWidth = 1
+ for (const s of [-1, 1]) { ctx.beginPath(); ctx.moveTo(cx, baseY); ctx.lineTo(cx + s * Math.sin(fallDeg * Math.PI / 180) * rodLen, baseY - Math.cos(fallDeg * Math.PI / 180) * rodLen); ctx.stroke() }
+
+ // rod
+ const danger = Math.abs(angleDeg) > fallDeg * 0.7
+ ctx.strokeStyle = danger ? '#fb7185' : '#c084fc'
+ ctx.lineWidth = 6
+ ctx.lineCap = 'round'
+ ctx.shadowColor = danger ? '#fb7185' : '#a855f7'
+ ctx.shadowBlur = danger ? 22 : 12
+ ctx.beginPath(); ctx.moveTo(cx, baseY); ctx.lineTo(tipX, tipY); ctx.stroke()
+ ctx.shadowBlur = 0
+
+ // tip ball
+ ctx.fillStyle = danger ? '#fb7185' : '#5eead4'
+ ctx.beginPath(); ctx.arc(tipX, tipY, 8, 0, Math.PI * 2); ctx.fill()
+
+ // pivot
+ ctx.fillStyle = '#e8eaf2'
+ ctx.beginPath(); ctx.arc(cx, baseY, 6, 0, Math.PI * 2); ctx.fill()
+
+ // angle readout near the rod
+ ctx.fillStyle = '#8a90a6'; ctx.font = '12px ' + 'monospace'
+ ctx.fillText(`${angleDeg.toFixed(1)}°`, cx + rodLen * 0.5 * Math.sin(a) + 12, baseY - rodLen * 0.5 * Math.cos(a))
+}
+
+function drawChart() {
+ const cv = els.chart, ctx = cv.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = cv.clientWidth, H = 150
+ cv.width = W * dpr; cv.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+ if (history.length < 2) { ctx.fillStyle = '#4b5266'; ctx.fillText('watching…', 10, 14); return }
+ const pts = history.slice(-180)
+ const pad = { l: 30, r: 8, t: 8, b: 18 }
+ const plotW = W - pad.l - pad.r, plotH = H - pad.t - pad.b
+ // fixed scale 0..65° (absolute tilt) so the fall threshold is a real line
+ const lim = 65
+ // gridlines at target angles
+ ctx.strokeStyle = '#1c2030'; ctx.lineWidth = 1
+ for (const deg of [0, 15, 30, 45, 60]) {
+ const y = pad.t + plotH - (deg / lim) * plotH
+ ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(W - pad.r, y); ctx.stroke()
+ ctx.fillStyle = '#4b5266'; ctx.font = '9px ' + 'monospace'; ctx.fillText(String(deg), 2, y - 3)
+ }
+ ctx.strokeStyle = 'rgba(251,113,133,0.5)'; ctx.lineWidth = 1
+ const fallY = pad.t + plotH - (60 / lim) * plotH
+ ctx.beginPath(); ctx.moveTo(pad.l, fallY); ctx.lineTo(W - pad.r, fallY); ctx.stroke()
+ ctx.strokeStyle = '#fbbf24'; ctx.lineWidth = 1.5; ctx.beginPath()
+ pts.forEach((h, i) => { const x = pad.l + (i / (pts.length - 1)) * plotW; const y = pad.t + plotH - (Math.min(lim, h.deg) / lim) * plotH; i ? ctx.lineTo(x, y) : ctx.moveTo(x, y) })
+ ctx.stroke()
+}
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history.slice(-30)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="n">#${h.step}</span><span class="d">${h.deg.toFixed(1)}°</span><span class="a">${h.action}</span><span>${(h.conf * 100).toFixed(0)}%</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function onTick(msg) {
+ els.title.textContent = msg.title || ''
+ angleDeg = msg.angle ?? angleDeg
+ vel = msg.vel ?? vel
+ step = msg.step ?? step
+ falls = msg.falls ?? falls
+ bestRun = msg.bestRun ?? bestRun
+ lastAction = msg.lastAction || lastAction
+ lastConf = msg.conf ?? lastConf
+ history = msg.history || history
+ gustEvery = msg.gustEvery ?? gustEvery
+ els.gustLbl.textContent = msg.gustEvery || 'some'
+
+ els.tilt.textContent = angleDeg.toFixed(1) + '°'
+ els.tilt.style.color = Math.abs(angleDeg) > 60 * 0.7 ? 'var(--rose)' : 'var(--amber)'
+ els.action.textContent = lastAction
+ els.falls.textContent = String(falls)
+ const min = (bestRun * (msg.stepMs || 80)) / 1000 / 60
+ els.best.textContent = min.toFixed(1) + ' min'
+ els.gauge.textContent = `angle ${angleDeg.toFixed(1)}° · velocity ${vel.toFixed(2)} rad/s · conf ${(lastConf * 100).toFixed(0)}%`
+ drawRod()
+ drawChart()
+ renderLog()
+}
+
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+window.addEventListener('resize', () => { drawRod(); drawChart() })
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-pendulum/viewer/viewer.mjs b/store/agents/jev-pendulum/viewer/viewer.mjs
new file mode 100644
index 000000000..5e04b6b39
--- /dev/null
+++ b/store/agents/jev-pendulum/viewer/viewer.mjs
@@ -0,0 +1,260 @@
+// Jev Pendulum viewer — a loopback server running a live balancing demo. A stiff rod stands on a
+// pivot and Jev (TypeSafe's System One model) decides the corrective torque every `pendulum.stepMs`
+// to keep it upright. The agent shapes pendulum.json (gravity, torque authority, gust strength) —
+// turn it up and watch Jev go from steady to scrambling. The physics is honest but simulated.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds pendulum.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT = {
+ title: 'The Balance Rod',
+ description: 'Jev keeps a stiff rod upright on a pivot — a live balancing act.',
+ instrument: 'ROD',
+ gravity: 7, length: 1.0, damping: 0.5, maxTorque: 0.8,
+ stepMs: 80, gustEvery: 10, gustStrength: 0.5, fallDeg: 60,
+ style: 'Keep the rod upright. Correct every lean immediately, shrink the swing, and never let it drift past the edge. You are a fast, steady balancer.',
+}
+
+const ORDER = ['LEFT_HARD', 'LEFT', 'CENTER', 'RIGHT', 'RIGHT_HARD']
+const TQ = { LEFT_HARD: -1, LEFT: -0.5, CENTER: 0, RIGHT: 0.5, RIGHT_HARD: 1 }
+
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+function stateBlock(p, angle, vel) {
+ const deg = (angle * 180) / Math.PI
+ const hardness = Math.max(0, Math.min(1, ((p.gravity || 7) - 4) / 6))
+ return `${p.style}
+A stiff rod of length ${p.length} stands on a pivot. You apply a torque every tick to keep it upright.
+angle: ${deg.toFixed(1)}° velocity: ${vel.toFixed(2)} rad/s (falls at ±${p.fallDeg}°)
+hardness: ${hardness.toFixed(2)}
+Choose the torque that corrects the lean and steadies the rod. Be decisive.`
+}
+
+export async function startPendulumViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let p = readCfg(join(workspace, 'pendulum.json'))
+ let rng = mulberry32(303)
+ // physical state
+ let angle = 0, vel = 0
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let error = null
+ let step = 0
+ let running = false
+ let falls = 0
+ let bestRun = 0
+ let thisRun = 0
+ let history = [] // per-decision samples of |angle| in degrees, capped
+ let lastAction = 'CENTER'
+ let lastConf = 0
+ let notifiedFall = false
+
+ function readCfg(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ return { ...DEFAULT, ...raw }
+ } catch (e) {
+ error = clean(e.message)
+ return DEFAULT
+ }
+ }
+
+ function resetState() {
+ angle = (rng() - 0.5) * 0.12
+ vel = (rng() - 0.5) * 0.4
+ falls = 0
+ bestRun = 0
+ thisRun = 0
+ history = []
+ notifiedFall = false
+ step = 0
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ const minutes = (bestRun * p.stepMs / 1000 / 60)
+ const state = history.length === 0 ? 'learning' : notifiedFall ? 'fell' : 'balancing'
+ return {
+ spec: 1,
+ ready: history.length > 0,
+ summary: error
+ ? 'Jev Pendulum needs a fix'
+ : notifiedFall
+ ? `${p.title || 'Balance Rod'} · fell after ${thisRun} ticks · best ${minutes.toFixed(1)} min · Jev lost its balance at gravity ${p.gravity}`
+ : `${p.title || 'Balance Rod'} · balancing · ${Math.round((angle * 180) / Math.PI)}° tilt · best ${minutes.toFixed(1)} min`,
+ findings: (error ? [{ severity: 'error', kind: 'pendulum', message: error }] : []).concat(
+ notifiedFall ? [{ severity: 'warn', kind: 'pendulum', message: `Jev fell at gravity ${p.gravity} after ${thisRun} ticks — dial gravity down or it keeps losing it` }] : []
+ ),
+ artifact: 'pendulum.json',
+ phases: [
+ { id: 'learn', name: 'Learning', state: history.length < 5 ? 'active' : 'done' },
+ { id: 'balance', name: 'Balancing', state: history.length >= 5 && !notifiedFall ? 'active' : notifiedFall ? 'done' : 'pending' },
+ { id: 'marginal', name: 'At the edge', state: notifiedFall ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick', title: p.title, description: p.description, instrument: p.instrument,
+ angle: (angle * 180) / Math.PI, vel, step, running, error,
+ falls, bestRun, thisRun, lastAction, lastConf,
+ history: history.slice(-240),
+ })
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ // A gust kicks the rod every gustEvery decisions — Jev must recover before the next.
+ if (step > 0 && p.gustEvery > 0 && step % p.gustEvery === 0) {
+ vel += p.gustStrength * (rng() < 0.5 ? -1 : 1)
+ notifiedFall = false
+ }
+ const res = await evaluate({
+ state: stateBlock(p, angle, vel),
+ questions: {
+ action: { type: 'choice', instructions: 'Which torque steadies the rod right now?', options: ORDER },
+ conf: { type: 'noul', instructions: 'Is the rod under control?' },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ lastAction = String(res.answers.action?.choice || 'CENTER')
+ lastConf = typeof res.answers.conf?.noul === 'number' ? res.answers.conf.noul : 0.5
+ const tau = (TQ[lastAction] ?? 0) * (p.maxTorque || 2.0)
+
+ // Integrate the rod for one decision interval.
+ const I = (p.length || 1.0) ** 2
+ const GT = (3 * (p.gravity || 7)) / 2
+ const c = p.damping || 0.5
+ const dt = 0.01
+ const nSub = Math.max(1, Math.round((p.stepMs || 80) / 10))
+ for (let s = 0; s < nSub; s++) {
+ const acc = GT * Math.sin(angle) + (3 * tau) / I - c * vel
+ vel += acc * dt
+ angle += vel * dt
+ }
+ step++
+ thisRun++
+ if (bestRun < thisRun) bestRun = thisRun
+
+ const absDeg = Math.abs(angle) * 180 / Math.PI
+ history.push({ step, deg: absDeg, action: lastAction, conf: lastConf })
+ if (history.length > 300) history.splice(0, history.length - 300)
+
+ if (absDeg > (p.fallDeg || 60)) {
+ falls++
+ notifiedFall = true
+ thisRun = 0
+ // put it back near vertical, with a fresh small tilt
+ angle = (rng() - 0.5) * 0.1
+ vel = 0
+ step++ // count the fall tick
+ } else if (notifiedFall) {
+ notifiedFall = false
+ }
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, p.stepMs) }
+ async function run() { if (stopped) return; await decide(); schedule() }
+ function start() { if (!running) { running = true; schedule() } }
+ function pause() { running = false; clearTimeout(timer) }
+ function reset() { resetState(); tail(); if (running) schedule() }
+
+ const watcher = watch(workspace, { recursive: true }, (_, name) => {
+ if (!name) return
+ if (String(name).split('/').join('/') === 'pendulum.json') {
+ p = readCfg(join(workspace, 'pendulum.json'))
+ tail()
+ if (running) schedule()
+ }
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: p.title, instrument: p.instrument, angle: (angle * 180) / Math.PI, vel, step, running, error, falls, bestRun, thisRun, lastAction, lastConf, history: history.slice(-240) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ resetState()
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startPendulumViewer({ workspace, port })
+ console.log(`Jev Pendulum listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-pong/.gitignore b/store/agents/jev-pong/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-pong/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-pong/AGENTS.md b/store/agents/jev-pong/AGENTS.md
new file mode 100644
index 000000000..ee39995bb
--- /dev/null
+++ b/store/agents/jev-pong/AGENTS.md
@@ -0,0 +1,86 @@
+# Jev Pong in OpenHarness
+
+On the left, Jev Pong is a live paddle-defense rally: a ball ricochets around a slim court and
+**Jev — TypeSafe's System One model — is the paddle.** Every tick Jev reads the ball's position and
+velocity and moves the paddle to meet the return. Each successful hit makes the ball a little
+faster, so a long rally is a losing battle — the show is Jev chasing, wobbling and finally dropping
+it.
+
+On the right, you edit `pong.json`. This is the ONLY file you edit. It sets the court, the paddle's
+authority, and the starting ball speed; the viewer watches it and Jev adapts immediately.
+
+## The pong file
+
+```jsonc
+{
+ "title": "Jev Pong",
+ "description": "Jev is the paddle — keep the rally alive as the ball speeds up.",
+ "instrument": "PONG",
+ "courtW": 200,
+ "courtH": 120,
+ "paddleH": 26,
+ "ballR": 3,
+ "speed": 6,
+ "maxSpeed": 3,
+ "accel": 0.5,
+ "topSpeed": 14,
+ "stepMs": 60,
+ "style": "Keep the rally alive. Track the ball, predict where it will cross your wall, and get the paddle there in time. Be decisive."
+}
+```
+
+- **`speed`** — the starting ball speed (the difficulty dial). `4–5` is easy; `6–8` is tense;
+ `9+` is a scramble from the first serve.
+- **`accel`** — how much faster the ball gets per return. Higher accel makes rallies short and
+ hectic; lower lets them grow long before Jev is overrun. This is the *other* tension knob.
+- **`maxSpeed`** — how fast Jev can move the paddle (FAST moves = `maxSpeed`, normal = half). A
+ paddle far slower than the ball is helpless; one near the ball's speed makes each rally a tight
+ race.
+- **`topSpeed`** — the cap the ball can reach. Leave it well above `speed` so rallies have room to
+ accelerate.
+- **`courtW` / `courtH` / `paddleH` / `stepMs`** — court geometry and responsiveness. A wider
+ court means longer cross-court flight (easier reads); a taller court means more vertical
+ scrambling.
+- **`style`** — the instruction to Jev. A decisive "get there in time" reads differently from a
+ cautious "wait for the ball".
+
+## Your job
+
+Design `pong.json` so the rally is an event:
+
+- **Pick a starting speed with tension.** `6` is a sweet spot: Jev holds a few returns, the ball
+ speeds up, and it eventually slips past — the natural arc of Pong.
+- **Tune accel for the right pace.** Low accel (≈0.3) builds long, impressive streaks; high accel
+ (≈0.8) makes every rally short and frantic.
+- **Set a style line that names a strategy.** Jev should *decide* how to defend, not guess.
+
+Do NOT just ship the template. Every `pong.json` you publish should be its own court with a
+deliberate, testable pace.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the motion: does Jev hold a
+few exchanges, speed the ball up, and occasionally lose it — or does it never miss (too easy) or
+always drop (too hard)? Either extreme is a finding to report, not a bug to mask.
+
+## Rules
+
+- Keep `pong.json` valid JSON always. A bad edit freezes the court on the last good state.
+- Keep `title`, `description` and `style` truthful — and never present this as a real physics app
+ or real control software.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read on a state
+ before you commit to it (e.g. "what does Jev do for a ball at x 40 y 70, vx −6 vy 2, paddle at
+ 50?"). Use the `jev` helpers: `noul`, `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the ball
+ and paddle and steers toward the predicted intercept — so the demo runs offline. With a key, the
+ viewer calls the real API.
+- The Jev Pong viewer writes `.harness/verdict.json` itself (misses, best rally, current rally). Do
+ not edit it.
+- This is a demo. The ball and paddle are canvas shapes and Jev is picking paper moves — never
+ present this as real game software or real control.
+
+## Definition of done
+
+- A valid `pong.json` that parses and passes `toolchain/check.mjs`.
+- A rally with real pace: Jev returns a few balls, the rally accelerates, and it eventually drops
+ one. A rally that never dies is a solved problem, not a good harness.
+- The style line actually shapes the defense — report it if Jev behaves identically no matter what
+ you write.
diff --git a/store/agents/jev-pong/LICENSE b/store/agents/jev-pong/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-pong/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-pong/README.md b/store/agents/jev-pong/README.md
new file mode 100644
index 000000000..66b5edc86
--- /dev/null
+++ b/store/agents/jev-pong/README.md
@@ -0,0 +1,57 @@
+# Jev Pong
+
+**Jev — TypeSafe's System One model — is the paddle.** A ball ricochets around a slim court; every
+tick Jev reads its position and velocity and moves the paddle to meet the return. Each hit makes
+the ball a little faster, so a long rally is a losing battle — watch Jev chase, wobble, and finally
+drop it.
+
+This is a harness for OpenHarness. The agent on the right edits `pong.json`; the viewer on the left
+simulates the rally and asks Jev for each tick's paddle move, live. The chase is the show.
+
+## Anatomy
+
+```
+jev-pong/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to build rallies with real pace
+ skills/pong/SKILL.md # the court-tuning + verification craft
+ template/pong.json # a starter court
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), rally-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates pong.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the live court)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` simulates the court over a loopback HTTP server. Each tick it meters the ball,
+asks Jev to pick a paddle move (`MOVE_UP_FAST`…`MOVE_DOWN_FAST`), integrates one step, and streams
+the live court, a predicted-intercept ghost, and a decision log to the pane. It calls
+`POST /v1/systemone` when `TYPESAFE_API_KEY` is set; without it a deterministic mock reads the same
+ball and paddle and steers toward the predicted intercept, so the demo runs offline.
+`.harness/verdict.json` tracks misses, the best rally and the current rally.
+
+The physics is honest but toy: the ball reflects off floor, ceiling and the far wall; Jev's paddle
+moves at a fixed `maxSpeed`; and **every successful return adds `accel` to the ball's speed**, so
+long rallies genuinely outrun the paddle. `speed` sets the starting pace (the difficulty dial);
+`maxSpeed` and `accel` set how hard Jev has to work and how fast the ball runs away.
+
+## Jev, honestly
+
+Jev's headline claim is speed — decide in a loop faster than a large model can. Pong celebrates
+that: a decision every ~40ms that has to actually meet a moving ball. But the ball and paddle are
+canvas shapes and the physics is a toy — this is a demo of decision-rate and tracking, not a signal
+for real game AI, and the mock is a stand-in for *plumbing*, not judgement. Treat any rally as a
+fun experiment, not an engineering result.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live paddle — a rally you can watch
+accelerate, scramble and finally drop._
diff --git a/store/agents/jev-pong/THIRD_PARTY_NOTICES.md b/store/agents/jev-pong/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-pong/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-pong/harness.json b/store/agents/jev-pong/harness.json
new file mode 100644
index 000000000..9a8e6075b
--- /dev/null
+++ b/store/agents/jev-pong/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-pong",
+ "name": "Jev Pong",
+ "category": "Games",
+ "author": "Autonomous",
+ "description": "A live paddle-defense rally. Jev — TypeSafe's System One model — is the paddle: every tick it reads the ball and moves to meet the return. The ball speeds up with every hit, so a long rally is a losing battle — watch Jev chase, wobble, and finally drop it.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "pong.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-pong/skills/pong/SKILL.md b/store/agents/jev-pong/skills/pong/SKILL.md
new file mode 100644
index 000000000..aea7ec172
--- /dev/null
+++ b/store/agents/jev-pong/skills/pong/SKILL.md
@@ -0,0 +1,55 @@
+---
+name: jev-pong
+description: Design and verify Jev's paddle-defense courts in OpenHarness's viewer, where Jev keeps a rally alive and loses it as the ball accelerates.
+---
+
+# Jev Pong court design
+
+Jev Pong simulates a paddle-defense rally: Jev (TypeSafe's System One model) reads the ball's
+position and velocity every tick and moves the paddle to meet the return. Each hit speeds the ball
+up, so a long rally outruns the paddle. The agent shapes `pong.json` — the court, the paddle's
+authority, and the starting ball speed.
+
+## The loop
+
+1. Update `pong.json` (title, courtW/courtH, speed, maxSpeed, accel, and a `style` line that tells
+ Jev a strategy). The viewer watches it and Jev adapts live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `pong.json` is valid. Run it
+ before you call a court done.
+3. Watch the rally. Does Jev return a few balls, speed the ball up, and *sometimes* drop it — or
+ never miss (too easy) / always drop (too hard)? That observation is the finding.
+
+## Reading the court
+
+The viewer shows the court, the ball with a predicted-intercept ghost at Jev's wall, the current
+move and confidence, and a decision log plus a rally tally. Good courts produce a natural arc:
+Jev holds a few returns, the ball accelerates, Jev scrambles harder, and it finally slips past.
+`speed` sets the starting pace; `accel` controls how fast each rally runs away; `maxSpeed` caps how
+quickly Jev can get there.
+
+## Verifying a court
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `pong.json` is invalid (no title,
+non-positive court/speed values, out-of-range stepMs). It doesn't replace watching the motion:
+confirm Jev holds a low speed comfortably, that raising `speed` or `accel` shortens rallies and
+raises the miss count, and that the style line shifts how decisively it moves.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's read on a
+state before you commit to a court:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "Keep the rally alive. A paddle on the left wall (centre y 50.0, half-height 13) defends a 200x120 court. ball: x 40.0 y 70.0 vx -6.0 vy 2.0 (toward you) speed: 6.0 Move the paddle to meet the ball.",
+ questions: {
+ move: jev.choice(["MOVE_UP_FAST", "MOVE_UP", "HOLD", "MOVE_DOWN", "MOVE_DOWN_FAST"], "Which paddle move keeps the rally alive?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-pong/store.json b/store/agents/jev-pong/store.json
new file mode 100644
index 000000000..008b524f6
--- /dev/null
+++ b/store/agents/jev-pong/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev is the paddle — a rally that speeds up and outruns it",
+ "examples": [
+ {
+ "prompt": "Set Jev Pong up as a tense rally — a mid-size court at speed 6 with a gentle accel so the ball builds up over a few returns. Give Jev a decisive style line, then watch it hold the streak until the rally outruns the paddle.",
+ "caption": "Jev's Rally — a fast decision model chasing a ball that speeds up with every return"
+ }
+ ]
+}
diff --git a/store/agents/jev-pong/template/pong.json b/store/agents/jev-pong/template/pong.json
new file mode 100644
index 000000000..3701611ab
--- /dev/null
+++ b/store/agents/jev-pong/template/pong.json
@@ -0,0 +1,15 @@
+{
+ "title": "Jev Pong",
+ "description": "Jev is the paddle \u2014 keep the rally alive as the ball speeds up.",
+ "instrument": "PONG",
+ "courtW": 200,
+ "courtH": 120,
+ "paddleH": 26,
+ "ballR": 3,
+ "speed": 6,
+ "maxSpeed": 3,
+ "stepMs": 60,
+ "style": "Keep the rally alive. Track the ball, predict where it will cross your wall, and get the paddle there in time. Be decisive.",
+ "accel": 0.5,
+ "topSpeed": 14
+}
\ No newline at end of file
diff --git a/store/agents/jev-pong/test/viewer.test.mjs b/store/agents/jev-pong/test/viewer.test.mjs
new file mode 100644
index 000000000..97ae62ff9
--- /dev/null
+++ b/store/agents/jev-pong/test/viewer.test.mjs
@@ -0,0 +1,82 @@
+// Viewer integration test for Jev Pong. Spins up the real viewer against a temp workspace and
+// checks the loop: the court ticks and the ball moves, Jev forms a defensive move, the verdict
+// updates, and control commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const CFG = {
+ title: 'Test Pong', instrument: 'PONG', courtW: 200, courtH: 120, paddleH: 26, ballR: 3,
+ speed: 6, maxSpeed: 3, accel: 0.5, topSpeed: 14, stepMs: 40,
+ style: 'Keep the rally alive.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-pong-test-'))
+ writeFileSync(join(ws, 'pong.json'), JSON.stringify({ ...CFG, ...overrides }))
+ const { startPongViewer } = await import(viewerPath)
+ const viewer = await startPongViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Pong ticks and Jev forms a defensive move', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const deadline = Date.now() + 3000
+ let saw = false
+ while (Date.now() < deadline) {
+ await wait(150)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ if (s.step >= 3 && s.history.length > 0) {
+ assert.ok(['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST'].includes(s.lastMove))
+ assert.ok(typeof s.ball.x === 'number' && typeof s.ball.y === 'number')
+ saw = true
+ break
+ }
+ }
+ assert.ok(saw, 'expected the court to tick and Jev to move')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Pong writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 2000
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Pong control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-pong/toolchain/README.md b/store/agents/jev-pong/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-pong/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-pong/toolchain/check.mjs b/store/agents/jev-pong/toolchain/check.mjs
new file mode 100644
index 000000000..daf6af7ae
--- /dev/null
+++ b/store/agents/jev-pong/toolchain/check.mjs
@@ -0,0 +1,31 @@
+#!/usr/bin/env node
+// check.mjs — validate a pong.json for the Jev Pong harness.
+// Enforces the shape the viewer needs: title, court, paddle, speed, step interval.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'pong.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read pong.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!p.title || typeof p.title !== 'string') bad('warn no title')
+if (typeof p.courtW !== 'number' || p.courtW <= 0) bad('error courtW must be a positive number')
+if (typeof p.courtH !== 'number' || p.courtH <= 0) bad('error courtH must be a positive number')
+if (typeof p.paddleH !== 'number' || p.paddleH <= 0) bad('error paddleH must be a positive number')
+if (typeof p.speed !== 'number' || p.speed <= 0) bad('error speed must be a positive number')
+if (p.speed < 4) console.log('hint speed < 4 is very easy — Jev will never miss')
+if (p.speed > 12) console.log('hint speed > 12 is nearly impossible — Jev misses constantly')
+if (typeof p.stepMs !== 'number' || p.stepMs < 30 || p.stepMs > 2000) bad('error stepMs must be ms 30..2000')
+if (!p.style || typeof p.style !== 'string') bad('warn a style line helps Jev defend coherently')
+
+console.log(fail ? 'fail invalid pong.json' : 'ok pong.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-pong/toolchain/doctor.sh b/store/agents/jev-pong/toolchain/doctor.sh
new file mode 100755
index 000000000..5da145360
--- /dev/null
+++ b/store/agents/jev-pong/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Pong viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-pong/toolchain/init-workspace.sh b/store/agents/jev-pong/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-pong/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-pong/toolchain/jev.mjs b/store/agents/jev-pong/toolchain/jev.mjs
new file mode 100644
index 000000000..305b20b4c
--- /dev/null
+++ b/store/agents/jev-pong/toolchain/jev.mjs
@@ -0,0 +1,589 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+/**
+ * Pendulum-balancing read used by the mock when the state text carries the current pole angle and
+ * angular velocity (the viewer renders e.g. "angle: +12° velocity: -0.8 rad/s"). We compute the
+ * corrective action the pole is asking for: lean/fall to the right (positive angle) wants a
+ * leftward torque, and also damp any velocity. Returns per-action boosts so the deterministic mock
+ * biases toward the right call while staying slightly noisy — so Jev can fail when it's sloppy and
+ * the fall reads as Jev's mistake. Real Jev reads the same text — the mock is a stand-in.
+ */
+function pendulumRead(text) {
+ const mA = text.match(/angle:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const mV = text.match(/velocity:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const deg = mA ? Number(mA[1]) : NaN
+ const vel = mV ? Number(mV[1]) : NaN
+ if (!Number.isFinite(deg) || !Number.isFinite(vel)) return null
+ const a = (deg * Math.PI) / 180
+ // desired torque = -(Kp*a + Kv*vel); pick the action whose torque is closest.
+ const want = -(6.5 * a + 3.2 * vel)
+ const ACTS = { LEFT_HARD: -1.6, LEFT: -0.8, CENTER: 0, RIGHT: 0.8, RIGHT_HARD: 1.6 }
+ const boost = {}
+ for (const [name, t] of Object.entries(ACTS)) {
+ boost[name] = 1.4 - Math.abs(t - Math.max(-1.6, Math.min(1.6, want))) * 0.9
+ }
+ // The mock can't see the gravity dial — it just balances. But a fast judge on a hard
+ // rig will hesitate more, so the misjudgement rate rises with how hard the balance is.
+ // Low gravity: calm, near-perfect. High gravity: it starts to overshoot and lose it.
+ const hard = (parseFloat((text.match(/hardness:\s*([0-9.]+)/i) || [null, '0'])[1]) || 0)
+ const noise = Math.min(0.55, 0.03 + hard * 0.06)
+ return { boost, noise }
+}
+
+/**
+ * Pong-defender read used by the mock when the state text carries a ball position/velocity and the
+ * paddle's centre. We predict where the ball will cross the paddle's wall (reflecting off floor and
+ * ceiling) and bias the paddle move toward that intercept, with a reaction that degrades as the ball
+ * gets faster. Returns per-move boosts plus a beta error chance so Jev can visibly lose a fast rally.
+ */
+function pongRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/ball:\s*x\s+([-0-9.]+)/i)
+ const y = num(/y\s+([-0-9.]+)\s+vx/i)
+ const vx = num(/vx\s+([-0-9.]+)\s+vy/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const paddleY = num(/centre y\s+([-0-9.]+)/i)
+ const half = num(/half-height\s+([-0-9.]+)/i)
+ const courtH = num(/court:\s*[-0-9.]+\s*[x×]\s*([-0-9.]+)/i)
+ const speed = num(/speed:\s*([-0-9.]+)/i)
+ if (![x, y, vx, vy, paddleY, half, courtH, speed].every(Number.isFinite)) return null
+ const r = 3
+ const span = courtH - 2 * r
+ // When the ball is moving away (rightward), the paddle's job is to stop chasing and hold still so
+ // it's framed to meet the ball when it comes back — letting the rally breathe.
+ if (vx >= 0) return { boost: { HOLD: 1.9, MOVE_UP: 0.7, MOVE_DOWN: 0.7, MOVE_UP_FAST: 0.3, MOVE_DOWN_FAST: 0.3 }, noise: 0, close: false }
+ // time (in ball steps) to reach the left wall
+ const t = -x / vx
+ const dy = vy * t
+ let u = ((y - r + dy) % (2 * span) + 2 * span) % (2 * span)
+ u = u <= span ? u : 2 * span - u
+ const ty = r + u
+ const want = ty - paddleY
+ const goDown = want > half * 0.5
+ const goUp = want < -half * 0.5
+ const boost = {}
+ for (const name of ['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST']) {
+ if (goDown) boost[name] = name === 'MOVE_DOWN' ? 1.8 : name === 'MOVE_DOWN_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else if (goUp) boost[name] = name === 'MOVE_UP' ? 1.8 : name === 'MOVE_UP_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else boost[name] = name === 'HOLD' ? 1.8 : 0.8
+ }
+ // faster ball → the intercept at the wall changes fast and the paddle has fewer ticks to reach it,
+ // so the physical difficulty (max paddle speed) does the work. No injected noise: a miss is honest.
+ return { boost }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Pendulum: if the state carries an angle + angular velocity, bias toward the balancing action,
+ // and occasionally flip to a neighbour (a fast model that sometimes hesitates) so the pole can
+ // visibly wobble — that wiggle is the demo.
+ const pen = pendulumRead(text)
+ if (pen) {
+ options.forEach((opt, i) => {
+ const b = pen.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (pen.noise && (hash01('pen', salt + 9) < pen.noise)) {
+ // flip the current best to two neighbours over — a big, costly overcorrection
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + (hash01('dir', salt) < 0.5 ? -2 : 2)))
+ if (ni !== best.i) raw[ni] += 2.2
+ }
+ }
+ // Pong: if the state text carries a ball + paddle, steer the paddle to the predicted intercept,
+ // and lag harder (miss more) as the ball speeds up.
+ const pong = pongRead(text)
+ if (pong) {
+ options.forEach((opt, i) => {
+ const b = pong.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-pong/toolchain/setup.sh b/store/agents/jev-pong/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-pong/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-pong/toolchain/viewer.sh b/store/agents/jev-pong/toolchain/viewer.sh
new file mode 100755
index 000000000..4d4fd54e4
--- /dev/null
+++ b/store/agents/jev-pong/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Pong viewer (Jev defends a rally as the paddle, live).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-pong/viewer/index.html b/store/agents/jev-pong/viewer/index.html
new file mode 100644
index 000000000..959f04dbb
--- /dev/null
+++ b/store/agents/jev-pong/viewer/index.html
@@ -0,0 +1,52 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Pong</title>
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Pong</h1></div>
+ <div class="stats">
+ <div class="stat"><label>Rally</label><span id="rally">0</span></div>
+ <div class="stat"><label>Best</label><span id="best">0</span></div>
+ <div class="stat"><label>Misses</label><span id="misses">0</span></div>
+ <div class="stat"><label>Move</label><span id="move">HOLD</span></div>
+ <div class="stat"><label>Speed</label><span id="speed">6</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="tick">Step</button>
+ <button class="primary" id="reset">Reset</button>
+ </div>
+ </div>
+ <main>
+ <section id="stage">
+ <div class="panel balancer">
+ <canvas id="court"></canvas>
+ <div id="gauge">watching…</div>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Jev, the paddle</div>
+ <div class="how">
+ Jev defends the left wall. Every tick it reads the ball and moves the paddle to predict
+ where it crosses. The ball <b>speeds up with every return</b> — so a long rally is a
+ losing battle, and the faster Jev is chased, the sooner it drops one.<br><br>
+ Edit <code>pong.json</code> on the right: raise <code>speed</code> to start Jev behind,
+ or turn it down to watch a long streak before the rally outruns it.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Decision log</div>
+ <ul id="log"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-pong/viewer/jev-hud.js b/store/agents/jev-pong/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-pong/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-pong/viewer/studio.css b/store/agents/jev-pong/viewer/studio.css
new file mode 100644
index 000000000..4638c7ca5
--- /dev/null
+++ b/store/agents/jev-pong/viewer/studio.css
@@ -0,0 +1,62 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #38bdf8; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #0c1a2b 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(16,26,40,.9), rgba(10,16,24,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#rally { color: var(--cyan); }
+#best { color: var(--ok); }
+#misses { color: var(--rose); }
+#move { color: var(--accent); }
+#speed { color: var(--amber); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #0284c7, #38bdf8); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+.balancer { display: flex; flex-direction: column; align-items: center; }
+#court { width: 100%; max-width: 760px; height: 60vh; min-height: 320px; aspect-ratio: 5/3; background: radial-gradient(circle at 30% 20%, #0b1018, #080a0f); border: 1px solid var(--line); border-radius: 8px; }
+#gauge { margin-top: 8px; font-size: 12px; color: var(--dim); }
+
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px; display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(12,20,32,.5); }
+.how { color: var(--dim); font-size: 13px; line-height: 1.5; }
+.how b { color: var(--amber); }
+.how code { color: var(--cyan); }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 50vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 8px; align-items: baseline; }
+#log li .n { color: var(--accent); }
+#log li .b { color: var(--amber); }
+#log li .m { color: var(--cyan); font-weight: 700; }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-pong/viewer/studio.js b/store/agents/jev-pong/viewer/studio.js
new file mode 100644
index 000000000..c27c5d2b3
--- /dev/null
+++ b/store/agents/jev-pong/viewer/studio.js
@@ -0,0 +1,117 @@
+// Jev Pong pane — draws the court, the bouncing ball, Jev's paddle, the rally and the decision log.
+// The ball ricochets; the paddle is Jev's. When a fast ball slips past the left wall, it's a miss.
+
+const $ = (id) => document.getElementById(id)
+const els = { rally: $('rally'), best: $('best'), misses: $('misses'), move: $('move'), speed: $('speed'), court: $('court'), gauge: $('gauge'), log: $('log') }
+
+let ball = { x: 140, y: 60, vx: -6, vy: 1 }
+let paddleY = 60
+let rally = 0, best = 0, misses = 0
+let lastMove = 'HOLD'
+let lastConf = 0.5
+let history = []
+let speedBase = 6
+
+// physics constants must mirror viewer defaults
+const VIR = { W: 200, H: 120, paddleH: 26, ballR: 3 }
+
+function draw() {
+ const cv = els.court, ctx = cv.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = cv.clientWidth, H = cv.clientHeight
+ cv.width = W * dpr; cv.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+ const sx = W / VIR.W, sy = H / VIR.H
+
+ // court border + centre line
+ ctx.strokeStyle = '#1c2030'; ctx.lineWidth = 2
+ ctx.strokeRect(2, 2, W - 4, H - 4)
+ ctx.beginPath(); ctx.moveTo(W / 2, 0); ctx.lineTo(W / 2, H); ctx.strokeStyle = '#161a26'; ctx.stroke()
+
+ // risk band near the paddle wall (where a miss happens)
+ ctx.fillStyle = 'rgba(251,113,133,0.06)'
+ ctx.fillRect(0, 0, 14, H)
+
+ // predicted intercept ghost: where the ball will cross the left wall (simple bounce fold)
+ if (ball.vx < 0) {
+ const span = VIR.H - 2 * VIR.ballR
+ const t = -ball.x / (ball.vx || -1)
+ const u = ((ball.y - VIR.ballR + ball.vy * t) % (2 * span) + 2 * span) % (2 * span)
+ const ty = u <= span ? u + VIR.ballR : 2 * VIR.H - VIR.ballR - (u - span) - VIR.ballR
+ const gx = 10, gy = ty * sy
+ ctx.strokeStyle = 'rgba(56,189,248,0.25)'; ctx.lineWidth = 1.5
+ ctx.beginPath()
+ // short fading line from ball to intercept
+ ctx.moveTo(ball.x * sx, ball.y * sy)
+ ctx.lineTo(gx, gy)
+ ctx.stroke()
+ ctx.fillStyle = 'rgba(56,189,248,0.4)'
+ ctx.beginPath(); ctx.arc(gx, gy, 3, 0, Math.PI * 2); ctx.fill()
+ }
+
+ // paddle (Jev)
+ const py = paddleY * sy
+ const ph = VIR.paddleH * sy
+ const hitNear = Math.abs(ball.x - 5) < 14 && Math.abs(ball.y - paddleY) < VIR.paddleH / 2 + 2
+ ctx.fillStyle = hitNear ? '#5eead4' : '#38bdf8'
+ ctx.shadowColor = '#38bdf8'; ctx.shadowBlur = hitNear ? 18 : 10
+ ctx.fillRect(3, py - ph / 2, 9, ph)
+ ctx.shadowBlur = 0
+
+ // ball
+ const danger = ball.vx < 0 && ball.x < 60
+ ctx.fillStyle = danger ? '#fb7185' : '#f8fafc'
+ ctx.shadowColor = danger ? '#fb7185' : '#e2e8f0'; ctx.shadowBlur = 10
+ ctx.beginPath(); ctx.arc(ball.x * sx, ball.y * sy, VIR.ballR * Math.min(sx, sy), 0, Math.PI * 2); ctx.fill()
+ ctx.shadowBlur = 0
+}
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history.slice(-30)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="n">#${h.step}</span><span class="b">y ${h.ballY.toFixed(0)}</span><span class="m">${h.move}</span><span>${(h.conf * 100).toFixed(0)}%</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function onTick(msg) {
+ if (msg.ball) { ball = { ...msg.ball }; paddleY = msg.paddleY ?? paddleY }
+ rally = msg.rally ?? rally
+ best = msg.bestRally ?? best
+ misses = msg.misses ?? misses
+ lastMove = msg.lastMove || lastMove
+ lastConf = msg.conf ?? lastConf
+ history = msg.history || history
+ speedBase = msg.speed ?? speedBase
+
+ els.rally.textContent = String(rally)
+ els.best.textContent = String(best)
+ els.misses.textContent = String(misses)
+ els.move.textContent = lastMove
+ const curSpeed = Math.abs(ball.vx)
+ els.speed.textContent = String(speedBase) + (curSpeed > speedBase ? `→${curSpeed.toFixed(1)}` : '')
+ els.gauge.textContent = `ball ${ball.x.toFixed(0)},${ball.y.toFixed(0)} @ ${Math.abs(ball.vx).toFixed(1)} · paddle ${paddleY.toFixed(1)} · conf ${(lastConf * 100).toFixed(0)}% · rally ${rally}`
+ draw()
+ renderLog()
+}
+
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+window.addEventListener('resize', draw)
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-pong/viewer/viewer.mjs b/store/agents/jev-pong/viewer/viewer.mjs
new file mode 100644
index 000000000..7f47784db
--- /dev/null
+++ b/store/agents/jev-pong/viewer/viewer.mjs
@@ -0,0 +1,262 @@
+// Jev Pong viewer — a loopback server running a live paddle-defense demo. A ball ricochets
+// around a slim court; Jev (TypeSafe's System One model) decides the paddle's vertical move every
+// `pong.stepMs` to keep a rally alive. The agent shapes pong.json (ball speed, paddle authority) —
+// turn the speed up and watch Jev chase, wobble and finally drop it. The physics is honest but toy.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds pong.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT = {
+ title: 'Jev Pong',
+ description: 'Jev is the paddle — keep the rally alive as the ball speeds up.',
+ instrument: 'PONG',
+ courtW: 200, courtH: 120, paddleH: 26, ballR: 3,
+ speed: 6, maxSpeed: 3, accel: 0.5, topSpeed: 14, stepMs: 60,
+ style: 'Keep the rally alive. Track the ball, predict where it will cross your wall, and get the paddle there in time. Be decisive.',
+}
+
+const MOVES = ['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST']
+const MV = { MOVE_UP_FAST: -2, MOVE_UP: -1, HOLD: 0, MOVE_DOWN: 1, MOVE_DOWN_FAST: 2 }
+
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+// Fold a trajectory's y onto the court (bounce off floor/ceiling) at a given travel distance dx.
+function bounceY(y0, dy, H, r) {
+ const span = H - 2 * r
+ let u = (y0 - r + dy) % (2 * span)
+ if (u < 0) u += 2 * span
+ return u <= span ? u + r : 2 * H - r - u - r + r // reflect off far edge
+}
+
+function stateBlock(p, ball, paddleY, speed) {
+ const b = ball
+ const hardness = Math.max(0, Math.min(1, (speed - 3) / 9))
+ const dir = b.vx < 0 ? 'toward you' : 'away'
+ return `${p.style}
+A paddle on the left wall (centre y ${paddleY.toFixed(1)}, half-height ${(p.paddleH / 2).toFixed(0)}) defends a ${p.courtW}×${p.courtH} court.
+ball: x ${b.x.toFixed(1)} y ${b.y.toFixed(1)} vx ${b.vx.toFixed(1)} vy ${b.vy.toFixed(1)} (${dir})
+speed: ${speed.toFixed(1)} hardness: ${hardness.toFixed(2)}
+Move the paddle to meet the ball when it crosses your wall. Be decisive.`
+}
+
+function penalty(streak) {
+ return streak <= 2 ? ' · Jev keeps dropping it, dial the speed down' : ''
+}
+
+export async function startPongViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let p = readCfg(join(workspace, 'pong.json'))
+ let rng = mulberry32(90210)
+ // court state
+ let ball = { x: p.courtW * 0.7, y: p.courtH / 2, vx: -p.speed, vy: (rng() - 0.5) * p.speed }
+ let paddleY = p.courtH / 2
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let error = null
+ let step = 0
+ let running = false
+ let misses = 0
+ let bestRally = 0
+ let rally = 0
+ let history = [] // per-decision {step, ballY, paddleY, move, conf}
+ let lastMove = 'HOLD'
+ let lastConf = 0
+ let notifiedMiss = false
+
+ function readCfg(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ return { ...DEFAULT, ...raw }
+ } catch (e) {
+ error = clean(e.message)
+ return DEFAULT
+ }
+ }
+
+ function resetState() {
+ ball = { x: p.courtW * 0.7, y: p.courtH / 2, vx: -p.speed, vy: (rng() - 0.5) * p.speed }
+ paddleY = p.courtH / 2
+ misses = 0; bestRally = 0; rally = 0; history = []; notifiedMiss = false; step = 0
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ const state = history.length === 0 ? 'learning' : notifiedMiss ? 'missed' : 'rallying'
+ return {
+ spec: 1,
+ ready: history.length > 0,
+ summary: error
+ ? 'Jev Pong needs a fix'
+ : notifiedMiss
+ ? `${p.title} · dropped after ${rally} hits · best ${bestRally} · Jev lost the rally at speed ${p.speed}`
+ : `${p.title} · rally ${rally} · best ${bestRally} · Jev defending at speed ${p.speed}`,
+ findings: (error ? [{ severity: 'error', kind: 'pong', message: error }] : []).concat(
+ notifiedMiss ? [{ severity: 'warn', kind: 'pong', message: `Jev missed the ball at speed ${p.speed} after ${rally} hits — dial the speed down or it keeps dropping it` }] : []
+ ),
+ artifact: 'pong.json',
+ phases: [
+ { id: 'learn', name: 'Learning', state: history.length < 5 ? 'active' : 'done' },
+ { id: 'rally', name: 'Rallying', state: history.length >= 5 && !notifiedMiss ? 'active' : notifiedMiss ? 'done' : 'pending' },
+ { id: 'edge', name: 'At the edge', state: notifiedMiss ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick', title: p.title, description: p.description, instrument: p.instrument,
+ ball, paddleY, speed: p.speed, step, running, error, misses, bestRally, rally, lastMove, lastConf,
+ history: history.slice(-240),
+ })
+ }
+
+ function reset() { resetState(); tail(); if (running) schedule() }
+ function pause() { running = false; clearTimeout(timer) }
+ function start() { if (!running) { running = true; schedule() } }
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, p.stepMs) }
+ async function run() { if (stopped) return; await decide(); schedule() }
+
+ function integrate() {
+ const W = p.courtW, H = p.courtH, r = p.ballR
+ // paddle velocity from the last move, integrated before Jev's next read
+ const half = p.paddleH / 2
+ paddleY += (MV[lastMove] ?? 0) * (p.maxSpeed || 2.4)
+ paddleY = Math.max(half, Math.min(H - half, paddleY))
+ ball.x += ball.vx
+ ball.y += ball.vy
+ if (ball.y < r) { ball.y = r; ball.vy = Math.abs(ball.vy) }
+ if (ball.y > H - r) { ball.y = H - r; ball.vy = -Math.abs(ball.vy) }
+ if (ball.x > W - r) { ball.x = W - r; ball.vx = -Math.abs(ball.vx) } // right wall
+ // left wall: paddle hit or miss
+ if (ball.x <= r) {
+ if (Math.abs(ball.y - paddleY) <= half) {
+ ball.x = r
+ rally++
+ if (rally > bestRally) bestRally = rally
+ notifiedMiss = false
+ // the rally accelerates: each hit speeds the ball up, so a long rally gets harder and harder
+ ball.vx = Math.sign(ball.vx) * Math.min(p.speed + (p.accel ?? 0.5) * rally, (p.topSpeed ?? p.speed + 8))
+ } else {
+ misses++
+ notifiedMiss = true
+ rally = 0
+ // restart far on the right with a fresh-ish aim at the dial speed
+ ball = { x: W * 0.75, y: r + rng() * (H - 2 * r), vx: -p.speed, vy: (rng() - 0.5) * p.speed }
+ ball.vx = -p.speed
+ }
+ }
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ const res = await evaluate({
+ state: stateBlock(p, ball, paddleY, p.speed),
+ questions: {
+ move: { type: 'choice', instructions: 'Which paddle move keeps the rally alive?', options: MOVES },
+ conf: { type: 'noul', instructions: 'Is the ball under control?' },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ lastMove = String(res.answers.move?.choice || 'HOLD')
+ lastConf = typeof res.answers.conf?.noul === 'number' ? res.answers.conf.noul : 0.5
+ step++
+ integrate()
+ history.push({ step, ballY: ball.y, paddleY, move: lastMove, conf: lastConf })
+ if (history.length > 300) history.splice(0, history.length - 300)
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ const watcher = watch(join(workspace, 'pong.json'), () => {
+ p = readCfg(join(workspace, 'pong.json'))
+ tail()
+ if (running) schedule()
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: p.title, instrument: p.instrument, ball, paddleY, speed: p.speed, step, running, error, misses, bestRally, rally, lastMove, lastConf, history: history.slice(-240) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ resetState()
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startPongViewer({ workspace, port })
+ console.log(`Jev Pong listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-sheets/.gitignore b/store/agents/jev-sheets/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-sheets/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-sheets/AGENTS.md b/store/agents/jev-sheets/AGENTS.md
new file mode 100644
index 000000000..1fd1fbf30
--- /dev/null
+++ b/store/agents/jev-sheets/AGENTS.md
@@ -0,0 +1,130 @@
+# Jev Sheets in OpenHarness
+
+On the left is a live spreadsheet. Every Jev column header is a question, and **Jev, TypeSafe's
+System One model, answers it for every row**. One call per row, all columns at once, each answer
+with a probability. Cells are shaded by confidence. Cells under the review line get a "?" flag.
+When a row has a truth label, the column header shows how often Jev was right.
+
+On the right, you edit `sheet.json`. This is the ONLY file you edit. The viewer watches it and
+reloads the sheet on every save. The viewer is already running in the pane. Never propose opening
+a browser, changing ports, or running a second server.
+
+All data in a sheet is made up. Say so in `description`. Never present a sheet as a real inbox,
+real customers, real candidates or real advice.
+
+## Your job
+
+1. **Build a sheet on any topic the person asks for.** Write the rows yourself (made-up data), and
+ write sharp column questions with a meaning for every option.
+2. **Read the results.** The viewer writes `.harness/verdict.json` with the accuracy of each column,
+ how many cells sit under the review line, and the weakest rows. Read it. Do not edit it.
+3. **Sharpen the wording.** Reword the weakest question, save, and read the verdict again. Only the
+ changed column is asked again, so this loop is fast.
+
+## The sheet file
+
+```jsonc
+{
+ "title": "Fernhill Cloud inbox",
+ "description": "Made-up inbound messages for a company that does not exist. All data is synthetic.",
+ "context": "Each row is one inbound message to the shared inbox of a made-up file sync service.",
+ "textLabel": "Message", // the heading of the text column
+ "reviewBelow": 0.65, // cells with confidence under this get a ? flag (0 to 1)
+ "concurrency": 8, // calls in flight at once (1 to 32)
+ "demo": true, // the ghost typist demo loop
+ "columns": [
+ { "id": "urgent", "header": "Urgent?" },
+ { "id": "team", "header": "Team: billing = payment or invoice problems | tech = bugs and outages | sales = pricing and quotes" },
+ { "id": "anger", "header": "Anger: calm < annoyed < furious" }
+ ],
+ "suggestions": ["Wants a refund?", "Churn risk: low < medium < high"],
+ "rows": [
+ { "id": "m01", "from": "Dana Whitfield", "plan": "pro", "group": "clear",
+ "text": "Hi, could you send me a copy of the invoice for March?",
+ "truth": { "urgent": false, "team": "billing", "anger": "calm" } }
+ ]
+}
+```
+
+- **`rows`**: 1 to 2000. Each needs a non-empty `text`. Give each a short unique `id`. Any other
+ plain field (`from`, `plan`, `channel`) is shown with the row and sent to Jev with the text.
+ `group` is a label for you and the pane (`"clear"` or `"mixed"`). It is not sent to Jev.
+ `truth` maps a column id to the right answer: `true` or `false` for a yes or no column, the option
+ name for a choice, the level name for a score. Truth is optional. It is never sent to Jev.
+- **`columns`**: 0 to 12. A column is a header string, or `{ "id", "header" }`. Give columns an `id`
+ when rows have truth labels, so you can reword the header and keep the labels lined up.
+- **`context`**: one sentence about what a row is. It is put in front of every question.
+- **`suggestions`**: headers shown as chips in the pane. The demo loop types them one at a time.
+
+## The person's own data
+
+The template's rows are made up. The real use is the person's own file. If they have a spreadsheet
+export or a log, have them drop it in the workspace, then point the sheet at it:
+
+```jsonc
+{
+ "title": "Inbound leads, week 38",
+ "source": "leads.csv", // .csv, .tsv, .jsonl or .json, inside the workspace, up to 8 MB
+ "textColumn": "message", // optional. Default: a column named text, message, body, ... or the longest one
+ "columns": ["Worth a call today?", "Segment: enterprise = 200+ seats | smb = small team | hobby"]
+}
+```
+
+Up to 2,000 rows are used. One column is the row's text. Every other column rides along as a plain
+field that Jev also reads, so "Seats" or "Plan" can inform an answer. The viewer watches the file:
+save it again and the sheet reloads. `rows` may be left out when `source` is set. Rows from the
+file have no truth labels, so the pane shows confidence and review flags, not accuracy.
+
+Look at the file before you write questions: read its header and a few rows, then write columns
+about what is really in it. Never copy the person's data into your replies beyond what you need,
+and never send it anywhere else.
+
+## The header grammar
+
+| Header | Type |
+|---|---|
+| `Urgent?` | ends with `?`, so it is a yes or no question (`noul`) |
+| `Team: billing \| tech \| sales` | `choice`, 2 to 255 options |
+| `Team: billing = payment or invoice problems \| tech = bugs and outages` | `choice` with a meaning for each option. Always do this. |
+| `Anger: calm < annoyed < furious` | `score`, 2 to 10 ordered levels, lowest first |
+| `Urgency` | a bare word is a score with `low < medium < high` |
+
+## Writing sharp questions
+
+- Ask about one thing. "Urgent and angry?" is two questions. Make two columns.
+- Give every choice option a meaning in plain words that would appear in a row. Options cannot see
+ each other, and Jev cannot see your other columns.
+- Name score levels so that each one is easy to tell from the next. Three to five levels work best.
+- A yes or no header should read as a full question when the topic is not obvious:
+ `Asks for a refund?` beats `Refund?`.
+- Put shared facts in `context`, not in every header.
+
+## Making the sheet honest
+
+Write most rows with one clear signal. Then add a block of rows with mixed signals on purpose and
+mark them `"group": "mixed"` ("No rush, but production is down"). Jev should be less sure on those,
+and the review line should catch them. If confidence is just as high on the mixed rows, or the clear
+rows are often wrong, report it. Do not hide it by deleting rows.
+
+## Rules
+
+- Keep `sheet.json` valid JSON. A bad edit does not crash the pane: it keeps the last good sheet and
+ shows the error. Fix the file when you see that.
+- Validate with `node "$JEV_DSH/toolchain/check.mjs"` before you say you are done.
+- Do not edit `.harness/verdict.json`. The viewer writes it. You may read it.
+- What a person does in the pane (typed columns, row edits, sort, the review line) is not saved to
+ `sheet.json`. If they like a column they typed, add it to `columns` for them.
+- Without a `TYPESAFE_API_KEY` the harness runs on a deterministic local mock that reads word cues.
+ It is a stand-in for the plumbing, not for Jev's judgement. On the mock, rows must use the same
+ words as the option meanings to be read well. With a key, the viewer calls the real API.
+- You can ask Jev directly through `toolchain/jev.mjs` (`evaluate`, `jev.noul`, `jev.choice`,
+ `jev.score`) to try a question on a few rows before you put it in the sheet.
+- This is a demo on made-up data. Keep `title` and `description` truthful.
+
+## Definition of done
+
+- `sheet.json` passes `toolchain/check.mjs`.
+- The sheet is on the topic the person asked for, with made-up rows and a mixed-signal block.
+- Every choice option has a meaning. Every score has clear levels.
+- You have read `.harness/verdict.json` and told the person, in plain words: how right each column
+ is, how many cells need review, and which question you would sharpen next.
diff --git a/store/agents/jev-sheets/LICENSE b/store/agents/jev-sheets/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-sheets/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-sheets/README.md b/store/agents/jev-sheets/README.md
new file mode 100644
index 000000000..151b968b0
--- /dev/null
+++ b/store/agents/jev-sheets/README.md
@@ -0,0 +1,114 @@
+# Jev Sheets
+
+**A spreadsheet where a column header is a question.** Type `Urgent?` at the top of a column and
+Jev, TypeSafe's System One model, answers it for every row. Each answer comes with a probability,
+so every cell is shaded by how sure Jev is, and the unsure ones are flagged for a person to review.
+
+This is a harness for OpenHarness. The agent on the right edits `sheet.json`. The viewer on the left
+is the sheet. It asks Jev one call per row, with every Jev column as a parallel question in that
+call, so a new column fills the sheet in a wave, top to bottom, in about a second.
+
+All the data is made up. The template is 60 inbound sales and support messages for Fernhill Cloud,
+a file sync company that does not exist. The names, the messages and the truth labels are synthetic.
+
+## Bring your own file
+
+The starter rows are made up. Put your own `leads.csv` (or `.tsv`, `.jsonl`, `.json`) in the workspace
+and set `"source": "leads.csv"` in `sheet.json`. Up to 2,000 rows load, one column becomes the row's
+text and the others ride along as fields Jev also reads. Then type any question as a column header.
+With a live key that is a few seconds and a fraction of a cent for a question over every row.
+
+## The header grammar
+
+| You type | It becomes |
+|---|---|
+| `Urgent?` | a yes or no question (`noul`). Ends with a question mark. |
+| `Team: billing \| tech \| sales` | a `choice` of 2 to 255 options |
+| `Team: billing = payment or invoice problems \| tech = bugs and outages` | the same, with a meaning for each option. This makes Jev sharper. |
+| `Anger: calm < annoyed < furious` | a `score` on 2 to 10 ordered levels |
+| `Urgency` | a bare word becomes a score: `low < medium < high` |
+
+One parser (`viewer/grammar.mjs`) is used by the viewer, by the pane while you type, and by
+`toolchain/check.mjs`.
+
+## What you can do in the pane
+
+- Type a header in the add box and press Enter. The column appears and fills in a wave.
+- Click a header to sort by it. Click again to reverse, again to clear. Rows slide to their places.
+- Click the small x on a header to remove the column.
+- Click a cell to inspect it: the row, the question Jev was asked, the full probability bars, and
+ the truth label if there is one.
+- Double-click a message to edit it. That row is judged again at once, across all columns.
+- Turn on "needs review only", and drag the review line. A small histogram shows where the
+ confidence of all cells sits.
+- Reset drops everything done in the pane and judges the sheet again from `sheet.json`.
+
+While nobody is playing, a "ghost typist" types a suggested header every 20 seconds or so, lets it
+fill, and retires the older demo column. It is tagged "demo". Anything you do rests it for a minute,
+and the demo button turns it off.
+
+## The honest dial
+
+The dial is ambiguity. The template has 44 clear rows and 16 rows written with mixed signals on
+purpose ("No rush at all, but our production backups have been failing since Monday"). Nothing is
+randomised. On the offline mock the tests measure:
+
+- clear rows: average confidence 0.86, 99% right
+- mixed rows: average confidence 0.72, 73% right
+- cells under the 0.65 review line: 1.5% of clear cells, 44% of mixed cells
+
+So the review line catches the rows a person should look at. Move the line and the count moves.
+
+## Anatomy
+
+```
+jev-sheets/
+ harness.json DSH manifest (engine: claude)
+ AGENTS.md what the chat agent does: build sheets, sharpen questions
+ skills/sheets/SKILL.md the craft of writing rows and questions
+ template/sheet.json the starter sheet (60 made-up messages, 3 Jev columns, truth labels)
+ toolchain/
+ jev.mjs the Jev client (real TypeSafe API, or a deterministic mock)
+ check.mjs validates sheet.json
+ viewer.sh setup.sh doctor.sh init-workspace.sh
+ viewer/
+ viewer.mjs the server: owns the sheet, the call pool, the cache, the verdict
+ grammar.mjs the header parser, shared with the pane and check.mjs
+ mock.mjs the offline stand-in reader (reads only the row text and the question)
+ kit.mjs loopback server, SSE, config watcher, verdict writer
+ index.html studio.css studio.js base.css jev-hud.js the pane
+ test/viewer.test.mjs
+```
+
+## How it runs
+
+`viewer/viewer.mjs` serves the pane on a loopback port and watches `sheet.json`. For each row with a
+missing cell it sends one `evaluate()` call: the row is the state, and every missing Jev column is a
+question. Eight calls run at a time. Answers are cached by row text plus column definition, so
+adding a column asks only for that column, editing a row asks only for that row, and adding rows
+asks only for the new rows. A bad JSON edit keeps the last good sheet on screen and shows the error.
+
+The viewer writes `.harness/verdict.json` itself: cells filled, cells under the review line, the
+accuracy of each column against the truth labels, and the weakest rows of each column. The chat
+agent reads it to decide which question to sharpen.
+
+With `TYPESAFE_API_KEY` set, the calls go to the real API (`POST /v1/systemone`). Without it, the
+harness runs on a deterministic local mock. The mock reads word cues in the row text, so it is a
+stand-in for the plumbing and not for Jev's judgement. It paces each call at about 90 ms so the
+wave looks like the live one. The pane always shows a MOCK or LIVE badge.
+
+## Jev, honestly
+
+The public claims about Jev are speed and price: about 100 ms per call, and $0.042 per million input
+tokens with free output. This harness shows both numbers live, and the cost of filling the whole
+template is well under a cent. But the inbox is made up, the truth labels are one person's opinion
+about made-up messages, and the accuracy you see offline is the mock's, not Jev's. Treat it as a
+demo of a pattern (typed questions over rows, with calibrated confidence and a review line), not as
+a measurement of any real support queue.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API. It contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed. This wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
diff --git a/store/agents/jev-sheets/THIRD_PARTY_NOTICES.md b/store/agents/jev-sheets/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-sheets/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-sheets/harness.json b/store/agents/jev-sheets/harness.json
new file mode 100644
index 000000000..cfeceb5d6
--- /dev/null
+++ b/store/agents/jev-sheets/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-sheets",
+ "name": "Jev Sheets",
+ "category": "Productivity",
+ "author": "Autonomous",
+ "description": "A live spreadsheet where a column header is a question. Type \"Urgent?\" and Jev, TypeSafe's System One model, answers it for every row: one call per row, all columns at once, each cell shaded by confidence and flagged for review when unsure. Made-up data. Runs offline on a mock.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "sheet.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-sheets/skills/sheets/SKILL.md b/store/agents/jev-sheets/skills/sheets/SKILL.md
new file mode 100644
index 000000000..018054a6e
--- /dev/null
+++ b/store/agents/jev-sheets/skills/sheets/SKILL.md
@@ -0,0 +1,97 @@
+# Craft: Jev Sheets
+
+Jev Sheets is a spreadsheet where a column header is a typed question and Jev answers it for every
+row. The craft has two halves: writing rows that feel real, and wording questions so the answers
+are right and the confidence is honest. All rows are made up. Say so in `description`.
+
+## How one row is judged
+
+For each row the viewer makes ONE call. The state is the row (its `text` plus plain fields like
+`from` or `plan`). The questions are all the Jev columns, asked in parallel. Questions cannot see
+each other, and nobody sees `truth` or `group`.
+
+```
+state { "text": "You charged my card twice. Refund it today.", "plan": "pro" }
+questions urgent noul "Urgent?"
+ team choice billing = payment or invoice problems | tech = bugs and outages | sales = ...
+ anger score calm < annoyed < furious
+answers urgent 0.86 team billing (0.84) anger annoyed (0.79)
+```
+
+Answers are cached by row text plus column definition. So after an edit to `sheet.json`, only the
+cells that changed are asked again. Rewording one header refills one column.
+
+## The header grammar
+
+```
+Urgent? yes or no (ends with ?)
+Team: billing | tech | sales choice (2 to 255 options)
+Team: billing = invoices, refunds | tech = bugs choice with meanings (always prefer this)
+Anger: calm < annoyed < furious score (2 to 10 levels, lowest first)
+Urgency score (bare word: low < medium < high)
+```
+
+In `sheet.json` a column is a header string or `{ "id": "team", "header": "Team: ..." }`. Use an
+`id` whenever rows carry `truth`, so rewording the header does not orphan the labels.
+
+## Building a sheet on a new topic
+
+1. Pick the unit of a row (a message, a review, an application, a bug report) and write `context`
+ in one sentence.
+2. Write 40 to 200 rows of made-up text, one to three sentences each. Vary length, tone and who is
+ writing. Add one or two plain fields if they help (`from`, `plan`, `channel`, `stars`).
+3. Write three to five columns. Mix the types: one yes or no, one choice, one score.
+4. Label `truth` for the starter columns on every row. It is what lets the pane show accuracy.
+5. Write a block of mixed-signal rows, about a quarter of the sheet, and mark them
+ `"group": "mixed"`. Mark the rest `"group": "clear"`. Good mixed rows pull two ways at once:
+ polite words with an angry point, "no rush" with an outage, a billing question inside a sales
+ request.
+6. Add six to ten `suggestions`: more headers a person could try on the same rows.
+7. Run `node "$JEV_DSH/toolchain/check.mjs"`.
+
+## Working on the person's own file
+
+Set `"source": "<file in the workspace>"` (csv, tsv, jsonl or json) and optionally `"textColumn"`.
+Read the file's header and a few rows first. Write columns about what is really there. The other
+columns are part of what Jev reads for each row, so questions can lean on them ("Worth a call
+today?" can use a `seats` column). There are no truth labels, so judge the questions by the review
+count and by reading the flagged rows in the verdict.
+
+## Reading the verdict
+
+The viewer writes `.harness/verdict.json`. Read `sheet.columns[]`:
+
+```jsonc
+{ "id": "team", "accuracy": 0.93, "labelled": 60, "underReviewLine": 11, "avgConfidence": 0.78,
+ "weakest": [ { "row": "x56", "text": "Before we sign for 200 seats, legal needs...",
+ "answered": "tech", "confidence": 0.47, "truth": "sales" } ] }
+```
+
+and `sheet.groups` for the average confidence of clear rows against mixed rows.
+
+- **Low accuracy on clear rows** means the question is unclear. Look at the weakest rows. Usually
+ two options overlap, or an option has no meaning written down. Reword and save.
+- **Many cells under the review line on clear rows** means the options are too close together, or a
+ score has too many levels. Merge or rename them.
+- **Mixed rows as confident as clear rows** means the mixed rows are not really mixed. Rewrite them
+ so the two signals are about equally strong.
+- **A confident wrong answer** is the most useful row in the sheet. Tell the person about it.
+
+Change one column at a time, save, and read the verdict again. Report what moved.
+
+## The offline mock
+
+Without `TYPESAFE_API_KEY`, a local mock answers. It counts word cues: the words of the header, the
+option names and their meanings, plus a small built-in list for common ideas (urgency, anger,
+billing, bugs, sales, refunds, churn, sentiment, spam, security). It knows nothing else. On the
+mock, a column only works if the rows use words that the option meanings also use. So write
+meanings with the words a row would really contain. The pane badges the mock as MOCK, and its
+accuracy says nothing about live Jev.
+
+## Definition of done
+
+- `sheet.json` passes `check.mjs`.
+- Made-up rows on the asked topic, with a mixed-signal block and truth labels.
+- Every choice option has a meaning. Scores have clear, ordered levels.
+- You read the verdict and reported: accuracy per column, cells under the review line, the average
+ confidence of clear against mixed rows, and the next question you would sharpen.
diff --git a/store/agents/jev-sheets/store.json b/store/agents/jev-sheets/store.json
new file mode 100644
index 000000000..6f43c0a70
--- /dev/null
+++ b/store/agents/jev-sheets/store.json
@@ -0,0 +1,17 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Type a question as a column header and Jev answers it for every row, live",
+ "examples": [
+ {
+ "prompt": "Build me a sheet of 80 made-up job applications for a junior designer role. Add Jev columns: \"Has a portfolio link?\", \"Fit: weak < fair < strong\" and \"Next step: reject = no relevant work | phone screen = some relevant work | interview = strong relevant work\". Put in 15 rows with mixed signals, label the truth, then read the accuracy and sharpen the weakest question.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/jev-sheets/typed-column.jpg",
+ "caption": "A header is a question: Jev fills every row in about a second, and the pane shows where it is unsure"
+ },
+ {
+ "prompt": "Turn the inbox sheet into a churn watch. Keep the rows, replace the columns with \"Wants to cancel?\", \"Churn risk: low < medium < high\" and \"Reason: price | bugs | missing feature | support\" with a clear meaning for each option. Then tell me which rows Jev is least sure about and why.",
+ "caption": "Reword the questions, watch only the changed column fill again, and review the low confidence cells"
+ }
+ ]
+}
diff --git a/store/agents/jev-sheets/template/sheet.json b/store/agents/jev-sheets/template/sheet.json
new file mode 100644
index 000000000..4b87f1b23
--- /dev/null
+++ b/store/agents/jev-sheets/template/sheet.json
@@ -0,0 +1,90 @@
+{
+ "title": "Fernhill Cloud inbox",
+ "description": "Made-up inbound sales and support messages for Fernhill Cloud, a file sync company that does not exist. Every name, message and label here is synthetic.",
+ "context": "Each row is one inbound message to the shared inbox of Fernhill Cloud, a made-up file sync and backup service.",
+ "textLabel": "Message",
+ "reviewBelow": 0.65,
+ "concurrency": 8,
+ "demo": true,
+ "columns": [
+ { "id": "urgent", "header": "Urgent?" },
+ { "id": "team", "header": "Team: billing = payment, invoice, charge or refund problems | tech = bugs, errors, sync failures and outages | sales = pricing, quotes, demos, upgrades, seats" },
+ { "id": "anger", "header": "Anger: calm < annoyed < furious" }
+ ],
+ "suggestions": [
+ "Wants a refund?",
+ "Churn risk: low < medium < high",
+ "Sentiment: negative < neutral < positive",
+ "Topic: login | sync | pricing | invoice | security",
+ "Asks for a manager?",
+ "Urgency",
+ "Mentions a competitor?",
+ "Company size: small < mid < large",
+ "Feature request?"
+ ],
+ "rows": [
+ { "id": "m01", "from": "Dana Whitfield, Marlow Dental", "plan": "pro", "group": "clear", "text": "Hi, could you send me a copy of the invoice for March? Our accountant needs the receipt for the books.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "m02", "from": "Tomas Reyes", "plan": "pro", "group": "clear", "text": "I was charged twice for my Pro plan this month. This is the second time it has happened and it is getting annoying. Please reverse the extra charge.", "truth": { "urgent": false, "team": "billing", "anger": "annoyed" } },
+ { "id": "m03", "from": "Priya Nair, Copperleaf Media", "plan": "team", "group": "clear", "text": "You charged my card $480 after I cancelled. This is outrageous and frankly a rip off. Refund it immediately or I dispute it with my bank.", "truth": { "urgent": true, "team": "billing", "anger": "furious" } },
+ { "id": "m04", "from": "Owen Hartley, Pinecrest Studio", "plan": "team", "group": "clear", "text": "We would like to move from monthly to annual billing. How does the payment work, and will we get one invoice for the year?", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "m05", "from": "Lucia Moretti, Halden Freight", "plan": "team", "group": "clear", "text": "Our payment failed this morning and the dashboard says the account will be suspended today. Can you retry the card right away? We cannot work without it.", "truth": { "urgent": true, "team": "billing", "anger": "calm" } },
+ { "id": "m06", "from": "Greta Lindqvist", "plan": "pro", "group": "clear", "text": "I asked for a VAT invoice two weeks ago and still have nothing. Quite disappointing, and not good enough for a paid product.", "truth": { "urgent": false, "team": "billing", "anger": "annoyed" } },
+ { "id": "m07", "from": "Sam Okafor", "plan": "pro", "group": "clear", "text": "Can I change the credit card on file? The old card expires next month. No rush.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "m08", "from": "Victor Brandt, Oakline Architects", "plan": "team", "group": "clear", "text": "THIS IS THE THIRD INVOICE WITH THE WRONG AMOUNT!!! Fix the billing right now, it is unacceptable.", "truth": { "urgent": true, "team": "billing", "anger": "furious" } },
+ { "id": "m09", "from": "Hannah Cole", "plan": "team", "group": "clear", "text": "Do you give refunds if we downgrade mid cycle? Just curious how the prorated amount shows on the bill.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "m10", "from": "Marek Novak", "plan": "pro", "group": "clear", "text": "My receipt shows a tax line that should not be there. I raised this before and I am a bit fed up with chasing it. Frustrating.", "truth": { "urgent": false, "team": "billing", "anger": "annoyed" } },
+ { "id": "m11", "from": "Aisha Rahman, Tidewater Labs", "plan": "enterprise", "group": "clear", "text": "Our finance team closes the quarter tomorrow. We need the corrected invoice and the payment receipt by end of day, it is urgent for the audit.", "truth": { "urgent": true, "team": "billing", "anger": "calm" } },
+ { "id": "m12", "from": "Colin Fraser", "plan": "team", "group": "clear", "text": "Your billing is a joke. I was overcharged for six months and nobody noticed. Pathetic, useless support. I want a manager to call me.", "truth": { "urgent": false, "team": "billing", "anger": "furious" } },
+ { "id": "m13", "from": "Mei Tanaka, Juniper and Moss", "plan": "team", "group": "clear", "text": "Please add our PO reference to future invoices. Thanks so much, the billing portal is great otherwise.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "m14", "from": "Rafael Duarte", "plan": "pro", "group": "clear", "text": "I need the refund for the duplicate payment today. I have asked twice already and I am not happy about the delay, it is getting old. Please treat it as urgent.", "truth": { "urgent": true, "team": "billing", "anger": "annoyed" } },
+ { "id": "m15", "from": "Ingrid Solberg, Birchwood School", "plan": "team", "group": "clear", "text": "Is it possible to pay by bank transfer instead of card? We are a school, and we would need an invoice for each term.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+
+ { "id": "m16", "from": "Noah Fischer", "plan": "pro", "group": "clear", "text": "The desktop app shows a sync error on one folder since the latest version. Everything else works. Logs attached for when you have time.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "m17", "from": "Bianca Russo, Bluegate Logistics", "plan": "enterprise", "group": "clear", "text": "The sync service is down AGAIN and my whole team is locked out. This outage is a nightmare, we are losing money every hour. FIX IT NOW!!!", "truth": { "urgent": true, "team": "tech", "anger": "furious" } },
+ { "id": "m18", "from": "Jonas Weber", "plan": "pro", "group": "clear", "text": "Uploads of large video files keep failing with a timeout. It is frustrating, this is the third time I have reported it.", "truth": { "urgent": false, "team": "tech", "anger": "annoyed" } },
+ { "id": "m19", "from": "Farah Haddad, Redfern Legal", "plan": "enterprise", "group": "clear", "text": "Production backups stopped working last night and we have an audit coming. Please look at this urgently, we are blocked.", "truth": { "urgent": true, "team": "tech", "anger": "calm" } },
+ { "id": "m20", "from": "Elliot Park", "plan": "free", "group": "clear", "text": "Small bug: the mobile app shows the wrong folder icon after a rename. Not urgent, just letting you know.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "m21", "from": "Dmitri Volkov", "plan": "team", "group": "clear", "text": "I am sick of this. Every update breaks the sync, the app crashes, and your support answers are useless. Worst backup tool I have paid for. We are switching to another provider.", "truth": { "urgent": false, "team": "tech", "anger": "furious" } },
+ { "id": "m22", "from": "Chloe Martin", "plan": "pro", "group": "clear", "text": "How do I restore a deleted file from version history? I could not find it in the web app.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "m23", "from": "Arjun Mehta, Lanternfish Games", "plan": "team", "group": "clear", "text": "The API returns error 500 on every upload since this morning. Our release is blocked and the deadline is Friday. Disappointing, and frankly not impressed with the silence on your status page.", "truth": { "urgent": true, "team": "tech", "anger": "annoyed" } },
+ { "id": "m24", "from": "Sofia Almeida", "plan": "pro", "group": "clear", "text": "The Windows app freezes for a few seconds when I open a big shared drive. Here is the error code: FS-2291.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "m25", "from": "Kwame Mensah, Goldfinch Design", "plan": "team", "group": "clear", "text": "We lost files!!! The sync corrupted a whole project folder and the client presentation is in two hours. This is an emergency. Absolutely unacceptable.", "truth": { "urgent": true, "team": "tech", "anger": "furious" } },
+ { "id": "m26", "from": "Petra Horvat", "plan": "free", "group": "clear", "text": "Is there a known glitch with the Linux client? It reinstalled itself after the last update and the sync starts from zero each time.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "m27", "from": "Liam Gallagher-Shaw", "plan": "pro", "group": "clear", "text": "Sync has been crashing on my laptop for a week. I reinstalled twice. Honestly a bit let down, I expected better, and this is tiresome.", "truth": { "urgent": false, "team": "tech", "anger": "annoyed" } },
+ { "id": "m28", "from": "Yara Haddad, Seaglass Clinic", "plan": "team", "group": "clear", "text": "Our office cannot work: the shared drive went down ten minutes ago for all 40 users. Please treat this as critical.", "truth": { "urgent": true, "team": "tech", "anger": "calm" } },
+ { "id": "m29", "from": "Ben Ashworth", "plan": "pro", "group": "clear", "text": "Logs attached. The upload of my photo library stops at 80 percent with a timeout error. Any idea?", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "m30", "from": "Nadia Petrova", "plan": "pro", "group": "clear", "text": "Third crash this week. Your desktop app is garbage and the last update made it worse. Ridiculous for a paid product.", "truth": { "urgent": false, "team": "tech", "anger": "furious" } },
+ { "id": "m31", "from": "Hugo Lambert, Atelier Nord", "plan": "team", "group": "clear", "text": "Could you check why conflict copies keep appearing in our design folder? It happens when two people save at the same time. It would be great if the app warned us.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+
+ { "id": "m32", "from": "Rosa Jimenez, Brightwater Agency", "plan": "free", "group": "clear", "text": "We are evaluating tools like yours for a 120 person agency. Could we get a demo and a quote for the team plan?", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m33", "from": "Andrew Kowalski, Ironbridge Group", "plan": "free", "group": "clear", "text": "Our procurement deadline is Friday. Please send pricing for 300 seats as soon as you can, the purchase has to be signed this week.", "truth": { "urgent": true, "team": "sales", "anger": "calm" } },
+ { "id": "m34", "from": "Leila Farouk, Open Shelf Trust", "plan": "free", "group": "clear", "text": "Do you have a discount for nonprofit organisations? We would need about 15 licenses.", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m35", "from": "Pete Sandoval", "plan": "free", "group": "clear", "text": "I am on the free plan and thinking about upgrading. How much is Pro per user if I pay yearly?", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m36", "from": "Ines Carvalho, Atlantico IT", "plan": "free", "group": "clear", "text": "We are a reseller in Portugal and would like to talk about a partnership. Who on your sales team should I contact? No hurry.", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m37", "from": "Grace Oduya, Kestrel Health", "plan": "team", "group": "clear", "text": "We want to buy 50 more seats today. Our new hires start tomorrow morning, so please send the quote right away.", "truth": { "urgent": true, "team": "sales", "anger": "calm" } },
+ { "id": "m38", "from": "Felix Braun", "plan": "free", "group": "clear", "text": "I asked for a demo twice through your website and nobody replied. Disappointing, and a frustrating way to treat someone who wants to buy.", "truth": { "urgent": false, "team": "sales", "anger": "annoyed" } },
+ { "id": "m39", "from": "Naomi Clarke, Wrenfield Partners", "plan": "team", "group": "clear", "text": "Can you share the price list for the enterprise plan? We are also looking at other providers for next year.", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m40", "from": "Stefan Ionescu, Corvid Systems", "plan": "free", "group": "clear", "text": "Our trial ends soon and we would like a proof of concept with single sign-on before we commit. Who can help with the rollout?", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m41", "from": "Amara Diallo, Stonebridge Retail", "plan": "enterprise", "group": "clear", "text": "Is there volume pricing above 500 seats? Our procurement team would like a formal quote.", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m42", "from": "Gordon Pike", "plan": "pro", "group": "clear", "text": "I have been trying to upgrade for a week and your sales team keeps ignoring me. Incompetent. How dare you leave a paying customer hanging. I want to speak to a manager.", "truth": { "urgent": false, "team": "sales", "anger": "furious" } },
+ { "id": "m43", "from": "Camille Roux, Maison Verre", "plan": "team", "group": "clear", "text": "We love the product. Could someone walk our leads through a demo of the team plan next month?", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "m44", "from": "Isaac Thornton", "plan": "team", "group": "clear", "text": "I need the quote for our annual plan by tomorrow. This is the second time I am asking and it is getting annoying. We sign this week.", "truth": { "urgent": true, "team": "sales", "anger": "annoyed" } },
+
+ { "id": "x45", "from": "Maya Lindgren", "plan": "pro", "group": "mixed", "text": "Thanks so much for the quick reply earlier. That said, being charged twice and then having sync break the same day is unacceptable.", "truth": { "urgent": false, "team": "billing", "anger": "annoyed" } },
+ { "id": "x46", "from": "Theo Marsh, Quillon Press", "plan": "team", "group": "mixed", "text": "No rush at all, but our production backups have been failing since Monday.", "truth": { "urgent": true, "team": "tech", "anger": "calm" } },
+ { "id": "x47", "from": "Olga Sorensen", "plan": "team", "group": "mixed", "text": "We might upgrade to the team plan, but first I need to know why the last invoice shows a charge for seats we never added.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "x48", "from": "Dev Kapoor, Saltmarsh Films", "plan": "team", "group": "mixed", "text": "Love the product, honestly. But the mobile app crashed again during a client demo and it was a bit disappointing.", "truth": { "urgent": false, "team": "tech", "anger": "annoyed" } },
+ { "id": "x49", "from": "Ruth Abernathy", "plan": "pro", "group": "mixed", "text": "Is the outage fixed? Whenever you get a moment, could you also tell me how much the enterprise plan costs?", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "x50", "from": "Carlos Vega", "plan": "pro", "group": "mixed", "text": "I want a refund. Actually, if you can fix the upload error today I will stay and even add seats.", "truth": { "urgent": true, "team": "tech", "anger": "annoyed" } },
+ { "id": "x51", "from": "Ann-Marie Lowe", "plan": "team", "group": "mixed", "text": "Your pricing page says one thing and my bill says another. Which is right? Not urgent, but it is getting old.", "truth": { "urgent": false, "team": "billing", "anger": "annoyed" } },
+ { "id": "x52", "from": "Jasper Quinn", "plan": "free", "group": "mixed", "text": "URGENT?? Not really, just kidding. When you get a chance, can you look at why my folder icons look odd.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "x53", "from": "Helena Voss, Pale Harbor Co", "plan": "team", "group": "mixed", "text": "The shared drive is down for one intern, everyone else is fine. Take your time.", "truth": { "urgent": false, "team": "tech", "anger": "calm" } },
+ { "id": "x54", "from": "Malik Osei", "plan": "team", "group": "mixed", "text": "Great service overall, five stars. One thing though: the renewal charge was higher than the quote your sales rep gave us.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "x55", "from": "Tessa Blom", "plan": "pro", "group": "mixed", "text": "I am not angry, just confused: the app says payment failed, but my bank shows the charge went through and now sync is paused.", "truth": { "urgent": false, "team": "billing", "anger": "calm" } },
+ { "id": "x56", "from": "Robert Achebe, Meridian Works", "plan": "free", "group": "mixed", "text": "Before we sign for 200 seats, legal needs to know if the outage last month caused any data loss. Deadline is Friday, but do not drop everything.", "truth": { "urgent": true, "team": "sales", "anger": "calm" } },
+ { "id": "x57", "from": "Pia Lund", "plan": "pro", "group": "mixed", "text": "Third time asking nicely: please cancel the add-on and refund the difference. Cheers.", "truth": { "urgent": false, "team": "billing", "anger": "annoyed" } },
+ { "id": "x58", "from": "Desmond Hale", "plan": "team", "group": "mixed", "text": "The new pricing is ridiculous, although to be fair the product itself has been flawless and support was kind.", "truth": { "urgent": false, "team": "sales", "anger": "annoyed" } },
+ { "id": "x59", "from": "Yuki Sato, Paperkite", "plan": "pro", "group": "mixed", "text": "Can someone call me right now about upgrading? Actually tomorrow is fine too, whenever works.", "truth": { "urgent": false, "team": "sales", "anger": "calm" } },
+ { "id": "x60", "from": "Erin Doyle", "plan": "team", "group": "mixed", "text": "Invoice attached. Also the desktop app asks me to log in every hour, and I would like a quote for ten more seats. Thanks!", "truth": { "urgent": false, "team": "tech", "anger": "calm" } }
+ ]
+}
diff --git a/store/agents/jev-sheets/test/viewer.test.mjs b/store/agents/jev-sheets/test/viewer.test.mjs
new file mode 100644
index 000000000..b0336663e
--- /dev/null
+++ b/store/agents/jev-sheets/test/viewer.test.mjs
@@ -0,0 +1,412 @@
+// Viewer tests for Jev Sheets. Each test spins up the real viewer against a temp workspace.
+// Time is driven with the `tick` and `drain` controls, never with sleeps on the wave.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { spawnSync } from 'node:child_process'
+import { connect } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseHeader } from '../viewer/grammar.mjs'
+import { startSheetsViewer } from '../viewer/viewer.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const TEMPLATE = JSON.parse(readFileSync(join(HERE, '../template/sheet.json'), 'utf8'))
+const CHECK = join(HERE, '../toolchain/check.mjs')
+const wait = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function fresh(overrides = {}, opts = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-sheets-test-'))
+ const file = join(ws, 'sheet.json')
+ writeFileSync(file, JSON.stringify({ ...TEMPLATE, ...overrides }))
+ const viewer = await startSheetsViewer({ workspace: ws, port: 0, ...opts })
+ const state = async () => (await fetch(`${viewer.url}/state`)).json()
+ const post = async (cmd, body = {}) => fetch(`${viewer.url}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd, ...body }) })
+ const ctl = async (cmd, body) => (await post(cmd, body)).json()
+ const until = async (pred, ms = 4000) => { const end = Date.now() + ms; for (;;) { const s = await state(); if (pred(s)) return s; if (Date.now() > end) assert.fail('timed out waiting for the viewer'); await wait(40) } }
+ return { ws, file, viewer, state, post, ctl, until }
+}
+
+test('the loop advances: one tick judges one row, every Jev column in one call', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ let s = await v.state()
+ assert.equal(s.stats.cellsFilled, 0)
+ assert.equal(s.stats.cellsTotal, 180)
+ assert.deepEqual(await v.ctl('tick'), { ok: true, row: 'm01' })
+ s = await v.state()
+ assert.equal(s.stats.calls, 1, 'one call for the row')
+ assert.equal(s.stats.cellsFilled, 3, 'three columns answered by that one call')
+ const c = s.cells.m01
+ assert.ok(c.urgent.p >= 0 && c.urgent.p <= 1 && [0, 1].includes(c.urgent.v))
+ assert.ok(c.team.v >= 0 && c.team.v < 3 && c.team.c > 0 && c.team.c <= 1)
+ assert.ok(c.anger.v >= 0 && c.anger.v < 3 && c.anger.s >= 0 && c.anger.s <= 2)
+ await v.ctl('tick')
+ s = await v.state()
+ assert.equal(s.stats.calls, 2)
+ assert.equal(s.stats.cellsFilled, 6)
+ assert.ok(s.stats.costUsd > 0, 'cost is metered')
+ assert.equal(s.client, 'mock')
+ // { n } runs many ticks at once, and a finished sheet ticks idle
+ assert.deepEqual(await v.ctl('tick', { n: 10 }), { ok: true, row: 'm12' })
+ assert.equal((await v.state()).stats.cellsFilled, 36)
+ await v.ctl('tick', { n: 500 })
+ s = await v.state()
+ assert.equal(s.stats.cellsFilled, 180)
+ assert.equal(s.stats.calls, 60)
+ assert.deepEqual(await v.ctl('tick'), { ok: true, idle: true })
+ } finally { await v.viewer.close() }
+})
+
+test('the sheet fills by itself in a wave, in about a second', async () => {
+ const v = await fresh()
+ try {
+ const t0 = Date.now()
+ const s = await v.until((x) => x.stats.cellsFilled === 180 && !x.stats.busy)
+ assert.ok(Date.now() - t0 < 3000, 'wave finished quickly')
+ assert.equal(s.stats.calls, 60, 'one call per row')
+ assert.ok(s.stats.cellsPerSec > 50, `cells per second is measured (${s.stats.cellsPerSec})`)
+ } finally { await v.viewer.close() }
+})
+
+test('config takes effect: non-default values from sheet.json show up in /state', async () => {
+ const v = await fresh({
+ title: 'Test Sheet 42', reviewBelow: 0.42, concurrency: 3, textLabel: 'Review', demo: false,
+ columns: ['Spam?', { id: 'stars', header: 'Stars: one < two < three < four < five' }],
+ rows: [{ id: 'a', text: 'Great product, love it, thanks!' }, { id: 'b', text: 'Click here for a limited offer, act now, bitcoin lottery' }],
+ suggestions: ['Rude?'],
+ }, { autostart: false })
+ try {
+ await v.ctl('drain')
+ const s = await v.state()
+ assert.equal(s.title, 'Test Sheet 42')
+ assert.equal(s.reviewBelow, 0.42)
+ assert.equal(s.concurrency, 3)
+ assert.equal(s.textLabel, 'Review')
+ assert.equal(s.ghost.enabled, false)
+ assert.deepEqual(s.columns.map((c) => [c.id, c.type]), [['spam', 'noul'], ['stars', 'score']])
+ assert.equal(s.columns[1].levels.length, 5)
+ assert.deepEqual(s.rows.map((r) => r.id), ['a', 'b'])
+ assert.deepEqual(s.suggestions, ['Rude?'])
+ assert.equal(s.cells.b.spam.v, 1, 'the spam row reads as spam')
+ assert.equal(s.cells.a.spam.v, 0)
+ } finally { await v.viewer.close() }
+})
+
+test('the verdict file is written with spec, summary, findings and phases', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ const file = join(v.ws, '.harness/verdict.json')
+ let verdict
+ for (let i = 0; i < 60; i++) { await wait(50); if (existsSync(file)) { verdict = JSON.parse(readFileSync(file, 'utf8')); if (verdict.ready) break } }
+ assert.equal(verdict.spec, 1)
+ assert.equal(verdict.ready, true)
+ assert.ok(verdict.summary && verdict.summary.length <= 200)
+ assert.ok(Array.isArray(verdict.findings) && verdict.findings.length >= 3)
+ for (const f of verdict.findings) assert.ok(['error', 'warning', 'info'].includes(f.severity) && f.message)
+ assert.ok(Array.isArray(verdict.phases) && verdict.phases.length === 3)
+ assert.equal(verdict.artifact, 'sheet.json')
+ const team = verdict.sheet.columns.find((c) => c.id === 'team')
+ assert.ok(team.accuracy > 0.8 && Array.isArray(team.weakest), 'the agent can read accuracy and the weakest rows')
+ } finally { await v.viewer.close() }
+})
+
+test('every control command answers 200', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ const cmds = [
+ ['pause'], ['tick'], ['start'], ['drain'], ['touch'],
+ ['addColumn', { header: 'Wants a refund?' }], ['addColumn', { header: 'Broken: only one' }],
+ ['sort', { col: 'team' }], ['sort', { col: 'nope' }], ['reviewOnly', { on: true }], ['reviewOnly', { on: false }],
+ ['setReview', { value: 0.5 }], ['setReview', { value: 7 }], ['editRow', { id: 'm02', text: 'Thanks, all good now.' }], ['editRow', { id: 'zz', text: 'x' }],
+ ['inspect', { row: 'm01', col: 'team' }], ['removeColumn', { id: 'wants_a_refund' }], ['demo', { on: false }], ['demo', { on: true }],
+ ['ghost'], ['reset'], ['no-such-command'],
+ ]
+ for (const [cmd, body] of cmds) assert.equal((await v.post(cmd, body)).status, 200, cmd)
+ assert.equal((await v.ctl('no-such-command')).ok, false)
+ const bad = await fetch(`${v.viewer.url}/control`, { method: 'POST', body: '{nope' })
+ assert.equal(bad.status, 400)
+ } finally { await v.viewer.close() }
+})
+
+test('a bad JSON edit keeps the demo alive and reports the error', async () => {
+ const v = await fresh()
+ try {
+ await v.until((s) => s.stats.cellsFilled === 180)
+ writeFileSync(v.file, '{ "title": "broken", "rows": [ ')
+ let s = await v.until((x) => x.error)
+ assert.match(s.error, /sheet\.json/)
+ assert.equal(s.rows.length, 60, 'the last good sheet is still there')
+ assert.equal(s.stats.cellsFilled, 180)
+ assert.equal((await v.post('tick')).status, 200)
+ // valid JSON, but no usable rows: still alive, still the last good sheet
+ writeFileSync(v.file, JSON.stringify({ title: 'Empty', rows: 'oops' }))
+ s = await v.until((x) => /rows/.test(x.error ?? ''))
+ assert.equal(s.rows.length, 60)
+ // a good edit heals it
+ writeFileSync(v.file, JSON.stringify({ ...TEMPLATE, title: 'Healed' }))
+ s = await v.until((x) => x.title === 'Healed')
+ assert.equal(s.error, null)
+ } finally { await v.viewer.close() }
+})
+
+test('a non-loopback Host header gets 403', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ const port = Number(new URL(v.viewer.url).port)
+ const ask = (host) => new Promise((resolveP, reject) => {
+ const sock = connect(port, '127.0.0.1', () => sock.write(`GET /state HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`))
+ let buf = ''
+ sock.on('data', (d) => (buf += d))
+ sock.on('end', () => resolveP(buf.split('\r\n')[0]))
+ sock.on('error', reject)
+ })
+ assert.match(await ask('evil.example.com'), / 403 /)
+ assert.match(await ask(`127.0.0.1:${port}`), / 200 /)
+ } finally { await v.viewer.close() }
+})
+
+test('the honest dial: clear rows beat mixed-signal rows, in confidence and in accuracy', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ const s = await v.state()
+ const { clear, mixed } = s.groups
+ console.log(` clear rows: avg confidence ${clear.avgConf}, accuracy ${clear.acc} · mixed rows: avg confidence ${mixed.avgConf}, accuracy ${mixed.acc}`)
+ assert.ok(clear.avgConf - mixed.avgConf >= 0.08, `clear ${clear.avgConf} vs mixed ${mixed.avgConf}`)
+ assert.ok(clear.acc - mixed.acc >= 0.1, `accuracy clear ${clear.acc} vs mixed ${mixed.acc}`)
+ // every starter column reaches 85% on the clear rows
+ for (const col of s.columns) {
+ const rows = s.rows.filter((r) => r.group === 'clear')
+ const right = rows.filter((r) => s.cells[r.id][col.id].ok === 1).length
+ console.log(` ${col.name}: ${right}/${rows.length} right on clear rows`)
+ assert.ok(right / rows.length >= 0.85, `${col.id} ${right}/${rows.length}`)
+ }
+ // the review line catches the mixed rows, not the clear ones
+ const share = (g) => { const rows = s.rows.filter((r) => r.group === g); let n = 0, f = 0; for (const r of rows) for (const c of s.columns) { n++; if (s.cells[r.id][c.id].c < s.reviewBelow) f++ } return f / n }
+ console.log(` cells under the ${s.reviewBelow} line: clear ${(share('clear') * 100).toFixed(1)}%, mixed ${(share('mixed') * 100).toFixed(1)}%`)
+ assert.ok(share('mixed') > share('clear') * 3)
+ // and the line itself is a dial: a higher line flags more cells
+ const low = (await v.ctl('setReview', { value: 0.5 })) && (await v.state()).stats.flagged
+ const high = (await v.ctl('setReview', { value: 0.85 })) && (await v.state()).stats.flagged
+ assert.ok(high > low * 2, `flagged at 0.85 (${high}) vs 0.5 (${low})`)
+ } finally { await v.viewer.close() }
+})
+
+test('a header typed in the pane creates a column and fills every row, computing only the missing cells', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ const before = (await v.state()).stats
+ const added = await v.ctl('addColumn', { header: 'Wants a refund?' })
+ assert.deepEqual(added, { ok: true, id: 'wants_a_refund', type: 'noul' })
+ let s = await v.state()
+ assert.equal(s.stats.cellsFilled, 180, 'old cells stay, new ones are pending')
+ assert.equal(s.stats.cellsTotal, 240)
+ await v.ctl('drain')
+ s = await v.state()
+ assert.equal(s.columns.at(-1).source, 'pane')
+ for (const r of s.rows) assert.ok(s.cells[r.id].wants_a_refund, `row ${r.id} filled`)
+ assert.equal(s.stats.computed - before.computed, 60, 'only the 60 new cells were asked for')
+ assert.equal(s.stats.calls - before.calls, 60)
+ assert.equal(s.cells.m03.wants_a_refund.v, 1, 'the refund row says yes')
+ assert.equal(s.cells.m16.wants_a_refund.v, 0)
+ // same header again, a broken header, and the 12 column cap
+ assert.equal((await v.ctl('addColumn', { header: 'Wants a refund?' })).ok, false)
+ assert.match((await v.ctl('addColumn', { header: 'Team: solo' })).error, /options|levels/)
+ for (let i = 0; i < 8; i++) assert.equal((await v.ctl('addColumn', { header: `Extra ${i}?` })).ok, true)
+ assert.match((await v.ctl('addColumn', { header: 'One too many?' })).error, /at most 12/)
+ } finally { await v.viewer.close() }
+})
+
+test('answers are cached by row text plus column definition', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ assert.equal((await v.state()).stats.calls, 60)
+ // the agent adds one row: only that row is judged
+ const rows = [...TEMPLATE.rows, { id: 'new1', text: 'Our whole office is down, this is an emergency, fix it immediately!' }]
+ writeFileSync(v.file, JSON.stringify({ ...TEMPLATE, rows }))
+ await v.until((s) => s.rows.length === 61)
+ await v.ctl('drain')
+ let s = await v.state()
+ assert.equal(s.stats.calls, 61)
+ assert.equal(s.cells.new1.urgent.v, 1)
+ // the agent rewords one column: only that column is asked again, one question per call
+ const columns = TEMPLATE.columns.map((c) => (c.id === 'urgent' ? { id: 'urgent', header: 'Needs a reply today?' } : c))
+ writeFileSync(v.file, JSON.stringify({ ...TEMPLATE, rows, columns }))
+ await v.until((x) => x.columns[0].header === 'Needs a reply today?')
+ await v.ctl('drain')
+ s = await v.state()
+ assert.equal(s.stats.calls, 122)
+ assert.equal(s.stats.computed, 183 + 61)
+ } finally { await v.viewer.close() }
+})
+
+test('editing a row re-judges it at once across all columns', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ let s = await v.state()
+ assert.deepEqual([s.cells.m01.urgent.v, s.cells.m01.team.v, s.cells.m01.anger.v], [0, 0, 0], 'calm billing row')
+ const calls = s.stats.calls
+ assert.equal((await v.ctl('editRow', { id: 'm01', text: 'The sync service is down, we are losing money every hour. This outage is unacceptable, it is a nightmare!!!' })).ok, true)
+ s = await v.state()
+ assert.equal(s.cells.m01, undefined, 'its cells are cleared and waiting')
+ assert.equal(s.rows[0].edited, true)
+ await v.ctl('drain')
+ s = await v.state()
+ assert.equal(s.stats.calls, calls + 1, 'one call re-judged the row')
+ assert.deepEqual([s.cells.m01.urgent.v, s.cells.m01.team.v, s.cells.m01.anger.v], [1, 1, 2], 'urgent, tech, furious')
+ assert.equal(s.cells.m01.urgent.ok, undefined, 'the old truth label no longer applies')
+ } finally { await v.viewer.close() }
+})
+
+test('sort, the review filter and the review line', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ assert.deepEqual((await v.ctl('sort', { col: 'anger' })).sort, { col: 'anger', dir: 'desc' })
+ let s = await v.state()
+ const score = (id) => s.cells[id].anger.v // the level: 0 calm, 1 annoyed, 2 furious
+ for (let i = 1; i < s.order.length; i++) assert.ok(score(s.order[i - 1]) >= score(s.order[i]))
+ assert.deepEqual((await v.ctl('sort', { col: 'anger' })).sort, { col: 'anger', dir: 'asc' })
+ s = await v.state()
+ assert.ok(score(s.order[0]) <= score(s.order.at(-1)))
+ assert.equal((await v.ctl('sort', { col: 'anger' })).sort, null)
+ assert.deepEqual((await v.state()).order, TEMPLATE.rows.map((r) => r.id))
+
+ await v.ctl('reviewOnly', { on: true })
+ s = await v.state()
+ assert.ok(s.order.length > 0 && s.order.length < 60)
+ for (const id of s.order) assert.ok(Object.values(s.cells[id]).some((c) => c.c < s.reviewBelow), `${id} has a flagged cell`)
+ await v.ctl('setReview', { value: 0 })
+ assert.equal((await v.state()).order.length, 0)
+ await v.ctl('setReview', { value: 1 })
+ assert.equal((await v.state()).order.length, 60)
+ } finally { await v.viewer.close() }
+})
+
+test('the ghost typist adds a demo column, fills it, and retires the older one; touch pauses it', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ const one = await v.ctl('ghost')
+ assert.equal(one.typed, TEMPLATE.suggestions[0])
+ let s = await v.state()
+ assert.equal(s.columns.at(-1).source, 'demo')
+ assert.equal(s.stats.cellsFilled, 240)
+ const two = await v.ctl('ghost')
+ assert.deepEqual(two.removed, [one.added])
+ s = await v.state()
+ assert.deepEqual(s.columns.filter((c) => c.source === 'demo').map((c) => c.id), [two.added])
+ assert.equal(s.ghost.pausedMs, 0)
+ await v.ctl('touch')
+ assert.ok((await v.state()).ghost.pausedMs > 55000, 'an interaction rests the ghost for a minute')
+ await v.ctl('demo', { on: false })
+ assert.equal((await v.state()).ghost.enabled, false)
+ } finally { await v.viewer.close() }
+})
+
+test('reset drops what was done in the pane', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ await v.ctl('drain')
+ await v.ctl('addColumn', { header: 'Urgency' })
+ await v.ctl('editRow', { id: 'm05', text: 'Never mind.' })
+ await v.ctl('sort', { col: 'team' })
+ await v.ctl('setReview', { value: 0.9 })
+ await v.ctl('reset')
+ await v.ctl('drain')
+ const s = await v.state()
+ assert.deepEqual(s.columns.map((c) => c.id), ['urgent', 'team', 'anger'])
+ assert.equal(s.rows[4].text, TEMPLATE.rows[4].text)
+ assert.equal(s.sort, null)
+ assert.equal(s.reviewBelow, 0.65)
+ assert.equal(s.stats.cellsFilled, 180)
+ } finally { await v.viewer.close() }
+})
+
+test('the header grammar', () => {
+ const ok = (h) => { const p = parseHeader(h); assert.ok(p.ok, `${h}: ${p.error}`); return p.column }
+ assert.deepEqual([ok('Urgent?').type, ok('Urgent?').id], ['noul', 'urgent'])
+ const team = ok('Team: billing = payment or invoice problems | tech = bugs and outages | sales')
+ assert.equal(team.type, 'choice')
+ assert.deepEqual(team.options, ['billing', 'tech', 'sales'])
+ assert.deepEqual(team.descriptions, { billing: 'payment or invoice problems', tech: 'bugs and outages' })
+ const anger = ok('Anger: calm < annoyed < furious')
+ assert.deepEqual([anger.type, anger.levels], ['score', ['calm', 'annoyed', 'furious']])
+ assert.deepEqual([ok('Urgency').type, ok('Urgency').levels, ok('Urgency').bare], ['score', ['low', 'medium', 'high'], true])
+ assert.equal(ok(`Pick: ${Array.from({ length: 255 }, (_, i) => `o${i}`).join(' | ')}`).options.length, 255)
+ for (const bad of ['', ' ', 'Team: solo', 'Team:', 'Mix: a | b < c', 'Dup: a | A', `Big: ${Array.from({ length: 256 }, (_, i) => `o${i}`).join(' | ')}`, 'Long: 1<2<3<4<5<6<7<8<9<10<11', 'Gap: a < < c'])
+ assert.equal(parseHeader(bad).ok, false, `"${bad.slice(0, 30)}" should be rejected`)
+})
+
+test('check.mjs accepts the template and rejects out-of-range values', () => {
+ const run = (sheet) => {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-sheets-check-'))
+ writeFileSync(join(ws, 'sheet.json'), typeof sheet === 'string' ? sheet : JSON.stringify(sheet))
+ return spawnSync(process.execPath, [CHECK], { env: { ...process.env, HARNESS_WORKSPACE: ws }, encoding: 'utf8' })
+ }
+ const good = run(TEMPLATE)
+ assert.equal(good.status, 0, good.stdout)
+ assert.match(good.stdout, /ok .*60 rows, 3 Jev columns/)
+ assert.equal(run({ ...TEMPLATE, reviewBelow: 1.5 }).status, 1)
+ assert.equal(run({ ...TEMPLATE, rows: [] }).status, 1)
+ assert.equal(run({ ...TEMPLATE, rows: [{ id: 'a', text: ' ' }] }).status, 1)
+ assert.equal(run({ ...TEMPLATE, columns: ['Heat: 1<2<3<4<5<6<7<8<9<10<11'] }).status, 1)
+ assert.equal(run({ ...TEMPLATE, columns: ['Team: solo'] }).status, 1)
+ assert.equal(run({ ...TEMPLATE, columns: Array.from({ length: 13 }, (_, i) => `Q${i}?`) }).status, 1)
+ assert.equal(run({ ...TEMPLATE, rows: [{ id: 'a', text: 'hi', truth: { team: 'marketing' } }] }).status, 1)
+ assert.equal(run('{ nope').status, 1)
+})
+
+test('the pane files are served, and nothing else', async () => {
+ const v = await fresh({}, { autostart: false })
+ try {
+ for (const f of ['/', '/studio.js', '/studio.css', '/base.css', '/jev-hud.js', '/grammar.mjs', '/jev']) assert.equal((await fetch(v.viewer.url + f)).status, 200, f)
+ assert.match(await (await fetch(v.viewer.url + '/')).text(), /Jev Sheets/)
+ for (const f of ['/mock.mjs', '/viewer.mjs', '/../toolchain/jev.mjs', '/sheet.json']) assert.equal((await fetch(v.viewer.url + f)).status, 404, f)
+ } finally { await v.viewer.close() }
+})
+
+test("rows can come from the person's own CSV in the workspace, and the file is watched", async () => {
+ const { loadSource, parseDelimited } = await import('../viewer/source.mjs')
+ assert.deepEqual(parseDelimited('a,b\n"x, ""quoted""",2\r\n3,4\n'), [['a', 'b'], ['x, "quoted"', '2'], ['3', '4']])
+ const v = await fresh({ rows: undefined, source: 'leads.csv', columns: ['Urgent?'], demo: false }, { autostart: false })
+ try {
+ // No file yet: the demo stays up and says what is wrong.
+ let s = await v.state()
+ assert.match(String(s.configError ?? s.error ?? JSON.stringify(s)), /leads\.csv/)
+ writeFileSync(join(v.ws, 'leads.csv'), 'company,message,seats\nAcme,"Our checkout is down, please call today",40\nBolt,Just browsing for next year,3\n')
+ writeFileSync(v.file, JSON.stringify({ ...TEMPLATE, rows: undefined, source: 'leads.csv', columns: ['Urgent?'], demo: false }))
+ s = await v.until((x) => x.rows?.length === 2)
+ assert.equal(s.source.name, 'leads.csv'); assert.equal(s.source.textColumn, 'message')
+ assert.equal(s.rows[0].text, 'Our checkout is down, please call today')
+ assert.deepEqual(s.rows[0].meta, { company: 'Acme', seats: 40 })
+ // Editing the CSV reloads the sheet.
+ writeFileSync(join(v.ws, 'leads.csv'), 'company,message,seats\nAcme,"Our checkout is down, please call today",40\nBolt,Just browsing for next year,3\nCato,Invoice question,12\n')
+ s = await v.until((x) => x.rows?.length === 3)
+ assert.equal(s.rows[2].meta.company, 'Cato')
+ // A named text column, and a column that does not exist.
+ assert.equal(loadSource(v.ws, 'leads.csv', { textColumn: 'company' }).rows[0].text, 'Acme')
+ assert.match(loadSource(v.ws, 'leads.csv', { textColumn: 'nope' }).error, /not a column/)
+ } finally { await v.viewer.close() }
+})
+
+test('a source file must stay inside the workspace, and JSONL works too', async () => {
+ const { loadSource } = await import('../viewer/source.mjs')
+ const ws = mkdtempSync(join(tmpdir(), 'jev-sheets-src-'))
+ assert.match(loadSource(ws, '../../etc/passwd').error, /inside the workspace/)
+ assert.match(loadSource(ws, '/etc/passwd').error, /inside the workspace/)
+ assert.match(loadSource(ws, '.harness/verdict.json').error, /\.harness/)
+ assert.match(loadSource(ws, 'notes.pdf').error, /cannot be read|must be a/)
+ writeFileSync(join(ws, 'tickets.jsonl'), '{"id":"T1","body":"Refund me now","plan":"pro"}\n"a bare string row"\n{"body":""}\n')
+ const got = loadSource(ws, 'tickets.jsonl')
+ assert.equal(got.error, null)
+ assert.equal(got.rows.length, 2, 'rows without text are skipped')
+ assert.deepEqual(got.rows[0], { text: 'Refund me now', id_: 'T1', plan: 'pro' })
+ assert.equal(got.info.textColumn, 'body')
+})
diff --git a/store/agents/jev-sheets/toolchain/README.md b/store/agents/jev-sheets/toolchain/README.md
new file mode 100644
index 000000000..e92012621
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/README.md
@@ -0,0 +1,44 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
+
+## Going live
+
+Without a key everything runs on the offline stand-in and the pane says `MOCK`. For the real model,
+give the harness a key. The viewer is started by the Harness daemon, which does not see variables
+you export in a shell, so the reliable place is a small file in your home folder:
+
+```sh
+mkdir -p ~/.config/typesafe && chmod 700 ~/.config/typesafe
+printf 'TYPESAFE_API_KEY=%s\n' 'paste-your-key-here' > ~/.config/typesafe/credentials
+chmod 600 ~/.config/typesafe/credentials
+```
+
+Two routes work, and both speak the same question format:
+
+| route | what goes in the file | where to get it |
+|---|---|---|
+| TypeSafe direct | `TYPESAFE_API_KEY=...` | https://console.typesafe.ai/keys (there may be a waitlist) |
+| Cloudflare Workers AI | `CLOUDFLARE_ACCOUNT_ID=...` and `CLOUDFLARE_API_TOKEN=...` | a Cloudflare API token with Workers AI permission, no TypeSafe waitlist |
+
+Environment variables of the same names win over the file. Restart the harness after changing the
+file. `toolchain/doctor.sh` prints which route is active and never prints the key. One file serves
+every Jev harness on the machine. Never paste a key into the chat, and never save one in the
+workspace. Under `node --test`, or with `JEV_OFFLINE=1`, a key is ignored so tests stay deterministic.
diff --git a/store/agents/jev-sheets/toolchain/check.mjs b/store/agents/jev-sheets/toolchain/check.mjs
new file mode 100644
index 000000000..7fc40c196
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/check.mjs
@@ -0,0 +1,90 @@
+#!/usr/bin/env node
+// check.mjs — validate a sheet.json for the Jev Sheets harness.
+// Uses the same header parser as the viewer, so what passes here is what the pane can show.
+// node toolchain/check.mjs checks $HARNESS_WORKSPACE/sheet.json (or ./sheet.json)
+// node toolchain/check.mjs path.json checks that file
+import { readFileSync } from 'node:fs'
+import { join, dirname, resolve } from 'node:path'
+import { parseHeader, LIMITS } from '../viewer/grammar.mjs'
+import { loadSource } from '../viewer/source.mjs'
+
+const file = process.argv[2] || join(process.env.HARNESS_WORKSPACE || '.', 'sheet.json')
+let errors = 0, warnings = 0
+const error = (msg) => { errors++; console.log(`error ${msg}`) }
+const warn = (msg) => { warnings++; console.log(`warn ${msg}`) }
+
+let sheet
+try {
+ sheet = JSON.parse(readFileSync(file, 'utf8'))
+} catch (e) {
+ console.log(`error cannot read sheet.json: ${e.message}`)
+ process.exit(1)
+}
+if (!sheet || typeof sheet !== 'object' || Array.isArray(sheet)) { console.log('error sheet.json must be a JSON object'); process.exit(1) }
+
+if (!sheet.title || typeof sheet.title !== 'string') warn('no title')
+if (!sheet.description || !/made.?up|synthetic|fictional|not real/i.test(String(sheet.description))) warn('say in "description" that the data is made up')
+
+// ---- columns: 0 to 12 valid headers ------------------------------------------------------------
+const columns = new Map()
+const rawCols = sheet.columns ?? []
+if (!Array.isArray(rawCols)) error('"columns" must be a list')
+else {
+ if (rawCols.length > LIMITS.maxColumns) error(`at most ${LIMITS.maxColumns} Jev columns (found ${rawCols.length})`)
+ rawCols.forEach((c, i) => {
+ const header = typeof c === 'string' ? c : c?.header
+ const parsed = parseHeader(header, c && typeof c === 'object' ? c.id : undefined)
+ if (!parsed.ok) return error(`column ${i + 1}: ${parsed.error}`)
+ const col = parsed.column
+ if (columns.has(col.id)) return error(`column ${i + 1}: id "${col.id}" is used twice`)
+ columns.set(col.id, col)
+ if (col.type === 'choice' && Object.keys(col.descriptions).length < col.options.length) warn(`column "${col.name}": give every option a meaning (option = what it means). It makes Jev sharper`)
+ if (col.bare) warn(`column "${col.name}": a bare word becomes low < medium < high. Name your own levels for a sharper scale`)
+ })
+}
+
+// ---- rows: 1 to 2000, each with text -----------------------------------------------------------
+// A sheet may take its rows from the person's own file in the workspace: "source": "leads.csv".
+let sourceRows = 0
+if (sheet.source !== undefined) {
+ if (typeof sheet.source !== 'string' || !sheet.source.trim()) error('"source" must be a file name inside the workspace')
+ else {
+ const got = loadSource(resolve(dirname(file)), sheet.source.trim(), { textColumn: sheet.textColumn, limit: LIMITS.maxRows })
+ if (got.error) error(got.error)
+ else { sourceRows = got.rows.length; console.log(`info source ${got.info.name}: ${got.info.used} of ${got.info.total} rows, text column "${got.info.textColumn}"`) }
+ }
+}
+const rows = sheet.rows === undefined && sheet.source !== undefined ? [] : sheet.rows
+if (!Array.isArray(rows)) error('"rows" must be a list')
+else {
+ if (rows.length + sourceRows < 1 || rows.length > LIMITS.maxRows) error(`rows must number 1 to ${LIMITS.maxRows} (found ${rows.length + sourceRows})`)
+ const ids = new Set()
+ let labelled = 0
+ rows.forEach((r, i) => {
+ const where = `row ${i + 1}${r?.id ? ` (${r.id})` : ''}`
+ if (!r || typeof r !== 'object' || typeof r.text !== 'string' || !r.text.trim()) return error(`${where}: needs a non-empty "text"`)
+ if (r.id != null) { if (ids.has(String(r.id))) error(`${where}: id is used twice`); ids.add(String(r.id)) }
+ if (r.truth == null) return
+ if (typeof r.truth !== 'object' || Array.isArray(r.truth)) return error(`${where}: "truth" must be an object of columnId -> value`)
+ labelled++
+ for (const [cid, v] of Object.entries(r.truth)) {
+ const col = columns.get(cid)
+ if (!col) { warn(`${where}: truth for "${cid}", but there is no column with that id`); continue }
+ if (col.type === 'noul' && typeof v !== 'boolean') error(`${where}: truth.${cid} must be true or false`)
+ if (col.type === 'choice' && !col.options.some((o) => o.toLowerCase() === String(v).toLowerCase())) error(`${where}: truth.${cid} "${v}" is not one of ${col.options.join(' | ')}`)
+ if (col.type === 'score' && !(Number.isInteger(v) ? v >= 0 && v < col.levels.length : col.levels.some((l) => l.toLowerCase() === String(v).toLowerCase()))) error(`${where}: truth.${cid} "${v}" is not one of ${col.levels.join(' < ')}`)
+ }
+ })
+ if (rows.length && !labelled && !sourceRows) warn('no truth labels, so the pane cannot show accuracy')
+}
+
+// ---- settings ----------------------------------------------------------------------------------
+if (sheet.reviewBelow != null && !(typeof sheet.reviewBelow === 'number' && sheet.reviewBelow >= 0 && sheet.reviewBelow <= 1)) error('reviewBelow must be a number from 0 to 1')
+if (sheet.concurrency != null && !(Number.isInteger(sheet.concurrency) && sheet.concurrency >= 1 && sheet.concurrency <= 32)) error('concurrency must be a whole number from 1 to 32')
+if (sheet.suggestions != null) {
+ if (!Array.isArray(sheet.suggestions)) error('"suggestions" must be a list of headers')
+ else sheet.suggestions.forEach((s, i) => { const p = parseHeader(s); if (!p.ok) error(`suggestion ${i + 1}: ${p.error}`) })
+}
+
+if (errors) { console.log(`fail invalid sheet.json (${errors} error${errors > 1 ? 's' : ''}, ${warnings} warning${warnings === 1 ? '' : 's'})`); process.exit(1) }
+console.log(`ok sheet.json is valid: ${rows.length} rows, ${columns.size} Jev columns${warnings ? `, ${warnings} warning${warnings > 1 ? 's' : ''}` : ''}`)
diff --git a/store/agents/jev-sheets/toolchain/doctor.sh b/store/agents/jev-sheets/toolchain/doctor.sh
new file mode 100755
index 000000000..768aa3638
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/doctor.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Sheets viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+cd "$(dirname "$0")/.."
+node -e "import('./toolchain/jev.mjs').then((m) => console.log('ok Jev: ' + m.describeCredentials())).catch((e) => console.log('warn Jev client did not load: ' + e.message))"
+echo "done"
diff --git a/store/agents/jev-sheets/toolchain/init-workspace.sh b/store/agents/jev-sheets/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-sheets/toolchain/jev.mjs b/store/agents/jev-sheets/toolchain/jev.mjs
new file mode 100644
index 000000000..190c7e9ac
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
+// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
+// score a position on a 2..10 level scale — a float plus per-level probabilities
+//
+// Questions are authored as options[] / legend{} (or an option -> description map) and translated
+// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The generic mock reads
+// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
+// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
+// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ return key ? 'typesafe' : 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ return (h >>> 0) / 4294967296
+}
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+
+/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
+export function stems(text) {
+ const out = []
+ for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
+ if (w.length < 2 || STOP.has(w)) continue
+ out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
+ }
+ return out
+}
+
+/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
+function evidence(stateStems, needle) {
+ const want = [...new Set(stems(needle))]
+ if (!want.length) return 0
+ let hit = 0
+ for (const w of want) if (stateStems.has(w)) hit++
+ return (hit / Math.sqrt(want.length)) * 1.2
+}
+
+function softmax(raw, temp = 1) {
+ const m = Math.max(...raw)
+ const exps = raw.map((r) => Math.exp((r - m) / temp))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ return exps.map((e) => e / sum)
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic generic mock. It turns the state text + question wording into a plausible
+// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`
+ const S = new Set(stems(text))
+ const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
+
+ if (q.type === 'noul') {
+ const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
+ const no = evidence(S, `${q.raw?.false ?? ''}`)
+ const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
+ const probs = softmax(raw, 0.6)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
+ const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
+ // No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
+ if (raw.every((r) => Math.abs(r) < 0.26)) {
+ const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
+ levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
+ }
+ const probs = softmax(raw, 0.7)
+ const probabilities = {}
+ levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
+ const score = probs.reduce((acc, p, i) => acc + p * i, 0)
+ return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// Imports are hoisted, so they can live here with the code that needs them.
+import { readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ out.raw = isMap(q.criteria) ? q.criteria : null
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+// ---------------------------------------------------------------------------
+// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
+// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
+// you happen to have open. Two live routes are supported, both speaking the same question format:
+// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
+// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
+// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
+// ---------------------------------------------------------------------------
+const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN']
+let credCache = null
+export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
+
+function readCredentialFile() {
+ const now = Date.now()
+ const path = credentialsPath()
+ if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
+ const values = {}
+ try {
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
+ if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
+ }
+ } catch { /* no file: fine */ }
+ credCache = { at: now, path, values }
+ return values
+}
+
+/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
+export function resolveCredentials(explicitKey) {
+ if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
+ // Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
+ // key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
+ if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
+ const file = readCredentialFile()
+ const get = (k) => process.env[k] || file[k] || ''
+ const key = explicitKey || get('TYPESAFE_API_KEY')
+ if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
+ const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
+ if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
+ return null
+}
+
+/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
+export function describeCredentials() {
+ const c = resolveCredentials()
+ if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
+ return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
+}
+
+async function liveEvaluate(body, cred) {
+ const endpoint = cred.url
+ const key = cred.secret
+ const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } } : body
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) {
+ const data = await res.json()
+ // Cloudflare wraps the model's reply as { result, success, errors }.
+ if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
+ return data?.result?.answers ? data.result : data
+ }
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const cred = resolveCredentials(key)
+ const client = cred ? cred.provider : 'mock'
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (cred) {
+ const data = await liveEvaluate({ model, state, questions: wire }, cred)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-sheets/toolchain/setup.sh b/store/agents/jev-sheets/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-sheets/toolchain/viewer.sh b/store/agents/jev-sheets/toolchain/viewer.sh
new file mode 100755
index 000000000..49f498d0a
--- /dev/null
+++ b/store/agents/jev-sheets/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Sheets viewer (a live spreadsheet where every column header is a question Jev answers for each row).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-sheets/viewer/base.css b/store/agents/jev-sheets/viewer/base.css
new file mode 100644
index 000000000..c41ddcd46
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/base.css
@@ -0,0 +1,83 @@
+/* base.css — the shared look of the Jev flagship viewers. Load before studio.css.
+ Set --accent / --accent2 in studio.css to give a harness its own colour. */
+:root {
+ --bg: #07080d; --panel: #10121a; --panel2: #161925; --line: #232838; --line2: #2e3550;
+ --ink: #e9ecf5; --dim: #8b92aa; --faint: #565d75;
+ --accent: #a78bfa; --accent2: #6d5bd0;
+ --ok: #34d399; --warn: #fbbf24; --bad: #fb7185; --cyan: #5eead4; --blue: #60a5fa;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ --radius: 12px;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1100px 700px at 75% -10%, color-mix(in srgb, var(--accent) 14%, transparent) 0%, transparent 60%), var(--bg);
+ color: var(--ink); font: 13px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+::selection { background: color-mix(in srgb, var(--accent) 45%, transparent); }
+::-webkit-scrollbar { width: 8px; height: 8px; }
+::-webkit-scrollbar-thumb { background: var(--line2); border-radius: 4px; }
+::-webkit-scrollbar-track { background: transparent; }
+
+#topbar {
+ display: flex; align-items: center; gap: 22px; padding: 10px 18px; flex: none; flex-wrap: wrap;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(20,22,34,.92), rgba(10,11,18,.7)); backdrop-filter: blur(8px);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font: 700 15px var(--mono); letter-spacing: .4px; margin: 0; white-space: nowrap; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 14px var(--accent); animation: dot 2.4s ease-in-out infinite; }
+@keyframes dot { 50% { transform: scale(.72); opacity: .7; } }
+.brand .sub { color: var(--dim); font-size: 11px; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; min-width: 54px; }
+.stat label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+button, .btn {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line2); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: border-color .15s, filter .15s, transform .05s; user-select: none;
+}
+button:hover { border-color: var(--accent); }
+button:active { transform: translateY(1px); }
+button.primary { background: linear-gradient(135deg, var(--accent2), var(--accent)); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.12); }
+button.ghost { background: transparent; }
+button.on { border-color: var(--accent); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
+button[disabled] { opacity: .45; cursor: default; }
+kbd { font: 600 10px var(--mono); padding: 1px 5px; border: 1px solid var(--line2); border-bottom-width: 2px; border-radius: 4px; color: var(--dim); }
+input[type=text], input[type=search], select, textarea {
+ font: 13px var(--mono); color: var(--ink); background: #0b0d14; border: 1px solid var(--line2); border-radius: 8px; padding: 7px 10px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+input[type=range] { accent-color: var(--accent); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow: auto; }
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 14px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; background: rgba(12,13,20,.55); }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; }
+.panel-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--dim); margin-bottom: 9px; display: flex; align-items: center; gap: 8px; }
+.panel-title .right { margin-left: auto; text-transform: none; letter-spacing: 0; }
+.how { color: var(--dim); font-size: 12.5px; line-height: 1.55; }
+.how b { color: var(--ink); } .how code { color: var(--warn); }
+.pill { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line2); color: var(--dim); }
+.pill.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
+.pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
+.pill.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); }
+
+.canvas-wrap { position: relative; flex: 1; min-height: 320px; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #05060a; }
+.canvas-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.banner { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); padding: 9px 20px; border-radius: 10px; font: 700 14px var(--mono); white-space: nowrap; backdrop-filter: blur(6px); }
+.banner.ok { background: rgba(16,185,129,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 34px rgba(16,185,129,.35); }
+.banner.bad { background: rgba(225,29,72,.16); border: 1px solid var(--bad); color: var(--bad); box-shadow: 0 0 34px rgba(225,29,72,.35); }
+.hidden { display: none !important; }
+.cfg-error { margin: 0 16px; padding: 8px 12px; border: 1px solid var(--bad); border-radius: 8px; color: var(--bad); background: rgba(225,29,72,.08); font-size: 12px; }
+
+@media (max-width: 900px) {
+ main { flex-direction: column; overflow: auto; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); overflow: visible; }
+ body { overflow: auto; }
+}
diff --git a/store/agents/jev-sheets/viewer/grammar.mjs b/store/agents/jev-sheets/viewer/grammar.mjs
new file mode 100644
index 000000000..ca742f969
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/grammar.mjs
@@ -0,0 +1,171 @@
+// grammar.mjs — the header grammar of Jev Sheets. ONE parser, shared by the viewer server, the pane
+// (it shows a live hint while a person types a header) and toolchain/check.mjs.
+//
+// A Jev column is a typed question, written as a spreadsheet header:
+// Urgent? ends with "?" -> noul (yes / no)
+// Team: billing | tech | sales name: a | b | c -> choice (2..255 options)
+// Team: billing = invoices | tech = bugs option = what it means -> choice with descriptions
+// Anger: calm < annoyed < furious name: low < ... < high -> score (2..10 ordered levels)
+// Urgency a bare word -> score low < medium < high
+
+export const LIMITS = {
+ maxRows: 2000, maxColumns: 12, maxHeader: 20000, maxName: 80,
+ minOptions: 2, maxOptions: 255, minLevels: 2, maxLevels: 10,
+}
+
+export const BARE_LEVELS = ['low', 'medium', 'high']
+
+/** A stable id from a name: "Churn risk" -> "churn_risk". */
+export function slug(s) {
+ return String(s ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 32) || 'col'
+}
+
+const fail = (error) => ({ ok: false, error })
+const dupe = (list) => { const seen = new Set(); for (const x of list) { const k = x.toLowerCase(); if (seen.has(k)) return x; seen.add(k) } return null }
+
+/**
+ * Parse one header into a column definition.
+ * @returns {{ok:true, column:{id,header,name,type,options?,descriptions?,levels?,bare?}} | {ok:false, error:string}}
+ */
+export function parseHeader(input, id = undefined) {
+ if (typeof input !== 'string') return fail('a header must be text')
+ const header = input.replace(/\s+/g, ' ').trim()
+ if (!header) return fail('type a header first')
+ if (header.length > LIMITS.maxHeader) return fail(`a header can be at most ${LIMITS.maxHeader} characters`)
+
+ const colon = header.indexOf(':')
+ const name = (colon > 0 ? header.slice(0, colon) : header).trim()
+ const body = colon > 0 ? header.slice(colon + 1).trim() : ''
+ const done = (col) => {
+ if (col.name.length > LIMITS.maxName) return fail(`keep the column name under ${LIMITS.maxName} characters`)
+ return { ok: true, column: { id: id ? slug(id) : slug(col.name), header, ...col } }
+ }
+
+ if (colon > 0 && body.includes('<') && body.includes('|')) return fail('use "|" for a choice or "<" for a score, not both')
+
+ if (colon > 0 && body.includes('<')) {
+ const levels = body.split('<').map((s) => s.trim())
+ if (levels.some((l) => !l)) return fail('a score has an empty level. Write low < medium < high')
+ if (levels.length < LIMITS.minLevels || levels.length > LIMITS.maxLevels) return fail(`a score needs ${LIMITS.minLevels} to ${LIMITS.maxLevels} levels`)
+ const d = dupe(levels); if (d) return fail(`level "${d}" is listed twice`)
+ return done({ name, type: 'score', levels })
+ }
+
+ if (colon > 0 && body.includes('|')) {
+ const options = [], descriptions = {}
+ for (const part of body.split('|')) {
+ const eq = part.indexOf('=')
+ const opt = (eq >= 0 ? part.slice(0, eq) : part).trim()
+ const desc = eq >= 0 ? part.slice(eq + 1).trim() : ''
+ if (!opt) return fail('a choice has an empty option. Write a | b | c')
+ options.push(opt)
+ if (desc) descriptions[opt] = desc
+ }
+ if (options.length < LIMITS.minOptions || options.length > LIMITS.maxOptions) return fail(`a choice needs ${LIMITS.minOptions} to ${LIMITS.maxOptions} options`)
+ const d = dupe(options); if (d) return fail(`option "${d}" is listed twice`)
+ return done({ name, type: 'choice', options, descriptions })
+ }
+
+ if (header.endsWith('?')) return done({ name: header.replace(/\s*\?+$/, '').trim() || header, type: 'noul' })
+
+ if (colon > 0) return fail(body ? 'after the colon, list options with "|" or levels with "<"' : 'after the colon, list options (a | b) or levels (low < high)')
+
+ return done({ name, type: 'score', levels: [...BARE_LEVELS], bare: true })
+}
+
+/** A short plain-English reading of a header, for the live hint under the add box. */
+export function describeColumn(col) {
+ if (col.type === 'noul') return 'yes / no question'
+ if (col.type === 'choice') return `choice of ${col.options.length}${Object.keys(col.descriptions ?? {}).length ? ', with descriptions' : ''}`
+ return `score with ${col.levels.length} levels${col.bare ? ' (a bare word)' : ''}`
+}
+
+/** The cache identity of a column: two headers that ask the same thing share answers. */
+export function columnKey(col) {
+ if (col.type === 'noul') return `noul|${col.header}`
+ if (col.type === 'choice') return `choice|${col.name}|${col.options.map((o) => `${o}=${col.descriptions?.[o] ?? ''}`).join('|')}`
+ return `score|${col.name}|${col.levels.join('<')}`
+}
+
+const RESERVED = new Set(['id', 'text', 'truth', 'group'])
+
+/**
+ * Turn raw sheet.json into a clean sheet. Never throws: problems come back as `errors` (the bad
+ * item is skipped) so one bad row or header cannot take the demo down.
+ */
+export function normalizeSheet(raw) {
+ const errors = []
+ const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
+ if (src !== raw) errors.push('sheet.json must be a JSON object')
+
+ const rows = []
+ const ids = new Set()
+ const rawRows = Array.isArray(src.rows) ? src.rows : []
+ if (!Array.isArray(src.rows)) errors.push('"rows" must be a list')
+ if (rawRows.length > LIMITS.maxRows) errors.push(`only the first ${LIMITS.maxRows} rows are used`)
+ rawRows.slice(0, LIMITS.maxRows).forEach((r, i) => {
+ const row = typeof r === 'string' ? { text: r } : r
+ if (!row || typeof row !== 'object' || typeof row.text !== 'string' || !row.text.trim()) { errors.push(`row ${i + 1} has no text`); return }
+ let rid = String(row.id ?? `r${i + 1}`)
+ while (ids.has(rid)) rid += '_'
+ ids.add(rid)
+ const meta = {}
+ for (const [k, v] of Object.entries(row)) if (!RESERVED.has(k) && ['string', 'number', 'boolean'].includes(typeof v)) meta[k] = v
+ rows.push({
+ id: rid, text: row.text.trim().slice(0, 4000), meta,
+ group: typeof row.group === 'string' ? row.group : null,
+ truth: row.truth && typeof row.truth === 'object' && !Array.isArray(row.truth) ? { ...row.truth } : null,
+ })
+ })
+
+ const columns = []
+ const colIds = new Set()
+ const rawCols = Array.isArray(src.columns) ? src.columns : []
+ if (src.columns != null && !Array.isArray(src.columns)) errors.push('"columns" must be a list')
+ if (rawCols.length > LIMITS.maxColumns) errors.push(`only the first ${LIMITS.maxColumns} columns are used`)
+ rawCols.slice(0, LIMITS.maxColumns).forEach((c, i) => {
+ const header = typeof c === 'string' ? c : c?.header
+ const parsed = parseHeader(header, typeof c === 'object' && c ? c.id : undefined)
+ if (!parsed.ok) { errors.push(`column ${i + 1}: ${parsed.error}`); return }
+ if (colIds.has(parsed.column.id)) { errors.push(`column ${i + 1}: id "${parsed.column.id}" is used twice`); return }
+ colIds.add(parsed.column.id)
+ columns.push(parsed.column)
+ })
+
+ let reviewBelow = Number(src.reviewBelow ?? 0.65)
+ if (!Number.isFinite(reviewBelow) || reviewBelow < 0 || reviewBelow > 1) { errors.push('reviewBelow must be between 0 and 1'); reviewBelow = 0.65 }
+ let concurrency = Math.round(Number(src.concurrency ?? 8))
+ if (!Number.isFinite(concurrency) || concurrency < 1 || concurrency > 32) { errors.push('concurrency must be 1 to 32'); concurrency = 8 }
+
+ return {
+ title: typeof src.title === 'string' && src.title.trim() ? src.title.trim().slice(0, 120) : 'Untitled sheet',
+ description: typeof src.description === 'string' ? src.description.slice(0, 400) : '',
+ context: typeof src.context === 'string' ? src.context.trim().slice(0, 600) : '',
+ textLabel: typeof src.textLabel === 'string' && src.textLabel.trim() ? src.textLabel.trim().slice(0, 40) : 'Text',
+ suggestions: Array.isArray(src.suggestions) ? src.suggestions.filter((s) => typeof s === 'string' && parseHeader(s).ok).slice(0, 24) : [],
+ demo: src.demo !== false,
+ reviewBelow, concurrency, rows, columns, errors,
+ }
+}
+
+/** The level a score answer lands on (nearest whole level). */
+export function levelOf(col, answer) {
+ return Math.max(0, Math.min(col.levels.length - 1, Math.round(Number(answer?.score ?? 0))))
+}
+
+/** Compare an answer with a truth label. Returns true / false, or null when there is no label. */
+export function judge(col, answer, truth) {
+ if (truth == null || !answer) return null
+ if (col.type === 'noul') return (answer.noul >= 0.5) === (truth === true || truth === 'yes' || truth === 1)
+ if (col.type === 'choice') return String(answer.choice).toLowerCase() === String(truth).toLowerCase()
+ const want = typeof truth === 'number' ? truth : col.levels.findIndex((l) => l.toLowerCase() === String(truth).toLowerCase())
+ if (want < 0) return null
+ return levelOf(col, answer) === want
+}
+
+/** How sure Jev is of the answer it shows: the probability of that answer. */
+export function confidenceOf(col, answer) {
+ if (!answer) return 0
+ if (col.type === 'noul') return Math.max(answer.noul, 1 - answer.noul)
+ return Math.max(0, Math.min(1, Number(answer.confidence ?? 0)))
+}
diff --git a/store/agents/jev-sheets/viewer/index.html b/store/agents/jev-sheets/viewer/index.html
new file mode 100644
index 000000000..e75b78960
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/index.html
@@ -0,0 +1,84 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Jev Sheets</title>
+ <link rel="icon" href="data:,">
+ <link rel="stylesheet" href="/base.css">
+ <link rel="stylesheet" href="/studio.css">
+ <script src="/jev-hud.js" defer></script>
+ <script type="module" src="/studio.js"></script>
+</head>
+<body>
+ <header id="topbar">
+ <div class="brand">
+ <span class="dot"></span>
+ <h1>Jev Sheets</h1>
+ <span class="sub" id="sheetTitle">loading the sheet</span>
+ <span class="pill warn" id="synthPill" title="Every name, message and truth label in this sheet is made up.">synthetic data</span>
+ </div>
+ <div class="stats big">
+ <div class="stat"><label>rows</label><span id="sRows">0</span></div>
+ <div class="stat"><label>Jev columns</label><span id="sCols">0</span></div>
+ <div class="stat"><label>cells filled</label><span><b id="sCells">0</b><i id="sCellsOf"></i></span></div>
+ <div class="stat" id="rateStat"><label>cells / s</label><span id="sRate">0</span></div>
+ <div class="stat"><label>cost so far</label><span id="sCost">$0</span></div>
+ <div class="stat" id="flagStat"><label>for review</label><span id="sFlag">0</span></div>
+ </div>
+ <div class="controls">
+ <button id="demoBtn" title="The ghost typist adds a column every 20 seconds or so while nobody is playing. Anything you do pauses it for a minute."><span class="gdot"></span>demo <b id="demoState">on</b></button>
+ <button id="resetBtn" title="Drop everything done in the pane and judge the sheet again from sheet.json">reset</button>
+ </div>
+ </header>
+ <div id="cfgError" class="cfg-error hidden"></div>
+ <main>
+ <section id="stage">
+ <div id="toolbar">
+ <div id="addBox" class="addbox">
+ <span class="plus">+</span>
+ <input id="addInput" type="text" autocomplete="off" spellcheck="false" maxlength="20000" placeholder="Add a column: type a question for every row, then press Enter">
+ <span id="ghostTag" class="demo-tag hidden">demo · ghost typist</span>
+ <kbd id="enterKey">Enter</kbd>
+ </div>
+ <button id="reviewOnlyBtn" title="Show only the rows with a cell under the review line">needs review only <b id="reviewOnlyN">0</b></button>
+ <div class="reviewbox" title="Cells where Jev's confidence is under this line get a ? flag">
+ <label for="reviewRange">review below <b id="reviewVal">0.65</b></label>
+ <div class="histwrap"><canvas id="hist"></canvas><input id="reviewRange" type="range" min="0" max="1" step="0.01" value="0.65"></div>
+ </div>
+ </div>
+ <div id="hint" class="hint"></div>
+ <div class="grid-wrap">
+ <div id="grid" class="grid">
+ <div id="ghead" class="ghead"></div>
+ <div id="gbody" class="gbody"></div>
+ </div>
+ <div id="empty" class="empty hidden"></div>
+ </div>
+ </section>
+ <aside id="rail">
+ <section class="panel" id="inspector">
+ <div class="panel-title">Cell inspector <span class="right" id="inspTag"></span></div>
+ <div id="inspBody" class="insp-empty">Click any cell to see what Jev was asked and its full answer.</div>
+ </section>
+ <section class="panel">
+ <div class="panel-title">How it works</div>
+ <div class="how">
+ A header is a <b>question</b>. Jev answers it for every row: one call per row, all columns at once, each answer with a probability.
+ <div class="grammar">
+ <button class="gex" data-ex="Urgent?"><code>Urgent?</code><span>ends with ? → yes / no</span></button>
+ <button class="gex" data-ex="Team: billing | tech | sales"><code>Team: billing | tech | sales</code><span>a | b → choice. Add meaning: <i>billing = invoices</i></span></button>
+ <button class="gex" data-ex="Anger: calm &lt; annoyed &lt; furious"><code>Anger: calm &lt; annoyed &lt; furious</code><span>low &lt; high → score, 2 to 10 levels</span></button>
+ <button class="gex" data-ex="Urgency"><code>Urgency</code><span>one word → score low &lt; medium &lt; high</span></button>
+ </div>
+ Cells fade when Jev is less sure. <b class="qmark">?</b> marks a cell under the review line. A <b class="redc">red corner</b> means the answer differs from the made-up truth label.
+ </div>
+ </section>
+ <section class="panel">
+ <div class="panel-title">Try a header <span class="right dim">click to add</span></div>
+ <div id="chips" class="chips"></div>
+ </section>
+ </aside>
+ </main>
+</body>
+</html>
diff --git a/store/agents/jev-sheets/viewer/jev-hud.js b/store/agents/jev-sheets/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-sheets/viewer/kit.mjs b/store/agents/jev-sheets/viewer/kit.mjs
new file mode 100644
index 000000000..f80d29b7d
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/kit.mjs
@@ -0,0 +1,112 @@
+// kit.mjs — the boring, security-relevant half of a Jev viewer, written once:
+// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
+// /control, plus an atomic verdict writer and a safe JSON config watcher.
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
+import { join, extname } from 'node:path'
+import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
+
+export const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+/** Deterministic PRNG so every run of a demo is reproducible. */
+export function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/**
+ * Serve a viewer.
+ * @param {object} o
+ * @param {string} o.here the viewer directory (static files live here)
+ * @param {number} o.port 0 = ephemeral
+ * @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
+ * @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
+ * @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ */
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+ const clients = new Set()
+ const allowed = new Set(files)
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ // Loopback only: a page on another origin (DNS rebinding) must not reach this server.
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ const path = url.pathname
+ try {
+ if (req.method === 'GET') {
+ const name = path === '/' ? 'index.html' : path.slice(1)
+ if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
+ if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (path === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
+ clients.add(res)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ }
+ if (req.method === 'POST' && path === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 65536) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const reply = control ? await control(String(j.cmd ?? ''), j) : null
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
+ res.writeHead(404); res.end('Not found')
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
+ }
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ clients,
+ /** Push a named SSE event (default 'state') to every connected pane. */
+ broadcast(obj, event = 'state') {
+ const line = `event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`
+ for (const c of clients) c.write(line)
+ },
+ async close() { for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+/** Atomic write of .harness/verdict.json (the harness reads this file; never edit it by hand). */
+export function writeVerdict(workspace, verdict) {
+ const dir = join(workspace, '.harness')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify({ spec: 1, ...verdict, updatedAt: new Date().toISOString() }))
+ renameSync(file + '.tmp', file)
+}
+
+/**
+ * Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
+ * good config and reports the parse error instead of crashing the demo.
+ * @returns {{ get(): object, error(): string|null, close(): void }}
+ */
+export function watchConfig(file, defaults, onChange) {
+ let cfg = { ...defaults }, err = null, timer = null
+ const load = () => {
+ try { cfg = { ...defaults, ...JSON.parse(readFileSync(file, 'utf8')) }; err = null }
+ catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
+ }
+ load()
+ let watcher = null
+ try {
+ watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ } catch { /* file may not exist yet; defaults stand */ }
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+}
diff --git a/store/agents/jev-sheets/viewer/mock.mjs b/store/agents/jev-sheets/viewer/mock.mjs
new file mode 100644
index 000000000..d8c77e762
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/mock.mjs
@@ -0,0 +1,308 @@
+// mock.mjs — the offline stand-in reader for Jev Sheets.
+//
+// Without a TYPESAFE_API_KEY the sheet still has to fill, so this file gives evaluate() a domain
+// reader. It sees exactly what live Jev would see: the row (as the state text) and the question
+// (the header wording, the option names and descriptions, the level names). It never sees truth
+// labels, row groups or anything else from the sheet.
+//
+// How it reads: a small lexicon maps the words of a question to cue words and phrases. Evidence is
+// how many cues the row text contains. One clear signal gives a confident answer. Mixed signals, or
+// no signal at all, give a flat distribution and a low confidence. So ambiguity in the text is the
+// only thing that lowers confidence. It is a stand-in for plumbing, not for Jev's judgement.
+import { hash01 } from '../toolchain/jev.mjs'
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+// Words too common in questions to count as evidence when they also show up in a row.
+const GENERIC = new Set('problem issue question customer user thing help need want other anything else general message request related row text person people someone something kind type best fit pick rate level scale mention mentions asking asks wants ask about contain contains'.split(' ').map(root))
+
+/** Crude word root, applied to both sides of every comparison so "charged" meets "charges". */
+export function root(w) {
+ for (let pass = 0; pass < 2; pass++) {
+ if (w.length > 4) {
+ const n = w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s|e|y)$/, '')
+ if (n === w || n.length < 3) break
+ w = n
+ } else if (w.length === 4 && /[sey]$/.test(w) && !w.endsWith('ss')) { w = w.slice(0, 3); break } else break
+ }
+ return w
+}
+
+const words = (text) => String(text).toLowerCase().replace(/['’]/g, '').split(/[^a-z0-9$%]+/).filter(Boolean)
+const needleRoots = (text) => [...new Set(words(text).filter((w) => w.length > 1 && !STOP.has(w)).map(root).filter((r) => !GENERIC.has(r)))]
+
+// ---------------------------------------------------------------------------
+// The lexicon. keys: words in a QUESTION that switch the concept on. mild / strong: cues in a ROW
+// (weight 1 / 2). anti: cues that argue the other way. Polar concepts have pos / neg ends instead.
+// Cues starting with "#" are text features: #bang2 (two or more "!"), #caps (shouted words),
+// #qmark (a question mark), #mid / #big (a head count of 20+ / 100+).
+// ---------------------------------------------------------------------------
+const list = (s) => s.split(',').map((x) => x.trim()).filter(Boolean)
+const cue = (c, w) => (c.startsWith('#') ? { key: c, feat: c, w, roots: [] }
+ : c.includes(' ') ? { key: c, phrase: ` ${words(c).join(' ')} `, w, roots: words(c).filter((x) => !STOP.has(x)).map(root) }
+ : { key: root(c), word: root(c), w, roots: [root(c)] })
+const concept = (id, o) => ({
+ id,
+ keys: new Set(list(o.keys).flatMap((k) => words(k)).map(root)),
+ cues: [...list(o.mild ?? '').map((c) => cue(c, 1)), ...list(o.strong ?? '').map((c) => cue(c, 2))],
+ anti: list(o.anti ?? '').map((c) => cue(c, 1)),
+ pos: list(o.pos ?? '').map((c) => cue(c, 1)),
+ neg: list(o.neg ?? '').map((c) => cue(c, 1)),
+ polar: !!o.pos,
+})
+
+const POSITIVE = 'thanks, thank, love, loving, great, awesome, amazing, excellent, happy, appreciate, fantastic, perfect, well done, helpful, impressed, brilliant, saved us, smooth, pleased, wonderful, kudos, delighted, best, flawless'
+const NEGATIVE = 'annoying, annoyed, frustrating, frustrated, disappointed, disappointing, unhappy, not happy, fed up, unacceptable, outrageous, ridiculous, worst, terrible, awful, useless, broken, hate, poor, worse, furious, sick of, let down, garbage, pathetic, nightmare, #bang2'
+
+const LEX = [
+ concept('urgency', {
+ keys: 'urgent, urgency, asap, priority, critical, emergency, rush, immediately, deadline, time sensitive, pressing, hurry, today',
+ mild: 'deadline, end of day, by tomorrow, by friday, by monday, this week, blocked, hurry, quickly, time sensitive, cant work, cannot work, as soon as, tonight, within the hour, before the launch, clock is ticking, today',
+ strong: 'urgent, urgently, asap, immediately, emergency, critical, right now, right away, outage, is down, are down, went down, losing money, losing data, losing customers, every minute, every hour, production',
+ anti: 'no rush, not urgent, no hurry, whenever, when you get a chance, low priority, next quarter, next month, next year, sometime, at some point, just curious, no deadline, eventually, take your time, nothing pressing',
+ }),
+ concept('anger', {
+ keys: 'anger, angry, furious, upset, frustration, frustrated, annoyed, mad, rage, irritated, temper, hostile, livid',
+ mild: 'annoying, annoyed, frustrating, frustrated, disappointed, disappointing, not happy, unhappy, third time, second time, fed up, irritating, yet again, getting old, let down, not impressed, tiresome, not good enough',
+ strong: 'furious, unacceptable, outrageous, ridiculous, worst, disgrace, scam, rip off, ripoff, incompetent, useless, sick of, livid, how dare, pathetic, garbage, terrible, awful, nightmare, #bang3, #caps',
+ anti: 'appreciate, no worries, cheers, love, great work, thank you so much, thanks so much, no complaints, all good',
+ }),
+ concept('billing', {
+ keys: 'billing, bill, payment, payments, invoice, invoices, charge, charges, finance, accounting, accounts',
+ mild: 'invoice, charged, charge, billing, billed, bill, payment, card, receipt, refund, charged twice, double charged, vat, tax, renewal, credit card, overcharged, debit, bank statement, billing cycle, payment failed, declined, prorated, purchase order number',
+ }),
+ concept('tech', {
+ keys: 'tech, technical, bug, bugs, engineering, outage, outages, error, errors, defect, incident, crash, failure, failures',
+ mild: 'bug, error, errors, crash, crashes, crashing, crashed, not working, doesnt work, stopped working, sync, syncing, upload, uploads, uploading, timeout, times out, outage, is down, went down, error code, freeze, freezes, frozen, glitch, reinstall, reinstalled, latest version, update broke, api, corrupted, stack trace, logs, desktop app, mobile app',
+ }),
+ concept('sales', {
+ keys: 'sales, sale, pricing, purchase, buy, buying, deal, lead, prospect, commercial, upgrade, upgrades, upsell, expansion, quote, quotes, demo, demos',
+ mild: 'pricing, price, quote, demo, trial, upgrade, upgrading, seats, licenses, licences, enterprise plan, team plan, discount, purchase, buy, buying, procurement, volume, sales team, talk to sales, how much, per user, evaluating, proof of concept, rollout, annual plan, reseller, partnership, nonprofit',
+ }),
+ concept('refund', {
+ keys: 'refund, refunds, reimburse, reimbursement, money back, chargeback',
+ mild: 'reimburse, reimbursement, credit back, reverse the charge',
+ strong: 'refund, refunded, money back, chargeback, charge back, return my money, want my money',
+ }),
+ concept('churn', {
+ keys: 'churn, cancel, cancellation, leave, leaving, retention, attrition, quit, lose, losing',
+ mild: 'cancel, cancelling, canceling, cancellation, alternatives, reconsider, not renew, not renewing, downgrade, downgrading, thinking of leaving, other options, might switch, considering switching, shopping around, last chance',
+ strong: 'cancel my, cancel our, cancel immediately, close my account, close our account, delete my account, switching to, moving to, done with, last straw, we are leaving, taking our business',
+ anti: 'renewed, happy customer, love the product, more seats, add seats, upgrade, upgrading, signing up, long term',
+ }),
+ concept('sentiment', { keys: 'sentiment, mood, satisfaction, satisfied, happiness, feeling, csat, nps, attitude, tone', pos: POSITIVE, neg: NEGATIVE }),
+ concept('polite', { keys: 'polite, politeness, courtesy, courteous, rude, rudeness, respectful, civility, manners', pos: 'please, thanks, thank, kindly, appreciate, best regards, kind regards, sorry, cheers, grateful', neg: 'unacceptable, ridiculous, useless, incompetent, pathetic, garbage, how dare, sick of, #bang3, #caps' }),
+ concept('positive', { keys: 'positive, happy, praise, compliment, delighted, pleased, good, promoter, thanks, thank, kudos, testimonial, fan', mild: POSITIVE }),
+ concept('negative', { keys: 'negative, unhappy, complaint, complaints, complain, complaining, dissatisfied, bad, detractor, critical feedback', mild: NEGATIVE }),
+ concept('spam', {
+ keys: 'spam, junk, phishing, unsolicited, promotion, promotional, marketing, outreach, solicitation, cold',
+ mild: 'seo, guest post, backlinks, link building, crypto, bitcoin, lottery, click here, limited offer, act now, unsubscribe, dear sir, investment opportunity, rank your website, web design services, lead generation, we offer, boost your, 10x your',
+ }),
+ concept('feature', {
+ keys: 'feature, features, idea, ideas, suggestion, suggestions, enhancement, roadmap, wishlist',
+ mild: 'feature, would be great, would love, wish, suggestion, suggest, could you add, please add, any plans, roadmap, feature request, idea, it would help, support for, dark mode, integration, integrate, nice to have',
+ }),
+ concept('security', {
+ keys: 'security, secure, privacy, breach, vulnerability, vulnerabilities, hacked',
+ mild: 'security, breach, hacked, compromised, unauthorized, unauthorised, suspicious, phishing, password, 2fa, two factor, sso, encryption, encrypted, vulnerability, pen test, soc 2, soc2, leaked, unknown device, login from',
+ }),
+ concept('legal', {
+ keys: 'legal, compliance, contract, contracts, gdpr, regulatory, lawyer, law, dpa',
+ mild: 'legal, lawyer, lawyers, attorney, gdpr, dpa, data processing, compliance, terms of service, contract, nda, lawsuit, sue, liability, regulator, audit, hipaa, msa',
+ }),
+ concept('size', {
+ keys: 'vip, enterprise, size, big, large, value, valuable, important, tier, revenue, whale, potential',
+ mild: 'team, seats, company, department, our users, employees, across the, organisation, organization, offices, #mid',
+ strong: 'enterprise, hundreds, thousand, thousands, company wide, all offices, global, annual contract, procurement, #big',
+ anti: 'just me, personal, hobby, student, free plan, solo, freelancer',
+ }),
+ concept('question', {
+ keys: 'question, questions, inquiry, enquiry, howto, how to, curious',
+ mild: 'how do i, how can, is it possible, can you, could you, where do, what is, wondering, does it, is there, #qmark',
+ }),
+ concept('escalate', {
+ keys: 'manager, supervisor, escalate, escalation, human, call, phone, callback, boss',
+ mild: 'manager, supervisor, escalate, escalation, speak to, talk to someone, call me, phone call, a real person, a human, someone senior, your boss, ceo, in charge',
+ }),
+ concept('competitor', {
+ keys: 'competitor, competitors, competition, alternative, alternatives, rival, rivals, switch, switching',
+ mild: 'competitor, competitors, switching to, switch to, moving to, alternative, alternatives, other vendors, another provider, other providers, compared to, cheaper elsewhere, other options, shopping around',
+ }),
+ concept('access', {
+ keys: 'login, account, access, password, authentication, onboarding, signin, sign in',
+ mild: 'login, log in, sign in, password, reset link, locked out, cant access, cannot access, two factor, 2fa, sso, verification email, invite, permissions, admin',
+ }),
+ concept('files', {
+ keys: 'sync, syncing, backup, backups, upload, storage, files, file, restore',
+ mild: 'sync, syncing, synced, upload, uploads, download, backup, backups, restore, version history, folder, folders, files, storage, quota, shared drive, conflict copies',
+ }),
+ concept('severity', {
+ keys: 'severity, impact, severe, serious, damage, blast radius',
+ mild: 'slow, some users, intermittent, sometimes, several users, error, crash, not working',
+ strong: 'data loss, lost files, all users, everyone, whole team, entire company, outage, is down, corrupted, cannot work, cant work, production, deleted, gone',
+ anti: 'workaround, minor, cosmetic, typo, small thing',
+ }),
+]
+
+const HIGH_WORDS = new Set('high severe critical extreme strong very hot max maximum most furious huge'.split(' '))
+const LOW_WORDS = new Set('low none mild calm cold min minimum least minor tiny'.split(' '))
+
+// ---------------------------------------------------------------------------
+// Reading a row
+// ---------------------------------------------------------------------------
+function readRow(stateText) {
+ let text = String(stateText ?? '')
+ try {
+ const o = JSON.parse(text)
+ if (o && typeof o === 'object') text = Object.values(o).filter((v) => typeof v === 'string' || typeof v === 'number').join(' \n ')
+ } catch { /* plain text state */ }
+ const toks = words(text)
+ let head = 0
+ for (const m of text.matchAll(/(\d{2,6})\s+(seats|users|people|employees|licen[cs]es|staff|engineers|teammates|accounts)/gi)) head = Math.max(head, Number(m[1]))
+ return {
+ text,
+ roots: new Set(toks.filter((w) => !STOP.has(w)).map(root)),
+ norm: ` ${toks.join(' ')} `,
+ bangs: (text.match(/!/g) || []).length,
+ caps: (text.match(/\b[A-Z]{4,}\b/g) || []).length,
+ qmarks: (text.match(/\?/g) || []).length,
+ head,
+ }
+}
+
+function hit(T, c) {
+ if (c.feat) {
+ if (c.feat === '#bang2') return T.bangs >= 2
+ if (c.feat === '#bang3') return T.bangs >= 3
+ if (c.feat === '#caps') return T.caps >= 2
+ if (c.feat === '#qmark') return T.qmarks >= 1
+ if (c.feat === '#mid') return T.head >= 20 && T.head < 100
+ if (c.feat === '#big') return T.head >= 100
+ return false
+ }
+ return c.phrase ? T.norm.includes(c.phrase) : T.roots.has(c.word)
+}
+
+/** Evidence in row T for a piece of question wording (a header, an option + description, a level). */
+function evidence(T, wording) {
+ const need = needleRoots(wording)
+ const active = LEX.filter((c) => need.some((r) => c.keys.has(r)))
+ const seen = new Set(), blocked = new Set()
+ let w = 0, anti = 0, pos = 0, neg = 0, polar = false
+ // "not urgent" argues against urgency, and its word "urgent" must not also count for it.
+ for (const c of active) for (const q of c.anti) if (hit(T, q)) { anti += q.w; for (const r of q.roots) blocked.add(r) }
+ for (const c of active) {
+ if (c.polar) {
+ polar = true
+ for (const q of c.pos) if (hit(T, q)) pos += q.w
+ for (const q of c.neg) if (hit(T, q)) neg += q.w
+ continue
+ }
+ for (const q of c.cues) if (!seen.has(q.key) && !(q.word && blocked.has(q.word)) && hit(T, q)) { seen.add(q.key); w += q.w }
+ }
+ // Plain wording overlap: the row uses the same word as the question or the option.
+ for (const r of need) if (!seen.has(r) && !blocked.has(r) && T.roots.has(r)) { seen.add(r); w += 1 }
+ return { w, anti, pos, neg, known: active.length > 0, polar }
+}
+
+const clamp = (x, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, x))
+const sat = (e, k = 1.6) => 1 - Math.exp(-Math.max(0, e) / k)
+
+function softmax(raw) {
+ const m = Math.max(...raw)
+ const ex = raw.map((r) => Math.exp(r - m))
+ const s = ex.reduce((a, b) => a + b, 0)
+ return ex.map((e) => e / s)
+}
+
+/** Never one-hot: keep a little mass on every option, like a calibrated model does. */
+function soften(probs, floor = 0.03) {
+ const n = probs.length
+ return probs.map((p) => p * (1 - floor) + floor / n)
+}
+
+function gaussian(n, pos, sigma) {
+ const raw = Array.from({ length: n }, (_, i) => -((i - pos) ** 2) / (2 * sigma * sigma))
+ return soften(softmax(raw))
+}
+
+const OTHER = /^(other|others|none|neither|general|misc|unknown|unclear|n\/a|something else)$/i
+
+/**
+ * The domain reader handed to evaluate() as `mock`.
+ * @param {(qid:string)=>object|undefined} lookup column definition for a question id
+ */
+export function sheetMock(lookup) {
+ return function mock(stateText, qid, q, salt) {
+ const col = lookup(qid)
+ if (!col) return null
+ const T = readRow(stateText)
+ const jit = (key, amp) => (hash01(`${qid}::${key}::${T.text.slice(0, 96)}::${T.text.length}`, salt) - 0.5) * amp
+
+ if (col.type === 'noul') {
+ const ev = evidence(T, col.header)
+ let logit
+ if (ev.polar && !ev.w) logit = (ev.pos - ev.neg) * 1.1
+ else if (!ev.known && !ev.w) logit = -0.75 // the stand-in does not know this question: lean no, unsure
+ else logit = -1.7 + 4.6 * sat(ev.w) - 1.9 * sat(ev.anti, 1)
+ const p = clamp(1 / (1 + Math.exp(-(logit + jit('noul', 0.5)))), 0.03, 0.97)
+ return { type: 'noul', noul: p }
+ }
+
+ if (col.type === 'choice') {
+ const evs = col.options.map((opt) => evidence(T, `${opt.replace(/[_-]+/g, ' ')} ${col.descriptions?.[opt] ?? ''}`))
+ const strength = evs.map((e) => Math.max(0, e.w + e.pos - 0.8 * (e.anti + e.neg)))
+ const best = Math.max(...strength)
+ const raw = col.options.map((opt, i) => {
+ const base = OTHER.test(opt) && best === 0 ? 1.2 : strength[i]
+ return 3.2 * sat(base) + jit(`o${i}`, 0.36)
+ })
+ const probs = soften(softmax(raw))
+ const bi = probs.indexOf(Math.max(...probs))
+ const probabilities = {}
+ col.options.forEach((opt, i) => (probabilities[opt] = probs[i]))
+ return { type: 'choice', choice: col.options[bi], confidence: probs[bi], probabilities }
+ }
+
+ if (col.type === 'score') {
+ const n = col.levels.length
+ const first = words(col.levels[0]), last = words(col.levels[n - 1])
+ const nameEv = evidence(T, col.name)
+ let reversed = first.some((w) => HIGH_WORDS.has(w)) || last.some((w) => LOW_WORDS.has(w))
+ let pos, sigma = 0.45
+
+ if (nameEv.polar) {
+ // A two-ended scale (sentiment, politeness): cues pull to either end, the middle is "neither".
+ const mid = (n - 1) / 2
+ if (needleRoots(col.levels[0]).some((r) => LEX.find((c) => c.id === 'positive').keys.has(r))) reversed = true
+ pos = mid + clamp((nameEv.pos - nameEv.neg) / 3, -1, 1) * mid
+ if (nameEv.pos && nameEv.neg) sigma = 0.85
+ } else if (nameEv.known) {
+ // A one-ended scale (urgency, anger, churn risk): more and stronger cues push it higher.
+ const eff = Math.max(0, nameEv.w - 1.2 * nameEv.anti)
+ pos = Math.min(1, eff / 4) ** 0.85 * (n - 1)
+ if (nameEv.w && nameEv.anti) sigma = 0.85
+ } else {
+ // The name means nothing to the stand-in. Try the level names themselves.
+ const evs = col.levels.map((l) => evidence(T, l))
+ const strength = evs.map((e) => Math.max(0, e.w - 0.8 * e.anti))
+ if (Math.max(...strength) > 0) {
+ const probs = soften(softmax(strength.map((s, i) => 3.2 * sat(s) + jit(`l${i}`, 0.3))))
+ return scoreAnswer(col, probs)
+ }
+ pos = hash01(`${qid}::${T.text.slice(0, 120)}`, salt) * (n - 1)
+ sigma = 1.15 // no idea: a flat, low-confidence guess
+ }
+ pos = clamp(pos + jit('pos', 0.2), 0, n - 1)
+ if (reversed) pos = n - 1 - pos
+ return scoreAnswer(col, gaussian(n, pos, sigma))
+ }
+ return null
+ }
+}
+
+function scoreAnswer(col, probs) {
+ const probabilities = {}
+ probs.forEach((p, i) => (probabilities[String(i)] = p))
+ const legend = Object.fromEntries(col.levels.map((l, i) => [String(i), l]))
+ return { type: 'score', score: probs.reduce((a, p, i) => a + p * i, 0), confidence: Math.max(...probs), legend, probabilities }
+}
diff --git a/store/agents/jev-sheets/viewer/source.mjs b/store/agents/jev-sheets/viewer/source.mjs
new file mode 100644
index 000000000..8d2b04668
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/source.mjs
@@ -0,0 +1,120 @@
+// source.mjs — bring your own rows. sheet.json may name a file in the workspace:
+//
+// { "source": "leads.csv", "textColumn": "message", ... }
+//
+// A .csv or .tsv file (header row first), a .jsonl file (one JSON object or string per line) or a
+// .json file (a list) becomes the sheet's rows. One column is the row's text; the other columns
+// ride along as plain fields that Jev also reads. The file must live inside the workspace.
+import { readFileSync, statSync } from 'node:fs'
+import { resolve, sep, extname } from 'node:path'
+
+export const SOURCE_LIMITS = { bytes: 8 * 1024 * 1024, field: 300, fields: 24 }
+const TEXT_NAMES = ['text', 'message', 'body', 'content', 'description', 'comment', 'note', 'notes', 'review', 'subject', 'title', 'summary']
+
+/** A small RFC 4180 reader: quoted fields, doubled quotes, CRLF, and a guessed delimiter. */
+export function parseDelimited(src, delimiter) {
+ const firstLine = src.slice(0, src.indexOf('\n') < 0 ? src.length : src.indexOf('\n'))
+ const d = delimiter ?? [',', '\t', ';', '|'].map((c) => [c, firstLine.split(c).length]).sort((a, b) => b[1] - a[1])[0][0]
+ const rows = []
+ let row = [], field = '', quoted = false
+ for (let i = 0; i < src.length; i++) {
+ const c = src[i]
+ if (quoted) {
+ if (c === '"') { if (src[i + 1] === '"') { field += '"'; i++ } else quoted = false } else field += c
+ } else if (c === '"' && field === '') quoted = true
+ else if (c === d) { row.push(field); field = '' }
+ else if (c === '\n' || c === '\r') {
+ if (c === '\r' && src[i + 1] === '\n') i++
+ row.push(field); field = ''
+ if (row.length > 1 || row[0] !== '') rows.push(row)
+ row = []
+ } else field += c
+ }
+ if (field !== '' || row.length) { row.push(field); rows.push(row) }
+ return rows
+}
+
+function pickTextColumn(headers, records, wanted) {
+ const lower = headers.map((h) => h.toLowerCase())
+ if (wanted) { const i = lower.indexOf(String(wanted).toLowerCase()); if (i >= 0) return { index: i } ; return { index: -1, error: `textColumn "${wanted}" is not a column of the file (columns: ${headers.join(', ')})` } }
+ for (const name of TEXT_NAMES) { const i = lower.indexOf(name); if (i >= 0) return { index: i } }
+ // Otherwise the column whose values are longest on average is the prose.
+ let best = 0, bestLen = -1
+ headers.forEach((_, i) => { const avg = records.slice(0, 200).reduce((a, r) => a + String(r[i] ?? '').length, 0) / Math.max(1, Math.min(200, records.length)); if (avg > bestLen) { bestLen = avg; best = i } })
+ return { index: best }
+}
+
+const tidyKey = (k) => String(k).trim().replace(/\s+/g, '_').replace(/[^\w.-]/g, '').slice(0, 40)
+function tidyValue(v) {
+ if (typeof v === 'number' || typeof v === 'boolean') return v
+ const s = String(v ?? '').trim()
+ if (s === '') return undefined
+ if (/^-?\d+(\.\d+)?$/.test(s) && s.length < 16) return Number(s)
+ return s.slice(0, SOURCE_LIMITS.field)
+}
+
+/**
+ * Load rows from a workspace file. Never throws: returns { rows, error, file, info }.
+ * @param {string} workspace absolute workspace path
+ * @param {string} name the file, relative to the workspace
+ */
+export function loadSource(workspace, name, { textColumn, limit = 2000 } = {}) {
+ const root = resolve(workspace)
+ const file = resolve(root, String(name))
+ const fail = (error) => ({ rows: [], error, file: null, info: null })
+ if (file !== root && !file.startsWith(root + sep)) return fail(`source "${name}" must be a file inside the workspace`)
+ if (file.split(sep).includes('.harness')) return fail('source must not be inside .harness')
+ let raw
+ try {
+ if (statSync(file).size > SOURCE_LIMITS.bytes) return fail(`source "${name}" is over ${SOURCE_LIMITS.bytes / 1024 / 1024} MB`)
+ raw = readFileSync(file, 'utf8').replace(/^/, '')
+ } catch (e) { return fail(`source "${name}" cannot be read: ${e.code ?? e.message}`) }
+
+ const ext = extname(file).toLowerCase()
+ let records // list of { text, ...fields }
+ let textName = 'text'
+ try {
+ if (ext === '.csv' || ext === '.tsv' || ext === '.txt') {
+ const table = parseDelimited(raw, ext === '.tsv' ? '\t' : undefined)
+ if (table.length < 2) return fail(`source "${name}" needs a header row and at least one data row`)
+ const headers = table[0].map((h, i) => String(h).trim() || `column_${i + 1}`)
+ const body = table.slice(1)
+ const pick = pickTextColumn(headers, body, textColumn)
+ if (pick.error) return fail(pick.error)
+ textName = headers[pick.index]
+ records = body.map((cells) => {
+ const rec = { text: String(cells[pick.index] ?? '').trim() }
+ headers.forEach((h, i) => { if (i !== pick.index && Object.keys(rec).length <= SOURCE_LIMITS.fields) { const v = tidyValue(cells[i]); if (v !== undefined) rec[tidyKey(h) || `column_${i + 1}`] = v } })
+ return rec
+ })
+ } else if (ext === '.jsonl' || ext === '.ndjson' || ext === '.json') {
+ const list = ext === '.json' ? JSON.parse(raw) : raw.split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l))
+ if (!Array.isArray(list)) return fail(`source "${name}" must hold a list`)
+ const objs = list.filter((x) => x && typeof x === 'object')
+ const keys = [...new Set(objs.slice(0, 200).flatMap((o) => Object.keys(o)))]
+ const pick = keys.length ? pickTextColumn(keys, objs.map((o) => keys.map((k) => (typeof o[k] === 'string' ? o[k] : ''))), textColumn) : { index: -1 }
+ if (pick.error) return fail(pick.error)
+ textName = keys[pick.index] ?? 'text'
+ records = list.map((item) => {
+ if (typeof item === 'string') return { text: item.trim() }
+ if (!item || typeof item !== 'object') return { text: '' }
+ const rec = { text: String(item[textName] ?? '').trim() }
+ for (const [k, v] of Object.entries(item)) if (k !== textName && ['string', 'number', 'boolean'].includes(typeof v) && Object.keys(rec).length <= SOURCE_LIMITS.fields) { const t = tidyValue(v); if (t !== undefined) rec[tidyKey(k)] = t }
+ return rec
+ })
+ } else return fail(`source "${name}" must be a .csv, .tsv, .jsonl or .json file`)
+ } catch (e) { return fail(`source "${name}" could not be parsed: ${e.message}`) }
+
+ const total = records.length
+ const rows = []
+ for (const rec of records) {
+ if (!rec.text) continue
+ // `id`, `truth` and `group` mean something to the sheet; a data column with that name is renamed.
+ const row = { text: rec.text }
+ for (const [k, v] of Object.entries(rec)) if (k !== 'text') row[['id', 'truth', 'group'].includes(k) ? `${k}_` : k] = v
+ rows.push(row)
+ if (rows.length >= limit) break
+ }
+ if (!rows.length) return fail(`source "${name}" has no rows with text in column "${textName}"`)
+ return { rows, error: null, file, info: { name: String(name), textColumn: textName, total, used: rows.length } }
+}
diff --git a/store/agents/jev-sheets/viewer/studio.css b/store/agents/jev-sheets/viewer/studio.css
new file mode 100644
index 000000000..37ca85e8f
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/studio.css
@@ -0,0 +1,211 @@
+/* studio.css — Jev Sheets. Loaded after base.css. */
+:root {
+ --accent: #fbbf24; --accent2: #b45309;
+ --rowh: 46px; --headh: 52px; --numw: 44px; --textw: 420px; --colw: 142px;
+ --cell-line: #1b1f2c;
+}
+
+/* ---- top bar ------------------------------------------------------------------------------ */
+#topbar { gap: 18px; padding: 9px 16px; }
+.brand .sub { max-width: 210px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.stats.big { gap: 22px; flex-wrap: nowrap; }
+.stats.big .stat { min-width: 62px; }
+.stats.big .stat span { font-size: 21px; line-height: 1.15; letter-spacing: -.3px; white-space: nowrap; }
+.stats.big .stat span b { font-weight: 700; }
+.stats.big .stat span i { font-style: normal; font-size: 12px; color: var(--faint); font-weight: 600; margin-left: 2px; }
+#rateStat span { color: var(--dim); transition: color .4s, text-shadow .4s; }
+#rateStat.hot span { color: var(--accent); text-shadow: 0 0 18px color-mix(in srgb, var(--accent) 70%, transparent); }
+#flagStat.some span { color: var(--accent); }
+.controls { gap: 8px; }
+#demoBtn { min-width: 132px; justify-content: center; font-variant-numeric: tabular-nums; }
+#demoBtn { display: inline-flex; align-items: center; gap: 7px; }
+#demoBtn .gdot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); }
+#demoBtn.on .gdot { background: var(--accent); box-shadow: 0 0 10px var(--accent); animation: dot 1.6s ease-in-out infinite; }
+#demoBtn.on { box-shadow: none; color: var(--ink); }
+#demoBtn.on b { color: var(--accent); }
+#demoBtn.resting .gdot { animation: none; opacity: .5; }
+
+#cfgError { margin: 10px 14px 0; }
+
+/* ---- stage -------------------------------------------------------------------------------- */
+#stage { overflow: hidden; gap: 0; padding: 12px 14px 12px; }
+#toolbar { display: flex; align-items: center; gap: 12px; flex: none; }
+.addbox {
+ flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; height: 42px; padding: 0 12px;
+ background: #0b0d14; border: 1px solid var(--line2); border-radius: 11px; transition: border-color .2s, box-shadow .2s;
+}
+.addbox:focus-within { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 20%, transparent); }
+.addbox.ghosting { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 16%, transparent), 0 0 34px color-mix(in srgb, var(--accent) 16%, transparent); }
+.addbox.bad { border-color: var(--bad); animation: shake .3s; }
+@keyframes shake { 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } }
+.addbox .plus { color: var(--accent); font-size: 20px; font-weight: 700; line-height: 1; flex: none; }
+.addbox input { flex: 1; min-width: 0; border: none !important; background: transparent !important; box-shadow: none !important; padding: 0; font-size: 14px; height: 100%; color: var(--ink); }
+.addbox input::placeholder { color: var(--faint); }
+.addbox kbd { flex: none; transition: all .12s; }
+.addbox kbd.pressed { color: #1a1204; background: var(--accent); border-color: var(--accent); transform: translateY(1px); box-shadow: 0 0 16px var(--accent); }
+.demo-tag {
+ flex: none; font-size: 9.5px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; color: var(--accent);
+ border: 1px dashed color-mix(in srgb, var(--accent) 60%, transparent); border-radius: 999px; padding: 2px 8px; white-space: nowrap;
+ background: color-mix(in srgb, var(--accent) 8%, transparent);
+}
+#reviewOnlyBtn { flex: none; height: 42px; border-radius: 11px; white-space: nowrap; }
+#reviewOnlyBtn b { display: inline-block; min-width: 18px; margin-left: 4px; padding: 0 5px; border-radius: 999px; background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); font-variant-numeric: tabular-nums; }
+.reviewbox { flex: none; width: 196px; height: 42px; padding: 3px 10px 0; border: 1px solid var(--line2); border-radius: 11px; background: #0b0d14; display: flex; flex-direction: column; }
+.reviewbox label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.1px; color: var(--dim); display: flex; justify-content: space-between; }
+.reviewbox label b { color: var(--accent); font-size: 11px; font-variant-numeric: tabular-nums; letter-spacing: 0; }
+.histwrap { position: relative; flex: 1; min-height: 0; }
+.histwrap canvas { position: absolute; left: 0; right: 0; top: 0; width: 100%; height: 18px; display: block; pointer-events: none; }
+.histwrap input[type=range] { position: absolute; left: -7px; right: -7px; bottom: -1px; width: calc(100% + 14px); margin: 0; height: 24px; background: transparent; opacity: .95; cursor: ew-resize; -webkit-appearance: none; appearance: none; }
+.histwrap input[type=range]::-webkit-slider-runnable-track { height: 2px; background: var(--line2); border-radius: 1px; margin-top: 16px; }
+.histwrap input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; border-radius: 50%; background: var(--accent); border: 2px solid #1a1204; margin-top: -6px; box-shadow: 0 0 10px color-mix(in srgb, var(--accent) 70%, transparent); }
+
+.hint { flex: none; height: 24px; line-height: 24px; padding: 0 4px; font-size: 11.5px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.hint b { color: var(--dim); font-weight: 600; }
+.hint.ok { color: var(--dim); }
+.hint.ok b { color: var(--accent); margin: 0 10px 0 4px; }
+.hint.ok em { font-style: normal; color: var(--faint); margin-left: 12px; }
+::-webkit-scrollbar-corner { background: transparent; }
+.hint.err { color: var(--bad); }
+
+/* ---- the grid ----------------------------------------------------------------------------- */
+.grid-wrap { position: relative; flex: 1; min-height: 0; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #090a10; box-shadow: 0 20px 60px rgba(0,0,0,.35); }
+.grid { position: absolute; inset: 0; overflow: auto; scroll-behavior: auto; overscroll-behavior: contain; outline: none; }
+.ghead { position: sticky; top: 0; z-index: 20; display: flex; height: var(--headh); min-width: 100%; background: #11131c; border-bottom: 1px solid var(--line2); }
+.gbody { position: relative; min-width: 100%; }
+
+.hc { flex: none; height: 100%; display: flex; flex-direction: column; justify-content: center; padding: 0 10px; border-right: 1px solid var(--cell-line); background: #11131c; min-width: 0; }
+.hc.num { width: var(--numw); position: sticky; left: 0; z-index: 3; align-items: center; color: var(--faint); font-size: 11px; padding: 0; }
+.hc.text { width: var(--textw); position: sticky; left: var(--numw); z-index: 3; transition: width .3s ease; }
+.hc.text .h-name { font-weight: 700; font-size: 12.5px; }
+.hc.text .h-sub { color: var(--faint); font-size: 10px; }
+.hc.jev { width: var(--colw); max-width: var(--colw); cursor: pointer; position: relative; overflow: hidden; transition: background .15s; }
+.hc.jev:hover { background: #171a27; }
+.hc.jev.sorted { background: linear-gradient(180deg, color-mix(in srgb, var(--accent) 13%, #11131c), #11131c); box-shadow: inset 0 2px 0 var(--accent); }
+.hc.jev.demo { background-image: repeating-linear-gradient(135deg, transparent 0 7px, color-mix(in srgb, var(--accent) 5%, transparent) 7px 14px); }
+.hc.add { flex: 1 1 0; min-width: 0; overflow: hidden; white-space: nowrap; flex-direction: row; align-items: center; justify-content: flex-start; gap: 8px; padding: 0 14px; border-right: none; color: var(--faint); font-size: 11.5px; cursor: pointer; transition: color .15s; }
+.hc.add span { color: var(--accent); font-size: 17px; font-weight: 700; line-height: 1; }
+.hc.add:hover { color: var(--ink); }
+.h-top { display: flex; align-items: center; gap: 4px; min-width: 0; }
+.h-top .h-name { flex: 1; }
+.h-name { min-width: 0; font-weight: 700; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.h-sort { flex: none; color: var(--accent); font-size: 10px; width: 10px; text-align: center; }
+.h-x { flex: none; width: 18px; height: 18px; padding: 0; line-height: 15px; font-size: 14px; border-radius: 5px; border-color: transparent; background: transparent; color: var(--faint); }
+.h-x:hover { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); background: rgba(225,29,72,.1); }
+.h-sub { display: flex; align-items: center; gap: 5px; margin-top: 3px; font-size: 10px; color: var(--dim); white-space: nowrap; min-width: 0; font-variant-numeric: tabular-nums; }
+.tag { font-size: 8.5px; font-weight: 700; letter-spacing: .8px; text-transform: uppercase; padding: 0 5px; border-radius: 4px; border: 1px solid var(--line2); color: var(--dim); line-height: 14px; }
+.tag.demo { color: var(--accent); border-style: dashed; border-color: color-mix(in srgb, var(--accent) 55%, transparent); }
+.tag.mixed { color: var(--cyan); border-color: color-mix(in srgb, var(--cyan) 40%, transparent); }
+.tag.edited { color: var(--blue); border-color: color-mix(in srgb, var(--blue) 40%, transparent); }
+.h-acc { color: var(--ok); font-weight: 700; }
+.h-acc.mid { color: var(--accent); }
+.h-acc.low { color: var(--bad); }
+.h-flag { color: var(--accent); }
+.h-fill { position: absolute; left: 0; bottom: 0; height: 2px; background: var(--accent); box-shadow: 0 0 8px var(--accent); transition: width .12s linear, opacity .5s .3s; }
+.h-fill.done { opacity: 0; }
+
+.row { position: absolute; left: 0; top: 0; height: var(--rowh); min-width: 100%; display: flex; --rowbg: #0b0c13; background: var(--rowbg); transition: transform .55s cubic-bezier(.22,.8,.22,1), opacity .3s; will-change: transform; }
+.row.odd { --rowbg: #0e1018; }
+.row:hover { --rowbg: #141724; }
+.row.gone { opacity: 0; }
+.row.editing { z-index: 8; }
+.row.moving { z-index: 2; box-shadow: 0 6px 18px rgba(0,0,0,.45); }
+.cell { flex: none; height: 100%; border-right: 1px solid var(--cell-line); border-bottom: 1px solid var(--cell-line); min-width: 0; }
+.c-num { width: var(--numw); position: sticky; left: 0; z-index: 2; background: var(--rowbg); display: flex; align-items: center; justify-content: center; color: var(--faint); font-size: 11px; font-variant-numeric: tabular-nums; }
+.c-text { width: var(--textw); position: sticky; left: var(--numw); z-index: 2; background: var(--rowbg); padding: 5px 10px; cursor: text; transition: width .3s ease; }
+.grid.xscrolled .c-text, .grid.xscrolled .hc.text { box-shadow: 8px 0 14px -6px rgba(0,0,0,.7); }
+.c-text .msg { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; font: 12.5px/1.38 var(--sans); color: #cfd4e4; }
+.c-text .who { color: var(--accent); font: 600 11px var(--mono); margin-right: 6px; opacity: .85; }
+.c-text .tag { margin-right: 5px; vertical-align: 1px; }
+.editor { position: absolute; left: 2px; top: 2px; width: calc(100% - 4px); height: 104px; z-index: 9; resize: none; font: 12.5px/1.4 var(--sans) !important; border-color: var(--accent) !important; box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent), 0 14px 40px rgba(0,0,0,.7) !important; background: #0d0f17 !important; }
+
+.c-jev { width: var(--colw); max-width: var(--colw); padding: 6px 9px 0; cursor: pointer; position: relative; overflow: hidden; --tone: var(--accent); --conf: 1;
+ background: color-mix(in srgb, var(--tone) calc(var(--conf) * var(--conf) * 13%), transparent); transition: background .25s, box-shadow .15s; }
+.c-jev:hover { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--tone) 55%, transparent); }
+.c-jev.sel { box-shadow: inset 0 0 0 2px var(--accent), inset 0 0 18px color-mix(in srgb, var(--accent) 22%, transparent); }
+.c-jev.sel.bydemo { box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--accent) 60%, transparent); }
+.ci { display: flex; flex-direction: column; gap: 5px; transform-origin: 50% 0; }
+.c-jev.flag .ci { opacity: .62; }
+.c-jev.flag::before { content: '?'; position: absolute; right: 4px; bottom: 4px; width: 13px; height: 13px; border-radius: 50%; font: 700 9px/13px var(--mono); text-align: center; color: #1a1204; background: var(--accent); box-shadow: 0 0 8px color-mix(in srgb, var(--accent) 70%, transparent); z-index: 1; }
+.c-jev.wrong::after { content: ''; position: absolute; left: 0; top: 0; border-top: 9px solid color-mix(in srgb, var(--bad) 85%, transparent); border-right: 9px solid transparent; }
+.cv { display: flex; align-items: center; gap: 6px; min-width: 0; height: 20px; }
+.cn { margin-left: auto; flex: none; font-size: 10.5px; color: var(--dim); font-variant-numeric: tabular-nums; }
+.opt { min-width: 0; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; font-weight: 700; padding: 1px 8px; border-radius: 999px; line-height: 16px;
+ color: var(--tone); background: color-mix(in srgb, var(--tone) 15%, transparent); border: 1px solid color-mix(in srgb, var(--tone) 45%, transparent); }
+.c-jev.flag .opt, .c-jev.flag .chip { border-style: dashed; }
+.chip { font-size: 11px; font-weight: 700; padding: 1px 8px; border-radius: 5px; line-height: 16px; border: 1px solid; }
+.chip.yes { color: var(--ok); background: color-mix(in srgb, var(--ok) 15%, transparent); border-color: color-mix(in srgb, var(--ok) 45%, transparent); }
+.chip.no { color: #9aa2ba; background: rgba(154,162,186,.08); border-color: rgba(154,162,186,.28); }
+.lvl { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11.5px; font-weight: 700; color: var(--ink); }
+.cbar { height: 3px; border-radius: 2px; background: rgba(255,255,255,.06); overflow: hidden; }
+.cbar i { display: block; height: 100%; border-radius: 2px; background: var(--tone); transition: width .3s ease-out; }
+.meter { display: flex; gap: 2px; height: 5px; }
+.meter i { flex: 1; border-radius: 2px; background: rgba(255,255,255,.07); }
+.meter i.on { background: var(--seg); box-shadow: 0 0 6px color-mix(in srgb, var(--seg) 55%, transparent); }
+
+.wait .sk { border-radius: 5px; background: linear-gradient(90deg, #171a26 20%, #2a3048 50%, #171a26 80%); background-size: 220% 100%; animation: shimmer 1.05s linear infinite; }
+.wait .sk.a { height: 16px; width: 62%; margin-top: 2px; border-radius: 999px; }
+.wait .sk.b { height: 3px; width: 100%; }
+@keyframes shimmer { from { background-position: 120% 0; } to { background-position: -100% 0; } }
+.c-jev.land { animation: land .55s ease-out; }
+.c-jev.land .ci { animation: flipin .42s cubic-bezier(.2,.9,.25,1.15); }
+.c-jev.land::before { animation: badgein .5s ease-out; }
+@keyframes badgein { 0%, 55% { opacity: 0; transform: scale(.4); } 100% { opacity: 1; transform: none; } }
+@keyframes flipin { 0% { transform: perspective(300px) rotateX(-92deg); opacity: 0; } 55% { opacity: 1; } 100% { transform: none; } }
+@keyframes land {
+ 0% { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 80%, transparent), inset 0 0 24px color-mix(in srgb, var(--accent) 42%, transparent); }
+ 35% { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 25%, transparent), inset 0 0 16px color-mix(in srgb, var(--accent) 16%, transparent); }
+ 100% { box-shadow: inset 0 0 0 1px transparent, inset 0 0 0 transparent; }
+}
+.enter { animation: colin .34s cubic-bezier(.2,.8,.2,1); }
+.leave { animation: colout .24s ease-in forwards; pointer-events: none; }
+@keyframes colin { from { max-width: 0; padding-left: 0; padding-right: 0; opacity: 0; } }
+@keyframes colout { to { max-width: 0; padding-left: 0; padding-right: 0; opacity: 0; border-right-width: 0; } }
+
+.empty { position: absolute; left: 0; right: 0; top: 40%; text-align: center; color: var(--dim); font-size: 13px; pointer-events: none; }
+.empty b { display: block; color: var(--ink); font-size: 15px; margin-bottom: 4px; }
+
+/* ---- rail --------------------------------------------------------------------------------- */
+#rail { width: 336px; gap: 12px; padding: 12px; }
+.insp-empty { color: var(--faint); font-size: 12px; line-height: 1.5; }
+.insp-row { font-size: 10.5px; line-height: 1.5; color: var(--dim); margin-bottom: 5px; }
+.insp-row b { color: var(--accent); font-variant-numeric: tabular-nums; margin-right: 6px; }
+.insp-row .tag { margin-left: 6px; }
+.insp-text { font: 12.5px/1.45 var(--sans); color: #d6dbea; max-height: 112px; overflow: auto; padding: 7px 9px; border-radius: 8px; background: #0b0d14; border: 1px solid var(--line); }
+.insp-q { margin-top: 9px; display: flex; align-items: baseline; gap: 6px; }
+.insp-q .qn { font-weight: 700; color: var(--accent); font-size: 13px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.insp-asked { font-size: 10.5px; color: var(--faint); margin: 3px 0 8px; line-height: 1.4; max-height: 44px; overflow: hidden; }
+.bars { display: flex; flex-direction: column; gap: 4px; }
+.bar { display: grid; grid-template-columns: 92px 1fr 40px; align-items: center; gap: 7px; font-size: 11px; min-height: 17px; }
+.bar .bl { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--dim); }
+.bar.top .bl { color: var(--ink); font-weight: 700; }
+.bar .bt { height: 9px; border-radius: 5px; background: rgba(255,255,255,.05); overflow: hidden; }
+.bar .bt i { display: block; height: 100%; width: 0; border-radius: 5px; background: color-mix(in srgb, var(--tone, var(--accent)) 45%, #30364d); transition: width .35s cubic-bezier(.2,.8,.2,1); }
+.bar.top .bt i { background: var(--tone, var(--accent)); box-shadow: 0 0 10px color-mix(in srgb, var(--tone, var(--accent)) 60%, transparent); }
+.bar .bv { text-align: right; font-variant-numeric: tabular-nums; color: var(--dim); }
+.bar.top .bv { color: var(--ink); }
+.bar .bd { grid-column: 1 / -1; font-size: 10px; color: var(--faint); margin: -2px 0 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.insp-more { font-size: 10px; color: var(--faint); }
+.insp-foot { margin-top: 9px; padding-top: 8px; border-top: 1px dashed var(--line); display: flex; flex-wrap: wrap; gap: 5px 6px; align-items: center; font-size: 10.5px; color: var(--dim); }
+.insp-foot .pill { font-size: 9.5px; }
+.how { font-size: 12px; }
+.grammar { display: flex; flex-direction: column; gap: 4px; margin: 8px 0; }
+.gex { display: flex; flex-direction: column; align-items: flex-start; gap: 1px; text-align: left; padding: 5px 9px; background: #0b0d14; border-color: var(--line); border-radius: 8px; font-weight: 400; }
+.gex code { color: var(--accent); font: 600 11.5px var(--mono); }
+.gex span { color: var(--faint); font-size: 10.5px; }
+.gex span i { color: var(--dim); font-style: normal; }
+.how .qmark { display: inline-block; width: 13px; height: 13px; border-radius: 50%; font: 700 9px/13px var(--mono); text-align: center; color: #1a1204; background: var(--accent); }
+.how .redc { color: var(--bad); }
+.dim { color: var(--faint); }
+.chips { display: flex; flex-wrap: wrap; gap: 6px; }
+.chips button { font-weight: 600; font-size: 11px; padding: 5px 9px; border-radius: 999px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; background: #0b0d14; }
+.chips button:hover { color: var(--accent); }
+.chips button.have { opacity: .4; text-decoration: line-through; cursor: default; }
+
+@media (max-width: 1240px) {
+ .stats.big { gap: 16px; }
+ .stats.big .stat span { font-size: 18px; }
+ .stats.big .stat { min-width: 50px; }
+ .brand .sub { display: none; }
+ #rail { width: 318px; }
+ .reviewbox { width: 168px; }
+}
diff --git a/store/agents/jev-sheets/viewer/studio.js b/store/agents/jev-sheets/viewer/studio.js
new file mode 100644
index 000000000..7cb309aae
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/studio.js
@@ -0,0 +1,631 @@
+// studio.js — the Jev Sheets pane. A DOM spreadsheet (virtual rows, sticky header and first column)
+// fed by the viewer server over SSE: `state` (the whole sheet), `cells` (answers as they land),
+// `view` (sort, filter, review line, numbers) and `ghost` (the demo typist).
+import { parseHeader, describeColumn } from '/grammar.mjs'
+
+const $ = (id) => document.getElementById(id)
+const h = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x))
+const ROW_H = 46, HEAD_H = 52, NUM_W = 44, OVERSCAN = 4, SEP = '\u0001'
+const PALETTE = ['#60a5fa', '#f472b6', '#34d399', '#a78bfa', '#fb923c', '#5eead4', '#f87171', '#a3e635', '#e879f9', '#38bdf8', '#fda4af', '#fcd34d']
+const HINT = '<b>Type a header</b> and press Enter: Jev fills every row. <b>Click a header</b> to sort. <b>Click a cell</b> to inspect. <b>Double-click a message</b> to edit it.'
+
+const grid = $('grid'), ghead = $('ghead'), gbody = $('gbody'), input = $('addInput'), addBox = $('addBox'), hint = $('hint')
+const root = document.documentElement
+
+// Every piece of state is declared here, before anything can run.
+let S = null
+let rowIndex = new Map(), colIndex = new Map(), posOf = new Map(), order = []
+let recs = new Map() // row id -> { id, el, num, text, msg, cells: Map(col id -> {el, sig}), y, dying }
+let headCells = new Map(), headNum = null, headText = null, headAdd = null
+let held = new Map() // "row SEP col" -> time when the answer may flip in
+let colBorn = new Map() // col id -> time first seen (new columns unfold)
+let lastRevealAt = 0
+let selected = null, inspSeq = 0, inspTimer = null
+let editing = null
+let ghostInfo = { enabled: true, phase: 'idle', pausedMs: 0 }, ghostInfoAt = 0, ghostRun = null, ghostOwnsInput = false
+let lastTouch = -1e9, lastTour = 0, hintErrorUntil = 0, reviewPostTimer = null, draggingReview = false
+let dirty = { rows: false, head: false, top: false, hist: false }
+const tw = { rows: { v: 0, t: 0 }, cols: { v: 0, t: 0 }, cells: { v: 0, t: 0 }, rate: { v: 0, t: 0 }, cost: { v: 0, t: 0 }, flag: { v: 0, t: 0 } }
+
+async function post(cmd, body = {}) {
+ try {
+ const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd, ...body }) })
+ return await r.json()
+ } catch { return { ok: false, error: 'the viewer is restarting' } }
+}
+
+// ---- colours ----------------------------------------------------------------------------------
+// One stable colour per option: its place in the column's option list picks it.
+const optTone = (col, i) => PALETTE[Math.max(0, i) % PALETTE.length]
+const lvlTone = (f) => `hsl(${Math.round(50 - 34 * f)} 94% ${Math.round(66 - 8 * f)}%)`
+function toneOf(col, cell) {
+ if (col.type === 'choice') return optTone(col, cell.v)
+ if (col.type === 'noul') return cell.v ? '#34d399' : '#9aa2ba'
+ return lvlTone(col.levels.length > 1 ? cell.v / (col.levels.length - 1) : 0)
+}
+const pctText = (c) => `${Math.round(c * 100)}%`
+
+// ---- layout -----------------------------------------------------------------------------------
+function layout() {
+ if (!S) return
+ const n = S.columns.length, avail = grid.clientWidth
+ const colw = avail < 800 ? 126 : 142
+ const textw = Math.round(clamp(avail - NUM_W - n * colw - 12, avail < 800 ? 250 : 300, 640))
+ root.style.setProperty('--colw', `${colw}px`)
+ root.style.setProperty('--textw', `${textw}px`)
+ const total = NUM_W + textw + n * colw
+ gbody.style.width = ghead.style.width = `${total}px`
+}
+
+// ---- header -----------------------------------------------------------------------------------
+function placeAfter(prev, el) {
+ let next = prev.nextSibling
+ while (next && next.classList?.contains('leave')) next = next.nextSibling
+ if (next !== el) prev.after(el)
+}
+function leave(el) { el.classList.remove('enter'); el.classList.add('leave'); setTimeout(() => el.remove(), 250) }
+const newborn = (id) => performance.now() - (colBorn.get(id) ?? -1e9) < 600
+
+function renderHead() {
+ if (!headNum) {
+ headNum = h('div', 'hc num', '#')
+ headText = h('div', 'hc text')
+ headText.append(h('div', 'h-name'), h('div', 'h-sub'))
+ ghead.append(headNum, headText)
+ }
+ headText.children[0].textContent = S.textLabel
+ const shownRows = order.length === S.rows.length ? `${S.rows.length} rows` : `${order.length} of ${S.rows.length} rows`
+ headText.children[1].textContent = S.source ? `${shownRows} · your file ${S.source.name} · text column "${S.source.textColumn}"${S.source.total > S.source.used ? ` · first ${S.source.used} of ${S.source.total}` : ''}` : `${shownRows} · made-up data · double-click to edit`
+ const pill = document.getElementById('synthPill'); if (pill) { pill.textContent = S.source ? 'your data' : 'synthetic data'; pill.title = S.source ? `Rows come from ${S.source.name} in the workspace.` : 'Every name, message and truth label in this sheet is made up.' }
+ for (const [id, el] of headCells) if (!colIndex.has(id)) { leave(el); headCells.delete(id) }
+ let prev = headText
+ for (const col of S.columns) {
+ let el = headCells.get(col.id)
+ if (!el) {
+ el = h('div', 'hc jev'); el.dataset.col = col.id
+ const top = h('div', 'h-top'); top.append(h('span', 'h-name'), h('span', 'h-sort'), h('button', 'h-x', '×'))
+ top.lastChild.title = 'Remove this column'
+ el.append(top, h('div', 'h-sub'), h('div', 'h-fill'))
+ if (newborn(col.id)) el.classList.add('enter')
+ headCells.set(col.id, el)
+ }
+ placeAfter(prev, el); prev = el
+ const st = S.colStats[col.id] ?? { filled: 0, flagged: 0 }
+ el.title = `${col.header}\n\nClick to sort. ${col.kind}.`
+ el.classList.toggle('demo', col.source === 'demo')
+ el.classList.toggle('sorted', S.sort?.col === col.id)
+ el.querySelector('.h-name').textContent = col.type === 'noul' ? `${col.name}?` : col.name
+ el.querySelector('.h-sort').textContent = S.sort?.col === col.id ? (S.sort.dir === 'desc' ? '▼' : '▲') : ''
+ const sub = el.querySelector('.h-sub')
+ sub.textContent = ''
+ sub.append(h('span', 'tag', col.type))
+ if (col.source === 'demo') sub.append(h('span', 'tag demo', 'demo'))
+ if (st.acc != null) { const a = h('span', `h-acc ${st.acc >= 0.85 ? '' : st.acc >= 0.7 ? 'mid' : 'low'}`, `✓ ${Math.round(st.acc * 100)}%`); a.title = `${st.correct} of ${st.labelled} rows match the made-up truth labels`; sub.append(a) }
+ if (st.flagged) { const f = h('span', 'h-flag', `?${st.flagged}`); f.title = `${st.flagged} cells under the review line`; sub.append(f) }
+ const fill = el.querySelector('.h-fill')
+ const frac = S.rows.length ? st.filled / S.rows.length : 1
+ fill.style.width = `${frac * 100}%`
+ fill.classList.toggle('done', frac >= 1)
+ }
+ if (!headAdd) {
+ headAdd = h('div', 'hc add')
+ headAdd.append(h('span', '', '+'), document.createTextNode('ask another question'))
+ headAdd.title = 'Type a header in the box above and press Enter'
+ headAdd.addEventListener('click', () => { dropGhostText(); input.focus() })
+ }
+ const used = NUM_W + parseFloat(root.style.getPropertyValue('--textw') || '0') + S.columns.length * parseFloat(root.style.getPropertyValue('--colw') || '0')
+ headAdd.classList.toggle('hidden', S.columns.length >= S.limits.maxColumns || used + 150 > grid.clientWidth) // only where there is spare room
+ if (ghead.lastChild !== headAdd) ghead.append(headAdd)
+}
+
+// ---- rows (virtual) ---------------------------------------------------------------------------
+function visibleRange() {
+ const top = grid.scrollTop, viewH = Math.max(0, grid.clientHeight - HEAD_H)
+ return [Math.max(0, Math.floor(top / ROW_H) - OVERSCAN), Math.min(order.length - 1, Math.ceil((top + viewH) / ROW_H) + OVERSCAN)]
+}
+function createRow(id, y) {
+ const el = h('div', 'row'); el.dataset.row = id
+ const num = h('div', 'cell c-num'), text = h('div', 'cell c-text'), msg = h('div', 'msg')
+ text.append(msg); el.append(num, text)
+ el.style.transform = `translateY(${y}px)`
+ gbody.append(el)
+ const rec = { id, el, num, text, msg, cells: new Map(), y, textSig: null, dying: false }
+ recs.set(id, rec)
+ return rec
+}
+function placeRow(rec, y) { if (rec.y !== y) { rec.y = y; rec.el.style.transform = `translateY(${y}px)` } }
+function fillRow(rec, i) {
+ const r = rowIndex.get(rec.id)
+ if (!r) return
+ rec.el.classList.toggle('odd', i % 2 === 1)
+ rec.num.textContent = r.n
+ const sig = `${r.text}|${r.edited}|${r.group}`
+ if (sig !== rec.textSig && editing?.id !== rec.id) {
+ rec.textSig = sig
+ rec.msg.textContent = ''
+ const who = r.meta?.from ?? Object.values(r.meta ?? {})[0]
+ if (who != null) rec.msg.append(h('span', 'who', String(who).split(',')[0]))
+ if (r.group === 'mixed') { const t = h('span', 'tag mixed', 'mixed'); t.title = 'This row was written with mixed signals on purpose'; rec.msg.append(t) }
+ if (r.edited) { const t = h('span', 'tag edited', 'edited'); t.title = 'Edited in the pane. Its truth label no longer applies.'; rec.msg.append(t) }
+ rec.msg.append(document.createTextNode(r.text))
+ rec.text.title = [r.text, '', ...Object.entries(r.meta ?? {}).map(([k, v]) => `${k}: ${v}`)].join('\n')
+ }
+ for (const [cid, c] of rec.cells) if (!colIndex.has(cid)) { leave(c.el); rec.cells.delete(cid) }
+ let prev = rec.text
+ for (const col of S.columns) {
+ let c = rec.cells.get(col.id)
+ if (!c) {
+ c = { el: h('div', 'cell c-jev'), sig: null }
+ c.el.dataset.col = col.id
+ if (newborn(col.id)) c.el.classList.add('enter')
+ rec.cells.set(col.id, c)
+ }
+ placeAfter(prev, c.el); prev = c.el
+ paintCell(rec, col, c, false)
+ }
+}
+function paintCell(rec, col, c, land) {
+ const cell = held.has(rec.id + SEP + col.id) ? null : S.cells[rec.id]?.[col.id]
+ const sig = cell ? `${col.type}${JSON.stringify(cell)}` : 'wait'
+ const el = c.el
+ if (sig !== c.sig) {
+ c.sig = sig
+ el.textContent = ''
+ const ci = h('div', 'ci')
+ if (!cell) ci.append(h('div', 'sk a'), h('div', 'sk b'))
+ else {
+ const tone = toneOf(col, cell)
+ el.style.setProperty('--tone', tone)
+ el.style.setProperty('--conf', String(cell.c))
+ const cv = h('div', 'cv')
+ if (col.type === 'choice') cv.append(h('span', 'opt', col.options[cell.v] ?? '?'))
+ else if (col.type === 'noul') cv.append(h('span', `chip ${cell.v ? 'yes' : 'no'}`, cell.v ? 'yes' : 'no'))
+ else cv.append(h('span', 'lvl', col.levels[cell.v] ?? '?'))
+ cv.append(h('span', 'cn', pctText(cell.c)))
+ ci.append(cv)
+ if (col.type === 'score') {
+ const m = h('div', 'meter'), n = col.levels.length
+ for (let i = 0; i < n; i++) { const seg = h('i', i <= cell.v ? 'on' : ''); seg.style.setProperty('--seg', lvlTone(n > 1 ? i / (n - 1) : 0)); m.append(seg) }
+ ci.append(m)
+ } else {
+ const bar = h('div', 'cbar'), fill = h('i'); fill.style.width = `${cell.c * 100}%`; bar.append(fill); ci.append(bar)
+ }
+ }
+ el.append(ci)
+ }
+ el.classList.toggle('wait', !cell)
+ el.classList.toggle('flag', !!cell && cell.c < S.reviewBelow)
+ el.classList.toggle('wrong', !!cell && cell.ok === 0)
+ const sel = selected && selected.row === rec.id && selected.col === col.id
+ el.classList.toggle('sel', !!sel)
+ el.classList.toggle('bydemo', !!sel && selected.by === 'demo')
+ if (land && cell) { el.classList.remove('land'); void el.offsetWidth; el.classList.add('land') }
+}
+function renderRows() {
+ if (!S) return
+ const [a, b] = visibleRange()
+ const want = new Set()
+ for (let i = a; i <= b; i++) want.add(order[i])
+ for (const [id, rec] of recs) {
+ if (want.has(id)) { if (rec.dying) { rec.dying = false; rec.el.classList.remove('gone') } continue }
+ if (rec.dying || editing?.id === id) continue
+ rec.el.remove(); recs.delete(id)
+ }
+ for (let i = a; i <= b; i++) {
+ const id = order[i]
+ const rec = recs.get(id) ?? createRow(id, i * ROW_H)
+ placeRow(rec, i * ROW_H)
+ fillRow(rec, i)
+ }
+ const none = order.length === 0
+ $('empty').classList.toggle('hidden', !none)
+ if (none) $('empty').innerHTML = S.rows.length ? '<b>Nothing under the review line</b>Drag the line to the right to see what Jev is least sure about.' : '<b>No rows yet</b>Ask the agent to build a sheet in sheet.json.'
+}
+/** Re-order rows. Rows slide to their new places; rows entering or leaving slide across the edge. */
+function setOrder(next, animate) {
+ const old = posOf
+ order = next
+ posOf = new Map(next.map((id, i) => [id, i]))
+ gbody.style.height = `${next.length * ROW_H}px`
+ if (!animate || !recs.size) return
+ const top = grid.scrollTop, lo = top - 2 * ROW_H, hi = top + grid.clientHeight + ROW_H
+ const [a, b] = visibleRange()
+ for (let i = a; i <= b; i++) {
+ const id = next[i], oi = old.get(id)
+ if (recs.has(id) || oi == null) continue
+ const rec = createRow(id, clamp(oi * ROW_H, lo, hi)); fillRow(rec, i)
+ }
+ void gbody.offsetHeight // commit the start positions so the move animates
+ for (const [id, rec] of recs) {
+ const ni = posOf.get(id)
+ if (ni != null && ni >= a && ni <= b) {
+ if (rec.y !== ni * ROW_H) { rec.el.classList.add('moving'); setTimeout(() => rec.el.classList.remove('moving'), 600) }
+ continue
+ }
+ if (editing?.id === id) continue
+ rec.dying = true
+ if (ni == null) rec.el.classList.add('gone'); else placeRow(rec, clamp(ni * ROW_H, lo, hi))
+ setTimeout(() => { if (rec.dying) { rec.el.remove(); if (recs.get(id) === rec) recs.delete(id) } }, ni == null ? 320 : 580)
+ }
+}
+
+// ---- server frames ----------------------------------------------------------------------------
+function applyState(s) {
+ const first = !S
+ const hadCols = new Set(S ? S.columns.map((c) => c.id) : [])
+ S = s
+ rowIndex = new Map(s.rows.map((r) => [r.id, r]))
+ colIndex = new Map(s.columns.map((c) => [c.id, c]))
+ const now = performance.now()
+ let grew = false
+ for (const c of s.columns) if (!colBorn.has(c.id)) { colBorn.set(c.id, first ? -1e9 : now); if (!first && !hadCols.has(c.id)) grew = true }
+ for (const id of [...colBorn.keys()]) if (!colIndex.has(id)) colBorn.delete(id)
+ for (const key of [...held.keys()]) { const [rid, cid] = key.split(SEP); if (!s.cells[rid]?.[cid]) held.delete(key) }
+ $('sheetTitle').textContent = s.title
+ $('sheetTitle').title = s.description
+ $('synthPill').title = s.description || 'Every row in this sheet is made up.'
+ document.title = `Jev Sheets · ${s.title}`
+ layout()
+ const sameOrder = order.length === s.order.length && order.every((id, i) => id === s.order[i])
+ setOrder(s.order, !first && !sameOrder)
+ if (first) {
+ // The sheet is usually full by the time the pane opens. Let it arrive as a wave anyway.
+ const [a, b] = visibleRange()
+ for (let i = a; i <= b; i++) s.columns.forEach((c, j) => { if (s.cells[s.order[i]]?.[c.id]) held.set(s.order[i] + SEP + c.id, now + 260 + (i - a) * 30 + j * 55) })
+ }
+ renderHead(); renderRows(); renderChips(); applyShared(s)
+ if (grew) grid.scrollTo({ left: grid.scrollWidth, behavior: 'smooth' })
+ if (selected) { if (rowIndex.has(selected.row) && colIndex.has(selected.col)) inspectSoon(); else select(null) }
+}
+function applyShared(v) {
+ $('cfgError').classList.toggle('hidden', !(v.error || v.jevError))
+ $('cfgError').textContent = v.error || (v.jevError ? `Jev: ${v.jevError}` : '')
+ $('reviewOnlyBtn').classList.toggle('on', !!S.reviewOnly)
+ if (!draggingReview) { $('reviewRange').value = S.reviewBelow; $('reviewVal').textContent = S.reviewBelow.toFixed(2) }
+ if (v.ghost) applyGhost(v.ghost)
+ dirty.top = dirty.hist = true
+}
+function applyView(v) {
+ if (!S) return
+ const orderChanged = v.order.length !== order.length || v.order.some((id, i) => id !== order[i])
+ const lineMoved = v.reviewBelow !== S.reviewBelow
+ Object.assign(S, { reviewBelow: draggingReview ? S.reviewBelow : v.reviewBelow, reviewOnly: v.reviewOnly, sort: v.sort, order: v.order, colStats: v.colStats, groups: v.groups, stats: v.stats, running: v.running, error: v.error, jevError: v.jevError })
+ if (orderChanged) setOrder(v.order, true)
+ renderHead(); renderRows(); applyShared(v)
+ if (lineMoved && selected) inspectSoon()
+}
+function applyCells(m) {
+ if (!S || m.rev !== S.rev) return
+ const now = performance.now()
+ const touched = new Map()
+ for (const [rid, cid, cell] of m.patches) {
+ (S.cells[rid] ??= {})[cid] = cell
+ const rec = recs.get(rid)
+ if (rec && !rec.dying) (touched.get(rid) ?? touched.set(rid, []).get(rid)).push(cid)
+ if (selected && selected.row === rid && selected.col === cid) inspectSoon()
+ }
+ // Answers land faster than the eye can follow. Let the visible ones flip in top to bottom.
+ const step = lastRevealAt - now > 700 ? 7 : 24
+ for (const rid of [...touched.keys()].sort((x, y) => (posOf.get(x) ?? 0) - (posOf.get(y) ?? 0))) {
+ lastRevealAt = Math.max(now, lastRevealAt + step)
+ touched.get(rid).forEach((cid, k) => held.set(rid + SEP + cid, lastRevealAt + k * 40))
+ }
+ S.colStats = m.colStats; S.groups = m.groups; S.stats = m.stats
+ dirty.head = dirty.top = dirty.hist = true
+}
+
+// ---- top bar ----------------------------------------------------------------------------------
+const fmtCost = (v) => (v <= 0 ? '$0' : v < 0.01 ? `$${v.toFixed(5)}` : `$${v.toFixed(4)}`)
+function localFlags() {
+ let n = 0, rowsN = 0
+ for (const rid in S.cells) { let any = false; for (const cid in S.cells[rid]) if (colIndex.has(cid) && S.cells[rid][cid].c < S.reviewBelow) { n++; any = true } if (any) rowsN++ }
+ return [n, rowsN]
+}
+function renderTop() {
+ const st = S.stats
+ const [flagged, flaggedRows] = localFlags()
+ tw.rows.t = st.rows; tw.cols.t = st.columns; tw.cells.t = st.cellsFilled; tw.rate.t = st.cellsPerSec; tw.cost.t = st.costUsd; tw.flag.t = flagged
+ $('sCellsOf').textContent = `/${st.cellsTotal}`
+ $('rateStat').classList.toggle('hot', !!st.busy)
+ $('rateStat').title = st.waveMs ? `Last wave: ${st.computed} cells so far, ${st.calls} calls. The last burst took ${st.waveMs} ms.` : ''
+ $('flagStat').classList.toggle('some', flagged > 0)
+ $('reviewOnlyN').textContent = flaggedRows
+}
+function stepTweens() {
+ for (const [k, t] of Object.entries(tw)) {
+ if (t.v === t.t && t.shown === t.t) continue
+ const eps = k === 'cost' ? 1e-7 : 0.5
+ t.v = Math.abs(t.t - t.v) < eps ? t.t : t.v + (t.t - t.v) * 0.2
+ const text = k === 'cost' ? fmtCost(t.v) : String(Math.round(t.v))
+ if (text !== t.text) { t.text = text; $({ rows: 'sRows', cols: 'sCols', cells: 'sCells', rate: 'sRate', cost: 'sCost', flag: 'sFlag' }[k]).textContent = text }
+ if (t.v === t.t) t.shown = t.t
+ }
+}
+
+// ---- confidence histogram under the review slider ---------------------------------------------
+function drawHist() {
+ const cv = $('hist'), dpr = window.devicePixelRatio || 1
+ const w = cv.clientWidth, hh = cv.clientHeight
+ if (!w || !hh) return
+ if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(hh * dpr)) { cv.width = Math.round(w * dpr); cv.height = Math.round(hh * dpr) }
+ const g = cv.getContext('2d')
+ g.setTransform(dpr, 0, 0, dpr, 0, 0)
+ g.clearRect(0, 0, w, hh)
+ const N = 28, bins = new Array(N).fill(0)
+ for (const rid in S.cells) for (const cid in S.cells[rid]) if (colIndex.has(cid)) bins[Math.min(N - 1, Math.floor(S.cells[rid][cid].c * N))]++
+ const max = Math.max(1, ...bins), bw = w / N
+ for (let i = 0; i < N; i++) {
+ if (!bins[i]) continue
+ const bh = Math.max(2, Math.sqrt(bins[i] / max) * (hh - 1)) // square root, so small bins still show
+ g.fillStyle = (i + 0.5) / N < S.reviewBelow ? 'rgba(251,191,36,.95)' : 'rgba(52,211,153,.5)'
+ g.fillRect(i * bw + 0.5, hh - bh, bw - 1, bh)
+ }
+ g.fillStyle = '#fbbf24'
+ g.fillRect(clamp(S.reviewBelow * w - 0.5, 0, w - 1), 0, 1, hh)
+}
+
+// ---- inspector --------------------------------------------------------------------------------
+function select(next) {
+ selected = next
+ for (const rec of recs.values()) for (const [cid, c] of rec.cells) {
+ const on = !!next && next.row === rec.id && next.col === cid
+ c.el.classList.toggle('sel', on); c.el.classList.toggle('bydemo', on && next.by === 'demo')
+ }
+ if (!next) { inspSeq++; $('inspTag').textContent = ''; $('inspBody').className = 'insp-empty'; $('inspBody').textContent = 'Click any cell to see what Jev was asked and its full answer.'; return }
+ inspectNow()
+}
+const inspectSoon = () => { clearTimeout(inspTimer); inspTimer = setTimeout(inspectNow, 60) }
+async function inspectNow() {
+ if (!selected) return
+ const seq = ++inspSeq
+ const d = await post('inspect', { row: selected.row, col: selected.col })
+ if (seq !== inspSeq || !selected) return
+ if (!d.ok) return select(null)
+ renderInspector(d)
+}
+function bar(label, p, top, tone, desc) {
+ const b = h('div', `bar${top ? ' top' : ''}`)
+ if (tone) b.style.setProperty('--tone', tone)
+ const track = h('div', 'bt'), fill = h('i')
+ track.append(fill)
+ const l = h('span', 'bl', label); l.title = desc ? `${label}: ${desc}` : label
+ b.append(l, track, h('span', 'bv', p >= 0.995 ? '1.00' : p.toFixed(2)))
+ if (desc) b.append(h('span', 'bd', desc))
+ requestAnimationFrame(() => (fill.style.width = `${Math.max(1.5, p * 100)}%`))
+ return b
+}
+function renderInspector(d) {
+ const body = $('inspBody'), col = d.column, cell = d.cell
+ body.className = ''
+ body.textContent = ''
+ const tag = $('inspTag'); tag.textContent = ''
+ if (selected.by === 'demo') tag.append(h('span', 'tag demo', 'demo tour'))
+ const rowLine = h('div', 'insp-row')
+ rowLine.append(h('b', '', `#${d.row.n}`), document.createTextNode(Object.values(d.row.meta ?? {}).join(' · ')))
+ if (d.row.group === 'mixed') rowLine.append(h('span', 'tag mixed', 'mixed signals'))
+ if (d.row.edited) rowLine.append(h('span', 'tag edited', 'edited'))
+ body.append(rowLine, h('div', 'insp-text', d.row.text))
+ const q = h('div', 'insp-q'); q.append(h('span', 'tag', col.type), h('span', 'qn', col.type === 'noul' ? col.header : col.name)); q.lastChild.title = col.header
+ const asked = String(d.question.instructions ?? '')
+ const askedEl = h('div', 'insp-asked', `Jev was asked: ${d.context && asked.startsWith(d.context) ? asked.slice(d.context.length).trim() : asked}`)
+ askedEl.title = asked
+ body.append(q, askedEl)
+ const bars = h('div', 'bars')
+ if (!cell) bars.append(h('div', 'insp-empty', 'Jev is judging this row…'))
+ else if (col.type === 'noul') {
+ const p = cell.answer.noul
+ bars.append(bar('yes', p, p >= 0.5, '#34d399'), bar('no', 1 - p, p < 0.5, '#9aa2ba'))
+ } else if (col.type === 'choice') {
+ let entries = col.options.map((o, i) => [o, cell.answer.probabilities?.[o] ?? 0, i])
+ if (entries.length > 8) entries = entries.sort((x, y) => y[1] - x[1]).slice(0, 8)
+ for (const [o, p, i] of entries) bars.append(bar(o, p, o === cell.answer.choice, optTone(col, i), col.descriptions?.[o]))
+ if (col.options.length > entries.length) bars.append(h('div', 'insp-more', `and ${col.options.length - entries.length} more options`))
+ } else {
+ const n = col.levels.length, lv = Math.round(cell.answer.score)
+ col.levels.forEach((l, i) => bars.append(bar(l, cell.answer.probabilities?.[String(i)] ?? 0, i === lv, lvlTone(n > 1 ? i / (n - 1) : 0))))
+ bars.append(h('div', 'insp-more', `score ${Number(cell.answer.score).toFixed(2)} on a 0 to ${n - 1} scale`))
+ }
+ body.append(bars)
+ if (cell) {
+ const foot = h('div', 'insp-foot')
+ foot.append(h('span', `pill ${cell.conf < S.reviewBelow ? 'warn' : 'ok'}`, cell.conf < S.reviewBelow ? `${cell.conf.toFixed(2)} · under the ${S.reviewBelow.toFixed(2)} line` : `confidence ${cell.conf.toFixed(2)}`))
+ if (cell.truth != null) foot.append(h('span', `pill ${cell.ok ? 'ok' : 'bad'}`, cell.ok ? `matches truth: ${fmtTruth(cell.truth)}` : `truth label says ${fmtTruth(cell.truth)}`))
+ else foot.append(h('span', 'pill', d.row.edited ? 'edited row, no truth' : 'no truth label'))
+ foot.append(document.createTextNode(`${cell.cached ? 'from cache' : cell.latencyMs < 1 ? '<1 ms' : `${Math.round(cell.latencyMs)} ms`} · ~${cell.tokens ?? '?'} tokens for the row · ${S.client === 'mock' ? 'offline stand-in' : 'live Jev'}`))
+ body.append(foot)
+ }
+}
+const fmtTruth = (t) => (t === true ? 'yes' : t === false ? 'no' : String(t))
+
+// ---- suggested headers ------------------------------------------------------------------------
+function renderChips() {
+ const box = $('chips')
+ box.textContent = ''
+ for (const s of S.suggestions) {
+ const p = parseHeader(s)
+ if (!p.ok) continue
+ const b = h('button', colIndex.has(p.column.id) ? 'have' : '', s)
+ b.title = colIndex.has(p.column.id) ? 'Already in the sheet' : `${s}\n${describeColumn(p.column)}`
+ b.addEventListener('click', () => { if (!colIndex.has(p.column.id)) submit(s) })
+ box.append(b)
+ }
+}
+
+// ---- the add box ------------------------------------------------------------------------------
+function updateHint(text = input.value) {
+ if (performance.now() < hintErrorUntil) return
+ const t = text.trim()
+ if (!t) { hint.className = 'hint'; hint.innerHTML = HINT; return }
+ const p = parseHeader(t)
+ if (!p.ok) { hint.className = 'hint err'; hint.textContent = p.error; return }
+ hint.className = 'hint ok'
+ hint.textContent = ''
+ const c = p.column
+ const detail = c.type === 'choice' ? c.options.join(' · ') : c.type === 'score' ? c.levels.join(' < ') : 'Jev gives the probability of yes for every row'
+ hint.append(document.createTextNode('→'), h('b', '', describeColumn(c)), document.createTextNode(detail))
+ if (!ghostRun) hint.append(h('em', '', 'press Enter'))
+}
+function flashError(msg) {
+ hintErrorUntil = 0
+ hint.className = 'hint err'; hint.textContent = msg
+ hintErrorUntil = performance.now() + 3500
+ addBox.classList.remove('bad'); void addBox.offsetWidth; addBox.classList.add('bad')
+ setTimeout(() => addBox.classList.remove('bad'), 400)
+}
+async function submit(header) {
+ const t = String(header ?? '').trim()
+ if (!t) return
+ const p = parseHeader(t)
+ if (!p.ok) return flashError(p.error)
+ const r = await post('addColumn', { header: t })
+ if (!r.ok) return flashError(r.error || 'could not add that column')
+ if (header === input.value) input.value = ''
+ hintErrorUntil = 0; updateHint()
+}
+function dropGhostText() { if (ghostOwnsInput) { input.value = ''; ghostOwnsInput = false } ghostRun = null; addBox.classList.remove('ghosting'); $('ghostTag').classList.add('hidden') }
+input.addEventListener('pointerdown', dropGhostText)
+input.addEventListener('focus', dropGhostText)
+input.addEventListener('input', () => { hintErrorUntil = 0; updateHint() })
+input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); submit(input.value) }
+ else if (e.key === 'Escape') { input.value = ''; updateHint(); input.blur() }
+})
+for (const b of document.querySelectorAll('.gex')) b.addEventListener('click', () => { dropGhostText(); input.value = b.dataset.ex; input.focus(); updateHint() })
+
+// ---- the ghost typist -------------------------------------------------------------------------
+function applyGhost(g) {
+ ghostInfo = g; ghostInfoAt = performance.now()
+ if (g.phase === 'typing' && g.header && document.activeElement !== input) {
+ if (!ghostRun || ghostRun.header !== g.header) ghostRun = { header: g.header, typeMs: g.typeMs, t0: performance.now() - g.elapsedMs }
+ } else if (ghostRun) {
+ const committed = g.phase === 'dwell'
+ if (committed) { $('enterKey').classList.add('pressed'); setTimeout(() => $('enterKey').classList.remove('pressed'), 320) }
+ dropGhostText(); updateHint()
+ }
+ $('demoBtn').classList.toggle('on', !!g.enabled)
+}
+function stepGhost(now) {
+ const left = ghostInfo.enabled ? Math.max(0, ghostInfo.pausedMs - (now - ghostInfoAt)) : 0
+ const label = !ghostInfo.enabled ? 'off' : left > 0 ? `rests ${Math.ceil(left / 1000)}s` : 'on'
+ if ($('demoState').textContent !== label) $('demoState').textContent = label
+ $('demoBtn').classList.toggle('resting', left > 0)
+ if (!ghostRun) return
+ const f = clamp((now - ghostRun.t0) / ghostRun.typeMs, 0, 1)
+ const typed = ghostRun.header.slice(0, Math.floor(f * ghostRun.header.length))
+ const caret = f < 1 && Math.floor(now / 380) % 2 === 0 ? '▍' : ''
+ if (input.value !== typed + caret) {
+ input.value = typed + caret; ghostOwnsInput = true
+ if (typed !== ghostRun.typed) { ghostRun.typed = typed; updateHint(typed) }
+ }
+ addBox.classList.add('ghosting'); $('ghostTag').classList.remove('hidden')
+}
+/** While the ghost is awake and nobody has picked a cell, it also walks the inspector around. */
+function stepTour(now) {
+ if (!S || !ghostInfo.enabled || now - lastTour < 3600 || editing) return
+ if (ghostInfo.pausedMs - (now - ghostInfoAt) > 0 || held.size) return // resting: the person is playing
+ lastTour = now
+ const pool = [], flagged = []
+ const sticky = NUM_W + parseFloat(root.style.getPropertyValue('--textw') || '300'), colw = parseFloat(root.style.getPropertyValue('--colw') || '142')
+ for (const rec of recs.values()) if (!rec.dying) for (const cid of rec.cells.keys()) {
+ const cell = S.cells[rec.id]?.[cid]
+ if (!cell || (selected && selected.row === rec.id && selected.col === cid)) continue
+ const top = rec.y - grid.scrollTop
+ if (top < 0 || top > grid.clientHeight - HEAD_H - ROW_H) continue
+ const left = sticky + S.columns.findIndex((c) => c.id === cid) * colw - grid.scrollLeft // only cells in full view
+ if (left < sticky - 2 || left + colw > grid.clientWidth + 2) continue
+ pool.push([rec.id, cid]); if (cell.c < S.reviewBelow || cell.ok === 0) flagged.push([rec.id, cid])
+ }
+ const from = flagged.length && Math.random() < 0.7 ? flagged : pool
+ if (!from.length) return
+ const [row, col] = from[Math.floor(Math.random() * from.length)]
+ select({ row, col, by: 'demo' })
+}
+function userTouch() {
+ const now = performance.now()
+ if (now - lastTouch < 1500) return
+ lastTouch = now
+ ghostInfo = { ...ghostInfo, pausedMs: 60000 }; ghostInfoAt = now
+ post('touch')
+}
+for (const ev of ['pointerdown', 'keydown', 'wheel']) window.addEventListener(ev, (e) => { if (e.isTrusted) userTouch() }, { capture: true, passive: true })
+
+// ---- interactions -----------------------------------------------------------------------------
+ghead.addEventListener('click', (e) => {
+ const cell = e.target.closest('.hc.jev')
+ if (!cell || cell.classList.contains('leave')) return
+ if (e.target.closest('.h-x')) post('removeColumn', { id: cell.dataset.col })
+ else post('sort', { col: cell.dataset.col })
+})
+gbody.addEventListener('click', (e) => {
+ const cell = e.target.closest('.c-jev')
+ if (!cell || cell.classList.contains('leave')) return
+ select({ row: cell.parentElement.dataset.row, col: cell.dataset.col, by: 'user' })
+})
+gbody.addEventListener('dblclick', (e) => {
+ const t = e.target.closest('.c-text')
+ if (t && !editing) startEdit(t.parentElement.dataset.row)
+})
+function startEdit(id) {
+ const rec = recs.get(id), r = rowIndex.get(id)
+ if (!rec || !r) return
+ const ta = h('textarea', 'editor')
+ ta.value = r.text
+ rec.text.append(ta); rec.el.classList.add('editing')
+ editing = { id, ta }
+ ta.focus(); ta.select()
+ const done = async (save) => {
+ if (!editing || editing.ta !== ta) return
+ editing = null
+ const text = ta.value.replace(/\s+/g, ' ').trim()
+ ta.remove(); rec.el.classList.remove('editing')
+ if (save && text && text !== r.text) { const res = await post('editRow', { id, text }); if (!res.ok) flashError(res.error || 'could not edit that row') }
+ dirty.rows = true
+ }
+ ta.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); done(true) } else if (e.key === 'Escape') done(false) })
+ ta.addEventListener('blur', () => done(true))
+}
+$('reviewOnlyBtn').addEventListener('click', () => post('reviewOnly', { on: !S?.reviewOnly }))
+$('resetBtn').addEventListener('click', () => { select(null); post('reset') })
+$('demoBtn').addEventListener('click', () => post('demo', { on: !ghostInfo.enabled }))
+const range = $('reviewRange')
+range.addEventListener('input', () => {
+ if (!S) return
+ draggingReview = true
+ S.reviewBelow = Number(range.value)
+ $('reviewVal').textContent = S.reviewBelow.toFixed(2)
+ for (const rec of recs.values()) for (const [cid, c] of rec.cells) { const cell = S.cells[rec.id]?.[cid]; c.el.classList.toggle('flag', !!cell && !held.has(rec.id + SEP + cid) && cell.c < S.reviewBelow) }
+ dirty.top = dirty.hist = true
+ if (!reviewPostTimer) reviewPostTimer = setTimeout(() => { reviewPostTimer = null; post('setReview', { value: S.reviewBelow }) }, 70)
+})
+range.addEventListener('change', () => { draggingReview = false; post('setReview', { value: Number(range.value) }) })
+window.addEventListener('keydown', (e) => { if (e.key === '/' && !/^(INPUT|TEXTAREA)$/.test(document.activeElement?.tagName ?? '')) { e.preventDefault(); input.focus() } })
+grid.addEventListener('scroll', () => { dirty.rows = true; grid.classList.toggle('xscrolled', grid.scrollLeft > 0) }, { passive: true })
+new ResizeObserver(() => { layout(); dirty.rows = dirty.hist = true }).observe(grid)
+
+// ---- the frame loop ---------------------------------------------------------------------------
+function frame(now) {
+ if (S) {
+ if (held.size) for (const [key, at] of held) {
+ if (now < at) continue
+ held.delete(key)
+ const [rid, cid] = key.split(SEP)
+ const rec = recs.get(rid), col = colIndex.get(cid), c = rec?.cells.get(cid)
+ if (rec && col && c) paintCell(rec, col, c, true)
+ }
+ if (dirty.rows) { dirty.rows = false; renderRows() }
+ if (dirty.head) { dirty.head = false; renderHead() }
+ if (dirty.top) { dirty.top = false; renderTop() }
+ if (dirty.hist) { dirty.hist = false; drawHist() }
+ stepTweens(); stepGhost(now); stepTour(now)
+ }
+ requestAnimationFrame(frame)
+}
+
+updateHint()
+const es = new EventSource('/events')
+es.addEventListener('state', (e) => applyState(JSON.parse(e.data)))
+es.addEventListener('cells', (e) => applyCells(JSON.parse(e.data)))
+es.addEventListener('view', (e) => applyView(JSON.parse(e.data)))
+es.addEventListener('ghost', (e) => applyGhost(JSON.parse(e.data)))
+requestAnimationFrame(frame)
diff --git a/store/agents/jev-sheets/viewer/viewer.mjs b/store/agents/jev-sheets/viewer/viewer.mjs
new file mode 100644
index 000000000..f3c2c75a9
--- /dev/null
+++ b/store/agents/jev-sheets/viewer/viewer.mjs
@@ -0,0 +1,548 @@
+// viewer.mjs — the Jev Sheets viewer server.
+//
+// A spreadsheet where a column header IS a question. The server owns the sheet: it watches
+// sheet.json, keeps the runtime state a person builds in the pane (typed columns, row edits, sort,
+// filter, the review line), and fills cells by asking Jev ONE call per row with every Jev column as
+// a parallel question. A small pool of calls makes a new column fill in a wave, top to bottom.
+// Answers are cached by row text plus column definition, so only missing cells are ever computed.
+import { join, dirname, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, jev, toWire, PRICE_PER_MTOK } from '../toolchain/jev.mjs'
+import { serveViewer, writeVerdict, watchConfig, mulberry32, clean } from './kit.mjs'
+import { parseHeader, normalizeSheet, columnKey, judge, confidenceOf, levelOf, describeColumn, LIMITS } from './grammar.mjs'
+import { sheetMock } from './mock.mjs'
+import { loadSource } from './source.mjs'
+import { watch as watchFile } from 'node:fs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const MARKER = 'sheet.json'
+const GHOST_PAUSE_MS = 60000
+const FALLBACK_SUGGESTIONS = ['Urgency', 'Sentiment: negative < neutral < positive', 'Asks a question?', 'Complaint?']
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+const r3 = (x) => Math.round(x * 1000) / 1000
+
+export async function startSheetsViewer({ workspace, port = 0, autostart = true, paceMs = Number(process.env.JEV_SHEETS_PACE_MS ?? 90) } = {}) {
+ // Every `let` lives here, above the first call that could touch it.
+ let server = null, watcher = null
+ let sourceWatcher = null, sourceFile = null, sourceInfo = null, sourceError = null, sourceTimer = null // the person's own file, if sheet.json names one
+ let sheet = normalizeSheet({ rows: [] }), configError = null, jevError = null
+ let rows = [], rowById = new Map(), columns = []
+ let cells = new Map() // row id -> Map(column id -> cell)
+ let cache = new Map() // column key -> Map(row state -> answer)
+ let todo = new Set() // row ids with at least one missing cell
+ let inflight = new Set() // row objects being judged right now
+ let order = [], sort = null, reviewOnly = false, reviewBelow = 0.65, fileReviewBelow = null, fileDemo = null
+ let running = autostart, stopped = false, epoch = 0, rev = 0
+ let counters = { calls: 0, cacheHits: 0, tokens: 0, costUsd: 0, errors: 0, computed: 0 }
+ let burst = { active: false, startedAt: 0, cells: 0, rate: 0, ms: 0 }
+ let patches = [], patchTimer = null, verdictTimer = null, retryTimer = null, ghostTimer = null
+ let ghost = { enabled: true, phase: 'idle', header: '', typeMs: 0, startedAt: 0, nextAt: 0, removeAt: 0, pausedUntil: 0, cursor: 0, watching: false }
+ const rng = mulberry32(20260919)
+ const mockMode = !process.env.TYPESAFE_API_KEY
+ const colById = (id) => columns.find((c) => c.id === id)
+ const mock = sheetMock(colById)
+
+ // ---- questions -----------------------------------------------------------------------------
+ const rowState = (row) => ({ text: row.text, ...row.meta })
+ function questionFor(col) {
+ const ctx = sheet.context ? `${sheet.context} ` : ''
+ if (col.type === 'noul') return jev.noul(`${ctx}${col.header}`)
+ if (col.type === 'choice') return jev.choice(Object.fromEntries(col.options.map((o) => [o, col.descriptions?.[o] || o])), `${ctx}${col.name}: which option fits this row best?`)
+ return jev.score(col.levels, `${ctx}${col.name}: where does this row sit on the scale?`)
+ }
+
+ // ---- cells ---------------------------------------------------------------------------------
+ const cellOf = (rowId, colId) => cells.get(rowId)?.get(colId)
+ const hasMissing = (row) => columns.some((c) => !cellOf(row.id, c.id))
+ function compact(col, cell) {
+ const a = cell.answer
+ const out = { c: r3(cell.conf) }
+ if (cell.ok != null) out.ok = cell.ok ? 1 : 0
+ if (col.type === 'noul') { out.v = a.noul >= 0.5 ? 1 : 0; out.p = r3(a.noul) }
+ else if (col.type === 'choice') out.v = col.options.indexOf(String(a.choice))
+ else { out.v = levelOf(col, a); out.s = r3(Number(a.score ?? 0)) }
+ return out
+ }
+ function setCell(row, col, answer, info) {
+ let m = cells.get(row.id)
+ if (!m) cells.set(row.id, (m = new Map()))
+ const cell = { answer, conf: confidenceOf(col, answer), ok: judge(col, answer, row.truth?.[col.id]), at: Date.now(), ...info }
+ m.set(col.id, cell)
+ return cell
+ }
+ function cacheFor(col) {
+ const k = columnKey(col)
+ let m = cache.get(k)
+ if (!m) cache.set(k, (m = new Map()))
+ return m
+ }
+ /** Fill what the cache already knows, and list the rows that still need Jev. */
+ function refill() {
+ const old = cells
+ cells = new Map()
+ todo = new Set()
+ for (const row of rows) {
+ const key = JSON.stringify(rowState(row))
+ for (const col of columns) {
+ const hit = cacheFor(col).get(key)
+ if (!hit) continue
+ const prev = old.get(row.id)?.get(col.id)
+ setCell(row, col, hit.answer, { cached: prev && prev.answer === hit.answer ? prev.cached : true, latencyMs: hit.latencyMs, tokens: hit.tokens })
+ }
+ if (hasMissing(row)) todo.add(row.id)
+ }
+ }
+
+ // ---- the numbers ---------------------------------------------------------------------------
+ function tally() {
+ const colStats = {}, groups = {}
+ for (const c of columns) colStats[c.id] = { filled: 0, flagged: 0, labelled: 0, correct: 0, conf: 0 }
+ let filled = 0, flagged = 0
+ for (const row of rows) {
+ const m = cells.get(row.id)
+ if (!m) continue
+ for (const c of columns) {
+ const cell = m.get(c.id)
+ if (!cell) continue
+ const s = colStats[c.id]
+ s.filled++; s.conf += cell.conf; filled++
+ if (cell.conf < reviewBelow) { s.flagged++; flagged++ }
+ if (cell.ok != null) { s.labelled++; if (cell.ok) s.correct++ }
+ if (row.group) {
+ const g = (groups[row.group] ??= { cells: 0, conf: 0, labelled: 0, correct: 0 })
+ g.cells++; g.conf += cell.conf
+ if (cell.ok != null) { g.labelled++; if (cell.ok) g.correct++ }
+ }
+ }
+ }
+ for (const s of Object.values(colStats)) { s.avgConf = s.filled ? r3(s.conf / s.filled) : 0; s.acc = s.labelled ? r3(s.correct / s.labelled) : null; delete s.conf }
+ for (const g of Object.values(groups)) { g.avgConf = g.cells ? r3(g.conf / g.cells) : 0; g.acc = g.labelled ? r3(g.correct / g.labelled) : null; delete g.conf }
+ const total = rows.length * columns.length
+ return {
+ colStats, groups,
+ stats: {
+ rows: rows.length, columns: columns.length, cellsTotal: total, cellsFilled: filled, flagged,
+ calls: counters.calls, cacheHits: counters.cacheHits, computed: counters.computed, tokens: counters.tokens, costUsd: Math.round(counters.costUsd * 1e8) / 1e8, errors: counters.errors,
+ cellsPerSec: r3(burst.rate), waveMs: Math.round(burst.ms), busy: todo.size + inflight.size > 0,
+ },
+ }
+ }
+
+ // ---- order: sort and the "needs review only" filter -----------------------------------------
+ function rowNeedsReview(row) {
+ const m = cells.get(row.id)
+ if (!m) return false
+ for (const c of columns) { const cell = m.get(c.id); if (cell && cell.conf < reviewBelow) return true }
+ return false
+ }
+ function sortKey(col, cell) {
+ if (!cell) return null
+ const a = cell.answer
+ if (col.type === 'noul') return a.noul
+ if (col.type === 'choice') { const i = col.options.indexOf(String(a.choice)); return -(i < 0 ? col.options.length : i) + cell.conf * 0.5 }
+ return levelOf(col, a) + cell.conf * 0.5 // by level, the surest first
+ }
+ function computeOrder() {
+ let list = rows
+ if (reviewOnly) list = list.filter((r) => rowNeedsReview(r) || hasMissing(r))
+ const col = sort && colById(sort.col)
+ if (!col) { if (sort) sort = null; order = list.map((r) => r.id); return }
+ const dir = sort.dir === 'asc' ? 1 : -1
+ const keyed = list.map((r, i) => ({ id: r.id, k: sortKey(col, cellOf(r.id, col.id)), i }))
+ keyed.sort((a, b) => (a.k == null) - (b.k == null) || (a.k == null ? 0 : dir * (a.k - b.k)) || a.i - b.i)
+ order = keyed.map((x) => x.id)
+ }
+
+ // ---- what the pane gets ---------------------------------------------------------------------
+ function ghostView() {
+ const now = Date.now()
+ return {
+ enabled: ghost.enabled, phase: ghost.phase, header: ghost.phase === 'typing' ? ghost.header : '',
+ typeMs: ghost.typeMs, elapsedMs: ghost.phase === 'typing' ? now - ghost.startedAt : 0,
+ pausedMs: Math.max(0, ghost.pausedUntil - now),
+ }
+ }
+ function lightView() {
+ return { rev, running, reviewBelow, reviewOnly, sort, order, error: configError, jevError, ghost: ghostView(), ...tally() }
+ }
+ function fullState() {
+ const cellsOut = {}
+ for (const row of rows) {
+ const m = cells.get(row.id)
+ if (!m) continue
+ const o = {}
+ for (const c of columns) { const cell = m.get(c.id); if (cell) o[c.id] = compact(c, cell) }
+ cellsOut[row.id] = o
+ }
+ return {
+ title: sheet.title, description: sheet.description, textLabel: sheet.textLabel, client: mockMode ? 'mock' : 'typesafe',
+ source: sourceInfo, // set when the rows come from the person's own file
+ concurrency: sheet.concurrency, limits: LIMITS,
+ suggestions: sheet.suggestions.length ? sheet.suggestions : FALLBACK_SUGGESTIONS,
+ columns: columns.map((c) => ({ id: c.id, header: c.header, name: c.name, type: c.type, options: c.options, descriptions: c.descriptions, levels: c.levels, bare: !!c.bare, source: c.source, kind: describeColumn(c) })),
+ rows: rows.map((r, i) => ({ id: r.id, n: i + 1, text: r.text, meta: r.meta, group: r.group, edited: !!r.edited, labelled: !!r.truth })),
+ cells: cellsOut,
+ ...lightView(),
+ }
+ }
+ const pushState = () => server?.broadcast(fullState(), 'state')
+ const pushView = () => server?.broadcast(lightView(), 'view')
+ const pushGhost = () => server?.broadcast(ghostView(), 'ghost')
+ function flushPatches() {
+ clearTimeout(patchTimer); patchTimer = null
+ if (!patches.length) return
+ const out = patches; patches = []
+ const t = tally()
+ server?.broadcast({ rev, patches: out, colStats: t.colStats, groups: t.groups, stats: t.stats }, 'cells')
+ }
+ const queuePatch = (row, col, cell) => { patches.push([row.id, col.id, compact(col, cell)]); if (!patchTimer) patchTimer = setTimeout(flushPatches, 40) }
+
+ // ---- the verdict ---------------------------------------------------------------------------
+ function verdict() {
+ const { colStats, groups, stats } = tally()
+ const pct = (x) => `${Math.round(x * 100)}%`
+ const accLine = columns.filter((c) => colStats[c.id].acc != null).map((c) => `${c.name} ${pct(colStats[c.id].acc)}`).join(', ')
+ const findings = []
+ if (configError) findings.push({ severity: 'error', kind: 'sheet', ref: MARKER, message: configError })
+ if (jevError) findings.push({ severity: 'warning', kind: 'jev', message: jevError })
+ const report = []
+ for (const c of columns) {
+ const s = colStats[c.id]
+ // The rows worth a second look: wrong ones first, then the least sure.
+ const weak = rows.map((r) => ({ r, cell: cellOf(r.id, c.id) })).filter((x) => x.cell && (x.cell.ok === false || x.cell.conf < reviewBelow))
+ .sort((a, b) => (a.cell.ok === false ? 0 : 1) - (b.cell.ok === false ? 0 : 1) || a.cell.conf - b.cell.conf).slice(0, 5)
+ .map(({ r, cell }) => ({ row: r.id, text: r.text.slice(0, 90), answered: shown(c, cell.answer), confidence: r3(cell.conf), truth: r.truth?.[c.id] ?? null }))
+ report.push({ id: c.id, header: c.header, type: c.type, source: c.source, filled: s.filled, accuracy: s.acc, labelled: s.labelled, underReviewLine: s.flagged, avgConfidence: s.avgConf, weakest: weak })
+ const share = s.filled ? s.flagged / s.filled : 0
+ findings.push({
+ severity: (s.acc != null && s.acc < 0.8) || share > 0.35 ? 'warning' : 'info', kind: 'column', ref: c.id,
+ message: `${c.name} (${c.type}): ${s.acc == null ? 'no truth labels' : `${s.correct}/${s.labelled} right, ${pct(s.acc)}`}, ${s.flagged} of ${s.filled} cells under ${reviewBelow}, average confidence ${s.avgConf}.`,
+ })
+ }
+ const g = Object.entries(groups).map(([k, v]) => `${k} ${v.avgConf}`).join(', ')
+ if (g) findings.push({ severity: 'info', kind: 'confidence', message: `Average confidence by row group: ${g}.` })
+ const full = stats.cellsTotal > 0 && stats.cellsFilled === stats.cellsTotal
+ return {
+ ready: !configError && full,
+ summary: clean(configError ? `sheet.json needs a fix: ${configError}` : `${sheet.title}: ${stats.rows} rows x ${stats.columns} Jev columns, ${stats.cellsFilled}/${stats.cellsTotal} cells, ${stats.flagged} under ${reviewBelow}${accLine ? `. Right: ${accLine}` : ''}`).slice(0, 200),
+ findings, artifact: MARKER,
+ phases: [
+ { id: 'load', name: 'Sheet loaded', state: configError ? 'failed' : 'done' },
+ { id: 'fill', name: 'Cells filled', state: full ? 'done' : stats.cellsTotal ? 'active' : 'pending' },
+ { id: 'review', name: 'Review', state: !full ? 'pending' : stats.flagged ? 'active' : 'done' },
+ ],
+ sheet: { client: mockMode ? 'mock' : 'typesafe', reviewBelow, rows: stats.rows, cellsFilled: stats.cellsFilled, cellsTotal: stats.cellsTotal, flagged: stats.flagged, costUsd: stats.costUsd, groups, columns: report },
+ }
+ }
+ function shown(col, a) {
+ if (col.type === 'noul') return a.noul >= 0.5 ? 'yes' : 'no'
+ if (col.type === 'choice') return String(a.choice)
+ return col.levels[levelOf(col, a)]
+ }
+ function saveVerdict() { clearTimeout(verdictTimer); verdictTimer = null; if (stopped) return; try { writeVerdict(workspace, verdict()) } catch { /* workspace gone */ } }
+ const verdictSoon = () => { if (!verdictTimer) verdictTimer = setTimeout(saveVerdict, 250) }
+
+ // ---- asking Jev: one call per row, every missing column as a parallel question ---------------
+ function nextRow() {
+ if (!todo.size) return null
+ const now = Date.now()
+ const busy = new Set([...inflight].map((r) => r.id))
+ const pick = (id) => { const row = rowById.get(id); return row && todo.has(id) && !busy.has(id) && !(row.retryAt > now) ? row : null }
+ for (const id of order) { const row = pick(id); if (row) return row }
+ for (const id of todo) { const row = pick(id); if (row) return row }
+ return null
+ }
+ async function judgeRow(row, fast) {
+ const myEpoch = epoch
+ const state = rowState(row)
+ const key = JSON.stringify(state)
+ const need = []
+ for (const col of columns) {
+ if (cellOf(row.id, col.id)) continue
+ const hit = cacheFor(col).get(key)
+ if (hit) { counters.cacheHits++; queuePatch(row, col, setCell(row, col, hit.answer, { cached: true, latencyMs: hit.latencyMs, tokens: hit.tokens })) } else need.push(col)
+ }
+ if (!need.length) { todo.delete(row.id); return }
+ inflight.add(row)
+ try {
+ // Offline, a call returns in under a millisecond. Pace it like the live model (about 100 ms)
+ // so the wave is visible. `tick` and `drain` skip the pacing.
+ if (!fast && mockMode && paceMs > 0) await sleep(paceMs * (0.7 + 0.6 * rng()))
+ const questions = Object.fromEntries(need.map((c) => [c.id, questionFor(c)]))
+ const res = await evaluate({ state, questions, salt: 1, mock, model: process.env.JEV_MODEL || 'jev-latest' })
+ if (stopped || myEpoch !== epoch || rowById.get(row.id) !== row || JSON.stringify(rowState(row)) !== key) return
+ const real = Number(res.usage?.input_tokens)
+ const tokens = Number.isFinite(real) && real > 0 ? real : Math.ceil((key.length + JSON.stringify(toWire(questions)).length) / 4)
+ counters.calls++; counters.tokens += tokens; counters.costUsd = (counters.tokens * PRICE_PER_MTOK) / 1e6
+ jevError = null
+ let n = 0
+ for (const col of need) {
+ const answer = res.answers[col.id]
+ if (!columns.includes(col) || !answer || answer.ok === false) continue
+ cacheFor(col).set(key, { answer, latencyMs: res.latencyMs, tokens })
+ queuePatch(row, col, setCell(row, col, answer, { cached: false, latencyMs: res.latencyMs, tokens }))
+ n++
+ }
+ counters.computed += n
+ const now = Date.now()
+ if (!burst.active) burst = { active: true, startedAt: now - Math.max(1, res.latencyMs), cells: 0, rate: 0, ms: 0 }
+ burst.cells += n; burst.ms = now - burst.startedAt; burst.rate = burst.cells / Math.max(0.03, burst.ms / 1000)
+ if (!hasMissing(row)) todo.delete(row.id)
+ } catch (e) {
+ counters.errors++
+ jevError = clean(e?.message ?? e)
+ row.retryAt = Date.now() + 5000 // leave the cell waiting, show the error, try again in a while (see pump)
+ pushView()
+ } finally {
+ inflight.delete(row)
+ }
+ }
+ function settle() {
+ if (todo.size || inflight.size) return
+ const wasBusy = burst.active
+ burst.active = false
+ if (sort || reviewOnly) computeOrder()
+ flushPatches()
+ if (wasBusy || sort || reviewOnly) pushView()
+ verdictSoon()
+ }
+ function pump() {
+ if (stopped || !running) return
+ while (inflight.size < sheet.concurrency) {
+ const row = nextRow()
+ if (!row) break
+ judgeRow(row, false).then(() => { pump(); settle() })
+ }
+ // Rows that failed are parked for a few seconds. Wake up when the first of them is due.
+ if (todo.size && !retryTimer) {
+ const now = Date.now()
+ let due = Infinity
+ for (const id of todo) { const at = rowById.get(id)?.retryAt ?? 0; if (at > now) due = Math.min(due, at) }
+ if (due < Infinity) retryTimer = setTimeout(() => { retryTimer = null; pump() }, Math.max(50, due - now + 20))
+ }
+ settle()
+ }
+ async function drain() {
+ const worker = async () => { for (let row = nextRow(); row && !stopped; row = nextRow()) await judgeRow(row, true) }
+ await Promise.all(Array.from({ length: sheet.concurrency }, worker))
+ for (let i = 0; inflight.size && i < 400; i++) await sleep(5)
+ settle()
+ }
+
+ // ---- changes -------------------------------------------------------------------------------
+ function changed() { rev++; computeOrder(); pushState(); verdictSoon(); pump() }
+ function addColumn(header, source = 'pane') {
+ const parsed = parseHeader(header)
+ if (!parsed.ok) return { ok: false, error: parsed.error }
+ if (columns.length >= LIMITS.maxColumns) return { ok: false, error: `a sheet holds at most ${LIMITS.maxColumns} Jev columns. Remove one first` }
+ if (colById(parsed.column.id)) return { ok: false, error: `there is already a column called "${parsed.column.name}"` }
+ columns.push({ ...parsed.column, source, addedAt: Date.now() })
+ refill(); changed()
+ return { id: parsed.column.id, type: parsed.column.type }
+ }
+ function removeColumn(id) {
+ const col = colById(id)
+ if (!col) return { ok: false, error: 'no such column' }
+ columns = columns.filter((c) => c !== col)
+ cache.delete(columnKey(col)) // its answers go with it; typing it again asks Jev again
+ if (sort?.col === id) sort = null
+ refill(); changed()
+ return { removed: id }
+ }
+ function editRow(id, text) {
+ const row = rowById.get(id)
+ const next = String(text ?? '').replace(/\s+/g, ' ').trim().slice(0, 4000)
+ if (!row) return { ok: false, error: 'no such row' }
+ if (!next) return { ok: false, error: 'a row needs some text' }
+ if (next === row.text) return { unchanged: true }
+ row.text = next; row.edited = true; row.truth = null; row.retryAt = 0 // the old truth label was for the old text
+ refill(); changed()
+ return { edited: id }
+ }
+ /** sheet.json may name a file in the workspace ("source": "leads.csv"); its rows join the sheet. */
+ function expandSource(raw) {
+ if (!raw || typeof raw !== 'object' || typeof raw.source !== 'string' || !raw.source.trim()) { watchSource(null); sourceInfo = null; sourceError = null; return raw }
+ const got = loadSource(workspace, raw.source.trim(), { textColumn: raw.textColumn, limit: LIMITS.maxRows })
+ sourceInfo = got.info; sourceError = got.error
+ watchSource(got.file)
+ return { ...raw, rows: [...(Array.isArray(raw.rows) ? raw.rows : []), ...got.rows] }
+ }
+ function watchSource(file) {
+ if (file === sourceFile) return
+ sourceWatcher?.close(); sourceWatcher = null; sourceFile = file
+ if (!file) return
+ try { sourceWatcher = watchFile(file, () => { clearTimeout(sourceTimer); sourceTimer = setTimeout(() => { if (!stopped) applySheet(watcher.get(), false) }, 80) }) } catch { /* the file may vanish; the next edit to sheet.json retries */ }
+ }
+ function applySheet(raw, fresh) {
+ const next = normalizeSheet(expandSource(raw))
+ const problems = [sourceError, ...next.errors].filter(Boolean).slice(0, 3).join('; ')
+ if (!next.rows.length && rows.length && !fresh) { configError = `${MARKER}: ${problems || 'needs at least one row with text'}. Showing the last good sheet`; pushView(); verdictSoon(); return }
+ configError = problems ? `${MARKER}: ${problems}` : null
+ sheet = next
+ epoch++
+ rows = next.rows.map((r) => ({ ...r, edited: false, retryAt: 0 }))
+ rowById = new Map(rows.map((r) => [r.id, r]))
+ inflight = new Set()
+ const fileIds = new Set(next.columns.map((c) => c.id))
+ const kept = fresh ? [] : columns.filter((c) => c.source !== 'file' && !fileIds.has(c.id))
+ columns = [...next.columns.map((c) => ({ ...c, source: 'file', addedAt: 0 })), ...kept].slice(0, LIMITS.maxColumns)
+ if (fresh || next.reviewBelow !== fileReviewBelow) reviewBelow = next.reviewBelow
+ if (fresh || next.demo !== fileDemo) ghost.enabled = next.demo
+ fileReviewBelow = next.reviewBelow; fileDemo = next.demo
+ refill(); changed()
+ }
+ function reset() {
+ cache = new Map(); sort = null; reviewOnly = false; jevError = null
+ counters = { calls: 0, cacheHits: 0, tokens: 0, costUsd: 0, errors: 0, computed: 0 }
+ burst = { active: false, startedAt: 0, cells: 0, rate: 0, ms: 0 }
+ patches = []
+ ghost = { ...ghost, phase: 'idle', header: '', pausedUntil: 0, nextAt: Date.now() + 5000, cursor: 0 }
+ applySheet(watcher.get(), true)
+ if (watcher.error()) { configError = `${watcher.error()}. Showing the last good sheet`; pushView() } // still broken on disk
+ }
+
+ // ---- the ghost typist: the demo loop that keeps the pane alive while nobody is playing -------
+ function touch() {
+ ghost.pausedUntil = Date.now() + GHOST_PAUSE_MS
+ if (ghost.phase === 'typing') { ghost.phase = 'idle'; ghost.header = '' }
+ ghost.nextAt = ghost.pausedUntil
+ pushGhost()
+ }
+ const demoColumns = () => columns.filter((c) => c.source === 'demo').sort((a, b) => a.addedAt - b.addedAt)
+ function nextSuggestion() {
+ const list = sheet.suggestions.length ? sheet.suggestions : FALLBACK_SUGGESTIONS
+ for (let i = 0; i < list.length; i++) {
+ const h = list[(ghost.cursor + i) % list.length]
+ const p = parseHeader(h)
+ if (p.ok && !colById(p.column.id)) { ghost.cursor = (ghost.cursor + i + 1) % list.length; return h }
+ }
+ return null
+ }
+ function trimDemo(keep) { const d = demoColumns(); while (d.length > keep) removeColumn(d.shift().id) }
+ function ghostTick() {
+ if (stopped) return
+ const now = Date.now()
+ const watching = (server?.clients.size ?? 0) > 0
+ if (watching && !ghost.watching) ghost.nextAt = Math.max(ghost.pausedUntil, now + 1400) // someone just opened the pane
+ ghost.watching = watching
+ if (!ghost.enabled || !running || !watching) { if (ghost.phase === 'typing') { ghost.phase = 'idle'; pushGhost() } return }
+ if (now < ghost.pausedUntil || todo.size || inflight.size) return
+ if (ghost.phase === 'idle' && now >= ghost.nextAt) {
+ if (columns.length >= LIMITS.maxColumns) trimDemo(0)
+ const h = columns.length < LIMITS.maxColumns ? nextSuggestion() : null
+ if (!h) { trimDemo(0); ghost.nextAt = now + 6000; return }
+ ghost = { ...ghost, phase: 'typing', header: h, startedAt: now, typeMs: Math.min(3600, Math.max(900, h.length * 58)) }
+ pushGhost()
+ } else if (ghost.phase === 'typing' && now >= ghost.startedAt + ghost.typeMs + 420) {
+ const h = ghost.header
+ ghost = { ...ghost, phase: 'dwell', header: '', removeAt: now + 7000 }
+ addColumn(h, 'demo')
+ } else if (ghost.phase === 'dwell' && now >= ghost.removeAt) {
+ trimDemo(1)
+ ghost = { ...ghost, phase: 'idle', nextAt: now + 8500 }
+ pushGhost()
+ }
+ }
+ /** One whole demo cycle at once, with no typing and no waiting. Tests use it. */
+ async function ghostCycle() {
+ const h = nextSuggestion()
+ if (!h) return { ok: false, error: 'no suggestion left to type' }
+ const added = addColumn(h, 'demo')
+ await drain()
+ const before = demoColumns().map((c) => c.id)
+ trimDemo(1)
+ const after = new Set(demoColumns().map((c) => c.id))
+ return { typed: h, added: added.id, removed: before.filter((id) => !after.has(id)) }
+ }
+
+ // ---- inspector -----------------------------------------------------------------------------
+ function inspect(rowId, colId) {
+ const row = rowById.get(rowId), col = colById(colId)
+ if (!row || !col) return { ok: false, error: 'no such cell' }
+ const cell = cellOf(rowId, colId)
+ const wire = toWire({ [col.id]: questionFor(col) })[col.id]
+ return {
+ row: { id: row.id, n: rows.indexOf(row) + 1, text: row.text, meta: row.meta, group: row.group, edited: !!row.edited },
+ column: { id: col.id, header: col.header, name: col.name, type: col.type, options: col.options, descriptions: col.descriptions, levels: col.levels, source: col.source },
+ question: wire, context: sheet.context,
+ cell: cell ? { answer: cell.answer, shown: shown(col, cell.answer), conf: r3(cell.conf), ok: cell.ok, truth: row.truth?.[col.id] ?? null, cached: !!cell.cached, latencyMs: cell.latencyMs, tokens: cell.tokens, flagged: cell.conf < reviewBelow } : null,
+ reviewBelow,
+ }
+ }
+
+ // ---- control -------------------------------------------------------------------------------
+ async function control(cmd, body) {
+ switch (cmd) {
+ case 'pause': running = false; pushView(); return { running }
+ case 'start': running = true; pushView(); pump(); return { running }
+ case 'reset': reset(); return { rev }
+ case 'tick': {
+ // One tick judges exactly one row, with no pacing. { n } runs several ticks in a row.
+ const n = Math.max(1, Math.min(5000, Math.floor(Number(body.n) || 1)))
+ let last = null
+ for (let i = 0; i < n; i++) { const row = nextRow(); if (!row) break; await judgeRow(row, true); last = row.id }
+ flushPatches(); settle()
+ return last == null ? { idle: true } : { row: last }
+ }
+ case 'drain': await drain(); return { filled: tally().stats.cellsFilled }
+ case 'touch': touch(); return null
+ case 'addColumn': { touch(); return addColumn(body.header, 'pane') }
+ case 'removeColumn': { touch(); return removeColumn(String(body.id ?? '')) }
+ case 'editRow': { touch(); return editRow(String(body.id ?? ''), body.text) }
+ case 'sort': {
+ touch()
+ const id = String(body.col ?? '')
+ if (!colById(id)) sort = null
+ else if (body.dir === 'asc' || body.dir === 'desc') sort = { col: id, dir: body.dir }
+ else sort = sort?.col !== id ? { col: id, dir: 'desc' } : sort.dir === 'desc' ? { col: id, dir: 'asc' } : null
+ computeOrder(); pushView(); return { sort }
+ }
+ case 'reviewOnly': touch(); reviewOnly = !!body.on; computeOrder(); pushView(); return { reviewOnly }
+ case 'setReview': {
+ touch()
+ const v = Number(body.value)
+ if (!Number.isFinite(v) || v < 0 || v > 1) return { ok: false, error: 'reviewBelow must be between 0 and 1' }
+ reviewBelow = r3(v)
+ if (reviewOnly) computeOrder()
+ pushView(); verdictSoon(); return { reviewBelow }
+ }
+ case 'demo': ghost.enabled = !!body.on; ghost.pausedUntil = 0; ghost.nextAt = Date.now() + 1200; if (!ghost.enabled && ghost.phase === 'typing') ghost.phase = 'idle'; pushGhost(); return { demo: ghost.enabled }
+ case 'ghost': return ghostCycle()
+ case 'inspect': return inspect(String(body.row ?? ''), String(body.col ?? ''))
+ default: return { ok: false, error: `unknown command "${cmd}"` }
+ }
+ }
+
+ // ---- go ------------------------------------------------------------------------------------
+ watcher = watchConfig(join(workspace, MARKER), {}, (cfg, err) => {
+ if (stopped) return
+ if (err) { configError = `${err}. Showing the last good sheet`; pushView(); verdictSoon(); return }
+ applySheet(cfg, false)
+ })
+ server = await serveViewer({ here: HERE, port, files: ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js', 'grammar.mjs'], state: fullState, control })
+ applySheet(watcher.get(), true)
+ if (watcher.error()) configError = watcher.error()
+ saveVerdict()
+ ghostTimer = setInterval(ghostTick, 200)
+
+ return {
+ url: server.url,
+ async close() {
+ sourceWatcher?.close(); clearTimeout(sourceTimer)
+ stopped = true
+ clearInterval(ghostTimer); clearTimeout(patchTimer); clearTimeout(verdictTimer); clearTimeout(retryTimer)
+ watcher.close()
+ await server.close()
+ },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startSheetsViewer({ workspace, port })
+ console.log(`Jev Sheets listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-shopper/.gitignore b/store/agents/jev-shopper/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-shopper/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-shopper/AGENTS.md b/store/agents/jev-shopper/AGENTS.md
new file mode 100644
index 000000000..862190284
--- /dev/null
+++ b/store/agents/jev-shopper/AGENTS.md
@@ -0,0 +1,84 @@
+# Jev Shopper in OpenHarness
+
+On the left, Jev Shopper is a live shop window: a few products stream price ticks, and **Jev —
+TypeSafe's System One model — is the buyer.** Every tick Jev reads the whole window and calls the
+best buy right now, says how sure it is, and when the signal is strong it spends (on paper). The
+shop is synthetic; the decision loop is the show.
+
+On the right, you edit `shopper.json`. This is the ONLY file you edit. It holds the products (name,
+start price, drift) and the market's volatility; the viewer watches it and Jev adapts immediately.
+
+## The shopper file
+
+```jsonc
+{
+ "title": "Jev Shopper",
+ "description": "Jev watches prices stream in and calls the best buy, live.",
+ "instrument": "SHOPPER",
+ "tickMs": 500,
+ "vol": 0.08,
+ "cash": 100,
+ "products": [
+ { "name": "Espresso Machine", "price": 240, "drift": 0.02 },
+ { "name": "Hiking Boots", "price": 120, "drift": -0.05 },
+ { "name": "Noise Cancellers", "price": 180, "drift": 0.01 },
+ { "name": "Desk Lamp", "price": 45, "drift": -0.03 }
+ ],
+ "style": "Watch the recent price stream and pick the product whose price is most likely still falling — the best value right now. Be decisive."
+}
+```
+
+- **`products[]`** — what's in the window. Each has a `name`, a starting `price`, and an optional
+ `drift` (the persistent daily direction, e.g. `-0.05` = falling ~5% per tick). Products with
+ different drifts give Jev a real spread to read.
+- **`vol`** — price volatility per tick. Low (`0.05`) is calm and Jev reads clean momentum; high
+ (`0.3+`) makes prices jitter so hard Jev's calls start to flip. This is the difficulty dial.
+- **`tickMs`** — how often the prices update (and Jev decides). Fast ticks = a frantic decision
+ rate; slow ticks = a contemplative shop.
+- **`cash`** — the paper budget Jev spends when it acts. Set it to your shop's vibe.
+- **`style`** — the instruction to Jev. It should name a buying strategy (momentum, value, wait)
+ so Jev *decides* rather than guesses.
+
+## Your job
+
+Design `shopper.json` so the shop is an event:
+
+- **Curate a coherent window.** Give it a theme — a coffee lover's cart, a weekend-camp haul, a
+ studio upgrade — with products whose drifts create genuine divergence (some falling, some rising).
+- **Pick a volatility with tension.** `8–12%` vol on mildly-drifted products gives clean, readable
+ calls. Crank `vol` to `0.3+` and watch Jev second-guess itself as prices jitter — that flip is
+ the fun.
+- **Write a distinct style line.** "Buy the steepest faller" plays very differently from "wait for a
+ clear signal" — and Jev will visibly act less.
+
+Do NOT just ship the template. Every `shopper.json` you publish should be its own shop with a
+deliberate, testable market.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the call: does Jev pick the
+product whose price is actually falling, and commit when the signal is decisive — or does it buy a
+riser (bad) or never commit (dull)? Either extreme is a finding to report, not a bug to mask.
+
+## Rules
+
+- Keep `shopper.json` valid JSON always. A bad edit freezes the shop on the last good state. You
+ can change `products` live — the viewer rebuilds the window for the new list.
+- Keep `title`, `description` and `style` truthful — and never present this as real trading, real
+ prices, or real financial advice.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read on a
+ window before you commit to it (e.g. "what does Jev call for this shop?"). Use the `jev`
+ helpers: `noul`, `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the price
+ stream and calls the steepest faller — so the demo runs offline. With a key, the viewer calls the
+ real API.
+- The Jev Shopper viewer writes `.harness/verdict.json` itself (ticks watched, best pick, any
+ commit). Do not edit it.
+- This is a demo. The shop is made up, the prices are synthetic, and Jev spends on paper — never
+ present this as a real store or real trading.
+
+## Definition of done
+
+- A valid `shopper.json` that parses and passes `toolchain/check.mjs`.
+- A shop with a real decision loop: Jev reads the window, calls the falling product, shows
+ confidence, and on a strong signal commits the paper budget.
+- The style and volatility actually shape the calls — report it if Jev picks the same product no
+ matter what, or never commits.
diff --git a/store/agents/jev-shopper/LICENSE b/store/agents/jev-shopper/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-shopper/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-shopper/README.md b/store/agents/jev-shopper/README.md
new file mode 100644
index 000000000..2c2d1bc87
--- /dev/null
+++ b/store/agents/jev-shopper/README.md
@@ -0,0 +1,57 @@
+# Jev Shopper
+
+**Jev — TypeSafe's System One model — is the buyer.** A small shop window streams live prices; every
+tick Jev reads the whole window and calls the best buy right now — the product whose price is still
+falling hardest — shows how sure it is, and spends on paper when the signal is strong. Nudge the
+volatility up and Jev's calls start to flip.
+
+This is a harness for OpenHarness. The agent on the right edits `shopper.json`; the viewer on the
+left runs the shop window and asks Jev for each tick's best-buy call, live. The decision loop is the
+show.
+
+## Anatomy
+
+```
+jev-shopper/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to build shops with real decision loops
+ skills/shopper/SKILL.md # the shop-crafting + verification craft
+ template/shopper.json # a starter shop window
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), shop-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates shopper.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the live shop window)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs the shop over a loopback HTTP server. Each tick it nudges every product's
+price (drift + volatility), asks Jev to pick the best buy and how urgent it is, and streams the live
+price cards (with sparklines), Jev's highlighted pick and confidence, and a decision log to the
+pane. It calls `POST /v1/systemone` when `TYPESAFE_API_KEY` is set; without it a deterministic mock
+reads the same price stream and calls the steepest faller, so the demo runs offline.
+`.harness/verdict.json` tracks ticks watched, the best pick, and any paper commit.
+
+The market is synthetic: each product is a random walk around a persistent `drift`, and `vol` sets
+how jittery the ticks are. Jev's "best buy" is a moment-to-moment momentum call — the product whose
+price is still falling hardest — which is why high volatility makes Jev look indecisive.
+
+## Jev, honestly
+
+Jev's headline claim is speed — decide in a loop faster than a large model can. Shopper celebrates
+that: a decision on every price tick. But the shop and the prices are entirely made up, and Jev
+spends nothing real — this is a demo of decision-rate and calibration on a synthetic signal, not a
+signal for how to shop or trade, and the mock is a stand-in for *plumbing*, not judgement. Treat
+any "buy" call as a fun experiment, not advice.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live shopper — a shop window you can
+watch Jev read, judge, and act on with every tick._
diff --git a/store/agents/jev-shopper/THIRD_PARTY_NOTICES.md b/store/agents/jev-shopper/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-shopper/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-shopper/harness.json b/store/agents/jev-shopper/harness.json
new file mode 100644
index 000000000..e28dbb855
--- /dev/null
+++ b/store/agents/jev-shopper/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-shopper",
+ "name": "Jev Shopper",
+ "category": "Shopping",
+ "author": "Autonomous",
+ "description": "A live price-watching demo. A small shop window streams prices; Jev — TypeSafe's System One model — reads the stream each tick and calls the best buy, showing how sure it is and spending on paper when the signal is strong. Turn up the volatility and watch Jev's calls start to flip.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "shopper.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-shopper/skills/shopper/SKILL.md b/store/agents/jev-shopper/skills/shopper/SKILL.md
new file mode 100644
index 000000000..c2f1da766
--- /dev/null
+++ b/store/agents/jev-shopper/skills/shopper/SKILL.md
@@ -0,0 +1,56 @@
+---
+name: jev-shopper
+description: Design and verify Jev's shop windows in OpenHarness's viewer, where Jev calls the best buy as prices stream in and spends on paper.
+---
+
+# Jev Shopper shop design
+
+Jev Shopper runs a live shop window: a few products stream price ticks and Jev (TypeSafe's System
+One model) reads the window each tick and calls the best buy — the product whose price is still
+falling hardest — showing confidence and spending on paper when the signal is strong. The agent
+shapes `shopper.json` — the products, their drifts, and the market's volatility.
+
+## The loop
+
+1. Update `shopper.json` (title, products with price/drift, vol, tickMs, and a `style` line that
+ tells Jev a buying strategy). The viewer watches it and Jev adapts live — no restart, no second
+ server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `shopper.json` is valid. Run it
+ before you call a shop done.
+3. Watch the window. Does Jev call the falling product, show real confidence, and commit on a clear
+ signal — or buy a riser (bad) or never commit (dull)? That observation is the finding.
+
+## Reading the shop
+
+The viewer shows each product as a price card with a sparkline, Jev's highlighted "best buy" pick
+and confidence, the remaining cash, and a decision log. Good shops produce a readable loop: Jev
+calls the steepest faller, the spread drives its confidence, and when one product clearly out-falls
+the field it commits the budget. `vol` is the difficulty dial — jitter it up and Jev's calls start
+to flip.
+
+## Verifying a shop
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `shopper.json` is invalid (no title,
+fewer than two products, a non-positive price, duplicate names, out-of-range vol/tickMs). It
+doesn't replace watching the calls: confirm Jev picks the product whose price is actually falling
+and commits on a decisive spread, and that cranking `vol` up makes it visibly second-guess.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's read on a
+window before you commit to it:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "Pick the best value. Prices tick live: Espresso Machine: 240.62 (+2.1% over 6 ticks) vol 8% — Hiking Boots: 119.50 (-4.2% over 6 ticks) vol 8% — Desk Lamp: 45.00 (-3.1% over 6 ticks) vol 8%. Which is the best buy to act on now?",
+ questions: {
+ buy: jev.choice(["Espresso Machine", "Hiking Boots", "Desk Lamp"], "Which product is the best buy to act on right now?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-shopper/store.json b/store/agents/jev-shopper/store.json
new file mode 100644
index 000000000..7c05bb0ac
--- /dev/null
+++ b/store/agents/jev-shopper/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev calls the best buy as a shop's prices stream in, live",
+ "examples": [
+ {
+ "prompt": "Set Jev Shopper up as a weekend-camp haul — a few pieces of gear with divergent price drifts. Give Jev a decisive momentum style line, then watch it read the window each tick, call the steepest faller, and commit the paper budget when the signal is clear. Crank the volatility to see its calls start to flip.",
+ "caption": "Jev's Shop — a fast decision model calling the best buy on every live price tick"
+ }
+ ]
+}
diff --git a/store/agents/jev-shopper/template/shopper.json b/store/agents/jev-shopper/template/shopper.json
new file mode 100644
index 000000000..3103d2828
--- /dev/null
+++ b/store/agents/jev-shopper/template/shopper.json
@@ -0,0 +1,15 @@
+{
+ "title": "Jev Shopper",
+ "description": "Jev watches prices stream in and calls the best buy, live.",
+ "instrument": "SHOPPER",
+ "tickMs": 500,
+ "vol": 0.08,
+ "cash": 100,
+ "products": [
+ { "name": "Espresso Machine", "price": 240, "drift": 0.02 },
+ { "name": "Hiking Boots", "price": 120, "drift": -0.05 },
+ { "name": "Noise Cancellers", "price": 180, "drift": 0.01 },
+ { "name": "Desk Lamp", "price": 45, "drift": -0.03 }
+ ],
+ "style": "Watch the recent price stream and pick the product whose price is most likely still falling — the best value right now. Be decisive."
+}
diff --git a/store/agents/jev-shopper/test/viewer.test.mjs b/store/agents/jev-shopper/test/viewer.test.mjs
new file mode 100644
index 000000000..57d15cde7
--- /dev/null
+++ b/store/agents/jev-shopper/test/viewer.test.mjs
@@ -0,0 +1,87 @@
+// Viewer integration test for Jev Shopper. Spins up the real viewer against a temp workspace and
+// checks the loop: prices tick, Jev forms a best-buy call and confidence, the verdict updates, and
+// control commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const CFG = {
+ title: 'Test Shop', instrument: 'SHOPPER', tickMs: 300, vol: 0.08, cash: 100,
+ products: [
+ { name: 'Espresso Machine', price: 240, drift: 0.02 },
+ { name: 'Hiking Boots', price: 120, drift: -0.05 },
+ { name: 'Desk Lamp', price: 45, drift: -0.03 },
+ ],
+ style: 'Pick the best buy.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-shopper-test-'))
+ writeFileSync(join(ws, 'shopper.json'), JSON.stringify({ ...CFG, ...overrides }))
+ const { startShopperViewer } = await import(viewerPath)
+ const viewer = await startShopperViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Shopper ticks prices and Jev forms a best-buy call', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const deadline = Date.now() + 3000
+ let saw = false
+ while (Date.now() < deadline) {
+ await wait(150)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ if (s.step >= 3 && s.history.length > 0) {
+ assert.ok(s.streams.length >= 2)
+ assert.ok(['Espresso Machine', 'Hiking Boots', 'Desk Lamp'].includes(s.lastPick))
+ assert.ok(typeof s.lastConf === 'number')
+ saw = true
+ break
+ }
+ }
+ assert.ok(saw, 'expected prices to tick and Jev to call a buy')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Shopper writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 2000
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Shopper control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-shopper/toolchain/README.md b/store/agents/jev-shopper/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-shopper/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-shopper/toolchain/check.mjs b/store/agents/jev-shopper/toolchain/check.mjs
new file mode 100644
index 000000000..cb4d9812a
--- /dev/null
+++ b/store/agents/jev-shopper/toolchain/check.mjs
@@ -0,0 +1,33 @@
+#!/usr/bin/env node
+// check.mjs — validate a shopper.json for the Jev Shopper harness.
+// Enforces the shape the viewer needs: title, products, tick interval, volatility.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'shopper.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read shopper.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!p.title || typeof p.title !== 'string') bad('warn no title')
+if (!Array.isArray(p.products) || p.products.length < 2) bad('error products must have at least 2 entries')
+for (const [i, prod] of (p.products || []).entries()) {
+ if (!prod || typeof prod.name !== 'string' || !prod.name.trim()) bad(`error products[${i}].name must be a non-empty string`)
+ if (typeof prod.price !== 'number' || prod.price <= 0) bad(`error products[${i}].price must be a positive number`)
+}
+const names = new Set((p.products || []).map((x) => x.name))
+if (names.size !== (p.products || []).length) bad('error product names must be unique')
+if (typeof p.tickMs !== 'number' || p.tickMs < 100 || p.tickMs > 5000) bad('error tickMs must be ms 100..5000')
+if (typeof p.vol !== 'number' || p.vol < 0 || p.vol > 0.5) bad('error vol must be a rate 0..0.5 per tick')
+if (!p.style || typeof p.style !== 'string') bad('warn a style line helps Jev buy coherently')
+
+console.log(fail ? 'fail invalid shopper.json' : 'ok shopper.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-shopper/toolchain/doctor.sh b/store/agents/jev-shopper/toolchain/doctor.sh
new file mode 100755
index 000000000..ec9056c5c
--- /dev/null
+++ b/store/agents/jev-shopper/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Shopper viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-shopper/toolchain/init-workspace.sh b/store/agents/jev-shopper/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-shopper/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-shopper/toolchain/jev.mjs b/store/agents/jev-shopper/toolchain/jev.mjs
new file mode 100644
index 000000000..2eb5a7259
--- /dev/null
+++ b/store/agents/jev-shopper/toolchain/jev.mjs
@@ -0,0 +1,634 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+/**
+ * Pendulum-balancing read used by the mock when the state text carries the current pole angle and
+ * angular velocity (the viewer renders e.g. "angle: +12° velocity: -0.8 rad/s"). We compute the
+ * corrective action the pole is asking for: lean/fall to the right (positive angle) wants a
+ * leftward torque, and also damp any velocity. Returns per-action boosts so the deterministic mock
+ * biases toward the right call while staying slightly noisy — so Jev can fail when it's sloppy and
+ * the fall reads as Jev's mistake. Real Jev reads the same text — the mock is a stand-in.
+ */
+function pendulumRead(text) {
+ const mA = text.match(/angle:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const mV = text.match(/velocity:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const deg = mA ? Number(mA[1]) : NaN
+ const vel = mV ? Number(mV[1]) : NaN
+ if (!Number.isFinite(deg) || !Number.isFinite(vel)) return null
+ const a = (deg * Math.PI) / 180
+ // desired torque = -(Kp*a + Kv*vel); pick the action whose torque is closest.
+ const want = -(6.5 * a + 3.2 * vel)
+ const ACTS = { LEFT_HARD: -1.6, LEFT: -0.8, CENTER: 0, RIGHT: 0.8, RIGHT_HARD: 1.6 }
+ const boost = {}
+ for (const [name, t] of Object.entries(ACTS)) {
+ boost[name] = 1.4 - Math.abs(t - Math.max(-1.6, Math.min(1.6, want))) * 0.9
+ }
+ // The mock can't see the gravity dial — it just balances. But a fast judge on a hard
+ // rig will hesitate more, so the misjudgement rate rises with how hard the balance is.
+ // Low gravity: calm, near-perfect. High gravity: it starts to overshoot and lose it.
+ const hard = (parseFloat((text.match(/hardness:\s*([0-9.]+)/i) || [null, '0'])[1]) || 0)
+ const noise = Math.min(0.55, 0.03 + hard * 0.06)
+ return { boost, noise }
+}
+
+/**
+ * Pong-defender read used by the mock when the state text carries a ball position/velocity and the
+ * paddle's centre. We predict where the ball will cross the paddle's wall (reflecting off floor and
+ * ceiling) and bias the paddle move toward that intercept, with a reaction that degrades as the ball
+ * gets faster. Returns per-move boosts plus a beta error chance so Jev can visibly lose a fast rally.
+ */
+function pongRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/ball:\s*x\s+([-0-9.]+)/i)
+ const y = num(/y\s+([-0-9.]+)\s+vx/i)
+ const vx = num(/vx\s+([-0-9.]+)\s+vy/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const paddleY = num(/centre y\s+([-0-9.]+)/i)
+ const half = num(/half-height\s+([-0-9.]+)/i)
+ const courtH = num(/court:\s*[-0-9.]+\s*[x×]\s*([-0-9.]+)/i)
+ const speed = num(/speed:\s*([-0-9.]+)/i)
+ if (![x, y, vx, vy, paddleY, half, courtH, speed].every(Number.isFinite)) return null
+ const r = 3
+ const span = courtH - 2 * r
+ // When the ball is moving away (rightward), the paddle's job is to stop chasing and hold still so
+ // it's framed to meet the ball when it comes back — letting the rally breathe.
+ if (vx >= 0) return { boost: { HOLD: 1.9, MOVE_UP: 0.7, MOVE_DOWN: 0.7, MOVE_UP_FAST: 0.3, MOVE_DOWN_FAST: 0.3 }, noise: 0, close: false }
+ // time (in ball steps) to reach the left wall
+ const t = -x / vx
+ const dy = vy * t
+ let u = ((y - r + dy) % (2 * span) + 2 * span) % (2 * span)
+ u = u <= span ? u : 2 * span - u
+ const ty = r + u
+ const want = ty - paddleY
+ const goDown = want > half * 0.5
+ const goUp = want < -half * 0.5
+ const boost = {}
+ for (const name of ['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST']) {
+ if (goDown) boost[name] = name === 'MOVE_DOWN' ? 1.8 : name === 'MOVE_DOWN_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else if (goUp) boost[name] = name === 'MOVE_UP' ? 1.8 : name === 'MOVE_UP_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else boost[name] = name === 'HOLD' ? 1.8 : 0.8
+ }
+ // faster ball → the intercept at the wall changes fast and the paddle has fewer ticks to reach it,
+ // so the physical difficulty (max paddle speed) does the work. No injected noise: a miss is honest.
+ return { boost }
+}
+
+/**
+ * Shopper read used by the mock when the state text carries the recent price stream for each
+ * product (the viewer renders "Name: price (+x% over N ticks) vol v% [spark]"). We score each
+ * product by how fast its price is still falling — the best value right now — and bias the "best
+ * buy" choice toward the steepest falling momentum, plus a confidence that depends on how far the
+ * top pick stands out. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function shopperRead(text) {
+ const picks = []
+ const re = /^\s*([^:\n]+?):\s*([0-9.]+)\s*\(\s*([+-][0-9.]+)% over (\d+) ticks\)\s*vol\s*([0-9.]+)%\s*\[([^\]]*)\]/gim
+ let m
+ while ((m = re.exec(text))) {
+ const name = m[1].trim()
+ const price = Number(m[2])
+ const chgPct = Number(m[3])
+ picks.push({ name, price, chgPct })
+ }
+ if (picks.length < 2) return null
+ // best value = most negative recent change (still falling the fastest)
+ const sorted = picks.slice().sort((a, b) => a.chgPct - b.chgPct)
+ const best = sorted[0]
+ const second = sorted[1]
+ const spread = second.chgPct - best.chgPct
+ const boost = {}
+ for (const p of picks) boost[p.name] = p.name === best.name ? 1.6 : p.name === second.name ? 0.9 : 0.2
+ // confidence: strong when the leader clearly out-falls the rest; weak when it's a dead heat
+ const confidence = Math.min(0.95, Math.max(0.15, 0.5 + spread * 0.6))
+ return { boost, confidence, best: best.name }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ // Shopper: "act now" is urgent when the best buy clearly out-falls the field. Ask Jev to spend
+ // when the momentum spread is wide, so the demo eventually commits on paper.
+ if (/act now|spend now|strong enough/i.test(qtext) || /buy|act/i.test(q.instructions)) {
+ const shop = shopperRead(text)
+ if (shop && shop.confidence) p = Math.max(p, Math.min(0.9, 0.4 + shop.confidence * 0.5))
+ }
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Pendulum: if the state carries an angle + angular velocity, bias toward the balancing action,
+ // and occasionally flip to a neighbour (a fast model that sometimes hesitates) so the pole can
+ // visibly wobble — that wiggle is the demo.
+ const pen = pendulumRead(text)
+ if (pen) {
+ options.forEach((opt, i) => {
+ const b = pen.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (pen.noise && (hash01('pen', salt + 9) < pen.noise)) {
+ // flip the current best to two neighbours over — a big, costly overcorrection
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + (hash01('dir', salt) < 0.5 ? -2 : 2)))
+ if (ni !== best.i) raw[ni] += 2.2
+ }
+ }
+ // Pong: if the state text carries a ball + paddle, steer the paddle to the predicted intercept,
+ // and lag harder (miss more) as the ball speeds up.
+ const pong = pongRead(text)
+ if (pong) {
+ options.forEach((opt, i) => {
+ const b = pong.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Shopper: if the state carries a product price stream, bias "best buy" toward the product
+ // whose price is still falling the fastest.
+ const shop = shopperRead(text)
+ if (shop) {
+ options.forEach((opt, i) => {
+ const b = shop.boost[String(opt).toLowerCase()]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-shopper/toolchain/setup.sh b/store/agents/jev-shopper/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-shopper/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-shopper/toolchain/viewer.sh b/store/agents/jev-shopper/toolchain/viewer.sh
new file mode 100755
index 000000000..e37e9490e
--- /dev/null
+++ b/store/agents/jev-shopper/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Shopper viewer (Jev calls the best buy as prices stream in, live).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-shopper/viewer/index.html b/store/agents/jev-shopper/viewer/index.html
new file mode 100644
index 000000000..c276f9742
--- /dev/null
+++ b/store/agents/jev-shopper/viewer/index.html
@@ -0,0 +1,51 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Shopper</title>
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Shopper</h1></div>
+ <div class="stats">
+ <div class="stat"><label>Ticks</label><span id="ticks">0</span></div>
+ <div class="stat"><label>Best buy</label><span id="pick">—</span></div>
+ <div class="stat"><label>Sure</label><span id="sure">—</span></div>
+ <div class="stat"><label>Cash</label><span id="cash">100</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="tick">Step</button>
+ <button class="primary" id="reset">Reset</button>
+ </div>
+ </div>
+ <main>
+ <section id="stage">
+ <div class="panel">
+ <div class="panel-title">The shop window</div>
+ <div id="shelf"></div>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Jev, the buyer</div>
+ <div class="how">
+ Each product streams a live price. On every tick Jev reads the whole window and calls
+ <b>the best buy now</b> — the one whose price is still falling hardest — and says how sure
+ it is. When it's sure enough, it spends on paper.<br><br>
+ Edit <code>shopper.json</code>: tune <code>vol</code> to wobble the prices faster (harder
+ calls), or rewrite <code>products</code> for a new shop window.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Decisions</div>
+ <ul id="log"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-shopper/viewer/jev-hud.js b/store/agents/jev-shopper/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-shopper/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-shopper/viewer/studio.css b/store/agents/jev-shopper/viewer/studio.css
new file mode 100644
index 000000000..53507e596
--- /dev/null
+++ b/store/agents/jev-shopper/viewer/studio.css
@@ -0,0 +1,73 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #f59e0b; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #17140c 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(32,26,14,.9), rgba(16,14,10,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#ticks { color: var(--dim); }
+#pick { color: var(--cyan); }
+#sure { color: var(--amber); }
+#cash { color: var(--ok); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #b45309, #f59e0b); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+
+#shelf { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px; }
+.card {
+ background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 14px;
+ transition: border-color .2s, box-shadow .2s;
+}
+.card.picked { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), 0 0 24px rgba(245,158,11,.15); }
+.card.bought { border-color: var(--ok); box-shadow: 0 0 0 1px var(--ok); }
+.card h3 { margin: 0 0 2px; font-size: 14px; color: var(--ink); }
+.card .price { font-size: 20px; font-weight: 700; }
+.card .chg { font-size: 12px; }
+.card .chg.up { color: var(--rose); }
+.card .chg.down { color: var(--ok); }
+.card .spark { width: 100%; height: 44px; margin-top: 6px; }
+.card .tag { display: inline-block; margin-top: 8px; font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px; display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(28,24,14,.5); }
+.how { color: var(--dim); font-size: 13px; line-height: 1.5; }
+.how b { color: var(--amber); }
+.how code { color: var(--cyan); }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 50vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 8px; align-items: baseline; }
+#log li .n { color: var(--accent); }
+#log li .p { color: var(--cyan); font-weight: 700; }
+#log li .s { color: var(--amber); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-shopper/viewer/studio.js b/store/agents/jev-shopper/viewer/studio.js
new file mode 100644
index 000000000..acc48248e
--- /dev/null
+++ b/store/agents/jev-shopper/viewer/studio.js
@@ -0,0 +1,106 @@
+// Jev Shopper pane — draws the shop window of live price cards with sparklines, highlights Jev's
+// current best-buy call, and logs each decision. The price cards are the show; Jev's pick is the
+// beat.
+
+const $ = (id) => document.getElementById(id)
+const els = { ticks: $('ticks'), pick: $('pick'), sure: $('sure'), cash: $('cash'), shelf: $('shelf'), log: $('log') }
+
+let streams = []
+let cash = 100
+let lastPick = '—'
+let lastConf = 0
+let lastAct = 0
+let history = []
+let ticks = 0
+let bought = new Set()
+
+function spark(canvas, series) {
+ const ctx = canvas.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = canvas.clientWidth, H = canvas.clientHeight
+ canvas.width = W * dpr; canvas.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+ if (series.length < 2) { ctx.fillStyle = '#4b5266'; ctx.font = '9px monospace'; ctx.fillText('…', 4, 10); return }
+ const lo = Math.min(...series), hi = Math.max(...series)
+ const span = (hi - lo) || 1
+ const pad = 2
+ ctx.strokeStyle = '#f59e0b'; ctx.lineWidth = 1.5
+ ctx.beginPath()
+ series.forEach((v, i) => {
+ const x = pad + (i / (series.length - 1)) * (W - 2 * pad)
+ const y = pad + (1 - (v - lo) / span) * (H - 2 * pad)
+ i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)
+ })
+ ctx.stroke()
+}
+
+function renderShelf() {
+ els.shelf.textContent = ''
+ for (const s of streams) {
+ const card = document.createElement('div')
+ card.className = 'card' + (s.name === lastPick ? ' picked' : '') + (bought.has(s.name) ? ' bought' : '')
+ const series = s.series || []
+ const first = series[0], last = series[series.length - 1]
+ const chg = first && last ? ((last - first) / first * 100) : 0
+ const up = chg >= 0
+ card.innerHTML = `
+ <h3>${esc(s.name)}</h3>
+ <div class="price">${(last ?? 0).toFixed(2)}</div>
+ <div class="chg ${up ? 'up' : 'down'}">${up ? '▲' : '▼'} ${Math.abs(chg).toFixed(1)}%</div>
+ <canvas class="spark"></canvas>
+ <div class="tag">${bought.has(s.name) ? 'bought for ' + last.toFixed(0) : s.name === lastPick ? 'best buy now' : 'watching'}</div>`
+ els.shelf.appendChild(card)
+ spark(card.querySelector('.spark'), series)
+ }
+}
+
+function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])) }
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history.slice(-30)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="n">#${h.step}</span><span class="p">${esc(h.buy)}</span><span class="s">${(h.conf * 100).toFixed(0)}%</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function onTick(msg) {
+ if (Array.isArray(msg.streams)) {
+ streams = msg.streams
+ for (const s of msg.committed || []) bought.add(s.name)
+ }
+ cash = msg.cash ?? cash
+ lastPick = msg.lastPick || lastPick
+ lastConf = msg.lastConf ?? lastConf
+ lastAct = msg.lastAct ?? lastAct
+ history = msg.history || history
+ ticks = msg.step ?? ticks
+
+ els.ticks.textContent = String(ticks)
+ els.pick.textContent = lastPick
+ els.sure.textContent = (lastConf * 100).toFixed(0) + '%'
+ els.cash.textContent = String(Math.round(cash))
+ renderShelf()
+ renderLog()
+}
+
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+window.addEventListener('resize', renderShelf)
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-shopper/viewer/viewer.mjs b/store/agents/jev-shopper/viewer/viewer.mjs
new file mode 100644
index 000000000..91f0ad66f
--- /dev/null
+++ b/store/agents/jev-shopper/viewer/viewer.mjs
@@ -0,0 +1,251 @@
+// Jev Shopper viewer — a loopback server running a live price-tracking demo. A few products stream
+// price ticks; Jev (TypeSafe's System One model) reads the stream and, every tick, decides which
+// product is the best buy right now (and how urgent it is). The agent shapes shopper.json (the
+// products, their price ranges, how fast they tick) — turn the volatility up and watch Jev's calls
+// start to flip. The market is synthetic; the decision loop is the demo.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds shopper.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT = {
+ title: 'Jev Shopper',
+ description: 'Jev watches prices stream in and calls the best buy, live.',
+ instrument: 'SHOPPER',
+ tickMs: 500, vol: 0.08, cash: 100,
+ products: [
+ { name: 'Espresso Machine', price: 240, drift: 0.02 },
+ { name: 'Hiking Boots', price: 120, drift: -0.05 },
+ { name: 'Noise Cancellers', price: 180, drift: 0.01 },
+ { name: 'Desk Lamp', price: 45, drift: -0.03 },
+ ],
+ style: 'Watch the recent price stream and pick the product whose price is most likely still falling — the best value right now. Be decisive.',
+}
+
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+// Manufacture a plausible synthetic price stream line so Jev (and the mock reader) can see momentum.
+function streamLine(product, prices, vol) {
+ const recent = prices.slice(-6)
+ const chgPct = (recent.length >= 2) ? ((recent[recent.length - 1] - recent[0]) / recent[0] * 100) : 0
+ const last = recent[recent.length - 1]
+ const spark = recent.map((p) => p.toFixed(0)).join(' ')
+ return `${product.name}: ${last.toFixed(2)} (${chgPct >= 0 ? '+' : ''}${chgPct.toFixed(1)}% over ${recent.length} ticks) vol ${(vol * 100).toFixed(0)}% [${spark}]`
+}
+
+function stateBlock(p, streams, cash) {
+ const lines = streams.map((s) => streamLine(s.product, s.prices, p.vol)).join('\n')
+ return `${p.style}
+You have ${cash.toFixed(0)} to spend. Prices tick live:
+${lines}
+Which single product is the best buy to act on right now?`
+}
+
+export async function startShopperViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let error = null
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let step = 0
+ let running = false
+ let cash = (DEFAULT.cash ?? 100)
+ let picks = [] // per-decision {step, buy, conf, act}
+ let lastPick = '—'
+ let lastConf = 0.5
+ let lastAct = 0.5
+ let committed = [] // {name, cash, price} after an "act now"
+ let notified = false // a buy was committed this window
+
+ // read the config file, merging over defaults; also handles a changed product list
+ let p = readCfg(join(workspace, 'shopper.json'))
+ let rng = mulberry32(616)
+ let streams = (p.products || []).map((prod) => ({ product: prod, prices: [prod.price], drift: prod.drift ?? 0 }))
+
+ function readCfg(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ return { ...DEFAULT, ...raw }
+ } catch (e) {
+ error = clean(e.message)
+ return p || DEFAULT
+ }
+ }
+
+ function resetState() {
+ streams = (p.products || []).map((prod) => ({ product: prod, prices: [prod.price], drift: prod.drift ?? 0 }))
+ cash = p.cash ?? 100
+ picks = []; committed = []; notified = false; step = 0
+ lastPick = '—'; lastConf = 0.5; lastAct = 0.5
+ }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ const best = picks.reduce((a, b) => (b.conf > a.conf ? b : a), { conf: 0 })
+ return {
+ spec: 1,
+ ready: picks.length > 0,
+ summary: error
+ ? 'Jev Shopper needs a fix'
+ : notified && committed.length
+ ? `${p.title} · bought ${committed[committed.length - 1].name} for ${committed[committed.length - 1].price.toFixed(0)} · ${picks.length} ticks watched`
+ : `${p.title} · watching ${streams.length} products · ${picks.length} ticks · best pick ${best.buy || '—'} at ${(best.conf * 100).toFixed(0)}%`,
+ findings: (error ? [{ severity: 'error', kind: 'shopper', message: error }] : []).concat(
+ notified ? [{ severity: 'info', kind: 'shopper', message: `Jev decided to buy ${committed[committed.length - 1].name} at ${committed[committed.length - 1].price.toFixed(0)}` }] : []
+ ),
+ artifact: 'shopper.json',
+ phases: [
+ { id: 'learn', name: 'Watching', state: picks.length < 5 ? 'active' : 'done' },
+ { id: 'call', name: 'Calling buys', state: picks.length >= 5 && !notified ? 'active' : notified ? 'done' : 'pending' },
+ { id: 'commit', name: 'Committed', state: notified ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick', title: p.title, description: p.description, instrument: p.instrument,
+ streams: streams.map((s) => ({ name: s.product.name, price: s.prices[s.prices.length - 1], series: s.prices.slice(-40) })),
+ cash, step, running, error, lastPick, lastConf, lastAct, committed,
+ history: picks.slice(-120),
+ })
+ }
+
+ function reset() { resetState(); tail(); if (running) schedule() }
+ function pause() { running = false; clearTimeout(timer) }
+ function start() { if (!running) { running = true; schedule() } }
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, p.tickMs) }
+ async function run() { if (stopped) return; await decide(); schedule() }
+
+ function tickPrices() {
+ for (const s of streams) {
+ const last = s.prices[s.prices.length - 1]
+ const drift = s.drift ?? 0
+ const shock = (rng() - 0.5) * 2 * (p.vol ?? 0.08)
+ const next = Math.max(1, last * (1 + drift + shock))
+ s.prices.push(next)
+ if (s.prices.length > 40) s.prices.shift()
+ }
+ step++
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ tickPrices()
+ const res = await evaluate({
+ state: stateBlock(p, streams, cash),
+ questions: {
+ buy: { type: 'choice', instructions: 'Which product is the best buy to act on right now?', options: streams.map((s) => s.product.name) },
+ act: { type: 'noul', instructions: 'Is this a strong enough signal to spend now?' },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ lastPick = String(res.answers.buy?.choice || '—')
+ lastConf = typeof res.answers.buy?.confidence === 'number' ? res.answers.buy.confidence : 0.5
+ lastAct = typeof res.answers.act?.noul === 'number' ? res.answers.act.noul : 0.5
+ picks.push({ step, buy: lastPick, conf: lastConf, act: lastAct })
+ if (picks.length > 300) picks.splice(0, picks.length - 300)
+ if (lastAct >= 0.8 && cash > 0 && lastPick !== '—' && !notified) {
+ const sold = streams.find((s) => s.product.name === lastPick)
+ if (sold) {
+ const price = sold.prices[sold.prices.length - 1]
+ committed.push({ name: lastPick, cash: cash, price })
+ cash = 0
+ notified = true
+ }
+ }
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ const watcher = watch(join(workspace, 'shopper.json'), () => {
+ p = readCfg(join(workspace, 'shopper.json'))
+ tail()
+ if (running) schedule()
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: p.title, instrument: p.instrument, streams: streams.map((s) => ({ name: s.product.name, price: s.prices[s.prices.length - 1], series: s.prices.slice(-40) })), cash, step, running, error, lastPick, lastConf, lastAct, committed, history: picks.slice(-120) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ resetState()
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startShopperViewer({ workspace, port })
+ console.log(`Jev Shopper listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-slalom/.gitignore b/store/agents/jev-slalom/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-slalom/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-slalom/AGENTS.md b/store/agents/jev-slalom/AGENTS.md
new file mode 100644
index 000000000..09d6589fc
--- /dev/null
+++ b/store/agents/jev-slalom/AGENTS.md
@@ -0,0 +1,80 @@
+# Jev Slalom in OpenHarness
+
+On the left, Jev Slalom is a course: a line of gates sweeps down a valley, and **Jev — TypeSafe's
+System One model — is the racer.** Every tick Jev reads its position and the next gate, and steers
+left or right to thread each gap. Clip a gate or hit the wall and the run is over. The course is
+synthetic; the decision loop is the show.
+
+On the right, you edit `slalom.json`. This is the ONLY file you edit. It holds the run profile — the
+descent speed, the valley width, how many gates — and the viewer watches it and Jev adapts
+immediately.
+
+## The slalom file
+
+```jsonc
+{
+ "title": "Jev Slalom",
+ "description": "Jev is the racer — carve a slalom line and thread every gate.",
+ "instrument": "SLALOM",
+ "tickMs": 160,
+ "speed": 2.2,
+ "gates": 18,
+ "valleyWidth": 18,
+ "style": "You are skiing the slalom. A line of gates sweeps toward you as you descend — steer left and right to thread each gap, lining up early and committing as each gate arrives. Clip a gate or hit the wall and you fall. Clean, decisive turns win the run."
+}
+```
+
+- **`speed`** — how many course-rows the skier descends per tick. This is the difficulty dial.
+ Calm (`1.6`) gives Jev time to line up and it threads everything; high (`3.0+`) makes the gates
+ arrive so fast Jev's aim wobbles and it clips a gate and falls.
+- **`gates`** — how many gates in the run (2–60). More gates = a longer run with more chances to
+ fall and a bigger payoff for a clean line.
+- **`valleyWidth`** — the width of the course in slots (6–60). Wider = more room to swing; narrower
+ = the skier rides closer to the walls.
+- **`tickMs`** — how often the world updates (and Jev decides). Fast ticks = frantic carving; slow
+ ticks = a contemplative descent.
+- **`style`** — the instruction to Jev. It should name a line strategy (line up early, commit, hug
+ the apex) so Jev *decides* rather than guesses.
+
+## Your job
+
+Design `slalom.json` so the run is an event:
+
+- **Curate a course with tension.** Default `speed` around `2.0–2.4` gives clean, readable carving.
+ Crank it to `3+` and Jev starts to wobble and fall — that flip is the fun.
+- **Pick a run length.** Short runs (10 gates) are over almost instantly; longer ones (24+) give Jev
+ time to build a rhythm and more chances to fall.
+- **Write a distinct style line.** "Line up early and commit" plays very differently from "sweep
+ wide and drift through" — and Jev will visibly carve differently.
+
+Do NOT just ship the template. Every `slalom.json` you publish should be its own run with a
+deliberate, testable course.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the run: does Jev thread every
+gate at the speed you set, and fall when you crank it up — or does it never fall (dull) or fall even
+at calm speed (bad)? Either extreme is a finding to report, not a bug to mask.
+
+## Rules
+
+- Keep `slalom.json` valid JSON always. A bad edit freezes the run on the last good state. You can
+ change `speed`/`gates`/`valleyWidth` live — the viewer rebuilds the course for the new profile.
+- Keep `title`, `description` and `style` truthful — and never present this as a real ski event,
+ real race timing, or real coaching.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read before you
+ commit to it (e.g. "which way does Jev steer with 2 ticks to the gate?"). Use the `jev` helpers:
+ `noul`, `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the course
+ and lines up on the next gate — so the demo runs offline. With a key, the viewer calls the real
+ API.
+- The Jev Slalom viewer writes `.harness/verdict.json` itself (ticks carved, gates threaded, any
+ fall). Do not edit it.
+- This is a demo. The skier, the course and the timing are made up — never present this as a real
+ race or real coaching.
+
+## Definition of done
+
+- A valid `slalom.json` that parses and passes `toolchain/check.mjs`.
+- A course with a real decision loop: Jev reads the next gate, steers to thread it, and on a calm
+ run carves a clean line — and falls when speed is cranked up.
+- The speed and style actually shape the line — report it if Jev never falls, or falls no matter
+ what.
diff --git a/store/agents/jev-slalom/LICENSE b/store/agents/jev-slalom/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-slalom/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-slalom/README.md b/store/agents/jev-slalom/README.md
new file mode 100644
index 000000000..106c5cf97
--- /dev/null
+++ b/store/agents/jev-slalom/README.md
@@ -0,0 +1,56 @@
+# Jev Slalom
+
+**Jev — TypeSafe's System One model — is the racer.** A line of gates sweeps down a valley; every
+tick Jev reads its position and the next gate and steers — LEFT / RIGHT, or a FAST commit — to
+thread each gap as it arrives. Clip a gate or hit the wall and the run is over. Crank the descent
+speed up and Jev's aim starts to wobble and it falls.
+
+This is a harness for OpenHarness. The agent on the right edits `slalom.json`; the viewer on the
+left runs the course and asks Jev for each tick's steer, live. The decision loop is the show.
+
+## Anatomy
+
+```
+jev-slalom/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to build courses with real decision loops
+ skills/slalom/SKILL.md # the course-design + verification craft
+ template/slalom.json # a starter run profile
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), slalom-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates slalom.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (the course)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs the course over a loopback HTTP server. Each tick it advances the skier
+down the valley, asks Jev for the steer, and streams the run — the skier's x and snow trail, the
+gates sweeping toward it (lighting up as they're threaded), a dashed line to the target gate, and a
+run log — to the pane. It calls `POST /v1/systemone` when `TYPESAFE_API_KEY` is set; without it a
+deterministic mock reads the same course and lines up on the next gate, so the demo runs offline.
+`.harness/verdict.json` tracks ticks carved, gates threaded, and any fall.
+
+The course is synthetic: gates alternate sides of a valley, and the skier descends at a fixed
+`speed`. Jev's "steer" is a moment-to-moment line call — line up on the gate, commit as it arrives —
+which is why high speed makes Jev look wobbly and fall.
+
+## Jev, honestly
+
+Jev's headline claim is speed — decide in a loop faster than a large model can. Slalom celebrates
+that: a steering decision on every tick. But the skier, the course and the timing are entirely made
+up, and Jev races nothing real — this is a demo of decision-rate and calibration on a synthetic
+line-following problem, not a signal for real racing, and the mock is a stand-in for *plumbing*, not
+judgement. Treat any "run" as a fun experiment, not coaching advice.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a fast decision model a live slalom racer — a course you can
+watch Jev carve, judge, and thread with every tick._
diff --git a/store/agents/jev-slalom/THIRD_PARTY_NOTICES.md b/store/agents/jev-slalom/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-slalom/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-slalom/harness.json b/store/agents/jev-slalom/harness.json
new file mode 100644
index 000000000..7eeb7b2db
--- /dev/null
+++ b/store/agents/jev-slalom/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-slalom",
+ "name": "Jev Slalom",
+ "category": "Sports",
+ "author": "Autonomous",
+ "description": "A live skiing demo. Jev — TypeSafe's System One model — is the racer, carving a slalom line as the gates sweep toward it, steering left and right to thread each gap. Crank the descent speed up and Jev's aim starts to wobble and it clips a gate and falls.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "slalom.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-slalom/skills/slalom/SKILL.md b/store/agents/jev-slalom/skills/slalom/SKILL.md
new file mode 100644
index 000000000..d1873720e
--- /dev/null
+++ b/store/agents/jev-slalom/skills/slalom/SKILL.md
@@ -0,0 +1,54 @@
+---
+name: jev-slalom
+description: Design and verify Jev's slalom courses in OpenHarness's viewer, where Jev is the racer steering to thread every gate.
+---
+
+# Jev Slalom course design
+
+Jev Slalom runs a live course: a line of gates sweeps down a valley and Jev (TypeSafe's System One
+model) reads its position and the next gate each tick and steers left/right to thread each gap. The
+agent shapes `slalom.json`: the descent speed, the valley width, and how many gates.
+
+## The loop
+
+1. Update `slalom.json` (title, speed, gates, valleyWidth, a `style` line that tells Jev a line
+ strategy). The viewer watches it and Jev adapts live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `slalom.json` is valid. Run it
+ before you call a run done.
+3. Watch the descent. Does Jev line up on the next gate, commit as it arrives, and thread a clean
+ run — or never fall (dull) or fall even at calm speed (bad)? That observation is the finding.
+
+## Reading the run
+
+The viewer shows a top-down course: the skier descends with a snow trail, gates sweep toward it and
+light up green as they're threaded, a dashed line marks the target gate, and a finished run shows a
+CLEAN RUN or FELL banner plus a run log. Good courses produce a readable loop: Jev carves across the
+valley to the next gate, threads it, and builds a rhythm; `speed` is the difficulty dial — crank it
+up and Jev's aim wobbles and it clips a gate and falls.
+
+## Verifying a course
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `slalom.json` is invalid (no title, a
+non-positive speed, out-of-range gates/valleyWidth/tickMs). It doesn't replace watching the run:
+confirm Jev threads the gates at the speed you set, and that cranking `speed` up makes it visibly
+fall.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's read on a
+gate before you commit to it:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "You are skiing the slalom. The skier descends at 3.0 rows/tick. Next gate: x 14.5, gap 6.0. skier x 9.0 gate x 14.5 gate in 1.2. Which way do you steer? LEFT_FAST / LEFT / HOLD / RIGHT / RIGHT_FAST",
+ questions: {
+ steer: jev.choice(["LEFT_FAST", "LEFT", "HOLD", "RIGHT", "RIGHT_FAST"], "Which way do you steer this tick?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-slalom/store.json b/store/agents/jev-slalom/store.json
new file mode 100644
index 000000000..90bb32efa
--- /dev/null
+++ b/store/agents/jev-slalom/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev skis the slalom, threading each gate as it sweeps by, live",
+ "examples": [
+ {
+ "prompt": "Set Jev Slalom up as a hard run — push the descent speed up near the limit. Give Jev a decisive line-up-early style, then watch it read the next gate every tick, carve the valley, thread every gate (or clip one and fall when the speed gets too hot).",
+ "caption": "Jev's Run — a fast decision model carving a slalom line and threading each gate on every tick"
+ }
+ ]
+}
diff --git a/store/agents/jev-slalom/template/slalom.json b/store/agents/jev-slalom/template/slalom.json
new file mode 100644
index 000000000..7425a4a4f
--- /dev/null
+++ b/store/agents/jev-slalom/template/slalom.json
@@ -0,0 +1,10 @@
+{
+ "title": "Jev Slalom",
+ "description": "Jev is the racer — carve a slalom line and thread every gate.",
+ "instrument": "SLALOM",
+ "tickMs": 160,
+ "speed": 2.2,
+ "gates": 18,
+ "valleyWidth": 18,
+ "style": "You are skiing the slalom. A line of gates sweeps toward you as you descend — steer left and right to thread each gap, lining up early and committing as each gate arrives. Clip a gate or hit the wall and you fall. Clean, decisive turns win the run."
+}
diff --git a/store/agents/jev-slalom/test/viewer.test.mjs b/store/agents/jev-slalom/test/viewer.test.mjs
new file mode 100644
index 000000000..c5517a4f5
--- /dev/null
+++ b/store/agents/jev-slalom/test/viewer.test.mjs
@@ -0,0 +1,82 @@
+// Viewer integration test for Jev Slalom. Spins up the real viewer against a temp workspace and
+// checks the loop: the skier descends, Jev steers, the verdict updates, and control commands answer.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const CFG = {
+ title: 'Test Run', instrument: 'SLALOM', tickMs: 100, speed: 2.0, gates: 10, valleyWidth: 18,
+ style: 'Thread the gates.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-slalom-test-'))
+ writeFileSync(join(ws, 'slalom.json'), JSON.stringify({ ...CFG, ...overrides }))
+ const { startSlalomViewer } = await import(viewerPath)
+ const viewer = await startSlalomViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Slalom descends and Jev steers', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const deadline = Date.now() + 2500
+ let saw = false
+ while (Date.now() < deadline) {
+ await wait(120)
+ const s = await (await fetch(`http://127.0.0.1:${port}/state`)).json()
+ if (s.history.length >= 3) {
+ assert.ok(['LEFT_FAST', 'LEFT', 'HOLD', 'RIGHT', 'RIGHT_FAST'].includes(s.move))
+ assert.ok(typeof s.x === 'number')
+ assert.ok(typeof s.rows === 'number')
+ assert.ok(Array.isArray(s.gates) && s.gates.length === 10)
+ saw = true
+ break
+ }
+ }
+ assert.ok(saw, 'expected the skier to descend and Jev to steer')
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Slalom writes a progressive verdict', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 1500
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Slalom control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-slalom/toolchain/README.md b/store/agents/jev-slalom/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-slalom/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-slalom/toolchain/check.mjs b/store/agents/jev-slalom/toolchain/check.mjs
new file mode 100644
index 000000000..903b6b6ad
--- /dev/null
+++ b/store/agents/jev-slalom/toolchain/check.mjs
@@ -0,0 +1,30 @@
+#!/usr/bin/env node
+// check.mjs — validate a slalom.json for the Jev Slalom harness.
+// Enforces the shape the viewer needs: title, course profile, tick interval.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let p
+try {
+ p = JSON.parse(readFileSync(join(ws, 'slalom.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read slalom.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!p.title || typeof p.title !== 'string') bad('warn no title')
+if (p.instrument && p.instrument !== 'SLALOM') bad('warn instrument should be SLALOM')
+if (typeof p.speed !== 'number' || p.speed <= 0) bad('error speed must be a positive number')
+if (typeof p.gates !== 'number' || p.gates < 2 || p.gates > 60) bad('error gates should be 2..60')
+const W = p.valleyWidth ?? 18
+if (typeof W !== 'number' || W < 6 || W > 60) bad('error valleyWidth should be 6..60')
+if (typeof p.tickMs !== 'number' || p.tickMs < 60 || p.tickMs > 2000) bad('error tickMs must be ms 60..2000')
+if (!p.style || typeof p.style !== 'string') bad('warn a style line helps Jev line up coherently')
+
+console.log(fail ? 'fail invalid slalom.json' : 'ok slalom.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-slalom/toolchain/doctor.sh b/store/agents/jev-slalom/toolchain/doctor.sh
new file mode 100755
index 000000000..922aa1b88
--- /dev/null
+++ b/store/agents/jev-slalom/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Slalom viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-slalom/toolchain/init-workspace.sh b/store/agents/jev-slalom/toolchain/init-workspace.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-slalom/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-slalom/toolchain/jev.mjs b/store/agents/jev-slalom/toolchain/jev.mjs
new file mode 100644
index 000000000..177b79507
--- /dev/null
+++ b/store/agents/jev-slalom/toolchain/jev.mjs
@@ -0,0 +1,731 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+/**
+ * Launcher ranking read used by the mock when the state text carries a command catalog and a
+ * current query (the viewer renders the palette as a numbered list of targets, each with aliases,
+ * plus a `Current query: "..."` line). For each target we score how well its name + aliases match
+ * the query tokens and return a per-target boost (0 = no match) plus a `dominance` signal (how far
+ * the best match clears the field). Real Jev reads the same catalog text and picks the best target
+ * — the mock is a stand-in for that judgement, not a replacement. `featured` targets lead when the
+ * query is empty.
+ */
+function launcherRank(text) {
+ const query = (text.match(/current query:\s*"([^"]*)"/i) || [null, ''])[1]
+ const targets = []
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*\d+\.\s+(.+?)\s+\[([^\]]+)\](?:\s+\(featured\))?\s+aliases:\s*(.+?)\s+—/i)
+ if (m) targets.push({ name: m[1].trim(), cat: m[2].trim(), aliases: m[3].split(',').map((s) => s.trim()).filter(Boolean), featured: /\(featured\)/i.test(line) })
+ }
+ if (!targets.length) return null
+ const qtoks = query.toLowerCase().match(/[a-z0-9]+/g) || []
+ const boost = new Map()
+ for (const t of targets) {
+ let s
+ if (qtoks.length === 0) {
+ s = t.featured ? 0.8 : 0.2
+ } else {
+ const toks = [t.name, ...t.aliases].join(' ').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ s = 0
+ for (const q of qtoks) {
+ let b = 0
+ for (const tok of toks) {
+ if (tok === q) b = Math.max(b, 1.2)
+ else if (tok.startsWith(q)) b = Math.max(b, 1.0)
+ else if (tok.includes(q)) b = Math.max(b, 0.7)
+ else { let k = 0; for (const c of q) { if (tok[k] === c) k++ } if (k === q.length) b = Math.max(b, 0.3) }
+ }
+ s += b
+ }
+ }
+ boost.set(t.name, s)
+ }
+ const vals = [...boost.values()]
+ const top = Math.max(...vals)
+ const second = vals.length > 1 ? vals.slice().sort((a, b) => b - a)[1] : 0
+ return { boost, query, dominance: top - second }
+}
+
+/**
+ * Pendulum-balancing read used by the mock when the state text carries the current pole angle and
+ * angular velocity (the viewer renders e.g. "angle: +12° velocity: -0.8 rad/s"). We compute the
+ * corrective action the pole is asking for: lean/fall to the right (positive angle) wants a
+ * leftward torque, and also damp any velocity. Returns per-action boosts so the deterministic mock
+ * biases toward the right call while staying slightly noisy — so Jev can fail when it's sloppy and
+ * the fall reads as Jev's mistake. Real Jev reads the same text — the mock is a stand-in.
+ */
+function pendulumRead(text) {
+ const mA = text.match(/angle:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const mV = text.match(/velocity:\s*([+-]?\d+(?:\.\d+)?)/i)
+ const deg = mA ? Number(mA[1]) : NaN
+ const vel = mV ? Number(mV[1]) : NaN
+ if (!Number.isFinite(deg) || !Number.isFinite(vel)) return null
+ const a = (deg * Math.PI) / 180
+ // desired torque = -(Kp*a + Kv*vel); pick the action whose torque is closest.
+ const want = -(6.5 * a + 3.2 * vel)
+ const ACTS = { LEFT_HARD: -1.6, LEFT: -0.8, CENTER: 0, RIGHT: 0.8, RIGHT_HARD: 1.6 }
+ const boost = {}
+ for (const [name, t] of Object.entries(ACTS)) {
+ boost[name] = 1.4 - Math.abs(t - Math.max(-1.6, Math.min(1.6, want))) * 0.9
+ }
+ // The mock can't see the gravity dial — it just balances. But a fast judge on a hard
+ // rig will hesitate more, so the misjudgement rate rises with how hard the balance is.
+ // Low gravity: calm, near-perfect. High gravity: it starts to overshoot and lose it.
+ const hard = (parseFloat((text.match(/hardness:\s*([0-9.]+)/i) || [null, '0'])[1]) || 0)
+ const noise = Math.min(0.55, 0.03 + hard * 0.06)
+ return { boost, noise }
+}
+
+/**
+ * Pong-defender read used by the mock when the state text carries a ball position/velocity and the
+ * paddle's centre. We predict where the ball will cross the paddle's wall (reflecting off floor and
+ * ceiling) and bias the paddle move toward that intercept, with a reaction that degrades as the ball
+ * gets faster. Returns per-move boosts plus a beta error chance so Jev can visibly lose a fast rally.
+ */
+function pongRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/ball:\s*x\s+([-0-9.]+)/i)
+ const y = num(/y\s+([-0-9.]+)\s+vx/i)
+ const vx = num(/vx\s+([-0-9.]+)\s+vy/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const paddleY = num(/centre y\s+([-0-9.]+)/i)
+ const half = num(/half-height\s+([-0-9.]+)/i)
+ const courtH = num(/court:\s*[-0-9.]+\s*[x×]\s*([-0-9.]+)/i)
+ const speed = num(/speed:\s*([-0-9.]+)/i)
+ if (![x, y, vx, vy, paddleY, half, courtH, speed].every(Number.isFinite)) return null
+ const r = 3
+ const span = courtH - 2 * r
+ // When the ball is moving away (rightward), the paddle's job is to stop chasing and hold still so
+ // it's framed to meet the ball when it comes back — letting the rally breathe.
+ if (vx >= 0) return { boost: { HOLD: 1.9, MOVE_UP: 0.7, MOVE_DOWN: 0.7, MOVE_UP_FAST: 0.3, MOVE_DOWN_FAST: 0.3 }, noise: 0, close: false }
+ // time (in ball steps) to reach the left wall
+ const t = -x / vx
+ const dy = vy * t
+ let u = ((y - r + dy) % (2 * span) + 2 * span) % (2 * span)
+ u = u <= span ? u : 2 * span - u
+ const ty = r + u
+ const want = ty - paddleY
+ const goDown = want > half * 0.5
+ const goUp = want < -half * 0.5
+ const boost = {}
+ for (const name of ['MOVE_UP_FAST', 'MOVE_UP', 'HOLD', 'MOVE_DOWN', 'MOVE_DOWN_FAST']) {
+ if (goDown) boost[name] = name === 'MOVE_DOWN' ? 1.8 : name === 'MOVE_DOWN_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else if (goUp) boost[name] = name === 'MOVE_UP' ? 1.8 : name === 'MOVE_UP_FAST' ? 1.4 : name === 'HOLD' ? 0.7 : 0.2
+ else boost[name] = name === 'HOLD' ? 1.8 : 0.8
+ }
+ // faster ball → the intercept at the wall changes fast and the paddle has fewer ticks to reach it,
+ // so the physical difficulty (max paddle speed) does the work. No injected noise: a miss is honest.
+ return { boost }
+}
+
+/**
+ * Shopper read used by the mock when the state text carries the recent price stream for each
+ * product (the viewer renders "Name: price (+x% over N ticks) vol v% [spark]"). We score each
+ * product by how fast its price is still falling — the best value right now — and bias the "best
+ * buy" choice toward the steepest falling momentum, plus a confidence that depends on how far the
+ * top pick stands out. Real Jev reads the same lines — the mock is a stand-in.
+ */
+function shopperRead(text) {
+ const picks = []
+ const re = /^\s*([^:\n]+?):\s*([0-9.]+)\s*\(\s*([+-][0-9.]+)% over (\d+) ticks\)\s*vol\s*([0-9.]+)%\s*\[([^\]]*)\]/gim
+ let m
+ while ((m = re.exec(text))) {
+ const name = m[1].trim()
+ const price = Number(m[2])
+ const chgPct = Number(m[3])
+ picks.push({ name, price, chgPct })
+ }
+ if (picks.length < 2) return null
+ // best value = most negative recent change (still falling the fastest)
+ const sorted = picks.slice().sort((a, b) => a.chgPct - b.chgPct)
+ const best = sorted[0]
+ const second = sorted[1]
+ const spread = second.chgPct - best.chgPct
+ const boost = {}
+ for (const p of picks) boost[p.name] = p.name === best.name ? 1.6 : p.name === second.name ? 0.9 : 0.2
+ // confidence: strong when the leader clearly out-falls the rest; weak when it's a dead heat
+ const confidence = Math.min(0.95, Math.max(0.15, 0.5 + spread * 0.6))
+ return { boost, confidence, best: best.name }
+}
+
+/**
+ * Lander read used by the mock when the state text carries booster telemetry
+ * ("ALT x VY y G g FUEL f%"). We pick a throttle by altitude and vertical speed — burn early and
+ * hard enough to keep descent in check while high, flare gently low so the touchdown is soft —
+ * and bias the throttle choice toward it, with a noise term that grows with gravity so high-g
+ * missions look twitchy and start to crash. Real Jev reads the same lines — the mock is a
+ * stand-in.
+ */
+function landerRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const alt = num(/alt\s+([-0-9.]+)/i)
+ const vy = num(/vy\s+([-0-9.]+)/i)
+ const g = num(/g\s+([-0-9.]+)/i)
+ if (![alt, vy, g].every((v) => Number.isFinite(v))) return null
+ let pick
+ if (alt > 30) {
+ if (vy < -2.5) pick = 'BURN'
+ else if (vy < -1.2) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 16) {
+ if (vy < -1.8) pick = 'BURN'
+ else if (vy < -0.8) pick = 'HOVER'
+ else pick = 'COAST'
+ } else if (alt > 7) {
+ if (vy < -1.0) pick = 'BURN'
+ else if (vy < -0.3) pick = 'HOVER'
+ else pick = 'COAST'
+ } else {
+ if (vy < -0.4) pick = 'BURN'
+ else pick = 'CUT'
+ }
+ const boost = { CUT: 0.2, COAST: 0.6, HOVER: 0.7, BURN: 0.5 }
+ if (boost[pick] !== undefined) boost[pick] = 1.9
+ // twitchiness grows with gravity: higher g -> more over/under correction
+ boost.noise = Math.min(0.55, 0.06 + Math.max(0, (g - 1.5)) * 0.14)
+ return { boost, pick, g }
+}
+
+/**
+ * Slalom read used by the mock when the state text carries the skier's x and the next gate ("skier x
+ * X gate x G gate in D"). We steer toward the gate — committing harder as it arrives — with a small
+ * aim error that grows the less time there is, so faster descents look wobblier and fall. Real Jev
+ * reads the same lines — the mock is a stand-in.
+ */
+function slalomRead(text) {
+ const num = (re) => { const m = text.match(re); return m ? Number(m[1]) : Number.NaN }
+ const x = num(/skier x\s+([-0-9.]+)/i)
+ const gx = num(/gate x\s+([-0-9.]+)/i)
+ const rowGap = num(/row gap\s+([-0-9.]+)/i)
+ const speed = num(/descends at\s+([-0-9.]+)/i)
+ if (![x, gx, rowGap].every((v) => Number.isFinite(v))) return null
+ const spd = Number.isFinite(speed) ? speed : 2.4
+ // Reaction lag: the faster the descent, the later Jev reacts to an approaching gate (fewer spare
+ // ticks to cross the valley), so it arrives pointed at the old line and clips the gate.
+ const lag = Math.max(0, Math.floor((spd - 1.8) * 1.7))
+ const reachRows = 18 - lag * spd
+ const need = Math.abs(gx - x)
+ let pick = 'HOLD'
+ if (rowGap <= reachRows) {
+ const want = gx - x
+ if (want < -1.3) pick = 'LEFT_FAST'
+ else if (want > 1.3) pick = 'RIGHT_FAST'
+ else if (want < -0.5) pick = 'LEFT'
+ else if (want > 0.5) pick = 'RIGHT'
+ else pick = 'HOLD'
+ }
+ const boost = { LEFT_FAST: 0.05, LEFT: 0.05, HOLD: 0.05, RIGHT: 0.05, RIGHT_FAST: 0.05 }
+ if (boost[pick] !== undefined) boost[pick] = 1.99
+ return { boost, pick, rowGap }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ // Shopper: "act now" is urgent when the best buy clearly out-falls the field. Ask Jev to spend
+ // when the momentum spread is wide, so the demo eventually commits on paper.
+ if (/act now|spend now|strong enough/i.test(qtext) || /buy|act/i.test(q.instructions)) {
+ const shop = shopperRead(text)
+ if (shop && shop.confidence) p = Math.max(p, Math.min(0.9, 0.4 + shop.confidence * 0.5))
+ }
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Launcher: if the state carries a numbered command catalog + a current query, bias the
+ // ranking by how well each target matches the query (and lead with featured targets on an
+ // empty query).
+ const lr = launcherRank(text)
+ if (lr) {
+ options.forEach((opt, i) => {
+ const coast = lr.boost.get(String(opt).toLowerCase())
+ if (coast !== undefined) raw[i] += coast + Math.min(0.5, lr.dominance * 0.6)
+ })
+ }
+ // Pendulum: if the state carries an angle + angular velocity, bias toward the balancing action,
+ // and occasionally flip to a neighbour (a fast model that sometimes hesitates) so the pole can
+ // visibly wobble — that wiggle is the demo.
+ const pen = pendulumRead(text)
+ if (pen) {
+ options.forEach((opt, i) => {
+ const b = pen.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (pen.noise && (hash01('pen', salt + 9) < pen.noise)) {
+ // flip the current best to two neighbours over — a big, costly overcorrection
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + (hash01('dir', salt) < 0.5 ? -2 : 2)))
+ if (ni !== best.i) raw[ni] += 2.2
+ }
+ }
+ // Pong: if the state text carries a ball + paddle, steer the paddle to the predicted intercept,
+ // and lag harder (miss more) as the ball speeds up.
+ const pong = pongRead(text)
+ if (pong) {
+ options.forEach((opt, i) => {
+ const b = pong.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Shopper: if the state carries a product price stream, bias "best buy" toward the product
+ // whose price is still falling the fastest.
+ const shop = shopperRead(text)
+ if (shop) {
+ options.forEach((opt, i) => {
+ const b = shop.boost[String(opt).toLowerCase()]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Lander: if the state carries booster telemetry, bias the throttle toward a plausible burn and
+ // flip to a worse one more often as gravity rises, so high-g missions look twitchy and crash.
+ const land = landerRead(text)
+ if (land) {
+ options.forEach((opt, i) => {
+ const b = land.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ if (land.boost.noise && (hash01('land', salt + 11) < land.boost.noise)) {
+ // over or under-throttle by one step — a costly hesitation
+ const best = options.map((o, i) => ({ o, i, r: raw[i] })).sort((a, b) => b.r - a.r)[0]
+ const step = hash01('ldir', salt) < 0.5 ? 1 : -1
+ const ni = Math.max(0, Math.min(options.length - 1, best.i + step))
+ if (ni !== best.i && land.boost[String(options[ni])] !== undefined) raw[ni] += 2.4
+ }
+ }
+ // Slalom: if the state carries the skier's x and the next gate, steer toward it once it's in
+ // reach; the physical slew limit (fast descents have too few ticks to cross the valley) is what
+ // makes it fall — no injected wobble.
+ const slal = slalomRead(text)
+ if (slal) {
+ options.forEach((opt, i) => {
+ const b = slal.boost[String(opt)]
+ if (b !== undefined) raw[i] += b
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-slalom/toolchain/setup.sh b/store/agents/jev-slalom/toolchain/setup.sh
new file mode 100755
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-slalom/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-slalom/toolchain/viewer.sh b/store/agents/jev-slalom/toolchain/viewer.sh
new file mode 100755
index 000000000..6c1f70d52
--- /dev/null
+++ b/store/agents/jev-slalom/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Slalom viewer (Jev is the racer, steering the skier to thread every gate).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-slalom/viewer/index.html b/store/agents/jev-slalom/viewer/index.html
new file mode 100644
index 000000000..cd36ae3bc
--- /dev/null
+++ b/store/agents/jev-slalom/viewer/index.html
@@ -0,0 +1,55 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Jev Slalom</title>
+<link rel="stylesheet" href="/studio.css">
+</head>
+<body>
+ <div id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Slalom</h1></div>
+ <div class="stats">
+ <div class="stat"><label>Gate</label><span id="gate">—</span></div>
+ <div class="stat"><label>Steer</label><span id="move">—</span></div>
+ <div class="stat"><label>Speed</label><span id="speed">—</span></div>
+ <div class="stat"><label>Pos</label><span id="pos">—</span></div>
+ <div class="stat"><label>Ticks</label><span id="ticks">0</span></div>
+ </div>
+ <div class="controls">
+ <button id="pause">Pause</button>
+ <button id="tick">Step</button>
+ <button class="primary" id="reset">Reset</button>
+ </div>
+ </div>
+ <main>
+ <section id="stage">
+ <div class="panel panel-stage">
+ <div class="panel-title">The course</div>
+ <div id="course">
+ <canvas id="scene"></canvas>
+ <div id="banner" class="hidden"></div>
+ </div>
+ </div>
+ </section>
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Jev, the racer</div>
+ <div class="how">
+ Jev is skiing the slalom. A line of gates sweeps down toward it, and every tick it reads
+ its position and the next gate and steers <code>LEFT</code> / <code>RIGHT</code> (or
+ commits fast) to thread each gap. Clip a gate or hit the wall and the run is over.<br><br>
+ Edit <code>slalom.json</code>: crank <code>speed</code> up and Jev's aim starts to wobble
+ and it falls; change <code>gates</code> for a longer or shorter course.
+ </div>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Run log</div>
+ <ul id="log"></ul>
+ </div>
+ </aside>
+ </main>
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-slalom/viewer/jev-hud.js b/store/agents/jev-slalom/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-slalom/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-slalom/viewer/studio.css b/store/agents/jev-slalom/viewer/studio.css
new file mode 100644
index 000000000..4145b9926
--- /dev/null
+++ b/store/agents/jev-slalom/viewer/studio.css
@@ -0,0 +1,71 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #f59e0b; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #16222e 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(24,34,46,.9), rgba(10,12,18,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#ticks { color: var(--dim); }
+#gate { color: var(--cyan); }
+#move { color: var(--accent); }
+#speed { color: var(--amber); }
+#pos { color: var(--ok); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #b45309, #f59e0b); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+.panel-stage { padding: 10px; }
+
+#course { position: relative; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: #cdd9ea; }
+#scene { width: 100%; height: 62vh; display: block; }
+#banner {
+ position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%);
+ padding: 10px 22px; border-radius: 10px; font-size: 15px; font-weight: 700; letter-spacing: .5px;
+ font-family: var(--mono);
+}
+#banner.ok { background: rgba(16,185,129,.18); border: 1px solid var(--ok); color: #065f46; box-shadow: 0 0 30px rgba(16,185,129,.4); }
+#banner.bad { background: rgba(225,29,72,.18); border: 1px solid #e11d48; color: #881337; box-shadow: 0 0 30px rgba(225,29,72,.4); }
+#banner.hidden { display: none; }
+
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px; display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(16,24,34,.5); }
+.how { color: var(--dim); font-size: 13px; line-height: 1.5; }
+.how b { color: var(--cyan); }
+.how code { color: var(--amber); }
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; max-height: 50vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 10px; align-items: baseline; }
+#log li .n { color: var(--accent); }
+#log li .a { width: 90px; color: var(--cyan); font-weight: 700; }
+#log li .p { color: var(--amber); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-slalom/viewer/studio.js b/store/agents/jev-slalom/viewer/studio.js
new file mode 100644
index 000000000..bde7c84d1
--- /dev/null
+++ b/store/agents/jev-slalom/viewer/studio.js
@@ -0,0 +1,167 @@
+// Jev Slalom pane — draws a top-down slalom course: the skier descends with snow spray, gates sweep
+// toward it and light up blue when threaded, and a finished run shows a clean-run or fell banner.
+
+const $ = (id) => document.getElementById(id)
+const els = {
+ gate: $('gate'), move: $('move'), speed: $('speed'), pos: $('pos'), ticks: $('ticks'),
+ banner: $('banner'), log: $('log'), scene: $('scene'),
+}
+
+let x = 9, rows = 0, speed = 2.2, width = 18, move = 'HOLD', ticks = 0
+let finished = null
+let gates = []
+let next = 0
+const THREADED = new Set()
+
+function draw() {
+ const c = els.scene
+ const ctx = c.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = c.clientWidth, H = c.clientHeight
+ c.width = W * dpr; c.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+
+ // snow ground
+ const grd = ctx.createLinearGradient(0, 0, 0, H)
+ grd.addColorStop(0, '#eef4fb')
+ grd.addColorStop(1, '#cdd9ea')
+ ctx.fillStyle = grd
+ ctx.fillRect(0, 0, W, H)
+
+ // course bounds
+ const margin = 30
+ const courseLeft = margin, courseRight = W - margin
+ const topY = 12, botY = H - 16
+
+ // valley walls
+ ctx.strokeStyle = '#8a97ad'; ctx.lineWidth = 10
+ ctx.lineCap = 'round'
+ ctx.beginPath(); ctx.moveTo(courseLeft, topY); ctx.lineTo(courseLeft, botY); ctx.stroke()
+ ctx.beginPath(); ctx.moveTo(courseRight, topY); ctx.lineTo(courseRight, botY); ctx.stroke()
+
+ const px = (gateX) => courseLeft + (gateX / width) * (courseRight - courseLeft)
+ const py = (row) => botY - (row / 130) * (botY - topY)
+
+ // threading gates: draw from far (top) to near (bottom)
+ for (let i = gates.length - 1; i >= 0; i--) {
+ const g = gates[i]
+ if (g.y < rows - 90) continue
+ const gx = px(g.x), gy = py(g.y)
+ const threaded = THREADED.has(i)
+ ctx.strokeStyle = threaded ? '#10b981' : '#e11d48'
+ ctx.lineWidth = 6
+ ctx.lineCap = 'round'
+ const half = (g.gap / width) * (courseRight - courseLeft) / 2
+ ctx.beginPath(); ctx.moveTo(gx - half, gy); ctx.lineTo(gx + half, gy); ctx.stroke()
+ // flags
+ ctx.fillStyle = threaded ? '#34d399' : '#f43f5e'
+ ctx.beginPath(); ctx.arc(gx - half, gy, 4, 0, Math.PI * 2); ctx.fill()
+ ctx.beginPath(); ctx.arc(gx + half, gy, 4, 0, Math.PI * 2); ctx.fill()
+ }
+
+ // snow trail from history
+ ctx.strokeStyle = 'rgba(255,255,255,.7)'; ctx.lineWidth = 8
+ ctx.lineCap = 'round'; ctx.lineJoin = 'round'
+ if (history.length > 1) {
+ ctx.beginPath()
+ history.forEach((h, i) => {
+ const hx = px(h.x), hy = py(h.rows)
+ i ? ctx.lineTo(hx, hy) : ctx.moveTo(hx, hy)
+ })
+ ctx.stroke()
+ }
+
+ // skier
+ const sx = px(x), sy = py(rows)
+ // spray
+ ctx.fillStyle = 'rgba(255,255,255,.9)'
+ for (let i = 0; i < 5; i++) {
+ ctx.beginPath()
+ ctx.arc(sx + (3 - i) * 3, sy, 3 + i * 1.2, 0, Math.PI * 2)
+ ctx.fill()
+ }
+ // body
+ ctx.fillStyle = '#1f2937'
+ ctx.beginPath(); ctx.arc(sx, sy, 7, 0, Math.PI * 2); ctx.fill()
+ ctx.fillStyle = '#f59e0b'
+ ctx.beginPath()
+ ctx.moveTo(sx, sy - 9)
+ ctx.lineTo(sx + 7, sy)
+ ctx.lineTo(sx - 7, sy)
+ ctx.closePath(); ctx.fill()
+
+ // target gate highlight
+ const cur = gates[next]
+ if (cur) {
+ ctx.strokeStyle = '#f59e0b'; ctx.lineWidth = 2; ctx.setLineDash([4, 4])
+ const gx = px(cur.x), gy = py(cur.y)
+ ctx.beginPath(); ctx.moveTo(sx, sy); ctx.lineTo(gx, gy); ctx.stroke()
+ ctx.setLineDash([])
+ }
+}
+
+function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])) }
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history.slice(-30)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="n">#${h.step}</span><span class="a">${esc(h.move)}</span><span class="p">x ${h.x.toFixed(1)}</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function renderBanner() {
+ if (!finished) { els.banner.classList.add('hidden'); return }
+ els.banner.classList.remove('hidden')
+ els.banner.textContent = finished.ok
+ ? `✓ CLEAN RUN · ${finished.gates} gates threaded`
+ : `✗ FELL at gate ${finished.atGate + 1} · ${finished.reason}`
+ els.banner.className = 'banner ' + (finished.ok ? 'ok' : 'bad')
+}
+
+let history = []
+
+function onTick(msg) {
+ if (typeof msg.x === 'number') x = msg.x
+ if (typeof msg.rows === 'number') rows = msg.rows
+ if (typeof msg.speed === 'number') speed = msg.speed
+ if (typeof msg.valleyWidth === 'number') width = msg.valleyWidth
+ move = msg.move || move
+ ticks = msg.step ?? ticks
+ finished = msg.finished || null
+ gates = msg.gates || gates
+ next = msg.next ?? next
+ history = msg.history || history
+
+ THREADED.clear()
+ gates.forEach((g, i) => { if (g.passed) THREADED.add(i) })
+
+ els.gate.textContent = finished ? '—' : `${Math.min(next + 1, gates.length)}/${gates.length}`
+ els.move.textContent = move
+ els.speed.textContent = 'v' + speed.toFixed(1)
+ els.pos.textContent = 'x' + x.toFixed(1)
+ els.ticks.textContent = String(ticks)
+
+ renderBanner()
+ renderLog()
+ draw()
+}
+
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => ctl('reset')
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-slalom/viewer/viewer.mjs b/store/agents/jev-slalom/viewer/viewer.mjs
new file mode 100644
index 000000000..3ef7e39a6
--- /dev/null
+++ b/store/agents/jev-slalom/viewer/viewer.mjs
@@ -0,0 +1,283 @@
+// Jev Slalom viewer — a loopback server running a live slalom demo. The skier descends a valley and
+// gates sweep toward it; Jev (TypeSafe's System One model) reads the skier's x and the next gate
+// every tick and steers left/right to thread each gap. Clip a gate or hit the wall and the run ends.
+// The agent shapes slalom.json (the descent speed, the valley width, how many gates) — crank the
+// speed up and Jev's aim starts to wobble and it falls. The course is synthetic; the decision loop
+// is the demo.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds slalom.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT = {
+ title: 'Jev Slalom',
+ description: 'Jev is the racer — carve a slalom line and thread every gate.',
+ instrument: 'SLALOM',
+ tickMs: 160, speed: 2.2, gates: 18, valleyWidth: 18,
+ style: 'You are skiing the slalom. A line of gates sweeps toward you as you descend — steer left and right to thread each gap, lining up early and committing as each gate arrives. Clip a gate or hit the wall and you fall. Clean, decisive turns win the run.',
+}
+
+const MOVES = ['LEFT_FAST', 'LEFT', 'HOLD', 'RIGHT', 'RIGHT_FAST']
+const MV = { LEFT_FAST: -1.9, LEFT: -1.0, HOLD: 0, RIGHT: 1.0, RIGHT_FAST: 1.9 }
+
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v))
+
+function makeGates(count, W, rng) {
+ // a regular course: gates alternate sides of the valley at a fixed spacing, so difficulty is
+ // purely a function of speed (fewer ticks between gates). rng only picks the first side.
+ const gates = []
+ let y = 12 + rng() * 3
+ const step = Math.max(13, W * 0.72)
+ let side = rng() < 0.5 ? -1 : 1
+ const gap = Math.min(6, W * 0.34)
+ const off = Math.min(W * 0.3, W / 2 - gap / 2 - 0.5)
+ for (let i = 0; i < count; i++) {
+ const center = W / 2 + side * off
+ gates.push({ y, x: clamp(center, gap / 2 + 0.5, W - gap / 2 - 0.5), gap, passed: false })
+ side = -side
+ y += step
+ }
+ return gates
+}
+
+function stateBlock(p, s) {
+ const g = s.gates[s.next]
+ const rowGap = Math.max(0, g.y - s.rows)
+ return `${p.style}
+The skier descends at ${p.speed.toFixed(1)} rows/tick (reaction lag ${Math.max(0, Math.floor((p.speed - 1.8) * 1.7))} ticks).
+Next gate: x ${g.x.toFixed(1)}, gap ${g.gap.toFixed(1)}, ROWS ${rowGap.toFixed(1)} ahead.
+skier x ${s.x.toFixed(1)} gate x ${g.x.toFixed(1)} row gap ${rowGap.toFixed(1)}
+Which way do you steer? ${MOVES.join(' / ')}`
+}
+
+export async function startSlalomViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let error = null
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let step = 0
+ let running = false
+ let state = null // {x, rows, gates, next}
+ let move = 'HOLD'
+ let episode = 0 // bumps each time an episode restarts on its own, so the next one differs
+ let finished = null // {ok, ticks, gates, reason, atGate}
+ let history = [] // {step, x, rows, move}
+ let notified = false
+ let rng
+
+ let lastCfg = null
+ let p = readCfg(join(workspace, 'slalom.json'))
+
+ function readCfg(file) {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
+ const merged = { ...DEFAULT, ...raw }
+ if (!lastCfg || merged.speed !== lastCfg.speed || merged.valleyWidth !== lastCfg.valleyWidth || merged.gates !== lastCfg.gates || !state) {
+ resetStateNow(merged)
+ }
+ lastCfg = merged
+ return merged
+ } catch (e) {
+ error = clean(e.message)
+ return lastCfg || DEFAULT
+ }
+ }
+
+ function resetStateNow(cfg) {
+ rng = mulberry32(2719 + episode * 97)
+ const W = cfg.valleyWidth ?? DEFAULT.valleyWidth
+ state = { x: W / 2, rows: 0, gates: makeGates(cfg.gates ?? DEFAULT.gates, W, rng), next: 0 }
+ move = 'HOLD'
+ finished = null
+ history = []
+ notified = false
+ step = 0
+ error = null
+ }
+ function resetState() { resetStateNow(p) }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function verdict() {
+ return {
+ spec: 1,
+ ready: history.length > 0 || finished !== null,
+ summary: error
+ ? 'Jev Slalom needs a fix'
+ : finished
+ ? `${p.title} · ${finished.ok ? 'clean run, ' + finished.gates + ' gates' : 'fell at gate ' + (finished.atGate + 1) + ' after ' + finished.gates + ' · ' + finished.reason}`
+ : `${p.title} · threading gate ${Math.min(state.next + 1, state.gates.length)}/${state.gates.length} · ${step} ticks`,
+ findings: (error ? [{ severity: 'error', kind: 'slalom', message: error }] : []).concat(
+ finished
+ ? [{ severity: finished.ok ? 'info' : 'error', kind: 'slalom', message: finished.ok ? `Jev carved a clean ${finished.gates}-gate run` : `Jev fell at gate ${finished.atGate + 1}: ${finished.reason}` }]
+ : []
+ ),
+ artifact: 'slalom.json',
+ phases: [
+ { id: 'learn', name: 'Carving', state: history.length < 5 ? 'active' : 'done' },
+ { id: 'call', name: 'Threading gates', state: history.length >= 5 && !finished ? 'active' : finished ? 'done' : 'pending' },
+ { id: 'finish', name: 'Run done', state: finished ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+ }
+
+ function tail() {
+ const v = verdict()
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick', title: p.title, description: p.description, instrument: p.instrument,
+ speed: p.speed, valleyWidth: p.valleyWidth,
+ x: state?.x, rows: state?.rows, move, step, running, error, finished,
+ gates: state?.gates, next: state?.next, history: history.slice(-300),
+ })
+ }
+
+ function reset() { resetState(); tail(); if (running) schedule() }
+ function pause() { running = false; clearTimeout(timer) }
+ function start() { if (!running) { running = true; schedule() } }
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, p.tickMs) }
+ async function run() {
+ if (stopped) return
+ if (finished) {
+ // Never sit on a finished screen: show the result briefly, then play again.
+ finished.shownAt ??= Date.now()
+ if (Date.now() - finished.shownAt > 3500) { episode++; resetState() }
+ tail(); schedule(); return
+ }
+ await decide()
+ schedule()
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ const res = await evaluate({
+ state: stateBlock(p, state),
+ questions: {
+ steer: { type: 'choice', instructions: 'Which way do you steer this tick?', options: MOVES },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const pick = String(res.answers.steer?.choice || 'HOLD')
+ move = MOVES.includes(pick) ? pick : 'HOLD'
+ // physics: advance the skier one tick
+ state.x = clamp(state.x + MV[move], 1, p.valleyWidth - 1)
+ state.rows += p.speed
+ step++
+ history.push({ step, x: state.x, rows: state.rows, move })
+ if (history.length > 400) history.splice(0, history.length - 400)
+ // check the current gate
+ const g = state.gates[state.next]
+ if (g && g.y - state.rows <= 0 && !g.passed) {
+ g.passed = true
+ if (Math.abs(state.x - g.x) > g.gap / 2) {
+ finished = { ok: false, ticks: step, gates: state.next, reason: 'clipped the gate', atGate: state.next }
+ notified = true
+ } else {
+ state.next++
+ }
+ }
+ // wall check
+ if (state.x <= 1.05 || state.x >= p.valleyWidth - 1.05) {
+ finished = { ok: false, ticks: step, gates: state.next, reason: 'hit the wall', atGate: state.next }
+ notified = true
+ }
+ // clean finish
+ if (!finished && state.next >= state.gates.length) {
+ finished = { ok: true, ticks: step, gates: state.gates.length, reason: 'clean run', atGate: state.gates.length }
+ notified = true
+ }
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ const watcher = watch(join(workspace, 'slalom.json'), () => {
+ p = readCfg(join(workspace, 'slalom.json'))
+ tail()
+ if (running) schedule()
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: p.title, instrument: p.instrument, speed: p.speed, valleyWidth: p.valleyWidth, x: state?.x, rows: state?.rows, move, step, running, error, finished, gates: state?.gates, next: state?.next, history: history.slice(-300) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ resetState()
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startSlalomViewer({ workspace, port })
+ console.log(`Jev Slalom listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/agents/jev-trader/.gitignore b/store/agents/jev-trader/.gitignore
new file mode 100644
index 000000000..350545b37
--- /dev/null
+++ b/store/agents/jev-trader/.gitignore
@@ -0,0 +1,2 @@
+.harness/
+node_modules/
diff --git a/store/agents/jev-trader/AGENTS.md b/store/agents/jev-trader/AGENTS.md
new file mode 100644
index 000000000..cb12b0681
--- /dev/null
+++ b/store/agents/jev-trader/AGENTS.md
@@ -0,0 +1,72 @@
+# Jev Trader in OpenHarness
+
+On the left, Jev Trader runs a paper-trading desk. **Jev — TypeSafe's System One model — is the
+trader.** A synthetic market ticks; Jev reads the tape and its own P&L and decides buy / hold / sell,
+tick by tick. You design the market Jev trades; Jev does the trading. The equity never leaves paper.
+
+On the right, you edit `market.json`. This is the ONLY file you edit. The viewer watches it and
+reframes Jev live — edit volatility, drift or style while the desk is running and Jev adapts.
+
+## The workspace
+
+- `market.json` — the market and the trader's brief.
+
+```jsonc
+{
+ "title": "A Desk Name",
+ "description": "A subtitle felt in the viewer.",
+ "instrument": "SYNTH", // ticker, shown on the tape
+ "startPrice": 100, // starting price
+ "volatility": 0.012, // per-step stdev of returns (0..0.2)
+ "drift": 0.0003, // per-step bias; positive = gently rising, negative = falling, 0 = flat
+ "stepMs": 900, // ms per tick (min 200)
+ "capital": 10000, // starting cash
+ "style": "Buy the trend, cut losses, keep some cash. You are a fast, disciplined trader."
+}
+```
+
+`check.mjs` validates the shape.
+
+## Your job
+
+Design markets that test Jev, and give it a coherent brief. Good desks:
+
+- **Make the trade signal real.** Give Jev a trend (positive or negative `drift`) it can read off
+ the tape, or a violent enough `volatility` that cutting losses matters. A flat, driftless, low-vol
+ tape gives Jev nothing to react to.
+- **Match style to market.** A momentum style on a trending market, a mean-reversion-ish cautious
+ style on a choppy one. The `style` line is Jev's brief — write one that's decisive.
+- **Tell a story.** The title + description make the desk an event ("The Iceberg Desk", "The Lottery
+ Fund").
+
+Do NOT just ship the template. Every `market.json` you publish should be a distinct, stressworthy
+market with a deliberate brief.
+
+Validate with `node "$JEV_DSH/toolchain/check.mjs"`. The real test is the curve: does Jev make
+coherent policy on your market (or just churn)? If it overtrades a flat market, that's a finding to
+report — not a bug to mask.
+
+## Keep current
+
+- Keep `market.json` valid JSON always. A bad edit freezes the desk on the last good state.
+- Keep `title`, `description` and `style` truthful — and never pass this off as real trading.
+
+## Rules
+
+- Never propose opening a browser, changing ports, or running a second server. The viewer is already
+ running on the left; it auto-trades on a clock.
+- Jev is reached through `toolchain/jev.mjs`. You can call it directly to ask Jev's read on a market
+ before you commit to it (e.g. "will a momentum Jev make money on this volatility?"). Use the
+ `jev` helpers: `noul`, `choice`, `score`.
+- Without a `TYPESAFE_API_KEY`, Jev runs on a deterministic local mock that still reads the price
+ tape and trades by momentum, so the desk works offline. With a key, the viewer calls the real API.
+- The Jev Trader viewer writes `.harness/verdict.json` itself. Do not edit it.
+- This is paper trading. Never present it as real investment guidance.
+
+## Definition of done
+
+- A valid `market.json` that parses and passes `toolchain/check.mjs`.
+- A market with a real signal (trend and/or meaningful volatility) and a decisive `style` brief.
+- The desk runs and Jev forms coherent policy on it (report if it overtrades or just holds).
+
+Happy trading — on paper.
diff --git a/store/agents/jev-trader/LICENSE b/store/agents/jev-trader/LICENSE
new file mode 100644
index 000000000..a499cd17e
--- /dev/null
+++ b/store/agents/jev-trader/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/jev-trader/README.md b/store/agents/jev-trader/README.md
new file mode 100644
index 000000000..5fd62f8f5
--- /dev/null
+++ b/store/agents/jev-trader/README.md
@@ -0,0 +1,52 @@
+# Jev Trader
+
+**Jev — TypeSafe's System One model — runs a paper-trading desk.** A synthetic market ticks every
+`stepMs`; Jev reads the recent price tape and its own P&L, then decides **buy / hold / sell**, with a
+confidence and conviction. The viewer draws the live equity curve and price as Jev trades. No fake
+money is ever at risk — the P&L is honest, but simulated: a sandbox where you watch a decision model
+trade.
+
+This is a harness for OpenHarness. The agent on the right edits `market.json`; the viewer on the
+left runs the market + portfolio engine and asks Jev for each decision in real time.
+
+## Anatomy
+
+```
+jev-trader/
+ harness.json # DSH manifest (engine: claude)
+ AGENTS.md # tells the agent to design markets that stress-test Jev
+ skills/trader/SKILL.md # the market-design + verification craft
+ template/market.json # a starter desk
+ toolchain/
+ jev.mjs # the Jev client (real TypeSafe API + deterministic mock), momentum-aware
+ viewer.sh # launches the viewer
+ check.mjs # validates market.json
+ setup.sh / doctor.sh / init-workspace.sh
+ viewer/ # the loopback viewer server + pane (equity curve)
+```
+
+## The viewer
+
+`viewer/viewer.mjs` runs a deterministic random-walk market and a portfolio engine (cash, holdings,
+equity). Each tick it advances the price, asks Jev to choose BUY/HOLD/SELL (with confidence +
+conviction), executes the trade, and streams the tape + equity to the pane. It calls
+`POST /v1/systemone` when `TYPESAFE_API_KEY` is set; without it a deterministic mock reads the same
+price tape and biases buy/hold/sell by momentum. `.harness/verdict.json` tracks P&L and phases.
+
+## Jev, honestly
+
+Jev is new and early-access; its headline claims are mostly vendor-reported, and the mock is a
+stand-in for *plumbing*, not judgement. This is paper trading on a synthetic market — deliberately
+**not** investment advice and not a signal for real money. The value is watching a decision model
+form policy (buy the trend / cut losses) and react to a moving tape. Treat any P&L as a demo, not a
+strategy.
+
+## Credit and stewardship
+
+- **Jev** is the work of **TypeSafe AI** (typesafe.ai). This harness is an OpenHarness wrapper that
+ only calls the public API; it contains no TypeSafe code.
+- **OpenHarness** (Autonomous) is MIT-licensed; this wrapper is MIT too (see `LICENSE`).
+- **You** (Autonomous) built this harness for OpenHarness's store.
+
+_Show, don't tell: this harness makes a decision model a live trader — a paper desk you can watch
+think and react._
diff --git a/store/agents/jev-trader/THIRD_PARTY_NOTICES.md b/store/agents/jev-trader/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..c5063e7c5
--- /dev/null
+++ b/store/agents/jev-trader/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,11 @@
+# Third-party notices
+
+**Jev** — TypeSafe AI's "System One" decision model (typesafe.ai). This harness does not vendor or
+fetch any TypeSafe code. It calls TypeSafe's public API (`POST /v1/systemone`) only when a
+`TYPESAFE_API_KEY` is set. Without one, the harness runs on a deterministic local mock (a stand-in
+for the *plumbing*, not for Jev's judgement). Jev and TypeSafe are trademarks of TypeSafe AI.
+
+**OpenHarness** — Autonomous (this repository), MIT license. This harness is a wrapper that adds a
+viewer and agent instructions; it does not modify TypeSafe AI's product.
+
+This project does not imply endorsement by TypeSafe AI.
diff --git a/store/agents/jev-trader/harness.json b/store/agents/jev-trader/harness.json
new file mode 100644
index 000000000..ea34fb7b1
--- /dev/null
+++ b/store/agents/jev-trader/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/jev-trader",
+ "name": "Jev Trader",
+ "category": "Finance",
+ "author": "Autonomous",
+ "description": "Jev — TypeSafe's System One model — runs a paper-trading desk on a synthetic market. It reads the price tape and its own P&L, then decides buy, hold or sell, tick by tick. Watch the equity curve move as a decision model trades. Reshape instrument, volatility and style while it runs.",
+ "engine": "claude",
+ "workspace": {
+ "template": "template",
+ "marker": "market.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "JEV_DSH": "${dsh}",
+ "JEV_MODEL": "jev-latest"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "toolchain/viewer.sh",
+ "url": "http://127.0.0.1:${port}/",
+ "artifactExtensions": [".json"]
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/jev-trader/skills/trader/SKILL.md b/store/agents/jev-trader/skills/trader/SKILL.md
new file mode 100644
index 000000000..ca7f2dc96
--- /dev/null
+++ b/store/agents/jev-trader/skills/trader/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: jev-trader
+description: Design and verify Jev's paper-trading desks in OpenHarness's viewer, where Jev trades a synthetic market live.
+---
+
+# Jev Trader market design
+
+Jev Trader shows a live paper-trading desk: Jev (TypeSafe's System One model) reads a synthetic
+price tape + its own P&L and decides buy / hold / sell each tick. The agent designs `market.json` —
+the market Jev trades and the `style` brief it follows.
+
+## The loop
+
+1. Update `market.json` (instrument, volatility, drift, style). The viewer watches it and reframes
+ Jev live — no restart, no second server.
+2. `node "$JEV_DSH/toolchain/check.mjs"` verifies the workspace's `market.json` is valid and
+ reports the verdict. Run it before you call a desk done.
+3. Watch the equity curve. Does Jev make coherent policy on your market — buy the trend, cut the
+ losses — or just churn? That observation is the finding.
+
+## Reading Jev
+
+The viewer shows Jev's last action (BUY/HOLD/SELL), shares, equity and confidence. A good desk
+produces *policy*: Jev should react to the tape you gave it, not move the same way regardless of
+your market. A decisive `style` brief + a real trend yields readable behavior; a flat, driftless
+market makes any movement look like noise.
+
+## Verifying a desk
+
+`node "$JEV_DSH/toolchain/check.mjs"` returns non-zero when `market.json` is invalid (bad price, ms,
+capital). It doesn't replace watching the curve: confirm the market ticks, Jev's equity moves, and
+its actions vary with the market rather than blindly holding.
+
+## Driving Jev yourself
+
+`toolchain/jev.mjs` exports a small client. Example (from the workspace) — ask Jev's read on a
+market before you commit:
+
+```bash
+node --input-type=module -e '
+import { evaluate, jev } from "$JEV_DSH/toolchain/jev.mjs";
+const res = await evaluate({
+ state: "Market: SYNTH, per-step volatility 0.05 with a strong upward drift. Would a momentum Jev be profitable with a buy-the-trend style?",
+ questions: {
+ edge: jev.noul("Is there a tradable edge here for a momentum trader?"),
+ churn: jev.score({0:"no",1:"some",2:"a lot"}, "How much would this market cause needless overtrading?"),
+ },
+});
+console.log(JSON.stringify(res.answers, null, 2));
+'
+```
+
+Without `TYPESAFE_API_KEY` this uses the deterministic mock; set the key to hit live Jev.
diff --git a/store/agents/jev-trader/store.json b/store/agents/jev-trader/store.json
new file mode 100644
index 000000000..f070ff865
--- /dev/null
+++ b/store/agents/jev-trader/store.json
@@ -0,0 +1,12 @@
+{
+ "homepage": "https://typesafe.ai",
+ "upstream": "https://typesafe.ai",
+ "license": "MIT",
+ "tagline": "Jev runs a paper-trading desk you can watch trade live",
+ "examples": [
+ {
+ "prompt": "Set Jev Trader as a momentum desk on a volatile synthetic instrument — high volatility, a trend-following style. Watch whether it buys the upswings and cuts the downswings, and keep it honest on paper.",
+ "caption": "Jev's Desk — a decision model trading a synthetic market, tick by tick"
+ }
+ ]
+}
diff --git a/store/agents/jev-trader/template/market.json b/store/agents/jev-trader/template/market.json
new file mode 100644
index 000000000..cfee38b59
--- /dev/null
+++ b/store/agents/jev-trader/template/market.json
@@ -0,0 +1,11 @@
+{
+ "title": "Jev's Desk",
+ "description": "A paper account run by a System One decision model. Watch it trade a synthetic market.",
+ "instrument": "SYNTH",
+ "startPrice": 100,
+ "volatility": 0.012,
+ "drift": 0.0003,
+ "stepMs": 900,
+ "capital": 10000,
+ "style": "Buy the trend, cut losses, keep some cash. You are a fast, disciplined trader."
+}
diff --git a/store/agents/jev-trader/test/viewer.test.mjs b/store/agents/jev-trader/test/viewer.test.mjs
new file mode 100644
index 000000000..f0c2d3ce1
--- /dev/null
+++ b/store/agents/jev-trader/test/viewer.test.mjs
@@ -0,0 +1,78 @@
+// Viewer integration test for Jev Trader. Spins up the real viewer against a temp workspace and
+// checks the loop: the market ticks, Jev trades (equity/holdings change), the verdict updates, and
+// control commands work.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const viewerPath = join(HERE, '../viewer/viewer.mjs')
+
+const MARKET = {
+ title: 'Test Desk', instrument: 'TEST', startPrice: 100, volatility: 0.012, drift: 0.0003, stepMs: 120, capital: 10000,
+ style: 'Buy the trend, cut losses.',
+}
+
+function wait(ms) { return new Promise((r) => setTimeout(r, ms)) }
+
+async function freshViewer(overrides = {}) {
+ const ws = mkdtempSync(join(tmpdir(), 'jev-trader-test-'))
+ writeFileSync(join(ws, 'market.json'), JSON.stringify({ ...MARKET, ...overrides }))
+ const { startTraderViewer } = await import(viewerPath)
+ const viewer = await startTraderViewer({ workspace: ws, port: 0 })
+ return { ws, viewer }
+}
+
+test('Jev Trader ticks the market and trades', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const state = async () => (await (await fetch(`http://127.0.0.1:${port}/state`)).json())
+ const deadline = Date.now() + 3000
+ let days = 0
+ while (Date.now() < deadline && days < 3) {
+ await wait(150)
+ const s = await state()
+ days = s.day
+ if (s.history.length) assert.ok(typeof s.equity === 'number')
+ }
+ assert.ok(days >= 3, `expected at least 3 ticks; got ${days}`)
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Trader writes a progressive verdict with a summary', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const deadline = Date.now() + 2000
+ while (Date.now() < deadline) { await wait(150); if (existsSync(join(ws, '.harness/verdict.json'))) break }
+ const v = JSON.parse(readFileSync(join(ws, '.harness/verdict.json'), 'utf8'))
+ assert.equal(v.spec, 1)
+ assert.ok(v.summary)
+ assert.ok(Array.isArray(v.findings))
+ assert.ok(Array.isArray(v.phases))
+ } finally {
+ await viewer.close()
+ }
+})
+
+test('Jev Trader control commands answer 200', async () => {
+ const { ws, viewer } = await freshViewer()
+ try {
+ const port = viewer.url.split(':').pop()
+ const ctl = async (cmd) => {
+ const res = await fetch(`http://127.0.0.1:${port}/control`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) })
+ return res.status
+ }
+ assert.equal(await ctl('pause'), 200)
+ assert.equal(await ctl('tick'), 200)
+ assert.equal(await ctl('start'), 200)
+ assert.equal(await ctl('reset'), 200)
+ } finally {
+ await viewer.close()
+ }
+})
diff --git a/store/agents/jev-trader/toolchain/README.md b/store/agents/jev-trader/toolchain/README.md
new file mode 100644
index 000000000..50d91b604
--- /dev/null
+++ b/store/agents/jev-trader/toolchain/README.md
@@ -0,0 +1,20 @@
+# Toolchain
+
+`jev.mjs` is the shared Jev client: a tiny, dependency-free wrapper for TypeSafe AI's "System One"
+decision model (`POST /v1/systemone`), with a deterministic mock fallback so everything runs offline
+and in tests.
+
+- Without `TYPESAFE_API_KEY`, `evaluate()` returns deterministic, stable answers from a local mock —
+ it exercises the plumbing (typed questions, probability shaping, confidence) exactly as live Jev
+ would, but is **not** a stand-in for Jev's judgement.
+- With `TYPESAFE_API_KEY` set, the same call hits the real model.
+
+Three question types (see `jev.mjs` builders):
+
+- `jev.noul("...")` — a yes/no probability (0..1).
+- `jev.choice(options, "...")` — 1 of up to 255 options, plus per-option probabilities + confidence.
+- `jev.score(legend, "...")` — a position on a 2..10 level scale.
+
+`evaluate({ state, questions, key, model, salt })` returns `{ answers, model, client, usage }`,
+with `answers[questionId]` shaped by question type. Use it to audition your piece design before you
+commit to it — the viewer and any direct calls share the same client.
diff --git a/store/agents/jev-trader/toolchain/check.mjs b/store/agents/jev-trader/toolchain/check.mjs
new file mode 100644
index 000000000..c9ae9ff23
--- /dev/null
+++ b/store/agents/jev-trader/toolchain/check.mjs
@@ -0,0 +1,29 @@
+#!/usr/bin/env node
+// check.mjs — validate a market.json for the Jev Trader harness.
+// Enforces the shape the viewer needs: instrument name, sane price/volatility/drift/stepMs/capital.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const ws = process.env.HARNESS_WORKSPACE || '.'
+
+let fail = false
+const bad = (msg) => { fail = true; console.log(msg) }
+
+let market
+try {
+ market = JSON.parse(readFileSync(join(ws, 'market.json'), 'utf8'))
+} catch (e) {
+ console.log(`error cannot read market.json: ${e.message}`)
+ process.exit(1)
+}
+
+if (!market.instrument || typeof market.instrument !== 'string') bad('error instrument (a ticker string) is required')
+if (!market.title || typeof market.title !== 'string') bad('warn no title')
+if (typeof market.startPrice !== 'number' || market.startPrice <= 0) bad('error startPrice must be a positive number')
+if (typeof market.volatility !== 'number' || market.volatility < 0 || market.volatility > 0.2) bad('warn volatility should be 0..0.2 per step')
+if (typeof market.stepMs !== 'number' || market.stepMs < 200 || market.stepMs > 20000) bad('error stepMs must be ms 200..20000')
+if (typeof market.capital !== 'number' || market.capital <= 0) bad('error capital must be a positive number')
+if (!market.style || typeof market.style !== 'string') bad('warn a style line helps Jev trade coherently')
+
+console.log(fail ? 'fail invalid market.json' : 'ok market.json is valid')
+process.exit(fail ? 1 : 0)
diff --git a/store/agents/jev-trader/toolchain/doctor.sh b/store/agents/jev-trader/toolchain/doctor.sh
new file mode 100644
index 000000000..f45c1636a
--- /dev/null
+++ b/store/agents/jev-trader/toolchain/doctor.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Doctor: verify the runtime prerequisites for the Jev Trader viewer.
+set -euo pipefail
+if ! command -v node >/dev/null 2>&1; then echo "fail node is required (Node 18+)"; exit 1; fi
+if ! node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 18 ? 0 : 1)" 2>/dev/null; then
+ echo "fail node >= 18 required (found $(node -v))"; exit 1
+fi
+echo "ok node $(node -v)"
+echo "done"
diff --git a/store/agents/jev-trader/toolchain/init-workspace.sh b/store/agents/jev-trader/toolchain/init-workspace.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-trader/toolchain/init-workspace.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-trader/toolchain/jev.mjs b/store/agents/jev-trader/toolchain/jev.mjs
new file mode 100644
index 000000000..cd6bd5761
--- /dev/null
+++ b/store/agents/jev-trader/toolchain/jev.mjs
@@ -0,0 +1,437 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it returns a calibrated
+// probability distribution per question in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — returns per-option probabilities + a
+// `confidence` (how concentrated the mass is)
+// score a position on a 2..10 level scale — returns a float plus the same probabilities
+//
+// Questions are authored as options[] / legend{} and translated to the API's real wire format
+// (choice: criteria map, score: criteria level list) by toWire() — see below.
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The mock reads real
+// evidence out of the state text and turns it into plausible, stable distributions, so the
+// *plumbing* (typed questions, probability shaping, confidence) is exercised exactly as with the
+// live model. It is deliberately NOT a stand-in for Jev's judgement.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ if (key) return 'typesafe'
+ return 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the seed. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ h = (h >>> 0) / 4294967296
+ return h
+}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x))
+}
+
+/**
+ * Greedy grid navigation used by the mock when the state text is a grid map. Parses the lines the
+ * viewer renders: '.' empty, '#' wall, '$' coin, 'G' goal, '@' the agent. Returns, for the cardinal
+ * directions, an estimated gain (reduction in Manhattan distance to the goal) adjusted for walls,
+ * or null when no grid shape is present. Not a planner — just a competent reactive stand-in, exactly
+ * the class of behaviour Jev's own model produces from the same text.
+ */
+function gridNav(text) {
+ const lines = text.split('\n')
+ const grid = []
+ let hero = null, goal = null
+ let start = false
+ for (const line of lines) {
+ const t = line.trim()
+ // The world block is the run of lines made only of '.', '#', '$', 'G', '@' of equal length.
+ if (t.length > 2 && /^[.#$G@]+$/.test(t) && !/^[- ]/.test(line)) {
+ const row = t.split('')
+ grid.push(row)
+ for (let x = 0; x < row.length; x++) {
+ const c = row[x]
+ if (c === '@') hero = { x, y: grid.length - 1, row: grid.length - 1 }
+ else if (c === 'G') goal = { x, y: grid.length - 1 }
+ }
+ } else if (grid.length && /[^\s]/.test(t)) {
+ // Coordinates can also be given in prose; keep looking for goal/hero there.
+ if (!goal) { const m = t.match(/goal[:\s]*\((\d+),(\d+)\)/); if (m) goal = { x: +m[1], y: +m[2] } }
+ if (!hero) { const m = t.match(/\((\d+),(\d+)\)\.?\s+goal/i); if (m) hero = { x: +m[1], y: +m[2] } }
+ }
+ }
+ if (!grid.length) return null
+ const H = grid.length, W = grid[0].length
+ const wallAt = (x, y) => x < 0 || y < 0 || x >= W || y >= H || grid[y][x] === '#'
+ if (!hero || !goal) return null
+ const dist = (p) => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)
+ const base = dist(hero)
+ if (base === 0) return { gain: {}, trapped: null }
+ const dirs = [
+ ['up', 0, -1], ['down', 0, 1], ['left', -1, 0], ['right', 1, 0],
+ ]
+ const gain = {}
+ const trapped = {}
+ for (const [name, dx, dy] of dirs) {
+ const nx = hero.x + dx, ny = hero.y + dy
+ if (wallAt(nx, ny)) { gain[name] = -2; trapped[name] = false }
+ else { gain[name] = base - dist({ x: nx, y: ny }); trapped[name] = true }
+ }
+ const anyOpen = dirs.some(([, dx, dy]) => !wallAt(hero.x + dx, hero.y + dy))
+ return { gain, trapped: anyOpen ? null : trapped }
+}
+
+/**
+ * Market momentum read used by the mock when the state text carries recent price lines (the viewer
+ * renders a series like "day 12: 103.40"). We average the last few per-day returns into a trend in
+ * [-1, 1] and bias buy (positive) / sell (negative) / hold (near-flat). Real Jev reads the same
+ * text — the mock is a stand-in for that judgement, not a replacement.
+ */
+function marketMomentum(text) {
+ const prices = []
+ for (const m of text.matchAll(/(?:day\s*)?(\d+)\s*[:=]\s*\$?([0-9]+(?:\.[0-9]+)?)/gi)) {
+ prices.push({ day: Number(m[1]), price: Number(m[2]) })
+ }
+ if (prices.length < 3) return null
+ prices.sort((a, b) => a.day - b.day)
+ const p = prices.map((x) => x.price)
+ const last = p.length, n = Math.min(5, last)
+ // Simple moving average over the tail: trend = (avg(last half) - avg(first half)) / avg(all).
+ const old = p.slice(last - n, last - Math.floor(n / 2))
+ const recent = p.slice(last - Math.floor(n / 2))
+ const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length
+ const denom = avg(p)
+ if (!denom) return null
+ const trend = (avg(recent) - avg(old)) / denom
+ return { trend: Math.max(-1, Math.min(1, trend * 6)) }
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic mock. It turns the state text + question instructions into a plausible
+// distribution. Evidence = how strongly the state "mentions" something relevant to the question.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`.toLowerCase()
+ const qtext = `${q.instructions ?? ''} ${(q.criteria ?? []).join(' ')}`.toLowerCase()
+ const h = hash01(`${qid}::${qtext}` + (state ?? ''), salt)
+
+ if (q.type === 'noul') {
+ // Noul: a probability that something is true. The mock nudges it from the mere prior.
+ const mention = text.includes(qtext.split(' ').find((w) => w.length > 3) ?? '')
+ let p = 0.5 + (h - 0.5) * 0.5
+ if (mention) p = Math.min(0.95, p + 0.25)
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || q.choices || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ // If the state carries a grid of '.', '#' and 'G' with '@' marking the agent, the mock behaves
+ // like a competent reactive navigator: it greedily reduces distance to the goal while avoiding
+ // walls. Real Jev reads the same grid text — the mock is a stand-in for that judgement, not a
+ // replacement for it.
+ const nav = gridNav(text)
+ let raw = options.map((opt) => {
+ const optToks = String(opt).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
+ let score = 0.2
+ for (const tok of optToks) if (text.includes(tok)) score += 0.7
+ score += (hash01(String(opt), salt + 7) - 0.5) * 0.35
+ return score
+ })
+ if (nav) {
+ // Score the cardinal actions by how much each shrinks the distance to the goal.
+ options.forEach((opt, i) => {
+ const gain = nav.gain[String(opt)]
+ if (gain !== undefined) raw[i] += gain * 1.6
+ })
+ if (nav.trapped) {
+ // Boxed in: strongly prefer the one legal opening, or wait, so it visibly pauses.
+ options.forEach((opt, i) => {
+ if (nav.trapped[String(opt)]) raw[i] += 1.4
+ })
+ }
+ }
+ // Market: if the state carries recent price lines, bias buy/hold/sell by momentum.
+ const mom = marketMomentum(text)
+ if (mom) {
+ options.forEach((opt, i) => {
+ const oKey = String(opt).toLowerCase()
+ if (oKey.includes('buy') || oKey === 'long') raw[i] += mom.trend * 1.4
+ else if (oKey.includes('sell') || oKey === 'short') raw[i] -= mom.trend * 1.4
+ else if (oKey.includes('hold') && Math.abs(mom.trend) < 0.12) raw[i] += 0.6
+ })
+ }
+ // Softmax into a distribution.
+ const exps = raw.map((r) => Math.exp(r))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ const probs = raw.map((r, i) => exps[i] / sum)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const best = options[probs.indexOf(Math.max(...probs))]
+ const confidence = clamp(Math.max(...probs))
+ return { type: 'choice', choice: String(best), confidence, probabilities }
+ }
+ if (q.type === 'score') {
+ const levels = q.legend
+ ? Object.values(q.legend)
+ : Array.from({ length: Number(q.levels) || 5 }, (_, i) => String(i + 1))
+ const lo = 0, hi = levels.length - 1
+ const pos = clamp01(h)
+ const score = lo + pos * (hi - lo)
+ // A bell around `score` for the per-level probabilities.
+ const probs = levels.map((_, i) => Math.exp(-((i - score) ** 2) / 0.6))
+ const psum = probs.reduce((a, b) => a + b, 0)
+ const probabilities = {}
+ levels.forEach((lv, i) => (probabilities[String(lv)] = probs[i] / psum))
+ const confidence = clamp(Math.max(...Object.values(probabilities)))
+ return { type: 'score', score, confidence, legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+function clamp01(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function liveEvaluate(body, key) {
+ const endpoint = process.env.TYPESAFE_API_URL || LIVE_ENDPOINT
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) return res.json()
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const apiKey = key ?? process.env.TYPESAFE_API_KEY
+ const client = pickClient(apiKey)
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (client === 'typesafe') {
+ const data = await liveEvaluate({ model, state, questions: wire }, apiKey)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client: 'typesafe', model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/agents/jev-trader/toolchain/setup.sh b/store/agents/jev-trader/toolchain/setup.sh
new file mode 100644
index 000000000..9879df4c3
--- /dev/null
+++ b/store/agents/jev-trader/toolchain/setup.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+set -euo pipefail
+exit 0
diff --git a/store/agents/jev-trader/toolchain/viewer.sh b/store/agents/jev-trader/toolchain/viewer.sh
new file mode 100644
index 000000000..47b14e5e3
--- /dev/null
+++ b/store/agents/jev-trader/toolchain/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Launch the Jev Trader viewer (Jev trades a synthetic market, live).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+HARNESS_DSH_DIR="${HARNESS_DSH_DIR:-$PWD}"
+exec node viewer/viewer.mjs
diff --git a/store/agents/jev-trader/viewer/index.html b/store/agents/jev-trader/viewer/index.html
new file mode 100644
index 000000000..ec25c2dad
--- /dev/null
+++ b/store/agents/jev-trader/viewer/index.html
@@ -0,0 +1,56 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Jev Trader</title>
+<link rel="icon" href="data:," />
+<link rel="stylesheet" href="/studio.css" />
+</head>
+<body>
+<header id="topbar">
+ <div class="brand"><span class="dot"></span><h1>Jev Trader</h1></div>
+ <div id="title"></div>
+ <div class="stats">
+ <div class="stat"><label>Equity</label><span id="equity"></span></div>
+ <div class="stat"><label>Return</label><span id="return"></span></div>
+ <div class="stat"><label>Price</label><span id="price"></span></div>
+ <div class="stat"><label>Cash</label><span id="cash"></span></div>
+ <div class="stat"><label>Shares</label><span id="shares"></span></div>
+ </div>
+ <div class="controls">
+ <button id="play" class="primary">Play</button>
+ <button id="pause">Pause</button>
+ <button id="tick">Tick</button>
+ <button id="reset">Reset</button>
+ </div>
+</header>
+
+<main>
+ <section id="stage">
+ <div class="panel">
+ <div class="panel-title">Equity &amp; price</div>
+ <canvas id="chart"></canvas>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Trade tape</div>
+ <div id="tape"><span class="pulse"></span><span>waiting for the first tick…</span></div>
+ </div>
+ </section>
+
+ <aside id="rail">
+ <div class="panel">
+ <div class="panel-title">Jev's decisions</div>
+ <ol id="log"></ol>
+ </div>
+ <div class="panel">
+ <div class="panel-title">Last action</div>
+ <div id="last"></div>
+ </div>
+ </aside>
+</main>
+
+<script src="/studio.js"></script>
+<script src="/jev-hud.js" defer></script>
+</body>
+</html>
diff --git a/store/agents/jev-trader/viewer/jev-hud.js b/store/agents/jev-trader/viewer/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/agents/jev-trader/viewer/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/agents/jev-trader/viewer/studio.css b/store/agents/jev-trader/viewer/studio.css
new file mode 100644
index 000000000..3a091c404
--- /dev/null
+++ b/store/agents/jev-trader/viewer/studio.css
@@ -0,0 +1,68 @@
+:root {
+ --bg: #0a0b10; --panel: #12141c; --panel2: #171a24;
+ --ink: #e8eaf2; --dim: #8a90a6; --line: #262a38;
+ --accent: #c084fc; --cyan: #5eead4; --amber: #fbbf24; --rose: #fb7185; --ok: #34d399;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1200px 800px at 70% -10%, #171a2b 0%, var(--bg) 55%);
+ color: var(--ink); font: 14px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+#topbar {
+ display: flex; align-items: center; gap: 20px; padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(23,26,36,.9), rgba(18,20,28,.6));
+ backdrop-filter: blur(6px); flex-wrap: wrap;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font-size: 16px; font-weight: 700; letter-spacing: .5px; margin: 0; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+#title { color: var(--accent); font-size: 15px; font-weight: 700; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; }
+.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; }
+#equity { color: var(--cyan); }
+#return { color: var(--amber); }
+#price { color: var(--ink); }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
+button {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line);
+ border-radius: 8px; background: var(--panel2); color: var(--ink); cursor: pointer; transition: all .15s;
+}
+button:hover { border-color: var(--accent); color: #fff; }
+button.primary { background: linear-gradient(135deg, #7c3aed, #a855f7); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.1); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; min-width: 0; }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }
+.panel-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin-bottom: 10px; }
+#chart { width: 100%; height: 320px; background: #0d0f16; border: 1px solid #1c2030; border-radius: 8px; }
+#tape { display: flex; align-items: center; gap: 12px; font-size: 14px; min-height: 32px; flex-wrap: wrap; }
+#tape .pulse { width: 14px; height: 14px; border-radius: 50%; background: var(--dim); flex: none; }
+#tape.buy .pulse { background: var(--ok); box-shadow: 0 0 12px var(--ok); }
+#tape.sell .pulse { background: var(--rose); box-shadow: 0 0 12px var(--rose); }
+#tape .bar { display: inline-flex; gap: 16px; font-size: 13px; }
+#tape .bar b.trade { font-size: 13px; } #tape .trade.buy { color: var(--ok); } #tape .trade.sell { color: var(--rose); } #tape .trade.hold { color: var(--dim); }
+#tape .bar .eq { color: var(--cyan); } #tape .bar .conf { color: var(--dim); }
+
+#rail {
+ width: 340px; flex: none; border-left: 1px solid var(--line); padding: 16px;
+ display: flex; flex-direction: column; gap: 16px; overflow-y: auto; background: rgba(18,20,28,.5);
+}
+#log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; max-height: 46vh; overflow-y: auto; }
+#log li { font-size: 12px; color: var(--dim); display: flex; gap: 8px; align-items: baseline; }
+#log li .d { color: var(--accent); }
+#log li .act.buy { color: var(--ok); font-weight: 700; } #log li .act.sell { color: var(--rose); font-weight: 700; } #log li .act.hold { color: var(--dim); }
+#log li .pr { color: var(--ink); }
+#last { font-size: 14px; color: var(--dim); }
+#last b.trade { font-size: 16px; } #last b.buy { color: var(--ok); } #last b.sell { color: var(--rose); } #last b.hold { color: var(--dim); }
+
+@media (max-width: 860px) {
+ main { flex-direction: column; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); }
+}
diff --git a/store/agents/jev-trader/viewer/studio.js b/store/agents/jev-trader/viewer/studio.js
new file mode 100644
index 000000000..ecb73a5c1
--- /dev/null
+++ b/store/agents/jev-trader/viewer/studio.js
@@ -0,0 +1,113 @@
+// Jev Trader pane — draws Jev's live paper-trading: equity + price curves, and the decision log.
+
+const $ = (id) => document.getElementById(id)
+const els = { title: $('title'), equity: $('equity'), return: $('return'), price: $('price'), cash: $('cash'), shares: $('shares'), chart: $('chart'), tape: $('tape'), log: $('log'), last: $('last') }
+
+let history = []
+let price = 100
+let capital = 10000
+let equityV = 10000
+
+function fmt(n, d = 0) { return n.toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d }) }
+
+function drawChart() {
+ const cv = els.chart, ctx = cv.getContext('2d')
+ const dpr = window.devicePixelRatio || 1
+ const W = cv.clientWidth, H = 320
+ cv.width = W * dpr; cv.height = H * dpr
+ ctx.scale(dpr, dpr)
+ ctx.clearRect(0, 0, W, H)
+ ctx.font = '10px ' + 'monospace'
+ ctx.textBaseline = 'top'
+
+ const pad = { l: 60, r: 14, t: 14, b: 24 }
+ const plotW = W - pad.l - pad.r, plotH = H - pad.t - pad.b
+ const px = (i) => pad.l + (history.length > 1 ? (i / (history.length - 1)) * plotW : pad.l)
+ // normalize both series to their own min/max over the visible window
+ const prices = history.map((h) => h.price)
+ const equities = history.map((h) => h.equity)
+ const all = [...prices, ...equities]
+ const lo = Math.min(...all), hi = Math.max(...all)
+ const span = (hi - lo) || 1
+ const py = (v) => pad.t + plotH - ((v - lo) / span) * plotH
+ const line = (key, color) => {
+ ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.beginPath()
+ history.forEach((h, i) => { const x = px(i), y = py(h[key]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y) })
+ ctx.stroke()
+ }
+ // gridlines + labels
+ ctx.strokeStyle = '#1c2030'; ctx.lineWidth = 1; ctx.fillStyle = '#6b7280'
+ for (let g = 0; g <= 4; g++) {
+ const y = pad.t + (g / 4) * plotH
+ ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(W - pad.r, y); ctx.stroke()
+ ctx.fillText((hi - (g / 4) * span).toFixed(0), 4, y)
+ }
+ line('price', '#c084fc')
+ line('equity', '#5eead4')
+ ctx.fillStyle = '#8a90a6'
+ ctx.fillText('price (violet)', pad.l + 6, H - 22)
+ ctx.fillText('equity (cyan)', pad.l + 90, H - 22)
+}
+
+function renderStats() {
+ els.equity.textContent = '$' + fmt(equityV, 0)
+ const ret = ((equityV - capital) / capital) * 100
+ els.return.textContent = (ret >= 0 ? '+' : '') + ret.toFixed(1) + '%'
+ els.return.style.color = ret >= 0 ? 'var(--ok)' : 'var(--rose)'
+ els.price.textContent = '$' + fmt(price, 2)
+}
+
+function renderLog() {
+ els.log.textContent = ''
+ for (const h of history.slice(-40)) {
+ const li = document.createElement('li')
+ li.innerHTML = `<span class="d">d${h.day}</span><span class="act ${h.action.toLowerCase()}">${h.action}</span><span class="pr">$ ${fmt(h.price)}</span><span>x${h.shares}</span><span>eq ${fmt(h.equity, 0)}</span>`
+ els.log.appendChild(li)
+ }
+ els.log.scrollTop = els.log.scrollHeight
+}
+
+function renderTape(msg) {
+ const last = history[history.length - 1]
+ els.tape.className = ''
+ if (!last) { els.tape.textContent = ''; const p = document.createElement('span'); p.className = 'pulse'; const s = document.createElement('span'); s.textContent = 'waiting for the first tick…'; els.tape.append(p, s); return }
+ els.tape.classList.add(last.action.toLowerCase())
+ const pulse = document.createElement('span'); pulse.className = 'pulse'
+ const bar = document.createElement('span'); bar.className = 'bar'
+ bar.innerHTML = `<b class="trade ${last.action.toLowerCase()}">${last.action}</b><span>x${last.shares} @ $${fmt(last.price, 2)}</span><span class="eq">$ ${fmt(last.equity, 0)}</span><span class="conf">conf ${(last.confidence * 100).toFixed(0)}%</span>`
+ els.tape.append(pulse, bar)
+ els.last.innerHTML = `<b class="trade ${last.action.toLowerCase()}">${last.action}</b> · x${last.shares} @ $${fmt(last.price, 2)}<br>conviction ${(last.conviction).toFixed(1)}/2 · equity $${fmt(last.equity, 0)}`
+}
+
+function onTick(msg) {
+ els.title.textContent = msg.title || ''
+ history = msg.history || history
+ price = msg.price ?? price
+ equityV = msg.equity ?? equityV
+ capital = capital || msg.history?.[0]?.equity || 10000
+ if (msg.cash !== undefined) els.cash.textContent = '$' + fmt(msg.cash, 0)
+ if (msg.holdings !== undefined) els.shares.textContent = String(msg.holdings)
+ renderStats()
+ renderTape()
+ renderLog()
+ drawChart()
+}
+
+$('play').onclick = () => ctl('start')
+$('pause').onclick = () => ctl('pause')
+$('tick').onclick = () => ctl('tick')
+$('reset').onclick = () => { history = []; capital = 10000; equityV = 10000; drawChart(); ctl('reset') }
+
+async function ctl(cmd) {
+ try { const r = await fetch('/control', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cmd }) }); if (!r.ok) throw new Error(String(r.status)) }
+ catch (e) { console.error('control failed', e) }
+}
+
+window.addEventListener('resize', drawChart)
+
+function connect() {
+ const es = new EventSource('/events')
+ es.addEventListener('state', (e) => onTick(JSON.parse(e.data)))
+ es.onerror = () => { /* auto-reconnect */ }
+}
+connect()
diff --git a/store/agents/jev-trader/viewer/viewer.mjs b/store/agents/jev-trader/viewer/viewer.mjs
new file mode 100644
index 000000000..dc4af9b46
--- /dev/null
+++ b/store/agents/jev-trader/viewer/viewer.mjs
@@ -0,0 +1,256 @@
+// Jev Trader viewer — a loopback server running a paper-trading simulator where Jev (TypeSafe's
+// System One model) is the trader. A synthetic market ticks every `market.stepMs`; Jev reads the
+// recent price tape + its portfolio and decides buy / hold / sell, with a confidence. The viewer
+// applies the trade, advances the market, and streams the price tape + equity curve to the pane.
+// The agent shapes market.json (instrument, volatility, starting capital, style). The strategy is
+// Jev's; the results are honest paper-trading P&L.
+//
+// Harness env: HARNESS_VIEWER_PORT, HARNESS_WORKSPACE. Workspace holds market.json (watched live).
+
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { evaluate, snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+const DEFAULT_MARKET = {
+ title: 'Jev’s Desk',
+ description: 'A paper account run by a System One decision model.',
+ instrument: 'SYNTH',
+ startPrice: 100,
+ volatility: 0.012, // per-step stdev of returns
+ drift: 0.0003, // small upward bias so flat motion still has signal
+ stepMs: 900,
+ capital: 10000,
+ style: 'Buy the trend, cut losses, keep some cash. You are a fast, disciplined trader.',
+}
+
+// Deterministic PRNG seeded per run so the market is reproducible within a session.
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+function stateBlock(market, prices, holdings, cash, equity) {
+ const tape = prices.slice(-10).map((p, i) => `day ${i + prices.length - 9}: ${p.toFixed(2)}`).join('\n')
+ return `You are a paper-trading decision model on a synthetic market.
+Instrument: ${market.instrument}. Style: ${market.style}
+Starting capital: $${market.capital}. Current cash: $${cash.toFixed(2)}; holdings: ${holdings} shares; equity: $${equity.toFixed(2)}.
+
+Recent price tape (last 10 days):
+${tape}
+
+Decide this period's action: BUY (add shares), HOLD (do nothing), or SELL (reduce shares). Respond with the action and
+how confident you are. You see only this tape and your own P&L.`
+}
+
+export async function startTraderViewer({ workspace, port = 0 } = {}) {
+ workspace = resolve(workspace)
+ mkdirSync(join(workspace, '.harness'), { recursive: true })
+
+ let market = readMarket(join(workspace, 'market.json'))
+ let rng = mulberry32(1337)
+ let prices = [market.startPrice]
+ let price = market.startPrice
+ let cash = market.capital
+ let holdings = 0
+ let clients = new Set()
+ let lastLine = null // the last frame sent, replayed to a pane that connects later
+ let stopped = false
+ let salt = 1
+ let running = false
+ let error = null
+ let history = [] // [{day, price, action, shares, cash, equity, confidence, at}]
+ let day = 0
+
+ function readMarket(file) {
+ try { return { ...DEFAULT_MARKET, ...JSON.parse(readFileSync(file, 'utf8')) } }
+ catch { return DEFAULT_MARKET }
+ }
+
+ function equityAt(p) { return cash + holdings * p }
+ function equity() { return equityAt(price) }
+
+ function broadcast(obj) {
+ const line = `event: state\ndata: ${JSON.stringify(obj)}\n\n`
+ lastLine = line
+ for (const c of clients) c.write(line)
+ }
+
+ function tail() {
+ const v = verdict(market, history, equity(), { error })
+ const file = join(workspace, '.harness/verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify(v))
+ renameSync(file + '.tmp', file)
+ broadcast({
+ type: 'tick',
+ title: market.title,
+ description: market.description,
+ instrument: market.instrument,
+ price,
+ cash,
+ holdings,
+ equity: equity(),
+ running,
+ error,
+ day,
+ history: history.slice(-120),
+ })
+ }
+
+ function advanceMarket() {
+ const ret = (rng() - 0.5) * 2 * market.volatility + market.drift
+ price = Math.max(0.01, price * (1 + ret))
+ prices.push(price)
+ day++
+ return price
+ }
+
+ async function decide() {
+ if (stopped) return
+ try {
+ advanceMarket() // the market moves even before Jev acts this period
+ const res = await evaluate({
+ state: stateBlock(market, prices, holdings, cash, equity()),
+ questions: {
+ action: {
+ type: 'choice',
+ instructions: 'Choose this period\'s action: BUY, HOLD, or SELL.',
+ options: ['BUY', 'HOLD', 'SELL'],
+ },
+ confident: {
+ type: 'noul',
+ instructions: 'Are you confident in this action, or guessing?',
+ },
+ conviction: {
+ type: 'score',
+ instructions: 'How strongly do you believe in this position?',
+ legend: { 0: 'weak', 1: 'moderate', 2: 'strong' },
+ },
+ },
+ salt: salt++,
+ model: process.env.JEV_MODEL || 'jev-latest',
+ })
+ const action = String(res.answers.action?.choice || 'HOLD').toUpperCase()
+ const confidence = typeof res.answers.confident?.noul === 'number' ? res.answers.confident.noul : 0.5
+ const conviction = typeof res.answers.conviction?.score === 'number' ? res.answers.conviction.score : 1
+ // Execute a plausible trade size (~10% of equity per BUY/SELL, scaled by conviction).
+ const target = Math.floor((equity() * 0.1 * (conviction + 0.5)) / price)
+ let execShares = 0
+ if (action === 'BUY' && target > 0 && cash >= target * price) {
+ cash -= target * price; holdings += target; execShares = target
+ } else if (action === 'SELL' && holdings > 0) {
+ const sell = Math.min(holdings, Math.max(1, target || Math.floor(holdings * 0.5)))
+ cash += sell * price; holdings -= sell; execShares = sell
+ }
+ history.push({ day, price, action, shares: execShares, cash, holdings, equity: equity(), confidence, conviction, at: new Date().toISOString(), client: res.client })
+ if (history.length > 400) history.splice(0, history.length - 400)
+ error = null
+ } catch (e) {
+ error = clean(e?.message ?? e?.name ?? String(e))
+ }
+ tail()
+ }
+
+ let timer = null
+ function schedule() { clearTimeout(timer); timer = setTimeout(run, market.stepMs) }
+ async function run() { if (stopped) return; await decide(); schedule() }
+ function start() { if (!running) { running = true; schedule() } }
+ function pause() { running = false; clearTimeout(timer) }
+ function reset() {
+ rng = mulberry32(1337); price = market.startPrice; prices = [price]; cash = market.capital; holdings = 0; day = 0; history = []; salt += 10; error = null
+ tail()
+ if (running) schedule()
+ }
+
+ const watcher = watch(workspace, { recursive: true }, (_, name) => {
+ if (!name) return
+ if (String(name).split('/').join('/') === 'market.json') {
+ market = readMarket(join(workspace, 'market.json'))
+ tail()
+ if (running) schedule()
+ }
+ })
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'index.html'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.js'))) }
+ if (req.method === 'GET' && url.pathname === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (req.method === 'GET' && url.pathname === '/jev-hud.js') { res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'jev-hud.js'))) }
+ if (req.method === 'GET' && url.pathname === '/studio.css') { res.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); return res.end(readFileSync(join(HERE, 'studio.css'))) }
+ if (req.method === 'GET' && url.pathname === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ title: market.title, instrument: market.instrument, price, cash, holdings, equity: equity(), running, day, history: history.slice(-120) })) }
+ if (req.method === 'GET' && url.pathname === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ clients.add(res)
+ if (lastLine) res.write(lastLine)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ if (req.method === 'POST' && url.pathname === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 1024) break }
+ const cmd = JSON.parse(body || '{}').cmd
+ if (cmd === 'pause') pause()
+ if (cmd === 'start') start()
+ if (cmd === 'reset') reset()
+ if (cmd === 'tick') await decide()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true }))
+ }
+ res.writeHead(404); res.end('Not found')
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+ tail()
+ start()
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ async close() { stopped = true; clearTimeout(timer); watcher.close(); for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+function verdict(market, history, equity, state) {
+ const start = market.capital
+ const ret = start ? ((equity - start) / start) * 100 : 0
+ const last = history[history.length - 1]
+ return {
+ spec: 1,
+ ready: history.length > 0,
+ summary: state.error
+ ? 'Jev Trader needs a fix'
+ : last
+ ? `${market.title || market.instrument} · $${equity.toFixed(0)} (${ret >= 0 ? '+' : ''}${ret.toFixed(1)}%) · ${last.action} · day ${last.day}`
+ : `${market.title || market.instrument} · waiting for the first tick`,
+ findings: (state.error ? [{ severity: 'error', kind: 'trader', message: state.error }] : []).concat(
+ ret < -20 ? [{ severity: 'warn', kind: 'trader', message: `Portfolio down ${ret.toFixed(1)}% — Jev may be overtrading a driftless market` }] : []
+ ),
+ artifact: 'market.json',
+ phases: [
+ { id: 'warm', name: 'Warm-up', state: history.length < 10 ? 'active' : 'done' },
+ { id: 'trade', name: 'Trading', state: history.length >= 10 ? 'active' : 'pending' },
+ ],
+ updatedAt: new Date().toISOString(),
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const workspace = process.env.HARNESS_WORKSPACE
+ const port = Number(process.env.HARNESS_VIEWER_PORT)
+ if (!workspace || !Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error('HARNESS_WORKSPACE and HARNESS_VIEWER_PORT are required')
+ const viewer = await startTraderViewer({ workspace, port })
+ console.log(`Jev Trader listening on ${viewer.url}`)
+ for (const s of ['SIGTERM', 'SIGINT']) process.once(s, () => viewer.close().then(() => process.exit(0)))
+}
diff --git a/store/showcase/jev-blocks/mind-on-the-board.jpg b/store/showcase/jev-blocks/mind-on-the-board.jpg
new file mode 100644
index 000000000..5cb66910c
Binary files /dev/null and b/store/showcase/jev-blocks/mind-on-the-board.jpg differ
diff --git a/store/showcase/jev-browser/booked-exactly-right.jpg b/store/showcase/jev-browser/booked-exactly-right.jpg
new file mode 100644
index 000000000..e9caa0835
Binary files /dev/null and b/store/showcase/jev-browser/booked-exactly-right.jpg differ
diff --git a/store/showcase/jev-browser/pick-the-flight.jpg b/store/showcase/jev-browser/pick-the-flight.jpg
new file mode 100644
index 000000000..acc3ed007
Binary files /dev/null and b/store/showcase/jev-browser/pick-the-flight.jpg differ
diff --git a/store/showcase/jev-compactor/context-tower.jpg b/store/showcase/jev-compactor/context-tower.jpg
new file mode 100644
index 000000000..785f8fad0
Binary files /dev/null and b/store/showcase/jev-compactor/context-tower.jpg differ
diff --git a/store/showcase/jev-firehose/triage-wall.jpg b/store/showcase/jev-firehose/triage-wall.jpg
new file mode 100644
index 000000000..8aefc01c5
Binary files /dev/null and b/store/showcase/jev-firehose/triage-wall.jpg differ
diff --git a/store/showcase/jev-fps/firefight.jpg b/store/showcase/jev-fps/firefight.jpg
new file mode 100644
index 000000000..25dbad0ad
Binary files /dev/null and b/store/showcase/jev-fps/firefight.jpg differ
diff --git a/store/showcase/jev-fps/pillar-hall.jpg b/store/showcase/jev-fps/pillar-hall.jpg
new file mode 100644
index 000000000..bf59a6a99
Binary files /dev/null and b/store/showcase/jev-fps/pillar-hall.jpg differ
diff --git a/store/showcase/jev-sheets/typed-column.jpg b/store/showcase/jev-sheets/typed-column.jpg
new file mode 100644
index 000000000..823b5cf5c
Binary files /dev/null and b/store/showcase/jev-sheets/typed-column.jpg differ
diff --git a/store/tools/jev-kit/README.md b/store/tools/jev-kit/README.md
new file mode 100644
index 000000000..e4fa7fd67
--- /dev/null
+++ b/store/tools/jev-kit/README.md
@@ -0,0 +1,183 @@
+# Building a flagship Jev harness
+
+You are building ONE harness for the OpenHarness store. A harness is a folder. When a person opens
+it, they get a **viewer on the left** (a live web pane) and a **coding agent in a chat on the
+right**. The agent edits one JSON file in the workspace; the viewer watches that file and reacts
+live. **The viewer is the experience.** It must be a joy to watch and to poke at. A plain canvas with
+a few shapes is a failure. Aim for something a person would screen-record and post.
+
+## What Jev is (facts, verified from the docs)
+
+Jev is TypeSafe AI's "System One" model. It never writes text. You send a `state` (text or JSON)
+plus a map of typed `questions`. It answers ALL questions in one parallel pass in roughly 100 ms,
+each with calibrated probabilities:
+
+- `noul` yes/no, returns `{ noul: 0..1 }`
+- `choice` one of up to 255 options, returns `{ choice, probabilities: {opt: p}, confidence }`
+- `score` a position on a 2 to 10 level scale, returns `{ score, legend, probabilities, confidence }`
+
+Price is $0.042 per million input tokens and output is free. State is encoded once and shared, and
+about 100 questions in one call cost almost no extra latency. So the idiomatic move is: **put shared
+facts in `state`, and ask MANY questions in ONE call.** Questions cannot see each other.
+
+What people post about Jev always flexes three numbers: **how fast, how cheap, how many.** Your
+viewer must show them, live.
+
+## The kit (copy it, do not rewrite it)
+
+Kit root: `store/tools/jev-kit/`. Copy these into your harness folder unchanged, then keep them current with `node store/tools/sync-jev-kit.mjs`:
+
+| kit file | goes to | what it is |
+|---|---|---|
+| `jev.mjs` | `toolchain/jev.mjs` | Jev client. Real API when `TYPESAFE_API_KEY` is set, else a deterministic mock. |
+| `kit.mjs` | `viewer/kit.mjs` | Loopback-only server: static files, `/state`, `/events` SSE, `/jev`, `/control`. Also `writeVerdict`, `watchConfig`, `mulberry32`, `clean`. |
+| `jev-hud.js` | `viewer/jev-hud.js` | The "Jev live mind" panel. Auto-mounts into `[data-jev-hud]`, else first in `#rail`. |
+| `base.css` | `viewer/base.css` | Shared look. Set `--accent` and `--accent2` in your `studio.css`. |
+| `LICENSE`, `THIRD_PARTY_NOTICES.md`, `.gitignore` | same names | boilerplate: copy from `store/agents/jev-fps/` |
+| `toolchain/setup.sh`, `init-workspace.sh`, `doctor.sh`, `viewer.sh`, `README.md` | `toolchain/` | boilerplate: copy from `store/agents/jev-fps/toolchain/`. Fix the harness name in the comments of `doctor.sh` and `viewer.sh`. Keep them executable (`chmod +x`). |
+
+`jev.mjs` API:
+
+```js
+import { evaluate, jev, snapshot } from '../toolchain/jev.mjs'
+const res = await evaluate({
+ state, // string | object | array
+ questions: { // ask many at once
+ team: jev.choice({ billing: 'payment or invoice problems', tech: 'bugs, outages' }, 'Which team owns this?'),
+ move: jev.choice(['LEFT', 'RIGHT', 'HOLD'], 'Which way?'),
+ urgent: jev.noul('Does this need a reply today?'),
+ anger: jev.score(['calm', 'annoyed', 'furious'], 'How angry is the customer?'),
+ },
+ salt, // mock only: vary per call
+ mock: (stateText, id, q, salt) => answerOrNull, // mock only: YOUR domain reader (see below)
+})
+res.answers.team // { type:'choice', choice:'tech', confidence:0.8, probabilities:{billing:.1, tech:.8} }
+res.client // 'typesafe' | 'mock'
+res.latencyMs
+```
+
+The generic mock scores word overlap between the state and each option's name plus description, so
+**always give options descriptions** and make synthetic text contain matching vocabulary. For a
+game or control loop, pass a `mock` function that parses your state text and returns a full answer
+object, in the same shape the API returns, with a real probability distribution (chosen option
+around 0.7 to 0.9, the rest spread, never exactly one-hot). Return `null` to fall through to the
+generic mock. The mock must read ONLY the state text that live Jev would also get. No peeking at
+hidden simulator variables. The mock is a stand-in for plumbing, and the HUD badges it `MOCK`.
+
+`kit.mjs` API: `serveViewer({ here, port, files?, state, control })` returns
+`{ url, broadcast(obj, event='state'), close() }`. `watchConfig(file, defaults, onChange)` returns
+`{ get(), error(), close() }`. `writeVerdict(workspace, {ready, summary, findings, artifact, phases})`.
+
+## Folder contract (the store's tests check all of this)
+
+```
+store/agents/<name>/
+ harness.json spec 1. id MUST be "autonomous/<name>". description <= 300 chars.
+ store.json ONLY these keys: homepage, upstream, license, tagline (<= 80 chars), examples[{prompt, caption}]. NO "$schema".
+ README.md must contain the exact heading "## Credit and stewardship"
+ AGENTS.md instructions for the chat agent
+ LICENSE THIRD_PARTY_NOTICES.md .gitignore
+ skills/<skill>/SKILL.md
+ template/<marker>.json the starter file the agent edits
+ toolchain/ jev.mjs check.mjs setup.sh init-workspace.sh doctor.sh viewer.sh README.md
+ viewer/ viewer.mjs kit.mjs index.html base.css studio.css studio.js jev-hud.js
+ test/viewer.test.mjs
+```
+
+Copy `harness.json`, `store.json`, `README.md`, `AGENTS.md`, `skills/*/SKILL.md` and
+`toolchain/check.mjs` structure from the reference harness `store/agents/jev-fps/` and rewrite
+every word for your harness. `harness.json` keeps the same shape: `engine: "claude"`,
+`workspace{template, marker, init}`, `agent{instructions, skills, env{JEV_DSH, JEV_MODEL}}`,
+`toolchain{setup, doctor}`, `viewer{command, url, artifactExtensions}`, `verdict`.
+
+`viewer.mjs` must export `async function start<Name>Viewer({ workspace, port = 0 })` returning
+`{ url, close() }`, and must run standalone from env `HARNESS_WORKSPACE` and `HARNESS_VIEWER_PORT`
+(see the bottom of `store/agents/jev-fps/viewer/viewer.mjs`). The viewer writes `.harness/verdict.json` itself.
+
+Rules for the words you write (README, AGENTS.md, SKILL.md, store.json):
+
+- It is a demo on synthetic data. Never present it as real trading, real security advice, real
+ medical or financial judgement, or a real product launch. Say the data is made up.
+- In AGENTS.md: the agent edits ONLY the marker JSON. It must never propose opening a browser,
+ changing ports, or running a second server. It must not edit `.harness/verdict.json`.
+- Plain, simple English. Short sentences. No hype words.
+- No trademarks in the harness name or id.
+
+## Viewer architecture
+
+- `viewer.mjs` owns the simulation. It ticks on a timer, calls `evaluate()` each decision, and
+ `broadcast()`s a compact state frame over SSE. Support `POST /control` commands at least
+ `pause`, `start`, `reset`, `tick` (advance exactly one decision, used by tests so they never wait
+ on timers), plus your own interaction commands.
+- Seed all randomness with `mulberry32` so runs are reproducible.
+- A bad JSON edit must never crash the demo. Keep the last good config and show the parse error in
+ the pane (`watchConfig` gives you this).
+- **Declare every `let` before the first function call that can touch it.** A past harness hit a
+ temporal-dead-zone error inside a try/catch, fell back to defaults silently, and ignored its
+ config. Add a test that a non-default config value really shows up in `/state`.
+- **Never end.** When an episode finishes, show the result for about 3 seconds, then start the next
+ episode on its own. An idle finished screen is a dead demo.
+- `studio.js` renders with `requestAnimationFrame` at 60 fps and interpolates between server frames,
+ so motion is smooth even when decisions arrive 8 to 10 times a second. Handle device pixel ratio
+ and resize. No frameworks, no CDNs, no network calls except to the viewer's own server.
+- Everything must work from `http://127.0.0.1:<port>/` inside an embedded pane about 900 to 1400 px
+ wide. Check 1100x800 as well as 1440x900.
+
+## The quality bar for the viewer
+
+1. **Alive in the first second.** Motion, numbers changing, no "press start".
+2. **Jev's mind is visible.** The kit HUD shows the questions and probability bars. Also tie the
+ decision into the main scene (an aim line, a highlight on the chosen option, a confidence glow).
+3. **The three numbers**: decisions per second, cost so far, items done. Large, in the top bar.
+4. **The person can play.** At least three real interactions in the pane (click, drag, type, slider,
+ buttons) that change what Jev faces, with instant visible effect. Explain them in one short line.
+5. **The difficulty dial is honest.** Easy settings: Jev does well. Hard settings: it visibly
+ struggles, because of a real limit (speed, noise, ambiguity), never injected randomness.
+ Prove the dial in a test.
+6. **Polish**: glow, particles, easing, trails, tabular numbers, no layout jumps, no overlapping
+ text, nothing clipped, no scrollbars in the main scene. Dark theme from `base.css`.
+7. **Honest**: the MOCK badge stays visible. Label synthetic data as synthetic.
+
+## Environment rules (important, the shell is restricted)
+
+- Work ONLY inside your harness folder and your scratch folder (both given in your task).
+- The shell refuses complex inline commands: no heredocs, no `for` loops with variables, no
+ `node -e` with long code, no `cd` to other repos. **Create and edit files with the Write and
+ Edit tools.** To run logic, write a `.mjs` file in your scratch folder and run `node <file>`.
+- Do NOT run any `git` command. Do not commit. The lead does that.
+- Do not install packages. Node 26 is available. No npm dependencies at all.
+- Use ports in your assigned range only.
+
+## How to look at your viewer (do this, more than once)
+
+`shot.mjs` in the kit drives a headless Chrome over CDP port 9333. Start one first:
+`"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless=new --remote-debugging-port=9333 --user-data-dir=<a scratch folder> about:blank`
+
+1. Write a tiny `serve.mjs` in your scratch folder that copies your `template/` into a temp
+ workspace and calls your `start<Name>Viewer({ workspace, port })` on a port in your range.
+ Run it in the background.
+2. `node store/tools/jev-kit/shot.mjs --url http://127.0.0.1:<port>/ --out <scratch>/a.png --wait 3000`
+ For interactions, write a `steps.json` (format is documented at the top of `shot.mjs`).
+3. Open the PNG with the Read tool and **look at it critically**. Fix what is ugly, empty, cramped,
+ overlapping or confusing. Repeat until it looks great. Any `PAGE EXCEPTION` or `PAGE console.error`
+ line printed by the tool is a bug to fix.
+4. Restart `serve.mjs` after you change `viewer.mjs` (it is a long-running process). Static files
+ are re-read on every request, so CSS and JS changes only need a new screenshot.
+
+## Tests and checks (all must pass before you report)
+
+- `node --test test/viewer.test.mjs` from your harness folder, with at least these tests:
+ the loop advances and Jev decides; config takes effect in `/state`; verdict file is written with
+ `spec:1`, `summary`, `findings[]`, `phases[]`; all control commands return 200; a bad JSON edit
+ keeps the demo alive and reports an error; a non-loopback `Host` header gets 403 (use a raw
+ `node:net` socket, because `fetch` will not let you override `Host`); **the difficulty dial**
+ (easy beats hard by a clear margin). Drive time with the `tick` control, not sleeps.
+- `harness dsh check .` from your harness folder prints `conforms to spec 1`.
+- `node toolchain/check.mjs` accepts the template and rejects an out-of-range value.
+- Screenshots reviewed at 1440x900 and 1100x800, with a clean page console.
+
+## Report back
+
+End with a short report: what you built, the interactions, the dial and its measured numbers, the
+test and check output (pass counts), the screenshot paths you judged final, and anything you know
+is weak. Be honest. If something does not work, say so.
diff --git a/store/tools/jev-kit/base.css b/store/tools/jev-kit/base.css
new file mode 100644
index 000000000..c41ddcd46
--- /dev/null
+++ b/store/tools/jev-kit/base.css
@@ -0,0 +1,83 @@
+/* base.css — the shared look of the Jev flagship viewers. Load before studio.css.
+ Set --accent / --accent2 in studio.css to give a harness its own colour. */
+:root {
+ --bg: #07080d; --panel: #10121a; --panel2: #161925; --line: #232838; --line2: #2e3550;
+ --ink: #e9ecf5; --dim: #8b92aa; --faint: #565d75;
+ --accent: #a78bfa; --accent2: #6d5bd0;
+ --ok: #34d399; --warn: #fbbf24; --bad: #fb7185; --cyan: #5eead4; --blue: #60a5fa;
+ --mono: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
+ --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ --radius: 12px;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body {
+ background: radial-gradient(1100px 700px at 75% -10%, color-mix(in srgb, var(--accent) 14%, transparent) 0%, transparent 60%), var(--bg);
+ color: var(--ink); font: 13px/1.45 var(--mono);
+ display: flex; flex-direction: column; overflow: hidden;
+}
+::selection { background: color-mix(in srgb, var(--accent) 45%, transparent); }
+::-webkit-scrollbar { width: 8px; height: 8px; }
+::-webkit-scrollbar-thumb { background: var(--line2); border-radius: 4px; }
+::-webkit-scrollbar-track { background: transparent; }
+
+#topbar {
+ display: flex; align-items: center; gap: 22px; padding: 10px 18px; flex: none; flex-wrap: wrap;
+ border-bottom: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(20,22,34,.92), rgba(10,11,18,.7)); backdrop-filter: blur(8px);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand h1 { font: 700 15px var(--mono); letter-spacing: .4px; margin: 0; white-space: nowrap; }
+.brand .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 14px var(--accent); animation: dot 2.4s ease-in-out infinite; }
+@keyframes dot { 50% { transform: scale(.72); opacity: .7; } }
+.brand .sub { color: var(--dim); font-size: 11px; }
+.stats { display: flex; gap: 20px; flex-wrap: wrap; }
+.stat { display: flex; flex-direction: column; min-width: 54px; }
+.stat label { font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px; color: var(--dim); }
+.stat span { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.controls { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+button, .btn {
+ font: 600 12px var(--mono); padding: 7px 13px; border: 1px solid var(--line2); border-radius: 8px;
+ background: var(--panel2); color: var(--ink); cursor: pointer; transition: border-color .15s, filter .15s, transform .05s; user-select: none;
+}
+button:hover { border-color: var(--accent); }
+button:active { transform: translateY(1px); }
+button.primary { background: linear-gradient(135deg, var(--accent2), var(--accent)); border-color: transparent; color: #fff; }
+button.primary:hover { filter: brightness(1.12); }
+button.ghost { background: transparent; }
+button.on { border-color: var(--accent); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
+button[disabled] { opacity: .45; cursor: default; }
+kbd { font: 600 10px var(--mono); padding: 1px 5px; border: 1px solid var(--line2); border-bottom-width: 2px; border-radius: 4px; color: var(--dim); }
+input[type=text], input[type=search], select, textarea {
+ font: 13px var(--mono); color: var(--ink); background: #0b0d14; border: 1px solid var(--line2); border-radius: 8px; padding: 7px 10px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+input[type=range] { accent-color: var(--accent); }
+
+main { flex: 1; display: flex; min-height: 0; }
+#stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow: auto; }
+#rail { width: 340px; flex: none; border-left: 1px solid var(--line); padding: 14px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; background: rgba(12,13,20,.55); }
+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; }
+.panel-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--dim); margin-bottom: 9px; display: flex; align-items: center; gap: 8px; }
+.panel-title .right { margin-left: auto; text-transform: none; letter-spacing: 0; }
+.how { color: var(--dim); font-size: 12.5px; line-height: 1.55; }
+.how b { color: var(--ink); } .how code { color: var(--warn); }
+.pill { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .8px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line2); color: var(--dim); }
+.pill.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
+.pill.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
+.pill.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 50%, transparent); }
+
+.canvas-wrap { position: relative; flex: 1; min-height: 320px; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: #05060a; }
+.canvas-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.banner { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); padding: 9px 20px; border-radius: 10px; font: 700 14px var(--mono); white-space: nowrap; backdrop-filter: blur(6px); }
+.banner.ok { background: rgba(16,185,129,.16); border: 1px solid var(--ok); color: var(--ok); box-shadow: 0 0 34px rgba(16,185,129,.35); }
+.banner.bad { background: rgba(225,29,72,.16); border: 1px solid var(--bad); color: var(--bad); box-shadow: 0 0 34px rgba(225,29,72,.35); }
+.hidden { display: none !important; }
+.cfg-error { margin: 0 16px; padding: 8px 12px; border: 1px solid var(--bad); border-radius: 8px; color: var(--bad); background: rgba(225,29,72,.08); font-size: 12px; }
+
+@media (max-width: 900px) {
+ main { flex-direction: column; overflow: auto; }
+ #rail { width: 100%; border-left: none; border-top: 1px solid var(--line); overflow: visible; }
+ body { overflow: auto; }
+}
diff --git a/store/tools/jev-kit/check-store-facts.mjs b/store/tools/jev-kit/check-store-facts.mjs
new file mode 100644
index 000000000..c7984347a
--- /dev/null
+++ b/store/tools/jev-kit/check-store-facts.mjs
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+// check-store-facts.mjs — a dependency-free mirror of the store's strict rules for a Jev harness's
+// harness.json and store.json (cli/src/dsh/registry.ts, StoreFactsSchema), plus the README and
+// LICENSE rules from cli/src/dsh/store.spec.ts. Run it before committing:
+//
+// node store/tools/jev-kit/check-store-facts.mjs every store/agents/jev-* folder
+// node store/tools/jev-kit/check-store-facts.mjs jev-fps just these
+import { existsSync, readFileSync, readdirSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const agents = join(dirname(dirname(dirname(fileURLToPath(import.meta.url)))), 'agents')
+const names = process.argv.slice(2).length ? process.argv.slice(2) : readdirSync(agents).filter((n) => n.startsWith('jev-'))
+const isUrl = (s) => { try { new URL(s); return true } catch { return false } }
+let bad = 0
+
+for (const name of names.sort()) {
+ const dir = join(agents, name), problems = []
+ const need = (ok, msg) => { if (!ok) problems.push(msg) }
+ try {
+ const m = JSON.parse(readFileSync(join(dir, 'harness.json'), 'utf8'))
+ need(m.id === `autonomous/${name}`, `harness.json id must be autonomous/${name}`)
+ need(typeof m.name === 'string' && m.name.length >= 1 && m.name.length <= 40, 'harness.json name must be 1..40 chars')
+ need(typeof m.description === 'string' && m.description.length <= 300, `harness.json description is ${m.description?.length} chars (max 300)`)
+ need(typeof m.category === 'string' && m.category.length <= 24, 'harness.json category must be <= 24 chars')
+ const f = JSON.parse(readFileSync(join(dir, 'store.json'), 'utf8'))
+ const allowed = ['homepage', 'upstream', 'license', 'tagline', 'screenshots', 'examples']
+ for (const k of Object.keys(f)) need(allowed.includes(k), `store.json has an unknown key "${k}"`)
+ for (const k of ['homepage', 'upstream']) if (f[k] !== undefined) need(isUrl(f[k]), `store.json ${k} must be a URL`)
+ need(f.tagline === undefined || (f.tagline.length >= 1 && f.tagline.length <= 80), `store.json tagline is ${f.tagline?.length} chars (max 80)`)
+ need(f.screenshots === undefined || (Array.isArray(f.screenshots) && f.screenshots.length <= 8 && f.screenshots.every(isUrl)), 'store.json screenshots must be up to 8 URLs')
+ need(f.examples === undefined || (Array.isArray(f.examples) && f.examples.length <= 8), 'store.json examples must be a list of up to 8')
+ for (const [i, e] of (f.examples ?? []).entries()) {
+ for (const k of Object.keys(e)) need(['prompt', 'image', 'caption'].includes(k), `examples[${i}] has an unknown key "${k}"`)
+ need(typeof e.prompt === 'string' && e.prompt.trim().length >= 1 && e.prompt.trim().length <= 600, `examples[${i}].prompt is ${e.prompt?.length} chars (1..600)`)
+ need(e.caption === undefined || (e.caption.trim().length >= 1 && e.caption.trim().length <= 120), `examples[${i}].caption is ${e.caption?.length} chars (max 120)`)
+ if (e.image !== undefined) {
+ need(isUrl(e.image) && e.image.startsWith('https://'), `examples[${i}].image must be an https URL`)
+ const local = e.image.match(/\/store\/showcase\/(.+)$/)
+ if (local) need(existsSync(join(agents, '..', 'showcase', local[1])), `examples[${i}].image points at store/showcase/${local[1]}, which does not exist`)
+ }
+ }
+ need(existsSync(join(dir, 'LICENSE')), 'LICENSE is missing')
+ need(/Credit and stewardship/.test(readFileSync(join(dir, 'README.md'), 'utf8')), 'README.md needs the heading "Credit and stewardship"')
+ } catch (e) { problems.push(e.message) }
+ if (problems.length) { bad++; console.log(`FAIL ${name}`); for (const p of problems) console.log(` ${p}`) } else console.log(`ok ${name}`)
+}
+console.log(bad ? `${bad} harness(es) would fail the store's tests` : 'every harness passes the store-facts rules')
+process.exit(bad ? 1 : 0)
diff --git a/store/tools/jev-kit/contract.mjs b/store/tools/jev-kit/contract.mjs
new file mode 100644
index 000000000..32ad6971b
--- /dev/null
+++ b/store/tools/jev-kit/contract.mjs
@@ -0,0 +1,111 @@
+// contract.mjs — node store/tools/jev-kit/contract.mjs
+// Contract test: run every harness's jev.mjs against a local fake of POST /v1/systemone that is
+// STRICT about the documented wire shape (choice: criteria map, score: criteria array, no
+// `options`/`legend` keys) and answers 422 otherwise. Also checks retry-on-529 and telemetry.
+import { createServer } from 'node:http'
+import { readdirSync, mkdtempSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const ROOT = join(dirname(dirname(dirname(fileURLToPath(import.meta.url)))), 'agents')
+let hits = 0, overloadFirst = false
+
+const server = createServer(async (req, res) => {
+ let body = ''
+ for await (const c of req) body += c
+ hits++
+ if (overloadFirst) { overloadFirst = false; res.writeHead(529); return res.end('overloaded') }
+ const fail = (msg) => { res.writeHead(422, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: msg })) }
+ let j
+ try { j = JSON.parse(body) } catch { return fail('not json') }
+ // Cloudflare Workers AI: same questions, wrapped as { model, input }, reply wrapped as { result }.
+ const cf = req.url === '/client/v4/accounts/acct-1/ai/run'
+ if (cf) {
+ if (req.headers.authorization !== 'Bearer cf-token') { res.writeHead(401); return res.end('bad token') }
+ if (j.model !== 'typesafe/jev' || !j.input) return fail('cloudflare wants { model: "typesafe/jev", input }')
+ j = { model: 'jev-latest', ...j.input }
+ } else if (req.headers.authorization !== 'Bearer test-key') { res.writeHead(401); return res.end('bad key') }
+ if (j.model !== 'jev-latest') return fail('model')
+ if (j.state == null) return fail('state required')
+ const answers = {}
+ for (const [id, q] of Object.entries(j.questions || {})) {
+ if ('options' in q || 'legend' in q || 'choices' in q || 'descriptions' in q || 'hints' in q || 'levels' in q) return fail(`${id}: unknown field`)
+ if (typeof q.instructions !== 'string' || !q.instructions) return fail(`${id}: instructions`)
+ if (q.type === 'choice') {
+ if (!q.criteria || Array.isArray(q.criteria) || typeof q.criteria !== 'object') return fail(`${id}: choice.criteria must be a map`)
+ const keys = Object.keys(q.criteria)
+ if (keys.length < 2 || keys.length > 255) return fail(`${id}: 2..255 options`)
+ if (!Object.values(q.criteria).every((v) => typeof v === 'string')) return fail(`${id}: descriptions must be strings`)
+ const probabilities = Object.fromEntries(keys.map((k, i) => [k, i === 0 ? 0.7 : 0.3 / (keys.length - 1)]))
+ answers[id] = { type: 'choice', choice: keys[0], probabilities, confidence: 0.6 }
+ } else if (q.type === 'score') {
+ if (!Array.isArray(q.criteria) || q.criteria.length < 2) return fail(`${id}: score.criteria must be an array of 2+`)
+ answers[id] = { type: 'score', score: 1.035, legend: Object.fromEntries(q.criteria.map((c, i) => [i, c])), confidence: 0.84 }
+ } else if (q.type === 'noul') {
+ if ('criteria' in q && (Array.isArray(q.criteria) || typeof q.criteria !== 'object')) return fail(`${id}: noul.criteria must be {true,false}`)
+ answers[id] = { type: 'noul', noul: 0.999 }
+ } else return fail(`${id}: type`)
+ }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ const reply = { model: 'jev-1.13', answers, usage: { input_tokens: 321, output_tokens: 12 } }
+ res.end(JSON.stringify(cf ? { result: reply, success: true, errors: [] } : reply))
+})
+await new Promise((r) => server.listen(0, '127.0.0.1', r))
+process.env.TYPESAFE_API_URL = `http://127.0.0.1:${server.address().port}/v1/systemone`
+
+let bad = 0
+for (const name of readdirSync(ROOT).filter((n) => n.startsWith('jev-')).sort()) {
+ const m = await import(join(ROOT, name, 'toolchain/jev.mjs'))
+ const { evaluate, jev, snapshot } = m
+ try {
+ overloadFirst = true // first call must survive one 529
+ const before = hits
+ const r = await evaluate({
+ key: 'test-key', state: 'The deploy failed twice and the customer is angry.',
+ questions: {
+ a: jev.choice(['billing', 'technical', 'sales'], 'Which team?'),
+ b: { type: 'choice', instructions: 'Which way?', options: ['LEFT', 'RIGHT'], criteria: ['be decisive'] },
+ c: jev.score({ 0: 'calm', 1: 'frustrated', 2: 'angry' }, 'How frustrated?'),
+ d: jev.noul('Is it urgent?', ['time pressure']),
+ e: jev.choice({ keep: 'still needed', drop: 'irrelevant now' }, 'Keep this tool result?'),
+ },
+ })
+ const s = snapshot()
+ const ok = r.client === 'typesafe' && r.answers.a.choice === 'billing' && r.answers.b.probabilities.LEFT === 0.7 &&
+ r.answers.c.score === 1.035 && r.answers.d.noul === 0.999 && r.answers.e.choice === 'keep' &&
+ hits - before === 2 && s.inputTokens === 321 && s.tokensEstimated === false && s.last.questions.length === 5 && r.latencyMs > 0
+ // and a bad key must fail fast with no retry
+ const h2 = hits
+ let threw = false
+ try { await evaluate({ key: 'nope', state: 'x', questions: { a: jev.noul('x?') } }) } catch { threw = true }
+ const fastFail = threw && hits - h2 === 1
+ // mock path still works and is metered
+ const mk = await evaluate({ key: '', state: 'aim x 3.0 target x 9.0', questions: { a: jev.choice(['LEFT', 'RIGHT'], 'go') } })
+ const mockOk = mk.client === 'mock' && typeof mk.answers.a.choice === 'string'
+ // Newer clients: a credentials file, and the Cloudflare route.
+ let routes = 'n/a'
+ if (typeof m.resolveCredentials === 'function') {
+ const dir = mkdtempSync(join(tmpdir(), 'jev-cred-'))
+ process.env.TYPESAFE_CREDENTIALS = join(dir, 'credentials')
+ process.env.CLOUDFLARE_API_BASE = `http://127.0.0.1:${server.address().port}`
+ writeFileSync(process.env.TYPESAFE_CREDENTIALS, '# comment\nCLOUDFLARE_ACCOUNT_ID=acct-1\nexport CLOUDFLARE_API_TOKEN="cf-token"\n')
+ await new Promise((r) => setTimeout(r, 0))
+ const c1 = m.resolveCredentials()
+ const viaCf = c1?.provider === 'cloudflare' ? await evaluate({ state: 'x', questions: { a: jev.choice({ keep: 'k', drop: 'd' }, 'Keep?') } }) : null
+ const forcedMock = await evaluate({ key: '', state: 'x', questions: { a: jev.noul('x?') } })
+ const safeLine = m.describeCredentials()
+ routes = c1?.provider === 'cloudflare' && viaCf?.client === 'cloudflare' && viaCf.answers.a.choice === 'keep' && forcedMock.client === 'mock' && !/cf-token/.test(safeLine)
+ delete process.env.TYPESAFE_CREDENTIALS; delete process.env.CLOUDFLARE_API_BASE
+ if (!routes) bad++
+ }
+ if (!(ok && fastFail && mockOk)) bad++
+ console.log(`${ok && fastFail && mockOk && routes !== false ? 'OK ' : 'BAD '} ${name.padEnd(14)} live=${ok} fastFail401=${fastFail} mock=${mockOk} credentialsFile+cloudflare=${routes}`)
+ } catch (e) {
+ bad++
+ console.log(`BAD ${name.padEnd(14)} ${e.message}`)
+ }
+}
+server.close()
+console.log(bad ? `CONTRACT FAIL (${bad})` : 'CONTRACT OK')
+process.exit(bad ? 1 : 0)
diff --git a/store/tools/jev-kit/jev-hud.js b/store/tools/jev-kit/jev-hud.js
new file mode 100644
index 000000000..1509ba180
--- /dev/null
+++ b/store/tools/jev-kit/jev-hud.js
@@ -0,0 +1,216 @@
+// jev-hud.js — "Jev's mind", live. A self-contained panel that polls the viewer's /jev route and
+// shows what Jev was just asked and the full probability distribution it answered with, plus the
+// numbers people care about: decisions per second, latency, tokens and cost.
+//
+// Drop-in: <script src="/jev-hud.js" defer></script>. It mounts into [data-jev-hud] if present,
+// else as the first panel of #rail, else as a floating card. No dependencies.
+(() => {
+ if (window.__jevHud) return
+ window.__jevHud = true
+
+ const css = `
+ .jh{--jh-ink:#e8eaf2;--jh-dim:#8a90a6;--jh-line:#262a38;--jh-bg:#12141c;--jh-acc:#a78bfa;--jh-ok:#34d399;--jh-warn:#fbbf24;--jh-bad:#fb7185;
+ font:12px/1.4 ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace;color:var(--jh-ink);background:var(--jh-bg);
+ border:1px solid var(--jh-line);border-radius:12px;padding:12px 14px;box-sizing:border-box}
+ .jh.float{position:fixed;right:14px;bottom:14px;width:320px;max-height:70vh;overflow:auto;z-index:50;box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);background:rgba(18,20,28,.92)}
+ .jh.float .jh-head{cursor:pointer;user-select:none}
+ .jh.float.mini{width:auto;max-width:320px;padding:8px 12px}
+ .jh.float.mini .jh-head{margin-bottom:0}
+ .jh.float.mini>*:not(.jh-head){display:none}
+ .jh-mini{display:none;font-size:11px;color:var(--jh-ink);font-variant-numeric:tabular-nums;white-space:nowrap}
+ .jh.float.mini .jh-mini{display:inline}
+ .jh.float.mini .jh-title{flex:none}
+ .jh *{box-sizing:border-box}
+ .jh-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
+ .jh-title{font-size:11px;letter-spacing:1.4px;text-transform:uppercase;color:var(--jh-dim);flex:1}
+ .jh-pulse{width:8px;height:8px;border-radius:50%;background:var(--jh-acc);box-shadow:0 0 0 0 rgba(167,139,250,.7)}
+ .jh-pulse.beat{animation:jhbeat .35s ease-out}
+ @keyframes jhbeat{0%{box-shadow:0 0 0 0 rgba(167,139,250,.8)}100%{box-shadow:0 0 0 9px rgba(167,139,250,0)}}
+ .jh-badge{font-size:10px;font-weight:700;letter-spacing:1px;padding:2px 7px;border-radius:999px;border:1px solid}
+ .jh-badge.mock{color:var(--jh-warn);border-color:rgba(251,191,36,.5);background:rgba(251,191,36,.08)}
+ .jh-badge.live{color:var(--jh-ok);border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
+ .jh-badge.err{color:var(--jh-bad);border-color:rgba(251,113,133,.5);background:rgba(251,113,133,.08)}
+ .jh-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:8px}
+ .jh-stat{background:rgba(255,255,255,.03);border:1px solid var(--jh-line);border-radius:8px;padding:6px 4px;text-align:center;min-width:0}
+ .jh-stat b{display:block;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .jh-stat span{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--jh-dim)}
+ .jh-spark{width:100%;height:26px;display:block;margin:2px 0 8px}
+ .jh-q{border-top:1px dashed var(--jh-line);padding-top:8px;margin-top:8px}
+ .jh-qh{display:flex;align-items:baseline;gap:6px;margin-bottom:5px}
+ .jh-qid{font-weight:700;color:var(--jh-acc)}
+ .jh-qt{font-size:9px;letter-spacing:1px;text-transform:uppercase;color:var(--jh-dim);border:1px solid var(--jh-line);border-radius:4px;padding:0 4px}
+ .jh-conf{margin-left:auto;color:var(--jh-dim);font-size:11px}
+ .jh-conf b{color:var(--jh-ink)}
+ .jh-row{display:grid;grid-template-columns:96px 1fr 38px;align-items:center;gap:6px;height:16px}
+ .jh-lab{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--jh-dim);font-size:11px}
+ .jh-row.top .jh-lab{color:var(--jh-ink);font-weight:700}
+ .jh-track{height:8px;border-radius:4px;background:rgba(255,255,255,.05);overflow:hidden}
+ .jh-bar{height:100%;width:0;border-radius:4px;background:linear-gradient(90deg,#6d5bd0,#a78bfa);transition:width .18s ease-out,background .18s}
+ .jh-row.top .jh-bar{background:linear-gradient(90deg,#10b981,#34d399)}
+ .jh-bar.no{background:linear-gradient(90deg,#be123c,#fb7185)}
+ .jh-val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--jh-dim)}
+ .jh-row.top .jh-val{color:var(--jh-ink)}
+ .jh-more{color:var(--jh-dim);font-size:10px;margin-top:2px}
+ .jh-scale{position:relative;height:22px;margin-top:2px}
+ .jh-scale i{position:absolute;top:8px;left:0;right:0;height:6px;border-radius:3px;background:linear-gradient(90deg,#34d399,#fbbf24,#fb7185);opacity:.55}
+ .jh-scale u{position:absolute;top:3px;width:4px;height:16px;border-radius:2px;background:#fff;box-shadow:0 0 8px #fff;transform:translateX(-2px);transition:left .18s ease-out}
+ .jh-lvl{font-size:11px;color:var(--jh-ink)}
+ .jh-foot{margin-top:10px;font-size:10px;color:var(--jh-dim);line-height:1.45}
+ .jh-foot code{color:var(--jh-warn)}
+ .jh-err{margin-top:8px;color:var(--jh-bad);font-size:11px;word-break:break-word}
+ `
+ const style = document.createElement('style')
+ style.textContent = css
+ document.head.appendChild(style)
+
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
+ const root = el('section', 'jh')
+ root.innerHTML = `
+ <div class="jh-head"><span class="jh-pulse"></span><span class="jh-title">Jev · live mind</span><span class="jh-mini"></span><span class="jh-badge mock">MOCK</span></div>
+ <div class="jh-stats">
+ <div class="jh-stat"><b data-k="rate">—</b><span>dec / s</span></div>
+ <div class="jh-stat"><b data-k="lat">—</b><span>latency</span></div>
+ <div class="jh-stat"><b data-k="tok">—</b><span>tok / call</span></div>
+ <div class="jh-stat"><b data-k="cost">—</b><span>cost</span></div>
+ </div>
+ <svg class="jh-spark" viewBox="0 0 200 26" preserveAspectRatio="none"><polyline fill="none" stroke="#a78bfa" stroke-width="1.5" points=""/></svg>
+ <div class="jh-qs"></div>
+ <div class="jh-err" hidden></div>
+ <div class="jh-foot"></div>`
+
+ function mount() {
+ const slot = document.querySelector('[data-jev-hud]')
+ const rail = document.getElementById('rail')
+ if (slot) slot.appendChild(root)
+ else if (rail) rail.insertBefore(root, rail.firstChild)
+ else {
+ root.classList.add('float', 'mini'); document.body.appendChild(root)
+ root.querySelector('.jh-head').title = 'Click to open or close Jev\'s live mind'
+ root.querySelector('.jh-head').addEventListener('click', () => root.classList.toggle('mini'))
+ }
+ }
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount()
+
+ const $k = (k) => root.querySelector(`[data-k="${k}"]`)
+ const qsBox = root.querySelector('.jh-qs')
+ const badge = root.querySelector('.jh-badge')
+ const pulse = root.querySelector('.jh-pulse')
+ const errBox = root.querySelector('.jh-err')
+ const foot = root.querySelector('.jh-foot')
+ const spark = root.querySelector('.jh-spark polyline')
+
+ const fmtMoney = (v) => v <= 0 ? '$0' : v < 0.0001 ? '<$.0001' : v < 1 ? '$' + v.toFixed(4).replace(/^0/, '') : '$' + v.toFixed(2)
+ const fmtInt = (v) => v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v))
+ const fmtLat = (ms) => ms < 1 ? '<1ms' : ms < 1000 ? Math.round(ms) + 'ms' : (ms / 1000).toFixed(1) + 's'
+
+ const blocks = new Map() // question id -> { key, node, rows }
+ const MAX_Q = 6, MAX_OPT = 6
+
+ function renderQuestion(q) {
+ const a = q.answer || {}
+ let shape = q.type
+ let opts = []
+ if (q.type === 'choice') {
+ const entries = Object.entries(a.probabilities || {})
+ const many = entries.length > MAX_OPT
+ opts = many ? entries.sort((x, y) => y[1] - x[1]).slice(0, MAX_OPT - 1) : entries
+ shape = 'choice:' + (many ? 'top' : entries.map((e) => e[0]).join('|'))
+ }
+ let b = blocks.get(q.id)
+ if (!b || b.key !== shape) {
+ if (b) b.node.remove()
+ const node = el('div', 'jh-q')
+ const head = el('div', 'jh-qh')
+ head.append(el('span', 'jh-qid', q.id), el('span', 'jh-qt', q.type))
+ const conf = el('span', 'jh-conf'); head.append(conf)
+ node.append(head)
+ node.title = q.instructions || ''
+ b = { key: shape, node, conf, rows: [] }
+ if (q.type === 'choice') {
+ const n = shape === 'choice:top' ? MAX_OPT - 1 : opts.length
+ for (let i = 0; i < n; i++) {
+ const row = el('div', 'jh-row'); const lab = el('span', 'jh-lab'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ }
+ b.more = el('div', 'jh-more'); node.append(b.more)
+ } else if (q.type === 'noul') {
+ const row = el('div', 'jh-row top'); const lab = el('span', 'jh-lab', 'yes'); const track = el('div', 'jh-track'); const bar = el('div', 'jh-bar'); const val = el('span', 'jh-val')
+ track.append(bar); row.append(lab, track, val); node.append(row); b.rows.push({ row, lab, bar, val })
+ } else {
+ const scale = el('div', 'jh-scale'); const strip = el('i'); const mark = el('u'); scale.append(strip, mark)
+ b.mark = mark; b.lvl = el('div', 'jh-lvl'); node.append(scale, b.lvl)
+ }
+ blocks.set(q.id, b)
+ qsBox.append(node)
+ }
+ if (q.type === 'choice') {
+ const total = Object.keys(a.probabilities || {}).length
+ opts.forEach(([name, p], i) => {
+ const r = b.rows[i]; if (!r) return
+ r.lab.textContent = name; r.lab.title = name
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.val.textContent = p >= 0.995 ? '1.00' : p.toFixed(2).replace(/^0/, '')
+ r.row.classList.toggle('top', name === a.choice)
+ })
+ b.more.textContent = total > opts.length ? `+ ${total - opts.length} more options` : ''
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ } else if (q.type === 'noul') {
+ const p = Number(a.noul ?? 0.5); const r = b.rows[0]
+ r.bar.style.width = Math.max(1.5, p * 100) + '%'
+ r.bar.classList.toggle('no', p < 0.5)
+ r.lab.textContent = p >= 0.5 ? 'yes' : 'no'
+ r.val.textContent = p.toFixed(2).replace(/^0/, '')
+ b.conf.innerHTML = `p(yes) <b>${p.toFixed(2)}</b>`
+ } else {
+ const legend = a.legend || {}; const n = Math.max(2, Object.keys(legend).length)
+ const s = Number(a.score ?? 0)
+ b.mark.style.left = Math.max(0, Math.min(100, (s / (n - 1)) * 100)) + '%'
+ const near = legend[String(Math.round(s))]
+ b.lvl.textContent = `${s.toFixed(2)} / ${n - 1}` + (near ? ` · ${near}` : '')
+ b.conf.innerHTML = `conf <b>${Number(a.confidence ?? 0).toFixed(2)}</b>`
+ }
+ }
+
+ let lastAt = 0
+ function render(s) {
+ const live = s.client && s.client !== 'mock'
+ const route = s.client === 'cloudflare' ? 'Cloudflare Workers AI' : 'the TypeSafe API'
+ badge.textContent = s.lastError ? 'ERROR' : live ? 'LIVE' : 'MOCK'
+ badge.className = 'jh-badge ' + (s.lastError ? 'err' : live ? 'live' : 'mock')
+ $k('rate').textContent = s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)
+ $k('lat').textContent = s.calls ? fmtLat(live ? s.avgLatencyMs : s.lastLatencyMs) : '—'
+ $k('tok').textContent = s.calls ? fmtInt(s.inputTokens / s.calls) : '—'
+ $k('cost').textContent = fmtMoney(s.costUsd)
+ root.querySelector('.jh-mini').textContent = `${s.questionsPerSec >= 10 ? Math.round(s.questionsPerSec) : s.questionsPerSec.toFixed(1)}/s · ${fmtMoney(s.costUsd)} ▾`
+ const lat = s.latencies || []
+ if (lat.length > 1) {
+ const max = Math.max(...lat, 1)
+ spark.setAttribute('points', lat.map((v, i) => `${(i / (lat.length - 1)) * 200},${24 - (v / max) * 22}`).join(' '))
+ }
+ errBox.hidden = !s.lastError
+ errBox.textContent = s.lastError || ''
+ foot.innerHTML = live
+ ? `Live Jev through ${route}. ${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers · ${fmtInt(s.inputTokens)} input tokens at ${s.pricePerMTok}/MTok. Output is free.`
+ : `${fmtInt(s.calls)} calls · ${fmtInt(s.questions)} typed answers. Running on the offline stand-in — cost is what live Jev would charge ($${s.pricePerMTok}/MTok). For the real model put <code>TYPESAFE_API_KEY=…</code> in <code>~/.config/typesafe/credentials</code>.`
+ if (s.last && s.last.at !== lastAt) {
+ lastAt = s.last.at
+ pulse.classList.remove('beat'); void pulse.offsetWidth; pulse.classList.add('beat')
+ const qs = s.last.questions.slice(0, MAX_Q)
+ const ids = new Set(qs.map((q) => q.id))
+ for (const [id, b] of blocks) if (!ids.has(id)) { b.node.remove(); blocks.delete(id) }
+ qs.forEach(renderQuestion)
+ if (s.last.questions.length > MAX_Q) {
+ let more = qsBox.querySelector('.jh-more.all'); if (!more) { more = el('div', 'jh-more all'); qsBox.append(more) }
+ more.textContent = `+ ${s.last.questions.length - MAX_Q} more questions answered in the same call`
+ }
+ }
+ }
+
+ async function tick() {
+ if (!document.hidden) {
+ try { const r = await fetch('/jev', { cache: 'no-store' }); if (r.ok) render(await r.json()) } catch { /* viewer restarting */ }
+ }
+ setTimeout(tick, 200)
+ }
+ tick()
+})()
diff --git a/store/tools/jev-kit/jev.mjs b/store/tools/jev-kit/jev.mjs
new file mode 100644
index 000000000..190c7e9ac
--- /dev/null
+++ b/store/tools/jev-kit/jev.mjs
@@ -0,0 +1,403 @@
+// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
+// with a deterministic mock fallback so the whole harness runs without a key.
+//
+// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
+// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
+// noul yes/no — returns a single probability 0..1
+// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
+// score a position on a 2..10 level scale — a float plus per-level probabilities
+//
+// Questions are authored as options[] / legend{} (or an option -> description map) and translated
+// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
+//
+// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
+// deterministic local mock so development, tests and offline demos work. The generic mock reads
+// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
+// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
+// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
+
+const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
+
+export class JevError extends Error {}
+
+function pickClient(key) {
+ return key ? 'typesafe' : 'mock'
+}
+
+/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
+export function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i)
+ h = Math.imul(h, 16777619)
+ }
+ return (h >>> 0) / 4294967296
+}
+
+const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
+
+/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
+export function stems(text) {
+ const out = []
+ for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
+ if (w.length < 2 || STOP.has(w)) continue
+ out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
+ }
+ return out
+}
+
+/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
+function evidence(stateStems, needle) {
+ const want = [...new Set(stems(needle))]
+ if (!want.length) return 0
+ let hit = 0
+ for (const w of want) if (stateStems.has(w)) hit++
+ return (hit / Math.sqrt(want.length)) * 1.2
+}
+
+function softmax(raw, temp = 1) {
+ const m = Math.max(...raw)
+ const exps = raw.map((r) => Math.exp((r - m) / temp))
+ const sum = exps.reduce((a, b) => a + b, 0)
+ return exps.map((e) => e / sum)
+}
+
+// ---------------------------------------------------------------------------
+// The deterministic generic mock. It turns the state text + question wording into a plausible
+// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
+// ---------------------------------------------------------------------------
+function mockAnswer(state, qid, q, salt) {
+ const text = `${state ?? ''}`
+ const S = new Set(stems(text))
+ const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
+
+ if (q.type === 'noul') {
+ const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
+ const no = evidence(S, `${q.raw?.false ?? ''}`)
+ const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
+ return { type: 'noul', noul: clamp(p) }
+ }
+
+ if (q.type === 'choice') {
+ const options = q.options || []
+ if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
+ const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
+ const probs = softmax(raw, 0.6)
+ const probabilities = {}
+ options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
+ const bi = probs.indexOf(Math.max(...probs))
+ return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
+ }
+
+ if (q.type === 'score') {
+ const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
+ const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
+ // No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
+ if (raw.every((r) => Math.abs(r) < 0.26)) {
+ const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
+ levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
+ }
+ const probs = softmax(raw, 0.7)
+ const probabilities = {}
+ levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
+ const score = probs.reduce((acc, p, i) => acc + p * i, 0)
+ return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
+ }
+
+ return { type: q.type, ok: false }
+}
+
+function clamp(x) {
+ return Math.min(1, Math.max(0, x))
+}
+
+// Imports are hoisted, so they can live here with the code that needs them.
+import { readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+// ---------------------------------------------------------------------------
+// Wire format. The live API (POST /v1/systemone) takes, per question:
+// noul { type, instructions, criteria?: { true: "...", false: "..." } }
+// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
+// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
+// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
+// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
+// straight to the API is a 422.
+// ---------------------------------------------------------------------------
+const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
+
+/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
+export function canon(q = {}) {
+ const type = q.type
+ const out = { ...q, type, instructions: q.instructions ?? '' }
+ if (type === 'choice') {
+ const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
+ out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
+ out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ } else if (type === 'score') {
+ let levels
+ if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
+ else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
+ else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
+ out.levels = levels
+ out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
+ out.hints = []
+ } else {
+ out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
+ out.raw = isMap(q.criteria) ? q.criteria : null
+ }
+ // The mock scores evidence off `criteria` as a flat list of strings.
+ out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
+ return out
+}
+
+/** Exactly what the live API accepts. */
+export function toWire(questions = {}) {
+ const wire = {}
+ for (const [id, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
+ if (q.type === 'choice') {
+ const criteria = {}
+ for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
+ wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
+ } else if (q.type === 'score') {
+ wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
+ } else {
+ const w = { type: 'noul', instructions: q.instructions + hint }
+ if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
+ wire[id] = w
+ }
+ }
+ return wire
+}
+
+/** Make a live answer look like the mock's, so viewers read one shape. */
+function fromWire(ans, q) {
+ if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
+ if (q.type === 'choice') {
+ const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
+ const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
+ const top = best != null && probabilities[best] != null ? probabilities[best] : 0
+ return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
+ }
+ if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
+ return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
+}
+
+// ---------------------------------------------------------------------------
+// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
+// asked, the full probability distribution it answered with, how long it took and what it cost.
+// ---------------------------------------------------------------------------
+export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
+
+export const telemetry = {
+ client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
+ inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
+ lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
+}
+const recent = [] // { t, n } per call, for a sliding-window rate
+const latencies = []
+
+function meter({ client, model, wire, state, answers, usage, latencyMs }) {
+ const now = Date.now()
+ const nQ = Object.keys(wire).length
+ const real = Number(usage?.input_tokens)
+ const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
+ const tokens = Number.isFinite(real) && real > 0 ? real : est
+ telemetry.client = client
+ telemetry.model = model
+ telemetry.calls++
+ telemetry.questions += nQ
+ telemetry.inputTokens += tokens
+ telemetry.outputTokens += Number(usage?.output_tokens) || 0
+ telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
+ telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
+ telemetry.lastLatencyMs = latencyMs
+ latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
+ telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
+ telemetry.lastError = null
+ telemetry.last = {
+ at: now, tokens, latencyMs,
+ questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
+ }
+ recent.push({ t: now, n: nQ })
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+}
+
+/** A JSON-safe snapshot for the viewer's /jev route. */
+export function snapshot() {
+ const now = Date.now()
+ while (recent.length && now - recent[0].t > 5000) recent.shift()
+ const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
+ return {
+ ...telemetry,
+ callsPerSec: recent.length / span,
+ questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
+ latencies: latencies.slice(-40),
+ pricePerMTok: PRICE_PER_MTOK,
+ uptimeMs: now - telemetry.startedAt,
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+// ---------------------------------------------------------------------------
+// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
+// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
+// you happen to have open. Two live routes are supported, both speaking the same question format:
+// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
+// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
+// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
+// ---------------------------------------------------------------------------
+const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN']
+let credCache = null
+export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
+
+function readCredentialFile() {
+ const now = Date.now()
+ const path = credentialsPath()
+ if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
+ const values = {}
+ try {
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
+ if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
+ }
+ } catch { /* no file: fine */ }
+ credCache = { at: now, path, values }
+ return values
+}
+
+/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
+export function resolveCredentials(explicitKey) {
+ if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
+ // Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
+ // key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
+ if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
+ const file = readCredentialFile()
+ const get = (k) => process.env[k] || file[k] || ''
+ const key = explicitKey || get('TYPESAFE_API_KEY')
+ if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
+ const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
+ if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
+ return null
+}
+
+/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
+export function describeCredentials() {
+ const c = resolveCredentials()
+ if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
+ return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
+}
+
+async function liveEvaluate(body, cred) {
+ const endpoint = cred.url
+ const key = cred.secret
+ const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } } : body
+ let lastErr
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
+ try {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ })
+ if (res.ok) {
+ const data = await res.json()
+ // Cloudflare wraps the model's reply as { result, success, errors }.
+ if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
+ return data?.result?.answers ? data.result : data
+ }
+ const detail = await res.text().catch(() => '')
+ lastErr = new JevError(`Jev API ${res.status}: ${detail.slice(0, 200)}`)
+ if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
+ } catch (e) {
+ if (e instanceof JevError && !/ (429|529|5\d\d):/.test(e.message)) throw e
+ lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
+ }
+ }
+ throw lastErr
+}
+
+/**
+ * Evaluate a set of typed questions against a state. All questions share the state and are
+ * answered in one parallel pass — ask many at once, it is nearly free.
+ *
+ * @param {object} opts
+ * @param {string|object|Array} opts.state the shared context block
+ * @param {object} opts.questions map of id -> question (see the `jev` builders)
+ * @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
+ * @param {string} [opts.model] 'jev-latest' by default
+ * @param {number} [opts.salt] mock-only seed so different callers diverge
+ * @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
+ * @returns {{client, model, answers, usage, latencyMs}}
+ */
+export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
+ const cred = resolveCredentials(key)
+ const client = cred ? cred.provider : 'mock'
+ const wire = toWire(questions)
+ const t0 = performance.now()
+ try {
+ if (cred) {
+ const data = await liveEvaluate({ model, state, questions: wire }, cred)
+ const rawAnswers = data.answers || data
+ const answers = {}
+ for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
+ const latencyMs = performance.now() - t0
+ meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
+ return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
+ }
+ // Mock: local, deterministic, instant.
+ const text = typeof state === 'string' ? state : JSON.stringify(state)
+ const answers = {}
+ for (const [qid, raw] of Object.entries(questions)) {
+ const q = canon(raw)
+ answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
+ }
+ const latencyMs = performance.now() - t0
+ meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
+ return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
+ } catch (e) {
+ telemetry.errors++
+ telemetry.lastError = String(e?.message ?? e).slice(0, 240)
+ throw e
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Question builders
+// ---------------------------------------------------------------------------
+export const jev = {
+ /** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
+ noul(instructions, criteria = undefined) {
+ const q = { type: 'noul', instructions }
+ if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
+ * (descriptions make Jev sharper; they are sent as the API's `criteria`).
+ */
+ choice(options, instructions, criteria = undefined) {
+ const q = { type: 'choice', instructions }
+ if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
+ if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
+ return q
+ },
+ /**
+ * score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
+ * or is an ordered list of level labels. 2..10 levels.
+ */
+ score(legend, instructions) {
+ const q = { type: 'score', instructions }
+ q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
+ return q
+ },
+}
+
+export default jev
diff --git a/store/tools/jev-kit/kit.mjs b/store/tools/jev-kit/kit.mjs
new file mode 100644
index 000000000..f80d29b7d
--- /dev/null
+++ b/store/tools/jev-kit/kit.mjs
@@ -0,0 +1,112 @@
+// kit.mjs — the boring, security-relevant half of a Jev viewer, written once:
+// a loopback-only HTTP server with static files, /state, /events (SSE), /jev (telemetry) and
+// /control, plus an atomic verdict writer and a safe JSON config watcher.
+import { createServer } from 'node:http'
+import { watch, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'
+import { join, extname } from 'node:path'
+import { snapshot as jevSnapshot } from '../toolchain/jev.mjs'
+
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml' }
+
+export const clean = (v) => String(v ?? '').replace(/\x1b\[[0-9;]*m/g, '').slice(0, 2000)
+
+/** Deterministic PRNG so every run of a demo is reproducible. */
+export function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6D2B79F5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/**
+ * Serve a viewer.
+ * @param {object} o
+ * @param {string} o.here the viewer directory (static files live here)
+ * @param {number} o.port 0 = ephemeral
+ * @param {string[]} [o.files] static file names served from `here` ('index.html' is also '/')
+ * @param {function} o.state () => JSON-safe full state (GET /state, and the first SSE frame)
+ * @param {function} [o.control] async (cmd, body) => optional JSON-safe reply (POST /control)
+ */
+export async function serveViewer({ here, port = 0, files = ['index.html', 'base.css', 'studio.css', 'studio.js', 'jev-hud.js'], state, control }) {
+ const clients = new Set()
+ const allowed = new Set(files)
+
+ const server = createServer(async (req, res) => {
+ res.setHeader('cache-control', 'no-store')
+ res.setHeader('x-content-type-options', 'nosniff')
+ // Loopback only: a page on another origin (DNS rebinding) must not reach this server.
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host ?? '')) { res.writeHead(403); return res.end('Loopback only') }
+ const url = new URL(req.url, 'http://127.0.0.1')
+ const path = url.pathname
+ try {
+ if (req.method === 'GET') {
+ const name = path === '/' ? 'index.html' : path.slice(1)
+ if (allowed.has(name)) { res.writeHead(200, { 'content-type': TYPES[extname(name)] ?? 'application/octet-stream' }); return res.end(readFileSync(join(here, name))) }
+ if (path === '/state') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(state())) }
+ if (path === '/jev') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(jevSnapshot())) }
+ if (path === '/events') {
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive' })
+ res.write(`event: state\ndata: ${JSON.stringify(state())}\n\n`)
+ clients.add(res)
+ req.on('close', () => clients.delete(res))
+ return
+ }
+ }
+ if (req.method === 'POST' && path === '/control') {
+ let body = ''
+ for await (const c of req) { body += c; if (body.length > 65536) { res.writeHead(413); return res.end('Too large') } }
+ let j
+ try { j = JSON.parse(body || '{}') } catch { res.writeHead(400); return res.end('Bad JSON') }
+ const reply = control ? await control(String(j.cmd ?? ''), j) : null
+ res.writeHead(200, { 'content-type': 'application/json' })
+ return res.end(JSON.stringify({ ok: true, ...(reply && typeof reply === 'object' ? reply : {}) }))
+ }
+ res.writeHead(404); res.end('Not found')
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: clean(e?.message ?? e) }))
+ }
+ })
+
+ await new Promise((resolveP, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolveP) })
+
+ return {
+ url: `http://127.0.0.1:${server.address().port}`,
+ clients,
+ /** Push a named SSE event (default 'state') to every connected pane. */
+ broadcast(obj, event = 'state') {
+ const line = `event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`
+ for (const c of clients) c.write(line)
+ },
+ async close() { for (const c of clients) c.end(); server.closeAllConnections(); await new Promise((r) => server.close(r)) },
+ }
+}
+
+/** Atomic write of .harness/verdict.json (the harness reads this file; never edit it by hand). */
+export function writeVerdict(workspace, verdict) {
+ const dir = join(workspace, '.harness')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'verdict.json')
+ writeFileSync(file + '.tmp', JSON.stringify({ spec: 1, ...verdict, updatedAt: new Date().toISOString() }))
+ renameSync(file + '.tmp', file)
+}
+
+/**
+ * Load a JSON config merged over defaults, and re-load on every edit. A bad edit keeps the last
+ * good config and reports the parse error instead of crashing the demo.
+ * @returns {{ get(): object, error(): string|null, close(): void }}
+ */
+export function watchConfig(file, defaults, onChange) {
+ let cfg = { ...defaults }, err = null, timer = null
+ const load = () => {
+ try { cfg = { ...defaults, ...JSON.parse(readFileSync(file, 'utf8')) }; err = null }
+ catch (e) { err = existsSync(file) ? clean(`${file.split('/').pop()}: ${e.message}`) : null }
+ }
+ load()
+ let watcher = null
+ try {
+ watcher = watch(file, () => { clearTimeout(timer); timer = setTimeout(() => { load(); onChange?.(cfg, err) }, 40) })
+ } catch { /* file may not exist yet; defaults stand */ }
+ return { get: () => cfg, error: () => err, close() { clearTimeout(timer); watcher?.close() } }
+}
diff --git a/store/tools/jev-kit/shot.mjs b/store/tools/jev-kit/shot.mjs
new file mode 100644
index 000000000..8be518e6d
--- /dev/null
+++ b/store/tools/jev-kit/shot.mjs
@@ -0,0 +1,77 @@
+#!/usr/bin/env node
+// shot.mjs — look at a viewer. Drives a headless Chrome over CDP (no dependencies; Node 22+).
+//
+// node shot.mjs --url http://127.0.0.1:4801/ --out /abs/path/a.png [--wait 3000] [--w 1440] [--h 900] [--cdp 9333]
+// node shot.mjs --url ... --steps /abs/steps.json
+//
+// steps.json is a list run in order; each item is ONE of:
+// { "wait": 1500 } sleep ms
+// { "eval": "document.title" } run JS in the page, print the result (await-ed)
+// { "click": "#reset" } click the centre of the first element matching a selector
+// { "clickAt": [640, 360] } click at viewport x,y
+// { "type": "hello", "into": "#q" } focus a selector and type text (real key events)
+// { "key": "Enter" } press one key
+// { "shot": "/abs/path/b.png" } save a PNG
+// Console errors and uncaught exceptions from the page are printed — a clean run prints none.
+import { writeFileSync } from 'node:fs'
+
+const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []))
+const CDP = Number(args.cdp || 9333), W = Number(args.w || 1440), H = Number(args.h || 900)
+if (!args.url) { console.error('need --url'); process.exit(2) }
+const steps = args.steps
+ ? JSON.parse((await import('node:fs')).readFileSync(args.steps, 'utf8'))
+ : [{ wait: Number(args.wait || 3000) }, { shot: args.out }]
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+const target = await (await fetch(`http://127.0.0.1:${CDP}/json/new?about:blank`, { method: 'PUT' })).json()
+const ws = new WebSocket(target.webSocketDebuggerUrl)
+await new Promise((r, j) => { ws.onopen = r; ws.onerror = j })
+let nextId = 1
+const pending = new Map()
+ws.onmessage = (ev) => {
+ const m = JSON.parse(ev.data)
+ if (m.id && pending.has(m.id)) { const { r, j } = pending.get(m.id); pending.delete(m.id); m.error ? j(new Error(m.error.message)) : r(m.result) }
+ else if (m.method === 'Runtime.exceptionThrown') console.log('PAGE EXCEPTION:', m.params.exceptionDetails.exception?.description ?? m.params.exceptionDetails.text)
+ else if (m.method === 'Runtime.consoleAPICalled' && ['error', 'warning'].includes(m.params.type)) console.log(`PAGE console.${m.params.type}:`, m.params.args.map((a) => a.value ?? a.description).join(' '))
+ else if (m.method === 'Log.entryAdded' && m.params.entry.level === 'error') console.log('PAGE LOG ERROR:', m.params.entry.text, m.params.entry.url ?? '')
+}
+const send = (method, params = {}) => new Promise((r, j) => { const id = nextId++; pending.set(id, { r, j }); ws.send(JSON.stringify({ id, method, params })) })
+const evalJs = async (expression) => {
+ const res = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
+ if (res.exceptionDetails) throw new Error(res.exceptionDetails.exception?.description ?? res.exceptionDetails.text)
+ return res.result.value
+}
+const clickAt = async (x, y) => {
+ await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
+ await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
+ await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
+}
+
+try {
+ await send('Page.enable'); await send('Runtime.enable'); await send('Log.enable')
+ await send('Emulation.setDeviceMetricsOverride', { width: W, height: H, deviceScaleFactor: 1, mobile: false })
+ await send('Page.navigate', { url: args.url })
+ await sleep(600)
+ for (const s of steps) {
+ if (s.wait != null) await sleep(s.wait)
+ else if (s.eval != null) console.log('eval ->', JSON.stringify(await evalJs(s.eval)))
+ else if (s.click != null) {
+ const box = await evalJs(`(() => { const e = document.querySelector(${JSON.stringify(s.click)}); if (!e) return null; const r = e.getBoundingClientRect(); return [r.x + r.width / 2, r.y + r.height / 2] })()`)
+ if (!box) console.log('click: no element for', s.click); else await clickAt(box[0], box[1])
+ } else if (s.clickAt != null) await clickAt(s.clickAt[0], s.clickAt[1])
+ else if (s.type != null) {
+ if (s.into) await evalJs(`document.querySelector(${JSON.stringify(s.into)})?.focus()`)
+ for (const ch of String(s.type)) await send('Input.insertText', { text: ch })
+ } else if (s.key != null) {
+ const code = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8, ArrowUp: 38, ArrowDown: 40, ArrowLeft: 37, ArrowRight: 39, ' ': 32 }[s.key] ?? 0
+ for (const type of ['keyDown', 'keyUp']) await send('Input.dispatchKeyEvent', { type, key: s.key, code: s.key === ' ' ? 'Space' : s.key, windowsVirtualKeyCode: code, text: type === 'keyDown' && s.key === 'Enter' ? '\r' : undefined })
+ } else if (s.shot != null) {
+ const { data } = await send('Page.captureScreenshot', { format: 'png' })
+ writeFileSync(s.shot, Buffer.from(data, 'base64'))
+ console.log('shot ->', s.shot, `(hidden=${await evalJs('document.hidden')})`)
+ }
+ }
+} finally {
+ await fetch(`http://127.0.0.1:${CDP}/json/close/${target.id}`).catch(() => {})
+ ws.close()
+}
diff --git a/store/tools/jev-kit/showcase.mjs b/store/tools/jev-kit/showcase.mjs
new file mode 100644
index 000000000..bbec07a01
--- /dev/null
+++ b/store/tools/jev-kit/showcase.mjs
@@ -0,0 +1,60 @@
+#!/usr/bin/env node
+// showcase.mjs — take a store showcase picture of a Jev harness: real output, 1600x1000 JPEG under
+// 350 KB, saved to store/showcase/<harness>/<name>.jpg (the rules in store/README.md).
+//
+// node store/tools/jev-kit/showcase.mjs <harness> <name> [--wait 6000] [--steps steps.json] [--port 4990] [--config '{"k":1}']
+//
+// It boots the harness's own viewer on a temp workspace seeded from template/ (with --config merged
+// into the marker file), drives a headless Chrome on CDP port 9333 through shot.mjs, and converts
+// the PNG with macOS `sips`. A steps file uses shot.mjs's format; its last shot is the picture.
+import { mkdtempSync, cpSync, readFileSync, writeFileSync, mkdirSync, statSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { execFile, execFileSync } from 'node:child_process'
+import { promisify } from 'node:util'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+const STORE = dirname(dirname(HERE))
+const [harness, name, ...rest] = process.argv.slice(2)
+const opt = Object.fromEntries(rest.reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []))
+if (!harness || !name) { console.error('usage: showcase.mjs <harness> <name> [--wait ms] [--steps file] [--port n] [--config json]'); process.exit(2) }
+
+const dir = join(STORE, 'agents', harness)
+const manifest = JSON.parse(readFileSync(join(dir, 'harness.json'), 'utf8'))
+const ws = mkdtempSync(join(tmpdir(), `showcase-${harness}-`))
+cpSync(join(dir, manifest.workspace.template), ws, { recursive: true })
+if (opt.config) {
+ const marker = join(ws, manifest.workspace.marker)
+ writeFileSync(marker, JSON.stringify({ ...JSON.parse(readFileSync(marker, 'utf8')), ...JSON.parse(opt.config) }, null, 2))
+}
+const mod = await import(join(dir, 'viewer/viewer.mjs'))
+const start = mod[Object.keys(mod).find((k) => /^start.*Viewer$/.test(k))]
+const port = Number(opt.port || 4990)
+const viewer = await start({ workspace: ws, port })
+
+const png = join(ws, 'shot.png')
+const steps = opt.steps
+ ? JSON.parse(readFileSync(opt.steps, 'utf8')).map((s) => (s.shot ? { shot: png } : s))
+ : [{ wait: Number(opt.wait || 6000) }, { shot: png }]
+const stepsFile = join(ws, 'steps.json')
+writeFileSync(stepsFile, JSON.stringify(steps))
+try {
+ // Async on purpose: this process also hosts the viewer, so a blocking call would freeze the page.
+ const { stdout: out } = await promisify(execFile)(process.execPath, [join(HERE, 'shot.mjs'), '--url', `http://127.0.0.1:${port}/`, '--steps', stepsFile, '--w', '1600', '--h', '1000'], { encoding: 'utf8' })
+ for (const line of out.split('\n')) if (/PAGE (EXCEPTION|console\.error)/.test(line)) console.log(line)
+ const destDir = join(STORE, 'showcase', harness)
+ mkdirSync(destDir, { recursive: true })
+ const dest = join(destDir, `${name}.jpg`)
+ let kb = 0
+ for (const q of [82, 74, 66, 58, 50, 42]) {
+ execFileSync('sips', ['-s', 'format', 'jpeg', '-s', 'formatOptions', String(q), png, '--out', dest], { stdio: 'ignore' })
+ kb = statSync(dest).size / 1024
+ if (kb <= 350) { console.log(`${dest} ${kb.toFixed(0)} KB at quality ${q}`); break }
+ }
+ if (kb > 350) console.log(`WARNING: ${dest} is ${kb.toFixed(0)} KB, over the 350 KB limit`)
+} finally {
+ await viewer.close()
+ rmSync(ws, { recursive: true, force: true })
+}
+process.exit(0)
diff --git a/store/tools/sync-jev-kit.mjs b/store/tools/sync-jev-kit.mjs
new file mode 100644
index 000000000..c58ff6701
--- /dev/null
+++ b/store/tools/sync-jev-kit.mjs
@@ -0,0 +1,55 @@
+#!/usr/bin/env node
+// Keep every Jev harness's copy of the shared Jev kit identical to store/tools/jev-kit/.
+//
+// A package installs alone (a sparse checkout of its own folder), so a Jev harness cannot import a
+// file outside itself: each one carries its own copy of the kit files it uses.
+//
+// node store/tools/sync-jev-kit.mjs rewrite every copy from the canonical files
+// node store/tools/sync-jev-kit.mjs --check exit 1, naming each copy that differs
+//
+// Which files a harness carries:
+// viewer/jev-hud.js every Jev harness that has one (the "Jev live mind" panel)
+// viewer/kit.mjs, viewer/base.css, toolchain/jev.mjs
+// only harnesses built on the kit, recognised by viewer/kit.mjs.
+// (Older Jev harnesses keep their own jev.mjs, which carries their
+// domain readers; they are not overwritten.)
+import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
+import { dirname, join, relative } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const store = dirname(dirname(fileURLToPath(import.meta.url)))
+const KIT = join(store, 'tools', 'jev-kit')
+const ALWAYS = [['jev-hud.js', 'viewer/jev-hud.js']]
+const KIT_BUILT = [['kit.mjs', 'viewer/kit.mjs'], ['base.css', 'viewer/base.css'], ['jev.mjs', 'toolchain/jev.mjs']]
+
+export function plan(root = store) {
+ const out = []
+ const agents = join(root, 'agents')
+ for (const e of readdirSync(agents, { withFileTypes: true })) {
+ if (!e.isDirectory() || !e.name.startsWith('jev-')) continue
+ const dir = join(agents, e.name)
+ const files = existsSync(join(dir, 'viewer/kit.mjs')) ? [...ALWAYS, ...KIT_BUILT] : ALWAYS
+ for (const [from, to] of files) if (existsSync(join(dir, to))) out.push({ from: join(KIT, from), to: join(dir, to) })
+ }
+ return out
+}
+
+export function check(root = store) {
+ return plan(root).filter(({ from, to }) => readFileSync(from, 'utf8') !== readFileSync(to, 'utf8'))
+ .map(({ from, to }) => `${relative(root, to)} differs from ${relative(root, from)}`)
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ if (process.argv.includes('--check')) {
+ const problems = check()
+ for (const p of problems) console.log(p)
+ console.log(problems.length ? `${problems.length} copies drifted. Run: node store/tools/sync-jev-kit.mjs` : 'every Jev kit copy is current')
+ process.exit(problems.length ? 1 : 0)
+ }
+ let n = 0
+ for (const { from, to } of plan()) {
+ const want = readFileSync(from, 'utf8')
+ if (readFileSync(to, 'utf8') !== want) { writeFileSync(to, want); n++; console.log('updated', relative(store, to)) }
+ }
+ console.log(n ? `${n} copies updated` : 'every Jev kit copy was already current')
+}