#!/usr/bin/env bash
# Thin Linux/macOS convenience wrapper for the kit CLI built into Oakhaven.
# Direct equivalent: Oakhaven [--headless] -- --kit <command> --cwd "$PWD" ...
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Runtime isolation (an internal task): the kit runs its bundled, pinned Python/Node/Postgres, never
# what the caller's environment steers them to. Clear every variable that redirects those runtimes.
unset PYTHONPATH PYTHONHOME PYTHONSTARTUP PYTHONUSERBASE PYTHONINSPECT NODE_OPTIONS NODE_PATH
while IFS= read -r _v; do unset "$_v"; done < <(compgen -e | grep -E '^PG[A-Z_]*$' || true)
kit_os="$(uname -s 2>/dev/null || true)"
# A kit unzipped by hand (unzip, macOS Archive Utility) loses the bundled runtimes' executable bits
# and symlinks: restore them once from KIT_UNIX_MODES.txt (kit/apply_unix_modes.sh, an internal task).
if [[ -f "$here/KIT_UNIX_MODES.txt" && -f "$here/apply_unix_modes.sh" ]]; then
  for _r in python/bin/python3 node/bin/node pgsql/bin/postgres; do
    if [[ -d "$here/${_r%%/*}" && ! -x "$here/$_r" ]]; then sh "$here/apply_unix_modes.sh" || true; break; fi
  done
fi
# macOS: a kit or browser downloaded with a web browser carries com.apple.quarantine, and Gatekeeper
# then refuses its unsigned bundled programs ("cannot be opened because the developer cannot be
# verified"). The person chose to run this kit, so clear the flag on the kit folder (and below on the
# browser app it runs) once. IAMAR_KIT_KEEP_QUARANTINE=1 leaves it alone.
unquarantine() {
  [[ "$kit_os" == Darwin && -z "${IAMAR_KIT_KEEP_QUARANTINE:-}" ]] || return 0
  command -v xattr >/dev/null 2>&1 || return 0
  local p
  for p in "$1" "$1/python/bin/python3" "$1/node/bin/node" "$1/pgsql/bin/postgres"; do
    if [[ -e "$p" ]] && xattr -p com.apple.quarantine "$p" >/dev/null 2>&1; then
      echo "iamar-world: clearing the macOS download quarantine on $1 (unsigned bundled programs; IAMAR_KIT_KEEP_QUARANTINE=1 keeps it)" >&2
      xattr -dr com.apple.quarantine "$1" 2>/dev/null || true
      return 0
    fi
  done
}
unquarantine "$here"
# The kit download bundles Python (with numpy and Pillow) and Blender (an internal task; the supported
# range is kit/requirements/tools.json, the pinned copy is 4.2): every
# command uses them unless PYTHON or BLENDER is set. macOS ships Blender as Blender.app.
if [[ -z "${PYTHON:-}" ]]; then
  # Unix layout python/bin/python3; the Windows kit (run from Git Bash) has python/python.exe (K6 G1).
  for _p in "$here/python/bin/python3" "$here/python/python.exe"; do
    [[ -x "$_p" ]] && { export PYTHON="$_p"; break; }
  done
fi
if [[ -z "${BLENDER:-}" ]]; then
  for _b in "$here/blender/blender" "$here/blender/Blender.app/Contents/MacOS/Blender"; do
    [[ -x "$_b" ]] && { export BLENDER="$_b"; break; }
  done
fi
project="${IAMAR_PROJECT:-$(dirname "$here")}"; browser="${IAMAR_BROWSER:-}"
cmd="${1:-help}"; shift || true
# download-login: a download pass for the invitation-only iamar browser, approved once by the
# person in their web browser (device code); kit/runtime_fetch.sh then uses it.
if [[ "$cmd" == download-login ]]; then exec "$here/download_login.sh" "$@"; fi
# --json (agents): the command prints one JSON object instead of text, with a fix hint on every
# ERROR/WARN and the next command (kit/agent_output/README.md). Commands that print their own JSON
# (doctor, lint, audit, assets search, terrain, ...) take --json themselves. Human-mode runs end
# with a NEXT: line instead (next_hint below; IAMAR_KIT_NO_NEXT=1 turns it off).
# kit_py: the Python 3 the kit's Python tools run on. PYTHON wins; otherwise the first of python3,
# python, py that really runs Python 3, so Windows' python3 "App execution alias" (the Microsoft
# Store stub: "Python was not found", WindowsApps) is skipped like kit/iamar-world.cmd skips it.
kit_py() {
  local c p
  if [[ -n "${PYTHON:-}" ]]; then printf '%s\n' "$PYTHON"; return 0; fi
  for c in python3 python py; do
    p="$(command -v "$c" 2>/dev/null)" || continue
    "$p" -c 'import sys; sys.exit(sys.version_info < (3,))' >/dev/null 2>&1 && { printf '%s\n' "$p"; return 0; }
  done
  return 1
}
agent_py() {
  local p
  p="$(kit_py)" && "$p" -c 'import json' >/dev/null 2>&1 && printf '%s\n' "$p"
}
# requirements / context / api / next (job CG-02, kit/context/README.md): a local agent's instructions,
# the requirements that apply, the world API index and the next step of a world, from the kit itself.
# Python 3 only, no browser needed; each takes --json. runtime (CG-41c) reads the draft's
# <world>/.iamar/runtime.jsonl that play writes (traps, log lines, budget refusals, throttles); state
# (CG-41f) reads <world>/.iamar/state.json that play rewrites every second (quests, entities, budget ledger).
# one activity line for a command that runs a Python tool directly (CG-65: terrain, materials, assets use)
log_activity_only() {
  [[ -z "${IAMAR_KIT_OUTPUT_CHILD:-}" && -z "${IAMAR_KIT_NO_ACTIVITY:-}" ]] || return 0
  local p; p="$(agent_py)" || return 0
  "$p" "$here/agent_output/agent_output.py" activity "$cmd" "$@" 2>/dev/null || true
}
# capabilities (CG-63, kit/capabilities/capabilities.py): what a world can ask for in this kit and browser.
if [[ "$cmd" == capabilities ]]; then
  py="$(kit_py || true)"
  if [[ -z "$py" ]]; then
    for a in "$@"; do [[ "$a" == --json ]] && { printf '{"schema": "iamar-kit-output/1", "command": "capabilities", "exit_code": 2, "ok": false, "errors": [{"message": "--json needs Python 3", "fix": "Install Python 3 or set PYTHON=/path/to/python3 (iamar-world doctor)"}]}\n'; exit 2; }; done
    echo "iamar-world capabilities: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2
  fi
  exec "$py" "$here/capabilities/capabilities.py" "$@"
