## Module 2: Ensuring Agent Working Directory Persistence

```mermaid
---
title: Module Environment Overview
---
flowchart LR
  USER["Lab User"] --> T1["Terminal 1:<br/>Hermes Sandbox"]
  USER --> T2["Terminal 2:<br/>VM Host"]
  T1 --> TD_LAYOUT
  T2 --> TD_LAYOUT
  
  %% DIR and its connections: switch to top-down orientation
  subgraph TD_LAYOUT["Using TiDB Cloud CLI and Filesystem"]
    direction TB
    TI1["ti"]
    TI1 -->|manage| FS["TiDB Cloud Filesystem<br/>aws-${LAB:REGION_CODE}"]
    DIR["Local Sandbox Directory<br/>aws-${LAB:REGION_CODE}"]
    TI1 -->|FUSE Mount| FS
    FS -->|FUSE Mount| DIR
  end
```

In this module, you will configure and launch the pre-installed Hermes Agent on the lab VM. Using the `ti` command, it will create, mount, and verify a TiDB Cloud Filesystem that persists independently of the VM, Agent session, or Agent sandbox lifecycle, and make it the Agent's default working directory.

### Step 1: Configure Hermes native sandbox and start a Hermes session

- Return to **[Terminal 1](ssh://monitor1-ssh#1)**.
- Run the following command to apply the Hermes pre-configured settings. We'll review the configuration details afterward.

```bash
# Apply the pre-defined configuration
cp ~/config.yaml.solution ~/.hermes/config.yaml
```

- Check the relevant configuration. More details are explained below.

```bash
# Check the relavent settings
hermes config check
cat ~/.hermes/config.yaml | grep -A17 'terminal:'
```

```output
terminal:
  backend: docker
  cwd: .
  timeout: 720
  home_mode: auto
  docker_mount_cwd_to_workspace: false
  docker_forward_env:
    - "TI_FS_TOKEN"
    - "TI_REGION_CODE"
    - "DATABASE_URL"
  docker_run_as_host_user: false
  docker_extra_args:
    - "--privileged"
    - "--device=/dev/fuse"
    - "--cap-add=SYS_ADMIN"
    - "--security-opt=apparmor=unconfined"
    - "--tmpfs=/tmp:rw,nosuid,size=512m,exec"
  docker_persist_across_processes: false
```

- Hermes configuration notes:
  - `backend: docker`: Use Docker as the tool backend so that commands are executed in a secure, short-lived container (Sandbox), not the VM's native shell.
  - `docker_forward_env`: This setting forwards the `TI_FS_TOKEN`, `TI_REGION_CODE`, and `DATABASE_URL` environment variables into the sandbox container. (Note: `DATABASE_URL` is needed for the next module.)
  - `docker_extra_args`: Docker parameters required for FUSE mounting the TiDB Cloud Filesystem in the container, including `--privileged`, `--device=/dev/fuse`, `--cap-add=SYS_ADMIN`, `--security-opt=apparmor=unconfined`, and an executable `/tmp` tmpfs.
  - `docker_persist_across_processes: false`: Do not persist Docker containers across Hermes processes, ensuring each new Hermes Chat uses a fresh container.

> [!NOTE]
> As mentioned in the previous module, as long as the environment contains the TI_FS_TOKEN variable and the region information of the filesystem, the TiDB Cloud CLI can mount the specific filesystem without user configuration.

- Start the Hermes session and enter the Hermes prompt. Startup may take over 30 seconds.

```bash
hermes chat
```

```output
 ⚕ deepseek.v3.2 │ ctx -- │ [░░░░░░░░░░] -- │ 18s │ ⏲ 0s 
──────────────────────────────────────────────────────────────────────────────────
❯ 
──────────────────────────────────────────────────────────────────────────────────
```

### Step 2: Help Hermes Agent understand TiDB Cloud CLI

- Stay in **[Terminal 1](ssh://monitor1-ssh#1)** to start interacting with the Agent.

- Ask Hermes to print the envrionment variables. Verify that the essential **`TI_`** environment variables are present in your environment. Instruct the Agent to run `env`, review the output, and verify that both **`TI_FS_TOKEN`** and **`TI_REGION_CODE`** are included. Your main goal is to confirm their presence, regardless of how the Agent interprets their specific purposes, for now.

```text
print env
```

```output
╭─ ⚕ Hermes ────────────────────────────────────────────────╮
I'll print the environment variables using the terminal tool.
.
TI_FS_TOKEN=*** (redacted)
.
TI_REGION_CODE=aws-${LAB:REGION_CODE}
.
```

- Confirm whether the Hermes terminal session is operating within a sandboxed environment.

```text
Is your terminal running inside a short-lived Sandbox container?
```

```output
╭─ ⚕ Hermes ────────────────────────────────────────────────────────╮
Let me check for more details about the Docker container environment.
.
.
.
Yes, according to system information, this terminal is running in a short-lived Sandbox container environment:
```

- Help the Agent learn how to use the TiDB Cloud CLI command-line tool. Observe its feedback to verify if it understands the value of a unified storage layer for the agent.

> [!TIP]
> We intentionally do NOT use dedicated TiDB Cloud Filesystem Agent Skills here.

```text
Visit https://github.com/tidbcloud/ti-cli. Tell me what capabilities this tool provides. Can you use these capabilities to improve your workflow?
```

```output
╭─ ⚕ Hermes ───────────────────────────────────────────────────────────────╮
I will check the GitHub repo to learn about the features of the ti-cli tool.
.
.
.
Summary: ti is a powerful cloud infrastructure management tool designed specifically for AI agents. It can significantly improve persistence, collaboration, and state management efficiency. If you are a TiDB Cloud user, this is an important tool to enhance agent workflows.
```

- Now, the Hermes Agent has understood how to use the TiDB Cloud Filesystem and the significance of a unified state storage layer, and is considering ways to leverage this capability to improve its workflows.

### Step 3: Allow the Agent to solve working directory persistence by itself

- Ask your agent to install the appropriate skill. Allow it up to 3 minutes to complete the installation, as it may perform verification steps afterwards. Observe the process and wait patiently while it works. If Hermes asks you for approval, choose proceed.

```text
Add this skill - https://github.com/pingcap/agent-rules/blob/main/skills/mount-tidb-cloud-fs/SKILL.md
```

```output
╭─ ⚕ Hermes ───────────────────────────────────────────────────────────────────────────────────────────╮
Looking at the GitHub repository URL, I need to fetch the skill content from the agent-rules repository.
.
.
.
The skill is now ready to be used anytime we have TI_FS_TOKEN and TI_REGION_CODE environment variables set - which we already do in this container!
```

- Copy the following instruction to tell Hermes Agent to use TiDB Cloud Filesystem as its own persistent, default working directory - `/workspace`. Watch closely how Hermes Agent proceeds, and whether it meets expectations.

```text
FUSE mount a TiDB Cloud Filesystem directly to the /workspace directory, and use it as the location for all your output files. Last, give me a report.
```

```output
╭─ ⚕ Hermes ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
I will mount the TiDB Cloud filesystem to a local directory. First, let me check the installation status of ti-cli and available regions:
.
.
.
This directory now provides a persistent, cross-session workspace, which can significantly improve the workflow, especially for complex, multi-step tasks.
```

> [!NOTE]
> By default, Hermes's sandbox environment does not include the `fusermount` binary required for FUSE operations or the `ti-cli` tool. Fortunately, the Agent can automatically detect and install these dependencies as needed. To avoid repeated installations after the sandbox is reset, consider committing a new image with these tools pre-installed. We will do it later.

### Step 4: Trigger Hermes Agent to use TiDB Cloud Filesystem

- Ask Hermes Agent to create a Python program that acts as a Solar system library. Once the Agent starts writing Python files, move on to the next step. You don't need to wait for the task to finish.

```text
Create a simple Python program under /workspace, it should return moons information about any planets in the Solar system.
```

```output
╭─ ⚕ Hermes ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
I'll create a Python program that can return moon information for planets in the Solar System. I'll use /workspace as the location for all output files as requested.
.
.
.
```

### Step 5: Verify Hermes Agent's use of TiDB Cloud Filesystem

- Switch to **[Terminal 2](ssh://monitor1-ssh#2)** and open a new Terminal 2:

- On the VM Host, run the following command to borrow Hermes's environment variables—mainly **`TI_FS_TOKEN`**, search for contents containing **Solar** in Hermes Sandbox's **`/workspace`** directory. Your output may differ from the sample.:

```bash
source ~/.hermes/.env
export TI_FS_TOKEN
ti fs search-file-content --pattern Solar 
```

> [!IMPORTANT]
> You can search it directly by using `ti`. The `ti fs search-file-content` command performs a semantic search, looking inside files for relevant content rather than just matching file names.

```output
{
  "path": "/",
  "results": [
    {
      "path": "/solar-system-moons/README.md",
      "name": "README.md"
    },
    {
      "path": "/solar-system-moons/test_moon_finder.py",
      "name": "test_moon_finder.py"
    }
  ]
}
```

### Step 6: Create a new sandbox image

- In **[Terminal 2](ssh://monitor1-ssh#2)**, create a new Docker image named **`hermes-sandbox:v1`** with the TiDB Cloud CLI and its dependencies pre-installed. This will help avoid redundant installations (`ti-cli`, `fusermount`, etc) each time the sandbox is recreated.

```bash
docker commit $(docker ps -l -q -f status=running | head -1) hermes-sandbox:v1
```

> [!NOTE]
> This action may take about 2 minutes to complete. We are using a small machine for this lab. Please be patient.

```output
sha256:88212b02b034........a3030400f49b0538579
```

- Modify the Hermes configuration so that the next time a new session is started, it will use the new sandbox image.

```bash
sed -i '/backend: docker/a\  docker_image: hermes-sandbox:v1' ~/.hermes/config.yaml
hermes config check
```

```output
.
.
.
    ○ TEAMS_PORT
    ○ TEAMS_HOST
    ○ TEAMS_ALLOWED_USERS
    ○ TEAMS_ALLOW_ALL_USERS
    ○ TEAMS_HOME_CHANNEL
    ○ TEAMS_HOME_CHANNEL_NAME
```

### Step 7: Test whether a new sandbox can inherit the TiDB Cloud Filesystem

- Stay in **[Terminal 2](ssh://monitor1-ssh#2)**, run the following command to confirm that the Sandbox container is currently running. The output will reflect your specific environment.

```bash
docker ps
```

```output
CONTAINER ID   IMAGE                                        COMMAND            CREATED          STATUS          PORTS     NAMES
19b7b29802b8   nikolaik/python-nodejs:python3.11-nodejs20   "sleep infinity"   21 minutes ago   Up 21 minutes             hermes-b401e193
```

- Go back to **[Terminal 1](ssh://monitor1-ssh#1)**, exit the current Hermes Chat session.

```text
/quit
```

```output
Resume this session with:
  hermes --resume 20260817_000435_239c2f
.
.
.
```

> [!IMPORTANT]
> Exiting the Hermes session also terminates the associated short-lived Sandbox container.

- Switch to **[Terminal 2](ssh://monitor1-ssh#2)** and run the following command to verify that the Sandbox container has been removed:

```bash
docker ps
```

```output
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
```

- Go back to **[Terminal 1](ssh://monitor1-ssh#1)**. Start a new session, which will use a brand new Sandbox.

```bash
hermes chat
```

- Ask Hermes about the status of the **`/workspace`** directory. If the directory is empty at the beginning, that's expected—the new Sandbox hasn't mounted the TiDB Cloud Filesystem yet.

```text
What's the status of /workspace now?
```

```output
╭─ ⚕ Hermes ──────────────────────────────────────────────────────────────────────╮
I need to check the current status of the /workspace directory. Let me take a look.
.
.
.
```

> [!IMPORTANT]
> If your agent did not auto-mount TiDB Cloud Filesystem to `/workspace`, use the following step to remind it to do so.

- If the TiDB Cloud Filesystem is not already auto mounted, use the following prompt to instruct the Agent to mount it and confirm that **no data has been lost**. (Output may differ.)

```text
FUSE mount a tidbcloud fs to it. List the /workspace structure after the mount.
```

```output
╭─ ⚕ Hermes ──────────────────────────────────────────────────────────────────────────────────────────────────────╮
I'll use the mount-tidb-cloud-fs skill to mount a TiDB Cloud Filesystem to /workspace. Let me load the skill first:
.
.
.
/workspace Structure:

total 31
drwxr-xr-x 2 root root    0 Aug 18 14:56 .
drwxr-xr-x 1 root root 4096 Aug 18 14:53 ..
-rw-r--r-- 1 root root 3420 README.md               # Solar System Moon Information Program documentation
-rw-r--r-- 1 root root 4389 comprehensive-report.md
-rw-r--r-- 1 root root  443 file-manifest.txt       # File listing
-rw-rw-r-- 1 root root   20 hello-world.txt         # "Hello TiDB Cloud FS"
-rw-r--r-- 1 root root   64 hermes-session.txt
-rw-r--r-- 1 root root   57 mount-status.txt
-rw-r--r-- 1 root root 4530 project_summary.txt
-rw-r--r-- 1 root root  773 quick-summary.txt
-rw-r--r-- 1 root root 6478 solar_system_moons.py   # Python program
-rw-r--r-- 1 root root 1751 system-info.txt
-rw-r--r-- 1 root root 1826 test_moons.py
-rw-r--r-- 1 root root  187 ti-cli-info.txt
```

- Exit Hermes Chat.

```text
/quit
```

> [!IMPORTANT]
> To clarify, so far we've simulated the scenario where two independent agent sessions hand off a working directory. In real-world, you can build a docker image that can always auto mount a TiDB Cloud Filesystem for your agent's sandbox.

Please proceed to the next module.
