Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(jev): persist reusable session capsules
Rahman8def988c2da8
diff --git a/app/api/v1/jev/route.test.ts b/app/api/v1/jev/route.test.tsindex 83de4a33..a03ecda1 100644--- a/app/api/v1/jev/route.test.ts+++ b/app/api/v1/jev/route.test.ts@@ -5,6 +5,7 @@ const {getSessionContext,getKey,readWindows,readCalibration,routeModel}=vi.hoistvi.mock("@/lib/auth/require-session",()=>({getSessionContext}));vi.mock("@/lib/config/store",()=>({hostCredentialStore:()=>({getKey})}));vi.mock("@/lib/workflow/jev-telemetry",()=>({readJevTelemetryWindows:readWindows,readJevCalibration:readCalibration}));+vi.mock("@/lib/agent/session-jev-preservation",()=>({jevPreservationStatus:vi.fn(async()=>({model:"~typesafe/jev-latest",credentialSource:"settings-ai/openrouter",openrouterConnected:true,liveSessions:3,archives:0,preservedLive:3,preservedArchives:0,pending:0}))}));vi.mock("@/lib/workflow/jev-services",()=>({routeModelWithJev:routeModel,budgetContextWithJev:vi.fn(),classifyMemoryAdmissionWithJev:vi.fn(),triageFailureWithJev:vi.fn(),assessRecipePromotionWithJev:vi.fn(),verifyActionOutcomeWithJev:vi.fn(),@@ -12,7 +13,7 @@ vi.mock("@/lib/workflow/jev-services",()=>({const {GET,POST}=await import("./route");beforeEach(()=>{getSessionContext.mockReset();getKey.mockReset();readWindows.mockReset();readCalibration.mockReset();routeModel.mockReset();getSessionContext.mockResolvedValue({role:"owner",session:{device_id:"dev-1"}});getKey.mockResolvedValue("never-return-me");readWindows.mockResolvedValue({today:{totalDecisions:1},days7:{totalDecisions:2},days30:{totalDecisions:3}});readCalibration.mockResolvedValue([]);routeModel.mockResolvedValue({kind:"mso.jev-decision.v1",route:"no-llm"});});describe("owner JEV control plane",()=>{- it("reports connection boolean and telemetry without exposing the OpenRouter key",async()=>{const r=await GET(),body=await r.json();expect(r.status).toBe(200);expect(body).toMatchObject({kind:"mso.jev-control-plane.v1",openrouterConnected:true,windows:{days30:{totalDecisions:3}}});expect(JSON.stringify(body)).not.toContain("never-return-me");});+ it("reports connection boolean and telemetry without exposing the OpenRouter key",async()=>{const r=await GET(),body=await r.json();expect(r.status).toBe(200);expect(body).toMatchObject({kind:"mso.jev-control-plane.v1",openrouterConnected:true,windows:{days30:{totalDecisions:3}},preservation:{liveSessions:3,preservedLive:3,pending:0}});expect(JSON.stringify(body)).not.toContain("never-return-me");});it("runs a bounded lab decision without executing tools",async()=>{const req=new Request("http://mso.test/api/v1/jev",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({decision_id:"model.route",state:{task:"route this"}})});const r=await POST(req as never);expect(r.status).toBe(200);expect(await r.json()).toMatchObject({route:"no-llm"});expect(routeModel).toHaveBeenCalledWith({task:"route this"},undefined,{correlationId:"web:dev-1"});});it("fails closed for non-owner callers",async()=>{getSessionContext.mockResolvedValue({role:"operator",session:{device_id:"dev-2"}});expect((await GET()).status).toBe(403);const req=new Request("http://mso.test/api/v1/jev",{method:"POST",headers:{"content-type":"application/json"},body:"{}"});expect((await POST(req as never)).status).toBe(403);});});diff --git a/app/api/v1/jev/route.ts b/app/api/v1/jev/route.tsindex 0a6b875e..d910c289 100644--- a/app/api/v1/jev/route.ts+++ b/app/api/v1/jev/route.ts@@ -4,6 +4,7 @@ import { hostCredentialStore } from "@/lib/config/store";import { DEFAULT_JEV_OPENROUTER_MODEL } from "@/lib/workflow/jev-openrouter";import { listJevDecisionDefinitions } from "@/lib/workflow/jev-decision-registry";import { readJevCalibration, readJevTelemetryWindows } from "@/lib/workflow/jev-telemetry";+import { jevPreservationStatus } from "@/lib/agent/session-jev-preservation";import { readSetupJson } from "@/lib/infra/setup-http";import { assessRecipePromotionWithJev, budgetContextWithJev, classifyMemoryAdmissionWithJev, routeModelWithJev, triageFailureWithJev, verifyActionOutcomeWithJev } from "@/lib/workflow/jev-services";@@ -14,10 +15,11 @@ const headers={"Cache-Control":"private, no-store"};export async function GET(){const context=await getSessionContext();if(!context?.session.device_id||context.role!=="owner")return NextResponse.json({error:"owner_role_required"},{status:403,headers});- const [openrouterKey,windows,calibration]=await Promise.all([+ const [openrouterKey,windows,calibration,preservation]=await Promise.all([hostCredentialStore().getKey(undefined,"openrouter"),readJevTelemetryWindows(),readJevCalibration(),+ jevPreservationStatus(),]);return NextResponse.json({kind:"mso.jev-control-plane.v1",@@ -26,6 +28,7 @@ export async function GET(){registry:listJevDecisionDefinitions(),windows,calibration,+ preservation,accounting:{actual:"Provider-reported JEV tokens/cost only.",estimated:"Avoided LLM/token/cost/latency fields are estimates and are never reported as actual savings."},},{headers});}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 4e63a36b..ee2deb2c 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -19,6 +19,12 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh- `release` record Windows taskbar fidelity+## 2026-09-27++**Added**++- `jev` persist reusable session capsules+## 2026-09-26**Added**diff --git a/docs/MEMORY-SAFETY.md b/docs/MEMORY-SAFETY.mdindex afb76430..835a1229 100644--- a/docs/MEMORY-SAFETY.md+++ b/docs/MEMORY-SAFETY.md@@ -95,6 +95,8 @@ widen retrieval grants for agents, operators or MCP clients.## Remaining integrations and release gates+JEV session preservation now writes a checksum-bound **value capsule** for every current session source. The capsule stores bounded semantic step summaries, unique tool routes, artifact references, decision metadata and the continuation packet; it does not store credentials or raw authorization material. `agent_session_resume` reuses the exact current capsule when its source SHA-256 and byte count still match, so even a session with zero probabilistic optimization recommendations retains a useful continuation asset. Capsule existence is preservation/value evidence, not raw-source deletion authority.+Jev now participates in **automatic observed workflow-memory admission** only.It may classify a bounded successful-route candidate as ignore, episodic, semantic,procedural, or candidate-recipe. Explicit user memory writes remain authoritative,diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 8b66587d..355ffbee 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,26 @@+## 2026-09-27 — JEV decision plane and value capsules++JEV is now a versioned bounded decision plane rather than a Workflow-only adapter.+Decision definitions, bounded state compilation, action proposal/execution separation,+post-action semantic verification, memory admission, model/context/failure routing and+metadata-only telemetry share one policy surface. JEV action proposals are held+server-side, expire, bind the exact capability contract digest and can auto-execute only+safe non-destructive reads through the existing MSO Capability Runtime; write/review/+destructive candidates remain on the normal explicit tool path.++Session preservation advances from a thin receipt to an exact-source+`mso.jev-session-capsule.v1`. Every capsule is bound to the current session SHA-256 and+byte count and retains bounded semantic steps, tool routes, artifact references, decision+metadata and the LLM continuation packet. `agent_session_resume` automatically includes+that capsule while the source identity still matches, so zero-recommendation sessions+still have useful continuation value. Capsule existence remains preservation/value+evidence and does not authorize deletion of raw session evidence.++Integrations → AI Providers exposes JEV connection state, actual provider-reported usage+separately from estimated avoided LLM impact, calibration/decision metadata, preservation+coverage and an owner-only bounded JEV Lab. Workflow Sessions explicitly distinguish JEV+DECISION, MCP ACTION and VERIFIED RESULT and show the continuation capsule value summary.+## 2026-09-27 — Windows taskbar fidelity releaseThe Windows desktop shell taskbar now follows the supplied Windows 11 reference@@ -42,7 +65,6 @@ code units and a raster icon re-encoded from magic-checked bytes, with mode`.env.local` with the existing constant-time compare; it does not add a secondpassword store. Deep links to `?section=devices` and `?section=about` still openthose panels, and mobile back returns to Account.-## 2026-09-26 — Crash-safe continuation and source-isolated agent workChatGPT/MCP continuation no longer depends on the user recovering a dead tab ordiff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.mdindex 2c6a7360..6656d53b 100644--- a/docs/WORKFLOW-GRAPH.md+++ b/docs/WORKFLOW-GRAPH.md@@ -238,6 +238,8 @@ For Jev, connect **OpenRouter** once in **Settings → AI** or **IntegrationsThe native Workflows UI exposes **Optimize** and a Flow Optimizer detail panel. Dirty graph edits are saved before opening the optimizer so preview/clone always operate on the revision the user can see. Jev mode shows OpenRouter Jev as the normal path, with explicit named-MCP fields retained only under a legacy/diagnostic override.+Workflow Sessions also retain a `mso.jev-session-capsule.v1` value packet after JEV preservation. The packet is exact-source checksum-bound and includes bounded semantic steps/tool routes/artifact refs plus the LLM continuation packet. It is surfaced in Workflow Sessions and automatically attached by `agent_session_resume` when still current. A zero-recommendation JEV result therefore still has reusable semantic value; it is not treated as permission to delete the source session.+The separate MCP capability `jev_action` is a policy gate, not an autonomous agent. `propose` scores only caller/host-supplied structured capability candidates and never executes. `execute` requires the server-held proposal id, rejects expired or capability-digest-stale proposals, and permits only selected safe non-destructive **read** capabilities. The call re-enters the normal MSO Capability Runtime, so token allowlists, argument constraints, workflow correlation and rate limits stay authoritative. Write/review/destructive candidates return to the normal explicit tool flow. Post-action Jev verification is a semantic signal alongside—not instead of—deterministic execution status.## Automatic learningdiff --git a/frontend/slices/workflows/components/workflow-session-details.tsx b/frontend/slices/workflows/components/workflow-session-details.tsxindex c59c6563..af8ddef8 100644--- a/frontend/slices/workflows/components/workflow-session-details.tsx+++ b/frontend/slices/workflows/components/workflow-session-details.tsx@@ -97,7 +97,7 @@ export function WorkflowSessionDetails({ view, node, onOpenTerminal, onOpenCode,<p className="mt-2 text-xs text-muted-foreground">Canvas shows intent-level steps. Click a step to inspect its grouped actions, commands, code, artifacts, and raw execution receipt.</p><div className="mt-2 flex flex-wrap items-center gap-2"><Button data-slot="use-jev-session" type="button" size="sm" variant="outline" className="h-7 text-[10px]" disabled={jevBusy} onClick={() => void runJev()}><BrainCircuit className="size-3.5"/>{jevBusy ? "Calculating…" : "Use JEV"}</Button><span className="text-[10px] text-muted-foreground">Review-first optimization packet for this session; no tools are executed.</span></div>{jevError ? <p className="mt-2 text-[10px] text-destructive">{jevError}</p> : null}- {jev ? <div data-slot="jev-session-output" className="mt-2 rounded-lg border bg-muted/15 p-2.5 text-[10px]"><div className="flex items-center gap-2"><Badge variant="outline" className="h-5 text-[9px]">JEV DECISION</Badge><Badge variant="outline" className="h-5 text-[9px]">{jev.provider}</Badge><span>{jev.summary.acceptedCount} accepted · {jev.summary.rejectedCount} rejected / {jev.summary.candidateCount} candidates</span><Button type="button" size="sm" variant="ghost" className="ml-auto h-6 text-[9px]" onClick={() => void navigator.clipboard?.writeText(JSON.stringify(jev.llmContext,null,2))}><Copy className="size-3"/>Copy for LLM</Button></div><div data-slot="jev-decision-metadata" className="mt-2 grid gap-1 rounded border bg-background/40 p-2 text-[9px] text-muted-foreground sm:grid-cols-2"><span>Decision v{jev.decision.version} · threshold {Math.round(jev.decision.threshold*100)}%</span><span>{jev.decision.model ?? "~typesafe/jev-latest"}{jev.decision.latencyMs != null ? ` · ${jev.decision.latencyMs} ms` : ""}</span><span>Provider input {jev.decision.inputTokens != null ? `${jev.decision.inputTokens} tokens` : "not reported"}</span><span>Actual JEV cost {jev.decision.actualCostUsd != null ? `${jev.decision.actualCostUsd.toFixed(6)}` : "not reported"}</span></div><div data-slot="jev-action-distinction" className="mt-2 flex flex-wrap gap-1.5"><Badge variant="outline" className="h-5 text-[9px]">MCP ACTION · not executed</Badge><Badge variant="outline" className="h-5 text-[9px]">VERIFIED RESULT · n/a</Badge></div>{jev.fallbackReason ? <p className="mt-1 text-muted-foreground">{jev.fallbackReason}</p> : null}<div className="mt-2 space-y-1">{jev.recommendations.slice(0,6).map(item=><div key={item.id} className="rounded border bg-background/40 p-2"><div className="font-medium">{Math.round(item.probability*100)}% · {item.title}</div><p className="mt-0.5 text-muted-foreground">{item.description}</p><div className="mt-1 font-mono text-[9px] text-muted-foreground">{item.actionRefs.slice(0,8).join(" · ")}</div></div>)}</div></div> : null}+ {jev ? <div data-slot="jev-session-output" className="mt-2 rounded-lg border bg-muted/15 p-2.5 text-[10px]"><div className="flex items-center gap-2"><Badge variant="outline" className="h-5 text-[9px]">JEV DECISION</Badge><Badge variant="outline" className="h-5 text-[9px]">{jev.provider}</Badge><span>{jev.summary.acceptedCount} accepted · {jev.summary.rejectedCount} rejected / {jev.summary.candidateCount} candidates</span><Button type="button" size="sm" variant="ghost" className="ml-auto h-6 text-[9px]" onClick={() => void navigator.clipboard?.writeText(JSON.stringify(jev.llmContext,null,2))}><Copy className="size-3"/>Copy for LLM</Button></div><div data-slot="jev-decision-metadata" className="mt-2 grid gap-1 rounded border bg-background/40 p-2 text-[9px] text-muted-foreground sm:grid-cols-2"><span>Decision v{jev.decision.version} · threshold {Math.round(jev.decision.threshold*100)}%</span><span>{jev.decision.model ?? "~typesafe/jev-latest"}{jev.decision.latencyMs != null ? ` · ${jev.decision.latencyMs} ms` : ""}</span><span>Provider input {jev.decision.inputTokens != null ? `${jev.decision.inputTokens} tokens` : "not reported"}</span><span>Actual JEV cost {jev.decision.actualCostUsd != null ? `${jev.decision.actualCostUsd.toFixed(6)}` : "not reported"}</span></div><div data-slot="jev-capsule-summary" className="mt-2 rounded border bg-background/40 p-2 text-[9px] text-muted-foreground">Continuation capsule · {jev.valueSummary.semanticStepCount} semantic steps · {jev.valueSummary.toolCount} unique tools · {jev.valueSummary.artifactRefCount} artifact refs</div><div data-slot="jev-action-distinction" className="mt-2 flex flex-wrap gap-1.5"><Badge variant="outline" className="h-5 text-[9px]">MCP ACTION · not executed</Badge><Badge variant="outline" className="h-5 text-[9px]">VERIFIED RESULT · n/a</Badge></div>{jev.fallbackReason ? <p className="mt-1 text-muted-foreground">{jev.fallbackReason}</p> : null}<div className="mt-2 space-y-1">{jev.recommendations.slice(0,6).map(item=><div key={item.id} className="rounded border bg-background/40 p-2"><div className="font-medium">{Math.round(item.probability*100)}% · {item.title}</div><p className="mt-0.5 text-muted-foreground">{item.description}</p><div className="mt-1 font-mono text-[9px] text-muted-foreground">{item.actionRefs.slice(0,8).join(" · ")}</div></div>)}</div></div> : null}{view.omittedEvents ? <p className="mt-2 text-[10px] text-muted-foreground">Projection uses the latest {view.shownEvents} of {view.totalEvents} events to stay fast. Raw session history remains the source of truth.</p> : null}</div><ScrollArea className="min-h-0 flex-1"><div className="space-y-3 p-3">diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.tsindex 0db242a3..8f3f58a6 100644--- a/frontend/slices/workflows/lib/api.ts+++ b/frontend/slices/workflows/lib/api.ts@@ -70,7 +70,7 @@ export type WorkflowLearningRecipeSummary = {sourceSessions:Array<{label:string;actionRef:string;eventRef:string;artifactRefs:string[]}>; forge:{eligible:boolean;promotion:"explicit"};};export async function listWorkflowLearning(force=false){const load=async()=> (await json<{recipes:WorkflowLearningRecipeSummary[]}>("/api/v1/workflows?learning=1")).recipes;return force?load():cachedWorkflowResource("learning",10000,load);}-export type JevSessionOptimization={provider:"jev"|"fallback";decision:{id:"session.optimize";version:number;threshold:number;model?:string;latencyMs?:number;inputTokens?:number;actualCostUsd?:number};source:{sessionLabel:string;observedAt:string;shownEvents:number;omittedEvents:number};summary:{candidateCount:number;acceptedCount:number;rejectedCount:number};recommendations:Array<{id:string;title:string;description:string;probability:number;actionRefs:string[]}>;llmContext:{kind:"mso.jev-session-optimization.v1";instruction:string;facts:string[];recommendations:Array<{id:string;probability:number;actionRefs:string[];guidance:string}>};fallbackReason?:string};+export type JevSessionOptimization={provider:"jev"|"fallback";decision:{id:"session.optimize";version:number;threshold:number;model?:string;latencyMs?:number;inputTokens?:number;actualCostUsd?:number};source:{sessionLabel:string;observedAt:string;shownEvents:number;omittedEvents:number};summary:{candidateCount:number;acceptedCount:number;rejectedCount:number};valueSummary:{semanticStepCount:number;toolCount:number;artifactRefCount:number};recommendations:Array<{id:string;title:string;description:string;probability:number;actionRefs:string[]}>;llmContext:{kind:"mso.jev-session-optimization.v1";instruction:string;facts:string[];recommendations:Array<{id:string;probability:number;actionRefs:string[];guidance:string}>};fallbackReason?:string};export async function optimizeSessionWithJev(id:string){return(await json<{optimization:JevSessionOptimization}>("/api/v1/agent-sessions",{method:"POST",body:JSON.stringify({action:"optimize-with-jev",id})})).optimization;}export type JevPreservationStatus={model:string;credentialSource:"settings-ai/openrouter";openrouterConnected:boolean;liveSessions:number;archives:number;preservedLive:number;preservedArchives:number;pending:number};export type JevPreservationBatch={total:number;cursor:number;nextCursor?:number;processed:number;preserved:number;skipped:number;failed:number;errors:string[]};diff --git a/frontend/slices/workflows/session-graph-ui.test.ts b/frontend/slices/workflows/session-graph-ui.test.tsindex 444cf6d2..4d752b96 100644--- a/frontend/slices/workflows/session-graph-ui.test.ts+++ b/frontend/slices/workflows/session-graph-ui.test.ts@@ -47,6 +47,8 @@ describe("Workflow session graph UI contract", () => {expect(sessionDetails).toContain("MCP ACTION · not executed");expect(sessionDetails).toContain("VERIFIED RESULT · n/a");expect(sessionDetails).toContain("Actual JEV cost");+ expect(sessionDetails).toContain('data-slot="jev-capsule-summary"');+ expect(sessionDetails).toContain("Continuation capsule");expect(learningPanel).toContain('data-slot="session-self-improve"');expect(learningPanel).toContain("Self-improve");expect(workflowApp).toContain("saveSessionWorkflowDraft");diff --git a/lib/agent/session-files.ts b/lib/agent/session-files.tsindex b205862a..67d23ed0 100644--- a/lib/agent/session-files.ts+++ b/lib/agent/session-files.ts@@ -132,6 +132,20 @@ export function normalizeSession(raw: AgentSession): AgentSession {return { ...base, estimatedTokens, lifetimeEstimatedTokens: Math.max(base.lifetimeEstimatedTokens, estimatedTokens) };}+export async function sessionFileIdentity(id: string): Promise<{ sha256: string; bytes: number }> {+ const file = fileFor(id);+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;+ try {+ handle = await fs.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);+ const stat = await handle.stat();+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_SESSION_BYTES) throw new Error("agent session has an invalid file shape");+ if ((stat.mode & 0o077) !== 0) throw new Error("agent session permissions are too broad; expected 0600");+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("agent session is not owned by the MSO user");+ const body = await handle.readFile();+ return { sha256: createHash("sha256").update(body).digest("hex"), bytes: body.length };+ } finally { await handle?.close().catch(() => undefined); }+}+export async function readSessionFile(id: string): Promise<AgentSession | null> {const file = fileFor(id);let handle: Awaited<ReturnType<typeof fs.open>> | null = null;diff --git a/lib/agent/session-jev-preservation.test.ts b/lib/agent/session-jev-preservation.test.tsindex ae132372..03acf6cb 100644--- a/lib/agent/session-jev-preservation.test.ts+++ b/lib/agent/session-jev-preservation.test.ts@@ -8,7 +8,7 @@ process.env.OS_AGENT_MEMORY_DIR=path.join(root,"memory");process.env.OS_AGENT_SESSION_ARCHIVE_DIR=path.join(root,"archives");process.env.OS_AGENT_SESSION_PRESERVATION_DIR=path.join(root,"preservation");vi.mock("@/lib/config/store",()=>({hostCredentialStore:()=>({getKey:vi.fn(async()=>"openrouter-key")})}));-vi.mock("@/lib/workflow/jev-session-optimizer",()=>({optimizeSessionWithJev:vi.fn(async(view:{session:{label:string}})=>({provider:"jev",source:{sessionLabel:view.session.label,observedAt:new Date().toISOString(),shownEvents:1,omittedEvents:0},recommendations:[],llmContext:{kind:"mso.jev-session-optimization.v1",instruction:"review",facts:["safe"],recommendations:[]}}))}));+vi.mock("@/lib/workflow/jev-session-optimizer",()=>({optimizeSessionWithJev:vi.fn(async(view:{session:{label:string};steps:Array<{ref:string}>})=>({provider:"jev",decision:{id:"session.optimize",version:1,threshold:.5,model:"typesafe/jev-test",latencyMs:4,inputTokens:12,actualCostUsd:.000001},source:{sessionLabel:view.session.label,observedAt:new Date().toISOString(),shownEvents:1,omittedEvents:0},summary:{candidateCount:0,acceptedCount:0,rejectedCount:0},recommendations:[],llmContext:{kind:"mso.jev-session-optimization.v1",instruction:"review",facts:["safe","semantic capsule"],recommendations:[]}}))}));vi.resetModules();const store=await import("./session-store");const preservation=await import("./session-jev-preservation");@@ -19,6 +19,12 @@ describe("JEV session preservation",()=>{const before=await preservation.jevPreservationStatus();expect(before).toMatchObject({openrouterConnected:true,liveSessions:1,preservedLive:0,pending:1});const batch=await preservation.optimizeSessionPreservationBatch({limit:6});expect(batch).toMatchObject({total:1,processed:1,preserved:1,failed:0});const after=await preservation.jevPreservationStatus();expect(after).toMatchObject({preservedLive:1,pending:0});+ const record=(await store.listAgentSessions("principal:jev",1))[0]!;+ const full=await store.getAgentSession("principal:jev",record.id);expect(full).toBeTruthy();+ const capsule=await preservation.readLiveJevSessionCapsule(full!);+ expect(capsule).toMatchObject({kind:"mso.jev-session-capsule.v1",sourceBytes:expect.any(Number),sourceSha256:expect.stringMatching(/^[a-f0-9]{64}$/),summary:{semanticStepCount:expect.any(Number)},continuation:{facts:expect.arrayContaining(["semantic capsule"])}});+ const resumed=await store.resumeAgentSession("principal:jev",record.id);+ expect(resumed.jevCapsule).toMatchObject({sourceSha256:capsule!.sourceSha256,sessionLabel:capsule!.sessionLabel});const replay=await preservation.optimizeSessionPreservationBatch({limit:6});expect(replay).toMatchObject({processed:1,preserved:0,skipped:1,failed:0});});});diff --git a/lib/agent/session-jev-preservation.ts b/lib/agent/session-jev-preservation.tsindex b0bb64dd..8462e4a9 100644--- a/lib/agent/session-jev-preservation.ts+++ b/lib/agent/session-jev-preservation.ts@@ -8,8 +8,8 @@ import { DEFAULT_JEV_OPENROUTER_MODEL } from "@/lib/workflow/jev-openrouter";import { optimizeSessionWithJev } from "@/lib/workflow/jev-session-optimizer";import { agentSessionLabel } from "./session-name";import { sessionGraph } from "./session-graph";-import { listSessionIds, listSessionRecords, normalizeSession, readSessionFile } from "./session-files";-import type { AgentSession } from "./session-types";+import { listSessionIds, listSessionRecords, normalizeSession, readSessionFile, sessionFileIdentity } from "./session-files";+import type { AgentSession, AgentSessionValueCapsule } from "./session-types";import { agentSessionPreservationRoot, hasAgentSessionArchiveJevReceipt, listAgentSessionArchives, readAgentSessionArchive, writeAgentSessionArchiveJevReceipt } from "./session-archive";export type JevPreservationStatus = { model: string; credentialSource: "settings-ai/openrouter"; openrouterConnected: boolean; liveSessions: number; archives: number; preservedLive: number; preservedArchives: number; pending: number };@@ -20,8 +20,89 @@ type Source = { kind: "live"; key: string; sessionId: string } | { kind: "archivfunction hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }function liveReceiptName(record: AgentSession): string { return `live-${record.id}-${hash(record.updatedAt).slice(0, 16)}.jev.json`; }async function root(): Promise<string> { const dir=agentSessionPreservationRoot(); await fs.mkdir(dir,{recursive:true,mode:0o700}); await fs.chmod(dir,0o700).catch(()=>undefined); return dir; }-async function hasLiveReceipt(record: AgentSession): Promise<boolean> { try { const raw=JSON.parse(await fs.readFile(path.join(await root(),liveReceiptName(record)),"utf8")) as Record<string,unknown>; return raw.schemaVersion===1&&raw.kind==="mso.jev-session-preservation.v1"&&raw.provider==="jev"&&raw.sessionId===record.id&&raw.updatedAt===record.updatedAt; } catch { return false; } }-async function writeLiveReceipt(record: AgentSession, optimization: Awaited<ReturnType<typeof optimizeSessionWithJev>>): Promise<void> { const dir=await root(),file=path.join(dir,liveReceiptName(record)),tmp=`${file}.${randomUUID()}.tmp`; const body=JSON.stringify(redactUnknown({schemaVersion:1,kind:"mso.jev-session-preservation.v1",provider:"jev",model:DEFAULT_JEV_OPENROUTER_MODEL,sessionId:record.id,sessionLabel:agentSessionLabel(record.name,record.title,record.cwd),updatedAt:record.updatedAt,preservedAt:new Date().toISOString(),optimization:optimization.llmContext}),null,2); await fs.writeFile(tmp,body,{encoding:"utf8",mode:0o600,flag:"wx"}); await fs.chmod(tmp,0o600); await fs.rename(tmp,file); await fs.chmod(file,0o600); }++function buildCapsule(+ record: AgentSession,+ view: ReturnType<typeof sessionGraph>,+ optimization: Awaited<ReturnType<typeof optimizeSessionWithJev>>,+ identity: { sha256: string; bytes: number },+): AgentSessionValueCapsule {+ const semanticSteps = view.steps.slice(-24).map((step) => {+ const tools = [...new Set(step.actions.map((action) => action.tool).filter((tool): tool is string => Boolean(tool)))].slice(0, 12);+ const artifactRefs = [...new Set(step.actions.flatMap((action) => action.artifact ? [action.artifact.ref] : []))].slice(0, 24);+ return {+ ref: step.ref,+ category: step.category,+ title: step.title.slice(0, 180),+ summary: step.summary.slice(0, 1200),+ tools,+ actionRefs: step.actions.map((action) => action.ref).slice(0, 48),+ artifactRefs,+ };+ });+ const toolCount = new Set(semanticSteps.flatMap((step) => step.tools)).size;+ const artifactRefCount = new Set(semanticSteps.flatMap((step) => step.artifactRefs)).size;+ return {+ kind: "mso.jev-session-capsule.v1",+ model: DEFAULT_JEV_OPENROUTER_MODEL,+ sourceSha256: identity.sha256,+ sourceBytes: identity.bytes,+ capturedAt: new Date().toISOString(),+ sessionLabel: agentSessionLabel(record.name, record.title, record.cwd),+ updatedAt: record.updatedAt,+ decision: {+ id: optimization.decision.id,+ version: optimization.decision.version,+ threshold: optimization.decision.threshold,+ provider: optimization.provider,+ ...(optimization.decision.model ? { model: optimization.decision.model } : {}),+ ...(optimization.decision.latencyMs != null ? { latencyMs: optimization.decision.latencyMs } : {}),+ ...(optimization.decision.inputTokens != null ? { inputTokens: optimization.decision.inputTokens } : {}),+ ...(optimization.decision.actualCostUsd != null ? { actualCostUsd: optimization.decision.actualCostUsd } : {}),+ },+ summary: {+ candidateCount: optimization.summary.candidateCount,+ acceptedCount: optimization.summary.acceptedCount,+ rejectedCount: optimization.summary.rejectedCount,+ semanticStepCount: semanticSteps.length,+ toolCount,+ artifactRefCount,+ },+ semanticSteps,+ recommendations: optimization.recommendations.map((row) => ({+ id: row.id,+ title: row.title,+ probability: row.probability,+ actionRefs: row.actionRefs,+ guidance: row.description,+ })),+ continuation: optimization.llmContext,+ };+}++export async function readLiveJevSessionCapsule(record: AgentSession): Promise<AgentSessionValueCapsule | null> {+ try {+ const file = path.join(await root(), liveReceiptName(record));+ const raw = JSON.parse(await fs.readFile(file, "utf8")) as {+ schemaVersion?: unknown; kind?: unknown; provider?: unknown; sessionId?: unknown; updatedAt?: unknown;+ sourceSha256?: unknown; sourceBytes?: unknown; capsule?: AgentSessionValueCapsule;+ };+ if (raw.schemaVersion !== 2 || raw.kind !== "mso.jev-session-preservation.v2" || raw.provider !== "jev" ||+ raw.sessionId !== record.id || raw.updatedAt !== record.updatedAt || typeof raw.sourceSha256 !== "string" ||+ typeof raw.sourceBytes !== "number" || raw.capsule?.kind !== "mso.jev-session-capsule.v1") return null;+ const current = await sessionFileIdentity(record.id);+ if (raw.sourceSha256 !== current.sha256 || raw.sourceBytes !== current.bytes ||+ raw.capsule.sourceSha256 !== current.sha256 || raw.capsule.sourceBytes !== current.bytes) return null;+ return raw.capsule;+ } catch { return null; }+}+async function hasLiveReceipt(record: AgentSession): Promise<boolean> { return Boolean(await readLiveJevSessionCapsule(record)); }+async function writeLiveReceipt(record: AgentSession, view: ReturnType<typeof sessionGraph>, optimization: Awaited<ReturnType<typeof optimizeSessionWithJev>>): Promise<void> {+ const identity = await sessionFileIdentity(record.id), capsule = buildCapsule(record, view, optimization, identity);+ const dir=await root(),file=path.join(dir,liveReceiptName(record)),tmp=`${file}.${randomUUID()}.tmp`;+ const body=JSON.stringify(redactUnknown({schemaVersion:2,kind:"mso.jev-session-preservation.v2",provider:"jev",model:DEFAULT_JEV_OPENROUTER_MODEL,sessionId:record.id,sessionLabel:capsule.sessionLabel,updatedAt:record.updatedAt,preservedAt:new Date().toISOString(),sourceSha256:identity.sha256,sourceBytes:identity.bytes,capsule}),null,2);+ await fs.writeFile(tmp,body,{encoding:"utf8",mode:0o600,flag:"wx"}); await fs.chmod(tmp,0o600); await fs.rename(tmp,file); await fs.chmod(file,0o600);+}function card(record: AgentSession): SessionCard { return { id:record.id,name:record.name,label:agentSessionLabel(record.name,record.title,record.cwd),title:record.title,source:record.source,status:"offline",receiverConnected:false,lastSeenAt:record.updatedAt,createdAt:record.createdAt,...(record.cwd?{cwd:record.cwd}:{}),eventCount:record.events.length,archiveCount:record.archiveCount,...(record.resumedFrom?{resumedFrom:record.resumedFrom}:{}),...(record.parentSessionId?{parentSessionId:record.parentSessionId}:{}) }; }async function sources(): Promise<Source[]> { const live=await listSessionIds(),archives=await listAgentSessionArchives(); return [...live.map(sessionId=>({kind:"live" as const,key:`live:${sessionId}`,sessionId})),...archives.map(row=>({kind:"archive" as const,key:`archive:${row.name}`,archiveName:row.name}))].sort((a,b)=>a.key.localeCompare(b.key)); }@@ -45,7 +126,7 @@ export async function optimizeSessionPreservationBatch(input: { cursor?: number;}const view=sessionGraph(record,card(record),120),optimization=await optimizeSessionWithJev(view);if(optimization.provider!=="jev")throw new Error(optimization.fallbackReason||"JEV decision unavailable");- if(source.kind==="live")await writeLiveReceipt(record,optimization);else{const archive=await readAgentSessionArchive(source.archiveName);await writeAgentSessionArchiveJevReceipt(source.archiveName,archive.sha256,{model:DEFAULT_JEV_OPENROUTER_MODEL,sessionId:record.id,sessionLabel:view.session.label,optimization:optimization.llmContext});}+ if(source.kind==="live")await writeLiveReceipt(record,view,optimization);else{const archive=await readAgentSessionArchive(source.archiveName);await writeAgentSessionArchiveJevReceipt(source.archiveName,archive.sha256,{model:DEFAULT_JEV_OPENROUTER_MODEL,sessionId:record.id,sessionLabel:view.session.label,optimization:optimization.llmContext});}preserved++;}catch(cause){failed++;errors.push(`${source.key}: ${cause instanceof Error?cause.message:"JEV preservation failed"}`.slice(0,320));}}diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.tsindex 8b1ca1d0..684a61a0 100644--- a/lib/agent/session-store.ts+++ b/lib/agent/session-store.ts@@ -4,6 +4,7 @@ import { conversationIndexReady, conversationLockTarget, listSessionRecords, priimport { normalizeAgentSessionCwd } from "./session-location";import { appendAgentSessionEvent } from "./session-mutations";import { requireOwned, summary } from "./session-record";+import { readLiveJevSessionCapsule } from "./session-jev-preservation";import type { AgentSession, AgentSessionResumePacket, AgentSessionSource, AgentSessionSummary } from "./session-types";export { appendAgentSessionEvent, maybeAutoTitleAgentSession, renameAgentSession, renameAgentSessionName, updateAgentSessionHistory } from "./session-mutations";export type { AgentSession,AgentSessionEvent,AgentSessionResumePacket,AgentSessionSource,AgentSessionSummary } from "./session-types";@@ -108,12 +109,14 @@ export async function resumeAgentSession(kind: "resumed",detail: `resumed ${targetId}`,});+ const jevCapsule = await readLiveJevSessionCapsule(target).catch(() => null);return {session: summary(target),memorySnapshot: target.memorySnapshot,...(target.contextSummary ? { contextSummary: target.contextSummary } : {}),recentHistory: target.history.slice(-24),recentEvents: target.events.slice(-40),+ ...(jevCapsule ? { jevCapsule } : {}),};}diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.tsindex e3eeebe5..98215bf0 100644--- a/lib/agent/session-types.ts+++ b/lib/agent/session-types.ts@@ -101,10 +101,26 @@ export interface AgentSessionSummary {historyTurns: number;}+export interface AgentSessionValueCapsule {+ kind: "mso.jev-session-capsule.v1";+ model: string;+ sourceSha256: string;+ sourceBytes: number;+ capturedAt: string;+ sessionLabel: string;+ updatedAt: string;+ decision: { id: string; version: number; threshold: number; provider: "jev" | "fallback"; model?: string; latencyMs?: number; inputTokens?: number; actualCostUsd?: number };+ summary: { candidateCount: number; acceptedCount: number; rejectedCount: number; semanticStepCount: number; toolCount: number; artifactRefCount: number };+ semanticSteps: Array<{ ref: string; category: SessionFlowCategory; title: string; summary: string; tools: string[]; actionRefs: string[]; artifactRefs: string[] }>;+ recommendations: Array<{ id: string; title: string; probability: number; actionRefs: string[]; guidance: string }>;+ continuation: { kind: "mso.jev-session-optimization.v1"; instruction: string; facts: string[]; recommendations: Array<{ id: string; probability: number; actionRefs: string[]; guidance: string }> };+}+export interface AgentSessionResumePacket {session: AgentSessionSummary;memorySnapshot: AgentMemorySnapshot;contextSummary?: string;recentHistory: unknown[];recentEvents: AgentSessionEvent[];+ jevCapsule?: AgentSessionValueCapsule;}diff --git a/lib/infra/connection-ui-layout.test.ts b/lib/infra/connection-ui-layout.test.tsindex 8cb630c9..b9314a29 100644--- a/lib/infra/connection-ui-layout.test.ts+++ b/lib/infra/connection-ui-layout.test.ts@@ -40,6 +40,7 @@ it("keeps AI Providers on the existing AI config/runtime SSOT and browser-only cexpect(CONNECTION_MANAGER_SCRIPT).toContain("Actual JEV input / cost · 30d");expect(CONNECTION_MANAGER_SCRIPT).toContain("Estimated LLM input / cost avoided · 30d");expect(CONNECTION_MANAGER_SCRIPT).toContain("Actual = provider-reported JEV usage");+ expect(CONNECTION_MANAGER_SCRIPT).toContain("Session value capsules");expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiTest=()=>json("/api/models/test"');expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiOauth=body=>json("/api/oauth/openai"');expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiRemove=provider=>json("/api/config?provider="');diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.tsindex 77597fc3..159f0926 100644--- a/lib/infra/connection-ui.ts+++ b/lib/infra/connection-ui.ts@@ -115,7 +115,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){const dynamic=Array.isArray(catalogResult?.providers)?catalogResult.providers:[],connected=Array.isArray(cfg?.providers)?cfg.providers:[],meta=new Map();for(const row of dynamic)meta.set(row.id,{id:row.id,name:row.name||row.id,...row});for(const row of connected)meta.set(row.id,{id:row.id,name:meta.get(row.id)?.name||row.id,...meta.get(row.id),...row});if(cfg.provider&&!meta.has(cfg.provider))meta.set(cfg.provider,{id:cfg.provider,name:cfg.provider});detail.replaceChildren(n("h2","AI Providers"),n("p","Alfa provider/model selection and credentials share the exact Settings SSOT. Saved keys stay server-side and are only shown masked."));- const openrouter=connected.find(row=>row.id==="openrouter"),jev=n("div",undefined,"connection-card"),jevTop=n("header",undefined,"connection-heading"),jevCopy=n("div");jevCopy.append(n("h3","JEV decision kernel"),n("small","~typesafe/jev-latest · OpenRouter Decisions API"));jevTop.append(jevCopy,n("span",openrouter?.hasKey?"Ready":"OpenRouter required","connection-state"));jev.append(jevTop,n("p","JEV reuses the same OpenRouter key managed here and in Settings → AI. No TypeSafe/JEV credential is stored separately.","identity-muted"));if(!openrouter?.hasKey){const jevKey=input("OpenRouter API key","","password"),jevActions=n("div",undefined,"identity-actions"),connectJev=b("Connect OpenRouter for JEV",async()=>{const apiKey=jevKey.input.value.trim();if(!apiKey){status.textContent="Enter an OpenRouter API key.";return}try{status.textContent="Connecting OpenRouter for JEV…";await bridge.aiSave({provider:"openrouter",apiKey,select:false});jevKey.input.value="";status.textContent="OpenRouter connected for JEV without changing the active AI model.";await aiProviders()}catch(e){status.textContent=textError(e)}},"primary");connectJev.disabled=!bridge.aiSave;jevActions.append(connectJev);jev.append(jevKey.label,jevActions)}detail.append(jev);if(jevStatus?.windows){const fmt=v=>Number.isFinite(Number(v))?Number(v):0,pct=v=>(Math.round(fmt(v)*1000)/10)+"%",usd=v=>"$"+fmt(v).toFixed(6),tokens=v=>Math.round(fmt(v)).toLocaleString(),w=jevStatus.windows,metrics=n("div",undefined,"identity-credential-status");for(const[label,row]of[["Today",w.today],["7 days",w.days7],["30 days",w.days30]]){const line=n("div");line.append(n("span",label+" decisions"),n("span",String(row?.totalDecisions||0),"credential-field-state"));metrics.append(line)}const actual=n("div");actual.append(n("span","Actual JEV input / cost · 30d"),n("span",tokens(w.days30?.actual?.jevInputTokens)+" / "+usd(w.days30?.actual?.jevCostUsd),"credential-field-state"));metrics.append(actual);const estimated=n("div");estimated.append(n("span","Estimated LLM input / cost avoided · 30d"),n("span",tokens(w.days30?.estimated?.inputTokensAvoided)+" / "+usd(w.days30?.estimated?.costAvoidedUsd),"credential-field-state"));metrics.append(estimated);const rates=n("div");rates.append(n("span","Escalation / verification success · 30d"),n("span",pct(w.days30?.escalationRate)+" / "+pct(w.days30?.verificationSuccessRate),"credential-field-state"));metrics.append(rates);jev.append(n("p","Default AI: "+String(cfg.provider||"—")+"/"+String(cfg.model||"—"),"identity-muted"),metrics,n("small","Actual = provider-reported JEV usage. Avoided LLM token/cost/latency figures are estimates, never actual savings."))}if(jevStatus?.registry){const lab=n("details",undefined,"connection-card"),summary=n("summary","JEV Lab · bounded decision test"),registry=n("div",undefined,"identity-credential-status");for(const row of jevStatus.registry){const line=n("div");line.append(n("span",row.id+" · v"+row.version+" · "+row.type),n("span","threshold "+Math.round(Number(row.threshold||0)*100)+"%","credential-field-state"));registry.append(line)}lab.append(summary,n("p","Inspect decision definitions and run a read-only semantic test. JEV Lab never executes tools, writes memory, or promotes recipes.","identity-muted"),registry);if(bridge.jevDecide){const decision=n("select"),decisionLabel=n("label","Test decision"),state=input("Bounded test state (JSON)",'{"task":"Should this request be escalated?"}'),result=n("pre",undefined,"identity-muted");for(const id of["model.route","failure.triage","recipe.promote"]){const o=n("option",id);o.value=id;decision.append(o)}decisionLabel.append(decision);const run=b("Run bounded test",async()=>{try{let parsed;try{parsed=JSON.parse(state.input.value)}catch{parsed={text:state.input.value}}status.textContent="Running JEV decision…";const out=await bridge.jevDecide({decision_id:decision.value,state:parsed});result.textContent=JSON.stringify(out,null,2).slice(0,4000);status.textContent="JEV Lab decision complete; no action executed."}catch(e){status.textContent=textError(e)}},"primary");lab.append(decisionLabel,state.label,run,result)}jev.append(lab)}+ const openrouter=connected.find(row=>row.id==="openrouter"),jev=n("div",undefined,"connection-card"),jevTop=n("header",undefined,"connection-heading"),jevCopy=n("div");jevCopy.append(n("h3","JEV decision kernel"),n("small","~typesafe/jev-latest · OpenRouter Decisions API"));jevTop.append(jevCopy,n("span",openrouter?.hasKey?"Ready":"OpenRouter required","connection-state"));jev.append(jevTop,n("p","JEV reuses the same OpenRouter key managed here and in Settings → AI. No TypeSafe/JEV credential is stored separately.","identity-muted"));if(!openrouter?.hasKey){const jevKey=input("OpenRouter API key","","password"),jevActions=n("div",undefined,"identity-actions"),connectJev=b("Connect OpenRouter for JEV",async()=>{const apiKey=jevKey.input.value.trim();if(!apiKey){status.textContent="Enter an OpenRouter API key.";return}try{status.textContent="Connecting OpenRouter for JEV…";await bridge.aiSave({provider:"openrouter",apiKey,select:false});jevKey.input.value="";status.textContent="OpenRouter connected for JEV without changing the active AI model.";await aiProviders()}catch(e){status.textContent=textError(e)}},"primary");connectJev.disabled=!bridge.aiSave;jevActions.append(connectJev);jev.append(jevKey.label,jevActions)}detail.append(jev);if(jevStatus?.windows){const fmt=v=>Number.isFinite(Number(v))?Number(v):0,pct=v=>(Math.round(fmt(v)*1000)/10)+"%",usd=v=>"$"+fmt(v).toFixed(6),tokens=v=>Math.round(fmt(v)).toLocaleString(),w=jevStatus.windows,metrics=n("div",undefined,"identity-credential-status");for(const[label,row]of[["Today",w.today],["7 days",w.days7],["30 days",w.days30]]){const line=n("div");line.append(n("span",label+" decisions"),n("span",String(row?.totalDecisions||0),"credential-field-state"));metrics.append(line)}const actual=n("div");actual.append(n("span","Actual JEV input / cost · 30d"),n("span",tokens(w.days30?.actual?.jevInputTokens)+" / "+usd(w.days30?.actual?.jevCostUsd),"credential-field-state"));metrics.append(actual);const estimated=n("div");estimated.append(n("span","Estimated LLM input / cost avoided · 30d"),n("span",tokens(w.days30?.estimated?.inputTokensAvoided)+" / "+usd(w.days30?.estimated?.costAvoidedUsd),"credential-field-state"));metrics.append(estimated);const rates=n("div");rates.append(n("span","Escalation / verification success · 30d"),n("span",pct(w.days30?.escalationRate)+" / "+pct(w.days30?.verificationSuccessRate),"credential-field-state"));metrics.append(rates);if(jevStatus.preservation){const caps=n("div");caps.append(n("span","Session value capsules"),n("span",String(jevStatus.preservation.preservedLive||0)+" / "+String(jevStatus.preservation.liveSessions||0)+(jevStatus.preservation.pending?" · "+jevStatus.preservation.pending+" pending":""),"credential-field-state"));metrics.append(caps)}jev.append(n("p","Default AI: "+String(cfg.provider||"—")+"/"+String(cfg.model||"—"),"identity-muted"),metrics,n("small","Actual = provider-reported JEV usage. Avoided LLM token/cost/latency figures are estimates, never actual savings."))}if(jevStatus?.registry){const lab=n("details",undefined,"connection-card"),summary=n("summary","JEV Lab · bounded decision test"),registry=n("div",undefined,"identity-credential-status");for(const row of jevStatus.registry){const line=n("div");line.append(n("span",row.id+" · v"+row.version+" · "+row.type),n("span","threshold "+Math.round(Number(row.threshold||0)*100)+"%","credential-field-state"));registry.append(line)}lab.append(summary,n("p","Inspect decision definitions and run a read-only semantic test. JEV Lab never executes tools, writes memory, or promotes recipes.","identity-muted"),registry);if(bridge.jevDecide){const decision=n("select"),decisionLabel=n("label","Test decision"),state=input("Bounded test state (JSON)",'{"task":"Should this request be escalated?"}'),result=n("pre",undefined,"identity-muted");for(const id of["model.route","failure.triage","recipe.promote"]){const o=n("option",id);o.value=id;decision.append(o)}decisionLabel.append(decision);const run=b("Run bounded test",async()=>{try{let parsed;try{parsed=JSON.parse(state.input.value)}catch{parsed={text:state.input.value}}status.textContent="Running JEV decision…";const out=await bridge.jevDecide({decision_id:decision.value,state:parsed});result.textContent=JSON.stringify(out,null,2).slice(0,4000);status.textContent="JEV Lab decision complete; no action executed."}catch(e){status.textContent=textError(e)}},"primary");lab.append(decisionLabel,state.label,run,result)}jev.append(lab)}const providerSelect=n("select"),providerLabel=n("label","Active provider"),modelSelect=n("select"),modelLabel=n("label","Model"),key=input("API key","","password"),fields=n("div",undefined,"identity-fields");for(const row of [...meta.values()].sort((a,b)=>String(a.name).localeCompare(String(b.name)))){const o=n("option",row.name+(row.freeAgentModelCount? " · "+row.freeAgentModelCount+" free agent model"+(row.freeAgentModelCount===1?"":"s"):""));o.value=row.id;providerSelect.append(o)}providerSelect.value=cfg.provider||providerSelect.options[0]?.value||"";providerLabel.append(providerSelect);modelLabel.append(modelSelect);fields.append(providerLabel,modelLabel,key.label);detail.append(fields);diff --git a/lib/workflow/jev-session-optimizer.ts b/lib/workflow/jev-session-optimizer.tsindex e111b652..392c2c24 100644--- a/lib/workflow/jev-session-optimizer.ts+++ b/lib/workflow/jev-session-optimizer.ts@@ -11,6 +11,7 @@ export type JevSessionOptimization = {decision:{id:"session.optimize";version:number;threshold:number;model?:string;latencyMs?:number;inputTokens?:number;actualCostUsd?:number};source: { sessionLabel: string; observedAt: string; shownEvents: number; omittedEvents: number };summary: { candidateCount: number; acceptedCount: number; rejectedCount: number };+ valueSummary: { semanticStepCount: number; toolCount: number; artifactRefCount: number };recommendations: Array<{ id: string; title: string; description: string; probability: number; actionRefs: string[] }>;llmContext: { kind: "mso.jev-session-optimization.v1"; instruction: string; facts: string[]; recommendations: Array<{ id: string; probability: number; actionRefs: string[]; guidance: string }> };fallbackReason?: string;@@ -36,10 +37,17 @@ export async function optimizeSessionWithJev(view: SessionGraphView, raw?: unknometa={...(evaluation.jev?.model?{model:evaluation.jev.model}:{}),...(evaluation.jev?.latencyMs!=null?{latencyMs:evaluation.jev.latencyMs}:{}),...(evaluation.jev?.inputTokens!=null?{inputTokens:evaluation.jev.inputTokens}:{}),...(evaluation.jev?.actualCostUsd!=null?{actualCostUsd:evaluation.jev.actualCostUsd}:{})};}catch(cause){provider="fallback";fallbackReason=cause instanceof Error?cause.message.slice(0,240):"Jev evaluation failed"}const recommendations=rows.map(row=>({...row, probability:provider==="jev"?(probabilities[row.id]??0):0, actionRefs:row.nodeIds})).filter(row=>row.probability>=definition.threshold).sort((a,b)=>b.probability-a.probability).map(({id,title,description,probability,actionRefs})=>({id,title,description,probability,actionRefs}));- const llmContext={kind:"mso.jev-session-optimization.v1" as const,instruction:"JEV DECISION only. Re-check live state before mutation. MCP ACTION and VERIFIED RESULT are separate stages; never infer credentials, arguments, permissions, execution, or success from this packet.",facts:[`Session ${view.session.label} has ${view.steps.length} semantic steps.`,`Projection covers ${view.shownEvents}/${view.totalEvents} events.`,...(view.omittedEvents?[`${view.omittedEvents} older events are omitted from this bounded projection.`]:[])],recommendations:recommendations.map(r=>({id:r.id,probability:r.probability,actionRefs:r.actionRefs,guidance:r.description}))};+ const semanticFacts=view.steps.slice(-16).map(step=>{+ const tools=[...new Set(step.actions.map(action=>action.tool).filter((tool):tool is string=>Boolean(tool)))].slice(0,8);+ return `${step.ref} · ${step.category} · ${step.title}: ${step.summary}${tools.length?` · tools ${tools.join(" → ")}`:""}`;+ });+ const tools=new Set(view.steps.flatMap(step=>step.actions.map(action=>action.tool).filter((tool):tool is string=>Boolean(tool))));+ const artifactRefs=new Set(view.steps.flatMap(step=>step.actions.flatMap(action=>action.artifact?[action.artifact.ref]:[])));+ const valueSummary={semanticStepCount:view.steps.length,toolCount:tools.size,artifactRefCount:artifactRefs.size};+ const llmContext={kind:"mso.jev-session-optimization.v1" as const,instruction:"JEV DECISION only. Re-check live state before mutation. MCP ACTION and VERIFIED RESULT are separate stages; never infer credentials, arguments, permissions, execution, or success from this packet.",facts:[`Session ${view.session.label} has ${view.steps.length} semantic steps.`,`Projection covers ${view.shownEvents}/${view.totalEvents} events.`,`Continuation capsule retains ${valueSummary.semanticStepCount} semantic steps, ${valueSummary.toolCount} unique tools, and ${valueSummary.artifactRefCount} artifact references.`,...(view.omittedEvents?[`${view.omittedEvents} older events are omitted from this bounded projection.`]:[]),...semanticFacts],recommendations:recommendations.map(r=>({id:r.id,probability:r.probability,actionRefs:r.actionRefs,guidance:r.description}))};if(provider==="jev"&&recommendations.length){const rawTokens=estimateJevTokens(state),selectedTokens=estimateJevTokens(llmContext),reuse=recommendations.some(row=>row.id.startsWith("reuse-"));await recordJevTelemetry({event:"impact",decisionId:"session.optimize",decisionVersion:definition.version,decisionType:definition.type,sessionRef:view.session.label,estimated:{llmAvoided:reuse,inputTokensAvoided:Math.max(0,rawTokens-selectedTokens)}}).catch(()=>undefined);}- return {provider,decision:{id:"session.optimize",version:definition.version,threshold:definition.threshold,...meta},source:{sessionLabel:view.session.label,observedAt:view.observedAt,shownEvents:view.shownEvents,omittedEvents:view.omittedEvents},summary:{candidateCount:rows.length,acceptedCount:recommendations.length,rejectedCount:Math.max(0,rows.length-recommendations.length)},recommendations,llmContext,...(fallbackReason?{fallbackReason}:{})};+ return {provider,decision:{id:"session.optimize",version:definition.version,threshold:definition.threshold,...meta},source:{sessionLabel:view.session.label,observedAt:view.observedAt,shownEvents:view.shownEvents,omittedEvents:view.omittedEvents},summary:{candidateCount:rows.length,acceptedCount:recommendations.length,rejectedCount:Math.max(0,rows.length-recommendations.length)},valueSummary,recommendations,llmContext,...(fallbackReason?{fallbackReason}:{})};}diff --git a/scripts/e2e/mcp-sessions.mjs b/scripts/e2e/mcp-sessions.mjsindex 5d8d8445..0454402f 100644--- a/scripts/e2e/mcp-sessions.mjs+++ b/scripts/e2e/mcp-sessions.mjs@@ -66,6 +66,13 @@ export async function mcpSessionsJourney(page, fixture) {const selectedGraphResponse = await page.request.get(fixture.base + `/api/v1/agent-sessions?view=graph&id=${encodeURIComponent(selectedMonitor.sessions[0].id)}`);const selectedGraph = await selectedGraphResponse.json();expect(selectedGraph.graph.nodes.length).toBeLessThanOrEqual(9);+ await page.getByRole("button", { name: "Use JEV", exact: true }).click();+ await expect(page.locator('[data-slot="jev-session-output"]')).toBeVisible();+ await expect(page.getByText("JEV DECISION", { exact: true })).toBeVisible();+ await expect(page.locator('[data-slot="jev-decision-metadata"]')).toContainText("Decision v1");+ await expect(page.locator('[data-slot="jev-capsule-summary"]')).toContainText("Continuation capsule");+ await expect(page.getByText("MCP ACTION · not executed", { exact: true })).toBeVisible();+ await expect(page.getByText("VERIFIED RESULT · n/a", { exact: true })).toBeVisible();const artifactStep = selectedGraph.steps.find(step => step.actions.some(action => action.artifact));const artifactAction = artifactStep?.actions.find(action => action.artifact);expect(artifactStep).toBeTruthy(); expect(artifactAction).toBeTruthy();diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex 0e036d6a..ddaa3abc 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -90,6 +90,15 @@ try {await page.getByRole("button", { name: "Unlock", exact: true }).click();await expect(page).toHaveURL(fixture.base + "/integrations");await expect(page.getByRole("group", { name: "Credential owner" }).getByRole("button")).toContainText("fixture");+ await page.getByRole("navigation", { name: "Integrations sections", exact: true }).getByRole("button", { name: "AI Providers", exact: true }).click();+ await expect(page.getByRole("heading", { name: "AI Providers", exact: true })).toBeVisible();+ await expect(page.getByRole("heading", { name: "JEV decision kernel", exact: true })).toBeVisible();+ await expect(page.getByText("Actual JEV input / cost · 30d", { exact: true })).toBeVisible();+ await expect(page.getByText("Estimated LLM input / cost avoided · 30d", { exact: true })).toBeVisible();+ await page.getByText("JEV Lab · bounded decision test", { exact: true }).click();+ await expect(page.getByText("JEV Lab never executes tools, writes memory, or promotes recipes.", { exact: true })).toBeVisible();+ await page.getByRole("button", { name: "Run bounded test", exact: true }).click();+ await expect(page.getByRole("status")).toContainText("JEV Lab decision complete; no action executed.");await storeExtensionsJourney(page, fixture);await page.goto(fixture.base + "/integrations");await page.getByRole("navigation", { name: "Integrations sections", exact: true }).getByRole("button", { name: "Transfer & backup", exact: true }).click();