> ## 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.

# Persistent Context Management

> Master context management to save, attach, and reuse project snapshots, making your AI interaction faster and more powerful.

While session management (`/session`) saves the conversation *history*, context management (`/context`) saves the *content of your working environment*. It is the most powerful feature for those working on multiple projects or who frequently need to consult the same codebase.

A **Context** is a named "snapshot" of one or more files and directories, processed and saved to disk for reuse at any time.

***

## The Lifecycle of a Context

Context usage follows a simple and powerful flow:

<Steps>
  <Step title="Create (/context create)">
    You define a set of files and folders, process them with a specific mode (e.g., `smart`, `chunked`), and save the result with a name.
  </Step>

  <Step title="Attach (/context attach)">
    You "attach" one or more saved contexts to your current conversation session.
  </Step>

  <Step title="Use">
    While attached, the context content is **automatically** sent to the AI with all your prompts, providing deep and continuous knowledge about your project.
  </Step>

  <Step title="Detach (/context detach)">
    When you no longer need the context, you detach it to free up space in the AI prompt.
  </Step>
</Steps>

***

## Context Management Commands

Here are all the available subcommands for managing your contexts.

### `create`: Create a New Context

Creates and saves a new context from files and directories.

**Syntax:**

```bash theme={"system"}
/context create <context-name> <path_1> [path_2...] [options]
```

**Options:**

| Flag | Description |
| :- | :- |
| `--mode <mode>` or `-m` | Defines how files will be processed. Modes: `full`, `summary`, `chunked`, `smart`, or [`knowledge`](/context/knowledge-base) (documentation or code/infra corpora as a keyless RAG knowledge base). |
| `--description <text>` or `-d` | Adds a text description to help identify the context. |
| `--tags <tag1,tag2>` or `-t` | Adds tags for easier filtering and organization. |
| `--force` or `-f` | Overwrites an existing context with the same name. |

**Example:**

```bash theme={"system"}
# Creates an 'api-core' context with smart mode, description, and tags
/context create api-core ./src/services ./docs/api \
  --mode smart \
  --description "Context with the API core and documentation" \
  --tags golang,api
```

***

### `attach` and `detach`: Attach and Detach from Session

These commands control which contexts are active in your current conversation.

| Command | Description |
| :- | :- |
| `/context attach <context-name>` | Attaches a context to the session. |
| `/context detach <context-name>` | Removes a context from the session. |
| `/context attached` | Lists all currently attached contexts. |

#### Advanced Chunk Attachment

If a context was created with `--mode=chunked`, you can attach specific parts of it:

| Flag | Description |
| :- | :- |
| `--chunk <N>` | Attaches only chunk number N. |
| `--chunks <N,M,...>` | Attaches a list of specific chunks. |
| `--priority <num>` | Defines the order in which attached contexts are sent (lower number = higher priority). |
| `--rag [K]` (or `--retrieve`, `-r`) | **Semantic retrieval**: injects only the top-K passages relevant to the turn, instead of the raw content. K optional (default 8). |
| `--full` (or `-f`) | **Whole-content attach, explicitly** — opts out of the automatic RAG upgrade for large contexts (below). |

**Example:**

```bash theme={"system"}
# Attaches only chunks 1 and 3 from the 'legado-db' context with high priority
/context attach legado-db --chunks 1,3 --priority 10
```

***

### `--rag`: Semantic Retrieval (don't dump raw data)

<Info>**The problem:** injecting whole files blows the context window on any non-trivial codebase. The `--rag` flag fixes it: instead of the raw dump, it embeds the context's passages and, each turn, injects **only the top-K most relevant to the current question**. For **documentation or code/infra corpora**, prefer [`--mode knowledge`](/context/knowledge-base): same principle, but **with no API key required** (keyless BM25), an index card in the prompt and the `@knowledge` tool for the agent to investigate.</Info>

```bash theme={"system"}
# Attach 'api-core' in retrieval mode — only relevant passages per turn
/context attach api-core --rag
# Or control K (number of passages):
/context attach api-core --rag 12
```

**How it works:**

<Steps>
  <Step title="Segmentation">
    Files are split into line-aware, overlapping **passages** (\~300 tokens each) — a fine grain, distinct from the token-budget `chunk`. IDs are content hashes, so unchanged files skip re-embedding.
  </Step>

  <Step title="Embed once, cache on disk">
    Passages are embedded lazily and persisted per context; edited/removed passages are pruned (never serve stale text).
  </Step>

  <Step title="Retrieve at prompt time">
    The turn's query is embedded and the top-K passages by cosine (with a relevance floor) are injected.
  </Step>
</Steps>

<Warning>**Requires an embedding provider** (`CHATCLI_EMBED_PROVIDER` — `voyage`, `openai` or `bedrock`). Set the provider after ChatCLI was already running? `/reload` rebuilds and rewires it on the spot. Without one, `--rag` falls back transparently to whole content, with a warning.</Warning>

