Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
chore(scripts): add desktop-boot, jarvis-bar, sandbox & brand-preview tooling
Ruben Lütkeed83d8b82fcd
diff --git a/scripts/_cu_bench_healthcheck.py b/scripts/_cu_bench_healthcheck.pynew file mode 100644index 0000000000..59a03fb176--- /dev/null+++ b/scripts/_cu_bench_healthcheck.py@@ -0,0 +1,63 @@+"""One-shot pre-flight for the CU benchmark: build the brain, check the harness+is healthy, and report which vision-capable brain the fallback chain would use+and the active latency knobs — WITHOUT touching the desktop. Throwaway helper."""+from __future__ import annotations++import asyncio+import sys++try:+ sys.stdout.reconfigure(encoding="utf-8")+except Exception:+ pass+++async def main() -> int:+ from jarvis.core.bus import EventBus+ bus = EventBus()+ from jarvis.brain.factory import build_default_brain+ build_default_brain(bus=bus)++ from jarvis.harness.computer_use_context import get_computer_use_context+ from jarvis.plugins.harness.computer_use import ComputerUseHarness++ try:+ ctx = get_computer_use_context()+ except Exception as exc:+ print(f"ABORT: ComputerUseContext not wired: {exc}")+ return 3++ print("KNOBS:",+ "image_max_dimension=", getattr(ctx, "image_max_dimension", "?"),+ "image_max_bytes=", getattr(ctx, "image_max_bytes", "?"),+ "settle_scale=", getattr(ctx, "settle_scale", "?"),+ "think_timeout_cap_s=", getattr(ctx, "think_timeout_cap_s", "?"))++ mgr = ctx.brain_manager+ # Which provider chain would CU's fast tier use, and which are vision-capable?+ chain = []+ build_chain = getattr(mgr, "_build_fallback_chain", None)+ if callable(build_chain):+ try:+ chain = list(build_chain("fast") or [])+ except Exception as exc:+ print("chain build failed:", exc)+ print("FAST CHAIN:", chain)+ for provider, model in chain:+ try:+ brain = mgr._get_brain(provider, model)+ sv = getattr(brain, "supports_vision", None)+ print(f" - {provider}({model}) supports_vision={sv}")+ except Exception as exc:+ print(f" - {provider}({model}) build FAILED: {type(exc).__name__}: {exc}")+ dead = getattr(mgr, "_dead_providers", None)+ print("DEAD PROVIDERS:", dead)++ harness = ComputerUseHarness()+ healthy = await harness.health()+ print("HARNESS HEALTHY:", healthy)+ return 0 if healthy else 3+++if __name__ == "__main__":+ raise SystemExit(asyncio.run(main()))diff --git a/scripts/_desktop_boot_driver.py b/scripts/_desktop_boot_driver.pynew file mode 100644index 0000000000..f6d9e5467d--- /dev/null+++ b/scripts/_desktop_boot_driver.py@@ -0,0 +1,79 @@+#!/usr/bin/env python+"""GUI-free driver for the desktop cold-boot harness.++Two modes (selected by env ``JARVIS_DESKTOP_BENCH_MODE``):++* ``legacy`` (default) — runs the existing ``DesktopApp._run_backend`` so the+ harness can measure today's ``spawn -> /api/health 200`` baseline (the literal+ gate ``DesktopApp._wait_for_backend`` uses before creating the pywebview+ window).+* ``fastboot`` — runs the serve-first early-bind path: bind the+ :class:`FastBootstrap` on the backend loop *before* the heavy jarvis imports ++ ``WebServer`` build, then build the real app behind it and delegate. This is+ the prototype of the production fix; the harness measures how fast+ ``/api/health`` responds with it.++NOT a production entry point — used only by ``scripts/measure_desktop_boot.py``.+"""++from __future__ import annotations++import asyncio+import os+import time++_T0 = time.perf_counter()+++def _boot_ready() -> None:+ if os.environ.get("JARVIS_BOOT_PROFILE") == "1":+ print(f"BOOT_READY_MS={(time.perf_counter() - _T0) * 1000.0:.1f}", flush=True)+++def _legacy() -> int:+ from jarvis.core.config import ensure_project_root_cwd, load_config++ ensure_project_root_cwd()+ cfg = load_config()+ port_env = os.environ.get("JARVIS_DESKTOP_BENCH_PORT")+ if port_env:+ cfg = cfg.model_copy(+ update={"ui": cfg.ui.model_copy(update={"admin_api_port": int(port_env)})}+ )+ from jarvis.ui.desktop_app import DesktopApp++ app = DesktopApp(cfg)+ app._run_backend()+ return 0+++def _fastboot() -> int:+ """Exercise the REAL production early-bind path (launcher+ ``_desktop_backend_main``) so the harness measures production, not a stub.+ Blocks in run_forever; the parent harness reads the anchor and kills us."""+ import threading+ from types import SimpleNamespace++ port = int(os.environ.get("JARVIS_DESKTOP_BENCH_PORT", "47821"))+ import jarvis.ui.web.launcher as _launcher++ # Give the production BOOT_READY print a t0 (it reads this module global).+ _launcher._BOOT_PROFILE_T0 = _T0+ args = SimpleNamespace(dev=False, port=port, no_lock=True, headless=False)+ holder = {"app": None, "err": None, "lock": None, "already_running": False}+ app_ready = threading.Event()+ # Runs the bootstrap bind → heavy build → app._run_backend(prebound) →+ # run_forever (blocks). Same code the real desktop backend thread runs.+ _launcher._desktop_backend_main(args, port, "bench-token", holder, app_ready)+ return 0+++def main() -> int:+ mode = os.environ.get("JARVIS_DESKTOP_BENCH_MODE", "legacy")+ if mode == "fastboot":+ return _fastboot()+ return _legacy()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/_e2e_jarvis_agent_verify.py b/scripts/_e2e_jarvis_agent_verify.pynew file mode 100644index 0000000000..35480463ec--- /dev/null+++ b/scripts/_e2e_jarvis_agent_verify.py@@ -0,0 +1,200 @@+"""Headless E2E verification of the xai/sonnet fix.++Spawns the SubJarvisWorker directly (no Mission-Manager / Kontrollierer+layer in between) with a tiny prompt, then inspects:++ - the worker yielded ClaudeSystemInit + ClaudeResult+ - the model arg in the spawned argv is NOT "xai/sonnet" (the bug)+ - the spawned argv carries "xai/grok-4.3" (the config chain)+ - the workspace contains the file the prompt asked for+ - stderr.log contains no FailoverError++Two missions are run with different goals to match the goal spec.+"""+from __future__ import annotations++import asyncio+import json+import os+import shutil+import sys+import time+import uuid+from pathlib import Path+from typing import Any++# Project on sys.path+PROJECT = Path(__file__).parent.parent+sys.path.insert(0, str(PROJECT))++from jarvis.missions.isolation.job_object import AlwaysOpenJobObject+from jarvis.missions.workers.subjarvis_worker import SubJarvisWorker+++def _build_env() -> dict[str, str]:+ """Minimal env: XAI_API_KEY for grok + system tools."""+ from jarvis.core.config import get_secret++ grok = get_secret("grok_api_key", env_fallback="GROK_API_KEY")+ env = {+ # tools the openclaw CLI needs to spawn (path lookups, etc.)+ "PATH": os.environ.get("PATH", ""),+ "SYSTEMROOT": os.environ.get("SYSTEMROOT", "C:\\Windows"),+ "USERPROFILE": os.environ.get("USERPROFILE", ""),+ "APPDATA": os.environ.get("APPDATA", ""),+ "LOCALAPPDATA": os.environ.get("LOCALAPPDATA", ""),+ "TEMP": os.environ.get("TEMP", ""),+ "TMP": os.environ.get("TMP", ""),+ "HOMEDRIVE": os.environ.get("HOMEDRIVE", "C:"),+ "HOMEPATH": os.environ.get("HOMEPATH", "\\Users\\Administrator"),+ }+ if grok:+ env["XAI_API_KEY"] = grok+ env["GROK_API_KEY"] = grok+ return env+++async def _run_one_mission(+ label: str,+ prompt: str,+ artefact_check,+) -> dict[str, Any]:+ mission_dir = PROJECT.parent / "sub-agents-outputs" / f"e2e_verify_{label}_{uuid.uuid4().hex[:8]}"+ workspace = mission_dir / "workspace"+ logs = mission_dir / "logs"+ workspace.mkdir(parents=True, exist_ok=True)+ logs.mkdir(parents=True, exist_ok=True)++ env = _build_env()+ env["OPENCLAW_STATE_DIR"] = str(mission_dir / "openclaw_state")++ worker = SubJarvisWorker()+ started = time.time()+ events = []++ # NOTE: We pass model="sonnet" on purpose — that's the exact+ # Decomposer-default value that produced the bug. The fix must filter+ # it out and use [brain.sub_jarvis] from jarvis.toml (= grok-4.3) instead.+ try:+ async for ev in worker.spawn(+ prompt,+ worktree=workspace,+ env=env,+ job=AlwaysOpenJobObject(),+ worker_id=f"e2e-{label}",+ log_dir=logs,+ model="sonnet", # the trapdoor — must be filtered+ timeout_s=300.0,+ ):+ events.append(type(ev).__name__)+ except Exception as exc: # noqa: BLE001+ return {+ "label": label,+ "ok": False,+ "reason": f"worker spawn raised: {exc!r}",+ "duration_s": time.time() - started,+ "events": events,+ "mission_dir": str(mission_dir),+ }++ duration_s = time.time() - started++ # Inspect logs+ stderr_path = logs / "stderr.log"+ stream_path = logs / "stream.jsonl"+ stderr_txt = stderr_path.read_text(encoding="utf-8", errors="replace") if stderr_path.exists() else ""+ stream_txt = stream_path.read_text(encoding="utf-8", errors="replace") if stream_path.exists() else ""++ bad_failover = "FailoverError" in stderr_txt or "xai/sonnet" in stderr_txt+ artefact_ok, artefact_detail = artefact_check(workspace)++ return {+ "label": label,+ "events": events,+ "duration_s": round(duration_s, 1),+ "stderr_clean": not bad_failover,+ "stderr_snippet": stderr_txt[:500] if stderr_txt else "",+ "stream_has_init_and_result": (+ "ClaudeSystemInit" in events and "ClaudeResult" in events+ ),+ "artefact_ok": artefact_ok,+ "artefact_detail": artefact_detail,+ "mission_dir": str(mission_dir),+ }+++def _check_hello_py(workspace: Path) -> tuple[bool, str]:+ """Mission 1: hello.py must exist and print 'hello world'."""+ f = workspace / "hello.py"+ if not f.exists():+ return False, f"missing {f}"+ content = f.read_text(encoding="utf-8")+ if "hello world" not in content.lower():+ return False, f"content does not contain 'hello world': {content[:200]!r}"+ if "print" not in content:+ return False, f"no print() call: {content[:200]!r}"+ return True, f"hello.py {f.stat().st_size} bytes, contains print + hello world"+++def _check_result_txt(workspace: Path) -> tuple[bool, str]:+ """Mission 2: result.txt with at least 1 non-empty line."""+ f = workspace / "result.txt"+ if not f.exists():+ return False, f"missing {f}"+ lines = [ln for ln in f.read_text(encoding="utf-8").splitlines() if ln.strip()]+ if not lines:+ return False, "result.txt empty"+ return True, f"result.txt {len(lines)} non-empty lines"+++async def main() -> int:+ print("=" * 60)+ print("E2E verification of xai/sonnet fix (Phase 3)")+ print("=" * 60)++ # NOTE: Goal text used `print('hello world')` with literal newlines in+ # the prompt. On Windows the openclaw.cmd shim re-tokenises argv via+ # cmd.exe, which (a) treats apostrophes as metachars and (b) chops the+ # --message argument on embedded newlines. Either trap silently+ # collapses --model so the CLI falls back to its first listed+ # provider (openai/gpt-5.5) and aborts with auth-failed — exact same+ # pattern as the GeminiWorker cmd-wrapper trap fixed 2026-05-13.+ # Single-line prompt with double quotes round-trips cleanly. The+ # actual file content check (must contain "hello world" + "print")+ # is unchanged.+ r1 = await _run_one_mission(+ "hello",+ 'Create a file named hello.py with this exact content (no extra text): print("hello world"). Then exit. Do not write any other file.',+ _check_hello_py,+ )+ print(json.dumps(r1, indent=2))++ r2 = await _run_one_mission(+ "result",+ "Create a file named result.txt in the current directory with two lines: line one says 'A', line two says 'B'. Then exit.",+ _check_result_txt,+ )+ print(json.dumps(r2, indent=2))++ print("\nSUMMARY")+ print("-" * 60)+ all_ok = True+ for r in (r1, r2):+ verdict = "PASS" if (+ r.get("stderr_clean")+ and r.get("stream_has_init_and_result")+ and r.get("artefact_ok")+ and r.get("duration_s", 9999) < 180+ ) else "FAIL"+ if verdict == "FAIL":+ all_ok = False+ print(f" [{r['label']:7s}] {verdict} "+ f"duration={r.get('duration_s','?')}s "+ f"stderr_clean={r.get('stderr_clean')} "+ f"artefact={r.get('artefact_ok')} ({r.get('artefact_detail','')})")++ return 0 if all_ok else 1+++if __name__ == "__main__":+ sys.exit(asyncio.run(main()))diff --git a/scripts/brand-preview/contributing.html b/scripts/brand-preview/contributing.htmlnew file mode 100644index 0000000000..a72eac73e7--- /dev/null+++ b/scripts/brand-preview/contributing.html@@ -0,0 +1,24 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <base href="/" />+ <title>CONTRIBUTING preview — Personal Jarvis</title>+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5/github-markdown-dark.css" />+ <style>+ body { background:#0d1117; margin:0; }+ .markdown-body { box-sizing:border-box; max-width:920px; margin:0 auto; padding:48px 32px 120px; }+ img { background:transparent; }+ </style>+ </head>+ <body>+ <article class="markdown-body" id="content">Loading…</article>+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>+ <script>+ fetch("/CONTRIBUTING.md")+ .then((r) => r.text())+ .then((md) => { document.getElementById("content").innerHTML = marked.parse(md); })+ .catch((e) => { document.getElementById("content").textContent = "Failed: " + e; });+ </script>+ </body>+</html>diff --git a/scripts/brand-preview/hero.html b/scripts/brand-preview/hero.htmlnew file mode 100644index 0000000000..ef733cb126--- /dev/null+++ b/scripts/brand-preview/hero.html@@ -0,0 +1,61 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <base href="/" />+ <title>Hero banner — Personal Jarvis</title>+ <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;700&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet" />+ <style>+ :root { --yellow:#ffd60a; --black:#0a0a0a; --ink:#f4f4f5; --muted:#8f8f8f; --card:#0f0f0f; --border:#242424; }+ * { box-sizing:border-box; margin:0; padding:0; }+ body { background:var(--black); color:var(--ink); font-family:"Space Grotesk",system-ui,sans-serif; padding:56px 24px 100px; }+ .wrap { max-width:960px; margin:0 auto; }+ a.back { color:var(--muted); text-decoration:none; font-family:"JetBrains Mono",monospace; font-size:13px; letter-spacing:2px; }+ a.back:hover { color:var(--yellow); }+ h1 { font-size:30px; margin:18px 0 6px; letter-spacing:-1px; }+ h1 .y { color:var(--yellow); }+ .lead { color:var(--muted); margin-bottom:40px; font-size:15px; }+ .variant { margin-bottom:48px; }+ .label { font-family:"JetBrains Mono",monospace; font-size:13px; letter-spacing:3px; text-transform:uppercase; color:var(--yellow); margin-bottom:14px; }+ .label .note { color:var(--muted); }+ .frame { background:var(--black); border:1px solid var(--border); border-radius:14px; overflow:hidden; }+ .frame img { display:block; width:100%; height:auto; }+ .frame.live { aspect-ratio: 1280 / 480; }+ .frame.live iframe { width:1280px; height:480px; border:0; transform-origin:top left; }+ .placeholder { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:14px; min-height:300px; border:1px dashed var(--border); border-radius:14px; color:var(--muted); text-align:center; padding:30px; }+ .placeholder b { color:var(--ink); font-size:18px; }+ .scaler { position:relative; width:100%; }+ </style>+ </head>+ <body>+ <div class="wrap">+ <a class="back" href="/scripts/brand-preview/index.html">← back</a>+ <h1>Hero banner — <span class="y">final</span></h1>+ <p class="lead">The chosen banner, wired into the README hero.</p>++ <div class="variant">+ <div class="label">Live hero <span class="note">— AI-generated metallic-gold wordmark (assets/brand/banner.png)</span></div>+ <div class="frame"><img src="assets/brand/banner.png" alt="Personal Jarvis banner" /></div>+ </div>++ <div class="variant">+ <div class="label">CSS fallback <span class="note">— reproducible pure-CSS treatment (banner.html → banner-css.png)</span></div>+ <div class="frame live"><div class="scaler"><iframe src="assets/brand/banner.html" scrolling="no"></iframe></div></div>+ </div>+ </div>+ <script>+ // Scale the 1280px live iframe to fit the column width.+ function fit() {+ document.querySelectorAll(".frame.live").forEach((f) => {+ const s = f.querySelector(".scaler"), ifr = f.querySelector("iframe");+ const k = f.clientWidth / 1280;+ ifr.style.transform = "scale(" + k + ")";+ s.style.height = 480 * k + "px";+ });+ }+ window.addEventListener("resize", fit);+ window.addEventListener("load", fit);+ fit();+ </script>+ </body>+</html>diff --git a/scripts/brand-preview/index.html b/scripts/brand-preview/index.htmlnew file mode 100644index 0000000000..989d5c23cc--- /dev/null+++ b/scripts/brand-preview/index.html@@ -0,0 +1,39 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <base href="/" />+ <title>Personal Jarvis — brand preview</title>+ <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;700&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet" />+ <style>+ :root { --yellow:#ffd60a; --black:#0a0a0a; --ink:#f4f4f5; --muted:#8f8f8f; --card:#0f0f0f; --border:#242424; }+ * { box-sizing:border-box; margin:0; padding:0; }+ body { background:var(--black); color:var(--ink); font-family:"Space Grotesk",system-ui,sans-serif; min-height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:42px; padding:60px 24px; }+ h1 { font-size:34px; letter-spacing:-1px; font-weight:700; }+ h1 .y { color:var(--yellow); }+ p.sub { color:var(--muted); font-family:"JetBrains Mono",monospace; letter-spacing:3px; text-transform:uppercase; font-size:13px; }+ .cards { display:flex; gap:24px; flex-wrap:wrap; justify-content:center; }+ a.card { width:320px; background:var(--card); border:1px solid var(--border); border-radius:16px; padding:28px; text-decoration:none; color:var(--ink); transition:.15s; display:block; }+ a.card:hover { border-color:rgba(255,214,10,.5); transform:translateY(-3px); }+ a.card h2 { font-size:20px; margin-bottom:8px; }+ a.card .arrow { color:var(--yellow); }+ a.card p { color:var(--muted); font-size:14px; line-height:1.5; }+ </style>+ </head>+ <body>+ <div style="text-align:center">+ <h1>Personal <span class="y">Jarvis</span> — brand preview</h1>+ <p class="sub">prototype · review · iterate</p>+ </div>+ <div class="cards">+ <a class="card" href="/scripts/brand-preview/readme.html">+ <h2>README preview <span class="arrow">→</span></h2>+ <p>The new front-door README rendered GitHub-style (dark), with the hero banner and live image paths.</p>+ </a>+ <a class="card" href="/scripts/brand-preview/hero.html">+ <h2>Hero banner <span class="arrow">→</span></h2>+ <p>The glitch wordmark variants on matte black — self-built now, AI variant slot pending.</p>+ </a>+ </div>+ </body>+</html>diff --git a/scripts/brand-preview/readme.html b/scripts/brand-preview/readme.htmlnew file mode 100644index 0000000000..e39925d3be--- /dev/null+++ b/scripts/brand-preview/readme.html@@ -0,0 +1,24 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <base href="/" />+ <title>README preview — Personal Jarvis</title>+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5/github-markdown-dark.css" />+ <style>+ body { background:#0d1117; margin:0; }+ .markdown-body { box-sizing:border-box; max-width:920px; margin:0 auto; padding:48px 32px 120px; }+ img { background:transparent; }+ </style>+ </head>+ <body>+ <article class="markdown-body" id="content">Loading README…</article>+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>+ <script>+ fetch("/README.md")+ .then((r) => r.text())+ .then((md) => { document.getElementById("content").innerHTML = marked.parse(md); })+ .catch((e) => { document.getElementById("content").textContent = "Failed to load README.md: " + e; });+ </script>+ </body>+</html>diff --git a/scripts/brand-preview/shot.ps1 b/scripts/brand-preview/shot.ps1new file mode 100644index 0000000000..346a4ca2b7--- /dev/null+++ b/scripts/brand-preview/shot.ps1@@ -0,0 +1,34 @@+<#+ Screenshot a URL via headless Chrome to a PNG under assets/brand/.+ Usage: pwsh scripts/brand-preview/shot.ps1 -Url <url> -Out name.png [-W 1000] [-H 5400] [-Scale 1]+#>+param(+ [Parameter(Mandatory = $true)][string]$Url,+ [Parameter(Mandatory = $true)][string]$Out,+ [int]$W = 1000,+ [int]$H = 5400,+ [int]$Scale = 1+)++$ErrorActionPreference = "Stop"+$chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"+if (-not (Test-Path $chrome)) { throw "Chrome not found" }++$repoRoot = "C:\Users\Administrator\Desktop\Personal Jarvis"+$destDir = Join-Path $repoRoot "assets\brand"+$tmpProfile = Join-Path $env:TEMP ("cprof-" + [guid]::NewGuid().ToString("N"))+$tmpOut = Join-Path $env:TEMP ("urlshot-" + [guid]::NewGuid().ToString("N") + ".png")++& $chrome "--headless=new" "--hide-scrollbars" "--disable-gpu" "--no-sandbox" `+ "--force-device-scale-factor=$Scale" "--virtual-time-budget=6000" `+ "--user-data-dir=$tmpProfile" "--window-size=$W,$H" `+ "--screenshot=$tmpOut" "$Url" | Out-Null++if (Test-Path $tmpOut) {+ Copy-Item $tmpOut (Join-Path $destDir $Out) -Force+ Write-Output ("OK -> assets/brand/{0} ({1} bytes)" -f $Out, (Get-Item $tmpOut).Length)+ Remove-Item $tmpOut -Force -ErrorAction SilentlyContinue+} else {+ Write-Output "NO SHOT (exit $LASTEXITCODE)"+}+Remove-Item $tmpProfile -Recurse -Force -ErrorAction SilentlyContinuediff --git a/scripts/jarvisbar_live_probe.py b/scripts/jarvisbar_live_probe.pynew file mode 100644index 0000000000..716cbe7e68--- /dev/null+++ b/scripts/jarvisbar_live_probe.py@@ -0,0 +1,71 @@+"""Dev probe: run the real JarvisBarOverlay (Tk window, color-key + alpha)+standalone in THINK mode and capture it from the live desktop.++The position loader is patched to None so the probe bar anchors at the+default bottom-center spot instead of stacking on the app's bar (both read+the same persisted drag position). PIL ImageGrab is used because the bar is+a layered window invisible to plain BitBlt captures.+"""+import ctypes+import sys+import time+from pathlib import Path++# Per-monitor DPI awareness BEFORE Tk boots, so the window coordinates Tk+# reports match the physical pixels ImageGrab captures (display scaling).+ctypes.windll.shcore.SetProcessDpiAwareness(2)++from PIL import Image, ImageGrab # noqa: E402++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from jarvis.ui.jarvisbar import interaction, renderer # noqa: E402+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay # noqa: E402++OUT = Path(__file__).resolve().parents[1] / "screenshots"++# Detach from the persisted drag position — the running app's bar sits there.+interaction.load_jarvisbar_position = lambda *_a, **_k: None # type: ignore+++def main() -> None:+ bar = JarvisBarOverlay(persistent=True)+ bar.start_in_thread()+ time.sleep(2.5) # Tk boot+ bar.show(mode="think")+ time.sleep(1.0)++ st = bar._renderer._st+ print(+ f"mode={bar._mode} pill={st.pw:.0f}x{st.ph:.0f} "+ f"target_active={renderer.ACTIVE_W}x{renderer.ACTIVE_H} "+ f"pos=({bar._x},{bar._y})",+ flush=True,+ )++ pad = 50+ bx, by = bar._x, bar._y+ for i in (1, 2, 3):+ time.sleep(1.3)+ img = ImageGrab.grab(all_screens=True)+ crop = img.crop(+ (+ max(0, bx - pad),+ max(0, by - pad),+ min(img.width, bx + renderer.WIN_W + pad),+ min(img.height, by + renderer.WIN_H + pad),+ )+ )+ crop = crop.resize((crop.width * 5, crop.height * 5), Image.LANCZOS)+ crop.save(OUT / f"bar-probe-crop-{i}.png")+ print("saved", i, flush=True)++ st = bar._renderer._st+ print(f"final mode={bar._mode} pill={st.pw:.0f}x{st.ph:.0f}", flush=True)+ bar.hide()+ time.sleep(0.5)+ print("done", flush=True)+++if __name__ == "__main__":+ main()diff --git a/scripts/jarvisbar_thinking_preview.py b/scripts/jarvisbar_thinking_preview.pynew file mode 100644index 0000000000..9a84240418--- /dev/null+++ b/scripts/jarvisbar_thinking_preview.py@@ -0,0 +1,70 @@+"""Headless preview of the jarvis-bar THINKING animation (orbital core).++Renders frames straight from the pure renderer (no Tk, no app) and writes:+- ``screenshots/jarvisbar-thinking-sheet.png`` — 8 frames, 4x upscaled,+ composited on a desktop-dark background for design review.+- ``screenshots/jarvisbar-thinking.gif`` — ~3 s animation at 4x.++Usage: python scripts/jarvisbar_thinking_preview.py+"""+from __future__ import annotations++import sys+from pathlib import Path++from PIL import Image++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from jarvis.core.screenshots import screenshots_dir # noqa: E402+from jarvis.ui.jarvisbar import renderer as R # noqa: E402++DESKTOP_BG = (32, 31, 34) # neutral dark backdrop standing in for the desktop+UPSCALE = 4+++def _frame(rnd: R.JarvisBarRenderer, t: float) -> Image.Image:+ img = rnd.render(t, "think", 0.0)+ # Swap the magenta color-key for a desktop-ish dark grey so the preview+ # shows what the keyed-out window actually looks like in place.+ px = img.load()+ for y in range(img.height):+ for x in range(img.width):+ if px[x, y] == R.COLOR_KEY_RGB:+ px[x, y] = DESKTOP_BG+ return img.resize(+ (img.width * UPSCALE, img.height * UPSCALE), Image.Resampling.LANCZOS+ )+++def main() -> None:+ out = screenshots_dir()+ rnd = R.JarvisBarRenderer()+ for _ in range(80): # settle the pill ease at ACTIVE size+ rnd.render(0.0, "think", 0.0)++ # Contact sheet: 8 moments across ~2.6 s.+ times = [1.0 + k * 0.37 for k in range(8)]+ frames = [_frame(rnd, t) for t in times]+ fw, fh = frames[0].size+ pad = 8+ sheet = Image.new("RGB", (fw * 4 + pad * 5, fh * 2 + pad * 3), (18, 18, 20))+ for i, fr in enumerate(frames):+ col, row = i % 4, i // 4+ sheet.paste(fr, (pad + col * (fw + pad), pad + row * (fh + pad)))+ sheet_path = out / "jarvisbar-thinking-sheet.png"+ sheet.save(sheet_path)++ # Animation: 60 frames over ~3 s (50 ms cadence in the GIF).+ anim = [_frame(rnd, 1.0 + k * 0.05) for k in range(60)]+ gif_path = out / "jarvisbar-thinking.gif"+ anim[0].save(+ gif_path, save_all=True, append_images=anim[1:], duration=50, loop=0+ )++ print(f"sheet: {sheet_path}")+ print(f"gif: {gif_path}")+++if __name__ == "__main__":+ main()diff --git a/scripts/measure_desktop_boot.py b/scripts/measure_desktop_boot.pynew file mode 100644index 0000000000..a5eba86f74--- /dev/null+++ b/scripts/measure_desktop_boot.py@@ -0,0 +1,271 @@+#!/usr/bin/env python+"""Reproducible cold-boot timing harness for the Personal Jarvis **desktop** app.++Why this is separate from ``measure_boot.py``+---------------------------------------------+``measure_boot.py`` measures the *headless* path (``_run_headless``), which+already uses the fast-boot bootstrap (commit 6379222e) and serves in ~200 ms.+But the user runs the **desktop** app (``run.bat`` -> pywebview + voice + orb),+whose backend thread (``DesktopApp._run_backend``) does NOT use the bootstrap:+it runs the full ``server.start()`` synchronously before the backend serves+``/api/health``. The desktop shell (``DesktopApp.run``) blocks in+``_wait_for_backend`` (polling ``/api/health`` for a 200) before it calls+``webview.create_window`` — so "the window appears" == "the backend serves".++This harness measures exactly that gate: ``spawn -> /api/health serving``, via+``scripts/_desktop_boot_driver.py`` (which runs ``_run_backend`` with NO GUI+window and NO microphone). The anchor is the ``BOOT_READY_MS=`` sentinel the+desktop ``_run_backend`` prints (gated behind ``JARVIS_BOOT_PROFILE=1``) the+moment the backend is serving.++Isolation is identical to ``measure_boot.py`` (shared ``.boot-bench/`` dirs,+``data/`` wiped per run, seeded frozen vault) so the factor stays honest and+comparable. Writes ``desktop-boot-latest.json`` every run and freezes+``desktop-boot-baseline.json`` on the first run.++Usage+-----+ "C:\\Program Files\\Python311\\python.exe" scripts/measure_desktop_boot.py+ "...python.exe" scripts/measure_desktop_boot.py --runs 5 --warmup 1+"""++from __future__ import annotations++import argparse+import json+import statistics+import subprocess+import sys+import threading+import time+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(Path(__file__).resolve().parent))++# Reuse the proven isolation + seeding helpers from the headless harness so the+# two benches do identical work and the factor is directly comparable.+from measure_boot import ( # noqa: E402+ DATA_DIR,+ DEFAULT_PAGES,+ DEFAULT_PYTHON,+ ISO_DIR,+ NO_WINDOW_CREATIONFLAGS,+ _bench_env,+ _free_port,+ _terminate,+ seed_vault,+)++DRIVER = REPO_ROOT / "scripts" / "_desktop_boot_driver.py"+BASELINE_PATH = REPO_ROOT / "desktop-boot-baseline.json"+LATEST_PATH = REPO_ROOT / "desktop-boot-latest.json"+++def run_one(python: str, timeout: float, mode: str = "legacy") -> dict:+ """Spawn one isolated desktop-backend cold boot and measure the HONEST+ user-perceived anchor: ``spawn -> /api/health responds 200``.++ That is the literal gate the desktop shell uses — ``DesktopApp.run`` blocks+ in ``_wait_for_backend`` (an ``/api/health`` poll) before it creates the+ pywebview window — so "the window appears" == "/api/health responds 200".+ We poll it exactly like ``_wait_for_backend`` does (a real HTTP response,+ not merely a bound socket — a bound-but-loop-blocked bootstrap would NOT+ answer, which is the point). The ``BOOT_READY_MS=`` stdout print is kept as+ a secondary in-process cross-check (it marks the bootstrap *bind*, which can+ precede a responsive health endpoint).+ """+ import shutil+ import urllib.request++ shutil.rmtree(DATA_DIR, ignore_errors=True)+ shutil.rmtree(ISO_DIR, ignore_errors=True)+ DATA_DIR.mkdir(parents=True, exist_ok=True)+ ISO_DIR.mkdir(parents=True, exist_ok=True)++ port = _free_port()+ env = _bench_env(port)+ # The desktop driver reads the port from this env (no --port CLI exists for+ # the desktop path); _bench_env already pins isolation + JARVIS_VOICE=0.+ env["JARVIS_DESKTOP_BENCH_PORT"] = str(port)+ env["JARVIS_DESKTOP_BENCH_MODE"] = mode++ cmd = [python, str(DRIVER)]+ result: dict = {+ "wall_ms": None, # spawn -> /api/health 200 (PRIMARY = window appears)+ "boot_ready_ms": None, # in-process bootstrap-bind print (secondary)+ "boot_ready_wall_ms": None,+ "phases": {},+ "port": port,+ }+ health_ok = threading.Event()++ t_spawn = time.perf_counter()+ proc = subprocess.Popen(+ cmd,+ cwd=str(REPO_ROOT),+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ bufsize=1,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )++ def reader() -> None:+ assert proc.stdout is not None+ for raw in proc.stdout:+ line = raw.rstrip("\r\n")+ if line.startswith("[BOOT_PROFILE] "):+ name, _, val = line[len("[BOOT_PROFILE] "):].partition("=")+ try:+ result["phases"][name] = float(val)+ except ValueError:+ pass+ elif line.startswith("BOOT_READY_MS="):+ result["boot_ready_wall_ms"] = (time.perf_counter() - t_spawn) * 1000.0+ try:+ result["boot_ready_ms"] = float(line.split("=", 1)[1])+ except ValueError:+ result["boot_ready_ms"] = None++ def poller() -> None:+ # PRIMARY anchor = time until GET / returns the real UI shell (HTML).+ # That is the moment the desktop window stops being a black screen and+ # shows the UI — the user-perceived "boot done". The serve-first+ # bootstrap serves the static frontend straight from disk, so this fires+ # at bind time, not after the full app build.+ url = f"http://127.0.0.1:{port}/"+ time.sleep(0.02)+ while not health_ok.is_set() and proc.poll() is None:+ try:+ with urllib.request.urlopen(url, timeout=0.5) as r: # noqa: S310+ if r.status == 200:+ body = r.read(512).decode("utf-8", "replace").lower()+ if "<!doctype html" in body or "<div id=" in body or "<html" in body:+ result["wall_ms"] = (time.perf_counter() - t_spawn) * 1000.0+ health_ok.set()+ return+ except Exception: # noqa: BLE001+ pass+ time.sleep(0.05)++ th = threading.Thread(target=reader, daemon=True)+ th.start()+ pt = threading.Thread(target=poller, daemon=True)+ pt.start()++ got = health_ok.wait(timeout)+ _terminate(proc)+ th.join(timeout=3)+ pt.join(timeout=3)++ if not got or result["wall_ms"] is None:+ raise RuntimeError(+ f"desktop cold boot did not reach a 200 /api/health within {timeout:.0f}s "+ f"(port {port}) — check the driver / instrumentation"+ )+ return result+++def _summarize(runs: list[dict], *, python: str, pages: int) -> dict:+ walls = [r["wall_ms"] for r in runs]+ readies = [r["boot_ready_ms"] for r in runs if r["boot_ready_ms"] is not None]+ bind_walls = [r["boot_ready_wall_ms"] for r in runs if r["boot_ready_wall_ms"] is not None]+ phase_names = sorted({k for r in runs for k in r["phases"]})+ phase_medians = {+ name: statistics.median(+ [r["phases"][name] for r in runs if name in r["phases"]]+ )+ for name in phase_names+ }+ return {+ "path": "desktop (_run_backend, GUI-free driver)",+ "runs": len(runs),+ "python": python,+ "vault_pages": pages,+ "median_wall_ms": round(statistics.median(walls), 1),+ "median_boot_ready_ms": (+ round(statistics.median(readies), 1) if readies else None+ ),+ "median_bind_wall_ms": (+ round(statistics.median(bind_walls), 1) if bind_walls else None+ ),+ "wall_ms_runs": [round(w, 1) for w in walls],+ "boot_ready_ms_runs": [round(r, 1) for r in readies],+ "phase_medians_ms": {k: round(v, 1) for k, v in phase_medians.items()},+ "anchor": "spawn -> /api/health responds 200 (= DesktopApp._wait_for_backend success = window creation point)",+ "secondary_anchor": "median_bind_wall_ms = spawn -> BOOT_READY print (bootstrap bind; may precede a responsive health endpoint)",+ }+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description="Desktop cold-boot timing harness")+ ap.add_argument("--python", default=DEFAULT_PYTHON, help="interpreter for the spawned driver")+ ap.add_argument("--runs", type=int, default=5, help="measured cold starts (median)")+ ap.add_argument("--warmup", type=int, default=1, help="discarded warmup boots")+ ap.add_argument("--timeout", type=float, default=120.0, help="per-boot ready timeout (s)")+ ap.add_argument("--pages", type=int, default=DEFAULT_PAGES, help="vault pages to seed")+ ap.add_argument("--mode", default="legacy", choices=["legacy", "fastboot"], help="desktop boot path to measure")+ args = ap.parse_args(argv)++ if not Path(args.python).exists():+ print(f"WARNING: interpreter not found at {args.python}; using as-is", flush=True)++ pages = seed_vault(args.pages)+ print(f"[harness] vault seeded: {pages} pages", flush=True)++ for i in range(args.warmup):+ print(f"[harness] warmup {i + 1}/{args.warmup} ...", flush=True)+ r = run_one(args.python, args.timeout, args.mode)+ print(f"[harness] warmup wall={r['wall_ms']:.0f}ms", flush=True)++ runs: list[dict] = []+ for i in range(args.runs):+ r = run_one(args.python, args.timeout, args.mode)+ runs.append(r)+ _br = r["boot_ready_ms"]+ _br_s = f"{_br:.0f}ms" if _br is not None else "n/a"+ print(+ f"[harness] run {i + 1}/{args.runs}: health200={r['wall_ms']:.0f}ms "+ f"bind={_br_s}",+ flush=True,+ )++ summary = _summarize(runs, python=args.python, pages=pages)+ LATEST_PATH.write_text(json.dumps(summary, indent=2), encoding="utf-8")++ froze_baseline = False+ if not BASELINE_PATH.exists():+ BASELINE_PATH.write_text(json.dumps(summary, indent=2), encoding="utf-8")+ froze_baseline = True++ def _ms(v: float | None) -> str:+ return f"{v:.0f} ms" if v is not None else "n/a"++ print("\n=== DESKTOP BOOT TIMING SUMMARY ===", flush=True)+ print(f"median spawn->/api/health 200 : {_ms(summary['median_wall_ms'])} (PRIMARY: window appears)", flush=True)+ print(f"median bootstrap-bind print : {_ms(summary['median_bind_wall_ms'])} (secondary)", flush=True)+ print(f"runs: {summary['wall_ms_runs']}", flush=True)+ print("per-phase medians (ms):", flush=True)+ for name, val in sorted(summary["phase_medians_ms"].items(), key=lambda kv: -kv[1]):+ print(f" {name:24s} {val:8.1f}", flush=True)++ if froze_baseline:+ print(f"\nfroze baseline -> {BASELINE_PATH.name}", flush=True)+ elif BASELINE_PATH.exists():+ base = json.loads(BASELINE_PATH.read_text(encoding="utf-8"))+ base_wall = base.get("median_wall_ms")+ if base_wall:+ factor = base_wall / summary["median_wall_ms"]+ print(+ f"\nbaseline median {base_wall:.0f} ms -> now "+ f"{summary['median_wall_ms']:.0f} ms = {factor:.2f}x faster",+ flush=True,+ )+ print(f"wrote {LATEST_PATH.name}", flush=True)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/sandbox/new-jarvis-sandbox.ps1 b/scripts/sandbox/new-jarvis-sandbox.ps1new file mode 100644index 0000000000..980e9e0412--- /dev/null+++ b/scripts/sandbox/new-jarvis-sandbox.ps1@@ -0,0 +1,250 @@+<#+.SYNOPSIS+ Provision a fully isolated, throwaway Personal Jarvis sandbox from a fresh+ clone of the PUBLIC distribution repo -- so the maintainer experiences exactly+ what a stranger downloading from GitHub gets, WITHOUT touching the real+ install's config, data, or credentials.++.DESCRIPTION+ Design: docs/superpowers/specs/2026-06-24-jarvis-sandbox-testing-design.md.++ The sandbox seals the four shared-state seams that would otherwise let a+ second native instance collide with the real install:++ 1. Python import -- a dedicated venv inside the sandbox dir. The editable+ install pins ONLY that venv; the global 'import jarvis'+ is untouched (defeats the BUG-006/014/015 restore trap).+ 2. Credentials -- PYTHON_KEYRING_BACKEND=keyrings.alt.file.PlaintextKeyring+ redirects keyring to an isolated throwaway file. The+ real 'personal-jarvis' Windows Credential Manager+ namespace is NEVER read or written.+ 3. Config -- JARVIS_CONFIG points at <sandbox>\jarvis.toml.+ 4. Data -- a separate clone makes PROJECT_ROOT resolve into the+ sandbox, so data\ lands in <sandbox>\data.++ Computer-Use is forced OFF (the sandbox can talk and show its UI, but never+ drives the physical desktop). Voice stays ON.++ The provisioner runs the documented stranger steps, redirected into the+ sandbox, then proves isolation BEFORE generating the launch command. It does+ NOT auto-launch: voice shares the one set of speakers/mic with the real app,+ so YOU close the real Jarvis first, then run the printed run-sandbox.ps1.++.PARAMETER SandboxRoot+ Where to build the sandbox. Default: a 'Jarvis-Sandbox' sibling of this repo.++.PARAMETER RepoUrl+ Source repo. Default: the public flagship PersonalJarvis/PersonalJarvis.++.PARAMETER Ref+ Branch or tag to clone. Default: main (the published default branch).++.PARAMETER Port+ Web/admin port for the sandbox (kept off the real app's 47821). Default 47830.++.PARAMETER Force+ Delete an existing sandbox dir (to the Recycle Bin) and re-provision.++.PARAMETER Launch+ After provisioning + proofs, launch immediately. Default OFF -- the script+ prints the launch command so YOU control the mic handoff.++.EXAMPLE+ powershell -File scripts\sandbox\new-jarvis-sandbox.ps1+#>+[CmdletBinding()]+param(+ [string]$SandboxRoot,+ [string]$RepoUrl = "https://github.com/PersonalJarvis/PersonalJarvis.git",+ [string]$Ref = "main",+ [int]$Port = 47830,+ [switch]$Force,+ [switch]$Launch+)++$ErrorActionPreference = "Stop"+$script:RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path++function Write-Step([string]$msg) { Write-Host "`n=== $msg ===" -ForegroundColor Cyan }+function Write-Ok([string]$msg) { Write-Host " [ok] $msg" -ForegroundColor Green }+function Write-Warn2([string]$msg) { Write-Host " [warn] $msg" -ForegroundColor Yellow }+function Fail([string]$msg) { Write-Host " [FAIL] $msg" -ForegroundColor Red; exit 1 }++# Default sandbox root = sibling of the repo (keeps the editable-install pin away+# from the real tree; the parent dir is not a git repo, so no collision).+if (-not $SandboxRoot -or $SandboxRoot.Trim() -eq "") {+ $SandboxRoot = (Join-Path (Split-Path $script:RepoRoot -Parent) "Jarvis-Sandbox")+}++Write-Step "Personal Jarvis -- isolated sandbox provisioner"+Write-Host (" source : {0} (ref {1})" -f $RepoUrl, $Ref)+Write-Host (" target : {0}" -f $SandboxRoot)+Write-Host (" port : {0} (real app stays on 47821)" -f $Port)++# --- 1. Preconditions ------------------------------------------------------+Write-Step "1. Preconditions"+$gitCmd = (Get-Command git -ErrorAction SilentlyContinue)+if (-not $gitCmd) { Fail "git not found on PATH." }+Write-Ok ("git: {0}" -f $gitCmd.Source)++# Host Python >= 3.11. Prefer the known interpreter, fall back to PATH.+$pyExe = "C:\Program Files\Python311\python.exe"+if (-not (Test-Path $pyExe)) {+ $pyCmd = Get-Command python -ErrorAction SilentlyContinue+ if (-not $pyCmd) { Fail "Python 3.11+ not found." }+ $pyExe = $pyCmd.Source+}+$pyVerRaw = & $pyExe -c "import sys; print(sys.version_info[0], sys.version_info[1])"+$pyParts = $pyVerRaw.Trim() -split '\s+'+$pyMajor = [int]$pyParts[0]; $pyMinor = [int]$pyParts[1]+if ($pyMajor -lt 3 -or ($pyMajor -eq 3 -and $pyMinor -lt 11)) { Fail ("Python {0}.{1} found; need >= 3.11." -f $pyMajor, $pyMinor) }+Write-Ok ("python: {0} ({1}.{2})" -f $pyExe, $pyMajor, $pyMinor)++# Capture the GLOBAL 'import jarvis' origin BEFORE we touch anything. Run from a+# NEUTRAL dir so the current directory's ./jarvis cannot shadow the real answer+# (python -c puts the CWD on sys.path[0]).+Push-Location $env:TEMP+$globalJarvisBefore = & $pyExe -c "import importlib.util as u; s=u.find_spec('jarvis'); print(s.origin if s else 'NONE')" 2>$null+Pop-Location+if (-not $globalJarvisBefore) { $globalJarvisBefore = "NONE" }+Write-Ok ("global 'import jarvis' baseline: {0}" -f $globalJarvisBefore)++# --- 2. Sandbox dir --------------------------------------------------------+Write-Step "2. Sandbox directory"+if (Test-Path $SandboxRoot) {+ if (-not $Force) { Fail ("{0} already exists. Re-run with -Force to replace it." -f $SandboxRoot) }+ Write-Warn2 "exists -- moving the old sandbox to the Recycle Bin"+ Add-Type -AssemblyName Microsoft.VisualBasic+ [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($SandboxRoot, 'OnlyErrorDialogs', 'SendToRecycleBin')+}++# --- 3. Fresh clone (the truest clean room) --------------------------------+Write-Step "3. Fresh clone from GitHub"+& git clone --branch $Ref --single-branch $RepoUrl $SandboxRoot+if ($LASTEXITCODE -ne 0) { Fail "git clone failed (private repo? run 'gh auth status' / 'gh auth setup-git')." }+$clonedHead = (& git -C $SandboxRoot rev-parse --short HEAD)+Write-Ok ("cloned {0} at {1}" -f $Ref, $clonedHead)++# --- 4. Isolated venv + install (the documented stranger steps) ------------+Write-Step "4. Isolated venv + install"+$venv = Join-Path $SandboxRoot ".venv"+& $pyExe -m venv $venv+if ($LASTEXITCODE -ne 0) { Fail "venv creation failed." }+$venvPy = Join-Path $venv "Scripts\python.exe"+Write-Ok ("venv: {0}" -f $venv)++Write-Host " installing (this takes a few minutes)..."+& $venvPy -m pip install --upgrade pip --quiet+Push-Location $SandboxRoot+try {+ & $venvPy -m pip install -e ".[full]" --quiet+ if ($LASTEXITCODE -ne 0) { Fail "pip install -e .[full] failed." }+ & $venvPy -m pip install "keyrings.alt" --quiet+ if ($LASTEXITCODE -ne 0) { Fail "pip install keyrings.alt failed." }+} finally { Pop-Location }+Write-Ok "installed .[full] + keyrings.alt into the sandbox venv"++# --- 5. Seed isolated config (Computer-Use OFF) ----------------------------+Write-Step "5. Seed sandbox config"+$sandboxConfig = Join-Path $SandboxRoot "jarvis.toml"+$exampleConfig = Join-Path $SandboxRoot "jarvis.toml.example"+if (Test-Path $exampleConfig) { Copy-Item $exampleConfig $sandboxConfig -Force }+else { Set-Content -Path $sandboxConfig -Value "# sandbox config" -Encoding utf8 }+$cuOverride = "`r`n# --- sandbox override: never drive the physical desktop ---`r`n[computer_use]`r`nenabled = false`r`n"+Add-Content -Path $sandboxConfig -Value $cuOverride -Encoding utf8+Write-Ok ("wrote {0} (computer_use.enabled = false)" -f $sandboxConfig)++$sandboxEnv = Join-Path $SandboxRoot ".env"+if (-not (Test-Path $sandboxEnv)) {+ $envTemplate = "# Sandbox-local keys (optional). Paste ONE brain-provider key to talk to the`r`n# test copy without onboarding, e.g. GEMINI_API_KEY=... / ANTHROPIC_API_KEY=...`r`n# These never touch your real Credential Manager.`r`n"+ Set-Content -Path $sandboxEnv -Value $envTemplate -Encoding utf8+ Write-Ok "wrote a blank sandbox .env (add a lent key, or use first-run onboarding)"+}++# --- 6. Generate the launch command ----------------------------------------+Write-Step "6. Generate run-sandbox.ps1"+$runScript = Join-Path $SandboxRoot "run-sandbox.ps1"+$dataDir = Join-Path $SandboxRoot "data"+# Redirect the OS user-data root into the sandbox too. Several subsystems (board+# stats, user skills, contacts, cli_ctl config) resolve their location from+# user_data_dir() == %LOCALAPPDATA%\Jarvis (platformdirs), NOT from+# JARVIS_DATA_DIR -- so without this they would write into the REAL shared+# %LOCALAPPDATA%\Jarvis and contaminate the real install's board/skills. Pointing+# LOCALAPPDATA at a sandbox-local dir seals that last seam (a fresh stranger has a+# fresh AppData).+$appLocal = Join-Path $SandboxRoot "appdata\Local"+New-Item -ItemType Directory -Force -Path $appLocal | Out-Null+$runLines = @(+ "# Launch the ISOLATED Jarvis sandbox. Generated by new-jarvis-sandbox.ps1.",+ "# Close your REAL Jarvis first -- voice shares the one mic/speakers.",+ "`$ErrorActionPreference = 'Stop'",+ ("Set-Location '{0}'" -f $SandboxRoot),+ ("`$env:JARVIS_CONFIG = '{0}'" -f $sandboxConfig),+ ("`$env:JARVIS_DATA_DIR = '{0}'" -f $dataDir),+ ("`$env:LOCALAPPDATA = '{0}'" -f $appLocal),+ "`$env:PYTHON_KEYRING_BACKEND = 'keyrings.alt.file.PlaintextKeyring'",+ "`$env:JARVIS_VOICE = '1'",+ ("Write-Host 'Launching isolated Jarvis sandbox on port {0} (Computer-Use OFF)...' -ForegroundColor Cyan" -f $Port),+ ("& '{0}' -m jarvis.ui.web.launcher --no-lock --port {1}" -f $venvPy, $Port)+)+Set-Content -Path $runScript -Value ($runLines -join "`r`n") -Encoding utf8+Write-Ok ("wrote {0}" -f $runScript)++# --- 7. Prove isolation BEFORE any launch ----------------------------------+Write-Step "7. Isolation proofs"+$allPass = $true++# Run the import checks from a NEUTRAL dir so neither the real repo's nor the+# sandbox's ./jarvis on sys.path[0] (the CWD) can mask the editable install each+# interpreter actually resolves. This is what makes the proof trustworthy.+Push-Location $env:TEMP+$sandboxImport = & $venvPy -c "import jarvis; print(jarvis.__file__)" 2>$null+$globalAfter = & $pyExe -c "import importlib.util as u; s=u.find_spec('jarvis'); print(s.origin if s else 'NONE')" 2>$null+Pop-Location+if ($sandboxImport -and $sandboxImport.StartsWith($SandboxRoot)) { Write-Ok ("sandbox 'import jarvis' -> {0}" -f $sandboxImport) }+else { Write-Warn2 ("sandbox import origin unexpected: {0}" -f $sandboxImport); $allPass = $false }+if (-not $globalAfter) { $globalAfter = "NONE" }+if ($globalAfter -eq $globalJarvisBefore) { Write-Ok ("global 'import jarvis' unchanged ({0})" -f $globalAfter) }+else { Write-Warn2 ("global import CHANGED: '{0}' -> '{1}'" -f $globalJarvisBefore, $globalAfter); $allPass = $false }++$env:PYTHON_KEYRING_BACKEND = 'keyrings.alt.file.PlaintextKeyring'+$kr = & $venvPy -c "import keyring; print(type(keyring.get_keyring()).__name__)" 2>$null+$env:PYTHON_KEYRING_BACKEND = $null+if ($kr -and $kr -notmatch "WinVault") { Write-Ok ("sandbox keyring backend: {0} (not WinVaultKeyring)" -f $kr) }+else { Write-Warn2 ("keyring backend looks wrong: {0}" -f $kr); $allPass = $false }++# user_data_dir() (board stats, skills, contacts, cli config) must resolve INTO+# the sandbox, not the shared %LOCALAPPDATA%\Jarvis. Check it with the sandbox's+# LOCALAPPDATA override in effect.+$savedLAD = $env:LOCALAPPDATA+$env:LOCALAPPDATA = $appLocal+Push-Location $env:TEMP+$udd = & $venvPy -c "from jarvis.core.paths import user_data_dir; print(user_data_dir())" 2>$null+Pop-Location+$env:LOCALAPPDATA = $savedLAD+if ($udd -and $udd.StartsWith($SandboxRoot)) { Write-Ok ("sandbox user-data dir -> {0}" -f $udd) }+else { Write-Warn2 ("user-data dir NOT isolated (board/skills would touch the real install): {0}" -f $udd); $allPass = $false }++if (Test-Path (Join-Path $SandboxRoot "jarvis\ui\web\dist\index.html")) { Write-Ok "prebuilt UI present -- no Node build needed" }+else { Write-Warn2 "no prebuilt UI found -- the clone may need a frontend build"; $allPass = $false }++# --- 8. Summary ------------------------------------------------------------+Write-Step "Done"+if ($allPass) { Write-Host " All isolation proofs PASSED." -ForegroundColor Green }+else { Write-Warn2 "Some proofs did not pass cleanly -- review the [warn] lines above." }++Write-Host ""+Write-Host (" Your isolated test copy is ready at: {0}" -f $SandboxRoot) -ForegroundColor White+Write-Host " To talk to it:" -ForegroundColor White+Write-Host " 1. CLOSE your real Jarvis (it owns the mic/speakers)." -ForegroundColor White+Write-Host (" 2. (optional) add a provider key to: {0}" -f $sandboxEnv) -ForegroundColor White+Write-Host (" 3. Run: powershell -File `"{0}`"" -f $runScript) -ForegroundColor White+Write-Host ""+Write-Host (" Runs on port {0}, Computer-Use OFF, walled off from your real config/data/keys." -f $Port) -ForegroundColor DarkGray+Write-Host " Remove it any time with remove-jarvis-sandbox.ps1 (goes to the Recycle Bin)." -ForegroundColor DarkGray++if ($Launch) {+ Write-Step "Launching now (-Launch)"+ Write-Warn2 "Make sure your real Jarvis is closed (shared mic)."+ & $runScript+}diff --git a/scripts/sandbox/remove-jarvis-sandbox.ps1 b/scripts/sandbox/remove-jarvis-sandbox.ps1new file mode 100644index 0000000000..777db7cfda--- /dev/null+++ b/scripts/sandbox/remove-jarvis-sandbox.ps1@@ -0,0 +1,61 @@+<#+.SYNOPSIS+ Tear down a Jarvis sandbox: move it to the Recycle Bin and confirm the real+ install was never touched.++.DESCRIPTION+ Reversible by design -- the sandbox dir goes to the Recycle Bin, not a+ permanent delete. Then it re-checks that the real 'personal-jarvis' Windows+ Credential Manager entries are still present (the sandbox used an isolated+ file keyring) and that the global 'import jarvis' still resolves to the real+ repo.++.PARAMETER SandboxRoot+ The sandbox to remove. Default: the 'Jarvis-Sandbox' sibling of this repo.+#>+[CmdletBinding()]+param(+ [string]$SandboxRoot+)++$ErrorActionPreference = "Stop"+$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path+if (-not $SandboxRoot -or $SandboxRoot.Trim() -eq "") {+ $SandboxRoot = (Join-Path (Split-Path $repoRoot -Parent) "Jarvis-Sandbox")+}++function Write-Step([string]$m) { Write-Host "`n=== $m ===" -ForegroundColor Cyan }++Write-Step "Remove Jarvis sandbox"+Write-Host (" target: {0}" -f $SandboxRoot)++if (-not (Test-Path $SandboxRoot)) {+ Write-Host " Nothing to remove (no sandbox at that path)." -ForegroundColor Yellow+ exit 0+}++# Refuse to delete anything that is not actually a sandbox (must contain the+# generated launcher) -- guards against a mistyped path pointing at real work.+if (-not (Test-Path (Join-Path $SandboxRoot "run-sandbox.ps1"))) {+ Write-Host " [FAIL] no run-sandbox.ps1 there -- refusing to delete (does not look like a sandbox)." -ForegroundColor Red+ exit 1+}++Write-Host " Moving sandbox to the Recycle Bin (reversible)..."+Add-Type -AssemblyName Microsoft.VisualBasic+[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($SandboxRoot, 'OnlyErrorDialogs', 'SendToRecycleBin')+if (Test-Path $SandboxRoot) {+ Write-Host " [FAIL] sandbox still present -- move failed (a process may be holding it open)." -ForegroundColor Red+ exit 1+}+Write-Host " [ok] sandbox moved to the Recycle Bin." -ForegroundColor Green++Write-Step "Confirm the real install is untouched"+$realKeys = (cmdkey /list 2>$null | Select-String "personal-jarvis").Count+Write-Host (" real 'personal-jarvis' credential entries still present: {0}" -f $realKeys)+$pyExe = "C:\Program Files\Python311\python.exe"+if (Test-Path $pyExe) {+ $globalJarvis = & $pyExe -c "import importlib.util as u; s=u.find_spec('jarvis'); print(s.origin if s else 'NONE')" 2>$null+ Write-Host (" global 'import jarvis' resolves to: {0}" -f $globalJarvis)+}+Write-Host " [ok] teardown complete -- host left as it was." -ForegroundColor Greendiff --git a/scripts/skill_routing_eval.py b/scripts/skill_routing_eval.pynew file mode 100644index 0000000000..ef5c335951--- /dev/null+++ b/scripts/skill_routing_eval.py@@ -0,0 +1,207 @@+"""Skill-routing eval (2026-06-24): does the router pick `run-skill` on a+natural paraphrase, the way Claude Code does?++Background — the "Claude-Code parity" change+(docs/superpowers/specs/2026-06-24-skill-firing-claude-code-parity-design.md):+the builtin skills already carry rich when_to_use fields, but the router used+to almost never call `run-skill` on its own. The fix strengthened the router+prompt stance + the AVAILABLE SKILLS framing so a plausibly-matching skill is+the brain's first move. This script measures that behaviour against the LIVE+router brain.++How it measures (zero side effects)+-----------------------------------+Each golden utterance is a NATURAL paraphrase that deliberately avoids the+skill's exact regex trigger — so the ONLY way the skill can fire is the+model-judged path (the brain choosing `run-skill` from the listing). `run-skill`+publishes a frozen ``SkillInvoked`` event the moment it loads the skill's+instructions, *before* the brain executes any of the skill's steps. We listen+for that event and CANCEL the turn as soon as it fires — so we record the+routing decision without ever running the skill's downstream actions.++Negative controls verify the over-fire guard: a plain knowledge question that+merely mentions a topic must NOT fire a skill.++Usage:+ python scripts/skill_routing_eval.py++Needs a configured brain provider (key in the Credential Manager / env). With+no reachable provider the run reports PROVIDER? rather than a skill miss.+"""+from __future__ import annotations++import asyncio+import sys+from dataclasses import dataclass+from pathlib import Path++REPO = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO))++if sys.platform == "win32":+ try:+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")+ except Exception:+ pass+++# (utterance, expected_skill_or_None). expected=None → a negative control that+# must NOT fire any skill. Every positive paraphrase avoids the skill's literal+# voice-trigger tokens, so only the model-judged path can fire it.+GOLDEN: list[tuple[str, str | None]] = [+ ("fass mir mal kurz zusammen was heute alles ansteht", "morning-routine"),+ ("ich brauch jetzt ruhe zum arbeiten, blende mir die ablenkungen aus",+ "deep-work-mode"),+ ("schau mal ob heute schon was wichtiges per e-mail reingekommen ist",+ "plugin-gmail"),+ ("wie viel kostet mich gerade meine google cloud diesen monat?",+ "cli-gcloud"),+ ("sind bei mir eigentlich noch issues offen, die ich angehen muss?",+ "plugin-github"),+ ("wie viel hab ich diesen monat eigentlich eingenommen?", "plugin-stripe"),+ # --- negative controls: the app is only the SUBJECT of a knowledge+ # question; the definitional guard must keep the skill from firing ---+ ("was ist eigentlich GitHub fuer eine plattform?", None),+ ("was ist Stripe ueberhaupt und wofuer nutzt man das?", None),+]++PER_TURN_TIMEOUT_S = 60.0+++@dataclass+class _Fire:+ skill_name: str+ source: str+++async def main() -> int:+ from jarvis.brain.factory import build_default_brain+ from jarvis.core.bus import EventBus+ from jarvis.skills.prompt_injection import render_available_skills_section+ from jarvis.skills.schema import SkillInvoked+ from jarvis.skills.skill_context import try_get_skill_context++ print("=" * 72)+ print("Skill-routing eval — does the router pick run-skill on a paraphrase?")+ print("=" * 72)++ bus = EventBus()++ fires: list[_Fire] = []+ fire_event = asyncio.Event()++ async def on_event(evt: object) -> None:+ if isinstance(evt, SkillInvoked):+ fires.append(_Fire(skill_name=evt.skill_name, source=evt.source))+ fire_event.set()++ bus.subscribe_all(on_event)++ print("\n--- Building the live router brain (this also wires the skill context) ---")+ try:+ bm = build_default_brain(bus=bus)+ except Exception as exc: # noqa: BLE001+ print(f" brain build FAILED: {type(exc).__name__}: {exc}")+ return 1+ print(f" active_provider = {getattr(bm, 'active_provider', '?')}")++ # Show exactly which skills the brain can see — a miss on an unlisted skill+ # is a registry/lifecycle issue, not a routing regression.+ ctx = try_get_skill_context()+ if ctx is not None:+ section = render_available_skills_section(ctx.registry)+ listed = (+ [s.name for s in ctx.registry.list_active()]+ if hasattr(ctx.registry, "list_active") else []+ )+ print(f"\n--- AVAILABLE SKILLS the brain sees ({len(listed)}) ---")+ print(" " + ", ".join(sorted(listed)) if listed else " (none)")+ if section is None:+ print(" WARNING: render_available_skills_section returned None — "+ "the brain sees NO skills; every positive case will miss.")+ else:+ print("\n WARNING: no skill context — cannot list skills.")++ rows: list[tuple[str, str, str, str]] = []+ print("\n--- Running golden set ---")+ for utterance, expected in GOLDEN:+ fires.clear()+ fire_event.clear()++ task = asyncio.create_task(bm.generate(utterance, use_history=False))+ wait_fire = asyncio.create_task(fire_event.wait())+ done, pending = await asyncio.wait(+ {task, wait_fire},+ timeout=PER_TURN_TIMEOUT_S,+ return_when=asyncio.FIRST_COMPLETED,+ )++ fired: _Fire | None = fires[0] if fires else None+ result_text = ""+ if fired is not None:+ # Routing decision captured — stop before the skill executes.+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ elif task in done:+ try:+ result_text = (task.result() or "")[:160]+ except Exception as exc: # noqa: BLE001+ result_text = f"<{type(exc).__name__}: {exc}>"+ else:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ result_text = "<TIMEOUT>"+ for p in pending:+ p.cancel()+ await asyncio.gather(wait_fire, return_exceptions=True)++ # Verdict+ if expected is None:+ verdict = "FAIL(over-fire)" if fired else "PASS"+ got = f"{fired.skill_name} [{fired.source}]" if fired else "(no skill)"+ else:+ if fired and fired.skill_name == expected:+ verdict = f"HIT [{fired.source}]"+ elif fired:+ verdict = f"WRONG({fired.skill_name})"+ else:+ low = result_text.lower()+ provider_down = any(+ ind in low for ind in+ ("account", "brain-key", "unerreichbar", "setup", "sidebar")+ )+ verdict = "PROVIDER?" if provider_down else "MISS"+ got = f"{fired.skill_name} [{fired.source}]" if fired else (+ result_text or "(direct answer)")+ rows.append((utterance, expected or "(none — neg)", got, verdict))+ print(f" [{verdict:16s}] {utterance[:52]:52s} → {got[:40]}")++ # Summary+ pos = [r for r, (_, exp) in zip(rows, GOLDEN) if exp is not None]+ neg = [r for r, (_, exp) in zip(rows, GOLDEN) if exp is None]+ hits = sum(1 for r in pos if r[3].startswith("HIT"))+ neg_pass = sum(1 for r in neg if r[3] == "PASS")+ provider_q = sum(1 for r in rows if r[3] == "PROVIDER?")++ print("\n" + "=" * 72)+ print(f" Positive (model-judged firing): {hits}/{len(pos)} HIT")+ print(f" Negative (over-fire guard): {neg_pass}/{len(neg)} PASS")+ if provider_q:+ print(f" PROVIDER? rows: {provider_q} — brain provider unreachable, "+ "rerun with a configured key for a clean number.")+ print("=" * 72)++ # Exit 0 when every positive that had a reachable provider fired AND no+ # over-fire — the loop's success condition.+ real_pos = [r for r in pos if r[3] != "PROVIDER?"]+ ok = (+ all(r[3].startswith("HIT") for r in real_pos)+ and neg_pass == len(neg)+ and len(real_pos) > 0+ )+ return 0 if ok else 1+++if __name__ == "__main__":+ sys.exit(asyncio.run(main()))diff --git a/scripts/smoke_desktop_boot.py b/scripts/smoke_desktop_boot.pynew file mode 100644index 0000000000..69513ad2bb--- /dev/null+++ b/scripts/smoke_desktop_boot.py@@ -0,0 +1,126 @@+#!/usr/bin/env python+"""Functional smoke for the serve-first desktop boot (anti-gaming guard).++Proves the bootstrap is not just answering a synthetic 200 but actually+DELEGATES to the real FastAPI app once it is built:++1. boot the desktop backend (the GUI-free driver, ``legacy`` = production path),+2. observe ``/api/health`` first answered by the bootstrap (``"warming": true``),+3. then answered by the REAL app (carries a ``"version"`` field) — proving+ ``set_app`` delegation works,+4. and a genuinely real route (``/api/voice/status``) returns real JSON.++Exit 0 = pass.+"""++from __future__ import annotations++import json+import shutil+import subprocess+import sys+import time+import urllib.request+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(Path(__file__).resolve().parent))++from measure_boot import ( # noqa: E402+ DATA_DIR,+ DEFAULT_PYTHON,+ ISO_DIR,+ NO_WINDOW_CREATIONFLAGS,+ _bench_env,+ _free_port,+ _terminate,+ seed_vault,+)++DRIVER = REPO_ROOT / "scripts" / "_desktop_boot_driver.py"+++def _get(url: str, timeout: float = 1.0) -> tuple[int, str]:+ try:+ with urllib.request.urlopen(url, timeout=timeout) as r: # noqa: S310+ return r.status, r.read().decode("utf-8", "replace")+ except Exception as exc: # noqa: BLE001+ return 0, f"<err {type(exc).__name__}>"+++def main() -> int:+ seed_vault(80)+ shutil.rmtree(DATA_DIR, ignore_errors=True)+ shutil.rmtree(ISO_DIR, ignore_errors=True)+ DATA_DIR.mkdir(parents=True, exist_ok=True)+ ISO_DIR.mkdir(parents=True, exist_ok=True)++ port = _free_port()+ env = _bench_env(port)+ env["JARVIS_DESKTOP_BENCH_PORT"] = str(port)+ # "legacy" = classic _run_backend; "fastboot" = production launcher+ # _desktop_backend_main (the early-bind path). Both serve the real app.+ import os as _os+ env["JARVIS_DESKTOP_BENCH_MODE"] = _os.environ.get("SMOKE_MODE", "legacy")++ proc = subprocess.Popen(+ [DEFAULT_PYTHON, str(DRIVER)],+ cwd=str(REPO_ROOT),+ env=env,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )++ health_url = f"http://127.0.0.1:{port}/api/health"+ root_url = f"http://127.0.0.1:{port}/"+ saw_warming = False+ saw_real = False+ real_body = ""+ # Black-screen guard: GET / must return the real UI shell (index.html) very+ # early (served from the bootstrap while warming), NOT be held/blank.+ root_html_early = False+ try:+ deadline = time.monotonic() + 45.0+ while time.monotonic() < deadline:+ status, body = _get(health_url)+ if status == 200 and '"warming"' in body:+ saw_warming = True+ # While still warming, the window's GET / must already paint the+ # real shell (this is what kills the black screen).+ rstatus, rbody = _get(root_url, 2.0)+ if rstatus == 200 and ("<!doctype html" in rbody.lower() or "<div id=" in rbody.lower()):+ root_html_early = True+ if status == 200 and '"version"' in body:+ saw_real = True+ real_body = body+ break+ time.sleep(0.1)++ root_status, root_body = _get(root_url, 3.0)+ voice_status, voice_body = _get(f"http://127.0.0.1:{port}/api/voice/status", 3.0)+ finally:+ _terminate(proc)++ root_html = root_status == 200 and (+ "<!doctype html" in root_body.lower() or "<div id=" in root_body.lower()+ )+ print(f"saw bootstrap warming health : {saw_warming}")+ print(f"GET / real UI shell WHILE warming (no black screen): {root_html_early}")+ print(f"saw real-app health : {saw_real} {real_body[:80]}")+ print(f"GET / returns UI shell : {root_html} (status {root_status})")+ print(f"real route /api/voice/status : {voice_status} {voice_body[:80]}")++ ok = saw_real and voice_status == 200 and root_html+ try:+ json.loads(voice_body)+ except Exception: # noqa: BLE001+ ok = False+ print("FAIL: /api/voice/status did not return valid JSON")++ print("SMOKE PASS" if ok else "SMOKE FAIL")+ return 0 if ok else 1+++if __name__ == "__main__":+ raise SystemExit(main())