Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
62.5 KB
Raw Blame
#!/usr/bin/env bash
# Registry-level behaviour of scripts/dev-env.sh, with no services started.
#
# Everything here runs against a throwaway MULTICA_DEV_HOME holding hand-written
# manifests, so the verbs are exercised end to end without a database, a
# backend, or a port.
set -euo pipefail

root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT

export MULTICA_DEV_HOME="$tmp_dir/dev"
export MULTICA_DEV_WORKSPACES_PARENT="$tmp_dir/workspaces-parent"
export MULTICA_DEV_DESKTOP_APP_DATA="$tmp_dir/app-data"
export MULTICA_DEV_PROFILES_HOME="$tmp_dir/profiles"

fake_bin="$tmp_dir/bin"
mkdir -p "$fake_bin"
cat > "$fake_bin/psql" <<'EOF'
#!/usr/bin/env bash
[ -z "${PSQL_LOG:-}" ] || printf '%s\n' "$*" >> "$PSQL_LOG"
case " $* " in
  *" DROP DATABASE "*) [ "${FAIL_DROP:-0}" != 1 ] ;;
  *) printf '1\n' ;;
esac
EOF
chmod +x "$fake_bin/psql"
export PATH="$fake_bin:$PATH"

fail() {
  echo "FAIL: $*" >&2
  exit 1
}

require_contains() {
  local file=$1 expected=$2
  if ! grep -Fq "$expected" "$file"; then
    echo "Expected output to contain: $expected" >&2
    echo "Observed:" >&2
    sed 's/^/  /' "$file" >&2
    exit 1
  fi
}

dev_env() {
  bash "$root_dir/scripts/dev-env.sh" "$@"
}

write_manifest() {
  local name=$1 dir=$2 offset=$3
  local profile="dev-dev-env-test-$offset"
  mkdir -p "$MULTICA_DEV_HOME/envs/$name/logs"
  cat > "$MULTICA_DEV_HOME/envs/$name/manifest.env" <<EOF
NAME=$name
DIR=$(printf '%q' "$dir")
CREATED_AT=2026-01-01T00:00:00Z
OWNER=agent
TTL_HOURS=0
ENV_FILE=.env.example
OFFSET=$offset
BACKEND_PORT=$((18080 + offset))
FRONTEND_PORT=$((13000 + offset))
DB_NAME=multica_dev_env_test_$offset
DATABASE_URL=postgres://multica:multica@localhost:5432/multica_dev_env_test_$offset?sslmode=disable
PROFILE=$profile
WORKSPACES_ROOT=$(printf '%q' "$MULTICA_DEV_WORKSPACES_PARENT/multica_workspaces_$profile")
DESKTOP_RENDERER_PORT=$((5174 + offset))
DESKTOP_APP_SUFFIX=$name
EOF
}

out="$tmp_dir/out"

assert_listener_ownership() {
  local case_name=$1 expected=$2 launcher=$3 listener=$4 listener_pgid=$5 recorded=${6:-}
  (
    # shellcheck disable=SC1090
    source "$root_dir/scripts/dev-env.sh"
    STATE_DIR="$tmp_dir/ownership-$case_name"
    mkdir -p "$STATE_DIR"
    [ -z "$recorded" ] || printf '%s\n' "$recorded" > "$(listener_pid_file web)"
    TEST_LAUNCHER=$launcher
    TEST_LISTENER=$listener
    TEST_LISTENER_PGID=$listener_pgid
    TEST_CASE=$case_name

    component_pid() { printf '%s' "$TEST_LAUNCHER"; }
    port_listener_pid() { printf '%s' "$TEST_LISTENER"; }
    process_group_id() { printf '%s' "$TEST_LISTENER_PGID"; }
    process_parent_id() {
      case "$TEST_CASE:$1" in
        nested:420) printf '310' ;;
        nested:310) printf '200' ;;
        nested:200) printf '%s' "$TEST_LAUNCHER" ;;
        *) printf '1' ;;
      esac
    }

    local actual=external
    if listener_belongs_to_component web 13000; then actual=owned; fi
    [ "$actual" = "$expected" ] \
      || fail "$case_name listener ownership = $actual, want $expected"
  )
}

assert_nested_listener_is_recorded() (
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  STATE_DIR="$tmp_dir/ownership-record"
  mkdir -p "$STATE_DIR"

  component_pid() { printf '100'; }
  port_listener_pid() { printf '420'; }
  process_group_id() { printf '310'; }
  process_parent_id() {
    case "$1" in
      420) printf '310' ;;
      310) printf '200' ;;
      200) printf '100' ;;
      *) printf '1' ;;
    esac
  }

  local claimed
  claimed="$(record_component_listener web 13000)" \
    || fail "nested listener was not claimed"
  [ "$claimed" = 420 ] || fail "claimed listener = $claimed, want 420"
  [ "$(cat "$(listener_pid_file web)")" = 420 ] \
    || fail "nested listener pid was not recorded"
)

assert_stop_handles_listener() {
  local case_name=$1 listener=$2 listener_pgid=$3 listener_parent=$4 recorded=${5:-}
  local expected_target=${6:-}
  (
    # shellcheck disable=SC1090
    source "$root_dir/scripts/dev-env.sh"
    STATE_DIR="$tmp_dir/stop-$case_name"
    mkdir -p "$STATE_DIR"
    BACKEND_PORT=18080
    FRONTEND_PORT=13000
    DESKTOP_RENDERER_PORT=5174
    local signals="$STATE_DIR/signals"
    [ -z "$recorded" ] || printf '%s\n' "$recorded" > "$(listener_pid_file web)"
    TEST_CASE=$case_name
    TEST_LISTENER=$listener
    TEST_LISTENER_PGID=$listener_pgid
    TEST_LISTENER_PARENT=$listener_parent

    component_pid() { [ "$TEST_CASE" = nested ] && printf '100'; }
    port_listener_pid() { printf '%s' "$TEST_LISTENER"; }
    process_group_id() { printf '%s' "$TEST_LISTENER_PGID"; }
    process_parent_id() {
      case "$1" in
        "$TEST_LISTENER") printf '%s' "$TEST_LISTENER_PARENT" ;;
        "$TEST_LISTENER_PARENT") printf '100' ;;
        *) printf '1' ;;
      esac
    }
    sleep() { :; }
    kill() {
      [ "$1" != -0 ] || return 1
      printf 'signal=%s target=%s\n' "$1" "${2:-}" >> "$signals"
    }

    stop_component web > "$out" 2>&1 || fail "$case_name stop failed"
    if [ -n "$expected_target" ]; then
      require_contains "$signals" "target=$expected_target"
    elif [ -s "$signals" ]; then
      fail "$case_name stop signalled an external listener: $(cat "$signals")"
    fi
  )
}

# Launcher 100 owns listener 200; listener 999 is someone else's. The api's
# sources fingerprint as fp-now, and `make up` recorded `api_build` for it
# ("-" for no record).
assert_component_state() {
  local case_name=$1 component=$2 listener=$3 reported_commit=$4 probe_ok=$5
  local expected_state=$6 expected_detail=$7 api_build=${8:-100 fp-now}
  (
    # shellcheck disable=SC1090
    source "$root_dir/scripts/dev-env.sh"
    STATE_DIR="$tmp_dir/state-$case_name"
    mkdir -p "$STATE_DIR"
    BACKEND_PORT=18080
    FRONTEND_PORT=13000
    COLLAB_PORT=14000
    TEST_LISTENER=$listener
    TEST_COMMIT=$reported_commit
    TEST_PROBE_OK=$probe_ok
    [ "$api_build" = - ] || printf '%s\n' "$api_build" > "$(api_build_file)"

    component_pid() { printf '100'; }
    port_listener_pid() { printf '%s' "$TEST_LISTENER"; }
    process_group_id() { [ "$1" = 200 ] && printf '100' || printf '%s' "$1"; }
    process_parent_id() { printf '1'; }
    checkout_commit() { printf 'bbb2222'; }
    api_source_fingerprint() { printf 'fp-now'; }
    health_json() {
      printf '{"pid":%s,"commit":"%s","started_at":"2026-01-01T00:00:00Z"}' "$TEST_LISTENER" "$TEST_COMMIT"
    }
    curl() { [ "$TEST_PROBE_OK" = 1 ]; }

    local row state detail
    row="$(component_state "$component")"
    state="${row%%|*}"
    detail="${row##*|}"
    [ "$state" = "$expected_state" ] \
      || fail "$case_name state = $state, want $expected_state ($row)"
    case "$detail" in
      *"$expected_detail"*) ;;
      *) fail "$case_name detail = $detail, want it to contain: $expected_detail" ;;
    esac
  )
}

