#!/bin/sh
# bostrat node boot: first-boot volume layout, then hand off to the CLI.
# Everything under $HOME sits on the Fly volume (see node.Dockerfile).
set -e
mkdir -p "$HOME/repos"
# Boxes commit as they work; give git an identity on first boot only — the
# operator can overwrite it (it persists in $HOME/.gitconfig on the volume).
git config --global user.name >/dev/null 2>&1 || git config --global user.name "bostrat node"
git config --global user.email >/dev/null 2>&1 || git config --global user.email "node@bostrat.ai"
# The agent drives boxes on a host tmux server (the Pi's globo-tmux.service
# equivalent): keep one alive with a detached keeper session.
SOCKET="${BOSTRAT_TMUX_SOCKET:-/tmp/tmux-0/default}"
mkdir -p "$(dirname "$SOCKET")"
tmux -S "$SOCKET" has-session 2>/dev/null || tmux -S "$SOCKET" new-session -d -s keeper "sleep infinity"
# The server is a daemon beside the agent, not its child: when `bostrat-node
# run` relaunches a stalled agent (BP-NG-R2 — heartbeat.json stale 3 min →
# SIGTERM/SIGKILL → respawn, node-cli.js createRunSupervisor), every box keeps
# running here and the lead resumes by session id on the next drive.
# In-VM OOM guard (BP-NG-R4 / D4): memory exhaustion inside the guest must
# kill the offending process, never the machine or the agent. The Fly init
# runs no systemd, so this is the Pi's earlyoom backstop started by hand with
# the Pi's tuning (ugrep-memory-lock-2026-07-17): act at 10% available memory
# / 70% swap free (no swap → only the memory leg counts), and print a memory
# report every 10 min to the machine log (the 09-22 flight recorder).
# earlyoom matches --prefer/--avoid against the KERNEL process name (comm,
# 15 chars) — not the command line. Node ≥ 24 names its main thread
# "MainThread", so a bare node process is "MainThread", never "node"; the CLI
# and the agent set their own titles (bostrat-node / bostrat-agent, node-cli.js
# runAgent + index.js) so the avoid list actually matches them. Claude's
# bundled helpers take their version string as comm (the 2.1.x pattern).
# Relaunched if it ever exits — a guard that silently died is no guard.
if command -v earlyoom >/dev/null 2>&1; then
  (
    while :; do
      earlyoom -m 10 -s 70 -r 600 \
        --prefer '^(ugrep|rg|2\.1\.[0-9]+|cursor-agent|codex|npm|node|MainThread)' \
        --avoid '^(bostrat-|tmux|earlyoom)' \
        2>&1 | sed -u 's/^/[earlyoom] /'
      sleep 5
    done
  ) &
fi
# Global-install layout (the GHCR image / npm -g) has bostrat-node on PATH;
# staged repo-context builds (`bostrat-node fly` wizard) run the tree copy.
# Both exec `run` — the foreground SUPERVISOR (self-update restarts + the stall
# watchdog), so this script needs no loop of its own; if the supervisor itself
# dies the machine's restart policy (always) brings the whole node back.
if command -v bostrat-node >/dev/null 2>&1; then
  exec bostrat-node run
else
  exec node /app/agent/bin/bostrat-node.js run
fi
