> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentastic.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Automate worktree setup with scripts

> Run shell scripts automatically when Agentastic creates a worktree or container, so dependencies and environment files are always ready.

Every time Agentastic creates a new worktree for an agent, you can run a setup script to bring that worktree to a working state automatically. Use setup scripts to install dependencies, copy environment files, run database migrations, or perform any other initialization your project needs. This page covers both the worktree setup script (per-repository) and the container setup script (per-machine).

## Worktree setup script

The worktree setup script runs inside each new worktree directory immediately after Agentastic creates it. It is defined per repository, so different projects can have different setup routines.

### Location and permissions

Create the script in your repository at:

```
.agentastic/setup.sh
```

Make it executable before committing:

```bash theme={null}
chmod +x .agentastic/setup.sh
```

### Environment variables

Agentastic injects the following variables into your script at runtime:

| Variable                    | Description                          | Example                                  |
| --------------------------- | ------------------------------------ | ---------------------------------------- |
| `AGENTASTIC_BRANCH`         | New branch name                      | `feature-auth`                           |
| `AGENTASTIC_BASE_BRANCH`    | Base branch, if specified            | `main`                                   |
| `AGENTASTIC_WORKTREE_PATH`  | Absolute path to the new worktree    | `/Users/dev/repo-worktrees/feature-auth` |
| `AGENTASTIC_MAIN_REPO_PATH` | Absolute path to the main repository | `/Users/dev/repo`                        |
| `AGENTASTIC_COMMIT`         | Commit SHA the worktree is based on  | `abc123def456...`                        |
| `AGENTASTIC_REPO_NAME`      | Repository folder name               | `my-project`                             |

### Basic example

```bash theme={null}
#!/bin/bash
set -euo pipefail

echo "Setting up worktree: $AGENTASTIC_BRANCH"

# Install dependencies
npm install

# Copy environment file from the main repo if it exists
if [ -f "$AGENTASTIC_MAIN_REPO_PATH/.env" ]; then
  cp "$AGENTASTIC_MAIN_REPO_PATH/.env" "$AGENTASTIC_WORKTREE_PATH/.env"
  echo "Copied .env file"
fi

echo "Setup complete!"
```

### Advanced example

This script detects the package manager, copies all `.env` files, and handles Ruby, Python, and Rails projects in addition to Node.js:

```bash theme={null}
#!/bin/bash
set -euo pipefail

echo "=== Agentastic Worktree Setup ==="
echo "Branch: $AGENTASTIC_BRANCH"
echo "Path: $AGENTASTIC_WORKTREE_PATH"

# Copy all .env files from main repo, preserving directory structure
copy_env_files() {
  local source="$1"
  local dest="$2"
  find "$source" -name '.env*' -type f | while read -r file; do
    relative="${file#$source/}"
    target="$dest/$relative"
    mkdir -p "$(dirname "$target")"
    cp "$file" "$target"
    echo "Copied: $relative"
  done
}

copy_env_files "$AGENTASTIC_MAIN_REPO_PATH" "$AGENTASTIC_WORKTREE_PATH"

# Detect package manager and install Node dependencies
if [ -f "package-lock.json" ]; then
  echo "Installing with npm..."
  npm ci
elif [ -f "yarn.lock" ]; then
  echo "Installing with yarn..."
  yarn install --frozen-lockfile
elif [ -f "pnpm-lock.yaml" ]; then
  echo "Installing with pnpm..."
  pnpm install --frozen-lockfile
fi

# Ruby / Rails
if [ -f "Gemfile" ]; then
  echo "Installing Ruby gems..."
  bundle install
fi

# Python
if [ -f "requirements.txt" ]; then
  echo "Setting up Python environment..."
  python -m venv .venv
  .venv/bin/pip install -r requirements.txt
fi

# Rails database
if [ -f "bin/rails" ]; then
  echo "Setting up database..."
  bin/rails db:setup || bin/rails db:migrate
fi

echo "=== Setup complete ==="
```

### Behavior notes

* The script runs **from the new worktree directory** as its working directory.
* Execution is **non-blocking** — worktree creation succeeds even if the script exits with an error.
* Script output appears in the **Worktree Setup** task panel.
* You can re-run the setup script at any time from the task panel.

## Container setup script

The container setup script runs on your **host machine** before Agentastic creates a container. Instead of performing setup actions directly, it outputs a JSON object that Agentastic uses to configure the container.

### Location

```
~/.config/agentastic/container-setup.sh
```

### How it works

<Steps>
  <Step title="Agentastic runs your script">
    Agentastic executes the script with environment variables describing the worktree being containerized.
  </Step>

  <Step title="Your script prints JSON to stdout">
    The JSON object tells Agentastic which paths to mount, which environment variables to inject, and how to configure the container.
  </Step>

  <Step title="Agentastic parses the JSON and creates the container">
    The container is created with the mounts, environment variables, network mode, and shell you specified.
  </Step>
