# How to start a VM

Start the agent-dev VM in the mode that fits your situation: an attached
shell, a detached session, a named session, or a Windows host.

For every installer mode and variable, see the
[Installer reference](installer.md).

## Prerequisites

- A supported host: Linux x86_64 or arm64 with a readable `/dev/kvm`, an
  Apple silicon Mac, or Windows x86_64.
- On Linux and macOS: `curl`, and `sha256sum` or `shasum`, on your `PATH`.

## Start with an attached shell

Run the installer from an interactive terminal:

```sh
curl -fsSL https://i9.io/vm | sh
```

The installer attaches your terminal to a shell in the guest. The command
returns when that shell ends.

On a host with no controlling terminal, the installer starts the VM detached
instead, as `I9_DETACH=1` does, and prints no separate notice.

## Start a detached session

Use this form from a script, a CI job, or an agent tool call:

```sh
curl -fsSL https://i9.io/vm | I9_DETACH=1 sh
```

Put the assignment on `sh`. The installer reads `I9_DETACH`, so an assignment
placed before `curl` never reaches it.

The command exits 0 when the session is ready. The session URL is the last
line on stdout, and `i9 run` also writes it to `~/.i9/run/vm.url`.

The installer reads `I9_CHANNEL` (`stable` or `edge`, default `stable`).
The stable channel receives releases that pass the slow-tier gate; the
edge channel tracks main.

## Name the session

Set `I9_SESSION_NAME` together with `I9_DETACH`:

```sh
curl -fsSL https://i9.io/vm | I9_DETACH=1 I9_SESSION_NAME=dev sh
```

The installer starts the session under the name `dev`, and `i9 run` writes its
URL to `~/.i9/run/dev.url`.

## What the VM runs at start

A start that resumes the image's checkpoint (the default) runs no start-up
work: the guest continues where the checkpoint was taken, with Docker already
serving.

A start at another size (`--memory` or `--vcpus` other than 2048 MiB and 2
vCPUs) boots the image from scratch. Its start-up script then runs once, in the
background, while your commands already run. It moves the root's writable
layer onto the scratch disk, prepares Docker's data root, and starts `dockerd`.
Those processes are recorded in `i9 trace` beside your own. `i9 trace show
<span>` on the span of your command keeps to that command.

## Start on Windows

On a Windows x86_64 host, run the Windows installer from PowerShell:

```powershell
irm https://i9.io/vm/install.ps1 | iex
```

The VM boots attached to your terminal. Windows has no detached mode and no
URL file, so the detached, named, and verify steps on this page need a Linux
or macOS host.

## Verify

For a detached session, list the sessions and run a command in the guest:

```sh
~/.i9/bin/i9 vm ls
~/.i9/bin/i9 vm exec "$(cat ~/.i9/run/vm.url)" -- echo ok
```

`vm ls` lists a row with the session name, and `vm exec` prints `ok`.

## Stop the session

```sh
~/.i9/bin/i9 vm stop "$(cat ~/.i9/run/vm.url)"
```