# Launcher 100 owns listener 200; listener 999 is someone else's. The probe of
# `/` fails `failed_probes` times before answering ("never" keeps failing), and
# every clock read advances 10s so the 300s wait runs out without sleeping.
assert_start_web() {
  local case_name=$1 listener=$2 failed_probes=$3 expected_status=$4
  local expected_output=$5 expected_events=$6
  (
    # shellcheck disable=SC1090
    source "$root_dir/scripts/dev-env.sh"
    STATE_DIR="$tmp_dir/start-web-$case_name"
    mkdir -p "$STATE_DIR"
    FRONTEND_PORT=13000
    ENV_FILE=.env.example
    local events="$STATE_DIR/events" probes="$STATE_DIR/probes" clock="$STATE_DIR/clock"
    printf '%s' "$listener" > "$STATE_DIR/listener"
    : > "$events"
    TEST_FAILED_PROBES=$failed_probes

    component_pid() { printf '100'; }
    port_listener_pid() { cat "$STATE_DIR/listener"; }
    process_group_id() { [ "$1" = 200 ] && printf '100' || printf '%s' "$1"; }
    process_parent_id() { printf '1'; }
    describe_port_owner() { printf 'pid %s' "$(port_listener_pid "$1")"; }
    curl() {
      local count
      count=$(($(cat "$probes" 2>/dev/null || echo 0) + 1))
      printf '%s' "$count" > "$probes"
      [ "$TEST_FAILED_PROBES" != never ] && [ "$count" -gt "$TEST_FAILED_PROBES" ]
    }
    now_epoch() {
      local now
      now=$(($(cat "$clock" 2>/dev/null || echo 1000) + 10))
      printf '%s' "$now" > "$clock"
      printf '%s' "$now"
    }
    sleep() { :; }
    kill() { printf 'kill %s\n' "$*" >> "$events"; }
    stop_component() { printf 'stop %s\n' "$1" >> "$events"; : > "$STATE_DIR/listener"; }
    launch_detached() { printf 'launch %s\n' "$1" >> "$events"; exit 0; }

    local status=0
    ( start_web ) > "$out" 2>&1 || status=$?
    [ "$status" = "$expected_status" ] \
      || { sed 's/^/  /' "$out" >&2; fail "$case_name start_web exited $status, want $expected_status"; }
    require_contains "$out" "$expected_output"
    [ "$(cat "$events")" = "$expected_events" ] \
      || fail "$case_name events = $(cat "$events"), want $expected_events"
  )
}

# Launcher 100 owns listener 200, which reports `reported_commit`; a relaunch
# gets launcher 101 and the same listener. The api's sources fingerprint as
# fp-now, and `make up` previously recorded `api_build` ("-" for no record).
assert_start_api() {
  local case_name=$1 reported_commit=$2 api_build=$3 expected_output=$4
  local expected_events=$5 expected_build=$6
  (
    # shellcheck disable=SC1090
    source "$root_dir/scripts/dev-env.sh"
    STATE_DIR="$tmp_dir/start-api-$case_name"
    LOG_DIR="$STATE_DIR"
    mkdir -p "$STATE_DIR"
    BACKEND_PORT=18080
    ENV_FILE=.env.example
    local events="$STATE_DIR/events"
    : > "$events"
    printf '100\n' > "$(pid_file api)"
    [ "$api_build" = - ] || printf '%s\n' "$api_build" > "$(api_build_file)"
    TEST_COMMIT=$reported_commit

    component_pid() { cat "$(pid_file api)"; }
    port_listener_pid() { printf '200'; }
    port_free() { :; }
    process_group_id() { [ "$1" = 200 ] && component_pid api || printf '%s' "$1"; }
    process_parent_id() { printf '1'; }
    checkout_commit() { printf 'bbb2222'; }
    api_source_fingerprint() { printf 'fp-now'; }
    health_json() {
      printf '{"pid":200,"commit":"%s","started_at":"2026-01-01T00:00:00Z"}' "$TEST_COMMIT"
    }
    now_epoch() { printf '1000'; }
    sleep() { :; }
    stop_component() { printf 'stop %s\n' "$1" >> "$events"; }
    launch_detached() {
      printf 'launch %s\n' "$1" >> "$events"
      printf '101\n' > "$(pid_file api)"
      TEST_COMMIT=bbb2222
    }

    local status=0
    ( start_api ) > "$out" 2>&1 || status=$?
    [ "$status" = 0 ] \
      || { sed 's/^/  /' "$out" >&2; fail "$case_name start_api exited $status"; }
    require_contains "$out" "$expected_output"
    [ "$(cat "$events")" = "$expected_events" ] \
      || fail "$case_name events = $(cat "$events"), want $expected_events"
    [ "$(cat "$(api_build_file)" 2>/dev/null)" = "$expected_build" ] \
      || fail "$case_name recorded api build = '$(cat "$(api_build_file)" 2>/dev/null)', want '$expected_build'"
  )
}

# The same current api as above, with `components` selected and collab's
# listener running or not. `recorded` is the collab URL the api was launched
# with ("-" for an api started before collab existed).
assert_start_api_collab() {
  local case_name=$1 components=$2 collab_running=$3 recorded=$4 expected_output=$5
  local expected_events=$6 expected_recorded=$7
  (
    # shellcheck disable=SC1090
    source "$root_dir/scripts/dev-env.sh"
    STATE_DIR="$tmp_dir/start-api-collab-$case_name"
    LOG_DIR="$STATE_DIR"
    mkdir -p "$STATE_DIR"
    BACKEND_PORT=18080
    COLLAB_PORT=14000
    COMPONENTS="$components"
    ENV_FILE=.env.example
    COLLAB_SECRET=test-secret
    local events="$STATE_DIR/events"
    : > "$events"
    printf '100\n' > "$(pid_file api)"
    printf '100 fp-now\n' > "$(api_build_file)"
    [ "$recorded" = - ] || printf '%s\n' "$recorded" > "$(api_collab_file)"
    TEST_COLLAB_RUNNING=$collab_running

    eval "original_$(declare -f listener_belongs_to_component)"
    listener_belongs_to_component() {
      if [ "$1" = collab ]; then [ "$TEST_COLLAB_RUNNING" = 1 ]; else original_listener_belongs_to_component "$@"; fi
    }
    component_pid() { cat "$(pid_file api)"; }
    port_listener_pid() { printf '200'; }
    port_free() { :; }
    process_group_id() { [ "$1" = 200 ] && component_pid api || printf '%s' "$1"; }
    process_parent_id() { printf '1'; }
    checkout_commit() { printf 'bbb2222'; }
    api_source_fingerprint() { printf 'fp-now'; }
    health_json() {
      printf '{"pid":200,"commit":"bbb2222","started_at":"2026-01-01T00:00:00Z"}'
    }
    now_epoch() { printf '1000'; }
    sleep() { :; }
    stop_component() { printf 'stop %s\n' "$1" >> "$events"; }
    launch_detached() {
      local arg wiring=""
      for arg in "$@"; do
        case "$arg" in COLLAB_INTERNAL_URL=*) wiring="$arg" ;; esac
      done
      printf 'launch %s %s\n' "$1" "$wiring" >> "$events"
      printf '101\n' > "$(pid_file api)"
    }

    local status=0
    ( start_api ) > "$out" 2>&1 || status=$?
    [ "$status" = 0 ] \
      || { sed 's/^/  /' "$out" >&2; fail "$case_name start_api exited $status"; }
    require_contains "$out" "$expected_output"
    [ "$(cat "$events")" = "$expected_events" ] \
      || fail "$case_name events = $(cat "$events"), want $expected_events"
    [ "$(cat "$(api_collab_file)" 2>/dev/null)" = "$expected_recorded" ] \
      || fail "$case_name recorded collab URL = '$(cat "$(api_collab_file)" 2>/dev/null)', want '$expected_recorded'"
  )
}

# The generated secret is created once, private, and reused; one set in the env
# file wins over it.
assert_collab_secret() (
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  STATE_DIR="$tmp_dir/collab-secret"
  mkdir -p "$STATE_DIR"
  unset COLLAB_SECRET
  local first second
  first="$(collab_secret)"
  second="$(collab_secret)"
  [ "${#first}" = 64 ] || fail "generated collab secret has ${#first} characters, want 64"
  [ "$first" = "$second" ] || fail "collab secret changed between calls"
  case "$(ls -l "$STATE_DIR/collab.secret")" in
    -rw-------*) ;;
    *) fail "collab secret file is readable by others: $(ls -l "$STATE_DIR/collab.secret")" ;;
  esac
  [ "$(COLLAB_SECRET=from-env-file collab_secret)" = from-env-file ] \
    || fail "a COLLAB_SECRET from the env file did not win"
)

