---
title: Session、上下文与 Memory
description: 恢复持久 Session，理解上下文压缩，并把跨 Session Memory 与对话历史分开。
---

下面三项能力看起来都像“Agent 记得了”，但解决的是不同问题：

| 能力 | 作用范围 | 持久事实来源 |
| --- | --- | --- |
| Session | 跨多个 Turn 的一段对话 | Append-only Session Event |
| Context Compaction | 长 Session 中有边界的 Model Input | 从 Session 派生的 Checkpoint；原始日志保持不变 |
| Memory | 跨 Session 复用的上下文 | 单独配置的 Memory Plugin |

不要用 Memory 代替 Session 历史，也不要把压缩摘要当作权威对话记录。

## 恢复一个 Session

默认 Session Adapter 会把事务化历史写入
`~/.lenso/agent/sessions.sqlite3`。通过同一个 Profile 启动或恢复：

```sh
lenso-agent --profile code
lenso-agent --profile code --session <session-id>
lenso-agent-cli --profile code --session <session-id> \
  "Continue the review."
```

检查哪些不可变 Generation 接纳了其中的 Turn：

```sh
lenso-agent-cli sessions provenance --session <session-id>
```

Session Storage 会 Fail Closed。选定的持久 Store 不可用时，Host 不会静默退回
内存 Transcript。

## 选择另一个 Session Adapter

SQLite 是默认实现。只有在透明文件或小型 Fixture 比并发事务存储更重要时，才选择
File Adapter：

```toml title="plugins/lenso.agent.session.file/local.toml"
directory = "/absolute/path/to/.lenso/agent/sessions"
```

```toml title="profiles/file-sessions.toml"
description = "File-backed sessions"
instances = ["lenso.agent.session.file/local"]
```

迁移是通过 `sessions export`、`sessions import` 或 `sessions migrate` 完成的显式
Operator 动作；切换 Adapter 不会隐式复制或覆盖历史。

## 让长 Session 保持可用

Context Compaction 会缩小 Model Input，但不会删除权威 Session Log。内置离线
Adapter 会保留有边界的抽取式摘要与近期 Turn：

```toml title="plugins/lenso.agent.context-compaction/context-compactor.toml"
max_input_characters = 1048576
max_summary_characters = 8192
retain_recent_turns = 8
```

Agent Loop 决定何时压缩，并把 Checkpoint 记录为持久 Session Fact。替换 Compactor
只会改变投影算法，不会改变 Session 所有权。

## 有意识地添加跨 Session Memory

默认本地 Memory Adapter 使用 SQLite 与 FTS5。为每种 Experience 设置清晰 Scope，
不要全局共享所有召回内容：

```toml title="plugins/lenso.agent.memory.sqlite/memory.toml"
database = "/absolute/path/to/.lenso/agent/code-memory.sqlite3"
scope = "code"
max_records = 10000
max_item_characters = 16384
max_recall_items = 8
max_recall_characters = 16384
```

召回的 Memory 是低权限 Request Context。它不能重写 Session 级 System
Instruction，也不能授予新的 Tool 权限。

继续阅读[选择 Profile 与 Tool 权限](/docs/zh/agent/profiles-and-tools)，了解如何为
不同 Experience 隔离 Storage 与 Memory Instance。
