# 分支与挂载

面向 Agent 的写时复制工作区、FUSE 挂载、同步命令和 Git 工作区。

## 使用分支

分支是叠在 Space 主线上的一层写时复制覆盖层，是 Agent 的工作区。分支里的内容**不解析、不进索引、不提炼记忆**，合并进主线才走正常处理，所以失败的试验不会污染知识和记忆。

```bash
# Open a branch. Keep its id (brn_...).
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "try-new-outline"}'

# Write to it. Main does not change.
curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/hello.md&branch=$BRANCH_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: text/markdown" \
  --data-binary @hello.md

# See what changed.
curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/diff" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Merge into main. Idempotency-Key is required here.
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/merge" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Idempotency-Key: merge-try-new-outline" \
  -H "Content-Type: application/json" \
  -d '{"message": "New outline", "on_conflict": "abort"}'
```

[`POST /v2/spaces/{space_id}/branches`](https://mirabase.io/zh/developers/api/branches.md#branches-create) 创建分支，[`GET /v2/spaces/{space_id}/branches/{branch_id}/diff`](https://mirabase.io/zh/developers/api/branches.md#branches-diff) 查看路径级改动，[`POST /v2/spaces/{space_id}/branches/{branch_id}/merge`](https://mirabase.io/zh/developers/api/branches.md#branches-merge) 合并进主线，[`DELETE /v2/spaces/{space_id}/branches/{branch_id}`](https://mirabase.io/zh/developers/api/branches.md#branches-abandon) 放弃分支。

- 会重试的调用里请用分支 id（以 `brn_` 开头），不要用名字：分支关闭后，名字可能指向另一个分支。
- 创建分支只需 Space 写权限，`write_mode` 在合并时才检查，所以 `proposal` 模式的 Agent 也能自由试验。
- 在这个 Space 有 `read_root` 的成员不能使用分支，见 [权限](https://mirabase.io/zh/developers/permissions.md#roots)。

## 在分支上读写

`files`、`files/batch`、`tree`、`tree/operations`、`uploads` 和 `changes` 接受可选的 `branch` 参数。不带时作用于主线。

- 分支读取先查覆盖层，未命中再穿透到主线最新内容。未被分支修改过的路径读到的是主线当前的内容，不是创建分支时的内容。
- 写入分支不产生版本，合并之前也不计 `writes`。响应里的 `etag` 是内容哈希，可以放回 `If-Match`。
- 分支上的 `DELETE` 只在这个分支隐藏文件，主线不变。要撤销分支上的改动，请回滚到检查点。
- 符号链接和权限位（`symlink`、`chmod`、`mode`）只在分支上可用，主线没有符号链接。
- `changes?branch=` 是分支自己的变更流，游标从 `tree?branch=` 获取，与主线的游标不通用。`source: branch` 的事件每个路径只留最新一次，当作要重读的路径处理。
- `search` 和 `context` 不接受 `branch`：分支内容在合并之前检索不到。

## 创建检查点和回滚

检查点记录分支某一时刻自身的改动。穿透到主线的路径不会被固定。回滚之后，后续的检查点仍保留，因此回滚可以撤销；用比回滚点旧的 `changes` 游标请求时，接口返回 410，需从 `tree?branch=` 重新读取。

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

curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/rollback" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"checkpoint_id": "'$CHECKPOINT_ID'"}'
```

## 合并分支

合并必须带 `Idempotency-Key`。全部路径一起生效或一起不生效，每个路径在主线上产生一个带 `message` 的新版本。

- 每个路径与分支首次修改它时主线上的版本比较，主线之后又修改过即视为冲突。默认整次合并失败，返回 409 `merge_conflict`，`error.conflicts` 列出每条冲突；`on_conflict` 可以改为保留主线或覆盖主线。不做内容合并。
- 带 `paths` 时只合并这些路径，分支保持 `active`；不带时分支变为 `merged`，之后不能再写入。
- Agent 合并不属于自己的文件需要 `write_mode: direct`。带 `Prefer: handling=proposal` 时，它对这类文件的修改变为提案，见 [提案](https://mirabase.io/zh/developers/files.md#proposals)。

## 以任务方式合并

超过同步上限的合并带 `Prefer: respond-async` 时作为任务执行，返回 202 和 `job_id`，进度通过 [`GET /v2/jobs/{job_id}`](https://mirabase.io/zh/developers/api/jobs.md#jobs-read) 查询，见 [任务](https://mirabase.io/zh/developers/conventions.md#jobs)。

curl:

```bash
# Over 1000 paths: run the merge as a job instead of 409 merge_too_large.
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/merge" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Idempotency-Key: merge-big-refactor" \
  -H "Prefer: respond-async" \
  -H "Content-Type: application/json" \
  -d '{"message": "Big refactor", "on_conflict": "abort"}'
```

TypeScript:

```ts
const merged = await mirabase.branches.startMerge(branchId, { message: "Big refactor", on_conflict: "abort" });
if ("job_id" in merged) {
  const job = await mirabase.jobs.get(merged.job_id);
  // job.result?.merged counts paths; a failed plan lists job.result?.conflicts.
}
```

Python:

```python
# branch_id is the branch to merge: the id mb.branches.create returned.
merged = mb.branches.start_merge(branch_id, {"message": "Big refactor", "on_conflict": "abort"})
if "job_id" in merged:
    job = mb.jobs.get(merged["job_id"])
    # job["result"]["merged"] counts paths; a failed plan lists job["result"]["conflicts"].
```

- 任务先规划全部路径：有冲突时直接失败，不写入任何内容。
- 之后分批合并，不是原子的。中途出现的冲突会使任务停止，已合并的路径已经离开分支：再合并一次以处理剩余路径。
- 任务排队或运行期间，这个分支不能再合并或写入文件；改名、创建检查点和放弃仍可用，放弃会使任务停止。

## 有效期和回收

每次写入将 `expires_at` 向后推迟 `ttl_days` 天，`ttl_days` 可以在创建时或用 [`PATCH /v2/spaces/{space_id}/branches/{branch_id}`](https://mirabase.io/zh/developers/api/branches.md#branches-update) 设置。一直没有写入的分支过期，变为 `abandoned`。分支放弃、过期或合并之后再保留 `branch_reclaim_days` 天，然后回收。分支空间计入 `storage_bytes`。各项默认值见 [限流与限额](https://mirabase.io/zh/developers/conventions.md#rate-limits)。

## 存储分支对象

[`PUT /v2/spaces/{space_id}/branches/{branch_id}/objects/{sha256}`](https://mirabase.io/zh/developers/api/branches.md#branches-putobject) 存储一个按哈希命名的不透明对象，用于存放 Git bundle 和 overlay。对象不是路径，不出现在 `tree` 和 `changes` 中，不合并、不解析、不索引，计入 `storage_bytes`。分支已合并或已放弃时，对象在回收之前仍可读取。

> **注意：** 分支对象中的内容（包括 Git bundle）在分支回收之前无法彻底删除。`purge` 只作用于主线的 Entry。要尽快移除这些内容，请放弃分支，等待 `branch_reclaim_days` 天后回收。

> **即将上线**

## CLI 和挂载（即将上线）

`mirabase` CLI 是无运行时依赖的单文件程序，适合放入沙箱，全部调用公开 API。它读取 `MIRABASE_API_KEY`（必填）、`MIRABASE_API_URL` 和 `MIRABASE_SPACE`。挂载写入分支，不写入主线：编辑器一次保存会产生多次写入和改名。

> **说明：** CLI 尚未发布，以下命令目前无法安装。分支功能本身已经上线，上文各节的接口均可直接调用。

```bash
export MIRABASE_API_KEY="mb_live_..."

# Stays in the foreground and prints the branch it opened.
mirabase mount ./workspace --space "$SPACE_ID"

# In another shell:
grep -rn "TODO" ./workspace
sed -i 's/one place/a single place/' ./workspace/notes/hello.md
mirabase drain ./workspace
mirabase branch diff "$BRANCH_ID" --space "$SPACE_ID"
mirabase branch merge "$BRANCH_ID" --message "Wording" --space "$SPACE_ID"
```

| 命令 | 作用 |
| --- | --- |
| `mirabase mount <dir> --space s [--branch b] [--read-only]` | FUSE 挂载，未传 `--branch` 时自动创建分支 |
| `mirabase sync <dir> --space s [--branch b] [--once]` | 用于无 FUSE 的沙箱环境：拉取、监听本地改动并推送 |
| `mirabase drain [dir] [--timeout 5m] [--ack]` | 阻塞至本地写入全部上传；退出码 0 表示全部上传，1 表示有写入被放弃或认证失败，2 表示超时，3 表示自己的写入被其他机器覆盖 |
| `mirabase branch <subcommand>` | `create`、`list`、`get`、`rename`、`extend`、`diff`、`checkpoint`、`checkpoints`、`rollback`、`merge`、`abandon` |
| `mirabase git save\|restore\|worktree` | Git 工作区，见下一节 |

- 一致性为 close-to-open：其他机器在下次打开时看到新内容。`fsync` 只保证写入本地磁盘，跨机器可见性以 `drain` 为准。
- 同一路径并发写时后写覆盖。
- 支持改名、mkdir、unlink、truncate、可执行位和符号链接，不支持硬链接、设备文件和文件锁。
- `.mirabase/memory/MEMORY.md` 在挂载目录里只读，写入返回 `EROFS`。
- 默认不上传 `.git/`、`node_modules/`、`.venv/`、`__pycache__/` 和 `.DS_Store`，只留在本地。可以用 `.mirabaseignore`（gitignore 语法）调整。
- Linux 下挂载需要 `/dev/fuse`（在容器中还需要 `SYS_ADMIN`）；不具备时请使用 `mirabase sync`。macOS 下需先安装 macFUSE 或 FUSE-T。

## Git 工作区（即将上线）

`mirabase git save` 将提交打包为 bundle（首次之后仅打包增量），将未提交和未跟踪的改动存为 overlay，再创建一个检查点，`git` 字段记录 `HEAD`、ref 和移除凭据后的远端地址。`mirabase git restore <checkpoint> <dir>` 在全新环境中恢复并校验 `HEAD` 和工作区。`mirabase git worktree <checkpoint> <dir> --ref r` 恢复后用 `git worktree` 打开另一个 ref。

```bash
# In a Git repository: bundle commits, store uncommitted changes, create a checkpoint.
# Without --branch it opens one and remembers it in .git/mirabase-branch.
mirabase git save --space "$SPACE_ID" --name "before-upgrade"

# Somewhere else: restore and verify HEAD and the working tree.
mirabase git restore "$CHECKPOINT_ID" ./repo --space "$SPACE_ID"
```

- bundle 和 overlay 存为分支对象，不会发送给模型提供方。
- 暂存区状态不单独保存，恢复后全部是未暂存改动。
- `.gitignore` 忽略的文件和 `.env` 默认不保存。需要时显式传 `--include-ignored`。
- 保存的内容在分支回收之前无法彻底删除，见 [分支对象](https://mirabase.io/zh/developers/branches.md#objects)。

## 下一步

- [同步、快照与导出](https://mirabase.io/zh/developers/sync.md#snapshots)：只要一个只读的固定点时用快照。
- [权限](https://mirabase.io/zh/developers/permissions.md)：谁能合并，Agent 的改动什么时候变成提案。
- [API 约定](https://mirabase.io/zh/developers/conventions.md#idempotency)：合并必须带幂等键。
