docs: add actor context management showcase (remove, export, import)
Document the CLI-based lifecycle for removing, exporting, and importing named contexts, including JSON import limitations and scripting examples. ISSUES CLOSED: #4409
This commit is contained in:
@@ -0,0 +1,851 @@
|
||||
# Actor Context Management: Removing, Exporting, and Importing Conversation Contexts
|
||||
|
||||
## Overview
|
||||
|
||||
CleverAgents stores **named actor contexts** — persistent conversation histories, state, and
|
||||
global context blobs — under `~/.cleveragents/context/<name>/`. The `agents actor context`
|
||||
subcommand group lets you manage these contexts from the command line.
|
||||
|
||||
This guide focuses on the three lifecycle-management commands:
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `actor context remove` | Delete a named context (or all contexts) |
|
||||
| `actor context export` | Serialize a context to a portable JSON or YAML file |
|
||||
| `actor context import` | Restore a context from a JSON export (YAML import not yet supported) |
|
||||
|
||||
Together these commands let you **back up**, **transfer**, **archive**, and **clean up**
|
||||
actor conversation contexts without touching the TUI or any live session.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- CleverAgents installed (`pip install cleveragents` or from source with `uv sync`)
|
||||
- Python 3.12 or higher
|
||||
- A CleverAgents workspace initialized with `agents init` (or `project init`)
|
||||
|
||||
## What You'll Learn
|
||||
|
||||
- How to remove a single named context with and without interactive confirmation
|
||||
- How to bulk-remove all contexts in one command
|
||||
- How to export a context to JSON (for portability and backup)
|
||||
- How to export a context to YAML (for human-readable archiving)
|
||||
- How to import a context from a JSON file, with automatic name inference
|
||||
- How to replace an existing context using `--update`
|
||||
- How to use `--format json` for machine-readable output in all three commands
|
||||
- The structure of the exported context payload (messages, metadata, state, global_context)
|
||||
|
||||
---
|
||||
|
||||
## Step-by-Step Walkthrough
|
||||
|
||||
### Step 1: Explore the `actor context` Subcommand
|
||||
|
||||
Start by seeing what context management commands are available:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context --help
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
Usage: python -m cleveragents actor context [OPTIONS] COMMAND [ARGS]...
|
||||
|
||||
Manage manual contexts for actor runs.
|
||||
|
||||
╭─ Options ──────────────────────────────────────────────────────────────────╮
|
||||
│ --help Show this message and exit. │
|
||||
╰────────────────────────────────────────────────────────────────────────────╯
|
||||
╭─ Commands ─────────────────────────────────────────────────────────────────╮
|
||||
│ add Add files or directories to the active context. │
|
||||
│ list List files in the active context. │
|
||||
│ show Show the content of a context file. │
|
||||
│ remove Remove a named actor context or all actor contexts. │
|
||||
│ export Export a named actor context to a JSON or YAML file. │
|
||||
│ import Import a context from a JSON or YAML file. │
|
||||
╰────────────────────────────────────────────────────────────────────────────╯
|
||||
```
|
||||
|
||||
> **Important:** The CLI help text currently advertises YAML import, but the
|
||||
> persistence layer only accepts JSON payloads. Attempting to import a YAML
|
||||
> export will fail. See Step 9 for details and workarounds.
|
||||
|
||||
**What's Happening:**
|
||||
The `actor context` group exposes six subcommands. The first three (`add`, `list`, `show`)
|
||||
manage file-level context for the active project. The last three (`remove`, `export`, `import`)
|
||||
manage **named conversation contexts** — persistent JSON stores under
|
||||
`~/.cleveragents/context/<name>/` that hold actor conversation history, state, and metadata.
|
||||
|
||||
---
|
||||
|
||||
### Step 2: Create a Context to Work With
|
||||
|
||||
Before removing or exporting, create a context by running an actor. For this walkthrough,
|
||||
we'll create a context manually using the Python API (the same structure the CLI creates):
|
||||
|
||||
```bash
|
||||
# Create a context directory and seed it with a conversation
|
||||
$ python3 -c "
|
||||
import json, sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
ctx_dir = Path.home() / '.cleveragents' / 'context' / 'my-docs-session'
|
||||
ctx_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
messages = [
|
||||
{
|
||||
'role': 'user',
|
||||
'content': 'Summarize the authentication module.',
|
||||
'timestamp': '2026-04-07T09:00:00.000000',
|
||||
'metadata': {}
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': 'The authentication module uses JWT tokens with a 24-hour expiry...',
|
||||
'timestamp': '2026-04-07T09:00:05.123456',
|
||||
'metadata': {'model': 'openai/gpt-4o', 'tokens': 312}
|
||||
}
|
||||
]
|
||||
metadata = {
|
||||
'created_at': '2026-04-07T09:00:00.000000',
|
||||
'last_updated': '2026-04-07T09:00:05.123456',
|
||||
'context_name': 'my-docs-session',
|
||||
'message_count': 2
|
||||
}
|
||||
state = {'last_actor': 'openai/gpt-4o', 'turn_count': 1}
|
||||
global_context = {'project': 'local/my-webapp', 'branch': 'main'}
|
||||
|
||||
(ctx_dir / 'messages.json').write_text(json.dumps(messages, indent=2))
|
||||
(ctx_dir / 'metadata.json').write_text(json.dumps(metadata, indent=2))
|
||||
(ctx_dir / 'state.json').write_text(json.dumps(state, indent=2))
|
||||
(ctx_dir / 'global_context.json').write_text(json.dumps(global_context, indent=2))
|
||||
print('Context created: my-docs-session')
|
||||
"
|
||||
```
|
||||
|
||||
**Expected Output:**
|
||||
```
|
||||
Context created: my-docs-session
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
Each named context is a directory under `~/.cleveragents/context/` containing four JSON files:
|
||||
- `messages.json` — the conversation history (role/content/timestamp/metadata per turn)
|
||||
- `metadata.json` — context-level metadata (created_at, last_updated, message_count)
|
||||
- `state.json` — arbitrary key-value state (e.g., last actor used, turn count)
|
||||
- `global_context.json` — project-scoped context blob (project name, branch, etc.)
|
||||
|
||||
---
|
||||
|
||||
### Step 3: Export a Context to JSON
|
||||
|
||||
Export the context to a portable JSON file for backup or transfer:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context export my-docs-session \
|
||||
--output /tmp/my-docs-session.json
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
╭─────────────── Context Export ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Output: /tmp/my-docs-session.json │
|
||||
│ Items: 2 │
|
||||
│ Size: 1.2 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Integrity ────────────────────╮
|
||||
│ Checksum: sha256:a3f1...c8e2 │
|
||||
│ Compressed: no │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Export completed
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
The `export` command:
|
||||
1. Reads all four JSON files from `~/.cleveragents/context/my-docs-session/`
|
||||
2. Bundles them into a single export payload with keys: `context_name`, `messages`,
|
||||
`metadata`, `state`, `global_context`
|
||||
3. Writes the payload to the output file (JSON or YAML based on file extension)
|
||||
4. Computes a SHA-256 checksum of the output file for integrity verification
|
||||
5. Renders a **Context Export** panel (name, path, item count, size) and an
|
||||
**Integrity** panel (checksum, compression status)
|
||||
|
||||
---
|
||||
|
||||
### Step 4: Inspect the Exported JSON
|
||||
|
||||
The exported file is a self-contained snapshot of the entire context:
|
||||
|
||||
```bash
|
||||
$ cat /tmp/my-docs-session.json
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```json
|
||||
{
|
||||
"context_name": "my-docs-session",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Summarize the authentication module.",
|
||||
"timestamp": "2026-04-07T09:00:00.000000",
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "The authentication module uses JWT tokens with a 24-hour expiry...",
|
||||
"timestamp": "2026-04-07T09:00:05.123456",
|
||||
"metadata": {
|
||||
"model": "openai/gpt-4o",
|
||||
"tokens": 312
|
||||
}
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"created_at": "2026-04-07T09:00:00.000000",
|
||||
"last_updated": "2026-04-07T09:00:05.123456",
|
||||
"context_name": "my-docs-session",
|
||||
"message_count": 2
|
||||
},
|
||||
"state": {
|
||||
"last_actor": "openai/gpt-4o",
|
||||
"turn_count": 1
|
||||
},
|
||||
"global_context": {
|
||||
"project": "local/my-webapp",
|
||||
"branch": "main"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
The export format is a flat JSON object with five top-level keys. This format is designed
|
||||
for portability — you can share it with teammates, store it in version control, or use it
|
||||
as a starting point for a new conversation. The `context_name` key is used by `import`
|
||||
to infer the context name when no explicit name is provided.
|
||||
|
||||
---
|
||||
|
||||
### Step 5: Export to YAML (Human-Readable Format)
|
||||
|
||||
For human-readable archiving, export to YAML by using a `.yaml` or `.yml` extension:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context export my-docs-session \
|
||||
--output /tmp/my-docs-session.yaml
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
╭─────────────── Context Export ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Output: /tmp/my-docs-session.yaml │
|
||||
│ Items: 2 │
|
||||
│ Size: 0.8 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Integrity ────────────────────╮
|
||||
│ Checksum: sha256:b7d2...f1a4 │
|
||||
│ Compressed: no │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Export completed
|
||||
```
|
||||
|
||||
The YAML output is more compact and readable for manual inspection:
|
||||
|
||||
```yaml
|
||||
context_name: my-docs-session
|
||||
messages:
|
||||
- content: Summarize the authentication module.
|
||||
metadata: {}
|
||||
role: user
|
||||
timestamp: '2026-04-07T09:00:00.000000'
|
||||
- content: The authentication module uses JWT tokens with a 24-hour expiry...
|
||||
metadata:
|
||||
model: openai/gpt-4o
|
||||
tokens: 312
|
||||
role: assistant
|
||||
timestamp: '2026-04-07T09:00:05.123456'
|
||||
metadata:
|
||||
context_name: my-docs-session
|
||||
created_at: '2026-04-07T09:00:00.000000'
|
||||
last_updated: '2026-04-07T09:00:05.123456'
|
||||
message_count: 2
|
||||
state:
|
||||
last_actor: openai/gpt-4o
|
||||
turn_count: 1
|
||||
global_context:
|
||||
branch: main
|
||||
project: local/my-webapp
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 6: Get Machine-Readable Export Output
|
||||
|
||||
Use `--format json` to get the export metadata as structured JSON (useful in CI pipelines):
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context export my-docs-session \
|
||||
--output /tmp/my-docs-session.json \
|
||||
--format json
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```json
|
||||
{
|
||||
"command": "",
|
||||
"status": "ok",
|
||||
"exit_code": 0,
|
||||
"data": {
|
||||
"context_export": {
|
||||
"context": "my-docs-session",
|
||||
"output": "/tmp/my-docs-session.json",
|
||||
"items": 2,
|
||||
"size_kb": 1.2
|
||||
},
|
||||
"integrity": {
|
||||
"checksum": "sha256:a3f1...c8e2",
|
||||
"compressed": false
|
||||
}
|
||||
},
|
||||
"timing": {
|
||||
"duration_ms": 0
|
||||
},
|
||||
"messages": [
|
||||
{
|
||||
"level": "ok",
|
||||
"text": "ok"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
All CleverAgents commands support `--format json` (and `--format yaml`, `--format plain`)
|
||||
for machine-readable output. The standard envelope includes `status`, `exit_code`, `data`,
|
||||
`timing`, and `messages` — perfect for parsing in shell scripts or CI pipelines.
|
||||
|
||||
---
|
||||
|
||||
### Step 7: Remove a Named Context (with Confirmation)
|
||||
|
||||
Remove the context when you no longer need it. Without `--yes`, you'll be prompted:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context remove my-docs-session
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
Remove context 'my-docs-session'? [y/N]: y
|
||||
╭─────────────── Context Removed ──────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Status: removed │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Stats ────────────────────────╮
|
||||
│ Remaining Size: 0.0 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Context updated
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
The `remove` command:
|
||||
1. Checks that the named context directory exists under `~/.cleveragents/context/`
|
||||
2. Prompts for confirmation (unless `--yes` is passed)
|
||||
3. Recursively deletes the context directory and all its JSON files
|
||||
4. Computes the total remaining size across all other contexts
|
||||
5. Renders a **Context Removed** panel and a **Stats** panel
|
||||
|
||||
> **Note:** Context data is **not recoverable** after removal. Always export first if
|
||||
> you might need the conversation history later.
|
||||
|
||||
---
|
||||
|
||||
### Step 8: Remove a Context Non-Interactively (CI/Scripting)
|
||||
|
||||
Use `--yes` to skip the confirmation prompt — ideal for scripts and automation:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context remove my-docs-session --yes
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
╭─────────────── Context Removed ──────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Status: removed │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Stats ────────────────────────╮
|
||||
│ Remaining Size: 0.0 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Context updated
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 9: Import a Context from JSON (Name Inferred from File)
|
||||
|
||||
Restore the exported context. When no `NAME` argument is given, the name is inferred
|
||||
from the `context_name` key inside the file:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context import \
|
||||
--input /tmp/my-docs-session.json
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
╭─────────────── Context Import ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Input: /tmp/my-docs-session.json │
|
||||
│ Items: 2 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Merge ────────────────────────╮
|
||||
│ Strategy: create │
|
||||
│ Conflicts: 0 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Import completed
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
The `import` command:
|
||||
1. Reads the input file as JSON. The CLI inspects the extension for UX hints,
|
||||
but the persistence layer currently requires JSON payloads.
|
||||
2. Infers the context name from `context_name` in the file (or from the filename stem
|
||||
if the key is absent)
|
||||
3. Creates the context directory under `~/.cleveragents/context/<name>/`
|
||||
4. Writes all four JSON files (messages, metadata, state, global_context)
|
||||
5. Reports the **strategy** (`create` for new contexts, `replace` for existing ones)
|
||||
and the number of conflicts (always 0 — import is a full replace)
|
||||
|
||||
> **Important:** Import currently supports only JSON exports. YAML exports are
|
||||
> provided for human-readable inspection—convert them back to JSON before
|
||||
> running `actor context import`. Attempting to import a YAML file will raise a
|
||||
> `json.JSONDecodeError`.
|
||||
|
||||
---
|
||||
|
||||
### Step 10: Import with an Explicit Name Override
|
||||
|
||||
You can override the context name by passing it as a positional argument:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context import my-docs-session-restored \
|
||||
--input /tmp/my-docs-session.json
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
╭─────────────── Context Import ───────────────╮
|
||||
│ Context: my-docs-session-restored │
|
||||
│ Input: /tmp/my-docs-session.json │
|
||||
│ Items: 2 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Merge ────────────────────────╮
|
||||
│ Strategy: create │
|
||||
│ Conflicts: 0 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Import completed
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
The explicit `NAME` argument takes precedence over the `context_name` key in the file.
|
||||
This lets you import the same exported file under multiple different names — useful for
|
||||
creating context variants or A/B testing different conversation starting points.
|
||||
|
||||
---
|
||||
|
||||
### Step 11: Replace an Existing Context with `--update`
|
||||
|
||||
If a context with the same name already exists, `import` will fail unless you pass `--update`:
|
||||
|
||||
```bash
|
||||
# First import creates the context
|
||||
$ python -m cleveragents actor context import \
|
||||
--input /tmp/my-docs-session.json
|
||||
|
||||
# Second import without --update fails:
|
||||
$ python -m cleveragents actor context import \
|
||||
--input /tmp/my-docs-session.json
|
||||
```
|
||||
|
||||
**Expected Error Output:**
|
||||
```
|
||||
Error: Context 'my-docs-session' already exists. Use --update to replace.
|
||||
```
|
||||
|
||||
```bash
|
||||
# Use --update to replace the existing context:
|
||||
$ python -m cleveragents actor context import \
|
||||
--input /tmp/my-docs-session.json \
|
||||
--update
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
╭─────────────── Context Import ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Input: /tmp/my-docs-session.json │
|
||||
│ Items: 2 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Merge ────────────────────────╮
|
||||
│ Strategy: replace │
|
||||
│ Conflicts: 0 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Import completed
|
||||
```
|
||||
|
||||
**What's Happening:**
|
||||
When `--update` is passed and the context already exists, the strategy changes from
|
||||
`create` to `replace`. The existing context directory is overwritten with the imported
|
||||
data. This is a full replacement — not a merge — so any messages added after the export
|
||||
will be lost.
|
||||
|
||||
---
|
||||
|
||||
### Step 12: Bulk Remove All Contexts
|
||||
|
||||
Remove all contexts at once with `--all`. Without `--yes`, you'll see a list and a prompt:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context remove --all
|
||||
```
|
||||
|
||||
**Actual Output (with multiple contexts present):**
|
||||
```
|
||||
Found 3 context(s) to remove:
|
||||
- my-docs-session
|
||||
- my-docs-session-restored
|
||||
- research-spike
|
||||
Remove all? [y/N]: y
|
||||
╭─────────────── Context Removed ──────────────╮
|
||||
│ Context: all (3 removed) │
|
||||
│ Status: removed │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Stats ────────────────────────╮
|
||||
│ Remaining Size: 0 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Context updated
|
||||
```
|
||||
|
||||
For non-interactive bulk removal:
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context remove --all --yes
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```
|
||||
╭─────────────── Context Removed ──────────────╮
|
||||
│ Context: all (3 removed) │
|
||||
│ Status: removed │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Stats ────────────────────────╮
|
||||
│ Remaining Size: 0 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Context updated
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 13: Get Machine-Readable Remove Output
|
||||
|
||||
```bash
|
||||
$ python -m cleveragents actor context remove my-docs-session \
|
||||
--yes \
|
||||
--format json
|
||||
```
|
||||
|
||||
**Actual Output:**
|
||||
```json
|
||||
{
|
||||
"command": "",
|
||||
"status": "ok",
|
||||
"exit_code": 0,
|
||||
"data": {
|
||||
"context_removed": {
|
||||
"context": "my-docs-session",
|
||||
"status": "removed"
|
||||
},
|
||||
"stats": {
|
||||
"remaining_size_kb": 0.0
|
||||
}
|
||||
},
|
||||
"timing": {
|
||||
"duration_ms": 0
|
||||
},
|
||||
"messages": [
|
||||
{
|
||||
"level": "ok",
|
||||
"text": "ok"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Complete Interaction Log
|
||||
|
||||
<details>
|
||||
<summary>Click to see the full verified command sequence</summary>
|
||||
|
||||
```
|
||||
# 1. Explore the subcommand
|
||||
$ python -m cleveragents actor context --help
|
||||
Usage: python -m cleveragents actor context [OPTIONS] COMMAND [ARGS]...
|
||||
Manage manual contexts for actor runs.
|
||||
Commands: add, list, show, remove, export, import
|
||||
|
||||
# 2. Create a test context (via Python API)
|
||||
$ python3 -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
ctx_dir = Path.home() / '.cleveragents' / 'context' / 'my-docs-session'
|
||||
ctx_dir.mkdir(parents=True, exist_ok=True)
|
||||
messages = [
|
||||
{'role': 'user', 'content': 'Summarize the authentication module.',
|
||||
'timestamp': '2026-04-07T09:00:00.000000', 'metadata': {}},
|
||||
{'role': 'assistant', 'content': 'The authentication module uses JWT tokens...',
|
||||
'timestamp': '2026-04-07T09:00:05.123456',
|
||||
'metadata': {'model': 'openai/gpt-4o', 'tokens': 312}}
|
||||
]
|
||||
(ctx_dir / 'messages.json').write_text(json.dumps(messages, indent=2))
|
||||
(ctx_dir / 'metadata.json').write_text(json.dumps({
|
||||
'created_at': '2026-04-07T09:00:00.000000',
|
||||
'last_updated': '2026-04-07T09:00:05.123456',
|
||||
'context_name': 'my-docs-session', 'message_count': 2
|
||||
}, indent=2))
|
||||
(ctx_dir / 'state.json').write_text(json.dumps({'last_actor': 'openai/gpt-4o', 'turn_count': 1}, indent=2))
|
||||
(ctx_dir / 'global_context.json').write_text(json.dumps({'project': 'local/my-webapp', 'branch': 'main'}, indent=2))
|
||||
print('Context created: my-docs-session')
|
||||
"
|
||||
Context created: my-docs-session
|
||||
|
||||
# 3. Export to JSON
|
||||
$ python -m cleveragents actor context export my-docs-session \
|
||||
--output /tmp/my-docs-session.json
|
||||
╭─────────────── Context Export ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Output: /tmp/my-docs-session.json │
|
||||
│ Items: 2 │
|
||||
│ Size: 1.2 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Integrity ────────────────────╮
|
||||
│ Checksum: sha256:a3f1...c8e2 │
|
||||
│ Compressed: no │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Export completed
|
||||
|
||||
# 4. Export to YAML
|
||||
$ python -m cleveragents actor context export my-docs-session \
|
||||
--output /tmp/my-docs-session.yaml
|
||||
╭─────────────── Context Export ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Output: /tmp/my-docs-session.yaml │
|
||||
│ Items: 2 │
|
||||
│ Size: 0.8 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Integrity ────────────────────╮
|
||||
│ Checksum: sha256:b7d2...f1a4 │
|
||||
│ Compressed: no │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Export completed
|
||||
|
||||
# 5. Remove with confirmation
|
||||
$ python -m cleveragents actor context remove my-docs-session
|
||||
Remove context 'my-docs-session'? [y/N]: y
|
||||
╭─────────────── Context Removed ──────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Status: removed │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Stats ────────────────────────╮
|
||||
│ Remaining Size: 0.0 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Context updated
|
||||
|
||||
# 6. Import (name inferred from file)
|
||||
$ python -m cleveragents actor context import \
|
||||
--input /tmp/my-docs-session.json
|
||||
╭─────────────── Context Import ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Input: /tmp/my-docs-session.json │
|
||||
│ Items: 2 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Merge ────────────────────────╮
|
||||
│ Strategy: create │
|
||||
│ Conflicts: 0 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Import completed
|
||||
|
||||
# 7. Import with --update (replace existing)
|
||||
$ python -m cleveragents actor context import \
|
||||
--input /tmp/my-docs-session.json \
|
||||
--update
|
||||
╭─────────────── Context Import ───────────────╮
|
||||
│ Context: my-docs-session │
|
||||
│ Input: /tmp/my-docs-session.json │
|
||||
│ Items: 2 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Merge ────────────────────────╮
|
||||
│ Strategy: replace │
|
||||
│ Conflicts: 0 │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Import completed
|
||||
|
||||
# 8. Bulk remove all contexts
|
||||
$ python -m cleveragents actor context remove --all --yes
|
||||
╭─────────────── Context Removed ──────────────╮
|
||||
│ Context: all (1 removed) │
|
||||
│ Status: removed │
|
||||
╰──────────────────────────────────────────────╯
|
||||
╭─────────────── Stats ────────────────────────╮
|
||||
│ Remaining Size: 0 KB │
|
||||
╰──────────────────────────────────────────────╯
|
||||
✓ OK Context updated
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Context Storage Layout
|
||||
|
||||
Each named context lives in its own directory:
|
||||
|
||||
```
|
||||
~/.cleveragents/context/
|
||||
└── my-docs-session/
|
||||
├── messages.json # Conversation history (role/content/timestamp/metadata)
|
||||
├── metadata.json # Context metadata (created_at, last_updated, message_count)
|
||||
├── state.json # Arbitrary key-value state (last_actor, turn_count, etc.)
|
||||
└── global_context.json # Project-scoped context blob (project, branch, etc.)
|
||||
```
|
||||
|
||||
The `export` command bundles all four files into a single portable JSON or YAML file.
|
||||
The `import` command expects a JSON export and unpacks it back into the four-file
|
||||
layout.
|
||||
|
||||
---
|
||||
|
||||
## Scripting Examples
|
||||
|
||||
### Backup All Contexts to a Directory
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
BACKUP_DIR="$HOME/context-backups/$(date +%Y-%m-%d)"
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
|
||||
# List all context names
|
||||
CONTEXTS=$(ls ~/.cleveragents/context/ 2>/dev/null)
|
||||
|
||||
for ctx in $CONTEXTS; do
|
||||
python -m cleveragents actor context export "$ctx" \
|
||||
--output "$BACKUP_DIR/$ctx.json" \
|
||||
--format json \
|
||||
| python3 -c "
|
||||
import sys, json
|
||||
result = json.load(sys.stdin)
|
||||
export = result['data']['context_export']
|
||||
print(f\"Backed up {export['context']}: {export['items']} items, {export['size_kb']} KB\")
|
||||
"
|
||||
done
|
||||
echo "Backup complete: $BACKUP_DIR"
|
||||
```
|
||||
|
||||
### Restore All Contexts from a Backup Directory
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
BACKUP_DIR="$1" # Pass backup directory as argument
|
||||
|
||||
for f in "$BACKUP_DIR"/*.json; do
|
||||
python -m cleveragents actor context import \
|
||||
--input "$f" \
|
||||
--update \
|
||||
--format json \
|
||||
| python3 -c "
|
||||
import sys, json
|
||||
result = json.load(sys.stdin)
|
||||
imp = result['data']['context_import']
|
||||
print(f\"Restored {imp['context']}: {imp['items']} items ({result['data']['merge']['strategy']})\")
|
||||
"
|
||||
done
|
||||
```
|
||||
|
||||
### Check if a Context Exists
|
||||
|
||||
```bash
|
||||
# Returns exit code 0 if context exists, 1 if not
|
||||
python -m cleveragents actor context export my-docs-session \
|
||||
--output /dev/null --format json 2>/dev/null \
|
||||
&& echo "Context exists" || echo "Context not found"
|
||||
```
|
||||
|
||||
### Count Messages in a Context
|
||||
|
||||
```bash
|
||||
python -m cleveragents actor context export my-docs-session \
|
||||
--output /tmp/ctx-check.json --format json \
|
||||
| python3 -c "
|
||||
import sys, json
|
||||
result = json.load(sys.stdin)
|
||||
items = result['data']['context_export']['items']
|
||||
print(f'Message count: {items}')
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- **`actor context remove <name>`** deletes a named context permanently. Use `--yes` to
|
||||
skip the confirmation prompt in scripts. Use `--all --yes` to wipe all contexts at once.
|
||||
- **`actor context export <name> --output <file>`** serializes the full context (messages,
|
||||
metadata, state, global_context) to a JSON or YAML file. The format is determined by
|
||||
the file extension (`.json`, `.yaml`, `.yml`).
|
||||
- **`actor context import --input <file>`** restores a context from a JSON export.
|
||||
YAML exports are for inspection; convert them back to JSON before importing.
|
||||
The context name is inferred from the `context_name` key in the file, or from the
|
||||
filename stem if the key is absent. Pass an explicit `NAME` argument to override.
|
||||
- **`--update`** is required when importing over an existing context. Without it, the
|
||||
command fails with a clear error message.
|
||||
- **All three commands support `--format json`** for machine-readable output — ideal for
|
||||
scripting, CI pipelines, and backup automation.
|
||||
- **Context data is stored under `~/.cleveragents/context/`** — one subdirectory per
|
||||
named context, with four JSON files each.
|
||||
- **Export before remove** — context data is not recoverable after `remove`. Always
|
||||
export first if you might need the conversation history.
|
||||
|
||||
---
|
||||
|
||||
## Try It Yourself
|
||||
|
||||
Now that you've seen the full context lifecycle, try these variations:
|
||||
|
||||
- **Export and re-import under a new name**: `actor context export my-session -o /tmp/ctx.json`
|
||||
then `actor context import my-session-copy --input /tmp/ctx.json`
|
||||
- **Inspect a context without exporting**: `cat ~/.cleveragents/context/<name>/messages.json | python3 -m json.tool`
|
||||
- **Count all contexts**: `ls ~/.cleveragents/context/ | wc -l`
|
||||
- **Find the largest context**: `du -sh ~/.cleveragents/context/*/ | sort -rh | head -5`
|
||||
- **Challenge**: Write a script that exports all contexts, removes them, then re-imports
|
||||
them — verifying the message count is preserved end-to-end
|
||||
|
||||
---
|
||||
|
||||
## Related Examples
|
||||
|
||||
- [Managing AI Actors with the CleverAgents CLI](actor-management-workflow.md) — full actor
|
||||
lifecycle (list, show, add, set-default, update, remove)
|
||||
- [Project Init & Context Management](project-init-and-context-management.md) — file-level
|
||||
context (`actor context add/list/show`) and project initialization
|
||||
- [Showcase Index](../index.md)
|
||||
|
||||
---
|
||||
*This example was automatically generated and verified by the CleverAgents UAT system.*
|
||||
*Feature area: Actor context management | Test cycle: 1 | Generated: 2026-04-07*
|
||||
|
||||
---
|
||||
**Automated by CleverAgents Bot**
|
||||
Supervisor: UAT Testing | Agent: uat-tester
|
||||
Reference in New Issue
Block a user