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

# Session Management

> Learn how to save, load, and manage multiple conversation sessions to organize your work and maintain history across different tasks.

Working on multiple projects or tasks can be challenging, especially when each one has a different conversation context. **ChatCLI** solves this with a simple and powerful session management system.

A session is essentially a complete "save" of your conversation history, allowing you to resume exactly where you left off.

<Info>
  ChatCLI uses a **unified history** — a single message array shared across all modes (chat, agent, coder). When saving a session, the entire context is preserved regardless of the mode in which it was generated. Use `/compact` to reduce size and `/rewind` to go back to earlier points.
</Info>

***

## Session Commands

All session management commands start with `/session`.

<Steps>
  <Step title="/session save <name>">
    Saves the current conversation (the entire history of prompts and responses) with a name of your choice.

    ```bash theme={"system"}
    /session save debug-api-pagamentos
    ```

    ```text theme={"system"}
    Sessão 'debug-api-pagamentos' salva com sucesso.
    ```

    <Tip>After saving, the session name will appear in your prompt (e.g., `debug-api-pagamentos`), indicating that you are working within that session.</Tip>
  </Step>

  <Step title="/session load <name>">
    Loads a previously saved session. The current conversation is replaced by the loaded session's history.

    ```bash theme={"system"}
    /session load documentação-site
    ```

    ```text theme={"system"}
    Sessão 'documentação-site' carregada. A conversa anterior foi restaurada.
    ```
  </Step>

  <Step title="/session list">
    Lists all sessions you have saved to disk.

    ```bash theme={"system"}
    /session list
    ```

    ```text theme={"system"}
    Sessões salvas:

      - debug-api-pagamentos
      - documentação-site
      - refatoração-legado
    ```
  </Step>

  <Step title="/session delete <name>">
    Permanently removes a saved session from disk. This action cannot be undone.

    ```bash theme={"system"}
    /session delete refatoração-legado
    ```

    ```text theme={"system"}
    Sessão 'refatoração-legado' deletada com sucesso do disco.
    ```

    <Warning>If you delete the currently active session, your current history will be cleared and you will start a new conversation.</Warning>
  </Step>

  <Step title="/session new (or /newsession)">
    Clears the current history and starts a completely new conversation. Perfect for starting a task from scratch without being tied to any named session.

    ```bash theme={"system"}
    /session new
    ```

    ```text theme={"system"}
    New conversation session started; history has been cleared.
    ```
  </Step>

  <Step title="/session fork <new-name>">
    Creates an **independent copy** of the current session with a new name. The original remains untouched and you automatically switch to working on the fork.

    Ideal for experimenting with different approaches without losing current progress, or branching a conversation in different directions.

    ```bash theme={"system"}
    /session fork experiment-v2
    ```

    ```text theme={"system"}
    ╭── ✅ Session forked!
    │    From:  my-session
    │    To:    experiment-v2
    │    Messages: 42
    │    Now working on the fork. Original remains intact.
    ╰──────────────────────────────────────────────
    ```

    <Tip>Works with both saved and unsaved (in-memory) sessions. For unsaved sessions, the fork is created from the current history state.</Tip>
  </Step>
</Steps>

***

## Automatic saving on exit

You don't have to remember `/session save`: when the interactive REPL exits, the conversation is **auto-saved** under a reserved `autosave-YYYYMMDD-HHMMSS` name. Trivial sessions (fewer than 2 non-system messages) are skipped, and one-shot `-p` runs never autosave. Gated by `CHATCLI_SESSION_AUTOSAVE` (**on** by default, shown in `/config session`). Autosaved conversations are fully searchable and readable via [`@session`](/features/session-search).