# Launcher 100 owns listener 200; listener 999 is someone else's ("" for a free
# port). /health answers when `healthy` is 1.
assert_start_collab() {
  local case_name=$1 listener=$2 healthy=$3 expected_status=$4
  local expected_output=$5 expected_events=$6
  (
    # shellcheck disable=SC1090
    source "$root_dir/scripts/dev-env.sh"
    STATE_DIR="$tmp_dir/start-collab-$case_name"
    LOG_DIR="$STATE_DIR"
    mkdir -p "$STATE_DIR"
    BACKEND_PORT=18080
    COLLAB_PORT=14000
    ENV_FILE=.env.example
    COLLAB_SECRET=test-secret
    local events="$STATE_DIR/events"
    printf '%s' "$listener" > "$STATE_DIR/listener"
    printf '%s' "$healthy" > "$STATE_DIR/healthy"
    : > "$events"

    component_pid() { printf '100'; }
    port_listener_pid() { cat "$STATE_DIR/listener"; }
    port_free() { [ -z "$(port_listener_pid)" ]; }
    process_group_id() { [ "$1" = 200 ] && printf '100' || printf '%s' "$1"; }
    process_parent_id() { printf '1'; }
    describe_port_owner() { printf 'pid %s' "$(port_listener_pid "$1")"; }
    collab_healthy() { [ "$(cat "$STATE_DIR/healthy")" = 1 ]; }
    collab_cdn_domain() { printf 'localhost'; }
    sleep() { :; }
    stop_component() { printf 'stop %s\n' "$1" >> "$events"; : > "$STATE_DIR/listener"; }
    launch_detached() {
      local arg wiring=""
      for arg in "$@"; do
        case "$arg" in COLLAB_PORT=*|MULTICA_API_URL=*) wiring="$wiring $arg" ;; esac
      done
      printf 'launch %s%s\n' "$1" "$wiring" >> "$events"
      printf '100\n' > "$(pid_file collab)"
      printf '200' > "$STATE_DIR/listener"
      printf '1' > "$STATE_DIR/healthy"
    }

    local status=0
    ( start_collab ) > "$out" 2>&1 || status=$?
    [ "$status" = "$expected_status" ] \
      || { sed 's/^/  /' "$out" >&2; fail "$case_name start_collab exited $status, want $expected_status"; }
    require_contains "$out" "$expected_output"
    [ "$(cat "$events")" = "$expected_events" ] \
      || fail "$case_name events = $(cat "$events"), want $expected_events"
  )
}

# The fingerprint follows server/'s uncommitted state in a real repository:
# tracked edits, staged edits and untracked files count, ignored files and
# changes outside server/ do not, and undoing an edit restores it.
assert_api_source_fingerprint() (
  local repo="$tmp_dir/fingerprint-repo" clean
  mkdir -p "$repo/server/bin"
  git -C "$repo" init -q
  printf 'package main\n' > "$repo/server/main.go"
  printf 'bin/\n' > "$repo/server/.gitignore"
  printf 'readme\n' > "$repo/README.md"
  git -C "$repo" add -A
  git -C "$repo" -c user.name=t -c [email protected] commit -qm init
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  DIR="$repo"
  fingerprint_is() {
    local label=$1 relation=$2 actual
    actual="$(api_source_fingerprint)"
    [ -n "$actual" ] || fail "fingerprint $label: empty"
    if [ "$relation" = same ]; then
      [ "$actual" = "$clean" ] || fail "fingerprint $label: changed, want it unchanged"
    else
      [ "$actual" != "$clean" ] || fail "fingerprint $label: unchanged, want it changed"
    fi
    printf '%s' "$actual"
  }
  clean="$(api_source_fingerprint)"
  [ -n "$clean" ] || fail "fingerprint of a clean tree is empty"
  [ "$(api_source_fingerprint)" = "$clean" ] || fail "fingerprint is not stable"

  printf 'built\n' > "$repo/server/bin/multica"
  printf 'edited\n' >> "$repo/README.md"
  fingerprint_is "ignored file and edit outside server/" same >/dev/null

  printf '// edit\n' >> "$repo/server/main.go"
  fingerprint_is "tracked edit" changed >/dev/null
  git -C "$repo" add server/main.go
  fingerprint_is "staged edit" changed >/dev/null
  git -C "$repo" reset -q
  git -C "$repo" checkout -q -- server/main.go
  fingerprint_is "reverted edit" same >/dev/null

  local first
  printf 'package main\n' > "$repo/server/new.go"
  first="$(fingerprint_is "untracked file" changed)"
  printf '// edit\n' >> "$repo/server/new.go"
  [ "$(fingerprint_is "edited untracked file" changed)" != "$first" ] \
    || fail "fingerprint did not follow an edit to an untracked file"
  rm "$repo/server/new.go"
  fingerprint_is "removed untracked file" same >/dev/null
)

# ---------------------------------------------------------------------------
# An empty registry is a normal state, not an error.
# ---------------------------------------------------------------------------
dev_env list > "$out" 2>&1 || fail "list on an empty registry must succeed"
require_contains "$out" "No environments registered"

dev_env list --json > "$out" 2>&1 || fail "list --json on an empty registry must succeed"
if [ "$(cat "$out")" != "[]" ]; then
  fail "list --json on an empty registry = $(cat "$out"), want []"
fi

# ---------------------------------------------------------------------------
# Manifest serialization and user-provided names are safe. A manifest is
# sourced by Bash, so values must be shell-escaped and a name must never be
# able to walk outside envs/ before destroy eventually runs rm -rf.
# ---------------------------------------------------------------------------
quoted="$tmp_dir/quoted.env"
dangerous='a path with spaces;$(touch should-not-exist)'
bash -c 'source "$1"; write_manifest_value DIR "$2"' _ "$root_dir/scripts/dev-env.sh" "$dangerous" > "$quoted"
loaded="$(bash -c 'source "$1"; printf %s "$DIR"' _ "$quoted")"
[ "$loaded" = "$dangerous" ] || fail "manifest value did not round-trip safely"
[ ! -e "$root_dir/should-not-exist" ] || fail "loading a manifest executed its value"

status=0
dev_env up --name ../../escape > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "up accepted a path-traversing environment name"
require_contains "$out" "Invalid environment name"

status=0
dev_env up --ttl nope > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "up accepted a non-numeric TTL"
require_contains "$out" "TTL must be a positive integer"

# Rewriting an allocated database name must preserve the existing connection
# endpoint, credentials and query parameters.
rewritten="$(bash -c 'source "$1"; database_url_with_name "$2" "$3"' _ \
  "$root_dir/scripts/dev-env.sh" \
  'postgres://dev:p%[email protected]:55432/old_db?sslmode=require&application_name=dev' \
  'new_db')"
[ "$rewritten" = 'postgres://dev:p%[email protected]:55432/new_db?sslmode=require&application_name=dev' ] \
  || fail "database URL rewrite changed more than the database name: $rewritten"

# ---------------------------------------------------------------------------
# A registered environment is visible to both renderings, and the JSON one
# parses — agents read it, so a stray log line in it is a broken contract.
# ---------------------------------------------------------------------------
write_manifest "probe-901" "$tmp_dir/checkout" 901
mkdir -p "$tmp_dir/checkout"

dev_env list > "$out" 2>&1 || fail "list must succeed with one environment"
require_contains "$out" "probe-901"
require_contains "$out" "18981"

dev_env status probe-901 --json > "$out" 2>&1 || fail "status --json must succeed"
node -e '
  const fs = require("fs");
  const payload = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
  if (payload.name !== "probe-901") throw new Error("name = " + payload.name);
  if (payload.backend_port !== 18981) throw new Error("backend_port = " + payload.backend_port);
  if (payload.desktop_cdp_port !== null) throw new Error("desktop_cdp_port = " + payload.desktop_cdp_port);
  if (payload.workspace_slug !== "dev") throw new Error("workspace_slug = " + payload.workspace_slug);
  // Manifests written before collab existed derive its port from the offset.
  if (payload.collab_port !== 14901) throw new Error("collab_port = " + payload.collab_port);
  for (const key of ["api", "collab", "web", "daemon", "desktop"]) {
    if (!payload.components[key]) throw new Error("missing component " + key);
    if (payload.components[key].state !== "stopped") {
      throw new Error(key + " state = " + payload.components[key].state);
    }
  }
' "$out" || fail "status --json is not machine-readable"

# ---------------------------------------------------------------------------
# Stopping an environment that is not running is a no-op that SUCCEEDS.
#
# This is the regression that made `make down` exit 1 after reporting success:
# on bash 3.2 a command substitution whose function ends in a failing command
# aborts the whole script under `set -e`, and "no process is listening on this
# port" is that function's normal answer.
# ---------------------------------------------------------------------------
status=0
dev_env down probe-901 --components api,web > "$out" 2>&1 || status=$?
if [ "$status" -ne 0 ]; then
  echo "Observed:" >&2
  sed 's/^/  /' "$out" >&2
  fail "down on a stopped environment exited $status, want 0"
fi
require_contains "$out" "stopped"

# `make down C=daemon` must reach the script as a component filter. Dropping C
# here stops api and web too, which is what `make up C=...` users do not expect.
make -s -n -C "$root_dir" down C=daemon > "$out" 2>&1 || fail "make -n down C=daemon failed"
require_contains "$out" "dev-env.sh down --components daemon"
if make -s -n -C "$root_dir" destroy C=daemon > "$out" 2>&1; then
  fail "make destroy C=daemon must refuse instead of destroying the whole environment"
fi
require_contains "$out" "make down C=daemon"

