# 同步、快照与导出

用目录树、变更流和 Webhook 将 Space 同步到其他系统，用快照固定某一时刻，用导出和导入迁移整个 Space。

同步由两个接口配合：[`GET /v2/spaces/{space_id}/tree`](https://mirabase.io/zh/developers/api/tree.md#tree-list) 取得某一时刻的全貌，[`GET /v2/spaces/{space_id}/changes`](https://mirabase.io/zh/developers/api/changes.md#changes-list) 取得之后的变更。

## 运行同步循环

1. 读 `tree`，保留**第一页**的 `changes_cursor`。翻页不是同一个快照，第一页的游标能覆盖翻页期间的写入。
2. 把游标传给 `changes`，应用返回的事件。
3. 继续用响应里的 `cursor`。`has_more` 为 `true` 时立即再调用一次，否则带 `wait` 长轮询。

curl:

```bash
# First page of the tree. Keep its changes_cursor.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/tree?recursive=true" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Then follow the feed, waiting up to 30 seconds when nothing has changed.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/changes?cursor=$CURSOR&wait=30" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

TypeScript:

```ts
// Every page of the tree, plus the first page's changes_cursor.
const { nodes, changesCursor } = await mirabase.tree.snapshot("/", { recursive: true });
for (const node of nodes) mirror(node);

// Long-polls, follows has_more, and reconnects after failures it can retry.
for await (const change of mirabase.changes.watch({ cursor: changesCursor })) apply(change);
```

Python:

```python
# Every page of the tree, plus the first page's changes_cursor.
nodes, cursor = mb.tree.snapshot(recursive=True)
for node in nodes:
    print(node["path"])

# Long-polls, follows has_more, and reconnects after failures it can retry.
for change in mb.changes.watch(cursor=cursor):
    print(change["op"], change.get("path"))
```

- 不带 `cursor` 时变更流从当前时刻开始，所以全量同步要先读 `tree`。
- 游标过期时返回 410 `cursor_expired`：重新读 `tree`，从新的 `changes_cursor` 继续。事件的保留期和长轮询的上限见参考页。

## 事件

每个事件的 `op` 是 `create`、`update`、`move`、`delete` 或 `restore`，含义见 [DevChangeOp](https://mirabase.io/zh/developers/api/schemas.md#DevChangeOp)。

## 应用事件

- 事件可能重复，也可能重复 `tree` 已经展示的内容，所以按 `entry_id` 幂等应用。
- `move` 只带新路径。自己维护 `entry_id` 到路径的映射，从 `tree` 开始。
- 目录自身不产生事件，空目录的增删需通过 `tree` 查看。
- Agent 的私有记忆不进入变更流。
- 带 `branch` 时是分支自己的变更流，形状和规则都不同，见 [分支与挂载](https://mirabase.io/zh/developers/branches.md#reads)。

## 查看最近的修改

多人或多个 Agent 共用一个 Space 时，开始工作前可先调用 [`GET /v2/spaces/{space_id}/activity`](https://mirabase.io/zh/developers/api/changes.md#changes-activity)：该接口已将最近几天的变更流按主体和 Entry 汇总，无需从头读取 `changes` 再自行归并。

## 接收 Webhook

不想轮询 `changes` 时，用 [`POST /v2/spaces/{space_id}/webhooks`](https://mirabase.io/zh/developers/api/webhooks.md#webhooks-create) 订阅主线的变更。Mirabase 按顺序推送，每批若干条事件，同一时间只有一批在途，至少送达一次；请求体的结构见 [DevWebhookPayload](https://mirabase.io/zh/developers/api/schemas.md#DevWebhookPayload)。

curl:

```bash
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/webhooks" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://hooks.example.com/mirabase", "ops": ["create", "update", "delete"]}'
```

TypeScript:

```ts
const webhook = await mirabase.webhooks.create({
  url: "https://hooks.example.com/mirabase",
  ops: ["create", "update", "delete"],
});
// Store webhook.secret now: it is in this response only.

for await (const delivery of mirabase.webhooks.deliveries(webhook.id)) console.log(delivery.attempt, delivery.outcome);
```

Python:

```python
webhook = mb.webhooks.create({
    "url": "https://hooks.example.com/mirabase",
    "ops": ["create", "update", "delete"],
})
# Store webhook["secret"] now: it is in this response only.