**Auto-RAG for large contexts**: when an embedding provider is configured, a context of **32 KiB or more** attached with no explicit flag is automatically upgraded to semantic retrieval (top-8 passages per turn) — the same default the agent-side `@context` tool has always used. The upgrade is announced at attach time; opt out per call with `--full`/`-f` or globally with `CHATCLI_ATTACH_AUTO_RAG=off`. Small contexts and no-embeddings setups keep the verbatim whole-content behavior, unchanged.

<Tip>**Cache-aware:** the retrieved content is query-driven, so it is injected in the prompt's **volatile zone** — never poisoning the cached prefix. And `--rag` cannot be combined with `--chunk(s)` (semantic vs. manual selection are contradictory).</Tip>

In a synthetic measurement, the injected block dropped to **44% of the raw size** while still retrieving the right passage from a synonym query — on large contexts the saving is far greater. It reuses the same `vindex` primitive as [RAG + HyDE](/agents/harness/rag-hyde) — provider-agnostic, OS-agnostic. The only env knob is the auto-upgrade gate `CHATCLI_ATTACH_AUTO_RAG` (on by default).

***

### `list`, `show`, and `inspect`: View Contexts

These commands help you understand what is in your saved contexts.

| Command | Description |
| :- | :- |
| `/context list` | Lists all available contexts with basic metadata. |
| `/context show <name>` | Displays detailed information about a context, including the complete list of files. |
| `/context inspect <name>` | Provides a deep statistical analysis of the context, such as file type distribution, line counts, and chunk size analysis. Use `--chunk N` to inspect a specific chunk. |

***

### Other Management Commands

<AccordionGroup>
  <Accordion title="/context delete <name>">
    Permanently deletes a context.
  </Accordion>

  <Accordion title="/context merge <new-name> <ctx1> <ctx2>">
    Combines multiple contexts into a new one, removing duplicate files.
  </Accordion>

  <Accordion title="/context export <name> <path.json>">
    Exports a context to a JSON file, making backup and sharing easier.
  </Accordion>

  <Accordion title="/context import <path.json>">
    Imports a context from a JSON file.
  </Accordion>

  <Accordion title="/context refresh <name>">
    Re-indexes a context from the paths it was built from. Every file carries a stamp (size, mtime, content hash) since the last scan: an unchanged corpus is reported as up to date and nothing is rebuilt — retrieval caches and vectors stay valid — while an edited, added or removed file triggers a rebuild in which only the passages that actually changed are re-embedded (passage ids are content hashes). A touch without an edit is not a change. Contexts created before source paths were recorded adopt the paths of the files they hold on their first refresh or watch (persisted from then on); one `/context update <name> <paths>` still re-records them explicitly.
  </Accordion>

  <Accordion title="/context watch <name> [off] · watch list · unwatch <name>">
    Keeps a context in step with its source paths through the filesystem watcher: directories are watched recursively (noise directories such as `node_modules` and `.git` skipped, new subdirectories picked up), bursts of events settle for 1.5 s and collapse into one refresh, and the outcome is printed at the next prompt as `context <name> refreshed: N changed, M added, K removed`. Watches live for the session (and per tenant on the gateway) and stop at exit.
  </Accordion>

  <Accordion title="/context metrics">
    Shows global statistics about all your contexts (total count, size, etc.).
  </Accordion>

  <Accordion title="/context status">
    **Prefix budget.** The system prefix (mode card, attachments, digests, skills, tool catalog) may take half the window before it degrades, in a declared order: skill bodies fold into read-on-demand pointers, knowledge digests shrink to their compact card, whole-content attachments fold into an index card that lists the files and how to pull them (`/context attach <name> --rag`). When the provider can count tokens (see [Cost tracking → Token counting by provider](/providers/cost-tracking#token-counting-by-provider)), the report also prints the provider-counted size of the live history and refreshes the learned ratio from it. The report shows the budget, its usage and what folded; nothing folds while the prefix fits. The chat prefix is also reserved from the compaction budget, and the footer `ctx N%` is now the projection for the **next** request (it may read above 100% right before an auto-compact).

    Answers "what is in my context right now, and what does each part cost". Lists every section of the last assembled system prompt (mode banner, attached contexts, skills, MCP catalog, workspace memory, recall blocks, dynamic context — cached-prefix sections marked with ●), the conversation history by role with compacted summaries and `@recall`-recoverable segments, and the totals: system prompt, history, projected next request as a share of the model window, and the point where auto-compact fires. Token figures use the chars/token ratio learned from the provider's real usage reports for the active model (the default 4 until the first report), so they converge with the `ctx%` the footer shows.
  </Accordion>

  <Accordion title="/context help">
    Displays a help screen specific to context commands.
  </Accordion>
</AccordionGroup>

***

## Next Steps

You now know the most powerful automation and context management features of ChatCLI. To wrap up, let's document the features that ensure portability and tool integration in scripts.

<CardGroup cols={2}>
  <Card title="Non-Interactive Mode" icon="terminal" href="/usage/non-interactive-mode">
    Use ChatCLI in scripts, automations, and CI/CD pipelines.
  </Card>

  <Card title="Session Management" icon="clock-rotate-left" href="/context/session-management">
    Save and restore complete conversation histories.
  </Card>
</CardGroup>

***


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.