Cotton code
716 lines · 30.3 KB · ShellRaw
#!/usr/bin/env bash# Runs the development household — an invented one, in a data folder of its own — and never the owner's real data folder.##   pnpm dev:household up|down|reset|status|seed|pending|approve <pairingId>|--all|install|uninstall|follow <sha>#   pnpm dev:household seed [--size one|small|large|huge|lists] [--seed <n>]#   pnpm dev:household --name member [--port 9791] [--dir ~/CottonDevMember] up|down|reset|seed|status|pending|approve## The owner's household is frozen (DEV MODE, 2026-10-03): development runs# against a second, FRESH household founded by `cotton-headless seed`, served# by `cotton-headless serve` from `$COTTON_DEV_DIR` (default `~/CottonDevHousehold`) on# port 9790 (`COTTON_DEV_PORT`), never the app's 8790, and never through the# relay (`COTTON_TUNNEL_OFF=1`, no `--relay`).## THE REFUSAL COMES FIRST. Every subcommand resolves `$COTTON_DEV_DIR` —# through symlinks and `..`, case-folded because APFS is case-insensitive —# and exits 2 with one sentence if it is the real data folder,# `~/Library/Application Support/CottonDB`, anything under either, or anything# ABOVE either (a `reset` of `$HOME` would wipe the real household with it).# This is the shell-side proof; `cotton-headless seed`'s own refusal is the# second. `reset` additionally wipes only a folder this script made (it holds# `.dev-household`) or a headless data folder (it holds `.cotton-headless.lock`).## The address is not hard-coded. `up` asks Tailscale for this Mac's MagicDNS# name (for a Mac named mac-b: `https://mac-b.<tailnet>.ts.net`) and serves it with# `tailscale serve --bg --https=443`, naming the device `<hostname -s>-dev`# (`mac-b-dev`). If Tailscale is missing or refuses (HTTPS certificates are a# tailnet-admin switch), it falls back to the LAN address# `http://<hostname -s>.local:9790` (for mac-b: `http://mac-b.local:9790`) — which a# phone accepts over http only as one label + `.local`, and which the server# admits only as `<--name>.local`, so the device is then named `<hostname -s>`.## A SECOND HOUSEHOLD — another person's, for the two-people walk — is the same# script with `--name member`: its own folder (`~/CottonDevMember`, or `--dir`),# its own port (9791, or `--port`), a small seed of its own, and the LAN# address only, because `tailscale serve --https=443` is one per machine. The# refusal judges `--dir` as it judges `$COTTON_DEV_DIR`. It has no login agent# and no follow build: `install`, `uninstall` and `follow` are refused for it.## The first household carries TWO databases: the large personal one and a# second, smaller one named `$SECOND_DATABASE` (default `Allotment`), founded# by `cotton-headless add-database` right after the seed, so the owner's phone# shows the switcher with two entries. A phone joins the personal database;# the serve enters it into the second at its next vault pass.## `$DEV_DIR/env` turns on the dev tools (`COTTON_DEV_TOOLS=1`).## `install` writes a LaunchAgent (`~/Library/LaunchAgents/com.cottondb.dev-household.plist`)# that runs `up` at every login and once now, so the household comes back after# a reboot with no session to start it; `uninstall` removes it and leaves the# server as it is. The plist pins the cotton-headless found at install time and# this script's own path, so it does not depend on which checkout is current.# A second agent (`com.cottondb.dev-defects`) keeps `pnpm dev:defects --watch`# running against the same folder, so a screen reported from Cotton Dev becomes# a report folder and a DEFECT line with no session to run the pass.## `follow <sha>` puts the household on the Cotton Dev build that just shipped# (build-main's last step runs it here over ssh, from S's own unpacked# tree). Already on S and answering: nothing.# Else it builds S's cotton-headless under the build lock into# `$COTTON_DEV_FOLLOW_DIR` (default `~/CottonDevHousehold-follow`, never inside# the household, which a reset wipes), compares S's store SCHEMA_VERSION with# the one the running household reports on /health (or the one it last# followed, when it is down): the same → restart on the new binary, data kept;# different or unknown → `reset` (dev data is disposable). Then `install`, so# the LaunchAgent pins the new binary and S's copy of this script.## `approve --all` approves every device `pending` lists — the one command after# a reset, when each joined phone and Mac asks to join again.## Every subcommand ends with one line: `DEV HOUSEHOLD <state> · <address>`.## Exit codes: 0 done, 1 failed, 2 refused (the data folder), 3 cotton-headless# is not built.set -euo pipefailREPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"# A SECOND household beside the first: `--name member [--port 9791] [--dir ~/CottonDevMember]`,# anywhere on the command line. Each option only sets the variable beside it,# so the refusal below judges `--dir` exactly as it judges `COTTON_DEV_DIR`.NAME="${COTTON_DEV_NAME:-}"ARGS=()while (( $# )); do  case "$1" in    --name) NAME="${2:?--name needs a name, such as member}"; shift 2 ;;    --port) COTTON_DEV_PORT="${2:?--port needs a port number}"; shift 2 ;;    --dir) COTTON_DEV_DIR="${2:?--dir needs a folder}"; shift 2 ;;    *) ARGS+=("$1"); shift ;;  esacdoneset -- ${ARGS[@]+"${ARGS[@]}"}if [[ -n "$NAME" && ! "$NAME" =~ ^[a-z][a-z0-9-]{0,23}$ ]]; then  printf '%s\n' "--name is a short lowercase word (letters, digits, hyphens), such as member — not: $NAME" >&2  exit 1fiif [[ -n "${COTTON_DEV_PORT:-}" && ! "$COTTON_DEV_PORT" =~ ^[0-9]{1,5}$ ]]; then  printf '%s\n' "--port is a port number, such as 9791 — not: $COTTON_DEV_PORT" >&2  exit 1fi# A named household's defaults: its own folder (`member` → `~/CottonDevMember`) and the next port.NAMED_DIR=""[[ -n "$NAME" ]] && NAMED_DIR="$HOME/CottonDev$(printf '%s' "${NAME:0:1}" | tr '[:lower:]' '[:upper:]')${NAME:1}"# Not `~/CottonDev`: that is Cotton Dev for Mac's own data folder, and one Mac runs both.DEV_DIR="${COTTON_DEV_DIR:-${NAMED_DIR:-$HOME/CottonDevHousehold}}"# shellcheck source=/dev/null. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/owned-root.sh"if [[ -n "$NAME" ]]; then PORT="${COTTON_DEV_PORT:-9791}"; else PORT="${COTTON_DEV_PORT:-9790}"; fiTAILSCALE="${COTTON_TAILSCALE:-/Applications/Tailscale.app/Contents/MacOS/Tailscale}"BOUND_TIMEOUT_S="${COTTON_DEV_BOUND_TIMEOUT:-60}"LAUNCHCTL="${COTTON_LAUNCHCTL:-/bin/launchctl}"LAUNCH_AGENTS="${COTTON_DEV_LAUNCH_AGENTS:-$HOME/Library/LaunchAgents}"AGENT_LABEL="com.cottondb.dev-household"AGENT_PLIST="$LAUNCH_AGENTS/$AGENT_LABEL.plist"DEFECTS_LABEL="com.cottondb.dev-defects"DEFECTS_PLIST="$LAUNCH_AGENTS/$DEFECTS_LABEL.plist"RUN_DIR="$DEV_DIR/run"PID_FILE="$RUN_DIR/headless.pid"ADDRESS_FILE="$RUN_DIR/address"# Present only while THIS script's `tailscale serve` is the one in force, so# `down` resets a serve config it made and never one somebody else did.SERVE_MARK="$RUN_DIR/tailscale-serve"HOUSEHOLD_MARK="$DEV_DIR/.dev-household"LOG="$DEV_DIR/headless.log"# Outside DEV_DIR on purpose: a reset wipes DEV_DIR, and this holds the build.FOLLOW_DIR="${COTTON_DEV_FOLLOW_DIR:-$HOME/CottonDevHousehold-follow}"# The tree whose commit `follow` installs: this script's own checkout (the CI# step unpacks S and runs S's script). The variable is the tests' seam.SOURCE_ROOT="${COTTON_DEV_SOURCE:-$REPO_ROOT}"SECOND_DATABASE="${COTTON_DEV_SECOND_DATABASE:-Allotment}"HEADLESS=""ANNOUNCE=0FOLLOW_NOTE=""usage() {  sed -n '4,6p' "${BASH_SOURCE[0]}" | sed 's/^#   //'}say() { printf '%s\n' "$*"; }lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }# The physical path `$1` names, whether or not it exists: each component is# followed if it is a symlink (relative targets against its own folder), and a# `..` steps out of what was RESOLVED so far — `realpath -m` semantics, which# macOS's realpath lacks.resolve_path() {  local path="$1" depth="${2:-0}"  if (( depth > 40 )); then printf '%s\n' "$path"; return; fi  [[ "$path" == /* ]] || path="$PWD/$path"  local IFS=/  local -a parts  read -r -a parts <<<"$path"  local cur="" part next target rest i  for (( i = 0; i < ${#parts[@]}; i++ )); do    part="${parts[i]}"    case "$part" in      "" | .) continue ;;      ..) cur="${cur%/*}"; continue ;;    esac    next="$cur/$part"    if [[ -L "$next" ]]; then      target="$(readlink "$next")"      [[ "$target" == /* ]] || target="$cur/$target"      rest="${parts[*]:i+1}"      resolve_path "$target/$rest" $(( depth + 1 ))      return    fi    cur="$next"  done  printf '%s\n' "${cur:-/}"}# Every home the owner's folder could sit under: `$HOME`, and the account's# own home from the user database, so a shell with `HOME` pointed elsewhere# still cannot reach the real one.homes() {  printf '%s\n' "$HOME"  local user  user="$(id -un 2>/dev/null || true)"  if [[ "$user" =~ ^[A-Za-z0-9._-]+$ ]]; then    local account_home    eval "account_home=~$user"    [[ "$account_home" == /* ]] && printf '%s\n' "$account_home"  fi  return 0}refuse_real_household() {  local asked real home folder dir  for dir in "$DEV_DIR" "$FOLLOW_DIR"; do    asked="$(lower "$(resolve_path "$dir")")"    while IFS= read -r home; do      for folder in "CottonDB" "Library/Application Support/CottonDB"; do        real="$(lower "$(resolve_path "$home/$folder")")"        if [[ "$asked" == "$real" || "$asked" == "$real"/* || "$real" == "$asked"/* || "$asked" == "/" ]]; then          say "Refused: $dir is (or holds) the app's own data folder $home/$folder — the development household lives in a folder of its own, such as $HOME/CottonDevHousehold." >&2          exit 2        fi      done    done < <(homes)  done}# A cargo build of this checkout puts the binary under the checkout's own# target directory — a worktree's `.cargo/config.toml` at the repo root# (written by the worktree setup) or `crates/.cargo/config.toml` — else# the classic places. A release binary is preferred: the large seed takes# ten minutes in debug and about one in release.find_headless() {  if [[ -n "${COTTON_HEADLESS:-}" ]]; then    [[ -x "$COTTON_HEADLESS" ]] && { printf '%s\n' "$COTTON_HEADLESS"; return 0; }    return 1  fi  local -a roots=()  local config configured  for config in "$REPO_ROOT/.cargo/config.toml" "$REPO_ROOT/crates/.cargo/config.toml"; do    configured="$(sed -n 's/^target-dir *= *"\(.*\)"/\1/p' "$config" 2>/dev/null | head -1 || true)"    [[ -n "$configured" ]] && roots+=("$configured")  done  [[ -n "${CARGO_TARGET_DIR:-}" ]] && roots+=("$CARGO_TARGET_DIR")  roots+=("$REPO_ROOT/crates/target" "$REPO_ROOT/target")  local root profile  for profile in release debug; do    for root in "${roots[@]}"; do      [[ -x "$root/$profile/cotton-headless" ]] && { printf '%s\n' "$root/$profile/cotton-headless"; return 0; }    done  done  command -v cotton-headless 2>/dev/null && return 0  return 1}need_headless() {  if ! HEADLESS="$(find_headless)"; then    say "cotton-headless is not built — build it with \`nice -n 10 cargo build --release --manifest-path crates/Cargo.toml -p cotton-ffi --bin cotton-headless\` (or point COTTON_HEADLESS at one)." >&2    exit 3  fi}# PORT goes into `env` BEFORE the first serve or seed: headless writes `PORT=0`# (an OS-picked port) only when the file is absent, and the server needs an# admin token of at least 16 characters beside it.ensure_env() {  mkdir -p "$RUN_DIR"  chmod 700 "$DEV_DIR" "$RUN_DIR"  touch "$HOUSEHOLD_MARK"  local env="$DEV_DIR/env"  if [[ ! -f "$env" ]]; then    local token    token="$(od -An -tx1 -N32 /dev/urandom | tr -d ' \n')"    (umask 077 && printf 'PORT=%s\nCOTTON_ADMIN_TOKEN=%s\n' "$PORT" "$token" >"$env")  elif ! grep -qx "PORT=$PORT" "$env"; then    (umask 077 && { grep -v '^PORT=' "$env" || true; printf 'PORT=%s\n' "$PORT"; } >"$env.next")    mv "$env.next" "$env"  fi  # The headless server reads its settings only from this file: the dev tools  # switch is written once, so an edit by hand stays.  grep -q '^COTTON_DEV_TOOLS=' "$env" || printf 'COTTON_DEV_TOOLS=1\n' >>"$env"  chmod 600 "$env"}served_port() {  local configured=""  [[ -f "$DEV_DIR/env" ]] && configured="$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$DEV_DIR/env" | tail -1)"  printf '%s\n' "${configured:-$PORT}"}headless_pid() {  [[ -f "$PID_FILE" ]] || return 1  local pid  pid="$(cat "$PID_FILE")"  [[ "$pid" =~ ^[0-9]+$ ]] || return 1  kill -0 "$pid" 2>/dev/null || return 1  # A recycled pid is somebody else's process.  ps -p "$pid" -o command= 2>/dev/null | grep -q cotton-headless || return 1  printf '%s\n' "$pid"}current_address() {  if [[ -s "$ADDRESS_FILE" ]]; then cat "$ADDRESS_FILE"; else say "not served yet"; fi}# The closing line, on every exit past the refusal and the binary check.announce() {  local code=$?  [[ "$ANNOUNCE" == 1 ]] || exit "$code"  local state=down  headless_pid >/dev/null && state=up  (( code == 0 )) || state="$state, $SUBCOMMAND failed"  say "DEV HOUSEHOLD $state · $(current_address)${FOLLOW_NOTE:+ · $FOLLOW_NOTE}"  exit "$code"}# Runs "$@" for at most `$1` seconds: `tailscale serve` blocks, waiting for a# browser, when HTTPS is not enabled on the tailnet.bounded() {  local seconds="$1"; shift  "$@" </dev/null >>"$LOG" 2>&1 &  local pid=$! waited=0  while kill -0 "$pid" 2>/dev/null; do    if (( waited >= seconds * 2 )); then      kill "$pid" 2>/dev/null || true      wait "$pid" 2>/dev/null || true      return 124    fi    sleep 0.5    waited=$(( waited + 1 ))  done  wait "$pid"}# This Mac's MagicDNS name — empty when Tailscale is missing, not running, or# the tailnet has no HTTPS certificates yet (CertDomains empty): then# `tailscale serve --https` can only fail after its 20-second wait, so `up`# goes straight to the LAN address.tailscale_dns() {  # `tailscale serve --https=443` is one per machine and the first household  # has it: a named household serves its LAN address only.  [[ -z "$NAME" ]] || return 0  [[ -x "$TAILSCALE" ]] || return 0  local json  json="$("$TAILSCALE" status --json 2>/dev/null)" || return 0  if command -v jq >/dev/null; then    printf '%s' "$json" | jq -r 'if ((.CertDomains // []) | length) == 0 then empty else (.Self.DNSName // empty) end' | sed 's/\.$//'  else    printf '%s' "$json" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const j=JSON.parse(s);if(!(j.CertDomains||[]).length)return;console.log(((j.Self||{}).DNSName||"").replace(/\.$/,""))}catch{}})'  fi}start_serve() {  local name="$1"; shift  touch "$LOG"  local offset  offset="$(wc -c <"$LOG" | tr -d ' ')"  printf '\n=== %s serve --name %s %s\n' "$(date -u +%FT%TZ)" "$name" "$*" >>"$LOG"  offset=$(( ${offset:-0} + 1 ))  COTTON_TUNNEL_OFF=1 nohup "$HEADLESS" serve --data-dir "$DEV_DIR" --name "$name" "$@" </dev/null >>"$LOG" 2>&1 &  local pid=$!  disown "$pid" 2>/dev/null || true  printf '%s\n' "$pid" >"$PID_FILE"  # The lane ledger: the household is kept while its server runs.  # Kept while its server runs, released three idle days after (a QA household is the same script on another folder).  bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lane-claim.sh" "$DEV_DIR" --kind household --rule idle_hours:72 --pid "$pid" >&2 || true  bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lane-claim.sh" "$FOLLOW_DIR" --kind household --rule idle_hours:72 >&2 || true  local waited=0 bound  while (( waited < BOUND_TIMEOUT_S * 2 )); do    bound="$(tail -c "+$offset" "$LOG" | sed -n 's/^BOUND \([0-9][0-9]*\)$/\1/p' | head -1)"    if [[ -n "$bound" ]]; then      [[ "$bound" == "$(served_port)" ]] || say "Warning: the server bound $bound, not $(served_port) — check $DEV_DIR/env." >&2      return 0    fi    if ! kill -0 "$pid" 2>/dev/null; then      # It left between the read above and this look: read what it wrote once      # more, or a BOUND printed in that gap is reported as never printed.      bound="$(tail -c "+$offset" "$LOG" | sed -n 's/^BOUND \([0-9][0-9]*\)$/\1/p' | head -1)"      [[ -n "$bound" ]] && return 0      break    fi    sleep 0.5    waited=$(( waited + 1 ))  done  say "cotton-headless serve did not print BOUND within ${BOUND_TIMEOUT_S}s — the end of $LOG:" >&2  tail -n 40 "$LOG" >&2  stop_serve  return 1}stop_serve() {  local pid  if pid="$(headless_pid)"; then    kill -TERM "$pid" 2>/dev/null || true    local waited=0    while kill -0 "$pid" 2>/dev/null && (( waited < 20 )); do      sleep 0.5      waited=$(( waited + 1 ))    done    kill -0 "$pid" 2>/dev/null && kill -KILL "$pid" 2>/dev/null || true  fi  rm -f "$PID_FILE"}cmd_up() {  need_headless  ensure_env  if headless_pid >/dev/null; then    say "Already serving $DEV_DIR (pid $(cat "$PID_FILE"))."    return 0  fi  if [[ ! -f "$DEV_DIR/registry.db" ]]; then    say "$DEV_DIR holds no household yet — run \`pnpm dev:seed\` (or \`pnpm dev:household reset\`) first." >&2    return 1  fi  local short dns address  short="$(hostname -s)"  dns="$(tailscale_dns || true)"  if [[ -n "$dns" ]]; then    address="https://$dns"    start_serve "$short-dev" --address "$address"    if bounded 20 "$TAILSCALE" serve --bg --https=443 "http://127.0.0.1:$(served_port)"; then      touch "$SERVE_MARK"    else      say "Tailscale would not serve https://$dns (HTTPS certificates may need enabling in the tailnet admin) — falling back to the LAN address." >&2      stop_serve      dns=""    fi  else    [[ -n "$NAME" ]] || say "Tailscale has no MagicDNS name or no HTTPS certificates for this tailnet (enable Serve/HTTPS in the tailnet admin) — serving the LAN address instead." >&2  fi  if [[ -z "$dns" ]]; then    address="http://$short.local:$(served_port)"    start_serve "$short"  fi  printf '%s\n' "$address" >"$ADDRESS_FILE"}cmd_down() {  stop_serve  if [[ -f "$SERVE_MARK" ]]; then    bounded 20 "$TAILSCALE" serve --https=443 off || say "tailscale serve --https=443 off failed — run \`$TAILSCALE serve --https=443 off\` by hand." >&2    rm -f "$SERVE_MARK"  fi}cmd_seed() {  local size="${COTTON_DEV_SIZE:-large}" seed="${COTTON_DEV_SEED:-1}"  # A named household is another person's: small, and from another seed, so  # its invented records are not the first household's.  [[ -z "$NAME" ]] || { size="${COTTON_DEV_SIZE:-small}"; seed="${COTTON_DEV_SEED:-2}"; }  while (( $# )); do    case "$1" in      --size) size="${2:?--size needs one, small, large or huge}"; shift 2 ;;      --seed) seed="${2:?--seed needs a whole number}"; shift 2 ;;      *) say "unknown seed argument: $1" >&2; return 1 ;;    esac  done  need_headless  ensure_env  "$HEADLESS" seed --data-dir "$DEV_DIR" --size "$size" --seed "$seed" --name "$(hostname -s)-${NAME:-dev}"  # TWO DATABASES (owner's ask, 5 Oct 2026): the first household carries a  # second, smaller database beside the personal one, so a phone that joins  # shows the switcher with something to switch to. `add-database` copies the  # owner's approved devices in at creation, and the serve enters each phone  # approved later at its next vault pass (within five minutes of the join).  # A named household is another person's and stays one database.  [[ -n "$NAME" ]] || "$HEADLESS" add-database --data-dir "$DEV_DIR" --database "$SECOND_DATABASE" --size small --seed $(( seed + 1 )) --name "$(hostname -s)-dev"}cmd_reset() {  need_headless  if [[ -d "$DEV_DIR" && -n "$(ls -A "$DEV_DIR")" && ! -e "$HOUSEHOLD_MARK" && ! -e "$DEV_DIR/.cotton-headless.lock" ]]; then    say "Refused: $DEV_DIR is not a development household this script or cotton-headless made — empty it or pick another COTTON_DEV_DIR." >&2    exit 2  fi  cmd_down  refuse_real_household  rm -rf "$DEV_DIR"  cmd_seed "$@"  cmd_up}cmd_status() {  need_headless  if [[ -d "$DEV_DIR" ]]; then    "$HEADLESS" status --data-dir "$DEV_DIR" || true  else    say "$DEV_DIR does not exist yet — \`pnpm dev:household reset\` founds it."  fi  local port  port="$(served_port)"  if curl -fsS --max-time 5 "http://127.0.0.1:$port/health"; then    echo  else    say "health: nothing answered on 127.0.0.1:$port"  fi  if [[ -f "$SERVE_MARK" && -x "$TAILSCALE" ]]; then    bounded 10 "$TAILSCALE" serve status || true  fi}# The LaunchAgent runs `up` at login and once at install: `up` is idempotent# (a running server is left alone), so a re-install or a second login costs# nothing. No KeepAlive — `up` exits once the server is detached, and a server# that dies comes back at the next login or `up`, never in a restart loop.# launchd starts with a bare PATH, so the plist names one that reaches node# and jq (the tailscale_dns readers). Paths are written as they are: a `$HOME`# with `&` or `<` in it would need escaping, and no Mac here has one.cmd_install() {  mkdir -p "$LAUNCH_AGENTS" "$RUN_DIR"  local script="$REPO_ROOT/scripts/dev-household.sh"  cat >"$AGENT_PLIST" <<EOF<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>  <key>Label</key><string>$AGENT_LABEL</string>  <key>ProgramArguments</key>  <array><string>/bin/bash</string><string>$script</string><string>up</string></array>  <key>RunAtLoad</key><true/>  <key>AbandonProcessGroup</key><true/>  <key>EnvironmentVariables</key>  <dict>    <key>PATH</key><string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>    <key>HOME</key><string>$HOME</string>    <key>COTTON_DEV_DIR</key><string>$DEV_DIR</string>    <key>COTTON_DEV_PORT</key><string>$PORT</string>    <key>COTTON_HEADLESS</key><string>$HEADLESS</string>    <key>COTTON_TAILSCALE</key><string>$TAILSCALE</string>  </dict>  <key>StandardOutPath</key><string>$RUN_DIR/launchd.log</string>  <key>StandardErrorPath</key><string>$RUN_DIR/launchd.log</string></dict></plist>EOF  "$LAUNCHCTL" bootout "gui/$(id -u)/$AGENT_LABEL" >/dev/null 2>&1 || true  "$LAUNCHCTL" bootstrap "gui/$(id -u)" "$AGENT_PLIST"  say "Installed $AGENT_PLIST — \`up\` runs at every login, and is running now (log: $RUN_DIR/launchd.log)."  install_defects_watcher}# The watcher is KeptAlive: dev-defects.ts is a loop that should never end, and# launchd restarts it (30 s apart at the fastest) if node or the folder# disappears for a moment. node is pinned where it is NOW — a version manager# may keep it off launchd's PATH — and tsx is the checkout's own.install_defects_watcher() {  local node tsx  node="$(command -v node || true)"  tsx="$REPO_ROOT/node_modules/.bin/tsx"  if [[ -z "$node" || ! -x "$tsx" ]]; then    say "dev-defects watcher not installed: needs node on PATH and $tsx (run pnpm install) — the server agent is installed." >&2    return 0  fi  cat >"$DEFECTS_PLIST" <<EOF<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>  <key>Label</key><string>$DEFECTS_LABEL</string>  <key>ProgramArguments</key>  <array><string>$node</string><string>$tsx</string><string>$REPO_ROOT/scripts/dev-defects.ts</string><string>--watch</string><string>--data-dir</string><string>$DEV_DIR</string></array>  <key>RunAtLoad</key><true/>  <key>KeepAlive</key><true/>  <key>ThrottleInterval</key><integer>30</integer>  <key>WorkingDirectory</key><string>$REPO_ROOT</string>  <key>EnvironmentVariables</key>  <dict>    <key>PATH</key><string>$(dirname "$node"):/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>    <key>HOME</key><string>$HOME</string>  </dict>  <key>StandardOutPath</key><string>$RUN_DIR/defects.log</string>  <key>StandardErrorPath</key><string>$RUN_DIR/defects.log</string></dict></plist>EOF  "$LAUNCHCTL" bootout "gui/$(id -u)/$DEFECTS_LABEL" >/dev/null 2>&1 || true  "$LAUNCHCTL" bootstrap "gui/$(id -u)" "$DEFECTS_PLIST"  say "Installed $DEFECTS_PLIST — \`pnpm dev:defects --watch\` runs on $DEV_DIR (log: $RUN_DIR/defects.log)."}cmd_uninstall() {  "$LAUNCHCTL" bootout "gui/$(id -u)/$DEFECTS_LABEL" >/dev/null 2>&1 || true  rm -f "$DEFECTS_PLIST"  "$LAUNCHCTL" bootout "gui/$(id -u)/$AGENT_LABEL" >/dev/null 2>&1 || true  rm -f "$AGENT_PLIST"  say "Removed $AGENT_PLIST and $DEFECTS_PLIST — the household stays as it is now; \`down\` stops it."}# The store SCHEMA_VERSION the tree being followed was written for.source_schema() {  sed -n 's/^pub const SCHEMA_VERSION: u32 = \([0-9][0-9]*\);.*/\1/p' "$SOURCE_ROOT/crates/cotton-store/src/schema/ddl.rs" 2>/dev/null | head -1}# The schema the household is serving now, from its own /health; empty when# nothing answers.running_schema() {  local body  body="$(curl -fsS --max-time 5 "http://127.0.0.1:$(served_port)/health" 2>/dev/null)" || return 0  printf '%s' "$body" | sed -n 's/.*"schemaVersion"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -1}# S's cotton-headless, release, built under the machine-wide build lock into a# target directory that outlives every tree (so only what changed recompiles),# then copied out beside the others: the agent pins the copy, never a path the# next build overwrites. cargo runs from `crates/` so its rust-toolchain.toml# picks the compiler. Class `ci`: it is the shipping lane's last step, and a# `local` waiter yields to every CI claim on a busy Mac until it times out.build_for_follow() {  local sha="$1" bin="$2" log="$FOLLOW_DIR/build.log"  command -v cargo >/dev/null || PATH="$HOME/.cargo/bin:$PATH"  say "Building cotton-headless at ${sha:0:9} (log: $log)."  if ! ( cd "$SOURCE_ROOT/crates" \    && BUILD_LOCK_LABEL="dev-household-follow" BUILD_LOCK_CLASS="${BUILD_LOCK_CLASS:-ci}" BUILD_LOCK_TIMEOUT_MIN="${BUILD_LOCK_TIMEOUT_MIN:-60}" CARGO_TARGET_DIR="$FOLLOW_DIR/target" \      bash "$SOURCE_ROOT/scripts/with-build-lock.sh" cargo build --release -p cotton-ffi --bin cotton-headless ) >"$log" 2>&1; then    say "The cotton-headless build at ${sha:0:9} failed — the end of $log:" >&2    tail -n 30 "$log" >&2    return 1  fi  cp "$FOLLOW_DIR/target/release/cotton-headless" "$bin.next"  mv "$bin.next" "$bin"}cmd_follow() {  local sha="${1:-}"  if [[ ! "$sha" =~ ^[0-9a-f]{7,40}$ ]]; then    say "follow needs the commit sha of the Cotton Dev build that shipped." >&2    return 1  fi  mkdir -p "$FOLLOW_DIR/bin"  local followed="" recorded="" running want  [[ -f "$FOLLOW_DIR/sha" ]] && followed="$(cat "$FOLLOW_DIR/sha")"  [[ -f "$FOLLOW_DIR/schema" ]] && recorded="$(cat "$FOLLOW_DIR/schema")"  running="$(running_schema)"  if [[ "$followed" == "$sha" && -n "$running" ]]; then    FOLLOW_NOTE="already on ${sha:0:9}, schema $running"    return 0  fi  want="$(source_schema)"  if [[ -z "$want" ]]; then    say "follow cannot read SCHEMA_VERSION from $SOURCE_ROOT/crates/cotton-store/src/schema/ddl.rs — is that the tree for ${sha:0:9}?" >&2    return 1  fi  # NEVER BACKWARDS. The shipping lane follows builds in the order they  # finish, not the order they landed: a run queued behind a schema step  # arrives later with the OLDER schema, and following it would reset the  # household onto data the phones on the new schema cannot read (4 Oct 2026:  # ten queued runs reset 9790 to 61 twice under a walk on 62). An older  # schema than the one serving is refused here and the household kept.  local serving="${running:-$recorded}"  if [[ -n "$serving" && "$want" -lt "$serving" ]]; then    FOLLOW_NOTE="kept on schema $serving — ${sha:0:9} reads $want, older than what serves; follow a later build"    say "$FOLLOW_NOTE"    return 0  fi  local bin="$FOLLOW_DIR/bin/cotton-headless-$sha"  [[ -x "$bin" ]] || build_for_follow "$sha" "$bin"  export COTTON_HEADLESS="$bin"  HEADLESS="$bin"  # Down, the household cannot say its schema: the one it last followed stands in.  local now="${running:-$recorded}"  if [[ -n "$now" && "$now" == "$want" && -f "$DEV_DIR/registry.db" ]]; then    cmd_down    cmd_up    FOLLOW_NOTE="restarted on ${sha:0:9}, schema $want, data kept"  else    cmd_reset    FOLLOW_NOTE="reset + reseeded on ${sha:0:9}: schema ${now:-unknown} → $want (joined devices must join again)"  fi  printf '%s\n' "$sha" >"$FOLLOW_DIR/sha"  printf '%s\n' "$want" >"$FOLLOW_DIR/schema"  cmd_install  # Only S's binary and S's tree are kept; the agent now pins both.  local old  for old in "$FOLLOW_DIR"/bin/cotton-headless-*; do    [[ "$old" == "$bin" || ! -e "$old" ]] || rm -f "$old"  done  if [[ -d "$FOLLOW_DIR/src" ]]; then    for old in "$FOLLOW_DIR"/src/*; do      [[ "$(basename "$old")" == "$sha" || ! -e "$old" ]] || rm -rf "$old"    done  fi}# Every device waiting to join, approved — the household is a development one,# and after a reset every joined phone and Mac asks again.approve_all() {  local ids id count=0  ids="$("$HEADLESS" pending --data-dir "$DEV_DIR" | sed -n 's/^\([A-Za-z0-9_-][A-Za-z0-9_-]*\)  .*digits .*/\1/p')"  for id in $ids; do    "$HEADLESS" approve "$id" --data-dir "$DEV_DIR"    count=$(( count + 1 ))  done  say "Approved $count waiting device(s)."}SUBCOMMAND="${1:-help}"[[ $# -gt 0 ]] && shiftcase "$SUBCOMMAND" in  help | -h | --help) usage; exit 0 ;;  up | down | reset | status | seed | pending | approve | install | uninstall | follow) ;;  *) say "unknown subcommand: $SUBCOMMAND" >&2; usage >&2; exit 1 ;;esacrefuse_real_household# After the app's own folder, so that refusal keeps its own sentence: neither# folder is a home folder or anything above one — `reset` removes the first# whole and `follow` prunes the second.refuse_wide_root "the development household (--dir / COTTON_DEV_DIR)" "$DEV_DIR"refuse_wide_root "the follow folder (COTTON_DEV_FOLLOW_DIR)" "$FOLLOW_DIR"# The login agent and the follow build belong to the first household alone: a# named one is started by hand, for the walk that needs it.if [[ -n "$NAME" ]]; then  case "$SUBCOMMAND" in    install | uninstall | follow)      say "Refused: $SUBCOMMAND is the first household's — the $NAME household is run by hand (up, down, reset, seed, status, pending, approve)." >&2      exit 1      ;;  esacfi# `follow` builds its own binary; the others need one built already.case "$SUBCOMMAND" in down | uninstall | follow) ;; *) need_headless ;; esacANNOUNCE=1trap announce EXITcase "$SUBCOMMAND" in  up) cmd_up ;;  down) cmd_down ;;  reset) cmd_reset "$@" ;;  status) cmd_status ;;  install) cmd_install ;;  uninstall) cmd_uninstall ;;  seed) cmd_seed "$@" ;;  pending) "$HEADLESS" pending --data-dir "$DEV_DIR" ;;  follow) cmd_follow "$@" ;;  approve)    [[ -n "${1:-}" ]] || { say "approve needs the pairing id \`pending\` printed, or --all." >&2; exit 1; }    if [[ "$1" == --all ]]; then approve_all; else "$HEADLESS" approve "$1" --data-dir "$DEV_DIR"; fi    ;;esac