# 记忆

写入、提炼、审核、更正和遗忘记忆，以及离线整理记忆。

## 记忆模型

`/v2/memories` 用统一结构返回三种来源：账户记忆、以 Entry 写入的记忆、从 Entry 提炼的事实。只有以 Entry 写入的记忆，`id` 才是 Entry id。提炼的事实通过 `provenance` 关联到 Entry 和版本。

每条记忆有一个范围和一个状态：范围决定记忆归谁（[DevMemoryScope](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryScope)），状态决定检索是否使用它（[DevMemoryStatus](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryStatus)）。

遗忘是物理删除，没有正文可返回，所以没有 `forgotten` 状态。

## 写入记忆

一句始终成立的陈述，例如偏好或决定，用 [`POST /v2/memories`](https://mirabase.io/zh/developers/api/memories.md#memories-create) 写入。写入后立即为 `confirmed`，此后的上下文和回答都会使用。同一内容不会重复写入，各范围需要的权限见参考。

curl:

```bash
curl -X POST https://api.mirabase.dev/v2/memories \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"scope": "project", "space_id": "'$SPACE_ID'", "kind": "decision", "text": "Releases go out on Thursdays."}'
```

TypeScript:

```ts
const memory = await mirabase.memories.create({
  scope: "project",
  space_id: spaceId,
  kind: "decision",
  text: "Releases go out on Thursdays.",
});
```

Python:

```python
memory = mb.memories.create({
    "scope": "project",
    "space_id": space_id,
    "kind": "decision",
    "text": "Releases go out on Thursdays.",
})
```

## 从对话中提炼记忆

若要提出候选而非直接写入，请导入对话：[`POST /v2/spaces/{space_id}/ingest`](https://mirabase.io/zh/developers/api/ingest.md#ingest-ingest) 带 `kind: conversation`、`session_id` 和 `messages`，返回 202。一个批次是一个 Entry，无论有多少轮。发送时持有 `memory:confirm`，提炼出的事实即是 `confirmed`，否则是 `candidate`；回执的 `memory_status` 说明是哪一种。

curl:

```bash
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/ingest" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Idempotency-Key: chat-42-batch-1" \
  -H "Content-Type: application/json" \
  -d '{"kind": "conversation", "session_id": "chat-42", "messages": [
    {"role": "user", "content": "Let us ship on Thursdays from now on.", "timestamp": 1762416000000},
    {"role": "assistant", "content": "Noted: releases on Thursdays."}
  ]}'
```

TypeScript:

```ts
const receipt = await mirabase.conversations.add(
  [
    { role: "user", content: "Let us ship on Thursdays from now on.", timestamp: 1762416000000 },
    { role: "assistant", content: "Noted: releases on Thursdays." },
  ],
  { sessionId: "chat-42", idempotencyKey: "chat-42-batch-1" },
);
```

Python:

```python
receipt = mb.conversations.add(
    [
        {"role": "user", "content": "Let us ship on Thursdays from now on.", "timestamp": 1762416000000},
        {"role": "assistant", "content": "Noted: releases on Thursdays."},
    ],
    session_id="chat-42",
    idempotency_key="chat-42-batch-1",
)
```

提炼在索引完成后进行，因此处理任务变为 `succeeded` 时，记忆可能尚未生成。轮询 [`GET /v2/entries/{entry_id}/processing`](https://mirabase.io/zh/developers/api/entries.md#entries-processing)，直到 `memory.state` 不再为 `pending`：`ready` 时用 [`GET /v2/memories?entry_id=`](https://mirabase.io/zh/developers/api/memories.md#memories-list) 列出该批次生成的记忆；`skipped` 表示该版本不提炼，原因见下文；`failed` 表示提炼失败。

curl:

```bash
# Repeat until memory.state is no longer "pending".
# "skipped" means the batch is not distilled: memory.reason says why.
curl "https://api.mirabase.dev/v2/entries/$ENTRY_ID/processing" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Then list what the batch wrote.
curl "https://api.mirabase.dev/v2/memories?entry_id=$ENTRY_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

TypeScript:

```ts
let processing = await mirabase.entries.processing(receipt.entry_id);
for (let attempt = 0; attempt < 30 && processing.memory?.state === "pending"; attempt += 1) {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  processing = await mirabase.entries.processing(receipt.entry_id);
}

if (processing.memory?.state === "skipped") {
  // Not distilled. reason says why, for example "model_not_configured";
  // remediation.action, when present, says what to do.
  console.log(processing.memory.reason, processing.memory.remediation?.action);
} else {
  for await (const memory of mirabase.memories.list({ entry: receipt.entry_id })) {
    console.log(memory.status, memory.text);
  }
}
```

Python:

```python
import time

processing = mb.entries.processing(receipt["entry_id"])
for _ in range(30):
    if processing.get("memory", {}).get("state") != "pending":
        break
    time.sleep(2)
    processing = mb.entries.processing(receipt["entry_id"])

memory_state = processing.get("memory", {})
if memory_state.get("state") == "skipped":
    # Not distilled. reason says why, for example "model_not_configured";
    # remediation["action"], when present, says what to do.
    print(memory_state.get("reason"), memory_state.get("remediation", {}).get("action"))
else:
    for memory in mb.memories.list(entry=receipt["entry_id"]):
        print(memory["status"], memory["text"])
```

- 同一批次重复导入会产生两个 Entry，因此重试时请携带 `Idempotency-Key`，见 [幂等](https://mirabase.io/zh/developers/conventions.md#idempotency)。
- 持续记录同一段对话时，每个批次使用相同的 `session_id`。该 id 也会存为元数据键 `session_id`，因此 [`GET /v2/entries?metadata={"session_id":"…"}`](https://mirabase.io/zh/developers/api/entries.md#entries-list) 可将它们一并列出，检索时可用 `filter.metadata` 限定到该对话。
- `proposal` 模式的 Agent 导入时，提炼结果总是 `candidate`。

### 提炼被跳过的原因

写入回执、处理状态和任务中的 `memory` 是同一个对象。`state` 为 `skipped` 时，`reason` 说明原因；原因可以处理时还带 `remediation`，按其中的 `remediation.action` 处理，例如部署没有配置提炼模型时，改为直接 [写入记忆](https://mirabase.io/zh/developers/memory.md#create)。部署不提炼记忆或 Entry 带有 `memory_exclude` 时，写入回执即为 `skipped`，无需轮询。`distill_disabled`、`model_not_configured` 和 `distill_paused` 涉及部署配置和账户用量，只有属于 `tenant_admin` 或持有 `knowledge:manage`、且未收窄到 Space 或元数据范围的 Key 能看到；其他 Key 看到的是 `distill_unavailable`（替代前两个）；`distill_paused` 不返回原因，状态仍为 `pending`。部署停止提炼之前已经提炼完成的版本仍为 `ready`。全部原因和对应的处理方式见 [DevMemoryProcessingReason](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryProcessingReason) 和 [remediation](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryProcessing.remediation)。

## 审核、更正和遗忘记忆

```bash
# Candidates waiting for review in one Space.
curl "https://api.mirabase.dev/v2/memories?space_id=$SPACE_ID&status=candidate" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Confirm one, or send "reject".
curl -X POST "https://api.mirabase.dev/v2/memories/$MEMORY_ID/review" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"decision": "confirm"}'

# Replace it with what is true now. The response is a new memory whose supersedes names the old one.
curl -X POST "https://api.mirabase.dev/v2/memories/$MEMORY_ID/correct" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Releases go out on Wednesdays."}'

# Where it came from.
curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID/provenance" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Forget it for good.
curl -X DELETE "https://api.mirabase.dev/v2/memories/$MEMORY_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

- 候选记忆需由人工审核：用 [`POST /v2/memories/{memory_id}/review`](https://mirabase.io/zh/developers/api/memories.md#memories-review) 确认或驳回。
- 内容有误时用 [`POST /v2/memories/{memory_id}/correct`](https://mirabase.io/zh/developers/api/memories.md#memories-correct) 写入正确的陈述，旧记忆关闭并保留为历史；新写入的记忆或更正可在 30 分钟内用 [`POST /v2/memories/{memory_id}/undo`](https://mirabase.io/zh/developers/api/memories.md#memories-undo) 撤销。
- [`DELETE /v2/memories/{memory_id}`](https://mirabase.io/zh/developers/api/memories.md#memories-forget) 永久遗忘，不能撤销。驳回或遗忘一条提炼事实后，同一句话不会在这个 Space 里再被提炼。
- [`GET /v2/memories/{memory_id}/provenance`](https://mirabase.io/zh/developers/api/memories.md#memories-provenance) 列出一条记忆依据的 Entry 版本和引文。
- 不想让一份来源产生记忆时，用 [`PATCH /v2/entries/{entry_id}`](https://mirabase.io/zh/developers/api/entries.md#entries-update) 设置 `memory_exclude: true`：从它提炼的事实停用，搜索和读取不受影响。设回 `false` 会重新提炼，已遗忘或更正的内容不会恢复。

## MEMORY.md

`/.mirabase/memory/MEMORY.md` 是生成的只读视图，供开始工作的 Agent 读取该 Space 的记忆。同样的记忆产生同样的字节，`ETag` 是内容哈希，适合做 prompt 缓存前缀。用 [`GET /v2/spaces/{space_id}/files`](https://mirabase.io/zh/developers/api/files.md#files-read) 读取；它只有原始字节，写入返回 405 `virtual_file`。在默认写法中，从对话提炼的事实不包含在内，请使用 [`GET /v2/memories`](https://mirabase.io/zh/developers/api/memories.md#memories-list) 或检索。开启了离线整理的部署改用索引写法，并增加 `RECENT.md`，见 [索引写法](https://mirabase.io/zh/developers/memory.md#memory-index)。

```bash
# Send back the ETag you have. 304 means nothing changed.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/.mirabase/memory/MEMORY.md" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H 'If-None-Match: "<etag>"'
```

## 离线整理（dreams）

Agent 不在工作时，后台会整理已有的记忆。API 将一次整理运行称为一个 dream。它**只整理、不生成**：不写新记忆，不改记忆的正文，每个动作都带证据，都可以撤销。合并和取代只生成提案，模型不会自行修改任何记忆，经人工批准后才生效。

> **说明：** 离线整理是部署可选的功能。未开启该功能的部署上，本节和下面两节的接口都返回 404，`MEMORY.md` 保持上面的默认写法，也没有 `RECENT.md`。

### 它做什么

- 核对引文：将每条提炼记忆的逐字引文与来源 Entry 的当前版本比对。若所有引文均不再存在，则将该记忆标为休眠（`quote_missing`）。
- 找出闲置的记忆：长期未被取用、也无人确认过的提炼记忆，默认只写进报告，设置为 `apply` 时标为休眠（`unused`），再次被取用时恢复。
- 统计重复：找出表达同一内容的记忆组，并在报告里记录整理前后生效记忆的条数和 token 数（`view`）。
- 比较记忆：Space 所有者显式开启 `d4` 后，才会调用模型比较成对的提炼记忆，判断是否重复、谁取代谁、是否矛盾，结论只会成为 [整理提案](https://mirabase.io/zh/developers/memory.md#memory-proposals)。默认不调用模型。
- 自动运行：某个范围有新记忆时自动运行，也可以手动发起。

### 它不做什么

- 不生成：不写新记忆，不改记忆正文，不写 Entry、文件或版本，除 `MEMORY.md` 和 `RECENT.md` 外不写入任何内容。
- 模型不直接修改：模型只说明两条记忆的关系，并逐字引用来源，不写任何会进入记忆的文字，也不直接改动记忆。`auto` 档位尚未开放。
- 不改动人工确认的内容：审核通过的候选和带 `memory:confirm` 导入的对话里提炼出的记忆，既不会因为找不到引文而被标记，也不会因为闲置而休眠；以 Entry 写入的记忆和账户记忆，整理都不修改。只有未经人工审核就生效的提炼记忆才可能休眠，它们的状态也是 `status: "confirmed"`。
- 不恢复已遗忘的记忆：撤销一次整理也不会使其恢复。
- 不越界：只在一个范围里整理（Space 的项目记忆，或一个 Agent 的私有记忆），不跨范围，不跨 Space，不在分支上运行。
- 不删除：整理本身最重的动作是标记休眠；关闭一条记忆只发生在人批准提案之后，也可以撤销。物理删除只来自调用方的遗忘和彻底删除。

### 记忆分层

不同的记忆适用不同的规则：很少用到却重要的规则，不应因为较少使用而被搁置；事件有先后顺序，不应作为重复项合并。层由记忆的 `kind` 和有效时间决定，在整理时计算；记忆本身没有这个字段，提案和判定上带 `layer`。

四个层各包含哪些记忆、哪些层参与比较和生成整理提案，见 [DevMemoryLayer](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryLayer)；记忆闲置多久会休眠，见 [DevMemoryDormancyReason](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryDormancyReason)。

取代只在模型判断的新旧与来源的时间先后一致时才成立，否则降为矛盾（`conflict`），仅供人工查看。

### 休眠与唤醒

休眠的记忆带 `dormant: {reason, dream_id}`。它不再进入 `RECENT.md`，也不参与模型比较，但仍可列出和搜索。`MEMORY.md` 里只有人工写入和人工确认过的记忆，这些从不休眠。两种原因的条件和清除方式见 [DevMemoryDormancyReason](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryDormancyReason)。

- 解除休眠不需要调用专门接口：通过 [`GET /v2/memories/{memory_id}`](https://mirabase.io/zh/developers/api/memories.md#memories-read) 读取记忆，或搜索、上下文包、回答返回这条记忆时，记忆即被唤醒。读取 `MEMORY.md`、`RECENT.md` 和列表不算。
- 从 `apply` 改回 `report` 不清除已有的标记，如需清除请撤销那次整理。

### 设置：默认只出提案

每个 Space 有三个设置：`memory_dreaming`（默认 `propose`，整理照常运行；`off` 停止）、`dormancy`（默认 `report`，闲置的记忆只写进报告；`apply` 标为休眠）和 `d4`（默认 `off`，不调用模型；`shadow` 只记录判定；`propose` 把通过校验的判定写成提案）。在 `propose` 下，整理本身只做可撤销、不修改正文的标记；合并重复的记忆、用新记忆取代旧记忆、标出互相矛盾的记忆、把 Agent 的私有记忆提升到项目，这类改动只生成 [整理提案](https://mirabase.io/zh/developers/memory.md#memory-proposals)，由人工决定。只有 Space 所有者能修改设置。

curl:

```bash
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/settings" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Stop dreams for this Space. What they already did stays; undo a dream to take it back.
curl -X PATCH "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/settings" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"memory_dreaming": "off"}'

# Mark unused memories dormant, and let a model propose merges and supersessions.
curl -X PATCH "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/settings" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"dormancy": "apply", "d4": "propose"}'
```

TypeScript:

```ts
const settings = await mirabase.memory.settings.get();
// settings.memory_dreaming is "propose" unless someone changed it.

await mirabase.memory.settings.update("off");

// A field left out keeps its value. settings.d4_available says whether this deployment can ask a model.
await mirabase.memory.settings.update({ dormancy: "apply", d4: "propose" });
```

Python:

```python
settings = mb.memory.settings.get()
# settings["memory_dreaming"] is "propose" unless someone changed it.

mb.memory.settings.update("off")

# A field left out keeps its value. settings["d4_available"] says whether this deployment can ask a model.
mb.memory.settings.update(dormancy="apply", d4="propose")
```

- 先读一次报告再把 `dormancy` 改为 `apply`。
- 先用 `shadow` 运行一段时间并查看判定，再改为 `propose`：已记录的判定直接转为提案，无需再次调用模型。
- 响应里的 `d4_available` 为假时，这个部署不调用模型，无论 `d4` 如何设置。

### 发起、查看和撤销整理

[`POST /v2/spaces/{space_id}/memory/dreams`](https://mirabase.io/zh/developers/api/memory-dreaming.md#memorydreams-start) 立即发起一次整理，返回 202，`job_id` 即整理 id，用 [`GET /v2/jobs/{job_id}`](https://mirabase.io/zh/developers/api/jobs.md#jobs-read) 跟进。[`GET /v2/memory/dreams/{dream_id}`](https://mirabase.io/zh/developers/api/memory-dreaming.md#memorydreams-read) 是报告，[`GET /v2/memory/dreams/{dream_id}/actions`](https://mirabase.io/zh/developers/api/memory-dreaming.md#memorydreams-actions) 列出每个改动和理由，[`GET /v2/memory/dreams/{dream_id}/judgments`](https://mirabase.io/zh/developers/api/memory-dreaming.md#memorydreams-judgments) 列出模型比较过的每一对。[`POST /v2/memory/dreams/{dream_id}/undo`](https://mirabase.io/zh/developers/api/memory-dreaming.md#memorydreams-undo) 撤销整次整理。一个范围同一时间只有一次整理。

curl:

```bash
# Start one now. job_id is the dream id (drm_...).
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/dreams" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"scope": "project"}'

# Poll until status is succeeded or failed.
curl "https://api.mirabase.dev/v2/jobs/$DREAM_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# The report, then every change with its reason.
curl "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
curl "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID/actions" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Every pair a model was asked about, proposed or not.
curl "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID/judgments" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Take it back.
curl -X POST "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID/undo" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'
```

TypeScript:

```ts
const started = await mirabase.memory.dreams.start({ scope: "project" });
let job = await mirabase.jobs.get(started.job_id);
while (job.status === "queued" || job.status === "running") {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  job = await mirabase.jobs.get(started.job_id);
}

const dream = await mirabase.memory.dreams.get(started.job_id);
console.log(dream.counts.checked, dream.counts.dormant_marked, dream.view?.live_before, dream.view?.live_after);
for await (const action of mirabase.memory.dreams.actions(dream.id)) {
  console.log(action.seq, action.memory_id, action.action, action.reason, action.state);
}
for await (const judgment of mirabase.memory.dreams.judgments(dream.id)) {
  console.log(judgment.outcome, judgment.kind, judgment.member_ids, judgment.evidence);
}

if (dream.undoable) await mirabase.memory.dreams.undo(dream.id);
```

Python:

```python
started = mb.memory.dreams.start(scope="project")
# Polls until status is succeeded, failed, or cancelled.
mb.jobs.wait(started["job_id"])

dream = mb.memory.dreams.get(started["job_id"])
print(dream["counts"]["dormant_marked"], dream.get("view"))
for action in mb.memory.dreams.actions(dream["id"]):
    print(action["seq"], action["memory_id"], action["action"], action["reason"], action["state"])
for judgment in mb.memory.dreams.judgments(dream["id"]):
    print(judgment["outcome"], judgment.get("kind"), judgment["member_ids"], judgment.get("evidence"))

if dream["undoable"]:
    mb.memory.dreams.undo(dream["id"])
```

- 撤销针对整次整理，逐条进行：休眠标记清除，未处理的提案变为 `withdrawn`，已批准的合并和取代被还原。之后变更过的记忆保持不变，计入 `conflict_skipped`。
- 报告和动作只统计来源对调用方可见的记忆；`agent` 范围的整理只对对应 Agent 和 Space 所有者可见。

## 整理提案

离线整理提出但不自行执行的改动称为整理提案，与 [文件提案](https://mirabase.io/zh/developers/files.md#proposals) 不同。整理提案的种类见 [DevMemoryProposalKind](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryProposalKind)，状态见 [DevMemoryProposalStatus](https://mirabase.io/zh/developers/api/schemas.md#DevMemoryProposalStatus)。调用方必须能看到每个成员的来源才能看到该整理提案。

> **说明：** 只有 Space 的 `d4` 设置为 `propose` 且当前部署已配置模型（`d4_available` 为真）时，整理才会生成提案；否则列表为空。

### 逐字引文

模型不生成结论文字，因此目前始终不返回 `proposed_text`。判断依据都来自来源原文：`evidence` 每个条目带 `memory_id`、`entry_id`、`version_id` 和逐字的 `quote`，`times` 是决定新旧顺序的日期，`plan` 写明批准后保留哪条（`keep`）、关闭哪些（`close`）。引文必须在对应记忆的来源中逐字匹配，否则整组判定会被丢弃，不会成为提案。

curl:

```bash
# Open proposals of one dream, oldest first.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/proposals?dream_id=$DREAM_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Read the exact version a quote came from.
curl "https://api.mirabase.dev/v2/entries/$ENTRY_ID/content?view=text&version=$VERSION_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Carry it out. It takes effect only now.
curl -X POST "https://api.mirabase.dev/v2/memory/proposals/$PROPOSAL_ID/approve" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'

# Or close it without changing any memory.
curl -X POST "https://api.mirabase.dev/v2/memory/proposals/$OTHER_PROPOSAL_ID/reject" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'
```

TypeScript:

```ts
for await (const proposal of mirabase.memory.proposals.list({ dreamId: dream.id })) {
  console.log(proposal.kind, proposal.layer, proposal.plan, proposal.times);
  for (const { entry_id, version_id, quote } of proposal.evidence ?? []) {
    // Read the exact version the quote came from, and show both to the person deciding.
    const source = await mirabase.entries.content(entry_id, { view: "text", version: version_id });
    console.log(quote, source.text?.includes(quote));
  }
}

// Once a person has decided.
await mirabase.memory.proposals.approve(proposalId);
await mirabase.memory.proposals.reject(otherProposalId);
```

Python:

```python
proposals = mb.memory.proposals.list(dream_id=dream["id"]).to_list()
for proposal in proposals:
    print(proposal["kind"], proposal.get("layer"), proposal.get("plan"), proposal.get("times"))
    for evidence in proposal.get("evidence", []):
        # Read the exact version the quote came from, and show both to the person deciding.
        source = mb.entries.content(evidence["entry_id"], view="text", version=evidence["version_id"])
        print(evidence["quote"], evidence["quote"] in source.get("text", ""))

# Once a person has decided: proposal_id is the one approved, other_proposal_id the one rejected.
mb.memory.proposals.approve(proposal_id)
mb.memory.proposals.reject(other_proposal_id)
```

### 批准和驳回

[`POST /v2/memory/proposals/{proposal_id}/approve`](https://mirabase.io/zh/developers/api/memory-dreaming.md#memoryproposals-approve) 执行 `merge` 或 `supersede`：`plan.close` 中的记忆关闭，`plan.keep` 保留，正文不变。[`POST /v2/memory/proposals/{proposal_id}/reject`](https://mirabase.io/zh/developers/api/memory-dreaming.md#memoryproposals-reject) 关闭提案，不修改任何记忆。

- `conflict` 和 `promote` 不能批准。矛盾需要通过 [更正或遗忘](https://mirabase.io/zh/developers/memory.md#govern) 其中一条来解决，或者直接驳回。
- 撤销批准：[撤销那次整理](https://mirabase.io/zh/developers/memory.md#dreams)。撤销针对整次整理，不能只撤销其中一条提案。

### 从记忆查找提案

开启了离线整理的部署上，[`GET /v2/memories`](https://mirabase.io/zh/developers/api/memories.md#memories-list) 和 [`GET /v2/memories/{memory_id}`](https://mirabase.io/zh/developers/api/memories.md#memories-read) 会在有待处理提案时返回 `pending_proposals`：关于这条记忆（或它所在组的成员）的提案 id，最早的在前，只包含调用方可见的提案，没有时不返回。要在界面上为这条记忆显示“待处理”标记，用这个字段即可。

curl:

```bash
# pending_proposals is present only when there are open proposals you can see.
curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

curl "https://api.mirabase.dev/v2/memory/proposals/$PROPOSAL_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

TypeScript:

```ts
const memory = await mirabase.memories.get("distill:ent_7f20:fact_31");

for (const id of memory.pending_proposals ?? []) {
  const proposal = await mirabase.memory.proposals.get(id);
  console.log(proposal.kind, proposal.plan, proposal.evidence);
}
```

Python:

```python
memory = mb.memories.get("distill:ent_7f20:fact_31")

for pending_id in memory.get("pending_proposals", []):
    proposal = mb.memory.proposals.get(pending_id)
    print(proposal["kind"], proposal.get("plan"), proposal.get("evidence"))
```

## MEMORY.md 的索引写法与 RECENT.md

开启了离线整理的部署上，`MEMORY.md` 是一份索引：按“规则和偏好”“决定和进度”“事实”分节，一行一条记忆，行尾是 `[m1]` 这样的引用号，文件末尾的 `References` 表把引用号映射到记忆 id。内容是人工写入的记忆（账户记忆、以 Entry 写入的记忆）和人工确认过的提炼记忆，这些都不会休眠；内容相同的记忆只出现一次。

```markdown
# Memory

## Rules and preferences

- Keep answers short and in English. [m1]

## Decisions and progress

- Releases go out on Thursdays. [m2]

## Facts

- The staging database runs PostgreSQL 16. [m3]

## References

[m1]: mem_5d02
[m2]: ent_9a41
[m3]: distill:ent_7f20:fact_31
```

- 整份最多 2,000 token，其中提炼记忆最多占 800 token。写不下的不截断，整条略去，最后一行写 `… N more: GET /v2/memories?space_id=...`。
- 不写日期和时间。排序只随内容变化：先列人工写入的记忆，再列人工确认过的提炼记忆，提炼记忆按新近度和 id 排序，不看取用次数。所以检索命中不会让 `ETag` 变化，它以 `mf2.` 开头，仍然适合做 prompt 缓存前缀。

`/.mirabase/memory/RECENT.md` 是第二个生成文件：这个 Space 最近 7 天写入的项目记忆和 Agent 记忆，包括尚未审核的候选，最新的在前，最多 50 条、1,000 token。每行标明类型和状态，引用号格式为 `[r1]`，`ETag` 以 `rf1.` 开头。账户记忆和休眠的记忆不在其中。读写规则与 `MEMORY.md` 相同。

```markdown
# Recent memory

- (decision, confirmed) Releases go out on Thursdays. [r1]
- (preference, candidate) Use metric units in reports. [r2]

## References

[r1]: ent_9a41
[r2]: distill:ent_7f20:fact_44
```

curl:

```bash
# The stable part: send back the ETag you have, 304 means nothing changed.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/.mirabase/memory/MEMORY.md" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H 'If-None-Match: "mf2.<sha256>"'

# The part that moves: what was written in the last 7 days.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/.mirabase/memory/RECENT.md" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

TypeScript:

```ts
const index = await mirabase.files.read("/.mirabase/memory/MEMORY.md");
const recent = await mirabase.files.read("/.mirabase/memory/RECENT.md");

// MEMORY.md first, as the cached prefix; RECENT.md later, where the prompt changes anyway.
const prompt = [index.text(), recent.text()].join("\n");
```

Python:

```python
index = mb.files.read("/.mirabase/memory/MEMORY.md")
recent = mb.files.read("/.mirabase/memory/RECENT.md")

# MEMORY.md first, as the cached prefix; RECENT.md later, where the prompt changes anyway.
prompt = index.text() + "\n" + recent.text()

# Later, send back the ETag you have: None means nothing changed.
newer = mb.files.read_if_changed("/.mirabase/memory/MEMORY.md", index.etag)
```

- 把 `MEMORY.md` 放在提示词前部做稳定前缀，`RECENT.md` 放在后部经常变化的地方。
- 两个文件都只包含调用方可见的记忆，因此不同调用方可能获得不同的字节和 `ETag`。

## 按 id 读取记忆

索引里只有一句话和一个 id。如需详情，按 `References` 里的 id 调用 [`GET /v2/memories/{memory_id}`](https://mirabase.io/zh/developers/api/memories.md#memories-read)；如需查看依据的版本和引文，再调用 [`GET /v2/memories/{memory_id}/provenance`](https://mirabase.io/zh/developers/api/memories.md#memories-provenance)。

curl:

```bash
# An id from the References table.
export MEMORY_ID="distill:ent_7f20:fact_31"
curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# The versions and quotes it rests on.
curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID/provenance" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

TypeScript:

```ts
const memory = await mirabase.memories.get("distill:ent_7f20:fact_31");
// memory.group_id and memory.sources when other memories say the same; memory.dormant when a dream set it aside.

const provenance = await mirabase.memories.provenance(memory.id);
```

Python:

```python
# An id from the References table.
memory = mb.memories.get("distill:ent_7f20:fact_31")
# memory["group_id"] and memory["sources"] when other memories say the same; memory["dormant"] when a dream set it aside.

# The versions and quotes it rests on.
provenance = mb.memories.provenance(memory["id"])
```

通过 MCP 工作的 Agent 用工具 `mira.memory.get`：输入 `memory_id`，默认连同来源返回 `{memory, provenance}`；传 `include_provenance: false` 只取记忆。它只在开启了离线整理的部署上出现在工具清单里。

```json
{
  "jsonrpc": "2.0",
  "id": 7,
  "method": "tools/call",
  "params": {
    "name": "mira.memory.get",
    "arguments": {
      "memory_id": "distill:ent_7f20:fact_31"
    }
  }
}
```

开启了离线整理的部署上，内容相同的提炼记忆在列表中合并为一组，带 `group_id` 和 `sources`；遗忘、更正和审核仍然按单条 id 调用。

## 下一步

- [检索与上下文](https://mirabase.io/zh/developers/retrieval.md)：记忆如何进入上下文和回答。
- [连接 Agent](https://mirabase.io/zh/developers/agents.md)：Agent 用 MCP 工具读写记忆。
- [权限](https://mirabase.io/zh/developers/permissions.md)：谁能确认、更正和遗忘记忆。