for delivery in mb.webhooks.deliveries(webhook["id"]):
    print(delivery["attempt"], delivery["outcome"])
```

TypeScript:

```ts
import { parseWebhook } from "@mirabase/sdk/developer";

// Verify against the raw body, before parsing JSON. Throws on a bad or stale signature.
const payload = await parseWebhook({
  secret: process.env.MIRABASE_WEBHOOK_SECRET!,
  header: request.headers.get("Mirabase-Signature"),
  body: await request.text(),
});
// Dedupe on payload.delivery_id: a retry resends the same batch.
for (const change of payload.events) apply(change);
```

Python:

```python
import os

from mirabase import parse_webhook


def receive(header: str | None, body: bytes) -> None:
    """header is the Mirabase-Signature header, body the raw request body."""
    # Verify against the raw body, before parsing JSON. Raises ValueError on a bad or stale signature.
    payload = parse_webhook(secret=os.environ["MIRABASE_WEBHOOK_SECRET"], header=header, body=body)
    # Dedupe on payload["delivery_id"]: a retry resends the same batch.
    for change in payload["events"]:
        print(change["op"], change.get("path"))
```

- 每个请求都要按上面的示例校验签名；签名格式和时间戳容差见 [DevWebhook](https://mirabase.io/zh/developers/api/schemas.md#DevWebhook)。
- 按 `Mirabase-Delivery-Id`（即 `delivery_id`）去重：重试时同一批原样重发。事件按 `entry_id` 应用。
- 尽快返回 2xx，将耗时的处理放在响应之后。失败的判定标准以及重试间隔见 [DevWebhook](https://mirabase.io/zh/developers/api/schemas.md#DevWebhook)。
- 密钥只在创建响应中返回。密钥丢失时调用 [`POST /v2/webhooks/{webhook_id}/rotate-secret`](https://mirabase.io/zh/developers/api/webhooks.md#webhooks-rotatesecret)。

推送停止时，`status` 变为 `disabled`，[disabled_reason](https://mirabase.io/zh/developers/api/schemas.md#DevWebhook.disabled_reason) 说明原因。[`PATCH /v2/webhooks/{webhook_id}`](https://mirabase.io/zh/developers/api/webhooks.md#webhooks-update) 带 `{status: "active"}` 重新启用，[`GET /v2/webhooks/{webhook_id}/deliveries`](https://mirabase.io/zh/developers/api/webhooks.md#webhooks-deliveries) 列出推送记录。

## 创建快照

[`POST /v2/spaces/{space_id}/snapshots`](https://mirabase.io/zh/developers/api/snapshots.md#snapshots-create) 记录当前时刻每个文件的路径和版本。版本不可变，所以快照不复制字节。

curl:

```bash
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/snapshots" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "before-import"}'

# Read a file as the snapshot pinned it, by name or id.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/hello.md&snapshot=before-import" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

TypeScript:

```ts
const snapshot = await mirabase.snapshots.create("before-import");

const then = await mirabase.files.readText("/notes/hello.md", { snapshot: "before-import" });
for await (const node of mirabase.tree("/", { recursive: true, snapshot: snapshot.id })) console.log(node.path);

// Everything written after the snapshot, with no gap and no overlap.
for await (const change of mirabase.changes.watch({ cursor: snapshot.changes_cursor })) apply(change);
```

Python:

```python
snapshot = mb.snapshots.create("before-import")

# Read a file as the snapshot pinned it, by name or id.
then = mb.files.read("/notes/hello.md", snapshot="before-import").text()
for node in mb.tree("/", recursive=True, snapshot=snapshot["id"]):
    print(node["path"])

# Everything written after the snapshot, with no gap and no overlap.
for change in mb.changes.watch(cursor=snapshot["changes_cursor"]):
    print(change["op"], change.get("path"))
```

- 在 `tree`、`files` 和 `files/content-url` 上传入 `snapshot=<id 或名称>`，即可读取快照固定的版本，即使文件此后已修改、移动或移入废纸篓。
- 快照的 `changes_cursor` 从同一时刻衔接 `changes`，因此快照加变更流就是一次不遗漏、不重复的全量同步。
- 快照只包含有路径的文件：空目录、记忆、导入的网址和文本都不在其中。

## 导出和导入