# Commands launched through env-exec must not inherit the daemon-task identity
# hints that make human/profile CLI commands reject --profile.
write_manifest "clean-env-903" "$root_dir" 903
# MULTICA_TASK_ENV_FILE counts as identity: the CLI reloads the task's
# production token from it, replacing the local one.
MULTICA_TASK_CONFIG_ROOT=/task/config \
MULTICA_TASK_WORKSPACES_ROOT=/task/workspaces \
MULTICA_WORKSPACES_ROOT=/owner/workspaces \
MULTICA_TASK_ENV_FILE=/task/task-env.json \
  dev_env exec clean-env-903 -- sh -c '
    test -z "${MULTICA_TASK_CONFIG_ROOT:-}" &&
    test -z "${MULTICA_TASK_WORKSPACES_ROOT:-}" &&
    test -z "${MULTICA_TASK_ENV_FILE:-}" &&
    test "$MULTICA_WORKSPACES_ROOT" = "$1" &&
    test "$MULTICA_DEV_ENV" = clean-env-903
  ' _ "$MULTICA_DEV_WORKSPACES_PARENT/multica_workspaces_dev-dev-env-test-903" \
  > "$out" 2>&1 || fail "env-exec leaked daemon task identity or owner workspaces root, or did not name its environment"
# Outside a task nothing was stripped, so the CLI must still be free to call a
# marker in the checkout a leftover.
env -u MULTICA_TASK_ID -u MULTICA_AGENT_ID -u MULTICA_TASK_CONFIG_ROOT -u MULTICA_DEV_ENV \
  bash "$root_dir/scripts/dev-env.sh" exec clean-env-903 -- sh -c 'test -z "${MULTICA_DEV_ENV:-}"' \
  > "$out" 2>&1 || fail "env-exec named its environment for a run that stripped no task identity"

# scripts/desktop-cdp.mjs finds Desktop through env-exec: a recorded CDP port
# becomes its endpoint, and an environment without one never inherits a URL.
write_manifest "cdp-exec-906" "$root_dir" 906
printf 'DESKTOP_CDP_PORT=10129\n' >> "$MULTICA_DEV_HOME/envs/cdp-exec-906/manifest.env"
dev_env exec cdp-exec-906 -- sh -c '
  test "$MULTICA_DEV_DESKTOP_CDP_URL" = http://127.0.0.1:10129 &&
  test "$MULTICA_DEV_DESKTOP_RENDERER_URL" = http://localhost:6080
' > "$out" 2>&1 || fail "env-exec did not export the Desktop CDP and renderer URLs"
MULTICA_DEV_DESKTOP_CDP_URL=http://127.0.0.1:1 dev_env exec clean-env-903 -- sh -c '
  test -z "${MULTICA_DEV_DESKTOP_CDP_URL:-}"
' > "$out" 2>&1 || fail "env-exec leaked a CDP URL into an environment without one"

# A health response without process identity is never proof that the process is
# this checkout's freshly launched API.
if bash -c 'source "$1"; api_started_after '\''{"status":"ok"}'\'' 1' _ "$root_dir/scripts/dev-env.sh"; then
  fail "legacy /health without started_at was accepted as current"
fi

# Listener ownership follows the process tree, not only the launcher's process
# group. Turbo/pnpm can create a nested process group for Next while keeping the
# listener below the launcher in the PPID chain.
assert_listener_ownership same-pgid owned 100 200 100
assert_listener_ownership nested owned 100 420 310
assert_listener_ownership recorded owned 100 200 200 200
assert_listener_ownership external external 100 999 999
assert_nested_listener_is_recorded

# Stopping first records an owned nested listener before killing the launcher's
# process group. An unrelated port occupant never receives a signal.
assert_stop_handles_listener nested 420 310 200 "" 420
assert_stop_handles_listener external 999 999 1 888

# Status separates "ours but out of date or busy" from "not ours". Only the
# latter means inspecting the port for an external listener; a commit after
# `make up` or a slow Next compile must not read like a hijacked port.
assert_component_state api-current api 200 bbb2222 1 running "commit bbb2222"
assert_component_state api-stale api 200 aaa1111 1 stale "running aaa1111, checkout at bbb2222; run make up"
assert_component_state api-foreign api 999 bbb2222 1 mismatch "not this checkout/process"
assert_component_state api-foreign-old api 999 aaa1111 1 mismatch "not this checkout/process"
assert_component_state api-dirty api 200 bbb2222 1 stale "pid 200 was compiled before server/ changed (uncommitted changes differ); run make up" "100 fp-old"
assert_component_state api-unrecorded api 200 bbb2222 1 stale "has no recorded source fingerprint" -
assert_component_state api-other-launcher api 200 bbb2222 1 stale "has no recorded source fingerprint" "300 fp-now"
assert_component_state web-running web 200 - 1 running "pid 200"
assert_component_state web-busy web 200 - 0 busy "pid 200 is ours but not responding"
assert_component_state web-foreign web 999 - 1 mismatch "listener pid 999 is not owned"
assert_component_state web-foreign-silent web 999 - 0 mismatch "listener pid 999 is not owned"

# `make up` waits for its own web server while Next compiles instead of calling
# the port busy, restarts it only once the launch timeout runs out, and still
# refuses a listener it does not own.
assert_start_web compiling 200 3 0 "web already running on :13000 (pid 200)" ""
assert_start_web hung 200 never 0 "did not answer within 300s; restarting it" $'stop web\nlaunch web'
assert_start_web foreign 999 0 1 "Port 13000 is busy: pid 999" ""
assert_start_web foreign-silent 999 never 1 "Port 13000 is busy: pid 999" ""

# `go run` compiles the api once, so `make up` restarts an api of the current
# commit when server/ has uncommitted changes it was not compiled from, and
# keeps it when nothing changed.
assert_api_source_fingerprint
assert_start_api unchanged bbb2222 "100 fp-now" "api already running on :18080 (pid 200, commit bbb2222)" "" "100 fp-now"
assert_start_api dirty bbb2222 "100 fp-old" "was compiled before server/ changed (uncommitted changes differ); restarting it" $'stop api\nlaunch api' "101 fp-now"
assert_start_api unrecorded bbb2222 - "has no recorded source fingerprint" $'stop api\nlaunch api' "101 fp-now"
assert_start_api old-commit aaa1111 "100 fp-now" "is ours but not commit bbb2222; restarting it" $'stop api\nlaunch api' "101 fp-now"

# The api is wired to collab only when collab is selected or already running,
# so a doc page never waits on a collab that is not there, and `make up`
# restarts an api whose wiring no longer matches.
assert_start_api_collab selected-new "api collab web" 0 - \
  "is not connected to collab on :14000; restarting it" \
  $'stop api\nlaunch api COLLAB_INTERNAL_URL=http://localhost:14000' "http://localhost:14000"
assert_start_api_collab selected-wired "api collab web" 0 "http://localhost:14000" \
  "api already running on :18080" "" "http://localhost:14000"
assert_start_api_collab running-unselected "api web" 1 "" \
  "is not connected to collab on :14000; restarting it" \
  $'stop api\nlaunch api COLLAB_INTERNAL_URL=http://localhost:14000' "http://localhost:14000"
assert_start_api_collab gone "api web" 0 "http://localhost:14000" \
  "points at a collab service that is not running; restarting it" \
  $'stop api\nlaunch api COLLAB_INTERNAL_URL=' ""
assert_start_api_collab never-wired "api web" 0 - \
  "api already running on :18080" "" ""

stopped_in="$(bash -c 'source "$1"; stop_order api collab web daemon' _ "$root_dir/scripts/dev-env.sh")"
[ "$stopped_in" = "collab api web daemon " ] \
  || fail "down must stop collab before the api it saves docs through, got: $stopped_in"

assert_collab_secret
assert_start_collab running 200 1 0 "collab already running on :14000 (pid 200)" ""
assert_start_collab hung 200 0 0 "is ours but not answering /health; restarting it" \
  $'stop collab\nlaunch collab COLLAB_PORT=14000 MULTICA_API_URL=http://localhost:18080'
assert_start_collab fresh "" 1 0 "collab serving ws://localhost:14000 (pid 200)" \
  $'launch collab COLLAB_PORT=14000 MULTICA_API_URL=http://localhost:18080'
assert_start_collab foreign 999 1 1 "Port 14000 is busy: pid 999" ""
assert_component_state collab-running collab 200 - 1 running "pid 200"
assert_component_state collab-busy collab 200 - 0 busy "not answering /health"
assert_component_state collab-foreign collab 999 - 1 mismatch "listener pid 999 is not owned"

# ---------------------------------------------------------------------------
# Daemon: `daemon start` is a no-op while one is running, so `make up` has to
# restart a daemon that is not running this checkout's current build itself.
# ---------------------------------------------------------------------------
head_commit="$(git -C "$root_dir" rev-parse HEAD)"
old_commit=0123456789abcdef0123456789abcdef01234567
old_short="$(git -C "$root_dir" rev-parse --short "$old_commit")"
daemon_fake="$tmp_dir/daemon-fake"
mkdir -p "$daemon_fake/server/bin" "$daemon_fake/go-bin"
printf '#!/usr/bin/env bash\nexit 0\n' > "$daemon_fake/go-bin/go"
chmod +x "$daemon_fake/go-bin/go"
cat > "$daemon_fake/server/bin/multica" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$*" >> "$FAKE_DAEMON/calls"
case "$1 $2" in
  "daemon status") cat "$FAKE_DAEMON/status" ;;
  "daemon stop") printf '{"status":"stopped"}' > "$FAKE_DAEMON/status" ;;
  "daemon start")
    printf '{"status":"running","pid":5002,"cli_commit":"%s","uptime":"1s"}' \
      "$(cat "$FAKE_DAEMON/start_commit")" > "$FAKE_DAEMON/status" ;;