fi
# rebuild (CG-65, kit/rebuild/rebuild.py): record a world's build (.iamar/source/build.json from the activity log),
# rebuild it from its kept sources into an empty folder and compare every content hash; build runs the agent's
# own build command in the world folder as one logged, replayable step. Python 3 only, no browser needed.
if [[ "$cmd" == rebuild || "$cmd" == build ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world $cmd: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  [[ "$cmd" == build ]] && set -- build "$@"
  exec "$py" "$here/rebuild/rebuild.py" "$@"
fi
if [[ "$cmd" == requirements || "$cmd" == context || "$cmd" == api || "$cmd" == next || "$cmd" == runtime || "$cmd" == state ]]; then
  py="$(kit_py || true)"
  if [[ -z "$py" ]]; then
    for a in "$@"; do [[ "$a" == --json ]] && { printf '{"schema": "iamar-kit-output/1", "command": "%s", "exit_code": 2, "ok": false, "errors": [{"message": "--json needs Python 3", "fix": "Install Python 3 or set PYTHON=/path/to/python3 (iamar-world doctor)"}]}\n' "$cmd"; exit 2; }; done
    echo "iamar-world $cmd: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2
  fi
  exec "$py" "$here/context/context.py" "$cmd" "$@"
fi
# docs / decisions (iamar Live Studio LS-04, kit/context/README.md): version-matched guidance search and a
# per-draft decision log. Python 3 only.
if [[ "$cmd" == docs || "$cmd" == decisions ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world $cmd: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/context/guidance.py" "$cmd" "$@"
fi
# draft (iamar Live Studio LS-01, kit/draft/README.md): revisioned, validated, atomic edits of one draft
# (read, edit, stop, undo, log). Python 3 only.
if [[ "$cmd" == draft ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world draft: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/draft/draft.py" "$@"
fi
# host-leak (iamar Live Studio LS-09a, kit/hostsplit/README.md): finds host-only artifacts (host rules Wasm,
# host.ts and its build outputs) in a visitor package, its piece list's bytes or a visitor cache. Python 3 only.
if [[ "$cmd" == host-leak ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world host-leak: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/hostsplit/host_leak.py" "$@"
fi
# host-publish (iamar Live Studio LS-09b, kit/hostsplit/README.md): host rules to their own folder for the World Host;
# the world folder names them by digest only. --check binds a host rules folder to a world or package. Python 3 only.
if [[ "$cmd" == host-publish ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world host-publish: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/hostsplit/host_publish.py" "$@"
fi
# self-review (job CG-66, kit/review/self_review.py): the builder's own art review on its own shots, with the
# rubric of kit/review/REVIEWER.md; `next` requires it before the independent review of step 9. Python 3 only.
if [[ "$cmd" == self-review ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world self-review: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/review/self_review.py" "$@"
fi
# look (job CG-22, kit/look/README.md): a screenshot of the draft the creator walks in the browser
# (Developer Mode > Play draft), from the current camera, a spawn point or a given place. Python 3 only.
if [[ "$cmd" == look ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world look: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/look/look.py" "$@"
fi
# mcp (job CG-03, kit/mcp/README.md): the kit as a local MCP server (stdio) for one world folder:
# `iamar-world mcp <world>` runs it, `iamar-world mcp --print-config [<world>] [--json]` prints the
# `claude mcp add` / `codex mcp add` lines. Node 20+: the kit's own, else PATH, else the pinned one.
if [[ "$cmd" == mcp ]]; then
  mcp_node="$here/node/bin/node"; [[ -x "$mcp_node" ]] || mcp_node="$(command -v node || true)"
  if [[ -z "$mcp_node" || "$("$mcp_node" -p 'Number(process.versions.node.split(".")[0]) >= 20' 2>/dev/null)" != true ]]; then
    mcp_node="$("$here/runtime_fetch.sh" node 2>/dev/null)" || mcp_node=""
  fi
  [[ -n "$mcp_node" && -x "$mcp_node" ]] || { echo 'iamar-world mcp: needs Node 20 or newer (iamar-world doctor)' >&2; exit 2; }
  exec "$mcp_node" "$here/mcp/server.mjs" "$@"
fi
# asset check (job CG-37a, kit/asset/README.md): one verdict per model (.glb): triangles against the class
# budget, LOD nodes, textures, texel density, draws, closure, hidden and duplicate faces, scale, credit.
# asset fit (job CG-37): LOD0 down to the class budget before baking (Blender: kit/blender/fit_budget.py),
# refused when the silhouette or the closure would break; then the verdict again.
# Python 3 with numpy (the kit's own Python); --json prints one iamar-asset-check/1 (fit: iamar-asset-fit/1) object.
if [[ "$cmd" == asset ]]; then
  case "${1:-}" in
    check) tool=asset_check.py ;;
    fit) tool=asset_fit.py ;;
    *) echo 'usage: iamar-world asset check <model.glb> ... [--class C] [--style P] [--json]
       iamar-world asset fit <model.glb> [--class C] [-o out.glb] [--shot before_after.png] [--json]' >&2; exit 2 ;;
  esac
  sub="$1"; shift
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world asset $sub: needs Python 3 with numpy; set PYTHON (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/asset/$tool" "$@"
fi
next_hint() {
  [[ -z "${IAMAR_KIT_OUTPUT_CHILD:-}" ]] || return 0
  local p; p="$(agent_py)" || return 0
  # activity log: one line in <world>/.iamar/activity.jsonl (agent_output.py; IAMAR_KIT_NO_ACTIVITY=1 turns it off)
  # IAMAR_KIT_ACTIVITY_OUT: the run's own output (preview/perf), so the log keeps the failed TARGET lines
  # that `iamar-world next` reads (a preview failing only worst_frame_ms is not a step-2 blocker; an internal task)
  "$p" "$here/agent_output/agent_output.py" activity "$cmd" "$@" 2>/dev/null || true
  [[ -z "${act_out:-}" ]] || rm -f "$act_out"
  [[ -z "${IAMAR_KIT_NO_NEXT:-}" ]] || return 0
  "$p" "$here/agent_output/agent_output.py" next "$cmd" "$@" 2>/dev/null || true
}
# new --terrain coast|island|lake|river (an internal task): run `new`, then `terrain` on the fresh folder, so an
# island/lake/river brief starts from the right ground, water and spawn, not the beach scaffold's half-plane sea.
if [[ "$cmd" == new && -z "${IAMAR_KIT_NEW_CHAIN:-}" ]]; then
  nt_args=(); nt_kind=""; nt_skip=0
  for a in "$@"; do
    if (( nt_skip )); then nt_kind="$a"; nt_skip=0; continue; fi
    if [[ "$a" == --terrain ]]; then nt_skip=1; else nt_args+=("$a"); fi
  done
  if [[ -n "$nt_kind" ]]; then
    case "$nt_kind" in coast|island|lake|river) ;; *) echo "iamar-world new: --terrain takes coast, island, lake or river" >&2; exit 2;; esac
    IAMAR_KIT_NEW_CHAIN=1 "${BASH:-bash}" "$here/iamar-world" new "${nt_args[@]}" || exit $?
    nt_dir="${nt_args[0]:-}"
    exec "${BASH:-bash}" "$here/iamar-world" terrain "$nt_kind" "$nt_dir"
  fi
fi
# preview and perf need a display (an internal task): on Linux with no display, re-run this launcher once under
# xvfb-run so `iamar-world preview|perf <world> <out>` works as the playbook says. IAMAR_NO_XVFB=1 opts out.
if [[ ( "$cmd" == preview || "$cmd" == perf ) && "$(uname -s)" == Linux && -z "${DISPLAY:-}${WAYLAND_DISPLAY:-}" \
      && -z "${IAMAR_XVFB_WRAPPED:-}" && "${IAMAR_NO_XVFB:-0}" != 1 ]] && command -v xvfb-run >/dev/null 2>&1; then
  export IAMAR_XVFB_WRAPPED=1
  exec xvfb-run -a "${BASH:-bash}" "$here/iamar-world" "$cmd" "$@"
fi
case " new import validate preview perf techniques tiers impostors assets package pack sign verify keygen add-to-browser playtest where compile-typescript " in
  *" $cmd "*)
    want_json=0; for a in "$@"; do [[ "$a" == --json ]] && want_json=1; done
    if [[ -z "${IAMAR_KIT_OUTPUT_CHILD:-}" && $want_json == 1 && ! ( "$cmd" == assets && "${1:-}" == search && "${2:-}" != --worlds ) ]]; then
      p="$(agent_py)" || {
        printf '{"schema": "iamar-kit-output/1", "command": "%s", "exit_code": 2, "ok": false, "errors": [{"message": "--json needs Python 3", "fix": "Install Python 3 or set PYTHON=/path/to/python3 (iamar-world doctor)"}]}\n' "$cmd"
        exit 2
      }
      exec "$p" "$here/agent_output/agent_output.py" run "$cmd" -- "${BASH:-bash}" "$here/iamar-world" "$cmd" "$@"
    fi;;
esac
# compile-typescript: pack world.ts into a world script.
# Default is the fast path: the pure-Node packer writes the compiled JS into
# the prebuilt QuickJS guest (Linux, macOS and Windows; Node >= 20).
# --from-source keeps the old per-world clang guest build (Linux x86_64 only,
# needs the IAMAR_TS_* toolchain variables).
if [[ "$cmd" == compile-typescript ]]; then
  from_source=0
  if [[ "${1:-}" == --from-source ]]; then from_source=1; shift; fi
  [[ $# == 3 ]] || { echo 'usage: iamar-world compile-typescript [--from-source] <world.ts> <template-folder> <fresh-output>' >&2; exit 2; }
  [[ -f "$1" && -d "$2" ]] || { echo 'compile-typescript: source file and package template directory are required' >&2; exit 2; }
  if (( from_source )); then
  [[ "${OSTYPE:-}" == linux* && "${HOSTTYPE:-}" == x86_64 ]] || {
    echo 'compile-typescript --from-source currently requires Linux x86_64' >&2; exit 2;
  }
  [[ -f "$project/tools/typescript-world/build.mjs" && -f "$project/api/typescript/iamar-world.d.ts" ]] || {
    echo 'compile-typescript --from-source needs a source checkout' >&2; exit 2;
  }
  for key in IAMAR_TS_NODE IAMAR_TS_COMPILER IAMAR_TS_QUICKJS IAMAR_TS_WASI_SDK IAMAR_TS_DEPENDENCY_LOCK; do
    value="${!key:-}"
    [[ "$value" == /* ]] || { printf 'compile-typescript: configure %s as an absolute approved local path\n' "$key" >&2; exit 2; }
  done
  [[ -f "$IAMAR_TS_NODE" && -x "$IAMAR_TS_NODE" ]] || { echo 'compile-typescript: configured Node executable is unavailable' >&2; exit 2; }
  [[ -f "$IAMAR_TS_COMPILER" && -f "$IAMAR_TS_DEPENDENCY_LOCK" && -d "$IAMAR_TS_QUICKJS" && -d "$IAMAR_TS_WASI_SDK" ]] || {
    echo 'compile-typescript: configured compiler, dependency lock or toolchain directory is unavailable' >&2; exit 2;
  }
  exec "$IAMAR_TS_NODE" "$project/tools/typescript-world/build.mjs" \
    --source "$1" --sdk "$project/api/typescript/iamar-world.d.ts" \
    --typescript "$IAMAR_TS_COMPILER" --quickjs "$IAMAR_TS_QUICKJS" \
    --wasi-sdk "$IAMAR_TS_WASI_SDK" --dependency-lock "$IAMAR_TS_DEPENDENCY_LOCK" \
    --template "$2" --out "$3"
  fi
  # An explicit compiler override is authoritative, even when empty or invalid.
  # Validate it before probing Node; never silently substitute another compiler.
  tsc=""
  if [[ "${IAMAR_TS_COMPILER+x}" == x ]]; then
    [[ "$IAMAR_TS_COMPILER" == /* && -f "$IAMAR_TS_COMPILER" && -r "$IAMAR_TS_COMPILER" ]] || {
      echo 'compile-typescript: IAMAR_TS_COMPILER must name an absolute readable compiler file' >&2; exit 2;
    }
    tsc="$IAMAR_TS_COMPILER"
  fi
  # A kit packer selects the complete kit set, never a mixture with source.
  # Preserve source-checkout fallback only when no kit packer entry exists.
  # IAMAR_PROJECT retains its existing meaning as the source project path.
  base="$here/ts-world"
  sdk="$base/iamar-world.d.ts"
  if [[ ! -e "$base/pack.mjs" && ! -L "$base/pack.mjs" ]]; then
    base="$project/tools/typescript-world"
    sdk="$project/api/typescript/iamar-world.d.ts"
  fi
  packer="$base/pack.mjs"
  prebuilt="$base/prebuilt/iamar_ts_guest.wasm"
  [[ -f "$packer" && -r "$packer" && -f "$prebuilt" && -r "$prebuilt" && -f "$sdk" && -r "$sdk" ]] || {
    echo 'compile-typescript: selected dependency set is incomplete (packer, prebuilt guest and SDK required)' >&2
    echo '  Use a complete kit/ts-world bundle or a complete source checkout; selected kit files never fall back individually.' >&2
    exit 2
  }
  if [[ -z "$tsc" ]]; then
    for tsc_path in "$base/node_modules/typescript/lib/typescript.js" "$base/typescript.js"; do
      [[ -f "$tsc_path" && -r "$tsc_path" ]] && { tsc="$tsc_path"; break; }
    done
  fi
  if [[ -z "$tsc" ]]; then
    echo 'compile-typescript: the official TypeScript 5.9.3 compiler is required.' >&2
    echo "  npm i typescript@5.9.3 --prefix \"$base\"  (or set IAMAR_TS_COMPILER=/absolute/typescript.js)" >&2
    exit 2
  fi
  # true when node $1 is version 20 or newer (a function, so the selection below stays testable)
  node20() { [[ "$("$1" -p 'Number(process.versions.node.split(".")[0]) >= 20' 2>/dev/null)" == true ]]; }
  # An explicitly set Node override is authoritative, including an empty value.
  # Only an unset override may discover a different executable on PATH.
  if [[ "${IAMAR_TS_NODE+x}" == x ]]; then
    node_bin="$IAMAR_TS_NODE"
  else
    # The kit's bundled Node first (an internal task), else PATH (a source checkout).
    node_bin="$here/node/bin/node"; [[ -x "$node_bin" ]] || node_bin="$(command -v node || true)"
    # No Node 20+ on PATH: the kit's own pinned Node (fetched once, kit/runtime_fetch.sh).
    if [[ -z "$node_bin" ]] || ! node20 "$node_bin"; then
      node_bin="$("$here/runtime_fetch.sh" node)" || node_bin=""
    fi
  fi
  [[ -n "$node_bin" && -x "$node_bin" ]] || { echo 'compile-typescript: Node >= 20 is required (PATH or IAMAR_TS_NODE)' >&2; exit 2; }
  [[ "$("$node_bin" -p 'Number(process.versions.node.split(".")[0]) >= 20')" == true ]] || {
    echo 'compile-typescript: Node >= 20 is required' >&2; exit 2;
  }
  # Not exec: the packer's output is followed by the NEXT: line like every other command.
  # CG-41: through agent_output/ts_compile.mjs, which runs the same packer and on a compile error
  # also writes <out>/BUILD_FAILED.json with one row per error (file, line, column, code, message, fix).
  wrap=(); [[ -f "$here/agent_output/ts_compile.mjs" ]] && wrap=("$here/agent_output/ts_compile.mjs")
  rc=0
  "$node_bin" ${wrap[@]+"${wrap[@]}"} "$packer" \
    --source "$1" --sdk "$sdk" --typescript "$tsc" \
    --prebuilt "$prebuilt" --template "$2" --out "$3" || rc=$?
  next_hint "$rc" "$@"
  exit $rc
fi
# compile-host (GAMEAPI T2b): pack a world's host rules (host.ts) into scripts/host.wasm with the
# kit alone (kit/ts-world host packer, prebuilt host guest, host SDK and spec), or a source checkout
# when no kit packer entry exists (never a mixture). Same compiler and Node selection as compile-typescript.
if [[ "$cmd" == compile-host ]]; then
  [[ $# == 2 ]] || { echo 'usage: iamar-world compile-host <host.ts> <fresh-output>' >&2; exit 2; }
  [[ -f "$1" ]] || { echo 'compile-host: source must name an existing file' >&2; exit 2; }
  tsc=""
  if [[ "${IAMAR_TS_COMPILER+x}" == x ]]; then
    [[ "$IAMAR_TS_COMPILER" == /* && -f "$IAMAR_TS_COMPILER" && -r "$IAMAR_TS_COMPILER" ]] || {
      echo 'compile-host: IAMAR_TS_COMPILER must name an absolute readable compiler file' >&2; exit 2;
    }
    tsc="$IAMAR_TS_COMPILER"
  fi
  base="$here/ts-world"
  sdk="$base/iamar-world-host.d.ts"; spec="$base/world_host_api.json"
  if [[ ! -e "$base/pack_host.mjs" && ! -L "$base/pack_host.mjs" ]]; then
    base="$project/tools/typescript-world"
    sdk="$project/api/typescript/iamar-world-host.d.ts"; spec="$project/api/world_host_api.json"
  fi
  packer="$base/pack_host.mjs"
  prebuilt="$base/prebuilt-host/iamar_ts_host_guest.wasm"
  [[ -f "$packer" && -f "$prebuilt" && -f "$sdk" && -f "$spec" ]] || {
    echo 'compile-host: selected dependency set is incomplete (host packer, prebuilt host guest, host SDK and spec required)' >&2
    echo '  Use a complete kit/ts-world bundle or a complete source checkout.' >&2
    exit 2
  }
  if [[ -z "$tsc" ]]; then
    for tsc_path in "$here/ts-world/node_modules/typescript/lib/typescript.js" "$here/ts-world/typescript.js" "$base/node_modules/typescript/lib/typescript.js" "$base/typescript.js"; do
      [[ -f "$tsc_path" && -r "$tsc_path" ]] && { tsc="$tsc_path"; break; }
    done
  fi
  if [[ -z "$tsc" ]]; then
    echo 'compile-host: the official TypeScript 5.9.3 compiler is required.' >&2
    echo "  npm i typescript@5.9.3 --prefix \"$here/ts-world\"  (or set IAMAR_TS_COMPILER=/absolute/typescript.js)" >&2
    exit 2
  fi
  node20() { [[ "$("$1" -p 'Number(process.versions.node.split(".")[0]) >= 20' 2>/dev/null)" == true ]]; }
  if [[ "${IAMAR_TS_NODE+x}" == x ]]; then
    node_bin="$IAMAR_TS_NODE"
  else
    node_bin="$here/node/bin/node"; [[ -x "$node_bin" ]] || node_bin="$(command -v node || true)"
    if [[ -z "$node_bin" ]] || ! node20 "$node_bin"; then node_bin="$("$here/runtime_fetch.sh" node)" || node_bin=""; fi
  fi
  [[ -n "$node_bin" && -x "$node_bin" ]] && node20 "$node_bin" || { echo 'compile-host: Node >= 20 is required (PATH or IAMAR_TS_NODE)' >&2; exit 2; }
  exec "$node_bin" "$packer" --source "$1" --sdk "$sdk" --spec "$spec" --typescript "$tsc" \
    --prebuilt "$prebuilt" --out "$2"
fi
# test-multi (GAMEAPI T1): a headless multi-client test of a world's host rules against the real
# World Host on a throwaway PostgreSQL (kit/test_multi/README.md). Node >= 20; no browser needed.
if [[ "$cmd" == test-multi ]]; then
  node_ok() { [[ "$("$1" -p 'Number(process.versions.node.split(".")[0]) >= 20' 2>/dev/null)" == true ]]; }
  node_bin="$here/node/bin/node"; [[ -x "$node_bin" ]] || node_bin="$(command -v node || true)"
  if [[ -z "$node_bin" ]] || ! node_ok "$node_bin"; then node_bin="$("$here/runtime_fetch.sh" node)" || node_bin=""; fi
  [[ -n "$node_bin" && -x "$node_bin" ]] || { echo 'test-multi: Node >= 20 is required (PATH)' >&2; exit 2; }
  exec "$node_bin" "$here/test_multi/test_multi.mjs" "$@"
fi
# CG-30 (an internal task): publish/package sign the world folder in place (signature.json). The check commands
# below copy or load it without the generated lods/, so a signed folder fails with "scene.json has changed
# since it was signed" and 34 checklist FAILs. Refuse at once instead; run them before publish.
if [[ "$cmd" == validate || "$cmd" == preview || "$cmd" == perf || "$cmd" == lowtier ]] && [[ "${IAMAR_ALLOW_SIGNED:-0}" != 1 ]]; then
  for a in "$@"; do
    [[ "$a" == -* ]] && continue
    if [[ -d "$a" && -f "$a/signature.json" ]]; then
      echo "ERROR iamar-world $cmd: $a is signed by publish/package (signature.json); checking it now fails with 'has changed since it was signed'." >&2
      echo "  Run validate, preview, perf and lowtier BEFORE publish. To check again after publish, remove signature.json and the manifest \"signer\" (publish and package do it for you), or set IAMAR_ALLOW_SIGNED=1." >&2
      exit 2
    fi
    break
  done
fi
# lint and compare-shots: style-profile checks in Python 3 (kit/lint), no browser needed.
# shots: fixed-camera review sheets (kit/shots/shots.py); Python drives preview through this launcher.
# audit: geometry audits (closure, zfight, roof, edge, door, dark-bake; kit/audit/audit.py), numpy only.
# materials: painted material library, texel-density rule, texture budget (kit/style/materials/materials.py).
# style-gen: masterplan house, convex-wing roof and door arch from a style profile (kit/style/gen/gen.py).
# forest: a wood by iamar city's method (kit/forest/forest.py, capability forest).
if [[ "$cmd" == lint || "$cmd" == compare-shots || "$cmd" == shots || "$cmd" == lowtier || "$cmd" == audit || "$cmd" == version || "$cmd" == doctor || "$cmd" == style-gen || "$cmd" == materials || "$cmd" == terrain || "$cmd" == forest || "$cmd" == road || "$cmd" == ground-shade || "$cmd" == publish-local || "$cmd" == publish ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world $cmd: needs Python 3 (texture and screenshot checks also numpy and Pillow); on Windows install it from python.org (python3 may be only the Microsoft Store stub) or set PYTHON=/path/to/python" >&2; exit 2; }
  tool=style_lint.py; [[ "$cmd" == compare-shots ]] && tool=compare_shots.py; [[ "$cmd" == shots ]] && tool=../shots/shots.py; [[ "$cmd" == lowtier ]] && tool=../shots/lowtier/lowtier.py
  [[ "$cmd" == audit ]] && tool=../audit/audit.py
  [[ "$cmd" == version ]] && tool=../version/version.py
  [[ "$cmd" == doctor ]] && tool=../doctor/doctor.py
  [[ "$cmd" == publish-local ]] && tool=../publish/publish.py
  # publish (CG-21, an internal task): publish-local, then the running browser registers and hosts it
  # (kit/publish/README.md). The old builder-key upload to the hub is gone: the hub hosts no uploads.
  [[ "$cmd" == publish ]] && { tool=../publish/publish.py; set -- --host "$@"; }
  [[ "$cmd" == style-gen ]] && tool=../style/gen/gen.py
  [[ "$cmd" == materials ]] && tool=../style/materials/materials.py
  [[ "$cmd" == terrain ]] && tool=../terrain/terrain.py
  # forest (CG-58a, an internal task): a wood by the city's method into scene.json (kit/forest/forest.py)
  [[ "$cmd" == forest ]] && tool=../forest/forest.py
  # road (CG-58d, an internal task): capability dirt-road, the city's dirt road as one call (kit/tools/road.py)
  [[ "$cmd" == road ]] && tool=../tools/road.py
  # ground-shade (CG-66d, an internal task): contact shade under every model where no sun shadow falls (kit/tools/ground_shade.py)
  [[ "$cmd" == ground-shade ]] && tool=../tools/ground_shade.py
  if [[ "$cmd" == terrain || "$cmd" == forest || "$cmd" == road || "$cmd" == ground-shade || "$cmd" == materials || "$cmd" == lint || "$cmd" == shots || "$cmd" == lowtier || "$cmd" == audit || "$cmd" == compare-shots ]]; then
    # logged in the world's activity (CG-65; lint/shots/lowtier/audit/compare-shots an internal task, so `iamar-world next`
    # sees them): `iamar-world rebuild record` replays them
    rc=0; "$py" "$here/lint/$tool" "$@" || rc=$?
    log_activity_only "$rc" "$@"
    exit $rc
  fi
  exec "$py" "$here/lint/$tool" "$@"
fi
# assets search: the object catalogue (kit/catalog/catalog.py: descriptions, synonyms, categories),
# Python 3 only, no browser needed. assets search --worlds: objects in downloaded worlds (browser).
if [[ "$cmd" == assets && "${1:-}" == search ]]; then
  if [[ "${2:-}" == --worlds ]]; then
    set -- search "${@:3}"
  elif [[ -f "$here/catalog/catalog.json" ]]; then
    py="$(kit_py || true)"
    [[ -n "$py" ]] && exec "$py" "$here/catalog/catalog.py" "$@"
  fi
fi
# assets show <id|name>: an id printed by `assets search` resolves in the same catalogue; anything
# else (a hash or name of a downloaded world's object) falls through to the browser.
if [[ "$cmd" == assets && "${1:-}" == show && -n "${2:-}" && -f "$here/catalog/catalog.json" ]]; then
  py="$(kit_py || true)"
  if [[ -n "$py" ]]; then
    "$py" "$here/catalog/catalog.py" show "$2" && exit 0
  fi
fi
# assets use <world> <id|name>: a catalogue object made for iamar (city models, harbour set, sounds) is
# copied into the world by the catalogue, with its tier files; built-in objects and objects of downloaded
# worlds (catalog.py exit 3) go on to the browser, which references them by hash.
if [[ "$cmd" == assets && "${1:-}" == use && -n "${3:-}" && -f "$here/catalog/catalog.json" ]]; then
  py="$(kit_py || true)"
  if [[ -n "$py" ]]; then
    rc=0; "$py" "$here/catalog/catalog.py" "$@" || rc=$?
    [[ $rc -ne 3 ]] && { log_activity_only "$rc" "$@"; exit $rc; }
  fi
fi
# assets ref <world> <id|name>: reference a public catalogue object by hash instead of carrying it
# (kit/catalog/refs.py, docs/CATALOG_PACKS.md). package/pack: the same module checks every catalogue
# reference and copy (hash, licence, attribution, release) before signing; skipped without Python.
if [[ "$cmd" == assets && "${1:-}" == ref && -f "$here/catalog/refs.py" ]]; then
  py="$(agent_py)" || { echo "assets ref needs Python 3 (set PYTHON=/path/to/python3)" >&2; exit 2; }
  exec "$py" "$here/catalog/refs.py" "$@"
fi
# assets fetch <world>: make the world's catalogue references available here, downloading each release
# pack once into the shared catalogue cache and keeping only objects that hash to their names (kit/catalog/packs.py).
if [[ "$cmd" == assets && "${1:-}" == fetch && -f "$here/catalog/packs.py" ]]; then
  py="$(agent_py)" || { echo "assets fetch needs Python 3 (set PYTHON=/path/to/python3)" >&2; exit 2; }
  exec "$py" "$here/catalog/packs.py" "$@"
fi
# quests (an internal task, an internal task): a creator's quest list (the hub's iamar-hub-quests shape) baked into
# scene.quests, giver by this world's npc names (kit/quests/quests_bake.py, kit/quests/README.md).
if [[ "$cmd" == quests ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world quests: needs Python 3; set PYTHON=/path/to/python3 (iamar-world doctor)" >&2; exit 2; }
  exec "$py" "$here/quests/quests_bake.py" "$@"
fi
# package/pack: a world with a quest source (<world>/.iamar/quests.json, `iamar-world quests source`) bakes its
# quests first; a failed bake stops the package. Worlds without one start no Python here.
if [[ ( "$cmd" == package || "$cmd" == pack ) && -n "${1:-}" && -f "$1/.iamar/quests.json" && -f "$here/quests/quests_bake.py" ]]; then
  py="$(kit_py || true)"
  [[ -n "$py" ]] || { echo "iamar-world $cmd: $1 bakes its quests (.iamar/quests.json), which needs Python 3; set PYTHON=/path/to/python3" >&2; exit 2; }
  rc=0; "$py" "$here/quests/quests_bake.py" bake "$1" || rc=$?
  [[ $rc == 0 ]] || exit $rc
fi
# validate/package/pack (CG-58j, an internal task): refuse a terrain heightmap over the tier's triangle bound
# (kit/terrain/terrain_cap.py); the tier is --tier <t> in the arguments, else low. Skipped without Python.
if [[ "$cmd" == validate || "$cmd" == package || "$cmd" == pack ]] && [[ -n "${1:-}" && -f "$1/scene.json" && -f "$here/terrain/terrain_cap.py" ]]; then
  if py="$(agent_py)"; then
    _ct=low; _prev=""
    for _a in "$@"; do [[ "$_prev" == --tier ]] && _ct="$_a"; _prev="$_a"; done
    [[ "$_ct" == low || "$_ct" == medium || "$_ct" == high ]] || _ct=low
    "$py" "$here/terrain/terrain_cap.py" "$1" --tier "$_ct" || exit 1
  fi
fi
# package/pack write the world's checklist (CG-04) from kit/requirements/requirements.json
[[ "$cmd" == package || "$cmd" == pack ]] && export IAMAR_KIT_DIR="${IAMAR_KIT_DIR:-$here}"
if [[ ( "$cmd" == package || "$cmd" == pack ) && -n "${1:-}" && -f "$1/manifest.json" && -f "$here/catalog/refs.py" ]]; then
  if py="$(agent_py)"; then
    "$py" "$here/catalog/refs.py" check "$1" || exit 1
  fi
fi
# package/pack (CG-66d, an internal task): where the low tier draws no sun shadow, one contact-shade .glb under
# every tree, building and prop (kit/tools/ground_shade.py --auto, a GATE FIXED line); it removes its own
# shade when the sun casts shadows again; manifest "x-ground-shade": false turns it off. Skipped without Python.
if [[ ( "$cmd" == package || "$cmd" == pack ) && -n "${1:-}" && -f "$1/scene.json" && -f "$here/tools/ground_shade.py" ]]; then
  if py="$(agent_py)"; then
    "$py" "$here/tools/ground_shade.py" "$1" --auto || exit 1
  fi
fi
# The developer kit ships its tools as iamar-kit.pck beside this launcher; the browser
# mounts it on demand (KitLoop.ensure_tool). Say where it is, whatever the browser path.
[[ -z "${IAMAR_KIT_PACK:-}" && -f "$here/iamar-kit.pck" ]] && export IAMAR_KIT_PACK="$here/iamar-kit.pck"
if [[ -z "$browser" && ! -f "$project/project.godot" && "$cmd" != blender && "$cmd" != blender-run ]]; then
  # Also the two homepage downloads unzipped side by side: <dir>/kit/ and <dir>/iamar/<browser>.
  # Git Bash on Windows: ../iamar and ../iamar/iamar also match iamar.exe (MSYS adds .exe).
  for c in "$here/../Oakhaven.x86_64" "$here/../Oakhaven.exe" \
      "$here/../iamar.app/Contents/MacOS/Oakhaven" "$here/../Oakhaven.app/Contents/MacOS/Oakhaven" "$here/../iamar" \
      "$here/../iamar.x86_64" "$here/../iamar/iamar" "$here/../iamar/iamar.x86_64" \
      "$here/../iamar/iamar.app/Contents/MacOS/iamar" "$here/../iamar/iamar.app/Contents/MacOS/Oakhaven"; do
    [[ -f "$c" && -x "$c" ]] && { browser="$(cd "$(dirname "$c")" && pwd)/$(basename "$c")"; break; }
  done
  # Developer Mode wrote browser.json beside this launcher: the browser that installed the kit.
  # Used only when the file's path is an executable file; a stale path falls through to the fetch.
  if [[ -z "$browser" && -f "$here/browser.json" ]]; then
    _bj="$(sed -n 's/.*"path"[[:space:]]*:[[:space:]]*"\(.*\)".*/\1/p' "$here/browser.json" | head -n1)"
    _bj="${_bj//\\\\/\\}"; _bj="${_bj//\\\//\/}"
    if [[ -n "$_bj" && -f "$_bj" && -x "$_bj" ]]; then browser="$_bj"; browser_why="browser.json ($here/browser.json)"
    else browser_why="browser.json names $_bj, which is missing or not executable; ignored"; fi
  fi
  # A kit downloaded on its own: use (or fetch once) the pinned iamar browser in kit/runtime/.
  if [[ -z "$browser" && "$cmd" != where ]]; then
    browser="$("$here/runtime_fetch.sh" browser)" || browser=""
  fi
fi
if [[ -z "$browser" && ! -f "$project/project.godot" && "$cmd" != blender && "$cmd" != blender-run ]]; then
  echo "iamar-world: no iamar browser found beside $here (looked in $here/.. and $here/../iamar/)" >&2
  [[ -n "${browser_why:-}" ]] && echo "  $browser_why" >&2
  echo "  Unzip the browser download next to the kit folder (kit/ and iamar/ side by side)," >&2
  echo "  or set IAMAR_BROWSER=/path/to/iamar, or allow" >&2
  echo "  kit/runtime_fetch.sh browser to fetch it (needs the network; IAMAR_KIT_NO_FETCH unset)." >&2
  exit 2
fi
# An older iamar browser has no kit commands: it starts the game and never answers. Ask it once
# (`--kit where` returns at once, status 0, or 3 when the kit pack is missing) and remember the answer
# for that exact file, so a wrong browser ends with a plain message instead of a hang.
check_browser() {
  local b="$1" key stamp pid rc="" i
  key="$(printf '%s' "$b" | cksum | cut -d' ' -f1)-$(stat -c '%s-%Y' "$b" 2>/dev/null || stat -f '%z-%m' "$b" 2>/dev/null)"
  stamp="$here/runtime/.compatible-$key"
  [[ -f "$stamp" ]] && return 0
  local probe; probe="$(mktemp "${TMPDIR:-/tmp}/iamar-probe.XXXXXX")"
  "$b" --headless --audio-driver Dummy -- --kit where >"$probe" 2>&1 & pid=$!
  # Wall-clock time ($SECONDS), not loop turns: Git Bash's `sleep 0.1` takes far longer than 0.1 s, so 250
  # turns were minutes there. And say what is waited on after 5 s, then every 30 s: a creator-sim builder saw
  # no output for 10 min while the browser queued for a render slot and took it for a hang (an internal task).
  # The answer limit (IAMAR_KIT_PROBE_TENTHS, 25 s) counts only from the browser's first output line (the
  # engine prints its banner at once; an old browser prints it, then runs the game and never answers).
  # Before that the browser has not started yet: on a busy computer it queues for a render slot, which
  # took over 5 min (an internal task: the 25 s probe timed out `new` on every such run and the next command
  # queued again), so that wait has its own, longer limit (IAMAR_KIT_PROBE_START_TENTHS, 1 h).
  local start=$SECONDS limit=$(( (${IAMAR_KIT_PROBE_TENTHS:-250} + 9) / 10 )) note=5
  local start_limit=$(( (${IAMAR_KIT_PROBE_START_TENTHS:-36000} + 9) / 10 )) began=""
  while :; do
    kill -0 "$pid" 2>/dev/null || { wait "$pid" && rc=0 || rc=$?; break; }
    if [[ -z "$began" && -s "$probe" ]]; then began=$SECONDS; fi
    if [[ -n "$began" ]]; then (( SECONDS - began < limit )) || break
    else (( SECONDS - start < start_limit )) || break; fi
    if (( SECONDS - start >= note )); then
      if [[ -n "$began" ]]; then
        echo "iamar-world: waiting for the iamar browser at $b to answer its first kit command ($(( SECONDS - began )) s of up to $limit s since it started; it waited $(( began - start )) s to start)" >&2
      else
        echo "iamar-world: waiting for the iamar browser at $b to start ($(( SECONDS - start )) s of up to $start_limit s; it has printed nothing yet: on a busy computer it first waits for a render slot)" >&2
      fi
      note=$(( note + 30 ))
    fi
    sleep 0.1
  done
  local timed_out=0
  if [[ -z "$rc" ]]; then timed_out=1; kill -9 "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true; fi
  # min_browser (signed kit VERSION.json): the oldest browser build this kit runs on untrusted worlds.
  # A browser that reports "BUILD <n>" below it is refused (an internal task); one that reports none is accepted.
  local minb built
  minb="$(sed -n 's/.*"min_browser"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$here/VERSION.json" 2>/dev/null | head -n1)" || minb=""
  built="$(sed -n 's/^BUILD[[:space:]][[:space:]]*\([0-9][0-9]*\).*/\1/p' "$probe" | head -n1)" || built=""
  rm -f "$probe"
  if [[ -n "$minb" && -n "$built" ]] && (( built < minb )); then
    echo "iamar-world: the iamar browser at $b is build $built; this kit needs build $minb or newer (older builds lack security fixes)." >&2
    echo "  Download the latest iamar browser from https://iamar.ai/download or set IAMAR_BROWSER=/path/to/a/newer/iamar." >&2
    exit 2
  fi
  if [[ "$rc" == 0 || "$rc" == 3 ]]; then mkdir -p "$here/runtime" 2>/dev/null && : > "$stamp"; return 0; fi
  if (( timed_out )); then
    if [[ -n "$began" ]]; then
      echo "iamar-world: the iamar browser at $b started but did not answer a kit command within $limit s (TIMED OUT)." >&2
      echo "  It is most likely too old (an old browser starts the game and never answers): download the latest" >&2
      echo "  browser from https://iamar.ai/download. If it is only slow, retry with IAMAR_KIT_PROBE_TENTHS=3000 iamar-world <command>." >&2
    else
      echo "iamar-world: the iamar browser at $b did not start within $start_limit s (TIMED OUT; it printed nothing)." >&2
      echo "  On a busy computer it first waits for a render slot (every command queues, headless ones too): retry later" >&2
      echo "  or with a longer wait, IAMAR_KIT_PROBE_START_TENTHS=72000 (2 h), in the background, and do the Python-only work meanwhile." >&2
      echo "  If it never starts, check that $b runs at all, or download the latest browser from https://iamar.ai/download." >&2
    fi
  else
    echo "iamar-world: the iamar browser at $b cannot run the developer kit commands (it exited with status $rc" >&2
    echo "  instead of answering, so it is too old). Download the latest iamar browser from https://iamar.ai/download, put kit/ beside it," >&2
    echo "  or set IAMAR_BROWSER=/path/to/a/newer/iamar. The kit needs the iamar browser to run its tools." >&2
  fi
  exit 2
}
case "$browser" in *.AppImage) export APPIMAGE_EXTRACT_AND_RUN=1;; esac   # an AppImage browser needs no FUSE
case "$browser" in *.app/Contents/MacOS/*) unquarantine "${browser%%.app/Contents/MacOS/*}.app";; esac
if [[ -n "$browser" && "$cmd" != blender && "$cmd" != blender-run ]]; then check_browser "$browser"; fi
# package/pack/checklist (checklist runs the same gate step; always on in a release kit: IAMAR_PACKAGE_TEXCOMPRESS=0 is honoured only by a development build, so it never
# stops the fetch here; IAMAR_KIT_NO_FETCH=1 does): the exported browser has no BC7 encoder, so the
# texture_compress step hands the encode to a stock Godot 4.7 editor: IAMAR_KIT_GODOT_EDITOR, else
# the kit's pinned one (kit/runtime_fetch.sh godot, 77-86 MB once; an internal task). No editor: the
# textures stay lossless and the step says why.
if [[ -n "$browser" && ( "$cmd" == package || "$cmd" == pack || "$cmd" == checklist ) && -z "${IAMAR_KIT_GODOT_EDITOR:-}" ]]; then
  if ed="$("$here/runtime_fetch.sh" godot)"; then
    case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) ed="$(cygpath -aw "$ed")";; esac
    export IAMAR_KIT_GODOT_EDITOR="$ed"
  else
    echo "iamar-world: no Godot editor to encode BC7 textures (kit/runtime_fetch.sh godot failed); they stay lossless" >&2
  fi
fi
# Blender remains an optional external modeller, not part of the browser. Keep its
# two convenience probes here; all world-kit behavior below is native.
find_blender() {
  local c v pf=() win=()
  # Windows (Git Bash): the Blender installer does not add itself to PATH, so look where it
  # installs, newest version first (kit/iamar-world.cmd and kit/doctor look there too).
  for v in "${ProgramW6432:-}" "${PROGRAMFILES:-}" "${ProgramFiles:-}"; do
    [[ -n "$v" ]] && pf+=("$(cygpath -u "$v" 2>/dev/null || printf '%s' "$v")")
  done
  for v in ${pf[@]+"${pf[@]}"} "/c/Program Files"; do
    [[ -d "$v/Blender Foundation" ]] || continue   # Windows only (and sort -V is not in older macOS sort)
    while IFS= read -r c; do win+=("$c"); done < <(printf '%s\n' "$v/Blender Foundation/Blender "*/blender.exe | sort -rV)
  done
  win+=("/c/Program Files (x86)/Steam/steamapps/common/Blender/blender.exe")
  for c in "${BLENDER:-}" "$(command -v blender 2>/dev/null || true)" "${win[@]}" \
      "$HOME"/opt/blender-*/blender /opt/blender*/blender /usr/bin/blender /snap/bin/blender \
      /Applications/Blender.app/Contents/MacOS/Blender "$HOME"/Applications/Blender.app/Contents/MacOS/Blender; do
    [[ -n "$c" && -x "$c" ]] && { printf '%s\n' "$c"; return; }
  done
  return 1
}
if [[ "$cmd" == blender || "$cmd" == blender-run ]]; then
  # The supported range is written once, in kit/requirements/tools.json (CG-34); doctor checks it.
  bl_text="$(sed -n 's/^ *"text": "\(Blender [^"]*\)".*/\1/p' "$here/requirements/tools.json" 2>/dev/null | head -n 1 || true)"
  b="$(find_blender)" || { echo "NO BLENDER: install ${bl_text:-Blender} from https://www.blender.org/download/ (ask your user first; iamar-world doctor checks the version) or set BLENDER=/path/to/blender" >&2; exit 1; }
  if [[ "$cmd" == blender-run ]]; then exec "$b" -b --factory-startup --python "$@"; fi
  echo "BLENDER $b"
  bl_out="$(mktemp "${TMPDIR:-/tmp}/iamar-blender.XXXXXX")"
  # A cold Blender start on a busy computer can take well over 10 s (an internal task, creator-sim
  # beach-house on Zoe); the limit only guards against a hung Blender.
  bl_secs="${IAMAR_BLENDER_PROBE_SECONDS:-60}"; [[ "$bl_secs" =~ ^[1-9][0-9]*$ ]] || bl_secs=60
  "$b" --version >"$bl_out" 2>&1 & pid=$!
  for (( bl_i = 0; bl_i < bl_secs * 10; bl_i++ )); do
    kill -0 "$pid" 2>/dev/null && { sleep 0.1; continue; }
    wait "$pid"; rc=$?; cat "$bl_out"
    # The same verdict as doctor's blender row (kit/doctor/doctor.py fits): tools.json min is
    # inclusive, below exclusive (an internal task, CG-30 run 8: a 5.2 Blender passed here, doctor flagged it).
    bl_n() { local a b c; IFS=. read -r a b c _ <<<"$1.0.0"; echo $(( 10#${a:-0} * 1000000 + 10#${b:-0} * 1000 + 10#${c:-0} )); }
    bl_tools="$(sed -n '/"blender": {/,/}/p' "$here/requirements/tools.json" 2>/dev/null || true)"
    bl_min="$(sed -n 's/^ *"min": "\([0-9.]*\)".*/\1/p' <<<"$bl_tools" | head -n 1)"
    bl_below="$(sed -n 's/^ *"below": "\([0-9.]*\)".*/\1/p' <<<"$bl_tools" | head -n 1)"
    bl_v="$(grep -oE 'Blender [0-9]+\.[0-9]+(\.[0-9]+)?' "$bl_out" | head -n 1 | cut -d' ' -f2 || true)"
    rm -f -- "$bl_out"
    bl_fix="install ${bl_text:-a supported Blender} (https://www.blender.org/download/) or set BLENDER=/path/to/blender"
    if [[ -z "$bl_v" ]]; then
      echo "BLENDER WARN: $b did not report a Blender version (iamar-world doctor checks it too). Fix: $bl_fix"
    elif [[ -n "$bl_min" ]] && { (( $(bl_n "$bl_v") < $(bl_n "$bl_min") )) || { [[ -n "$bl_below" ]] && (( $(bl_n "$bl_v") >= $(bl_n "$bl_below") )); }; }; then
      echo "BLENDER WARN: Blender $bl_v is outside ${bl_text:-the supported range} (kit/requirements/tools.json; iamar-world doctor reports it too). Fix: $bl_fix"
    elif [[ -n "$bl_min" ]]; then
      echo "BLENDER VERSION OK: Blender $bl_v is inside ${bl_text:-the supported range} (kit/requirements/tools.json)"
    fi
    exit "$rc"
  done
  kill "$pid" 2>/dev/null || true; sleep 0.2; kill -9 "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true
  rm -f -- "$bl_out"
  echo "BLENDER ERROR: Blender --version did not finish within ${bl_secs}s (a hung or very slow Blender). Fix: try again when the computer is less busy, or raise the limit: IAMAR_BLENDER_PROBE_SECONDS=120" >&2; exit 1
fi
# playtest: drive a visitor through a world in the real browser game (talk, pick up, use,
# triggers) and report quest state, script effects and a shot per step (kit/playtest/README.md).
# The browser gets a private profile for the run, so the player's own settings, saves and
# world data are never read or written. --headless skips the shots.
if [[ "$cmd" == playtest ]]; then
  pt="$(mktemp -d "${TMPDIR:-/tmp}/iamar-playtest.XXXXXX")"; trap 'rm -rf -- "$pt"' EXIT
  pt_head=(); pt_args=()
  for a in "$@"; do if [[ "$a" == --headless ]]; then pt_head=(--headless); else pt_args+=("$a"); fi; done
  # IAMAR_HALL_FIRST=0 (an internal task): the classic city start, set before the browser starts. world_playtest.gd
  # sets it too, but in the release browser (iamar 35c67b4cf AppImage) that came too late: the hall-first
  # boot ran anyway and the browser segfaulted ~12 s in (headless exit 139, 127 through the launcher) on
  # every world, before step 1; with it in the launch environment the same run passes.
  pt_env=(env XDG_DATA_HOME="$pt/data" XDG_CONFIG_HOME="$pt/config" OAK_SETTINGS="$pt/settings.cfg" IAMAR_HALL_FIRST=0)
    # Job 10388: say what is missing instead of failing with only a NEXT line.
  if [[ ${#pt_args[@]} -lt 2 || "${pt_args[0]}" == -* || "${pt_args[1]}" == -* ]]; then
    echo "PLAYTEST ERROR: the folders are missing. Fix: iamar-world playtest <world folder> <out folder> [--auto] (the out folder receives playtest.json and the shots)." >&2; next_hint 2 ${pt_args[@]+"${pt_args[@]}"}; exit 2
  fi
  if [[ ${#pt_head[@]} -eq 0 && "$(uname -s)" == Linux && -z "${DISPLAY:-}" && -z "${WAYLAND_DISPLAY:-}" ]]; then
    echo "PLAYTEST ERROR: no display found (DISPLAY and WAYLAND_DISPLAY are empty), and the playtest takes shots. Fix: run it under a virtual display, xvfb-run -a iamar-world playtest <world> <out> --auto, or add --headless to skip the shots." >&2; next_hint 2 ${pt_args[@]+"${pt_args[@]}"}; exit 2
  fi
  : > "$pt/started"
  if [[ -n "$browser" ]]; then
    "${pt_env[@]}" "$browser" --audio-driver Dummy ${pt_head[@]+"${pt_head[@]}"} -- --kit-script res://scripts/kit/world_playtest.gd --cwd "$PWD" ${pt_args[@]+"${pt_args[@]}"}
  else
    "${pt_env[@]}" "${GODOT:-godot}" --audio-driver Dummy ${pt_head[@]+"${pt_head[@]}"} --path "$project" -- --kit-script res://scripts/kit/world_playtest.gd --cwd "$PWD" ${pt_args[@]+"${pt_args[@]}"}
  fi && rc=0 || rc=$?
  # Jobs 9605, 9847 (exit 127 seen on a PASS run): the browser can crash while it quits (exit 139, segfault in its teardown) after the
  # playtest finished and wrote <out>/playtest.json. The result stands: report it, not the crash.
  pt_json=""
  if [[ ${#pt_args[@]} -ge 2 && "${pt_args[0]}" != -* && "${pt_args[1]}" != -* ]]; then pt_json="${pt_args[1]}/playtest.json"; fi
  if (( rc >= 127 )) && [[ -n "$pt_json" && -f "$pt_json" && "$pt_json" -nt "$pt/started" ]]; then
    if grep -qE '^  "ok": true' "$pt_json"; then new_rc=0; else new_rc=1; fi   # (top level only: each step has its own ok)
    echo "NOTE playtest: the browser crashed while quitting (exit $rc) after the playtest wrote $pt_json; that result stands (exit $new_rc). A browser bug, not your world." >&2
    rc=$new_rc
  fi
  next_hint "$rc" ${pt_args[@]+"${pt_args[@]}"}
  exit $rc
fi
# checklist (CG-04): the package gate, then <world>/.iamar/checklist.json (iamar-checklist/1), one item per
# requirement of kit/requirements/requirements.json (scripts/kit/world_checklist.gd). --json prints that
# file (the gate's own lines go to stderr); --verify checks the stored checklist against the content.
if [[ "$cmd" == checklist ]]; then
  export IAMAR_KIT_DIR="${IAMAR_KIT_DIR:-$here}"
  cl_json=0; cl_args=()
  for a in "$@"; do [[ "$a" == --json ]] && cl_json=1 || cl_args+=("$a"); done
  cl_run() {
    if [[ -n "$browser" ]]; then
      "$browser" --headless --audio-driver Dummy -- --kit-script res://scripts/kit/world_checklist.gd --cwd "$PWD" "$@"
    else
      "${GODOT:-godot}" --headless --audio-driver Dummy --path "$project" -- --kit-script res://scripts/kit/world_checklist.gd --cwd "$PWD" "$@"
    fi
  }
  rc=0
  if (( cl_json )); then
    cl_out="$(mktemp "${TMPDIR:-/tmp}/iamar-checklist.XXXXXX")"
    cl_run ${cl_args[@]+"${cl_args[@]}"} --out "$cl_out" >&2 || rc=$?
    if [[ -s "$cl_out" ]]; then cat "$cl_out"
    else printf '{"schema": "iamar-checklist/1", "ok": false, "error": "the checklist did not run (exit %s): read the lines above"}\n' "$rc"; fi
    rm -f "$cl_out"
    exit $rc
  fi
  cl_run ${cl_args[@]+"${cl_args[@]}"} || rc=$?
  next_hint "$rc" ${cl_args[@]+"${cl_args[@]}"}
  exit $rc
fi
# reverify (CG-47a): iamar's verifier re-runs the full gate on an untrusted package, compares it with the
# checklist it carries and writes a signed iamar-verification/1 record (scripts/kit/world_reverify.gd);
# --check-record checks a record's signature. tools/verify_world.sh runs it with a clean environment.
if [[ "$cmd" == reverify ]]; then
  export IAMAR_KIT_DIR="${IAMAR_KIT_DIR:-$here}"
  if [[ -n "$browser" ]]; then
    exec "$browser" --headless --audio-driver Dummy -- --kit-script res://scripts/kit/world_reverify.gd --cwd "$PWD" "$@"
  fi
  exec "${GODOT:-godot}" --headless --audio-driver Dummy --path "$project" -- --kit-script res://scripts/kit/world_reverify.gd --cwd "$PWD" "$@"
fi
# play: walk an unsigned draft in the real browser game at once, offline, reloading on save
# (kit/play/README.md). A separate draft profile kept between runs, never the player's own.
# The person plays it, so it has sound; --headless (tests) and --mute run silent.
if [[ "$cmd" == play ]]; then
  prof="${IAMAR_PLAY_PROFILE:-${XDG_DATA_HOME:-$HOME/.local/share}/iamar-draft-profile}"
  mkdir -p "$prof/data" "$prof/config" "$prof/appdata"
  pl_head=(); pl_args=(); pl_audio=()
  for a in "$@"; do
    case "$a" in --headless) pl_head=(--headless);; --mute) pl_audio=(--audio-driver Dummy);; *) pl_args+=("$a");; esac
  done
  # IAMAR_PLAY_KIT: this launcher, so play can compile a TypeScript draft's world.ts on save (CG-41e)
  pl_env=(env XDG_DATA_HOME="$prof/data" XDG_CONFIG_HOME="$prof/config" APPDATA="$prof/appdata" OAK_SETTINGS="$prof/settings.cfg" IAMAR_PLAY_KIT="$here/iamar-world" IAMAR_HALL_FIRST=0)   # (classic start before launch, as playtest: an internal task)
  # Line-buffer the browser's output: redirected to a file or pipe, stdio holds "PLAY READY" and
  # "PLAY RELOADED" back until the buffer fills or the run ends, so an agent (or the reload test)
  # tailing the log waits for a line that was already true (an internal task).
  command -v stdbuf >/dev/null 2>&1 && pl_env=(stdbuf -oL -eL "${pl_env[@]}")
  next_hint 0 ${pl_args[@]+"${pl_args[@]}"}   # play runs until the person closes it: log that it started
  if [[ -n "$browser" ]]; then
    exec "${pl_env[@]}" "$browser" ${pl_audio[@]+"${pl_audio[@]}"} ${pl_head[@]+"${pl_head[@]}"} -- --kit-script res://scripts/kit/world_play.gd --cwd "$PWD" ${pl_args[@]+"${pl_args[@]}"}
  fi
  exec "${pl_env[@]}" "${GODOT:-godot}" ${pl_audio[@]+"${pl_audio[@]}"} ${pl_head[@]+"${pl_head[@]}"} --path "$project" -- --kit-script res://scripts/kit/world_play.gd --cwd "$PWD" ${pl_args[@]+"${pl_args[@]}"}
fi
# A command queued behind the shared render slot prints nothing for minutes (CG-30 run 3, gap 6: 9 min at
# `validate`). While the browser runs, a background ticker says every IAMAR_KIT_WAIT_NOTE_SECS (default 30 s)
# that the command is still running and may be waiting for a render slot. Silent for quick commands.
slot_note_start() {
  local every="${IAMAR_KIT_WAIT_NOTE_SECS:-30}" label="$1"
  [[ "$every" =~ ^[0-9]+$ ]] && (( every > 0 )) || return 0
  ( t=0; sp=""; trap '[[ -n "$sp" ]] && kill "$sp" 2>/dev/null; exit 0' TERM
    while sleep "$every" & sp=$!; wait "$sp"; do t=$(( t + every ))
      echo "iamar-world: $label still running after $t s (may be waiting for a render slot on a busy computer; not hung)" >&2
    done ) & slot_note_pid=$!
}
slot_note_stop() {
  if [[ -n "${slot_note_pid:-}" ]]; then
    kill "$slot_note_pid" 2>/dev/null || true
    wait "$slot_note_pid" 2>/dev/null || true
    slot_note_pid=""
  fi
  return 0
}
run_native() {
  local headless=(--headless) command="$1"; shift
  case "$command" in preview|perf|impostors) headless=();; esac
  local rc=0
  slot_note_start "$command"
  if [[ -n "$browser" ]]; then
    "$browser" --audio-driver Dummy ${headless[@]+"${headless[@]}"} -- --kit "$command" --cwd "$PWD" "$@" || rc=$?
  else
    "${GODOT:-godot}" --audio-driver Dummy ${headless[@]+"${headless[@]}"} --path "$project" -- --kit "$command" --cwd "$PWD" "$@" || rc=$?
  fi
  slot_note_stop
  return $rc
}
# preview: the renderer sometimes aborts at random (glibc "double free or corruption" /
# "realloc(): invalid old size", exit 134; or a segfault, 139) and the same command then works
# (kit/blindtest/harbour/gaps.md G7). Run it once more in that case; IAMAR_PREVIEW_RETRY=0 turns it off.
if [[ "$cmd" == preview && "${IAMAR_PREVIEW_RETRY:-1}" != 0 ]]; then
  rc=0
  if [[ -n "${IAMAR_KIT_OUTPUT_CHILD:-}" ]]; then
    # --json (an internal task): the agent_output.py parent captures stdout and stderr apart, so the
    # run must not merge them: 2>&1 | tee moved the launcher/browser error onto stdout, where
    # parse() drops it and errors[] fell back to "preview failed with exit code N". No tee here:
    # the parent logs the activity from the parsed result, and next_hint is a no-op in child mode.
    set +e; run_native preview "$@"; rc=$?; set -e
    if [[ $rc == 134 || $rc == 139 ]]; then
      echo "iamar-world: preview crashed (exit $rc), running it once more (known intermittent renderer crash, gaps G7)" >&2
      set +e; run_native preview "$@"; rc=$?; set -e
    fi
  else
    act_out="$(mktemp 2>/dev/null || true)"; export IAMAR_KIT_ACTIVITY_OUT="$act_out"
    set +e; run_native preview "$@" 2>&1 | tee ${act_out:+"$act_out"}; rc=${PIPESTATUS[0]}; set -e
    if [[ $rc == 134 || $rc == 139 ]]; then
      echo "iamar-world: preview crashed (exit $rc), running it once more (known intermittent renderer crash, gaps G7)" >&2
      set +e; run_native preview "$@" 2>&1 | tee ${act_out:+"$act_out"}; rc=${PIPESTATUS[0]}; set -e
    fi
  fi
  next_hint "$rc" "$@"
  exit $rc
fi
headless=(--headless)
case "$cmd" in preview|perf|impostors) headless=();; esac
rc=0
slot_note_start "$cmd"
if [[ "$cmd" == perf ]]; then
  set +e
  if [[ -n "${IAMAR_KIT_OUTPUT_CHILD:-}" ]]; then
    # --json (an internal task): keep stderr apart, as for preview above.
    if [[ -n "$browser" ]]; then
      "$browser" --audio-driver Dummy -- --kit "$cmd" --cwd "$PWD" "$@"
    else
      "${GODOT:-godot}" --audio-driver Dummy --path "$project" -- --kit "$cmd" --cwd "$PWD" "$@"
    fi
    rc=$?
  else
    act_out="$(mktemp 2>/dev/null || true)"; export IAMAR_KIT_ACTIVITY_OUT="$act_out"
    { if [[ -n "$browser" ]]; then
        "$browser" --audio-driver Dummy -- --kit "$cmd" --cwd "$PWD" "$@"
      else
        "${GODOT:-godot}" --audio-driver Dummy --path "$project" -- --kit "$cmd" --cwd "$PWD" "$@"
      fi; } 2>&1 | tee ${act_out:+"$act_out"}
    rc=${PIPESTATUS[0]}
  fi
  set -e
elif [[ -n "$browser" ]]; then
  "$browser" --audio-driver Dummy ${headless[@]+"${headless[@]}"} -- --kit "$cmd" --cwd "$PWD" "$@" || rc=$?
else
  "${GODOT:-godot}" --audio-driver Dummy ${headless[@]+"${headless[@]}"} --path "$project" -- --kit "$cmd" --cwd "$PWD" "$@" || rc=$?
fi
slot_note_stop
next_hint "$rc" "$@"
exit $rc