</Steps>

### Output format

Your script must print a JSON object to stdout with the following structure:

```json theme={null}
{
  "mounts": [
    {
      "host": "/path/on/host",
      "container": "/path/in/container",
      "readonly": true
    }
  ],
  "env": {
    "ANTHROPIC_API_KEY": "sk-...",
    "CUSTOM_VAR": "value"
  },
  "network": "bridge",
  "workdir": "/workspace",
  "shell": "/bin/bash"
}
```

### Default script

Agentastic creates a default script the first time you use containers. To open it for editing:

```bash theme={null}
open ~/.config/agentastic/container-setup.sh
```

### Example customization

Add a shared npm cache mount and a custom environment variable to the default script:

```bash theme={null}
#!/bin/bash
# ... (default script content) ...

# Add a custom mount for npm cache
MOUNTS+='{"host": "'"$HOME"'/.npm", "container": "/root/.npm", "readonly": false},'

# Add a custom environment variable
ENV+='  "MY_CUSTOM_VAR": "my-value",'

# ... (rest of default script) ...
```

### Environment variables

Agentastic passes these variables to the container setup script:

| Variable                       | Description                              |
| ------------------------------ | ---------------------------------------- |
| `AGENTASTIC_WORKTREE_PATH`     | Path to the worktree being containerized |
| `AGENTASTIC_REPO_NAME`         | Repository name                          |
| `AGENTASTIC_BRANCH`            | Branch name                              |
| `AGENTASTIC_MOUNT_SSH_KEYS`    | `true` or `false`                        |
| `AGENTASTIC_MOUNT_GIT_CONFIG`  | `true` or `false`                        |
| `AGENTASTIC_COPY_SHELL_CONFIG` | `true` or `false`                        |
| `AGENTASTIC_NETWORK_MODE`      | `bridge`, `restricted`, or `none`        |

### Resetting the container setup script

If your container setup script produces invalid output or you want to start fresh:

1. Open **Settings > Agents**
2. Click **Reset Setup Script**

## Teardown scripts

Agentastic does not currently run teardown scripts automatically. To clean up a worktree when you are done:

1. Stop any running processes in the worktree
2. Remove the worktree via **Settings > Agents** or by running `git worktree remove <path>`
3. Containers are stopped and removed automatically when you close the associated worktree

## Best practices

### Write idempotent scripts

Your script may be run more than once — for example, if you trigger it manually from the task panel. Make each step safe to repeat:

```bash theme={null}
# Good: only copies if the file is missing
[ -f .env ] || cp "$AGENTASTIC_MAIN_REPO_PATH/.env" .env

# Avoid: always overwrites, which can cause problems
cp "$AGENTASTIC_MAIN_REPO_PATH/.env" .env
```

### Handle errors gracefully

Use `set -euo pipefail` to catch errors early, or handle individual failures explicitly:

```bash theme={null}
set -euo pipefail

# Or, allow specific steps to fail without stopping the whole script
npm install || echo "npm install failed, continuing..."
```

### Log progress

Print messages at each stage so you can follow along in the task panel:

```bash theme={null}
echo "Step 1: Installing dependencies..."
npm install

echo "Step 2: Copying environment files..."
# ...
```

### Test your script manually

Before committing, run the script yourself with the expected environment variables to catch any issues:

```bash theme={null}
AGENTASTIC_BRANCH=test \
AGENTASTIC_WORKTREE_PATH=/tmp/test \
AGENTASTIC_MAIN_REPO_PATH=/path/to/repo \
.agentastic/setup.sh
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Script is not running">
    Check three things:

    1. The file exists at `.agentastic/setup.sh`
    2. It is executable: `chmod +x .agentastic/setup.sh`
    3. It has no syntax errors: `bash -n .agentastic/setup.sh`
  </Accordion>

  <Accordion title="Script fails silently">
    Add shell debugging flags at the top of your script:

    ```bash theme={null}
    set -x  # Print each command as it runs
    set -e  # Exit immediately on any error
    ```

    The output appears in the Worktree Setup task panel.
  </Accordion>

  <Accordion title="Environment variables are missing">
    Print them at the start of your script to verify they are being injected:

    ```bash theme={null}
    echo "AGENTASTIC_BRANCH: $AGENTASTIC_BRANCH"
    echo "AGENTASTIC_WORKTREE_PATH: $AGENTASTIC_WORKTREE_PATH"
    ```
  </Accordion>

  <Accordion title="Container setup script outputs invalid JSON">
    Test the script directly and pipe its output through `jq` to find syntax errors:

    ```bash theme={null}
    ~/.config/agentastic/container-setup.sh | jq .
    ```

    If `jq` reports a parse error, fix the JSON syntax in your script and test again.
  </Accordion>
</AccordionGroup>