esac
EOF
chmod +x "$daemon_fake/server/bin/multica"

# Args: case, commit the running daemon reports, recorded "<pid> <hash>" (or
# "-" for none), commit a fresh start reports, expected exit, expected output,
# expected record afterwards.
assert_start_daemon() (
  local case_name=$1 running_commit=$2 recorded=$3 start_commit=$4
  local expected_status=$5 expected=$6 expected_record=$7 status=0 bin_hash
  export FAKE_DAEMON="$tmp_dir/daemon-$case_name"
  mkdir -p "$FAKE_DAEMON"
  printf '{"status":"running","pid":5001,"cli_commit":"%s","active_task_count":1}' \
    "$running_commit" > "$FAKE_DAEMON/status"
  printf '%s' "$start_commit" > "$FAKE_DAEMON/start_commit"
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  PATH="$daemon_fake/go-bin:$PATH"
  DIR="$root_dir" PROFILE=dev-test STATE_DIR="$FAKE_DAEMON" PROFILE_DIR="$FAKE_DAEMON"
  WORKSPACES_ROOT="$FAKE_DAEMON/ws" MULTICA_BIN="$daemon_fake/server/bin/multica"
  bin_hash="$(file_sha256 "$MULTICA_BIN")"
  [ -n "$bin_hash" ] || fail "file_sha256 printed nothing"
  case "$recorded" in
    -) ;;
    current) printf '5001 %s\n' "$bin_hash" > "$(daemon_build_file)" ;;
    *) printf '%s\n' "$recorded" > "$(daemon_build_file)" ;;
  esac
  (start_daemon) > "$out" 2>&1 || status=$?
  [ "$status" = "$expected_status" ] || { sed 's/^/  /' "$out" >&2; fail "$case_name: start_daemon exited $status, want $expected_status"; }
  require_contains "$out" "$expected"
  case "$expected_record" in
    restarted) [ "$(cat "$(daemon_build_file)")" = "5002 $bin_hash" ] \
      || fail "$case_name: recorded build is '$(cat "$(daemon_build_file)" 2>/dev/null)', want the restarted daemon" ;;
    kept) ! grep -q '^daemon stop' "$FAKE_DAEMON/calls" \
      || fail "$case_name: stopped a daemon that already ran the current build" ;;
  esac
)
assert_start_daemon current "$head_commit" current "$head_commit" 0 "daemon already running for profile dev-test (pid 5001" kept
assert_start_daemon old-commit "$old_commit" current "$head_commit" 0 "runs commit $old_short, checkout is at" restarted
assert_start_daemon dirty-edit "$head_commit" "5001 not-this-binary" "$head_commit" 0 "uncommitted changes differ" restarted
assert_start_daemon unrecorded "$head_commit" - "$head_commit" 0 "was not started from" restarted
assert_start_daemon other-pid "$head_commit" "4000 x" "$head_commit" 0 "interrupts 1 active task(s)" restarted
assert_start_daemon wrong-start "$old_commit" current "$old_commit" 1 "reports commit $old_short after start" -

# `make status` shows the daemon's commit, and calls a daemon that `make up`
# would restart stale instead of running.
assert_daemon_state() (
  local case_name=$1 running_commit=$2 recorded=$3 expected_state=$4 expected=$5 row
  export FAKE_DAEMON="$tmp_dir/daemon-state-$case_name"
  mkdir -p "$FAKE_DAEMON"
  printf '{"status":"running","pid":5001,"cli_commit":"%s","uptime":"3m0s"}' \
    "$running_commit" > "$FAKE_DAEMON/status"
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  DIR="$root_dir" PROFILE=dev-test STATE_DIR="$FAKE_DAEMON" PROFILE_DIR="$FAKE_DAEMON"
  WORKSPACES_ROOT="$FAKE_DAEMON/ws" MULTICA_BIN="$daemon_fake/server/bin/multica"
  [ "$recorded" = - ] || printf '5001 %s\n' "$(file_sha256 "$MULTICA_BIN")" > "$(daemon_build_file)"
  row="$(component_state daemon)"
  [ "${row%%|*}" = "$expected_state" ] || fail "$case_name: daemon state row '$row', want $expected_state"
  case "$row" in *"$expected"*) ;; *) fail "$case_name: daemon state row '$row', want '$expected'" ;; esac
)
assert_daemon_state current "$head_commit" current running "pid 5001 commit $(git -C "$root_dir" rev-parse --short HEAD) up 3m0s"
assert_daemon_state old-commit "$old_commit" current stale "runs commit $old_short, checkout is at"
assert_daemon_state unrecorded "$head_commit" - stale "run make up C=daemon to restart"

# ---------------------------------------------------------------------------
# Desktop: CDP port, env file, process tree, and the daemon Desktop starts.
# ---------------------------------------------------------------------------

# A recorded CDP port is reported for Playwright, and the next allocation skips
# a port another environment already holds.
write_manifest "cdp-905" "$tmp_dir/checkout" 905
printf 'DESKTOP_CDP_PORT=19999\n' >> "$MULTICA_DEV_HOME/envs/cdp-905/manifest.env"
dev_env status cdp-905 --json > "$out" 2>&1 || fail "status --json with a CDP port must succeed"
node -e '
  const payload = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"));
  if (payload.desktop_cdp_port !== 19999) throw new Error("desktop_cdp_port = " + payload.desktop_cdp_port);
' "$out" || fail "status --json did not report the recorded CDP port"
allocated="$(bash -c 'source "$1"; port_free() { :; }; allocate_cdp_port self 19999' _ "$root_dir/scripts/dev-env.sh")"
[ "$allocated" = 20000 ] || fail "CDP allocation reused another environment's port: $allocated"
dev_env destroy cdp-905 --yes > "$out" 2>&1 || fail "destroying the CDP fixture failed"

status=0
dev_env up --components api --cdp > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "up accepted --cdp without the desktop component"
require_contains "$out" "need the desktop component"

# Clearing the port without the desktop component would leave a running
# Desktop serving it while status reports null.
status=0
dev_env up --components api --no-cdp > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "up accepted --no-cdp without the desktop component"
require_contains "$out" "need the desktop component"

status=0
dev_env up --components desktop --remote-debugging-port 80 > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "up accepted a privileged CDP port"
require_contains "$out" "between 1024 and 65535"

# `up` without the desktop component still points a missing or managed env
# file at this backend, and never rewrites a file a human wrote.
assert_desktop_env_sync() (
  local case_name=$1 initial=$2 expected=$3
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  NAME=sync-env BACKEND_PORT=18555 FRONTEND_PORT=13555
  DESKTOP_ENV_FILE="$tmp_dir/desktop-env-$case_name"
  rm -f "$DESKTOP_ENV_FILE"
  [ -z "$initial" ] || printf '%s\n' "$initial" > "$DESKTOP_ENV_FILE"
  sync_desktop_env_file > "$out" 2>&1
  grep -Fqx "$expected" "$DESKTOP_ENV_FILE" \
    || fail "$case_name env file = $(cat "$DESKTOP_ENV_FILE"), want a line: $expected"
)
assert_desktop_env_sync missing "" "VITE_API_URL=http://localhost:18555"
assert_desktop_env_sync managed-elsewhere "# Managed by scripts/dev-env.sh for environment old-env." \
  "VITE_API_URL=http://localhost:18555"
assert_desktop_env_sync managed-missing-app "# Managed by scripts/dev-env.sh for environment sync-env.
VITE_API_URL=http://localhost:18555
VITE_WS_URL=ws://localhost:18555/ws" "VITE_APP_URL=http://localhost:13555"
assert_desktop_env_sync hand-written "VITE_API_URL=https://staging.example" "VITE_API_URL=https://staging.example"

# Turbo puts Electron in a nested process group; the stop path finds it through
# the launcher's PPID chain instead.
bash -c 'sleep 30 & bash -c "sleep 30; :" & wait' 2>/dev/null &
tree_root=$!
sleep 0.5
tree="$(bash -c 'source "$1"; descendant_pids "$2"' _ "$root_dir/scripts/dev-env.sh" "$tree_root" | sort)"
for child in $tree; do kill "$child" 2>/dev/null || true; done
wait "$tree_root" 2>/dev/null || true
[ "$(printf '%s\n' "$tree" | grep -c .)" -ge 3 ] \
  || fail "descendant_pids found $(printf '%s' "$tree" | tr '\n' ' ') under $tree_root, want both sleeps and the nested shell"

