From 427b1a30484d640228979abed6e9780cea9adc13 Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 04:51:20 +0100 Subject: [PATCH 01/10] feat(demo): add opt-in guarded AI Thinkers HOTL recovery supervisor --- demos/ai-thinkers/hotl.py | 216 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 demos/ai-thinkers/hotl.py diff --git a/demos/ai-thinkers/hotl.py b/demos/ai-thinkers/hotl.py new file mode 100644 index 0000000..8e96739 --- /dev/null +++ b/demos/ai-thinkers/hotl.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""AI Thinkers HOTL local-kind spike. NOT production automation. + +Explicit enablement; exact workload guard; AI only proposes; atomic Kubernetes +preconditions; separate evidence; Ctrl-C stops future attempts. +""" +import argparse +import fcntl +import json +import os +import subprocess +import sys +import time +import urllib.request +from datetime import datetime, timezone +from pathlib import Path +from urllib.parse import urlsplit + +NS = "wjax-demo" +NAME = "wjax-nginx" +IMAGE = "nginx:1.27.5-alpine" +EXPECTED = {"operation": "deploy", "workload": "nginx", "replicas": 2, "target": "demo"} +CONSENT = "I_ACCEPT_LOCAL_KIND_ONLY" + + +def record(path, event, **kwargs): + item = {"at": datetime.now(timezone.utc).isoformat(), "event": event, **kwargs} + with path.open("a", encoding="utf-8") as f: + f.write(json.dumps(item, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + print(json.dumps(item, sort_keys=True), flush=True) + + +def run_kubectl(config, *args): + p = subprocess.run( + ["kubectl", "--kubeconfig", str(config), "-n", NS, *args], + capture_output=True, text=True, timeout=15, check=False, + ) + if p.returncode: + raise RuntimeError("kubectl operation failed; exit=" + str(p.returncode)) + return p.stdout + + +def check_target(config): + """Fail closed unless dedicated kubeconfig targets the local kind demo.""" + p = subprocess.run( + ["kubectl", "--kubeconfig", str(config), "config", "view", "--minify", "-o", "json"], + capture_output=True, text=True, timeout=10, check=True, + ) + data = json.loads(p.stdout) + contexts = data.get("contexts", []) + clusters = data.get("clusters", []) + if len(contexts) != 1 or len(clusters) != 1: + raise RuntimeError("AMBIGUOUS_KUBECONFIG") + ctx = contexts[0]["context"] + cluster = clusters[0]["cluster"] + endpoint = urlsplit(cluster.get("server", "")) + if (ctx.get("namespace", NS) != NS or endpoint.scheme != "https" + or endpoint.hostname not in ("127.0.0.1", "localhost", "::1") + or not endpoint.port or cluster.get("insecure-skip-tls-verify")): + raise RuntimeError("NOT_LOCAL_DEMO_ENDPOINT") + # Independently require the live kind control plane at the SAME address. + p = subprocess.run( + ["kind", "get", "kubeconfig", "--name", "wjax-demo"], + capture_output=True, text=True, timeout=10, check=False, + ) + if p.returncode: + raise RuntimeError("KIND_DEMO_NOT_FOUND") + # kind writes YAML; kubectl can parse it from a temporary file only. + # Instead ask kind for its kubeconfig via an isolated process and kubectl stdin. + # Strict endpoint comparison is also performed against kubectl's kind context. + p = subprocess.run( + ["kubectl", "--context", "kind-wjax-demo", "config", "view", + "--minify", "-o", "json"], + capture_output=True, text=True, timeout=10, check=True, + ) + kind_data = json.loads(p.stdout) + kind_endpoint = kind_data["clusters"][0]["cluster"].get("server") + if kind_endpoint != cluster.get("server"): + raise RuntimeError("DEMO_ENDPOINT_MISMATCH") + + +def observe(config): + obj = json.loads(run_kubectl(config, "get", "deployment", NAME, "-o", "json")) + meta, spec, status = obj["metadata"], obj["spec"], obj.get("status", {}) + images = [c.get("image") for c in spec["template"]["spec"].get("containers", [])] + if (meta.get("name") != NAME or meta.get("namespace") != NS + or not meta.get("uid") or len(images) != 1 or images[0] != IMAGE + or spec.get("selector", {}).get("matchLabels") != {"app": NAME}): + raise RuntimeError("WORKLOAD_IDENTITY_OR_IMAGE_CHANGED") + return { + "uid": meta["uid"], "resourceVersion": meta["resourceVersion"], + "generation": meta["generation"], "observedGeneration": status.get("observedGeneration", 0), + "desired": spec.get("replicas", 1), "ready": status.get("readyReplicas", 0), + "available": status.get("availableReplicas", 0), + } + + +def ask_ollama(): + prompt = ( + "Return ONLY JSON with exactly the keys operation, workload, replicas, target. " + "Allowed values: operation deploy or unknown, workload nginx or unknown, " + "replicas integer or null, target demo or production. " + "The observed local demo Deployment wjax-nginx has 0 desired replicas; " + "trusted demo intent is exactly 2 replicas. Propose the smallest recovery." + ) + req = urllib.request.Request( + "http://127.0.0.1:11434/api/generate", + data=json.dumps({"model": "llama3.2:latest", "prompt": prompt, + "stream": False, "format": "json", + "options": {"temperature": 0}}).encode(), + headers={"Content-Type": "application/json"}, method="POST", + ) + with urllib.request.urlopen(req, timeout=40) as res: + obj = json.load(res) + candidate = json.loads(obj["response"]) + if not isinstance(candidate, dict) or candidate != EXPECTED: + raise RuntimeError("POLICY_DENY_UNEXPECTED_AI_PROPOSAL") + return candidate + + +def verify(config, uid, deadline): + while time.monotonic() < deadline: + state = observe(config) + if state["uid"] != uid: + raise RuntimeError("UID_CHANGED_DURING_VERIFICATION") + if (state["desired"] == state["ready"] == state["available"] == 2 + and state["generation"] == state["observedGeneration"]): + return state + time.sleep(2) + raise RuntimeError("RECOVERY_NOT_READY_WITHIN_TIMEOUT") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--enable-hotl", action="store_true") + ap.add_argument("--once", action="store_true", help="One recovery maximum, then exit") + ap.add_argument("--interval", type=int, default=5) + ap.add_argument("--runtime-dir", required=True) + args = ap.parse_args() + if not args.enable_hotl or os.environ.get("AI_THINKERS_HOTL") != CONSENT: + ap.error("HOTL disabled; require --enable-hotl and explicit AI_THINKERS_HOTL consent") + if not 2 <= args.interval <= 60: + ap.error("--interval must be 2..60 seconds") + home = Path(args.runtime_dir).expanduser().resolve(strict=True) + if home.is_symlink() or home.stat().st_mode & 0o077: + ap.error("runtime directory must be private (0700)") + config = home / ".demo-kubeconfig.json" + if not config.is_file() or config.is_symlink() or config.stat().st_mode & 0o077: + ap.error("dedicated executor kubeconfig missing or unsafe") + check_target(config) + audit = home / "ai-thinkers-evidence.jsonl" + lock = home / "ai-thinkers.lock" + with lock.open("a+") as lockfile: + try: + fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + ap.error("another HOTL supervisor already holds this runtime lock") + record(audit, "HOTL_ENABLED", scope="local-kind/wjax-demo/wjax-nginx", + mode="one-shot" if args.once else "watch") + seen = None + completed = set() + print("AI Thinkers HOTL: watching. Ctrl-C stops future actions.", flush=True) + try: + while True: + try: + state = observe(config) + key = (state["uid"], state["generation"]) + # Require two consecutive observed 0/0 states for the SAME UID+generation. + if state["desired"] == 0 and state["ready"] == 0 and key not in completed: + if seen != key: + seen = key + print("Drift observed; awaiting stable second observation", flush=True) + else: + completed.add(key) # No retries even after errors. + record(audit, "DRIFT_CONFIRMED", uid=state["uid"], + generation=state["generation"]) + candidate = ask_ollama() + record(audit, "AI_PROPOSAL", candidate=candidate, + model="llama3.2:latest") + # Re-read immediately before mutation; reject any concurrent change. + fresh = observe(config) + if (fresh["uid"] != state["uid"] or fresh["generation"] != state["generation"] + or fresh["desired"] != 0 or fresh["ready"] != 0): + raise RuntimeError("STALE_OBSERVATION") + # Atomic test/replace; no create, apply or manifest modifications. + patch = [ + {"op": "test", "path": "/metadata/uid", "value": fresh["uid"]}, + {"op": "test", "path": "/metadata/resourceVersion", + "value": fresh["resourceVersion"]}, + {"op": "test", "path": "/spec/replicas", "value": 0}, + {"op": "replace", "path": "/spec/replicas", "value": 2}, + ] + run_kubectl(config, "patch", "deployment", NAME, "--type=json", + "-p", json.dumps(patch)) + record(audit, "HOTL_EXECUTED", uid=fresh["uid"], + generation=fresh["generation"], action="replicas:0->2") + recovered = verify(config, fresh["uid"], time.monotonic() + 90) + record(audit, "HOTL_RECOVERY_VERIFIED", uid=fresh["uid"], + result="READY_VERIFIED", observed=recovered) + if args.once: + return 0 + else: + seen = None + except Exception as exc: + record(audit, "HOTL_FAILED_CLOSED", reason=str(exc)[:140]) + return 1 # No blind retry after errors. + time.sleep(args.interval) + except KeyboardInterrupt: + record(audit, "HOTL_STOPPED_BY_OPERATOR") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 6dd78c2ba577338b28409a85ea139b56c238e3cf Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 04:51:36 +0100 Subject: [PATCH 02/10] docs(demo): document HOTL opt-in, runbook, fallback and boundaries --- demos/ai-thinkers/README.md | 78 +++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 demos/ai-thinkers/README.md diff --git a/demos/ai-thinkers/README.md b/demos/ai-thinkers/README.md new file mode 100644 index 0000000..d5f7c34 --- /dev/null +++ b/demos/ai-thinkers/README.md @@ -0,0 +1,78 @@ +# OpenKubes AI Thinkers — local HOTL spike + +**Status: experimental / not production safe.** Original W-JAX HITL demo remains unchanged. This is a separate opt-in HOTL supervisor, intentionally scoped to the disposable local kind cluster only. It reuses the **Executor** ServiceAccount from the W-JAX lab; the AI receives no kubeconfig. + +## Scope + +- Trusted intent: existing \`wjax-demo/wjax-nginx\` should have exactly 2 replicas of \`nginx:1.27.5-alpine\`. +- Only action: atomically change \`spec.replicas\` **0 to 2** after two consistent 0/0 observations and an exact Ollama proposal. +- Before patch: verify same UID, generation and resourceVersion, only that name, namespace, image, selector, and local API. +- Fails closed on unexpected output, missing service, concurrent changes or unsuccessful verification. +- Logs HOTL-specific events into \`ai-thinkers-evidence.jsonl\`. This is **not cryptographically authenticated or independently verified evidence**. The read-back verification uses the same executor credentials and process. +- No production namespaces, generic remediation, background agents, or automatic cleanup. HOTL opt-in grants permission for the whole running process; Ctrl-C prevents future actions, but cannot cancel a submitted Kubernetes API request. +- Unlike the original HITL demo, this performs an automated one-shot action; **do not** confuse it with the W-JAX \`make wjax-demo-verify\` mechanism, which requires explicit HUMAN_APPROVED evidence. + +## Before the demo + +Use your **existing** local W-JAX kind lab (do not recreate it). From repo root: + +\`\`\`bash +export DOCKER_CONTEXT=colima +export WJAX_DEMO_RUNTIME_DIR="$PWD/.wjax-local-runtime/recreated-20261125-044033" +kubectl --context kind-wjax-demo -n wjax-demo get deploy wjax-nginx +make wjax-demo-check +make wjax-demo-status +curl -fsS http://127.0.0.1:11434/api/tags >/dev/null +\`\`\` + +**The runtime path above is an example from the 25 November session; use your actual active runtime.** Ensure the existing Deployment is healthy at 2/2. The original browser UI at port 8788 is still the HITL demo; it is *not* the HOTL supervisor UI. + +## Show HOTL in two terminals + +In terminal **A**, run the supervisor with explicit consent (only on local kind): + +\`\`\`bash +export AI_THINKERS_HOTL=I_ACCEPT_LOCAL_KIND_ONLY +python3 demos/ai-thinkers/hotl.py --enable-hotl --once \ + --runtime-dir "$WJAX_DEMO_RUNTIME_DIR" +\`\`\` + +Terminal A waits and observes. In terminal **B** introduce the demo drift: + +\`\`\`bash +kubectl --context kind-wjax-demo -n wjax-demo scale deploy/wjax-nginx --replicas=0 +kubectl --context kind-wjax-demo -n wjax-demo get deploy wjax-nginx +\`\`\` + +Expected terminal A progression: + +\`\`\`text +HOTL_ENABLED +DRIFT_CONFIRMED +AI_PROPOSAL +HOTL_EXECUTED +HOTL_RECOVERY_VERIFIED / READY_VERIFIED +\`\`\` + +Verify with **admin observation** on the disposable lab: + +\`\`\`bash +kubectl --context kind-wjax-demo -n wjax-demo get deploy wjax-nginx +\`\`\` + +The HOTL log is separate from the old HITL log. The original \`make wjax-demo-verify\` is **not** valid for this flow because it intentionally refuses executions without a prior HUMAN_APPROVED event. + +## Safe fallback + +If the HOTL run fails or the Ollama model is slow, stop terminal A with Ctrl-C and return to the already-tested W-JAX HITL demo. Do not modify the stored JSONL evidence to simulate success. Manual admin recovery of the disposable demo is: + +\`\`\`bash +kubectl --context kind-wjax-demo -n wjax-demo scale deploy/wjax-nginx --replicas=2 +kubectl --context kind-wjax-demo -n wjax-demo rollout status deploy/wjax-nginx --timeout=120s +\`\`\` + +Any manual recovery must be disclosed as **manual**, not HOTL evidence. + +## Limitations to address before production + +The implementation has no enterprise identity, tamper-evident audit, independent verifier, trusted GitOps intent, revoke protocol, scoped signed grants, escalation workflow or sophisticated retry budget. The Kubernetes RBAC from the original disposable demo can create deployments namespace-wide; that privilege must be reduced before any production use. Also add unit/integration tests and an isolated E2E test before relying on the HOTL flow in a live presentation. From 92b1e637e48a6ccef0a9e5dd9e25846c4468a411 Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 04:51:42 +0100 Subject: [PATCH 03/10] docs: normalize HOTL runbook Markdown --- demos/ai-thinkers/README.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/demos/ai-thinkers/README.md b/demos/ai-thinkers/README.md index d5f7c34..4e647ad 100644 --- a/demos/ai-thinkers/README.md +++ b/demos/ai-thinkers/README.md @@ -4,26 +4,26 @@ ## Scope -- Trusted intent: existing \`wjax-demo/wjax-nginx\` should have exactly 2 replicas of \`nginx:1.27.5-alpine\`. -- Only action: atomically change \`spec.replicas\` **0 to 2** after two consistent 0/0 observations and an exact Ollama proposal. +- Trusted intent: existing `wjax-demo/wjax-nginx` should have exactly 2 replicas of `nginx:1.27.5-alpine`. +- Only action: atomically change `spec.replicas` **0 to 2** after two consistent 0/0 observations and an exact Ollama proposal. - Before patch: verify same UID, generation and resourceVersion, only that name, namespace, image, selector, and local API. - Fails closed on unexpected output, missing service, concurrent changes or unsuccessful verification. -- Logs HOTL-specific events into \`ai-thinkers-evidence.jsonl\`. This is **not cryptographically authenticated or independently verified evidence**. The read-back verification uses the same executor credentials and process. +- Logs HOTL-specific events into `ai-thinkers-evidence.jsonl`. This is **not cryptographically authenticated or independently verified evidence**. The read-back verification uses the same executor credentials and process. - No production namespaces, generic remediation, background agents, or automatic cleanup. HOTL opt-in grants permission for the whole running process; Ctrl-C prevents future actions, but cannot cancel a submitted Kubernetes API request. -- Unlike the original HITL demo, this performs an automated one-shot action; **do not** confuse it with the W-JAX \`make wjax-demo-verify\` mechanism, which requires explicit HUMAN_APPROVED evidence. +- Unlike the original HITL demo, this performs an automated one-shot action; **do not** confuse it with the W-JAX `make wjax-demo-verify` mechanism, which requires explicit HUMAN_APPROVED evidence. ## Before the demo Use your **existing** local W-JAX kind lab (do not recreate it). From repo root: -\`\`\`bash +```bash export DOCKER_CONTEXT=colima export WJAX_DEMO_RUNTIME_DIR="$PWD/.wjax-local-runtime/recreated-20261125-044033" kubectl --context kind-wjax-demo -n wjax-demo get deploy wjax-nginx make wjax-demo-check make wjax-demo-status curl -fsS http://127.0.0.1:11434/api/tags >/dev/null -\`\`\` +``` **The runtime path above is an example from the 25 November session; use your actual active runtime.** Ensure the existing Deployment is healthy at 2/2. The original browser UI at port 8788 is still the HITL demo; it is *not* the HOTL supervisor UI. @@ -31,45 +31,45 @@ curl -fsS http://127.0.0.1:11434/api/tags >/dev/null In terminal **A**, run the supervisor with explicit consent (only on local kind): -\`\`\`bash +```bash export AI_THINKERS_HOTL=I_ACCEPT_LOCAL_KIND_ONLY python3 demos/ai-thinkers/hotl.py --enable-hotl --once \ --runtime-dir "$WJAX_DEMO_RUNTIME_DIR" -\`\`\` +``` Terminal A waits and observes. In terminal **B** introduce the demo drift: -\`\`\`bash +```bash kubectl --context kind-wjax-demo -n wjax-demo scale deploy/wjax-nginx --replicas=0 kubectl --context kind-wjax-demo -n wjax-demo get deploy wjax-nginx -\`\`\` +``` Expected terminal A progression: -\`\`\`text +```text HOTL_ENABLED DRIFT_CONFIRMED AI_PROPOSAL HOTL_EXECUTED HOTL_RECOVERY_VERIFIED / READY_VERIFIED -\`\`\` +``` Verify with **admin observation** on the disposable lab: -\`\`\`bash +```bash kubectl --context kind-wjax-demo -n wjax-demo get deploy wjax-nginx -\`\`\` +``` -The HOTL log is separate from the old HITL log. The original \`make wjax-demo-verify\` is **not** valid for this flow because it intentionally refuses executions without a prior HUMAN_APPROVED event. +The HOTL log is separate from the old HITL log. The original `make wjax-demo-verify` is **not** valid for this flow because it intentionally refuses executions without a prior HUMAN_APPROVED event. ## Safe fallback If the HOTL run fails or the Ollama model is slow, stop terminal A with Ctrl-C and return to the already-tested W-JAX HITL demo. Do not modify the stored JSONL evidence to simulate success. Manual admin recovery of the disposable demo is: -\`\`\`bash +```bash kubectl --context kind-wjax-demo -n wjax-demo scale deploy/wjax-nginx --replicas=2 kubectl --context kind-wjax-demo -n wjax-demo rollout status deploy/wjax-nginx --timeout=120s -\`\`\` +``` Any manual recovery must be disclosed as **manual**, not HOTL evidence. From 9b5eee0b08a988488b7898d10f44f65e2acaad96 Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 04:52:00 +0100 Subject: [PATCH 04/10] fix(demo): tighten dedicated kubeconfig context and CA guard --- demos/ai-thinkers/hotl.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/demos/ai-thinkers/hotl.py b/demos/ai-thinkers/hotl.py index 8e96739..8e921b3 100644 --- a/demos/ai-thinkers/hotl.py +++ b/demos/ai-thinkers/hotl.py @@ -56,7 +56,8 @@ def check_target(config): ctx = contexts[0]["context"] cluster = clusters[0]["cluster"] endpoint = urlsplit(cluster.get("server", "")) - if (ctx.get("namespace", NS) != NS or endpoint.scheme != "https" + if (contexts[0].get("name") != data.get("current-context") + or ctx.get("namespace", NS) != NS or endpoint.scheme != "https" or endpoint.hostname not in ("127.0.0.1", "localhost", "::1") or not endpoint.port or cluster.get("insecure-skip-tls-verify")): raise RuntimeError("NOT_LOCAL_DEMO_ENDPOINT") @@ -77,8 +78,12 @@ def check_target(config): ) kind_data = json.loads(p.stdout) kind_endpoint = kind_data["clusters"][0]["cluster"].get("server") - if kind_endpoint != cluster.get("server"): - raise RuntimeError("DEMO_ENDPOINT_MISMATCH") + if (kind_data.get("current-context") != "kind-wjax-demo" + or kind_data["clusters"][0].get("name") != "kind-wjax-demo" + or kind_endpoint != cluster.get("server") + or kind_data["clusters"][0]["cluster"].get("certificate-authority-data") + != cluster.get("certificate-authority-data")): + raise RuntimeError("DEMO_ENDPOINT_OR_CA_MISMATCH") def observe(config): From 41f511bba32c4c1794364d7e8f924378fe86cd66 Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 04:55:25 +0100 Subject: [PATCH 05/10] feat(demo): add read-only loopback HOTL timeline dashboard --- demos/ai-thinkers/dashboard.py | 192 +++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 demos/ai-thinkers/dashboard.py diff --git a/demos/ai-thinkers/dashboard.py b/demos/ai-thinkers/dashboard.py new file mode 100644 index 0000000..fe79e13 --- /dev/null +++ b/demos/ai-thinkers/dashboard.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Read-only, loopback-only AI Thinkers HOTL event dashboard (local demo only).""" +import argparse +import json +import os +import stat +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +HTML = r""" + + +OpenKubes AI Thinkers | HOTL +
+
OPENKUBES · LOCAL KIND EXPERIMENT
+

AI Thinkers HOTL

+

Human-on-the-Loop · AI proposes · Policy constrains · Kubernetes recovers · Evidence records

+ +
+
Recorded session mode
—
+
Latest observed result
—
+
Events recorded
0
+
+

Recovery sequence

+
+
01Enable HOTL
+
02Detect drift
+
03AI proposal
+
04Bounded patch
+
05Verify 2/2
+
+

Evidence timeline (newest first)

No events yet
+
Read-only display on 127.0.0.1. No Kubernetes credentials in this browser. JSONL is a local, mutable demo log, not signed evidence. This display cannot enable, pause or stop the supervisor. Use Ctrl-C in its terminal to prevent future actions. Once-only completion is not an ongoing authorization.
+
+""" + +ALLOWED = { + "HOTL_ENABLED", "DRIFT_CONFIRMED", "AI_PROPOSAL", "HOTL_EXECUTED", + "HOTL_RECOVERY_VERIFIED", "HOTL_FAILED_CLOSED", "HOTL_STOPPED_BY_OPERATOR", +} + + +def read_events(audit): + if not audit.exists(): + return [], 0 + if audit.is_symlink() or not audit.is_file() or audit.stat().st_size > 2_000_000: + raise ValueError("AUDIT_FILE_UNSAFE_OR_TOO_LARGE") + parsed = [] + with audit.open(encoding="utf-8") as f: + for line in f: + if not line.strip(): + continue + try: + obj = json.loads(line) + except json.JSONDecodeError: + continue # Partial event while writer flushes. + if isinstance(obj, dict) and obj.get("event") in ALLOWED: + e = {"event": obj["event"], "at": str(obj.get("at", ""))[:40]} + if e["event"] == "HOTL_ENABLED": + e["mode"] = str(obj.get("mode", ""))[:24] + elif e["event"] == "AI_PROPOSAL": + e["model"] = str(obj.get("model", ""))[:48] + elif e["event"] == "HOTL_EXECUTED": + e["action"] = str(obj.get("action", ""))[:40] + elif e["event"] == "HOTL_RECOVERY_VERIFIED": + e["result"] = str(obj.get("result", ""))[:40] + state = obj.get("observed") or {} + if isinstance(state, dict): + for key in ("ready", "desired"): + if type(state.get(key)) is int: + e[key] = state[key] + elif e["event"] == "HOTL_FAILED_CLOSED": + e["reason"] = str(obj.get("reason", ""))[:100] + parsed.append(e) + return parsed[-80:], len(parsed) + + +def serve(runtime, port): + audit = runtime / "ai-thinkers-evidence.jsonl" + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/": + body = HTML.encode("utf-8") + mime = "text/html; charset=utf-8" + status = 200 + elif self.path == "/api/events": + try: + events, total = read_events(audit) + body = json.dumps({"events": events, "total": total}).encode("utf-8") + status = 200 + except (OSError, ValueError): + body = b'{"error":"AUDIT_UNAVAILABLE"}' + status = 503 + mime = "application/json; charset=utf-8" + else: + body = b'{"error":"NOT_FOUND"}' + mime = "application/json; charset=utf-8" + status = 404 + self.send_response(status) + self.send_header("Content-Type", mime) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "no-referrer") + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + self.send_error(405, "Read-only dashboard") + + def log_message(self, format, *args): + return + + print(f"AI Thinkers read-only dashboard: http://127.0.0.1:{port}/", flush=True) + ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--runtime-dir", required=True) + parser.add_argument("--port", type=int, default=8794) + args = parser.parse_args() + if not 1024 <= args.port <= 65535: + parser.error("invalid TCP port") + runtime = Path(args.runtime_dir).expanduser() + if runtime.is_symlink(): + parser.error("runtime symlinks not supported") + runtime = runtime.resolve(strict=True) + if not runtime.is_dir() or stat.S_IMODE(runtime.stat().st_mode) & 0o077: + parser.error("runtime directory must be private") + serve(runtime, args.port) + + +if __name__ == "__main__": + main() From 497cfe50acf38fc591ca53d1582c1a08d730de75 Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 04:55:35 +0100 Subject: [PATCH 06/10] test(demo): exercise HOTL dashboard event redaction and scoped constants --- demos/ai-thinkers/test_hotl.py | 68 ++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 demos/ai-thinkers/test_hotl.py diff --git a/demos/ai-thinkers/test_hotl.py b/demos/ai-thinkers/test_hotl.py new file mode 100644 index 0000000..2968a0a --- /dev/null +++ b/demos/ai-thinkers/test_hotl.py @@ -0,0 +1,68 @@ +"""Non-mutating checks for local HOTL evidence projection and policy defaults.""" +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path + +BASE = Path(__file__).resolve().parent + + +def load(name): + spec = importlib.util.spec_from_file_location(name, BASE / (name + ".py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class DashboardTests(unittest.TestCase): + def setUp(self): + self.dashboard = load("dashboard") + + def test_empty_runtime(self): + with tempfile.TemporaryDirectory() as directory: + self.assertEqual(self.dashboard.read_events(Path(directory) / "missing.jsonl"), ([], 0)) + + def test_projection_excludes_sensitive_fields(self): + with tempfile.TemporaryDirectory() as directory: + file = Path(directory) / "ai-thinkers-evidence.jsonl" + file.write_text( + json.dumps({"at": "2026-11-25T00:00:00Z", "event": "AI_PROPOSAL", + "model": "llama3.2:latest", "token": "SECRET", + "candidate": {"token": "SECRET"}}) + "\n" + + json.dumps({"event": "HOTL_RECOVERY_VERIFIED", + "result": "READY_VERIFIED", + "observed": {"ready": 2, "desired": 2, "uid": "hidden"}}) + "\n" + ) + events, count = self.dashboard.read_events(file) + self.assertEqual(count, 2) + self.assertEqual(events[1]["ready"], 2) + self.assertNotIn("SECRET", json.dumps(events)) + self.assertNotIn("hidden", json.dumps(events)) + + def test_symlink_refused(self): + with tempfile.TemporaryDirectory() as directory: + file = Path(directory) / "evidence.jsonl" + file.write_text("{}\n") + link = Path(directory) / "linked.jsonl" + link.symlink_to(file) + with self.assertRaises(ValueError): + self.dashboard.read_events(link) + + +class SupervisorTests(unittest.TestCase): + def setUp(self): + self.hotl = load("hotl") + + def test_exact_policy_candidate(self): + self.assertEqual(self.hotl.EXPECTED, { + "operation": "deploy", "workload": "nginx", "replicas": 2, "target": "demo" + }) + + def test_trusted_target_pinned(self): + self.assertEqual((self.hotl.NS, self.hotl.NAME, self.hotl.IMAGE), + ("wjax-demo", "wjax-nginx", "nginx:1.27.5-alpine")) + + +if __name__ == "__main__": + unittest.main() From 814cdbebff59346b6f1f9fd1b3ba9eb5f838fdcd Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 04:55:44 +0100 Subject: [PATCH 07/10] docs(demo): add HOTL presentation dashboard and smoke-test instructions --- demos/ai-thinkers/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/demos/ai-thinkers/README.md b/demos/ai-thinkers/README.md index 4e647ad..71275a8 100644 --- a/demos/ai-thinkers/README.md +++ b/demos/ai-thinkers/README.md @@ -76,3 +76,30 @@ Any manual recovery must be disclosed as **manual**, not HOTL evidence. ## Limitations to address before production The implementation has no enterprise identity, tamper-evident audit, independent verifier, trusted GitOps intent, revoke protocol, scoped signed grants, escalation workflow or sophisticated retry budget. The Kubernetes RBAC from the original disposable demo can create deployments namespace-wide; that privilege must be reduced before any production use. Also add unit/integration tests and an isolated E2E test before relying on the HOTL flow in a live presentation. + +## Read-only presentation dashboard (optional) + +From the same repository and with the **same** `WJAX_DEMO_RUNTIME_DIR` as the supervisor, run in a third terminal: + +```bash +python3 demos/ai-thinkers/dashboard.py --runtime-dir "$WJAX_DEMO_RUNTIME_DIR" +``` + +Open **http://127.0.0.1:8794/**. The dashboard polls only the local HOTL JSONL event log, shows a five-step timeline, and does not send Kubernetes API calls or change cluster resources. The displayed mode indicates the **recorded** session mode, not whether a running supervisor is currently authorized. A prior successful run remains visible in the file; this is historical evidence, not real-time liveness. The dashboard never displays the full candidate, UID, or credentials. The current UI cannot pause or stop a supervisor; use Ctrl-C in the supervisor terminal. To do another `--once` run, restart the supervisor explicitly before creating drift. + +### Smoke tests (no Kubernetes writes) + +```bash +python3 -m py_compile demos/ai-thinkers/hotl.py demos/ai-thinkers/dashboard.py +python3 -m unittest discover -s demos/ai-thinkers -p 'test_*.py' -v +``` + +### Live presentation order + +1. Show original W-JAX HITL UI at http://127.0.0.1:8788/ and explain manual approval. +2. Show HOTL dashboard at http://127.0.0.1:8794/. +3. Start the opt-in one-shot supervisor in a terminal. +4. Scale **only** disposable `wjax-demo/wjax-nginx` to zero from a second terminal. +5. Show timeline through `HOTL_RECOVERY_VERIFIED`, then confirm `2/2` with `kubectl --context kind-wjax-demo`. +6. Point out: evidence from the HOTL process is not independently verified and does not imply unattended production safety. + From e8aeca17cd1f4dc32202f74c51a0deeafb88c3b6 Mon Sep 17 00:00:00 2001 From: Arash Date: Wed, 25 Nov 2026 05:02:36 +0100 Subject: [PATCH 08/10] style(demo): align AI Thinkers dashboard with OpenKubes Console light brand tokens --- demos/ai-thinkers/dashboard.py | 74 +++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 18 deletions(-) diff --git a/demos/ai-thinkers/dashboard.py b/demos/ai-thinkers/dashboard.py index fe79e13..3f503ff 100644 --- a/demos/ai-thinkers/dashboard.py +++ b/demos/ai-thinkers/dashboard.py @@ -12,23 +12,61 @@ OpenKubes AI Thinkers | HOTL
OPENKUBES · LOCAL KIND EXPERIMENT

AI Thinkers HOTL

@@ -47,7 +85,7 @@
04Bounded patch
05Verify 2/2
-

Evidence timeline (newest first)

No events yet
+

Evidence timeline (newest first)

No events yet
Read-only display on 127.0.0.1. No Kubernetes credentials in this browser. JSONL is a local, mutable demo log, not signed evidence. This display cannot enable, pause or stop the supervisor. Use Ctrl-C in its terminal to prevent future actions. Once-only completion is not an ongoing authorization.