#!/usr/bin/env bash
# DV-1 §7, the fence: imajev I-1's sandbox form (bwrap; --unshare-net leaves only lo), holding the server AND
# the client in one network-less namespace. The whole filesystem is read-only; /home is a tmpfs with only these
# visible: uv's CPython 3.13.14 (read-only), the estate worktree's bench/ (read-only) with this arm's rows-smoke/, rows/ and receipts/ writable,
# the model's venv and the bench's HF cache (read-only), and a scratch HOME. The laptop's GPU is never reachable:
# CUDA_VISIBLE_DEVICES is empty, the venvs carry CPU-only torch, and /dev is bwrap's minimal one (no /dev/dri,
# no /dev/nvidia*). Phone-home switches: the house list (lev L-2's SWITCHES), plus the runtime's own CPU device.
#   usage: sandbox_deciders.sh <von-cpu|laya-cpu> <command...>
set -euo pipefail
ARM=$1; shift
B=/workshop/bench-archive/plans-2026-10-01/deciders-von-laya
WT=/workshop/estate-worktrees/deciders-von-laya/bench
A=$WT/deciders-von-laya-2026-10-01
case "$ARM" in
  von-cpu|von-cpu-nochains)  VENV=$B/venv-von ;;     # DV-4: the companion uses Von's own venv, its own HOME
  laya-cpu) VENV=$B/venv-laya ;;
  *) echo "unknown arm $ARM" >&2; exit 2 ;;
esac
H=$B/home-$ARM
UVPY=/workshop/.local/share/uv/python          # the venvs' interpreter (CPython 3.13.14, uv-managed), read-only
mkdir -p "$H/tmp" "$A/rows-smoke" "$A/rows" "$A/receipts"
THREADS=${THREADS:-8}
exec bwrap \
  --ro-bind / / \
  --tmpfs /home \
  --ro-bind "$WT" "$WT" \
  --bind "$A/rows-smoke" "$A/rows-smoke" --bind "$A/rows" "$A/rows" --bind "$A/receipts" "$A/receipts" \
  --ro-bind "$VENV" "$VENV" --ro-bind "$B/hf" "$B/hf" --bind "$H" "$H" \
  --ro-bind "$UVPY" "$UVPY" \
  --tmpfs /srv --tmpfs /opt --tmpfs /var --tmpfs /mnt --tmpfs /media --tmpfs /data \
  --dev /dev --proc /proc --tmpfs /tmp --tmpfs /run \
  --unshare-net --unshare-ipc --unshare-pid --unshare-uts \
  --die-with-parent --new-session --clearenv \
  --setenv HOME "$H" --setenv TMPDIR "$H/tmp" \
  --setenv PATH "$VENV/bin:/usr/bin:/bin" --setenv LANG C.UTF-8 \
  --setenv HF_HOME "$B/hf" \
  --setenv ORT_DISABLE_TELEMETRY 1 --setenv HF_HUB_DISABLE_TELEMETRY 1 \
  --setenv HF_HUB_OFFLINE 1 --setenv TRANSFORMERS_OFFLINE 1 \
  --setenv VLLM_NO_USAGE_STATS 1 --setenv GRADIO_ANALYTICS_ENABLED False \
  --setenv CUDA_VISIBLE_DEVICES "" --setenv USE_TF 0 \
  --setenv OMP_NUM_THREADS "$THREADS" --setenv MKL_NUM_THREADS "$THREADS" \
  --setenv TOKENIZERS_PARALLELISM false --setenv PYTHONDONTWRITEBYTECODE 1 \
  --setenv VON_DEVICE cpu \
  --setenv LAYA_DEVICE cpu --setenv LAYA_REVISION reviewed --setenv LAYA_MODELS english,multilingual \
  --setenv LAYA_PRELOAD 1 --setenv LAYA_THREADS "$THREADS" \
  -- "$@"