# Desktop's own daemon outlives Electron. Stopping Desktop stops it, and only a
# confirmed stop lets destroy remove the profile Desktop derived from this
# backend's URL; that profile holds the pid a retried destroy needs.
desktop_profile_dir="$MULTICA_DEV_PROFILES_HOME/desktop-localhost-18080"
mkdir -p "$desktop_profile_dir"
desktop_daemon="$(sleep 60 > /dev/null 2>&1 & printf '%s' "$!")"
printf '%s\n' "$desktop_daemon" > "$desktop_profile_dir/daemon.pid"
fake_checkout="$tmp_dir/fake-checkout"
stop_mode="$tmp_dir/daemon-stop-mode"
mkdir -p "$fake_checkout/server/bin"
# The fake CLI stops the daemon only in "kill" mode. "lies" exits 0 with the
# daemon still alive, like a plain `daemon stop` that is still finishing a run.
cat > "$fake_checkout/server/bin/multica" <<EOF
#!/usr/bin/env bash
[ "\$*" = "daemon stop --force --profile desktop-localhost-18080" ] || exit 0
case "\$(cat "$stop_mode")" in
  kill)
    kill -KILL $desktop_daemon
    while kill -0 $desktop_daemon 2>/dev/null; do sleep 0.1; done
    ;;
  lies) ;;
  *) exit 1 ;;
esac
EOF
chmod +x "$fake_checkout/server/bin/multica"

printf 'lies' > "$stop_mode"
status=0
(
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  OFFSET=0 BACKEND_PORT=18080 MULTICA_BIN="$fake_checkout/server/bin/multica" DIR="$fake_checkout"
  stop_desktop_daemon
) > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "stop_desktop_daemon trusted a stop that left the daemon running"
kill -0 "$desktop_daemon" 2>/dev/null || fail "the fake daemon died before the retry test"

printf 'fails' > "$stop_mode"
write_manifest "desktop-profile-906" "$fake_checkout" 0
status=0
dev_env destroy desktop-profile-906 --yes > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "destroy succeeded while Desktop's daemon was still running"
[ -f "$desktop_profile_dir/daemon.pid" ] || fail "a failed destroy removed Desktop's daemon pid"
[ -f "$MULTICA_DEV_HOME/envs/desktop-profile-906/manifest.env" ] \
  || fail "a failed destroy discarded the manifest"
require_contains "$out" "kept Desktop's CLI profile desktop-localhost-18080"

printf 'kill' > "$stop_mode"
dev_env destroy desktop-profile-906 --yes > "$out" 2>&1 \
  || { sed 's/^/  /' "$out" >&2; fail "retrying destroy after the daemon could be stopped failed"; }
! kill -0 "$desktop_daemon" 2>/dev/null || fail "Desktop's daemon is still running after destroy"
[ ! -d "$desktop_profile_dir" ] || fail "destroy left Desktop's CLI profile behind"

# ---------------------------------------------------------------------------
# A slot is one backend port and one database name derived from its offset.
# `make` exports PORT=8080, POSTGRES_DB=multica and their DATABASE_URL before
# this script runs, so an env file that lacks those keys used to register the
# shared backend and database, and destroy then dropped `multica`.
# ---------------------------------------------------------------------------
assert_slot_identity() (
  local expected=$1
  shift
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  local problem
  problem="$(slot_identity_problem "$@")"
  case "$expected" in
    ok) [ -z "$problem" ] || fail "slot_identity_problem $* = '$problem', want none" ;;
    *) case "$problem" in *"$expected"*) ;; *) fail "slot_identity_problem $* = '$problem', want '$expected'" ;; esac ;;
  esac
)
slot_url() { printf 'postgres://multica:multica@localhost:5432/%s?sslmode=disable' "$1"; }
assert_slot_identity ok 283 18363 multica_multica_283 "$(slot_url multica_multica_283)"
assert_slot_identity ok 790 18870 multica_mul_8357_team_790 "$(slot_url multica_mul_8357_team_790)"
assert_slot_identity ok 0 18080 multica_env_0 "$(slot_url multica_env_0)"
assert_slot_identity "outside the slot range" -10000 8080 multica "$(slot_url multica)"
assert_slot_identity "outside the slot range" 1920 20000 multica_x_1920 "$(slot_url multica_x_1920)"
assert_slot_identity "not slot 283's port 18363" 283 8080 multica_multica_283 "$(slot_url multica_multica_283)"
assert_slot_identity "database multica is not slot 283's" 283 18363 multica "$(slot_url multica)"
assert_slot_identity "is not slot 5's" 5 18085 multica_foo_15 "$(slot_url multica_foo_15)"
assert_slot_identity "DATABASE_URL points at database multica" 283 18363 multica_multica_283 "$(slot_url multica)"

oneline_bin="$tmp_dir/oneline-bin"
mkdir -p "$oneline_bin"
cat > "$oneline_bin/go" <<'EOF'
#!/usr/bin/env bash
[ -z "${GO_ENV_LOG:-}" ] || env > "$GO_ENV_LOG"
exit 1
EOF
chmod +x "$oneline_bin/go"

# Runs `up` in a fresh checkout whose .env holds one flag (plus ONELINE_ENV),
# with the values `make` exports. The stub `go` fails the migration, which comes
# right after the environment is registered, so nothing is started; with
# GO_ENV_LOG set it records the environment the api would have inherited.
# ONELINE_WORKTREE=1 makes it a worktree with no env file, so `up` generates
# .env.worktree the way a fresh worktree does.
oneline_up() (
  local checkout=$1
  shift
  rm -rf "$checkout"
  mkdir -p "$checkout/scripts" "$checkout/server"
  cp "$root_dir/scripts/dev-env.sh" "$root_dir/scripts/local-env.sh" "$checkout/scripts/"
  if [ "${ONELINE_WORKTREE:-0}" = 1 ]; then
    cp "$root_dir/scripts/init-worktree-env.sh" "$checkout/scripts/"
    printf 'gitdir: %s/.git-dir\n' "$checkout" > "$checkout/.git"
    cd "$checkout"
  else
    printf 'FF_DOCS_V1=true\n%s' "${ONELINE_ENV:-}" > "$checkout/.env"
  fi
  export MULTICA_DEV_HOME="$tmp_dir/dev-$(basename "$checkout")" MULTICA_DEV_TMPDIR="$tmp_dir/dev-tmp"
  export PATH="$oneline_bin:$PATH"
  export PORT=8080 FRONTEND_PORT=3000 FRONTEND_ORIGIN=http://localhost:3000 POSTGRES_DB=multica
  export MULTICA_PUBLIC_URL=http://localhost:8080 LOCAL_UPLOAD_BASE_URL=http://localhost:8080 GOOGLE_REDIRECT_URI=http://localhost:3000/auth/callback
  export DATABASE_URL="$(slot_url multica)"
  for assignment in "$@"; do export "${assignment?}"; done
  bash "$checkout/scripts/dev-env.sh" up --components api --ephemeral
)

oneline_checkout="$tmp_dir/oneline-checkout"
oneline_env_log="$tmp_dir/oneline-go.env"
status=0
oneline_up "$oneline_checkout" GO_ENV_LOG="$oneline_env_log" > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] && grep -Fq "Migrations failed" "$out" \
  || { sed 's/^/  /' "$out" >&2; fail "up with a one-line .env did not register and reach the migration"; }
