Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(server,web,docs): export and import a Memory scope group as a whole (#372)

Yaowei Zhengc9b2667d5629
diff --git a/changelog/unreleased/2026-08-20-memory-scope-transfer.md b/changelog/unreleased/2026-08-20-memory-scope-transfer.md
new file mode 100644
index 00000000..f5995383
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-memory-scope-transfer.md
@@ -0,0 +1,68 @@
+# Memory groups export and import as a whole
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#372](https://github.com/Prism-Shadow/penguin-harness/pull/372)
+
+[中文版](2026-08-20-memory-scope-transfer.zh.md)
+
+Each scope group on the Memory tab — user memory, and one per Workspace — now moves in one
+piece. Export downloads the group as a single JSON document holding every memory and the
+group's `MEMORY.md`; import reads such a document back into any group of any agent, so a
+convention worked out with one agent can be handed to another, or a Workspace's memories
+carried to a second machine.
+
+## The document
+
+`GET /api/projects/:p/agents/:a/memory/scopes/:key/export` returns one JSON object —
+`format` / `version` / `scopeKey` / `kind` / `workspacePath` / `exportedAt`, the scope's
+`index`, and a `files` array of `{name, content}` — served as an attachment. Everything in a
+Memory scope is UTF-8 Markdown, so the document is plain text end to end: readable in an
+editor, diffable in git, and reviewable before it is imported.
+
+The saved file is named `<agent>-<scope>-memory-<YYYYMMDD-HHmm>.json`, stamped from the
+document's own `exportedAt` (the viewer's clock in the Web App, the server's in the
+attachment header), so repeated exports of one scope stay apart in a downloads folder.
+
+## Import, and what it costs
+
+`POST …/memory/scopes/:key/import` takes `{payload, mode?, confirm?}`:
+
+- `skip` (the default) writes only names the group does not already have. Nothing on disk is
+ replaced or deleted.
+- `overwrite` replaces a same-named memory's content, leaving memories the document does not
+ carry alone.
+- `replace` additionally deletes every memory the document does not carry.
+
+An import that would overwrite or delete anything is refused with 409
+`memory_import_confirm_required` unless `confirm` is set — and the gate is what the import
+would actually cost, not the mode's name, so `replace` into an empty group needs no
+confirmation. The Web App computes the same plan before sending and puts the two destructive
+modes behind a confirmation naming each memory that would be overwritten or deleted.
+
+The index follows the files: a group with no `MEMORY.md` takes the document's, `replace`
+takes it too, and a merge keeps the index that is there and appends the document's lines for
+the memories that arrived — the mirror of the pruning a delete already does. Only the indexes
+enter the model's context, so an unindexed memory would be one the agent never reads.
+
+## Validation and access
+
+Entry names go through the same check that guards every other write into a Memory directory:
+a plain Markdown topic name, no path, no leading dot, not the reserved index, re-checked for
+containment after resolution. A document is refused whole — nothing is written — when an entry
+name is a path or climbs out, when content is not a string or carries a NUL, when a name
+repeats, or when it exceeds 500 entries, 512KB per file or 8MB in total. Writes go to a
+temporary file and are renamed over the target, so a symlink standing at a memory's name is
+replaced rather than followed.
+
+Export is available to any Project member, as reading the files one by one already was.
+Import is owner-only, matching the Agent State snapshot's split, and enforced on the server:
+a member gets 403 `owner_required`, a non-member 404 on both routes.
+
+## Web App
+
+Each group header carries labeled **Export** and (for owners) **Import** buttons beside its
+existing Add entry — icon plus text, with a tooltip saying that the whole group travels.
+Import opens a modal naming the picked file and its memory count, with the collision choice
+spelled out, then reports what the import did — added, replaced, deleted — as a toast.
diff --git a/changelog/unreleased/2026-08-20-memory-scope-transfer.zh.md b/changelog/unreleased/2026-08-20-memory-scope-transfer.zh.md
new file mode 100644
index 00000000..10dc3ecd
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-memory-scope-transfer.zh.md
@@ -0,0 +1,57 @@
+# 记忆分组支持整组导出与导入
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#372](https://github.com/Prism-Shadow/penguin-harness/pull/372)
+
+[English](2026-08-20-memory-scope-transfer.md)
+
+Memory 标签页上的每个作用域分组——用户记忆,以及每个 Workspace 一组——现在可以整组搬运。导出把
+一组记忆下载为一份 JSON 文档,含其中全部记忆与这一组的 `MEMORY.md`;导入把这样一份文档写回任意
+agent 的任意分组,于是在一个 agent 上磨出来的约定可以交给另一个,某个 Workspace 的记忆也能带到
+第二台机器上。
+
+## 文档格式
+
+`GET /api/projects/:p/agents/:a/memory/scopes/:key/export` 返回一个 JSON 对象——`format` /
+`version` / `scopeKey` / `kind` / `workspacePath` / `exportedAt`、这一组的 `index`,以及由
+`{name, content}` 组成的 `files` 数组——以附件形式下载。记忆作用域里的一切本就是 UTF-8 Markdown,
+因此这份文档从头到尾都是纯文本:编辑器里能读,git 里能 diff,导入之前能审。
+
+保存的文件名为 `<agent>-<scope>-memory-<YYYYMMDD-HHmm>.json`,时间戳取自文档自身的
+`exportedAt`(Web App 内按浏览者时钟、附件响应头按服务器时钟渲染),同一分组的多次导出在下载
+目录里互不覆盖。
+
+## 导入及其代价
+
+`POST …/memory/scopes/:key/import` 接受 `{payload, mode?, confirm?}`:
+
+- `skip`(缺省)只写入分组中尚未存在的名字,磁盘上的内容既不被覆盖也不被删除。
+- `overwrite` 覆盖同名记忆的内容,文档中没有的记忆保持不变。
+- `replace` 在此之上删除文档中没有携带的每一条记忆。
+
+会造成覆盖或删除的导入,未携带 `confirm` 时以 409 `memory_import_confirm_required` 拒绝——判据
+是这次导入实际的代价而不是模式的名字,因此对空分组执行 `replace` 无需确认。Web App 在发送前算出
+同一份计划,把两种破坏性模式挡在确认框之后,并逐条列出将被覆盖或删除的记忆。
+
+索引跟随文件走:没有 `MEMORY.md` 的分组直接采用文档的索引,`replace` 同样采用;合并式导入则保留
+现有索引,并为新到达的记忆追加文档里对应的索引行——正是删除时清理索引行的镜像操作。只有索引会进入
+模型上下文,因此没有索引行的记忆等于 agent 永远读不到的记忆。
+
+## 校验与权限
+
+条目名走的是守护记忆目录里每一次写入的同一道校验:必须是普通的 Markdown 主题文件名,不含路径、
+不以点开头、不是保留的索引名,解析之后再复核是否仍在目录内。以下情形整份文档被拒、一个字节也不写入:
+条目名是路径或会越出目录、内容不是字符串或含 NUL、名字重复,以及超过 500 个条目、单文件 512KB
+或总计 8MB 的上限。写入先落临时文件再重命名覆盖目标,因此顶着某条记忆名字的软链接会被替换,而不是
+被跟随。
+
+导出对任何 Project 成员开放——逐个文件读取本来就是成员权限;导入仅 owner 可用,与 Agent State
+快照的分工一致,并由服务端强制:成员得到 403 `owner_required`,非成员在两个端点上都得到 404。
+
+## Web App
+
+每个分组标题在原有的「添加」入口旁增加带文字的**导出**与(owner 可见的)**导入**按钮——图标加
+文字,悬停提示说明搬运的是整组记忆。导入弹窗列出所选文件与其中的记忆条数,并把同名处理方式写明,
+完成后以提示条汇报本次导入的结果——新增、覆盖、删除各多少条。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 417c4b3b..81fdca03 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -142,6 +142,8 @@ The paths below omit the `/api/projects/:projectId` prefix.
| POST | /agents/:agentId/memory/template-placeholder | Insert the `{{MEMORY}}` placeholder into the prompt template (idempotent; the explicit adoption path for an Agent created before Memory) |
| GET | /agents/:agentId/memory/scopes/:key/files | List one scope's topic files (frontmatter + stats); `:key` is a workspace key or `user` |
| GET / DELETE | /agents/:agentId/memory/scopes/:key/files/:name | Read one topic file / delete it (also pruning its `MEMORY.md` index lines) |
+| GET | /agents/:agentId/memory/scopes/:key/export | One scope as a single JSON document: every topic file plus its `MEMORY.md`, downloaded as an attachment |
+| POST | /agents/:agentId/memory/scopes/:key/import | Write such a document back (owner only): `{payload, mode?, confirm?}`. `mode` is `skip` (the default — adds only names the scope lacks), `overwrite` (replaces same-named files) or `replace` (also deletes what the document omits); anything that would overwrite or delete needs `confirm`, else 409 `memory_import_confirm_required` |
| GET | /agents/:agentId/export | Export the Agent State snapshot (tar.gz download) |
| POST | /agents/:agentId/import | Import a snapshot: `{dataBase64, confirm?}`; 409 on version conflict without confirm |
| GET / POST | /agents/:agentId/skills | List / install installed Skills |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index d84333f2..2f452730 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -142,6 +142,8 @@ curl -c cookies.txt -H "Content-Type: application/json" \
| POST | /agents/:agentId/memory/template-placeholder | 向提示词模板插入 `{{MEMORY}}` 占位符(幂等;创建于记忆功能之前的 Agent 的显式采用路径) |
| GET | /agents/:agentId/memory/scopes/:key/files | 列出单个作用域的主题文件(frontmatter + 文件信息);`:key` 为 workspace key 或 `user` |
| GET / DELETE | /agents/:agentId/memory/scopes/:key/files/:name | 读取单个主题文件 / 删除它(并同步清理其 `MEMORY.md` 索引行) |
+| GET | /agents/:agentId/memory/scopes/:key/export | 把整个作用域导出为一份 JSON 文档:全部主题文件加它的 `MEMORY.md`,以附件形式下载 |
+| POST | /agents/:agentId/memory/scopes/:key/import | 把这样一份文档写回(仅 owner):`{payload, mode?, confirm?}`。`mode` 为 `skip`(缺省,只添加作用域尚未有的名字)、`overwrite`(覆盖同名文件)或 `replace`(并删除文档中没有的文件);任何会覆盖或删除的操作都需要 `confirm`,否则返回 409 `memory_import_confirm_required` |
| GET | /agents/:agentId/export | 导出 Agent State 快照(tar.gz 下载) |
| POST | /agents/:agentId/import | 导入快照:`{dataBase64, confirm?}`;版本冲突且未确认时返回 409 |
| GET / POST | /agents/:agentId/skills | 已安装 Skill 列表 / 安装 |
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 3cf3499a..349c4ec3 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -89,13 +89,13 @@ The list page creates and deletes Agents; clicking through opens the `/agents/:a
| --- | --- |
| Overview | Basic info, export / import of Agent State snapshots, and restoring the default configuration (overwrites customizations, keeping only name/description) |
| Prompt | AGENTS.md and system_prompt |
-| Memory | The Agent-level switch, then every memory grouped by scope — user memory first, then one group per Workspace, each group collapsible with an add entry — with view / delete / edit-via-chat actions per row |
+| Memory | The Agent-level switch, then every memory grouped by scope — user memory first, then one group per Workspace, each group collapsible with add, export and import entries — with view / delete / edit-via-chat actions per row |
| Runtime | Runtime parameters such as max_turns, model.*, compaction.* |
| Tools | Built-in tool table (incl. per-tool call_description switches) and MCP Server management: a table plus an add/edit form whose fields follow the transport (http by default; changes save immediately; full transport validation server-side; a permission control fixes the approval level of that server's tools at `auto` / `r` / `rw`, and the table shows each server's effective level); connectivity testing mirrors the models page — a standalone button in the form probes the current entry (toast with tool count and latency), and a section-level button tests every server in turn with a result badge on each row |
| Vault | Environment-variable entries with masked values |
| Schedule | Scheduled tasks (TOML-defined): create, edit, toggle, delete |
-The Memory tab's switch writes immediately rather than joining the tab-level Save, so turning Memory off never drags an unrelated half-finished edit along with it. Turning it off keeps every file and the tab fully usable: it only stops Memory from entering the agent's context and from preparing directories for new Sessions. Scope groups collapse on header click, with the collapse state remembered in the browser per user × Project × Agent; each group header carries an **Add** text entry to its collapse arrow's left (the models page's group convention) — like editing, it goes through a bridge modal (a required content-or-source field plus a live prompt preview) into a new chat, where the agent organizes the content into that scope; the drafts stay deliberately minimal, since the save mechanics live in the Memory prompt. Rows are read-only on purpose, their actions icon-only like the skills tab's — **View** renders the body in a right drawer on desktop and a bottom sheet on narrow screens (the chat page panels' interaction, with half / full snap points), **Delete** confirms and also removes the file's `MEMORY.md` index lines, and **Edit** opens a bridge modal first (what to change plus a prompt preview), then jumps to a new chat with this agent; a Workspace scope's chat also pins that Workspace, so the Session reads the very index it is changing. Below the groups the two memory prompts (`memory.prompt` / `memory.workspace_prompt`) are edited in place, and when the prompt template carries no `{{MEMORY}}` placeholder (an agent created before Memory) it shows a hint with a one-click insert — an explicit, idempotent config write. The agent list cards' stat line also shows the memory count, deep-linking to this tab. For the storage model, see [Configuration](/configuration#memory).
+The Memory tab's switch writes immediately rather than joining the tab-level Save, so turning Memory off never drags an unrelated half-finished edit along with it. Turning it off keeps every file and the tab fully usable: it only stops Memory from entering the agent's context and from preparing directories for new Sessions. Scope groups collapse on header click, with the collapse state remembered in the browser per user × Project × Agent; each group header carries an **Add** text entry to its collapse arrow's left (the models page's group convention) — like editing, it goes through a bridge modal (a required content-or-source field plus a live prompt preview) into a new chat, where the agent organizes the content into that scope; the drafts stay deliberately minimal, since the save mechanics live in the Memory prompt. Rows are read-only on purpose, their actions icon-only like the skills tab's — **View** renders the body in a right drawer on desktop and a bottom sheet on narrow screens (the chat page panels' interaction, with half / full snap points), **Delete** confirms and also removes the file's `MEMORY.md` index lines, and **Edit** opens a bridge modal first (what to change plus a prompt preview), then jumps to a new chat with this agent; a Workspace scope's chat also pins that Workspace, so the Session reads the very index it is changing. A whole group also moves in one piece: **Export** downloads it as a JSON document (every memory plus the group's `MEMORY.md`) whose file name carries the export date and time, so repeated exports stay apart, and **Import** — owner only, mirroring the Agent State snapshot's split — reads one back. Import asks what to do with a name the group already has: keep the one that is here (the default, which loses nothing), take the file's version, or replace the whole group; either of the latter two confirms first, naming the memories that would be overwritten or deleted. Below the groups the two memory prompts (`memory.prompt` / `memory.workspace_prompt`) are edited in place, and when the prompt template carries no `{{MEMORY}}` placeholder (an agent created before Memory) it shows a hint with a one-click insert — an explicit, idempotent config write. The agent list cards' stat line also shows the memory count, deep-linking to this tab. For the storage model, see [Configuration](/configuration#memory).
Scheduled tasks fire on a fixed period (minimum 5 minutes) and run only while the service is running.
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index f5e0c6da..72cceef9 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -88,13 +88,13 @@ penguin web
| --- | --- |
| Overview | 基本信息、Agent State 快照的导出 / 导入,以及还原为默认配置(覆盖自定义内容,仅保留名称与描述) |
| Prompt | AGENTS.md 与 system_prompt |
-| Memory | Agent 级开关,以及按作用域分组的全部记忆——用户记忆在前、每个 Workspace 一组,分组可折叠并带添加入口——每行提供查看 / 删除 / 对话编辑 |
+| Memory | Agent 级开关,以及按作用域分组的全部记忆——用户记忆在前、每个 Workspace 一组,分组可折叠并带添加、导出与导入入口——每行提供查看 / 删除 / 对话编辑 |
| Runtime | max_turns、model.*、compaction.* 等运行参数 |
| Tools | 内置工具表格(含条目级 call_description 开关)与 MCP Server 管理:表格 + 添加/编辑表单(默认 http,字段随 transport 切换,改动即时保存,服务端按 transport 完整校验;permission 控件把该 Server 工具的审批等级固定为 `auto` / `r` / `rw`,表格列出各 Server 的生效等级);测试连接与模型页同款——表单内独立按钮测当前条目(toast 报工具数与耗时),区块级按钮逐一测试全部 Server 并在各行显示结果徽标 |
| Vault | 环境变量条目,值以掩码显示 |
| Schedule | 定时任务(TOML 定义):创建、编辑、启停、删除 |
-Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,因此关闭记忆不会连带把别处未改完的内容一起存盘。关闭记忆也不会删除任何文件,标签页仍可正常查看与删除——只是记忆不再进入 Agent 上下文,也不再为新 Session 准备目录。作用域分组可折叠,折叠状态按「用户 × Project × Agent」记在浏览器本地;每组标题的折叠箭头左侧有**添加**文字入口(与模型页的分组约定一致)——和编辑一样经中转弹窗(必填的内容或来源 + 引导语实时预览)跳到新对话,由 agent 整理保存到该作用域;引导语刻意极简,写入规范由记忆提示词承载。记忆行有意不提供就地编辑,操作与技能页一致为纯图标按钮:**查看**在桌面端从右侧抽屉、窄屏从底部弹层(与对话页面板同一交互,半屏 / 全屏两档吸附)渲染正文;**删除**先确认,并同步清掉该文件在 `MEMORY.md` 中的索引行;**编辑**先打开中转弹窗(修改要求 + 引导语预览),再跳到与该 Agent 的新对话——Workspace 作用域的对话还会锁定对应 Workspace,让会话恰好读到它正在修改的那份索引。标签页下方可直接编辑两段记忆提示词(`memory.prompt` / `memory.workspace_prompt`);当提示词模板中没有 `{{MEMORY}}` 占位符(创建于记忆功能之前的 agent)时会给出提示并提供一键插入——显式且幂等的配置写入。Agent 列表卡片的统计行也显示记忆条数,点击直达本标签页。存储模型见[配置说明](/configuration#记忆)。
+Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,因此关闭记忆不会连带把别处未改完的内容一起存盘。关闭记忆也不会删除任何文件,标签页仍可正常查看与删除——只是记忆不再进入 Agent 上下文,也不再为新 Session 准备目录。作用域分组可折叠,折叠状态按「用户 × Project × Agent」记在浏览器本地;每组标题的折叠箭头左侧有**添加**文字入口(与模型页的分组约定一致)——和编辑一样经中转弹窗(必填的内容或来源 + 引导语实时预览)跳到新对话,由 agent 整理保存到该作用域;引导语刻意极简,写入规范由记忆提示词承载。记忆行有意不提供就地编辑,操作与技能页一致为纯图标按钮:**查看**在桌面端从右侧抽屉、窄屏从底部弹层(与对话页面板同一交互,半屏 / 全屏两档吸附)渲染正文;**删除**先确认,并同步清掉该文件在 `MEMORY.md` 中的索引行;**编辑**先打开中转弹窗(修改要求 + 引导语预览),再跳到与该 Agent 的新对话——Workspace 作用域的对话还会锁定对应 Workspace,让会话恰好读到它正在修改的那份索引。整组记忆也可以一次搬运:**导出**把它下载为一份 JSON 文档(这一组的全部记忆加它的 `MEMORY.md`),文件名带导出日期时间,多次导出互不覆盖;**导入**把这样一份文档读回来——与 Agent State 快照同样的分工,仅 owner 可用。导入时需要指定同名记忆的处理方式:保留现有的(缺省,不丢失任何内容)、改用文件里的版本、或整组替换;后两者会先弹出确认,逐条列出将被覆盖或删除的记忆。标签页下方可直接编辑两段记忆提示词(`memory.prompt` / `memory.workspace_prompt`);当提示词模板中没有 `{{MEMORY}}` 占位符(创建于记忆功能之前的 agent)时会给出提示并提供一键插入——显式且幂等的配置写入。Agent 列表卡片的统计行也显示记忆条数,点击直达本标签页。存储模型见[配置说明](/configuration#记忆)。
定时任务按固定周期触发(最短 5 分钟),且仅在服务运行期间执行。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index ace2a4c2..8887edd0 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -844,6 +844,8 @@ export interface MemoryScopeInfo {
workspacePath?: string;
/** Number of Markdown topic files in the directory (the `MEMORY.md` index not counted). */
fileCount: number;
+ /** Whether the directory holds a `MEMORY.md` index, so an import confirmation can say whether one would be replaced. */
+ hasIndex: boolean;
/** Most recent topic-file mtime in the directory (ISO 8601); unset when the directory holds no topic file. */
updatedAt?: string;
}
@@ -888,6 +890,69 @@ export interface MemoryFileResponse {
content: string;
}
+/** One topic file inside a transfer document: the name it had in its scope, and its whole text. */
+export interface MemoryTransferFile {
+ /** File name inside the scope directory, e.g. `prefers-pnpm.md` — a name, never a path. */
+ name: string;
+ /** The file's full Markdown text, frontmatter included. */
+ content: string;
+}
+
+/**
+ * GET …/memory/scopes/:key/export, and the body a POST …/import carries back: everything one
+ * scope holds, as one JSON document — the topic files and the scope's own `MEMORY.md`.
+ */
+export interface MemoryScopeExport {
+ /** Format marker, so a foreign JSON file is refused with a clear reason rather than half-imported. */
+ format: "penguin-memory-scope";
+ /** Document version. A reader accepts exactly this; a later format bumps it and states its own compatibility. */
+ version: 1;
+ /** The scope this was exported from. Informational: an import writes into the scope its URL names. */
+ scopeKey: string;
+ kind: MemoryScopeInfo["kind"];
+ /** The Workspace the source scope stood for, when it had a `.workspace` marker. */
+ workspacePath?: string;
+ /** When the document was produced (ISO 8601). */
+ exportedAt: string;
+ /** The scope's `MEMORY.md`, or null when the scope has none. Only the index reaches the model's context. */
+ index: string | null;
+ files: MemoryTransferFile[];
+}
+
+/**
+ * What an import does with a name the target scope already holds:
+ * - `skip` — keep what is on disk, write only names the scope does not have (destroys nothing);
+ * - `overwrite` — replace a same-named file's content;
+ * - `replace` — additionally delete every topic file the document does not carry.
+ * The two destructive modes require `confirm`.
+ */
+export type MemoryImportMode = "skip" | "overwrite" | "replace";
+
+/** POST …/memory/scopes/:key/import */
+export interface MemoryImportRequest {
+ /** Defaults to `skip`. */
+ mode?: MemoryImportMode;
+ /** Required by `overwrite` and `replace`; without it they are refused with 409 `memory_import_confirm_required`. */
+ confirm?: boolean;
+ payload: MemoryScopeExport;
+}
+
+/** What one import did, name by name, so the UI can report it rather than claim success. */
+export interface MemoryImportResponse {
+ scopeKey: string;
+ mode: MemoryImportMode;
+ /** Names written that the scope did not have. */
+ added: string[];
+ /** Names whose existing content was replaced. */
+ overwritten: string[];
+ /** Names left untouched because the scope already had them (`skip` only). */
+ skipped: string[];
+ /** Names deleted because `replace` dropped everything the document did not carry. */
+ removed: string[];
+ /** Whether the scope's `MEMORY.md` was written or extended. */
+ indexWritten: boolean;
+}
+
// ---------------------------------------------------------------------------
// Session
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/http/routes/memory.ts b/packages/server/src/http/routes/memory.ts
index d45facbb..57104130 100644
--- a/packages/server/src/http/routes/memory.ts
+++ b/packages/server/src/http/routes/memory.ts
@@ -1,14 +1,21 @@
/**
- * Memory routes (`agent_state/memory/`), all Project-member operations:
+ * Memory routes (`agent_state/memory/`), Project-member operations except where noted:
* GET /api/projects/:p/agents/:a/memory # switch + scope groups (user scope first)
* POST /api/projects/:p/agents/:a/memory/template-placeholder # insert the {{MEMORY}} placeholder into the template
* GET /api/projects/:p/agents/:a/memory/scopes/:key/files # one scope's topic files
* GET …/memory/scopes/:key/files/:name # one topic file's content
* DELETE …/memory/scopes/:key/files/:name # delete + prune its index lines
+ * GET …/memory/scopes/:key/export # the whole scope as one JSON document
+ * POST …/memory/scopes/:key/import # write such a document back (owner only)
*
- * Deliberately read + delete only: content edits go through a chat Session where the model
- * maintains the files and their `MEMORY.md` index together. The `memory.enabled` switch is
- * Agent configuration and lives on PUT …/agents/:a/config.
+ * Per-file content edits go through a chat Session where the model maintains the files and their
+ * `MEMORY.md` index together. The `memory.enabled` switch is Agent configuration and lives on
+ * PUT …/agents/:a/config.
+ *
+ * Import is the one route here that is not a Project-member operation. It follows the Agent State
+ * snapshot's split, for the same reason: reading a scope is reading Agent State, which every
+ * member may do, while writing a whole scope at once can cost the Agent memories no member
+ * agreed to lose (agent-transfer.ts).
*
* No route accepts an absolute path: a file is addressed by `agentId` + `scopeKey` + a name
* inside that scope, and MemoryService re-checks that the resolved path stayed inside the
@@ -18,12 +25,22 @@ import { Hono } from "hono";
import type { Context } from "hono";
import type { AppEnv } from "../../auth/middleware.js";
import type { AppDeps } from "../../app.js";
-import { pathParam, requireValidId } from "../validate.js";
+import type { MemoryImportMode } from "../../api/types.js";
+import { optionalBoolean, optionalEnum, pathParam, readJson, requireValidId } from "../validate.js";
+
+const IMPORT_MODES: readonly MemoryImportMode[] = ["skip", "overwrite", "replace"];
+
+/** The export attachment's `YYYYMMDD-HHmm` stamp, from the document's `exportedAt` (local clock). */
+function exportStamp(exportedAt: string): string {
+ const d = new Date(exportedAt);
+ const p = (n: number): string => String(n).padStart(2, "0");
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
+}
export function memoryRoutes(deps: AppDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
- /** Shared preamble: id validation before any path construction (FD-4), then the Project membership check. */
+ /** Shared preamble: id validation before any path construction, then the Project membership check. */
const scope = (c: Context<AppEnv>) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
@@ -55,6 +72,40 @@ export function memoryRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json(await deps.memoryService.readFile(projectId, agentId, key, name));
});
+ app.get("/scopes/:scopeKey/export", async (c) => {
+ const { projectId, agentId } = scope(c);
+ const key = pathParam(c, "scopeKey");
+ const doc = await deps.memoryService.exportScope(projectId, agentId, key);
+ // Named for the Agent, the scope, and the document's own `exportedAt` (`YYYYMMDD-HHmm`,
+ // this process's local clock), so repeated exports of one scope stay apart in a downloads
+ // folder. The Agent id is validated and the scope key has just passed the service's key
+ // rule, so neither can carry a quote or a newline into the header; the stamp is digits
+ // and a dash by construction. The Web App saves through an object URL with the same
+ // pattern rendered on the viewer's clock (see memoryDocumentFileName).
+ return new Response(JSON.stringify(doc, null, 2), {
+ headers: {
+ "Content-Type": "application/json; charset=utf-8",
+ "Content-Disposition": `attachment; filename="${agentId}-${key}-memory-${exportStamp(doc.exportedAt)}.json"`,
+ },
+ });
+ });
+
+ // Owner only: one request can replace or delete every memory in the scope.
+ app.post("/scopes/:scopeKey/import", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ const key = pathParam(c, "scopeKey");
+ const body = await readJson(c);
+ return c.json(
+ await deps.memoryService.importScope(projectId, agentId, key, {
+ mode: optionalEnum(body, "mode", IMPORT_MODES) ?? "skip",
+ confirm: optionalBoolean(body, "confirm") ?? false,
+ payload: body.payload,
+ }),
+ );
+ });
+
app.delete("/scopes/:scopeKey/files/:fileName", async (c) => {
const { projectId, agentId } = scope(c);
const key = pathParam(c, "scopeKey");
diff --git a/packages/server/src/services/memory-service.ts b/packages/server/src/services/memory-service.ts
index c2cb1424..f9d5cbf4 100644
--- a/packages/server/src/services/memory-service.ts
+++ b/packages/server/src/services/memory-service.ts
@@ -9,10 +9,13 @@
* the one difference is that it may be created on demand, since it belongs to the Agent rather
* than to a Session that has run.
*
- * The API is deliberately read + delete only: content changes go through a chat Session where
- * the model edits the same files, keeping frontmatter and index in step. The one write this
- * service performs is mechanical — deleting a topic file also drops its `](<file>)` index lines,
- * so the index never lists a file that is gone.
+ * Per-file content changes go through a chat Session where the model edits the same files,
+ * keeping frontmatter and index in step; this service's own writes are the mechanical ones a
+ * model cannot be asked for. Deleting a topic file drops its `](<file>)` index lines, so the
+ * index never lists a file that is gone. Whole-scope import writes the files a transfer
+ * document carries and adds their index lines, the same invariant read the other way: the
+ * index never omits a file that arrived. Only the indexes enter the model's context (core's
+ * state/memory.ts), so an unindexed topic file would be a file the Agent never reads.
*
* This service never invents paths from client input — a request names an `agentId`, a
* `scopeKey` and a file name inside that scope, each validated against a character rule and
@@ -22,6 +25,7 @@
* Files are the source of truth and are read fresh on every request (they are small, requests
* are rare, and the model edits the same files from its side).
*/
+import { randomBytes } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import {
@@ -38,8 +42,12 @@ import type {
MemoryFileInfo,
MemoryFilesResponse,
MemoryFileResponse,
+ MemoryImportMode,
+ MemoryImportResponse,
MemoryOverviewResponse,
+ MemoryScopeExport,
MemoryScopeInfo,
+ MemoryTransferFile,
} from "../api/types.js";
import { HttpError } from "../http/errors.js";
import { badRequest } from "../http/validate.js";
@@ -48,6 +56,47 @@ import type { AgentConfigService } from "./agent-config-service.js";
/** Scope directory names: what core's key generator produces (a safe base may start with `_`), plus the leeway of a hand-made directory. Excludes `.`/`..` and any separator, so the name can never climb out of `memory/`. */
const SCOPE_KEY_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
+/** The transfer document's format marker, checked before anything in it is believed. Typed against the DTO so the two literals cannot drift apart. */
+const SCOPE_FORMAT: MemoryScopeExport["format"] = "penguin-memory-scope";
+
+/** The document version this reader accepts. A later format bumps it and states its own compatibility. */
+const SCOPE_FORMAT_VERSION: MemoryScopeExport["version"] = 1;
+
+/**
+ * What one import may carry.
+ *
+ * These are Memory's own numbers, not the attachment budget's: an attachment is an opaque blob
+ * handed to the model's file tools, while a memory is Markdown the model wrote for itself to
+ * re-read, and 100MB of it would be a scope no index could describe. The request as a whole is
+ * already bounded by the API body cap before any of this runs — what follows bounds what one
+ * scope directory can be made to hold.
+ */
+/** Topic files one document may carry. A scope the model keeps by hand runs to tens of files, so this is far past ordinary use and still a directory that lists. */
+const MAX_IMPORT_FILES = 500;
+
+/** Bytes of one file's text (UTF-8), the index included. A memory that does not fit in 512KB of Markdown is not a memory. */
+const MAX_IMPORT_FILE_BYTES = 512 * 1024;
+
+/** Bytes across the whole document: one scope directory's total. */
+const MAX_IMPORT_TOTAL_BYTES = 8 * 1024 * 1024;
+
+/**
+ * Bytes of one file name. The name rule says nothing about length, and a name longer than the
+ * filesystem's own limit for a path component fails at the write with ENAMETOOLONG — a 500 for
+ * what is plainly a bad request. 255 is that limit on ext4, APFS and NTFS alike.
+ */
+const MAX_IMPORT_NAME_BYTES = 255;
+
+/**
+ * Matches an index line's Markdown link to one file — `](file)`, `](./file)`, `](<file>)`,
+ * `](file "title")`. A prose mention of the name is not a link and never matches, which is what
+ * keeps both index edits (prune on delete, extend on import) mechanical rather than clever.
+ */
+function indexLinkPattern(fileName: string): RegExp {
+ const escaped = fileName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return new RegExp(`\\]\\(\\s*<?(?:\\./)?${escaped}>?\\s*(?:"[^"]*"\\s*)?\\)`);
+}
+
/**
* Whether a name is a topic file: any Markdown file that is not a dotfile (`.workspace` is the
* Harness's), carries no path separator, and is not the index under any casing — macOS and
@@ -66,6 +115,82 @@ export function isTopicFileName(name: string): boolean {
);
}
+/**
+ * Validates a transfer document on its way to the server's disk.
+ *
+ * Everything here is untrusted: the document may have been hand-written, produced by another
+ * tool, or crafted. So the shape is checked field by field before any of it is believed, and the
+ * result carries only what was verified — the entry names are handed to the same `resolveFile`
+ * check that guards every other write, which is what keeps one definition of "a legal memory
+ * file name" in the service.
+ *
+ * Refuses, with the reason: a foreign or future format, entries that are not text, a name that
+ * carries a NUL or is longer than a path component may be (both of which the filesystem layer
+ * would throw on rather than reject), the same name twice, and any of the size bounds.
+ */
+function parseTransferDocument(payload: unknown): {
+ index: string | null;
+ files: MemoryTransferFile[];
+} {
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
+ throw badRequest("payload must be a Memory scope export object.");
+ }
+ const doc = payload as Record<string, unknown>;
+ if (doc.format !== SCOPE_FORMAT) {
+ throw badRequest(`payload.format must be "${SCOPE_FORMAT}".`);
+ }
+ if (doc.version !== SCOPE_FORMAT_VERSION) {
+ throw badRequest(`payload.version must be ${SCOPE_FORMAT_VERSION}.`);
+ }
+ if (!Array.isArray(doc.files)) throw badRequest("payload.files must be an array.");
+ if (doc.files.length > MAX_IMPORT_FILES) {
+ throw badRequest(`payload.files must hold at most ${MAX_IMPORT_FILES} entries.`);
+ }
+ let total = 0;
+ const measure = (text: string, label: string): void => {
+ if (text.includes("\u0000")) throw badRequest(`${label} must be text.`);
+ const bytes = Buffer.byteLength(text, "utf8");
+ if (bytes > MAX_IMPORT_FILE_BYTES) {
+ throw badRequest(`${label} exceeds the ${MAX_IMPORT_FILE_BYTES / 1024}KB limit.`);
+ }
+ total += bytes;
+ if (total > MAX_IMPORT_TOTAL_BYTES) {
+ throw badRequest(
+ `payload exceeds the ${MAX_IMPORT_TOTAL_BYTES / (1024 * 1024)}MB total limit.`,
+ );
+ }
+ };
+
+ let index: string | null = null;
+ if (doc.index !== null && doc.index !== undefined) {
+ if (typeof doc.index !== "string") throw badRequest("payload.index must be a string or null.");
+ measure(doc.index, "payload.index");
+ index = doc.index;
+ }
+
+ const files: MemoryTransferFile[] = [];
+ const seen = new Set<string>();
+ for (const entry of doc.files) {
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
+ throw badRequest("Each payload.files entry must be an object.");
+ }
+ const { name, content } = entry as Record<string, unknown>;
+ if (typeof name !== "string") throw badRequest("Each payload.files entry needs a name.");
+ if (typeof content !== "string") {
+ throw badRequest(`Content of ${name} must be a string.`);
+ }
+ if (name.includes("\u0000")) throw badRequest("A file name must be text.");
+ if (Buffer.byteLength(name, "utf8") > MAX_IMPORT_NAME_BYTES) {
+ throw badRequest(`A file name must be at most ${MAX_IMPORT_NAME_BYTES} bytes.`);
+ }
+ if (seen.has(name)) throw badRequest(`payload.files names ${name} twice.`);
+ seen.add(name);
+ measure(content, `Content of ${name}`);
+ files.push({ name, content });
+ }
+ return { index, files };
+}
+
export class MemoryService {
constructor(
private readonly root: string,
@@ -152,10 +277,24 @@ export class MemoryService {
kind,
...(workspacePath !== undefined ? { workspacePath } : {}),
fileCount: files.length,
+ hasIndex: await this.hasIndexFile(dir),
...(latest > 0 ? { updatedAt: new Date(latest).toISOString() } : {}),
};
}
+ /**
+ * Whether the scope holds its own `MEMORY.md`. lstat, not stat: a symlink planted at that name
+ * is not an index — treating it as one would carry a read or a write outside the Memory
+ * directory, and the atomic write below replaces such a link instead of following it.
+ */
+ private async hasIndexFile(dir: string): Promise<boolean> {
+ try {
+ return (await fs.lstat(path.join(dir, MEMORY_INDEX_FILENAME))).isFile();
+ } catch {
+ return false;
+ }
+ }
+
/** Topic files of one scope: regular Markdown files only — the index, the `.workspace` marker, stray directories and symlinks (dirents that are not regular files) all stay out. */
private async topicFileNames(dir: string): Promise<string[]> {
try {
@@ -208,6 +347,172 @@ export class MemoryService {
}
}
+ /**
+ * The whole scope as one transfer document: every topic file plus the scope's own `MEMORY.md`.
+ *
+ * JSON rather than an archive, because the payload is entirely UTF-8 Markdown and the import
+ * side of it is an untrusted write into the Agent's Memory directory: a JSON document carries
+ * no paths, no permissions and no compression, so its entries can go through the same per-file
+ * name check every other write here uses, with nothing to unpack first.
+ *
+ * Unreadable entries are left out rather than failing the export, as elsewhere in this service.
+ * The size bounds below apply to import only — an export reports what the directory actually
+ * holds, and a scope grown past them is exactly the thing its owner needs to see.
+ */
+ async exportScope(
+ projectId: string,
+ agentId: string,
+ scopeKey: string,
+ ): Promise<MemoryScopeExport> {
+ const dir = await this.requireScopeDir(projectId, agentId, scopeKey);
+ const files: MemoryTransferFile[] = [];
+ for (const name of await this.topicFileNames(dir)) {
+ const content = await this.readTextFile(path.join(dir, name));
+ if (content !== null) files.push({ name, content });
+ }
+ const kind = scopeKey === USER_SCOPE_KEY ? "user" : "workspace";
+ const workspacePath = kind === "workspace" ? await readWorkspaceMarker(dir) : undefined;
+ return {
+ format: SCOPE_FORMAT,
+ version: SCOPE_FORMAT_VERSION,
+ scopeKey,
+ kind,
+ ...(workspacePath !== undefined ? { workspacePath } : {}),
+ exportedAt: new Date().toISOString(),
+ index: (await this.hasIndexFile(dir))
+ ? await this.readTextFile(path.join(dir, MEMORY_INDEX_FILENAME))
+ : null,
+ files,
+ };
+ }
+
+ /**
+ * Writes a transfer document into one scope.
+ *
+ * The default mode keeps every file already on disk and writes only names the scope does not
+ * have, so an import can never cost the user a memory they did not agree to lose. `overwrite`
+ * replaces a same-named file's content and `replace` additionally deletes what the document
+ * does not carry; both are refused with 409 unless `confirm` is set — but only when they would
+ * actually destroy something, since a confirmation that names nothing is just a click.
+ *
+ * The index follows the files. A scope with no index takes the document's; `replace` takes it
+ * too (the whole scope is being replaced); a merge keeps the index that is there and appends
+ * the document's lines for the files this import added, because only the indexes enter the
+ * model's context and an unindexed memory is one the Agent never reads.
+ */
+ async importScope(
+ projectId: string,
+ agentId: string,
+ scopeKey: string,
+ request: { mode: MemoryImportMode; confirm: boolean; payload: unknown },
+ ): Promise<MemoryImportResponse> {
+ const dir = await this.requireScopeDir(projectId, agentId, scopeKey);
+ const { index, files } = parseTransferDocument(request.payload);
+ // Names are resolved before anything is written, so a document with one bad entry writes
+ // nothing at all rather than half of itself.
+ const planned = files.map((f) => ({ ...f, target: this.resolveFile(dir, f.name) }));
+
+ const present = new Set(await this.topicFileNames(dir));
+ const carried = new Set(files.map((f) => f.name));
+ const collides = files.filter((f) => present.has(f.name)).map((f) => f.name);
+ const removed =
+ request.mode === "replace" ? [...present].filter((name) => !carried.has(name)) : [];
+ const overwritten = request.mode === "skip" ? [] : collides;
+ const skipped = request.mode === "skip" ? collides : [];
+ // `replace` takes the document's index over the scope's own, which is the user's text too.
+ const replacesIndex =
+ request.mode === "replace" && index !== null && (await this.hasIndexFile(dir));
+ if (!request.confirm && (overwritten.length > 0 || removed.length > 0 || replacesIndex)) {
+ throw new HttpError(
+ 409,
+ "memory_import_confirm_required",
+ `This import would overwrite ${overwritten.length} and delete ${removed.length} memories in ${scopeKey}` +
+ `${replacesIndex ? `, and replace its ${MEMORY_INDEX_FILENAME}` : ""}. Repeat it with confirm set.`,
+ );
+ }
+
+ const added: string[] = [];
+ for (const file of planned) {
+ if (request.mode === "skip" && present.has(file.name)) continue;
+ await this.writeScopeFile(dir, file.target, file.content);
+ if (!present.has(file.name)) added.push(file.name);
+ }
+ for (const name of removed) {
+ await fs.unlink(path.join(dir, name)).catch(() => {
+ // Raced with a delete from a Session: the file is gone either way.
+ });
+ }
+
+ const written = [...added, ...overwritten];
+ let indexWritten = false;
+ if (index !== null) {
+ if (replacesIndex || !(await this.hasIndexFile(dir))) {
+ await this.writeScopeFile(dir, path.join(dir, MEMORY_INDEX_FILENAME), index);
+ indexWritten = true;
+ } else {
+ indexWritten = await this.extendIndex(dir, index, written);
+ }
+ }
+ // Whatever the index now says, it must not list a file this import deleted.
+ for (const name of removed) await this.pruneIndexLines(dir, name);
+
+ return { scopeKey, mode: request.mode, added, overwritten, skipped, removed, indexWritten };
+ }
+
+ /**
+ * Appends the document's index lines for the files this import wrote: a line linking a written
+ * file that the scope's index does not already link is added at the end, in the document's own
+ * order. Nothing else is touched — the mirror image of pruneIndexLines, so between them the
+ * index lists neither a file that is gone nor omits one that arrived.
+ */
+ private async extendIndex(dir: string, docIndex: string, written: string[]): Promise<boolean> {
+ const indexPath = path.join(dir, MEMORY_INDEX_FILENAME);
+ const current = await this.readTextFile(indexPath);
+ if (current === null) return false;
+ const docLines = docIndex.split("\n");
+ const additions: string[] = [];
+ for (const name of written) {
+ const link = indexLinkPattern(name);
+ if (link.test(current)) continue;
+ const line = docLines.find((l) => link.test(l));
+ if (line !== undefined && !additions.includes(line)) additions.push(line);
+ }
+ if (additions.length === 0) return false;
+ const head = current === "" || current.endsWith("\n") ? current : `${current}\n`;
+ await this.writeScopeFile(dir, indexPath, `${head}${additions.join("\n")}\n`);
+ return true;
+ }
+
+ /**
+ * The write path for imported content, shared by the topic files and the index.
+ *
+ * The target has already been through `resolveFile` (or is the reserved index name, which is
+ * never client-supplied), so it names a file directly inside this scope. The write goes to a
+ * temporary dotfile — invisible to every topic listing — and is renamed over the target, so a
+ * symlink standing at that name is replaced rather than followed out of the Memory directory,
+ * and a reader never sees a half-written memory.
+ */
+ private async writeScopeFile(dir: string, target: string, content: string): Promise<void> {
+ const tmp = path.join(dir, `.import-${randomBytes(6).toString("hex")}.tmp`);
+ try {
+ await fs.writeFile(tmp, content, "utf8");
+ await fs.rename(tmp, target);
+ } catch (err) {
+ await fs.rm(tmp, { force: true });
+ throw err;
+ }
+ }
+
+ /** Reads a regular file as text, null when it is absent, unreadable, or not a regular file (lstat, so a symlink is never followed). */
+ private async readTextFile(target: string): Promise<string | null> {
+ try {
+ if (!(await fs.lstat(target)).isFile()) return null;
+ return await fs.readFile(target, "utf8");
+ } catch {
+ return null;
+ }
+ }
+
/**
* Deletes a topic file and mechanically drops its lines from the scope's `MEMORY.md`: any
* line whose Markdown link target is exactly this file (`](<file>)`) goes; a mention of the
@@ -239,10 +544,7 @@ export class MemoryService {
} catch {
return;
}
- // Match the mechanical link forms an index line may use: `](file)`, `](./file)`,
- // `](<file>)`, `](file "title")`. A prose mention without the link form survives.
- const escaped = fileName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- const link = new RegExp(`\\]\\(\\s*<?(?:\\./)?${escaped}>?\\s*(?:"[^"]*"\\s*)?\\)`);
+ const link = indexLinkPattern(fileName);
const lines = content.split("\n");
const kept = lines.filter((line) => !link.test(line));
if (kept.length === lines.length) return;
diff --git a/packages/server/test/memory.test.ts b/packages/server/test/memory.test.ts
index 26c60ead..f85a1f1f 100644
--- a/packages/server/test/memory.test.ts
+++ b/packages/server/test/memory.test.ts
@@ -4,6 +4,10 @@
* read / deleted, deleting a file prunes its index lines, path traversal in a scope key or
* file name is rejected, the switch round-trips through the Agent config without touching any
* file, and non-members see 404.
+ *
+ * A second suite covers whole-scope transfer: what an export carries, each branch of the import
+ * collision policy (skip / overwrite / replace, and when a confirmation is required), every
+ * rejection on that untrusted write path, and the owner gate on import.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -18,7 +22,11 @@ import type {
AgentConfigResponse,
MemoryFileResponse,
MemoryFilesResponse,
+ MemoryImportMode,
+ MemoryImportResponse,
MemoryOverviewResponse,
+ MemoryScopeExport,
+ MemoryTransferFile,
ProjectCreateResponse,
} from "../src/api/types.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
@@ -297,3 +305,380 @@ describe("memory api", () => {
expect((await outsider.delete(`${filesPath()}/x.md`)).status).toBe(404);
});
});
+
+describe("memory scope export/import", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ let member: ReturnType<typeof apiClient>;
+ let outsider: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let memoryPath: string;
+ let wsDir: string;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_a");
+ const b = await provisionUser(t.app, "member_b");
+ const c = await provisionUser(t.app, "outsider_c");
+ owner = apiClient(t.app, a.cookie);
+ member = apiClient(t.app, b.cookie);
+ outsider = apiClient(t.app, c.cookie);
+ const created = (await (
+ await owner.post("/api/projects", { projectId: "owner_a-transfer", name: "transfer" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ expect(
+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,
+ ).toBe(201);
+ memoryPath = `/api/projects/${projectId}/agents/default_agent/memory`;
+ wsDir = memoryScopeDir(t.root, projectId, "default_agent", WORKSPACE_KEY);
+ await fs.mkdir(wsDir, { recursive: true });
+ await fs.writeFile(path.join(wsDir, ".workspace"), "/home/dev/my-app\n", "utf8");
+ });
+
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ const exportPath = (key = WORKSPACE_KEY) => `${memoryPath}/scopes/${key}/export`;
+ const importPath = (key = WORKSPACE_KEY) => `${memoryPath}/scopes/${key}/import`;
+
+ /** A transfer document carrying the given files; its index links each of them unless one is given. */
+ const document = (files: MemoryTransferFile[], index?: string | null): MemoryScopeExport => ({
+ format: "penguin-memory-scope",
+ version: 1,
+ scopeKey: WORKSPACE_KEY,
+ kind: "workspace",
+ exportedAt: "2026-08-20T00:00:00.000Z",
+ index:
+ index === undefined
+ ? `# Memories\n\n${files.map((f) => `- [${f.name}](${f.name}) — imported`).join("\n")}\n`
+ : index,
+ files,
+ });
+
+ const topic = (name: string, body: string): MemoryTransferFile => ({
+ name,
+ content: `---\nname: ${name}\n---\n${body}\n`,
+ });
+
+ const runImport = async (
+ payload: unknown,
+ opts: { mode?: MemoryImportMode; confirm?: boolean; key?: string } = {},
+ ) =>
+ owner.post(importPath(opts.key), {
+ payload,
+ ...(opts.mode !== undefined ? { mode: opts.mode } : {}),
+ ...(opts.confirm !== undefined ? { confirm: opts.confirm } : {}),
+ });
+
+ const namesOnDisk = async (): Promise<string[]> =>
+ (await fs.readdir(wsDir))
+ .filter((n) => n.endsWith(".md") && n !== MEMORY_INDEX_FILENAME)
+ .sort();
+
+ const readIndex = (): Promise<string> =>
+ fs.readFile(path.join(wsDir, MEMORY_INDEX_FILENAME), "utf8");
+
+ it("exports every topic file plus the scope's index, as one attachment", async () => {
+ await fs.writeFile(path.join(wsDir, "testing-conventions.md"), TOPIC, "utf8");
+ await fs.writeFile(path.join(wsDir, "项目背景.md"), "---\nname: 项目背景\n---\n正文\n", "utf8");
+ await fs.writeFile(path.join(wsDir, MEMORY_INDEX_FILENAME), "- [t](t.md) — hook\n", "utf8");
+
+ const res = await owner.get(exportPath());
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-disposition")).toMatch(
+ new RegExp(`filename="default_agent-${WORKSPACE_KEY}-memory-\\d{8}-\\d{4}\\.json"`),
+ );
+ const doc = (await res.json()) as MemoryScopeExport;
+ expect(doc.format).toBe("penguin-memory-scope");
+ expect(doc.version).toBe(1);
+ expect(doc.kind).toBe("workspace");
+ expect(doc.workspacePath).toBe("/home/dev/my-app");
+ // The index travels with the files: only the index enters the model's context.
+ expect(doc.index).toBe("- [t](t.md) — hook\n");
+ expect(doc.files.map((f) => f.name)).toEqual(["testing-conventions.md", "项目背景.md"]);
+ expect(doc.files[0]?.content).toBe(TOPIC);
+ // The .workspace marker is the Harness's, not a memory.
+ expect(doc.files.map((f) => f.name)).not.toContain(".workspace");
+ });
+
+ it("exports the user scope, creating it on demand, with no workspace path", async () => {
+ const doc = (await (await owner.get(exportPath(USER_SCOPE_KEY))).json()) as MemoryScopeExport;
+ expect(doc.kind).toBe("user");
+ expect(doc.workspacePath).toBeUndefined();
+ // A provisioned Agent starts with an empty user index on disk, so the document carries an
+ // empty string; null is reserved for a scope that has no MEMORY.md at all — as this
+ // Workspace scope, created by hand above, does not.
+ expect(doc.index).toBe("");
+ expect(doc.files).toEqual([]);
+ expect(((await (await owner.get(exportPath())).json()) as MemoryScopeExport).index).toBeNull();
+ });
+
+ it("round-trips one scope's export into another scope", async () => {
+ await fs.writeFile(path.join(wsDir, "testing-conventions.md"), TOPIC, "utf8");
+ await fs.writeFile(path.join(wsDir, MEMORY_INDEX_FILENAME), "- [T](testing-conventions.md)\n");
+ const doc = (await (await owner.get(exportPath())).json()) as MemoryScopeExport;
+
+ const res = await runImport(doc, { key: USER_SCOPE_KEY });
+ expect(res.status).toBe(200);
+ expect((await res.json()) as MemoryImportResponse).toMatchObject({
+ scopeKey: USER_SCOPE_KEY,
+ mode: "skip",
+ added: ["testing-conventions.md"],
+ indexWritten: true,
+ });
+ const userDir = memoryScopeDir(t.root, projectId, "default_agent", USER_SCOPE_KEY);
+ expect(await fs.readFile(path.join(userDir, "testing-conventions.md"), "utf8")).toBe(TOPIC);
+ expect(await fs.readFile(path.join(userDir, MEMORY_INDEX_FILENAME), "utf8")).toBe(
+ "- [T](testing-conventions.md)\n",
+ );
+ });
+
+ // —— The collision policy, branch by branch ——
+
+ it("defaults to skip: an existing memory is kept and the newcomer is indexed beside it", async () => {
+ await fs.writeFile(path.join(wsDir, "keep.md"), "on disk\n", "utf8");
+ await fs.writeFile(path.join(wsDir, MEMORY_INDEX_FILENAME), "- [Keep](keep.md) — mine\n");
+
+ const res = await runImport(
+ document([topic("keep.md", "from the file"), topic("new.md", "n")]),
+ );
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as MemoryImportResponse;
+ expect(body).toMatchObject({ mode: "skip", added: ["new.md"], skipped: ["keep.md"] });
+ expect(body.overwritten).toEqual([]);
+ expect(body.removed).toEqual([]);
+ // Nothing was lost: the file on disk is untouched.
+ expect(await fs.readFile(path.join(wsDir, "keep.md"), "utf8")).toBe("on disk\n");
+ // The index keeps its own line and gains one for the file that arrived — an unindexed
+ // memory would be one the Agent never reads.
+ const index = await readIndex();
+ expect(index).toContain("- [Keep](keep.md) — mine");
+ expect(index).toContain("- [new.md](new.md) — imported");
+ expect(body.indexWritten).toBe(true);
+ });
+
+ it("refuses overwrite and replace without confirmation, naming what would be lost", async () => {
+ await fs.writeFile(path.join(wsDir, "keep.md"), "on disk\n", "utf8");
+ const doc = document([topic("keep.md", "from the file")]);
+
+ for (const mode of ["overwrite", "replace"] as const) {
+ const res = await runImport(doc, { mode });
+ expect(res.status).toBe(409);
+ const body = (await res.json()) as { error: { code: string; message: string } };
+ expect(body.error.code).toBe("memory_import_confirm_required");
+ expect(body.error.message).toContain("overwrite 1");
+ }
+ expect(await fs.readFile(path.join(wsDir, "keep.md"), "utf8")).toBe("on disk\n");
+ });
+
+ it("overwrites same-named memories on confirmation and leaves the rest alone", async () => {
+ await fs.writeFile(path.join(wsDir, "keep.md"), "on disk\n", "utf8");
+ await fs.writeFile(path.join(wsDir, "untouched.md"), "not in the document\n", "utf8");
+
+ const res = await runImport(document([topic("keep.md", "from the file")]), {
+ mode: "overwrite",
+ confirm: true,
+ });
+ expect(res.status).toBe(200);
+ expect((await res.json()) as MemoryImportResponse).toMatchObject({
+ mode: "overwrite",
+ added: [],
+ overwritten: ["keep.md"],
+ removed: [],
+ });
+ expect(await fs.readFile(path.join(wsDir, "keep.md"), "utf8")).toContain("from the file");
+ // overwrite is a merge: a memory the document does not carry survives.
+ expect(await namesOnDisk()).toEqual(["keep.md", "untouched.md"]);
+ });
+
+ it("replaces the whole scope on confirmation, deleting what the document does not carry", async () => {
+ await fs.writeFile(path.join(wsDir, "keep.md"), "on disk\n", "utf8");
+ await fs.writeFile(path.join(wsDir, "gone.md"), "not in the document\n", "utf8");
+ await fs.writeFile(
+ path.join(wsDir, MEMORY_INDEX_FILENAME),
+ "- [Keep](keep.md) — mine\n- [Gone](gone.md) — mine\n",
+ "utf8",
+ );
+
+ const res = await runImport(document([topic("keep.md", "from the file")]), {
+ mode: "replace",
+ confirm: true,
+ });
+ expect(res.status).toBe(200);
+ expect((await res.json()) as MemoryImportResponse).toMatchObject({
+ mode: "replace",
+ overwritten: ["keep.md"],
+ removed: ["gone.md"],
+ indexWritten: true,
+ });
+ expect(await namesOnDisk()).toEqual(["keep.md"]);
+ // The document's index replaces the old one wholesale; no line survives for a deleted file.
+ const index = await readIndex();
+ expect(index).toContain("- [keep.md](keep.md) — imported");
+ expect(index).not.toContain("gone.md");
+ });
+
+ it("prunes the index of a replace whose document carries none", async () => {
+ await fs.writeFile(path.join(wsDir, "gone.md"), "x\n", "utf8");
+ await fs.writeFile(path.join(wsDir, MEMORY_INDEX_FILENAME), "- [Gone](gone.md) — mine\n");
+
+ const res = await runImport(document([topic("new.md", "n")], null), {
+ mode: "replace",
+ confirm: true,
+ });
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as MemoryImportResponse).removed).toEqual(["gone.md"]);
+ expect(await readIndex()).not.toContain("gone.md");
+ });
+
+ it("needs no confirmation for a destructive mode that would destroy nothing", async () => {
+ // The gate is what the import would actually cost, not the mode's name: an empty scope
+ // loses nothing either way, and a confirmation naming nothing is just a click.
+ const res = await runImport(document([topic("new.md", "n")]), { mode: "replace" });
+ expect(res.status).toBe(200);
+ expect((await res.json()) as MemoryImportResponse).toMatchObject({
+ added: ["new.md"],
+ removed: [],
+ overwritten: [],
+ });
+ });
+
+ // —— Rejections on the untrusted write path ——
+
+ /** The NUL byte, built rather than typed: an invisible byte in a source file is nobody's friend. */
+ const NUL = String.fromCharCode(0);
+
+ /** Posts a document (or a whole raw body) that must be refused with 400, having written nothing. */
+ const rejects = async (files: unknown, hint: string): Promise<void> => {
+ const res = await runImport(
+ Array.isArray(files) ? document(files as MemoryTransferFile[]) : files,
+ );
+ expect(res.status, hint).toBe(400);
+ };
+
+ it("rejects a name that is a path, climbs out, or is not a topic file", async () => {
+ const outside = path.join(t.root, "outside-target.md");
+ await rejects([topic("../escape.md", "x")], "parent traversal");
+ await rejects([topic("..\\escape.md", "x")], "windows traversal");
+ await rejects([topic("sub/notes.md", "x")], "nested path");
+ await rejects([topic(outside, "x")], "absolute path");
+ await rejects([topic(MEMORY_INDEX_FILENAME, "x")], "the index is not a topic file");
+ await rejects([topic("memory.md", "x")], "the index under another casing");
+ await rejects([topic("notes.txt", "x")], "not markdown");
+ await rejects([topic(".workspace", "x")], "the workspace marker");
+ await rejects([topic("", "x")], "empty name");
+ await rejects([topic(`bad${NUL}.md`, "x")], "NUL in the name");
+ // Not one of them reached the filesystem, inside the scope or out.
+ expect(await namesOnDisk()).toEqual([]);
+ await expect(fs.stat(outside)).rejects.toThrow();
+ });
+
+ it("writes nothing at all when one entry in the document is bad", async () => {
+ const res = await runImport(document([topic("fine.md", "ok"), topic("../escape.md", "x")]));
+ expect(res.status).toBe(400);
+ expect(await namesOnDisk()).toEqual([]);
+ });
+
+ it("rejects entries that are not text", async () => {
+ await rejects([{ name: "n.md", content: 42 }], "number content");
+ await rejects([{ name: "n.md", content: { body: "x" } }], "object content");
+ await rejects([{ name: "n.md" }], "missing content");
+ await rejects([{ name: 7, content: "x" }], "non-string name");
+ await rejects(["n.md"], "entry is not an object");
+ await rejects([{ name: "n.md", content: `binary${NUL}payload` }], "NUL in the content");
+ await rejects({ ...document([topic("n.md", "x")]), index: 5 }, "non-string index");
+ expect(await namesOnDisk()).toEqual([]);
+ });
+
+ it("rejects absurd counts and sizes", async () => {
+ await rejects(
+ Array.from({ length: 501 }, (_, i) => topic(`m${i}.md`, "x")),
+ "too many entries",
+ );
+ await rejects([{ name: "huge.md", content: "x".repeat(512 * 1024 + 1) }], "one oversized file");
+ // Longer than a path component may be: the write would fail with ENAMETOOLONG, which is a
+ // 500 for what is plainly a bad request.
+ await rejects([topic(`${"a".repeat(253)}.md`, "x")], "an oversized name");
+ // Individually legal, together over the whole-document budget.
+ const half = "y".repeat(512 * 1024);
+ await rejects(
+ Array.from({ length: 17 }, (_, i) => ({ name: `big${i}.md`, content: half })),
+ "over the total budget",
+ );
+ expect(await namesOnDisk()).toEqual([]);
+ });
+
+ it("rejects a foreign or future document, and a body with no document at all", async () => {
+ await rejects({ ...document([]), format: "some-other-tool" }, "foreign format");
+ await rejects({ ...document([]), version: 2 }, "future version");
+ await rejects({ ...document([]), files: "not-an-array" }, "files is not an array");
+ await rejects([topic("a.md", "1"), topic("a.md", "2")], "the same name twice");
+ expect((await owner.post(importPath(), {})).status).toBe(400);
+ expect((await owner.post(importPath(), { payload: "text" })).status).toBe(400);
+ expect((await owner.post(importPath(), { payload: document([]), mode: "wipe" })).status).toBe(
+ 400,
+ );
+ });
+
+ it("replaces a symlink standing at a memory's name instead of writing through it", async () => {
+ const outside = path.join(t.root, "outside-secret.md");
+ await fs.writeFile(outside, "secret\n", "utf8");
+ await fs.symlink(outside, path.join(wsDir, "leak.md"));
+
+ const res = await runImport(document([topic("leak.md", "imported body")]), {
+ mode: "overwrite",
+ confirm: true,
+ });
+ expect(res.status).toBe(200);
+ // The link is gone, the memory is a real file inside the scope, and the file it pointed at
+ // never saw the write.
+ expect((await fs.lstat(path.join(wsDir, "leak.md"))).isSymbolicLink()).toBe(false);
+ expect(await fs.readFile(path.join(wsDir, "leak.md"), "utf8")).toContain("imported body");
+ expect(await fs.readFile(outside, "utf8")).toBe("secret\n");
+ });
+
+ it("leaves no temporary file behind in the scope directory", async () => {
+ expect((await runImport(document([topic("a.md", "x")]))).status).toBe(200);
+ expect((await fs.readdir(wsDir)).filter((n) => n.endsWith(".tmp"))).toEqual([]);
+ });
+
+ it("rejects a bad scope key and a scope smuggled in as a symlink, on both routes", async () => {
+ expect((await owner.get(exportPath("..%2Fescape"))).status).toBe(400);
+ expect((await runImport(document([]), { key: "..%2Fescape" })).status).toBe(400);
+ expect((await owner.get(exportPath("never-run-0badc0de"))).status).toBe(404);
+ expect((await runImport(document([]), { key: "never-run-0badc0de" })).status).toBe(404);
+
+ const outside = path.join(t.root, "outside-dir");
+ await fs.mkdir(outside, { recursive: true });
+ await fs.symlink(outside, memoryScopeDir(t.root, projectId, "default_agent", "evil-12345678"));
+ expect((await owner.get(exportPath("evil-12345678"))).status).toBe(404);
+ expect((await runImport(document([topic("a.md", "x")]), { key: "evil-12345678" })).status).toBe(
+ 404,
+ );
+ expect(await fs.readdir(outside)).toEqual([]);
+ });
+
+ // —— Authorization ——
+
+ it("lets any member export but only the owner import", async () => {
+ await fs.writeFile(path.join(wsDir, "testing-conventions.md"), TOPIC, "utf8");
+ // Export is reading Agent State, which every Project member may already do file by file.
+ expect((await member.get(exportPath())).status).toBe(200);
+ // Import can cost the Agent memories, so it follows the Agent State snapshot's owner gate.
+ const denied = await member.post(importPath(), { payload: document([topic("a.md", "x")]) });
+ expect(denied.status).toBe(403);
+ expect(((await denied.json()) as { error: { code: string } }).error.code).toBe(
+ "owner_required",
+ );
+ expect(await namesOnDisk()).toEqual(["testing-conventions.md"]);
+ });
+
+ it("404s both routes for a non-member, without leaking that the scope exists", async () => {
+ expect((await outsider.get(exportPath())).status).toBe(404);
+ const res = await outsider.post(importPath(), { payload: document([topic("a.md", "x")]) });
+ expect(res.status).toBe(404);
+ expect(await namesOnDisk()).toEqual([]);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index fad2509a..daf67eb2 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -42,7 +42,10 @@ import type {
MembersResponse,
MemoryFileResponse,
MemoryFilesResponse,
+ MemoryImportRequest,
+ MemoryImportResponse,
MemoryOverviewResponse,
+ MemoryScopeExport,
MessagesResponse,
ModelProtocolDetectRequest,
ModelProtocolDetectResponse,
@@ -293,6 +296,30 @@ export const deleteMemoryFile = (
method: "DELETE",
});
+const memoryScopeBase = (projectId: string, agentId: string, scopeKey: string) =>
+ `${memoryBase(projectId, agentId)}/scopes/${encodeURIComponent(scopeKey)}`;
+
+/**
+ * One scope as a transfer document. Fetched as ordinary JSON rather than followed as a download
+ * link so a failure arrives as an ApiError and reaches the user as a toast — a bare `<a download>`
+ * would save the error body as a file (the skills tab hit the same wall). The server still sets
+ * Content-Disposition, for anyone opening the URL directly.
+ */
+export const exportMemoryScope = (projectId: string, agentId: string, scopeKey: string) =>
+ apiFetch<MemoryScopeExport>(`${memoryScopeBase(projectId, agentId, scopeKey)}/export`);
+
+/** Writes a transfer document into one scope (owner only); `confirm` is required by the modes that would destroy something. */
+export const importMemoryScope = (
+ projectId: string,
+ agentId: string,
+ scopeKey: string,
+ body: MemoryImportRequest,
+) =>
+ apiFetch<MemoryImportResponse>(`${memoryScopeBase(projectId, agentId, scopeKey)}/import`, {
+ method: "POST",
+ body,
+ });
+
// Agent & its configuration ----------------------------------------------------------------
export const listAgents = (projectId: string) =>
diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsx
index 1b14ec0d..5145d5fe 100644
--- a/packages/web/src/features/agents/memory-tab.tsx
+++ b/packages/web/src/features/agents/memory-tab.tsx
@@ -3,13 +3,18 @@
* scope — user memory first (read by every Session), then one group per Workspace (labeled by
* its `.workspace` path, newest activity first).
*
- * The tab is read + delete only, matching the API: a memory's content is the model's document,
- * so both "edit" and each scope header's "add" open a bridge modal first — a text field and
- * a live preview of the generated prompt, the same shape as the skill import modal — and then
- * jump to a new chat with this Agent and the prompt as the prefilled draft (the same
- * draft-cache route). For a Workspace scope the draft also pins that Workspace, so the Session
- * is injected with the very index it is about to change. Deleting confirms first and also
- * drops the file's MEMORY.md index lines (server-side).
+ * A memory's content is the model's document, so per-file editing stays out of the tab: both
+ * "edit" and each scope header's "add" open a bridge modal first — a text field and a live
+ * preview of the generated prompt, the same shape as the skill import modal — and then jump to
+ * a new chat with this Agent and the prompt as the prefilled draft (the same draft-cache
+ * route). For a Workspace scope the draft also pins that Workspace, so the Session is injected
+ * with the very index it is about to change. Deleting confirms first and also drops the file's
+ * MEMORY.md index lines (server-side).
+ *
+ * A whole group moves in one piece, though: each header carries export and import, following
+ * the Agent State snapshot's split — any member may download a group, only the owner may write
+ * one back. Import defaults to the mode that loses nothing, and the two that do not are held
+ * behind a confirmation naming the memories at stake.
*
* The switch writes immediately rather than joining a tab-level Save, so turning Memory off
* never drags an unrelated half-finished edit along with it. Off keeps every file and this tab
@@ -17,23 +22,33 @@
* for new Sessions.
*/
import { useCallback, useEffect, useRef, useState } from "react";
-import type { RefObject } from "react";
+import type { ChangeEvent, RefObject } from "react";
import { useNavigate } from "react-router";
-import type { MemoryFileInfo, MemoryScopeInfo } from "@prismshadow/penguin-server/api";
+import type {
+ MemoryFileInfo,
+ MemoryImportMode,
+ MemoryScopeExport,
+ MemoryScopeInfo,
+} from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatRelativeDate } from "../../lib/format";
+import { toneStrip } from "../../lib/tone";
import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import { useProject } from "../../state/project";
import { Button } from "../../components/ui/button";
import { CopiedStatus, CopyCheckGlyph, useCopied } from "../../components/ui/copy-button";
import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { InfoPopover } from "../../components/ui/info-popover";
+import { HelpFold } from "../../components/ui/help-fold";
import { Modal } from "../../components/ui/modal";
import { Textarea } from "../../components/ui/input";
import { Switch } from "../../components/ui/switch";
import { Chevron } from "../../components/ui/chevron";
+import { DownloadIcon, UploadIcon } from "../../components/ui/icons";
+import { HiddenFileInput } from "../../components/ui/hidden-file-input";
import { Drawer } from "../../components/ui/drawer";
import { Sheet, type SheetSnap } from "../../components/ui/sheet";
import { ConfirmModal, useSaveConfirm } from "../../components/ui/confirm-modal";
@@ -43,9 +58,13 @@ import { Md } from "../chat/md";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";
import { buildMemoryAddPrompt, buildMemoryEditPrompt } from "./memory-chat-prompts";
-import { toneStrip } from "../../lib/tone";
-import { InfoPopover } from "../../components/ui/info-popover";
-import { HelpFold } from "../../components/ui/help-fold";
+import {
+ MemoryDocumentError,
+ memoryDocumentFileName,
+ parseMemoryScopeDocument,
+ planMemoryImport,
+} from "./memory-transfer";
+import type { MemoryImportPlan } from "./memory-transfer";
/** The body without its frontmatter block: the drawer's metadata header already shows those fields, so rendering the raw YAML too would only repeat them. */
function bodyWithoutFrontmatter(content: string): string {
@@ -64,6 +83,17 @@ const TRASH_ICON =
/** "Add" plus glyph on the group headers, matching the models page's per-group add entry. */
const PLUS_ICON = "M12 5v14M5 12h14";
+/**
+ * The small ghost button's look on a `<label>`: the Button component only renders a `<button>`,
+ * and the import control has to wrap a file input (the Agent State section's transfer label does
+ * the same for its own size). Mirrors Button's `ghost` variant at `sm`, icon + text.
+ */
+const GHOST_LABEL_CLASS =
+ "inline-flex cursor-pointer items-center justify-center gap-1 rounded-md border border-transparent " +
+ "px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 " +
+ "focus-within:ring-2 focus-within:ring-gray-400/30 " +
+ "dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";
+
/**
* Collapsed scope keys, persisted per user \u00d7 Project \u00d7 Agent (localStorage, same conventions as
* the chat draft cache: userId in the key against cross-account leaks, tolerant reads, silent
@@ -117,6 +147,9 @@ export function MemoryTab({
const userId = useAuth().user?.userId ?? null;
const { currentProject, setCurrentAgentId, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
+ // Import writes a whole group at once, so it follows the Agent State snapshot's owner gate;
+ // the server enforces it either way, this only keeps the control out of a member's reach.
+ const isOwner = currentProject?.role === "owner";
const [enabled, setEnabled] = useState(true);
const [templateHasMemory, setTemplateHasMemory] = useState(true);
@@ -142,6 +175,15 @@ export function MemoryTab({
const [editRequirement, setEditRequirement] = useState("");
const [adding, setAdding] = useState<MemoryScopeInfo | null>(null);
const [addContent, setAddContent] = useState("");
+ // A picked document waiting for its mode, then the plan the user is being asked to confirm.
+ const [importing, setImporting] = useState<{
+ scope: MemoryScopeInfo;
+ fileName: string;
+ doc: MemoryScopeExport;
+ } | null>(null);
+ const [importMode, setImportMode] = useState<MemoryImportMode>("skip");
+ const [importPlan, setImportPlan] = useState<MemoryImportPlan | null>(null);
+ const [importBusy, setImportBusy] = useState(false);
const [removing, setRemoving] = useState<Selected | null>(null);
// ≥1024px the view opens as a right Drawer, below as a bottom Sheet — same live-updating
// breakpoint as the chat page's panels; the two are mounted mutually exclusively.
@@ -357,6 +399,85 @@ export function MemoryTab({
if (adding) openChatWithDraft(addPrompt, adding.workspacePath);
};
+ /**
+ * Downloads one group as a transfer document. Fetched as JSON and saved through an object URL
+ * rather than followed as a link, so a failed request becomes a toast instead of an error body
+ * saved to disk (the skills tab's export made the same call).
+ */
+ const exportScope = async (scope: MemoryScopeInfo) => {
+ if (!projectId) return;
+ try {
+ const doc = await api.exportMemoryScope(projectId, agentId, scope.scopeKey);
+ const url = URL.createObjectURL(
+ new Blob([JSON.stringify(doc, null, 2)], { type: "application/json" }),
+ );
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = memoryDocumentFileName(agentId, scope.scopeKey, doc.exportedAt);
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+ URL.revokeObjectURL(url);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ };
+
+ /** Reads the picked file and opens the import modal; a file that is not a document never gets that far. */
+ const pickImport = async (scope: MemoryScopeInfo, event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ // Cleared so picking the same file again still fires a change event.
+ event.target.value = "";
+ if (!file) return;
+ try {
+ const doc = parseMemoryScopeDocument(await file.text());
+ setImportMode("skip");
+ setImporting({ scope, fileName: file.name, doc });
+ } catch (e) {
+ toastError(e instanceof MemoryDocumentError ? e.message : S.memory.importInvalidFile);
+ }
+ };
+
+ const runImport = async (confirm: boolean) => {
+ if (!projectId || !importing) return;
+ setImportBusy(true);
+ try {
+ const res = await api.importMemoryScope(projectId, agentId, importing.scope.scopeKey, {
+ mode: importMode,
+ confirm,
+ payload: importing.doc,
+ });
+ const touched = res.added.length + res.overwritten.length + res.removed.length;
+ if (touched === 0) toastSuccess(S.memory.importNothingNew);
+ else
+ toastSuccess(
+ S.memory.importDone(res.added.length, res.overwritten.length, res.removed.length),
+ );
+ setImportPlan(null);
+ setImporting(null);
+ await load();
+ // The agent card's memory count changed; refresh the list provider too.
+ void reloadAgents();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setImportBusy(false);
+ }
+ };
+
+ /** Import's first click: straight through when nothing would be lost, otherwise into the confirmation. */
+ const submitImport = () => {
+ if (!importing) return;
+ const group = groups?.find((g) => g.scope.scopeKey === importing.scope.scopeKey);
+ const plan = planMemoryImport(
+ importing.doc,
+ { names: group?.files.map((f) => f.name) ?? [], hasIndex: importing.scope.hasIndex },
+ importMode,
+ );
+ if (plan.destroys) setImportPlan(plan);
+ else void runImport(false);
+ };
+
const confirmRemove = async () => {
if (!projectId || !removing) return;
const target = removing;
@@ -488,7 +609,7 @@ export function MemoryTab({
className="overflow-hidden rounded-lg border border-gray-200 dark:border-gray-800"
>
{/* Group header (the models page's group convention): the collapse button fills
- the row, the Add entry is a ghost text button to the chevron's left — a real
+ the row, the group's own actions sit between it and the chevron — a real
<button> cannot nest another, so the actions are siblings, with the hover
highlight on the whole header so it reads as a single unit. */}
<div className="flex items-center gap-2 bg-gray-50 pr-2 transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60">
@@ -511,6 +632,35 @@ export function MemoryTab({
{S.memory.itemCount(files.length)}
</span>
</button>
+ {/* Whole-group transfer, icon + label (the labels are what say which way a
+ transfer goes): export for any member, import for the owner. The tooltip
+ carries what the label cannot — that the whole group travels. */}
+ <span className="shrink-0">
+ <Button
+ size="sm"
+ variant="ghost"
+ title={S.memory.exportScopeHint}
+ aria-label={S.memory.exportScopeLabel(scopeTitle(scope))}
+ onClick={() => void exportScope(scope)}
+ >
+ <DownloadIcon size={13} />
+ {S.memory.exportScope}
+ </Button>
+ </span>
+ {isOwner && (
+ <label
+ className={`${GHOST_LABEL_CLASS} shrink-0`}
+ title={S.memory.importScopeHint}
+ aria-label={S.memory.importScopeLabel(scopeTitle(scope))}
+ >
+ <HiddenFileInput
+ accept=".json,application/json"
+ onChange={(e) => void pickImport(scope, e)}
+ />
+ <UploadIcon size={13} />
+ {S.memory.importScope}
+ </label>
+ )}
<span className="shrink-0">
<Button size="sm" variant="ghost" onClick={() => openAdd(scope)}>
<GlyphIcon d={PLUS_ICON} size={13} />
@@ -743,6 +893,80 @@ export function MemoryTab({
)}
</Modal>
+ {/* Import modal: the file that was picked, then the one consequential choice — what to do
+ with a name this group already has. The default loses nothing; the other two are held
+ behind the confirmation below. */}
+ <Modal
+ open={importing !== null}
+ title={S.memory.importTitle}
+ onClose={() => setImporting(null)}
+ widthClass="sm:max-w-lg"
+ >
+ {importing && (
+ <div className="space-y-3">
+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.memory.importWhy}</p>
+ <p className="break-all font-mono text-[11px] text-gray-500 dark:text-gray-400">
+ {S.memory.importFile(importing.fileName, importing.doc.files.length)}
+ </p>
+ <fieldset className="space-y-2">
+ <legend className="mb-1 text-xs font-medium text-gray-500 dark:text-gray-400">
+ {S.memory.importModeLabel}
+ </legend>
+ {(
+ [
+ ["skip", S.memory.importModeSkip, S.memory.importModeSkipHint],
+ ["overwrite", S.memory.importModeOverwrite, S.memory.importModeOverwriteHint],
+ ["replace", S.memory.importModeReplace, S.memory.importModeReplaceHint],
+ ] as [MemoryImportMode, string, string][]
+ ).map(([mode, label, hint]) => (
+ <label key={mode} className="flex cursor-pointer items-start gap-2 text-sm">
+ <input
+ type="radio"
+ name="memory-import-mode"
+ className="mt-1 shrink-0"
+ checked={importMode === mode}
+ onChange={() => setImportMode(mode)}
+ />
+ <span className="min-w-0">
+ <span className="text-gray-800 dark:text-gray-200">{label}</span>
+ <span className="block text-xs text-gray-500 dark:text-gray-400">{hint}</span>
+ </span>
+ </label>
+ ))}
+ </fieldset>
+ <div className="flex justify-end">
+ <Button size="sm" variant="primary" disabled={importBusy} onClick={submitImport}>
+ {S.memory.importAction}
+ </Button>
+ </div>
+ </div>
+ )}
+ </Modal>
+
+ {/* What the chosen mode costs, memory by memory, before it runs. The import modal stays
+ underneath (the skills tab's overwrite confirmation does the same), so cancelling comes
+ back to the mode choice rather than to an empty tab. */}
+ <ConfirmModal
+ open={importPlan !== null}
+ tone="danger"
+ title={S.memory.importConfirmTitle}
+ confirmLabel={S.memory.importAction}
+ busy={importBusy}
+ onClose={() => setImportPlan(null)}
+ onConfirm={() => void runImport(true)}
+ >
+ <div className="space-y-1.5 text-sm text-gray-700 dark:text-gray-300">
+ {importPlan && importPlan.overwritten.length > 0 && (
+ <p className="break-words">{S.memory.importWillOverwrite(importPlan.overwritten)}</p>
+ )}
+ {importPlan && importPlan.removed.length > 0 && (
+ <p className="break-words">{S.memory.importWillRemove(importPlan.removed)}</p>
+ )}
+ {importPlan?.replacesIndex && <p>{S.memory.importWillReplaceIndex}</p>}
+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.memory.importIrreversible}</p>
+ </div>
+ </ConfirmModal>
+
<ConfirmModal
open={removing !== null}
tone="danger"
diff --git a/packages/web/src/features/agents/memory-transfer.ts b/packages/web/src/features/agents/memory-transfer.ts
new file mode 100644
index 00000000..66b6dc1e
--- /dev/null
+++ b/packages/web/src/features/agents/memory-transfer.ts
@@ -0,0 +1,136 @@
+/**
+ * Whole-scope transfer for the Memory tab: reading a downloaded document back in, and working
+ * out what one import mode would cost before it is sent. Pure — mirrors memory-chat-prompts.ts,
+ * exported for unit tests.
+ *
+ * The plan below is a preview, not the decision: the server runs the same policy over the
+ * directory as it is at that moment, and refuses a destructive import that arrives without
+ * confirmation. What this buys is a confirmation that can name the memories at stake instead of
+ * asking the user to agree to an unknown.
+ *
+ * Read `S` inside the functions, never at module top level: the dictionary binding is swapped
+ * on language switch.
+ */
+import type {
+ MemoryImportMode,
+ MemoryScopeExport,
+ MemoryTransferFile,
+} from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+
+/** Format marker of a scope document, typed against the DTO so this literal cannot drift from the server's. */
+const SCOPE_FORMAT: MemoryScopeExport["format"] = "penguin-memory-scope";
+const SCOPE_FORMAT_VERSION: MemoryScopeExport["version"] = 1;
+
+/** A picked file that is not a scope document. Its message is already localized, so callers toast it as is. */
+export class MemoryDocumentError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "MemoryDocumentError";
+ }
+}
+
+function isTransferFile(value: unknown): value is MemoryTransferFile {
+ if (value === null || typeof value !== "object") return false;
+ const entry = value as Record<string, unknown>;
+ return typeof entry.name === "string" && typeof entry.content === "string";
+}
+
+/**
+ * Reads a picked file's text as a scope document. Only the shape is checked here — names, sizes
+ * and counts are the server's to enforce, and a second copy of those bounds would only drift.
+ */
+export function parseMemoryScopeDocument(text: string): MemoryScopeExport {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ throw new MemoryDocumentError(S.memory.importInvalidFile);
+ }
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw new MemoryDocumentError(S.memory.importInvalidFile);
+ }
+ const doc = parsed as Record<string, unknown>;
+ if (doc.format !== SCOPE_FORMAT || doc.version !== SCOPE_FORMAT_VERSION) {
+ throw new MemoryDocumentError(S.memory.importInvalidFile);
+ }
+ if (!Array.isArray(doc.files) || !doc.files.every(isTransferFile)) {
+ throw new MemoryDocumentError(S.memory.importInvalidFile);
+ }
+ if (doc.files.length === 0 && typeof doc.index !== "string") {
+ throw new MemoryDocumentError(S.memory.importEmptyFile);
+ }
+ return doc as unknown as MemoryScopeExport;
+}
+
+/** What the scope holds right now, as the tab already knows it. */
+export interface MemoryScopeState {
+ /** File names listed in the group. */
+ names: readonly string[];
+ /** Whether the scope has a `MEMORY.md` index. */
+ hasIndex: boolean;
+}
+
+/** What one import mode would do to that scope, name by name. */
+export interface MemoryImportPlan {
+ /** Memories the scope does not have yet. */
+ added: string[];
+ /** Memories whose content the file would replace. */
+ overwritten: string[];
+ /** Memories left as they are, because the scope already has that name. */
+ skipped: string[];
+ /** Memories deleted, because the file does not carry them. */
+ removed: string[];
+ /** Whether the scope's existing index would be replaced wholesale. */
+ replacesIndex: boolean;
+ /** Whether anything would be lost — the one question the confirmation exists to ask. */
+ destroys: boolean;
+}
+
+export function planMemoryImport(
+ doc: MemoryScopeExport,
+ scope: MemoryScopeState,
+ mode: MemoryImportMode,
+): MemoryImportPlan {
+ const present = new Set(scope.names);
+ const carried = new Set(doc.files.map((f) => f.name));
+ const collides = doc.files.filter((f) => present.has(f.name)).map((f) => f.name);
+ const added = doc.files.filter((f) => !present.has(f.name)).map((f) => f.name);
+ const overwritten = mode === "skip" ? [] : collides;
+ const skipped = mode === "skip" ? collides : [];
+ const removed = mode === "replace" ? [...present].filter((name) => !carried.has(name)) : [];
+ const replacesIndex = mode === "replace" && scope.hasIndex && doc.index !== null;
+ return {
+ added,
+ overwritten,
+ skipped,
+ removed,
+ replacesIndex,
+ destroys: overwritten.length > 0 || removed.length > 0 || replacesIndex,
+ };
+}
+
+/** `YYYYMMDD-HHmm` in the viewer's local time, or null when the ISO string is unreadable. */
+function fileNameStamp(exportedAt: string): string | null {
+ const d = new Date(exportedAt);
+ if (Number.isNaN(d.getTime())) return null;
+ const p = (n: number): string => String(n).padStart(2, "0");
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
+}
+
+/**
+ * File name of a downloaded scope document: Agent, scope, and the document's own `exportedAt`
+ * rendered in the viewer's local time, so repeated exports of one scope stay apart in a
+ * downloads folder. Same `<agent>-<scope>-memory-<stamp>.json` pattern as the export route's
+ * Content-Disposition, whose stamp renders on the server's clock instead.
+ */
+export function memoryDocumentFileName(
+ agentId: string,
+ scopeKey: string,
+ exportedAt: string,
+): string {
+ const stamp = fileNameStamp(exportedAt);
+ return stamp === null
+ ? `${agentId}-${scopeKey}-memory.json`
+ : `${agentId}-${scopeKey}-memory-${stamp}.json`;
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 10e34358..1e381f83 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -762,6 +762,36 @@ export const en: Strings = {
/** Prefilled draft for the edit-via-chat flow; the user completes the trailing requirement line before sending. */
editPromptLead: (title: string): string => `Please update a memory: ${title}`,
editPromptTail: "What to change: ",
+ exportScope: "Export",
+ exportScopeHint: "Download every memory in this group as one JSON document",
+ exportScopeLabel: (scope: string): string => `Export ${scope}`,
+ importScope: "Import",
+ importScopeHint: "Restore memories into this group from an exported JSON document",
+ importScopeLabel: (scope: string): string => `Import into ${scope}`,
+ importTitle: "Import memories",
+ importWhy:
+ "Reads a memory group exported from this or another agent: a JSON file holding the memories and the group's MEMORY.md index.",
+ importFile: (name: string, count: number): string => `${name} — ${count} memories`,
+ importModeLabel: "When this group already has a memory of the same name",
+ importModeSkip: "Keep the one that is here",
+ importModeSkipHint: "Adds only what this group does not have. Nothing here is lost.",
+ importModeOverwrite: "Take the file's version",
+ importModeOverwriteHint: "Memories the file does not carry are left alone.",
+ importModeReplace: "Replace the whole group",
+ importModeReplaceHint: "Every memory the file does not carry is deleted.",
+ importAction: "Import",
+ importInvalidFile: "This file is not a memory export.",
+ importEmptyFile: "This file carries no memories.",
+ importConfirmTitle: "Confirm the import",
+ importWillOverwrite: (names: string[]): string =>
+ `${names.length} memories will be overwritten: ${names.join(", ")}`,
+ importWillRemove: (names: string[]): string =>
+ `${names.length} memories will be deleted: ${names.join(", ")}`,
+ importWillReplaceIndex: "The group's MEMORY.md index will be replaced.",
+ importIrreversible: "This cannot be undone.",
+ importDone: (added: number, overwritten: number, removed: number): string =>
+ `Imported: ${added} added, ${overwritten} replaced, ${removed} deleted`,
+ importNothingNew: "Nothing to import — this group already has every memory in the file",
},
vault: {
@@ -1626,6 +1656,8 @@ Scenarios:
member_not_found: "This user is not a member of the Project.",
already_member: "This user is already a member of the Project.",
already_owner: "This user is already an owner of the Project.",
+ memory_import_confirm_required:
+ "This import would overwrite or delete memories. Confirm it to continue.",
schedule_exists: "A scheduled task with this name already exists.",
schedule_not_found: "This scheduled task no longer exists.",
unknown_skill: "This skill is not in the library.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 0300cb98..8c6335f9 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -736,6 +736,36 @@ export const zh = {
/** Prefilled draft for the edit-via-chat flow; the user completes the trailing requirement line before sending. */
editPromptLead: (title: string): string => `请帮我更新一条记忆:${title}`,
editPromptTail: "修改要求:",
+ exportScope: "导出",
+ exportScopeHint: "将该组全部记忆下载为一份 JSON 文档",
+ exportScopeLabel: (scope: string): string => `导出${scope}`,
+ importScope: "导入",
+ importScopeHint: "从导出的 JSON 文档恢复记忆到该组",
+ importScopeLabel: (scope: string): string => `导入到${scope}`,
+ importTitle: "导入记忆",
+ importWhy:
+ "读取从本 agent 或其他 agent 导出的一组记忆:一个 JSON 文件,含这组记忆与它的 MEMORY.md 索引。",
+ importFile: (name: string, count: number): string => `${name} —— ${count} 条记忆`,
+ importModeLabel: "当这一组里已有同名记忆时",
+ importModeSkip: "保留现有的这条",
+ importModeSkipHint: "只添加这一组还没有的记忆,不会丢失任何现有内容。",
+ importModeOverwrite: "改用文件里的版本",
+ importModeOverwriteHint: "文件中没有的记忆保持不变。",
+ importModeReplace: "整组替换",
+ importModeReplaceHint: "文件中没有的记忆将被删除。",
+ importAction: "导入",
+ importInvalidFile: "这个文件不是记忆导出文件。",
+ importEmptyFile: "这个文件里没有记忆。",
+ importConfirmTitle: "确认导入",
+ importWillOverwrite: (names: string[]): string =>
+ `将覆盖 ${names.length} 条记忆:${names.join("、")}`,
+ importWillRemove: (names: string[]): string =>
+ `将删除 ${names.length} 条记忆:${names.join("、")}`,
+ importWillReplaceIndex: "这一组的 MEMORY.md 索引将被替换。",
+ importIrreversible: "此操作不可恢复。",
+ importDone: (added: number, overwritten: number, removed: number): string =>
+ `已导入:新增 ${added} 条,覆盖 ${overwritten} 条,删除 ${removed} 条`,
+ importNothingNew: "没有可导入的内容——文件里的记忆这一组都已经有了",
},
vault: {
@@ -1585,6 +1615,7 @@ Benchmark:
member_not_found: "该用户不是本 Project 的成员。",
already_member: "该用户已是本 Project 的成员。",
already_owner: "该用户已是本 Project 的所有者。",
+ memory_import_confirm_required: "本次导入会覆盖或删除已有记忆,请确认后继续。",
schedule_exists: "已存在同名定时任务。",
schedule_not_found: "该定时任务已不存在。",
unknown_skill: "该技能不在技能库中。",
diff --git a/packages/web/test/memory-transfer.test.ts b/packages/web/test/memory-transfer.test.ts
new file mode 100644
index 00000000..3ec287da
--- /dev/null
+++ b/packages/web/test/memory-transfer.test.ts
@@ -0,0 +1,137 @@
+/**
+ * The Memory tab's whole-scope transfer helpers: what counts as a scope document, and what each
+ * import mode would cost the group it is aimed at.
+ *
+ * The plan is what the confirmation reads from, so these pin the two halves that matter — the
+ * default mode destroys nothing, and every mode that does report exactly which memories.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import type { MemoryScopeExport } from "@prismshadow/penguin-server/api";
+import { S, setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+import {
+ MemoryDocumentError,
+ memoryDocumentFileName,
+ parseMemoryScopeDocument,
+ planMemoryImport,
+} from "../src/features/agents/memory-transfer";
+
+afterEach(() => setActiveStrings(zh));
+
+const doc = (names: string[], index: string | null = "# Memories\n"): MemoryScopeExport => ({
+ format: "penguin-memory-scope",
+ version: 1,
+ scopeKey: "my-app-a81f32c4",
+ kind: "workspace",
+ exportedAt: "2026-08-20T00:00:00.000Z",
+ index,
+ files: names.map((name) => ({ name, content: `---\nname: ${name}\n---\nbody\n` })),
+});
+
+describe("parseMemoryScopeDocument", () => {
+ it("reads a document the export route produced", () => {
+ const parsed = parseMemoryScopeDocument(JSON.stringify(doc(["a.md", "b.md"])));
+ expect(parsed.files.map((f) => f.name)).toEqual(["a.md", "b.md"]);
+ expect(parsed.scopeKey).toBe("my-app-a81f32c4");
+ });
+
+ it("refuses anything that is not one, in the active language", () => {
+ const refusals = [
+ "not json at all",
+ JSON.stringify([1, 2]),
+ JSON.stringify({ ...doc(["a.md"]), format: "some-other-tool" }),
+ JSON.stringify({ ...doc(["a.md"]), version: 2 }),
+ JSON.stringify({ ...doc(["a.md"]), files: "nope" }),
+ JSON.stringify({ ...doc([]), files: [{ name: "a.md" }] }),
+ ];
+ for (const text of refusals) {
+ expect(() => parseMemoryScopeDocument(text)).toThrow(MemoryDocumentError);
+ }
+ setActiveStrings(en);
+ expect(() => parseMemoryScopeDocument("{}")).toThrow(S.memory.importInvalidFile);
+ setActiveStrings(zh);
+ expect(() => parseMemoryScopeDocument("{}")).toThrow(S.memory.importInvalidFile);
+ });
+
+ it("calls a document with neither memories nor an index empty", () => {
+ expect(() => parseMemoryScopeDocument(JSON.stringify(doc([], null)))).toThrow(
+ S.memory.importEmptyFile,
+ );
+ // An index alone is still worth importing: it is the only part the model reads.
+ expect(parseMemoryScopeDocument(JSON.stringify(doc([], "# Memories\n"))).files).toEqual([]);
+ });
+});
+
+describe("planMemoryImport", () => {
+ const scope = { names: ["keep.md", "gone.md"], hasIndex: true };
+
+ it("destroys nothing in the default mode", () => {
+ const plan = planMemoryImport(doc(["keep.md", "new.md"]), scope, "skip");
+ expect(plan).toMatchObject({
+ added: ["new.md"],
+ skipped: ["keep.md"],
+ overwritten: [],
+ removed: [],
+ replacesIndex: false,
+ destroys: false,
+ });
+ });
+
+ it("names the memories overwrite would replace, and keeps the rest", () => {
+ const plan = planMemoryImport(doc(["keep.md", "new.md"]), scope, "overwrite");
+ expect(plan).toMatchObject({
+ added: ["new.md"],
+ overwritten: ["keep.md"],
+ skipped: [],
+ // A memory the file does not carry survives an overwrite.
+ removed: [],
+ destroys: true,
+ });
+ });
+
+ it("names the memories replace would delete, and the index it would take over", () => {
+ const plan = planMemoryImport(doc(["keep.md"]), scope, "replace");
+ expect(plan).toMatchObject({
+ added: [],
+ overwritten: ["keep.md"],
+ removed: ["gone.md"],
+ replacesIndex: true,
+ destroys: true,
+ });
+ });
+
+ it("has nothing to confirm when the group is empty, whatever the mode", () => {
+ const empty = { names: [], hasIndex: false };
+ for (const mode of ["skip", "overwrite", "replace"] as const) {
+ const plan = planMemoryImport(doc(["new.md"]), empty, mode);
+ expect(plan.destroys, mode).toBe(false);
+ expect(plan.added).toEqual(["new.md"]);
+ }
+ });
+
+ it("leaves an index alone that the document does not carry", () => {
+ const plan = planMemoryImport(doc(["keep.md"], null), { names: [], hasIndex: true }, "replace");
+ expect(plan.replacesIndex).toBe(false);
+ expect(plan.destroys).toBe(false);
+ });
+});
+
+describe("memoryDocumentFileName", () => {
+ it("stamps the document's exportedAt in the viewer's local time", () => {
+ const iso = "2026-08-21T03:07:00.000Z";
+ // The expected stamp is computed with the same local-time getters the formatter uses,
+ // so the assertion holds in any timezone the suite runs in.
+ const d = new Date(iso);
+ const p = (n: number): string => String(n).padStart(2, "0");
+ const stamp = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
+ expect(memoryDocumentFileName("default_agent", "my-app-a81f32c4", iso)).toBe(
+ `default_agent-my-app-a81f32c4-memory-${stamp}.json`,
+ );
+ });
+
+ it("falls back to the unstamped name when exportedAt is unreadable", () => {
+ expect(memoryDocumentFileName("default_agent", "my-app-a81f32c4", "not-a-date")).toBe(
+ "default_agent-my-app-a81f32c4-memory.json",
+ );
+ });
+});