[`POST /v2/spaces/{space_id}/exports`](https://mirabase.io/zh/developers/api/transfers.md#transfers-createexport) 把文件导出为 tar 归档，[`POST /v2/spaces/{space_id}/imports`](https://mirabase.io/zh/developers/api/transfers.md#transfers-createimport) 把 tar 或 gzip 压缩的 tar 导入 Space。两者都以任务执行，返回 202 和 `job_id`，按 [API 约定](https://mirabase.io/zh/developers/conventions.md#jobs) 跟踪。

curl:

```bash
# Export as a job, then follow it with GET /v2/jobs/$JOB_ID
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/exports" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"snapshot": "before-import"}'

# Once it succeeded: a signed download, valid up to five minutes.
curl "https://api.mirabase.dev/v2/jobs/$JOB_ID/content-url" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Import a tar that is already a file you can read, into another Space.
curl -X POST "https://api.mirabase.dev/v2/spaces/$OTHER_SPACE_ID/imports" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"source_entry_id": "'$ARCHIVE_ENTRY_ID'", "path": "/", "on_conflict": "skip"}'
```

TypeScript:

```ts
const exported = await mirabase.transfers.startExport({ snapshot: "before-import" });
// ...poll mirabase.jobs.get(exported.job_id) until it succeeded, then:
const archive = await mirabase.transfers.archiveUrl(exported.job_id);

// Put the archive somewhere as a file, then import it into another Space.
const written = await mirabase.files.write("/imports/space.tar", await (await fetch(archive.url)).blob(), {
  space: otherSpaceId,
  contentType: "application/x-tar",
});
const imported = await mirabase.transfers.startImport(
  { source_entry_id: written.entry.id, path: "/", on_conflict: "skip" },
  { space: otherSpaceId },
);
```

Python:

```python
from urllib.request import urlopen

exported = mb.transfers.start_export({"snapshot": "before-import"})
# Polls until status is succeeded, failed, or cancelled.
mb.jobs.wait(exported["job_id"])
archive = mb.transfers.archive_url(exported["job_id"])

# Put the archive in another Space as a file, then import it there. other_space_id is that Space's id.
uploaded = mb.files.write(
    "/imports/space.tar",
    urlopen(archive["url"]).read(),
    space=other_space_id,
    content_type="application/x-tar",
)
imported = mb.transfers.start_import(
    {"source_entry_id": uploaded["entry"]["id"], "path": "/", "on_conflict": "skip"},
    space=other_space_id,
)
```

### 导出

- 任务开始时确定文件列表，因此归档对应开始时刻的 Space 状态；传入 `snapshot` 时则对应该快照的状态。
- 归档只包含文件：没有路径的内容、记忆和版本历史都不导出。归档的格式见参考页。
- 任务成功后，用 [`GET /v2/jobs/{job_id}/content-url`](https://mirabase.io/zh/developers/api/transfers.md#transfers-archiveurl) 获取归档的下载地址。

> **注意：** 归档保留 7 天。彻底删除该 Space 内的任何文件，或者设置、修改发起人的 `read_root`，都会使归档立即失效，需要重新导出。

### 导入

- 先用 `PUT .../files` 或 `uploads` 把归档放进任意 Space，`source_entry_id` 是归档的 Entry id。
- 本 API 导出的归档会按原路径和媒体类型导回，因此导出后再导入可以还原；其他归档放到 `path` 下。
- 每个文件都像 `PUT` 一样写入，适用相同的路径规则、写入根路径、`write_mode` 和配额；导入不会变成提案。
- 导入不是原子操作：无法写入的条目不会中止任务，计入 `result.failed`；配额用完时任务停止，已导入的内容保留。

> **即将上线**
>
> 复刻 Space（[`POST /v2/spaces/{space_id}/forks`](https://mirabase.io/zh/developers/api/transfers.md#transfers-createfork)）即将上线。在此之前，可先创建快照，带 `snapshot` 导出，新建一个 Space，再将归档导入其中。

## 下一步

- [分支与挂载](https://mirabase.io/zh/developers/branches.md)：给 Agent 一个可以放弃的工作区。
- [API 约定](https://mirabase.io/zh/developers/conventions.md#jobs)：跟踪导出和导入这类任务。
- [错误码](https://mirabase.io/zh/developers/errors.md#codes)：`cursor_expired` 等错误码的处理方式。