(
  # shellcheck disable=SC1090
  . "$tmp_dir"/dev-oneline-checkout/envs/*/manifest.env
  [ "$BACKEND_PORT" = $((18080 + OFFSET)) ] || fail "one-line .env registered backend $BACKEND_PORT for slot $OFFSET"
  [ "$DB_NAME" = "multica_oneline_checkout_$OFFSET" ] || fail "one-line .env registered database $DB_NAME"
  [ "$DATABASE_URL" = "$(slot_url "$DB_NAME")" ] || fail "one-line .env registered DATABASE_URL $DATABASE_URL"
  for line in FF_DOCS_V1=true "PORT=$BACKEND_PORT" "FRONTEND_PORT=$FRONTEND_PORT" "POSTGRES_DB=$DB_NAME" \
    "DATABASE_URL=$DATABASE_URL" "MULTICA_PUBLIC_URL=http://localhost:$BACKEND_PORT" \
    "LOCAL_UPLOAD_BASE_URL=http://localhost:$BACKEND_PORT" \
    "GOOGLE_REDIRECT_URI=http://localhost:$FRONTEND_PORT/auth/callback"; do
    grep -Fqx "$line" "$oneline_checkout/.env" || fail "the rewritten .env lacks the line $line"
  done
  # `make` exported the :8080 and :3000 values before the slot existed; the run
  # that allocates the slot must already hand the api the slot's URLs.
  for line in "PORT=$BACKEND_PORT" "LOCAL_UPLOAD_BASE_URL=http://localhost:$BACKEND_PORT" \
    "GOOGLE_REDIRECT_URI=http://localhost:$FRONTEND_PORT/auth/callback"; do
    grep -Fqx "$line" "$oneline_env_log" || fail "the first up launched with $(grep "^${line%%=*}=" "$oneline_env_log"), want $line"
  done
  psql_log="$tmp_dir/psql-oneline.log"
  MULTICA_DEV_HOME="$tmp_dir/dev-oneline-checkout" PSQL_LOG="$psql_log" \
    bash "$oneline_checkout/scripts/dev-env.sh" destroy "$NAME" --yes > "$out" 2>&1 \
    || { sed 's/^/  /' "$out" >&2; fail "destroying the one-line .env environment failed"; }
  grep -Fq "DROP DATABASE IF EXISTS \"$DB_NAME\"" "$psql_log" || fail "destroy did not drop the slot database"
)

# An explicit TTL renewal must reuse this checkout even after its previous
# expiry. The automatic collection of another checkout still takes place.
renewal_checkout="$tmp_dir/renewal-checkout"
status=0
oneline_up "$renewal_checkout" > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "renewal fixture unexpectedly started a backend"
require_contains "$out" "Migrations failed"
(
  export MULTICA_DEV_HOME="$tmp_dir/dev-renewal-checkout"
  export PATH="$oneline_bin:$PATH"
  manifests=("$MULTICA_DEV_HOME"/envs/*/manifest.env)
  manifest="${manifests[0]}"
  # shellcheck disable=SC1090
  . "$manifest"
  expired=2000-01-01T00:00:00Z
  printf 'EXPIRES_AT=%s\n' "$expired" >> "$manifest"
  neighbor="expired-neighbor-$((OFFSET + 1))"
  neighbor_checkout="$tmp_dir/expired-neighbor"
  mkdir -p "$neighbor_checkout"
  write_manifest "$neighbor" "$neighbor_checkout" "$((OFFSET + 1))"
  printf 'TTL_HOURS=24\nEXPIRES_AT=%s\n' "$expired" >> "$MULTICA_DEV_HOME/envs/$neighbor/manifest.env"

  cd "$renewal_checkout"
  psql_log="$tmp_dir/psql-renewal.log"
  status=0
  PSQL_LOG="$psql_log" bash scripts/dev-env.sh up --components api --ttl 48 > "$out" 2>&1 || status=$?
  [ "$status" -ne 0 ] || fail "renewal fixture unexpectedly started a backend"
  require_contains "$out" "Migrations failed"
  require_contains "$out" "Reusing environment $NAME"
  if grep -Fq "DROP DATABASE IF EXISTS \"$DB_NAME\"" "$psql_log"; then
    fail "renewing an expired environment dropped its database"
  fi
  [ ! -f "$MULTICA_DEV_HOME/envs/$neighbor/manifest.env" ] \
    || fail "renewal prevented collecting another expired environment"
  # shellcheck disable=SC1090
  . "$manifest"
  [ "$TTL_HOURS" = 48 ] && [ "$EXPIRES_AT" != "$expired" ] \
    || fail "renewal did not update the recorded expiration"
)

# A setting the rewrite does not own can still win when the file is loaded
# back; `up` must refuse rather than register the shared port.
status=0
oneline_up "$tmp_dir/override-checkout" BACKEND_PORT=8080 > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "up registered an environment while BACKEND_PORT=8080 overrode the slot"
require_contains "$out" "still resolves to: PORT=8080"
if ls "$tmp_dir"/dev-override-checkout/envs/*/manifest.env >/dev/null 2>&1; then
  fail "up wrote a manifest although the slot did not take effect"
fi

# A localhost upload or redirect URL follows the slot; one that names another
# host is what someone configured, and stays as written like a ${...} line that
# already resolves to the slot.
assert_local_url() (
  local label=$1 key=$2 env_lines=$3 shell_value=$4 want=$5 want_line=${6:-}
  local checkout="$tmp_dir/local-url-$label" log="$tmp_dir/local-url-$label.env" backend frontend
  local args=("GO_ENV_LOG=$log")
  [ -z "$shell_value" ] || args+=("$key=$shell_value")
  ONELINE_ENV="$env_lines" oneline_up "$checkout" "${args[@]}" > "$out" 2>&1 || true
  grep -Fq "Migrations failed" "$out" || { sed 's/^/  /' "$out" >&2; fail "$label: up did not reach the migration"; }
  # shellcheck disable=SC1090
  backend="$(. "$tmp_dir/dev-local-url-$label"/envs/*/manifest.env && printf '%s' "$BACKEND_PORT")"
  frontend=$((backend - 18080 + 13000))
  want="${want//@BACKEND@/$backend}"
  want="${want//@FRONTEND@/$frontend}"
  grep -Fqx "$key=$want" "$log" || fail "$label: the api got $(grep "^$key=" "$log"), want $key=$want"
  case "$want_line" in
    "") ;;
    -) ! grep -q "^$key=" "$checkout/.env" || fail "$label: up wrote $key into .env" ;;
    *) grep -Fqx "$want_line" "$checkout/.env" || fail "$label: .env lost the line $want_line" ;;
  esac
)
assert_local_url file-localhost LOCAL_UPLOAD_BASE_URL $'LOCAL_UPLOAD_BASE_URL=http://localhost:8080\n' "" \
  "http://localhost:@BACKEND@"
assert_local_url file-quoted-loopback LOCAL_UPLOAD_BASE_URL $'LOCAL_UPLOAD_BASE_URL="http://127.0.0.1:8080/"\n' "" \
  "http://localhost:@BACKEND@"
assert_local_url file-remote LOCAL_UPLOAD_BASE_URL $'LOCAL_UPLOAD_BASE_URL=https://files.example.test\n' "" \
  "https://files.example.test" "LOCAL_UPLOAD_BASE_URL=https://files.example.test"
assert_local_url file-localhost-path LOCAL_UPLOAD_BASE_URL $'LOCAL_UPLOAD_BASE_URL=http://localhost:9000/files\n' "" \
  "http://localhost:9000/files" "LOCAL_UPLOAD_BASE_URL=http://localhost:9000/files"
assert_local_url shell-remote LOCAL_UPLOAD_BASE_URL "" "https://cdn.example.test" "https://cdn.example.test" -
# shellcheck disable=SC2016
assert_local_url file-derived GOOGLE_REDIRECT_URI \
  $'FRONTEND_ORIGIN=http://localhost:${FRONTEND_PORT}\nGOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback\n' "" \
  "http://localhost:@FRONTEND@/auth/callback" 'GOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback'
# FRONTEND_ORIGIN is appended below this line, so it still expands to make's :3000.
# shellcheck disable=SC2016
assert_local_url file-derived-early GOOGLE_REDIRECT_URI $'GOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback\n' "" \
  "http://localhost:@FRONTEND@/auth/callback"

# A fresh worktree's generated .env.worktree already names the slot, so `up`
# adopts it without rewriting anything; make's :8080 upload URL must still go.
worktree_checkout="$tmp_dir/worktree-checkout"
worktree_env_log="$tmp_dir/worktree-go.env"
ONELINE_WORKTREE=1 oneline_up "$worktree_checkout" GO_ENV_LOG="$worktree_env_log" > "$out" 2>&1 || true
grep -Fq "Migrations failed" "$out" || { sed 's/^/  /' "$out" >&2; fail "worktree up did not reach the migration"; }
[ -f "$worktree_checkout/.env.worktree" ] || fail "worktree up did not generate .env.worktree"
(
  # shellcheck disable=SC1090
  . "$tmp_dir"/dev-worktree-checkout/envs/*/manifest.env
  for line in "PORT=$BACKEND_PORT" "LOCAL_UPLOAD_BASE_URL=http://localhost:$BACKEND_PORT" \
    "GOOGLE_REDIRECT_URI=http://localhost:$FRONTEND_PORT/auth/callback"; do
    grep -Fqx "$line" "$worktree_env_log" \
      || fail "the first worktree up launched with $(grep "^${line%%=*}=" "$worktree_env_log"), want $line"
  done
  grep -Fqx "LOCAL_UPLOAD_BASE_URL=http://localhost:$BACKEND_PORT" "$worktree_checkout/.env.worktree" \
    || fail "the worktree .env.worktree does not pin LOCAL_UPLOAD_BASE_URL to the slot"
)

# A manifest that names the shared backend and database is never acted on:
# destroy keeps `multica`, Desktop's 8080 profile and its daemon, and the
# manifest so the leftover stays visible.
write_manifest "poisoned-907" "$fake_checkout" 907
printf 'BACKEND_PORT=8080\nDB_NAME=multica\nDATABASE_URL=%s\n' "$(slot_url multica)" \
  >> "$MULTICA_DEV_HOME/envs/poisoned-907/manifest.env"
shared_profile_dir="$MULTICA_DEV_PROFILES_HOME/desktop-localhost-8080"
mkdir -p "$shared_profile_dir"
shared_daemon="$(sleep 60 > /dev/null 2>&1 & printf '%s' "$!")"
printf '%s\n' "$shared_daemon" > "$shared_profile_dir/daemon.pid"
psql_log="$tmp_dir/psql-poisoned.log"
status=0
PSQL_LOG="$psql_log" dev_env destroy poisoned-907 --yes > "$out" 2>&1 || status=$?
kill -0 "$shared_daemon" 2>/dev/null || fail "destroy stopped the daemon of Desktop's shared 8080 profile"
kill "$shared_daemon" 2>/dev/null || true
[ "$status" -ne 0 ] || fail "destroy reported success while refusing to drop the shared database"
! grep -Fq "DROP DATABASE" "$psql_log" 2>/dev/null || fail "destroy dropped a database that is not the slot's: $(cat "$psql_log")"
require_contains "$out" "refusing to drop database multica"
require_contains "$out" "refusing to remove Desktop's CLI profile desktop-localhost-8080"
require_contains "$out" "left Desktop's daemon for profile desktop-localhost-8080 alone"
[ -d "$shared_profile_dir" ] || fail "destroy removed Desktop's shared 8080 profile"
[ -f "$MULTICA_DEV_HOME/envs/poisoned-907/manifest.env" ] || fail "destroy discarded the poisoned manifest"
rm -rf "$MULTICA_DEV_HOME/envs/poisoned-907" "$shared_profile_dir"

# ---------------------------------------------------------------------------
# Unknown names and components fail loudly instead of doing something else.
# ---------------------------------------------------------------------------
status=0
dev_env status no-such-env > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "status on an unknown environment must fail"
require_contains "$out" "Unknown environment"

status=0
dev_env up --components nope > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "up with an unknown component must fail"
require_contains "$out" "Unknown component"

# ---------------------------------------------------------------------------
# gc reports what it would collect and touches nothing in --dry-run. An
# environment whose checkout is gone has no owner left to stop it, which is how
# 152 databases accumulated with nothing on the machine able to list them.
# ---------------------------------------------------------------------------
write_manifest "orphan-902" "$tmp_dir/deleted-checkout" 902

dev_env gc --dry-run > "$out" 2>&1 || fail "gc --dry-run must succeed"
require_contains "$out" "orphan-902 would be collected"
if grep -Fq "probe-901 would be collected" "$out"; then
  fail "gc must not collect an environment whose directory still exists"
fi
[ -f "$MULTICA_DEV_HOME/envs/orphan-902/manifest.env" ] || fail "gc --dry-run deleted a manifest"

# A failed database drop keeps the manifest and slot so cleanup can be retried;
# destroy must never print success and forget the only deletion recipe.
write_manifest "drop-fails-904" "$root_dir" 904
status=0
FAIL_DROP=1 dev_env destroy drop-fails-904 --yes > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "destroy succeeded after DROP DATABASE failed"
[ -f "$MULTICA_DEV_HOME/envs/drop-fails-904/manifest.env" ] \
  || fail "destroy discarded the manifest after DROP DATABASE failed"
require_contains "$out" "manifest and slot were kept"
dev_env destroy drop-fails-904 --yes > "$out" 2>&1 || fail "retrying destroy after database recovery failed"

# ---------------------------------------------------------------------------
# Without psql, `up` creates the database through the shared compose container,
# so destroy has to drop it there too, or every destroy on such a machine leaks
# its slot database.
# ---------------------------------------------------------------------------
no_psql_path=""
IFS=: read -ra path_dirs <<< "$PATH"
for dir in "${path_dirs[@]}"; do
  [ "$dir" != "$fake_bin" ] || continue
  if [ -e "$dir/psql" ]; then
    shadow="$tmp_dir/no-psql/$(printf '%s' "$dir" | cksum | cut -d' ' -f1)"
    mkdir -p "$shadow"
    for exe in "$dir"/*; do [ "${exe##*/}" = psql ] || ln -sf "$exe" "$shadow/"; done
    dir=$shadow
  fi
  no_psql_path="${no_psql_path:+$no_psql_path:}$dir"