**MCP sessions autosave too**: the MCP/ACP server mirrors each live conversation to a rolling `mcp-<session>` file after every turn (both the full-pipeline and plain paths), and `manage_session clear` saves one last time before discarding. An explicit `CHATCLI_MCP_SESSION_AUTOSAVE` always wins; unset, it follows the global `CHATCLI_SESSION_AUTOSAVE` gate — on by default. Retention for both surfaces is covered under [Automatic Cleanup](#automatic-cleanup) below.

***

## Where Sessions Are Stored

Sessions are saved as **JSON files** in the current working directory (CWD) — that is, the directory from which you launched ChatCLI.

The file naming pattern is:

```text theme={"system"}
.chatcli_session_<name>.json
```

For example, running `/session save debug-api` creates the file:

```text theme={"system"}
.chatcli_session_debug-api.json
```

<Info>
  The `SessionManager` is the internal component responsible for all session file I/O. It handles read/write errors (permissions, full disk, malformed JSON) and displays clear messages if something fails.
</Info>

Session files contain the **complete conversation history** at the time of saving — including user messages, AI responses, tool call results, and summaries generated by `/compact`.

<Warning>
  Since files are stored in the CWD, starting ChatCLI from different directories will show different sessions. Use `/session list` to check which sessions are available in the current directory.
</Warning>

***

## Data Format (v2)

Session files use the **v2 format**, defined by the `SessionData` struct in the `models` package. The JSON structure is:

```json theme={"system"}
{
  "version": 2,
  "chat_history": [
    {
      "role": "user",
      "content": "Explain the Repository pattern",
      "meta": {
        "is_summary": false,
        "summary_of": 0,
        "mode": "chat"
      },
      "tool_calls": null,
      "tool_call_id": ""
    },
    {
      "role": "assistant",
      "content": "The Repository pattern is...",
      "meta": {
        "is_summary": false,
        "summary_of": 0,
        "mode": "chat"
      },
      "tool_calls": null,
      "tool_call_id": ""
    }
  ],
  "agent_history": [],
  "coder_history": [],
  "shared_memory": []
}
```

### Message Fields

| Field             | Type       | Description                                                                |
| ----------------- | ---------- | -------------------------------------------------------------------------- |
| `role`            | string     | `"user"`, `"assistant"`, `"system"`, or `"tool"`                           |
| `content`         | string     | Text content of the message                                                |
| `meta.is_summary` | bool       | `true` if the message is a summary generated by `/compact`                 |
| `meta.summary_of` | int        | Number of original messages this summary represents                        |
| `meta.mode`       | string     | Mode in which the message was generated (`"chat"`, `"agent"`, `"coder"`)   |
| `tool_calls`      | array/null | List of tool calls (agent/coder mode)                                      |
| `tool_call_id`    | string     | ID of the tool call this message responds to (for `role: "tool"` messages) |

### Format Evolution

* **v1** (older versions): Maintained separate histories per mode — `chat_history`, `agent_history`, and `coder_history` each with their own messages.
* **v2** (current version): Uses a **unified history**. The `chat_history` field contains all messages from all modes. The `agent_history` and `coder_history` fields exist for compatibility but are empty in new sessions.

<Tip>
  When loading a v1 session (with separate per-mode histories), ChatCLI **automatically merges** the messages in chronological order into the unified history. No manual intervention is required.
</Tip>

***

## Unified History and Sessions

ChatCLI uses a **single message array** for all interaction modes. This means:

* When saving a session, the **entire unified history** is serialized — including messages from chat, agent, and coder mode.
* System messages, tool call results, and compacted summaries are **all preserved** in the file.
* When loading a session, the current history is **completely replaced** by the loaded session's history.

The active session name appears as a prefix in the interactive prompt:

```text theme={"system"}
[debug-api] claude-sonnet-4-6>
```

This makes it easy to know which context you are working in at any time.

<Warning>
  Loading a session **replaces** the entire current history. If you have an unsaved conversation, it will be lost. Save first with `/session save` if you want to preserve it.
</Warning>

***

## Interaction with Other Systems

Sessions interact with several other ChatCLI subsystems. Here is how each one behaves:

### Compaction (`/compact`)

The `/compact` command reduces history size by creating summaries of older messages. If you save a session **after** compacting, the resulting file will be significantly smaller, as it contains summaries instead of the original messages.

### Rewind (`/rewind`)

The checkpoints used by `/rewind` exist **only in memory** during the current run. They are **not saved** in the session file. When loading a session, you will not have rewind points available until you create new ones during the conversation.

### Bootstrap (SOUL.md, etc.)

Bootstrap files are **not part of the session**. They are loaded automatically on every ChatCLI startup, regardless of which session is active. This ensures that the AI's base behavior is always consistent.

### Memory (`/memory`)

Memory is **global** — it is not tied to any specific session. Data saved with `/memory save` is available across all sessions and survives ChatCLI restarts.

### Context (`/context attach`)

Contexts attached via `/context attach` are **not saved** in the session file. When loading a session, you need to re-attach the necessary contexts manually.

<Info>
  **Quick summary**: Sessions only save the message history. Bootstrap, memory, contexts, and rewind checkpoints are managed separately.
</Info>

***

## Auto-Save and Persistence

<Warning>
  Sessions are **not auto-saved**. You must explicitly call `/session save` to persist the conversation to disk.
</Warning>

If you close ChatCLI without saving, the conversation history will be **permanently lost**. There is no automatic recovery mechanism.

### The `.chatcli_history` File (Don't Confuse)

ChatCLI maintains a separate file called `.chatcli_history` that stores the **command input history** (similar to `~/.bash_history`). This file:

* Contains only the text you typed at the prompt, **not** the AI's responses
* Is controlled by the `HISTORY_FILE` and `HISTORY_MAX_SIZE` environment variables
* Has **no relation** to session files (`.chatcli_session_*.json`)

| Aspect  | Sessions (`.chatcli_session_*.json`)            | Command History (`.chatcli_history`)         |
| ------- | ----------------------------------------------- | -------------------------------------------- |
| Content | Complete conversation (user + assistant + tool) | Only what you typed                          |
| Saving  | Manual (`/session save`)                        | Automatic                                    |
| Format  | Structured JSON (v2)                            | Plain text, one line per command             |
| Control | `/session` commands                             | `HISTORY_FILE`, `HISTORY_MAX_SIZE` variables |

***

## Recommended Workflow

To get the most out of the session system, follow these practices:

<Steps>
  <Step title="Name sessions after the task">
    Use descriptive names that clearly identify the objective. Examples: `fix-auth-bug`, `refactor-api`, `docs-v2`, `debug-memory-leak`.

    ```bash theme={"system"}
    /session save fix-auth-bug
    ```
  </Step>

  <Step title="Compact before saving">
    Use `/compact` before `/session save` to reduce file size and keep only the essential information.

    ```bash theme={"system"}
    /compact
    /session save fix-auth-bug
    ```
  </Step>

  <Step title="Start clean before switching sessions">
    Use `/session new` before loading another session. This ensures the previous context doesn't interfere.

    ```bash theme={"system"}
    /session new
    /session load refactor-api
    ```
  </Step>

  <Step title="Switch between tasks freely">
    You can have multiple sessions saved for different tasks and switch between them as needed.

    ```bash theme={"system"}
    /session save fix-auth-bug      # save current work
    /session load refactor-api      # load another task
    # ... work on the refactoring ...
    /session save refactor-api      # save progress
    /session load fix-auth-bug      # go back to the bug
    ```
  </Step>
</Steps>

***

## Session Encryption

Session files can be **encrypted at rest** using AES-256-GCM to protect sensitive conversation data:

| Variable                 | Description                               | Default         |
| ------------------------ | ----------------------------------------- | --------------- |
| `CHATCLI_ENCRYPTION_KEY` | Encryption key (32 bytes, base64-encoded) | `""` (disabled) |

When configured, all session operations (save/load) use transparent encryption:

```bash theme={"system"}
# Generate a secure key
export CHATCLI_ENCRYPTION_KEY=$(openssl rand -base64 32)

# Save and load sessions normally - encryption is transparent
/session save my-secure-session
/session load my-secure-session
```

<Info>
  Key derivation uses **HKDF** (HMAC-based Key Derivation Function) to generate unique per-session keys from the master key. This ensures that compromising one session does not compromise others.
</Info>

**Transparent migration:** Existing plaintext sessions are automatically encrypted when loaded and saved again. No manual action is needed to migrate old sessions.

<Warning>
  Store the encryption key in a secure location. If the key is lost, encrypted sessions **cannot be recovered**.
</Warning>

***

## Automatic Cleanup

ChatCLI applies a bounded lifecycle to **machine-created** sessions on startup (REPL and MCP/ACP server alike). The core rule: **sessions you named are never deleted automatically** — only the `autosave-` and `mcp-` prefixed files ChatCLI creates on its own are subject to retention.

| Variable                        | Description                                                       | Default                                                         |
| ------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------- |
| `CHATCLI_SESSION_TTL`           | Maximum machine-session lifetime, in days (`0` disables expiry)   | `90d` (90 days — 3× Claude Code's default transcript retention) |
| `CHATCLI_SESSION_AUTOSAVE_KEEP` | Keep-count backstop per machine prefix (newest survive, by mtime) | `600`                                                           |

Time is the primary retention: machine sessions untouched for the TTL are removed in the background at startup. The keep-count is a generous backstop against pathological accumulation, not the working limit. And nothing distilled is ever lost: facts, episodes and rollups extracted from a session are permanent and survive its cleanup — pruning bounds disk and search cost, not knowledge.

```bash theme={"system"}
export CHATCLI_SESSION_TTL=30d   # Expire machine sessions older than 30 days
chatcli
```

<Tip>
  Use `CHATCLI_SESSION_TTL=0` to disable automatic cleanup and keep all sessions indefinitely. To make one conversation immortal regardless of policy, just save it under a name: `/session save my-checkpoint`.
</Tip>

***

## Name Validation

Session names are validated with a **strict regex** to prevent path traversal and problematic characters:

* **Allowed characters:** letters (a-z, A-Z), numbers (0-9), hyphens (`-`), underscores (`_`), and dots (`.`)
* **Length:** 1 to 128 characters
* **Forbidden:** spaces, slashes, special characters, `..` sequences

```text theme={"system"}
Pattern: ^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$
```

Invalid names are rejected with a clear error message indicating the allowed characters.

***

## Frequently Asked Questions

<AccordionGroup>
  <Accordion title="Are sessions shared between machines?">
    **No.** Session files are stored locally in the current working directory. To transfer a session between machines, you would need to manually copy the `.chatcli_session_<name>.json` file to the same directory on the other machine.
  </Accordion>

  <Accordion title="Is there a size limit for sessions?">
    Technically, the limit is defined by the `HISTORY_MAX_SIZE` variable (default: 100MB), but in practice sessions rarely exceed a few megabytes. If the history is too large, use `/compact` before saving to significantly reduce the size.
  </Accordion>

  <Accordion title="Can I manually edit the session JSON file?">
    **Yes**, but with care. The file follows the v2 format described above. You can remove messages, edit content, or adjust metadata. Make sure to keep the JSON valid and the structure intact (especially the `version` field).
  </Accordion>

  <Accordion title="What happens if I load a session from an older version?">
    ChatCLI automatically detects sessions in the v1 format (with separate per-mode histories) and performs an **automatic migration** to v2, merging all messages in chronological order into the unified history. The process is transparent and requires no action from the user.
  </Accordion>

  <Accordion title="Can I have sessions with the same name in different directories?">
    **Yes.** Since files are saved in the CWD, each directory has its own session namespace. A session called `debug` in `/project-a` is completely independent from a session called `debug` in `/project-b`.
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Conversation Control" icon="clock-rotate-left" href="/features/conversation-control">
    Use /compact and /rewind to manage history size and state.
  </Card>

  <Card title="Persistent Context" icon="database" href="/features/persistent-context">
    Save, attach, and reuse project snapshots with the /context command.
  </Card>

  <Card title="Bootstrap and Memory" icon="memory" href="/features/bootstrap-memory">
    Customize the AI and maintain long-term context.
  </Card>

  <Card title="One-Shot Mode" icon="terminal" href="/features/non-interactive-mode">
    Use ChatCLI in scripts, automations, and CI/CD pipelines.
  </Card>
</CardGroup>

***