The command saves the session to a parked archive under
`~/.i9/state/parked/`, prints the archive path on stdout, and shuts the
VM down. To resume the session later, run `i9 run <archive> --session`.
To stop without saving, use `i9 vm stop --discard`. A discard still
leaves the run's traces under `~/.i9/sessions` and the image pages it
fetched in the image page cache under `~/.i9/store`, which later runs of
the same image reuse. `i9 store ls` lists that cache and `i9 store prune`
reclaims it (see `i9 store` in the [CLI reference](cli.md#i9-store)).

For the flags of each command, see `i9 vm` in the
[CLI reference](cli.md#i9-vm).

## Run a test matrix across forked children

This recipe runs one command in several forked children, with no human in
the loop, and leaves no VM behind. It works on a free-tier Linux arm64
install with the public `i9` binary. It has four steps, in this order:

1. **Choose the size before you prepare.** `--vcpus` and `--memory` apply when
   the parent is prepared; a different size means preparing again. The
   published image resumes from a checkpoint captured at 2 vCPUs and 2048 MiB,
   and any other size boots from scratch, so pick the size once for the whole
   matrix.
2. **Check the cap before you fork.** The parent and every running child count
   as their vCPUs against the cap. `i9 vm ls` ends with a line such as
   `2.0 of 16.0 vCPUs count against the cap`, and `i9 --json grant show`
   reports the same two numbers as `running_millivcpus` and
   `max_millivcpus`. Size the matrix to what is free, as the script does.
3. **Prepare, save, fork, run, collect.** Prepare the parent, `i9 vm save` it,
   fork each child from that snapshot with `i9 vm fork`, run the command in
   each with `i9 vm exec` and a per-child marker (`-e MATRIX_SETTING=<name>`),
   and collect each child's stdout and exit status.
4. **Tear everything down, including on failure.** Stop every child and the
   parent with `i9 vm stop --discard` from a `trap`, then confirm with
   `i9 vm ls` that none is left.

Save this as `fork_matrix.sh` and run `sh fork_matrix.sh` (or pass the path of
your `i9` as the first argument). Set `VCPUS`, `MEMORY`, `SETTINGS` and `SUITE`
to change the size, the matrix and the command.

```sh
#!/bin/sh
# Headless fork matrix: size the parent, check the cap, prepare once, save,
# fork one child per setting from the snapshot, run a command in each, collect
# the output, and tear everything down even when a step fails.
#
#   fork_matrix.sh [path-to-i9]        (default: the binary named i9, from PATH)
#
# Environment: VCPUS (default 1) and MEMORY in MiB (default 1024) size every
# VM; SETTINGS is the space-separated list of matrix settings (default four);
# SUITE is the command each child runs (default `uname -m`), and it reads its
# setting from $MATRIX_SETTING; OUT is the directory the results land in.
set -eu

I9=${1:-i9}
VCPUS=${VCPUS:-1}
MEMORY=${MEMORY:-1024}
SETTINGS=${SETTINGS:-"alpha bravo charlie delta"}
SUITE=${SUITE:-"uname -m"}
OUT=${OUT:-./fork-matrix-out}
IMAGE=https://a.i9.io/vm/manifest.json
RUN_ID=fm$$
PARENT=$RUN_ID-parent
SNAP=$PWD/$RUN_ID.i9io
CHILDREN=

# Step 4, guaranteed teardown: every child, then the parent, discarded, then
# `vm ls` as the confirmation. Runs on success, on failure and on a signal.
cleanup() {
  status=$?
  trap - EXIT INT TERM
  for c in $CHILDREN; do "$I9" vm stop "$c" --discard >/dev/null 2>&1 || true; done
  "$I9" vm stop "$PARENT" --discard >/dev/null 2>&1 || true
  rm -f "$SNAP"
  if "$I9" vm ls 2>&1 | grep -q "$RUN_ID"; then
    echo "fork-matrix: teardown incomplete, still listed by vm ls:" >&2
    "$I9" vm ls >&2
    status=1
  else
    echo "fork-matrix: teardown confirmed, no $RUN_ID VM in vm ls" >&2
  fi
  exit "$status"
}
trap cleanup EXIT INT TERM

# Step 2, cap preflight: the parent and every child count as VCPUS each while
# they run. `i9 grant show --json` reports the cap and the vCPUs running now
# in thousandths (max_millivcpus 0 means no cap on this build, and an
# unlimited grant reports 4294967295; both leave the matrix unconstrained).
grant=$("$I9" --json grant show)
cap=$(printf '%s\n' "$grant" | sed -n 's/.*"max_millivcpus": *\([0-9][0-9]*\).*/\1/p' | head -n 1)
running=$(printf '%s\n' "$grant" | sed -n 's/.*"running_millivcpus": *\([0-9][0-9]*\).*/\1/p' | head -n 1)
n=$(printf '%s\n' $SETTINGS | wc -l | tr -d ' ')
need=$(( (n + 1) * VCPUS * 1000 ))
if [ "${cap:-0}" -ne 0 ] && [ $(( cap - running )) -lt "$need" ]; then
  fit=$(( (cap - running) / (VCPUS * 1000) - 1 ))
  [ "$fit" -ge 0 ] || fit=0
  echo "fork-matrix: $n settings at $VCPUS vCPU each need $((need / 1000)) vCPUs with the parent; $(( (cap - running) / 1000 )) are free under the cap. Trim SETTINGS to $fit or lower VCPUS." >&2
  exit 1
fi

# Step 1, sizing: --vcpus and --memory apply when the parent is prepared. A
# different size means preparing again, so it is chosen here, once.
echo "fork-matrix: preparing $PARENT ($VCPUS vCPU, $MEMORY MiB)" >&2
"$I9" run "$IMAGE" --session --detach --name "$PARENT" --vcpus "$VCPUS" --memory "$MEMORY" >/dev/null
"$I9" vm exec "$PARENT" -- true

# Step 3: save the prepared state, then fork each child from the snapshot.
"$I9" vm save "$PARENT" --out "$SNAP" --description "$RUN_ID matrix base" >/dev/null
mkdir -p "$OUT"
for s in $SETTINGS; do
  child=$RUN_ID-$s
  CHILDREN="$CHILDREN $child"
  "$I9" vm fork "$SNAP" --name "$child" >/dev/null
done

# Run the suite in every child at once, each with its own marker, and collect
# stdout and exit status per setting.
for s in $SETTINGS; do
  (
    rc=0
    "$I9" vm exec "$RUN_ID-$s" -e "MATRIX_SETTING=$s" --shell -- "$SUITE" >"$OUT/$s.out" 2>"$OUT/$s.err" || rc=$?
    echo "$rc" >"$OUT/$s.rc"
  ) &
done
wait

failed=0
for s in $SETTINGS; do
  rc=$(cat "$OUT/$s.rc")
  echo "fork-matrix: $s exit=$rc output=$OUT/$s.out" >&2
  [ "$rc" -eq 0 ] || failed=1
done
exit "$failed"
```

The script exits 0 when every child's command exited 0, and 1 when any
did not or when the matrix does not fit under the cap. Each child's stdout is
in `$OUT/<setting>.out`.

## Troubleshooting

| Problem | Cause | Fix |
|---------|-------|-----|
| The command opens an attached shell instead of detaching | `I9_DETACH=1` precedes `curl`, so the installer never sees it | Move the assignment to `sh`, after the pipe |
| The VM starts detached when you wanted a shell | The host has no controlling terminal | No action. To choose the detached mode on purpose, set `I9_DETACH=1` |
| The installer exits 7 with `the VM did not come up` | `i9 run --detach` did not report the VM ready | Read the startup log whose path is printed above the line |
| The installer exits with another error | The `[i9] E<NAME>:` line on stderr names the reason | See [How to troubleshoot setup](how-to-troubleshoot-setup.md) |