done
docker_bin="$tmp_dir/docker-bin"
mkdir -p "$docker_bin"
cat > "$docker_bin/docker" <<'EOF'
#!/usr/bin/env bash
[ -z "${DOCKER_LOG:-}" ] || printf '%s\n' "$*" >> "$DOCKER_LOG"
[ "${DOCKER_POSTGRES_UP:-1}" = 1 ] || { echo 'service "postgres" is not running' >&2; exit 1; }
case " $* " in
  *" exec -T postgres psql "*"DROP DATABASE "*) exit 0 ;;
  *" exec -T postgres psql "*) printf '1\n' ;;
  *) exit 1 ;;
esac
EOF
chmod +x "$docker_bin/docker"
no_psql_dev_env() {
  PATH="$docker_bin:$no_psql_path" bash "$root_dir/scripts/dev-env.sh" "$@"
}
PATH="$docker_bin:$no_psql_path" command -v psql >/dev/null 2>&1 \
  && fail "the no-psql PATH still resolves psql"

docker_log="$tmp_dir/docker-no-psql.log"
write_manifest "no-psql-908" "$root_dir" 908
status=0
DOCKER_POSTGRES_UP=0 DOCKER_LOG="$docker_log" no_psql_dev_env destroy no-psql-908 --yes > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "destroy succeeded with neither psql nor the PostgreSQL container"
require_contains "$out" "psql not found and the shared PostgreSQL container is not reachable"
[ -f "$MULTICA_DEV_HOME/envs/no-psql-908/manifest.env" ] \
  || fail "destroy discarded the manifest while the database was left in place"
! grep -Fq "DROP DATABASE" "$docker_log" || fail "destroy tried to drop through a container that is not running"

: > "$docker_log"
DOCKER_LOG="$docker_log" no_psql_dev_env destroy no-psql-908 --yes > "$out" 2>&1 \
  || { sed 's/^/  /' "$out" >&2; fail "destroy without psql did not drop the database through the container"; }
grep -Fq "exec -T postgres psql -U multica -d postgres -v ON_ERROR_STOP=1 -c DROP DATABASE IF EXISTS \"multica_dev_env_test_908\" WITH (FORCE)" "$docker_log" \
  || fail "destroy without psql did not drop the slot database in the container: $(cat "$docker_log")"
[ ! -d "$MULTICA_DEV_HOME/envs/no-psql-908" ] || fail "destroy without psql kept the manifest after dropping the database"

# The container only serves localhost:5432; a database elsewhere is not its to drop.
write_manifest "no-psql-remote-909" "$root_dir" 909
sed -i.bak 's#@localhost:5432/#@db.example.com:5432/#' "$MULTICA_DEV_HOME/envs/no-psql-remote-909/manifest.env"
: > "$docker_log"
status=0
DOCKER_LOG="$docker_log" no_psql_dev_env destroy no-psql-remote-909 --yes > "$out" 2>&1 || status=$?
[ "$status" -ne 0 ] || fail "destroy without psql reported success for a remote database"
[ ! -s "$docker_log" ] || fail "destroy dropped a remote environment's database through the local container: $(cat "$docker_log")"
[ -f "$MULTICA_DEV_HOME/envs/no-psql-remote-909/manifest.env" ] || fail "destroy discarded the remote environment's manifest"
rm -rf "$MULTICA_DEV_HOME/envs/no-psql-remote-909"

# ---------------------------------------------------------------------------
# destroy consumes the manifest: the slot is free afterwards, which is what
# makes the registry an allocator rather than a second place to leak.
# ---------------------------------------------------------------------------
dev_env destroy probe-901 --yes > "$out" 2>&1 || fail "destroy must succeed"
[ ! -d "$MULTICA_DEV_HOME/envs/probe-901" ] || fail "destroy left the environment directory behind"

dev_env list > "$out" 2>&1 || fail "list must succeed after destroy"
if grep -Fq "probe-901" "$out"; then
  fail "destroyed environment is still listed"
fi

# Declining the confirmation is a successful no-op, not a failure.
printf 'n\n' | dev_env destroy orphan-902 > "$out" 2>&1 || fail "declining destroy must exit 0"
require_contains "$out" "Cancelled."
[ -d "$MULTICA_DEV_HOME/envs/orphan-902" ] || fail "declined destroy removed the environment anyway"

# ---------------------------------------------------------------------------
# uutils mkdir (Ubuntu 26.04) reports success to a caller that lost the race
# to create a directory. A mkdir that succeeds on the held allocation lock must
# not hand it to a second holder, or two `up`s allocate the same slot.
# ---------------------------------------------------------------------------
(
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  command mkdir -p "$LOCK_DIR"
  printf '%s\n' "$PPID" > "$LOCK_DIR/pid"
  mkdir() { command mkdir "$@" 2>/dev/null || [ -d "$LOCK_DIR" ]; }
  sleep() { :; }
  if (acquire_lock) > "$out" 2>&1; then
    fail "a mkdir that succeeded on the held lock directory let a second holder in"
  fi
  require_contains "$out" "Timed out waiting for the allocation lock"
  [ "$(cat "$LOCK_DIR/pid")" = "$PPID" ] || fail "the lock holder's pid was overwritten"
  command rm -rf "$LOCK_DIR"
)

# Releasing must drop only this holder's claim. Under uutils mkdir the next
# caller can claim the directory as soon as the pid file is unlinked; deleting
# the directory after that would hand the lock to a third caller.
(
  # shellcheck disable=SC1090
  source "$root_dir/scripts/dev-env.sh"
  acquire_lock
  rm() {
    command rm -f "$LOCK_DIR/pid"
    # The next caller claims the lock between the unlink and the directory removal.
    printf '%s\n' "$PPID" > "$LOCK_DIR/pid"
    case "$1" in -r*) command rmdir "$LOCK_DIR" ;; esac
  }
  release_lock 2> "$out" || fail "release_lock failed when the next holder had already claimed the lock"
  unset -f rm
  [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$PPID" ] || fail "release_lock removed the next holder's lock"
  command rm -rf "$LOCK_DIR"
)

echo "✓ dev-env.sh registry behaviour verified"