A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
List a memory's changes in the dialog and restore them by row id
Fei241162b4d9225c4b
diff --git a/docs/plans/2026-11-01-memory-restore.md b/docs/plans/2026-11-01-memory-restore.mdindex 2f2297c6..9b148cae 100644--- a/docs/plans/2026-11-01-memory-restore.md+++ b/docs/plans/2026-11-01-memory-restore.md@@ -9,16 +9,26 @@ issue: 464`journal.jsonl` (and a private Bot's own log) already keeps every memory change withthe line before and after, but nothing reads it for undo: a wrong remember, replace,-or forget is permanent unless the files are edited by hand. This adds a narrow,-API-only restore — `memory-restore` on the `api/bot` channel — that applies the-inverse of one journal row. A panel History view can come later; this is the part-that makes the log actionable.+or forget is permanent unless the files are edited by hand. This adds a restore —+`memory-restore` on the `api/bot` channel — that applies the inverse of one journal+row, and the Change history page in the memory dialog that lists those rows with an+Undo button each (`memory-history`).## Shape-- Request: `{ line, botId? }`. `line` is the 1-based line of the change log;- `botId` picks a private Bot's own log (`bots/<id>/journal.jsonl`), everything- else is in the shared log — the same routing `journalFor` uses for writes.+- `memory-history` takes the same owner params as `memory-view` (`{botId}` or+ `{roomId}`) plus an optional `before` row id for paging, and returns+ `{ rows, more }`, newest first, 50 rows a page. A Bot's panel reads its own+ scope and the team's — the shared log, or the Bot's own log when it is+ private (`journalFor` resolves both) — a group's panel reads its group scope.+ Each row carries `{ id, time, op, scope, text, by, restored }`; `restored`+ marks rows some later row already undid. `archive` rows are skipped.+- `memory-restore` takes the same owner params plus `id`, the journal row to+ undo. A row outside the owner's scopes, or one already restored, is refused.+ On success it returns the fresh memory view, as `memory-forget` does.+- The dialog's ⋯ menu gets "Change history" after "All entries": a page with a+ back button, one row per change (the change line, `time · by`, and Undo or a+ muted Undone), a Load more button while `more` is set.- One row is undone with its inverse op, and only while what it reads still readsas the row left it:- `add` → the recorded `after` line is taken back out, verbatim. A topic left@@ -43,6 +53,6 @@ that makes the log actionable.## Deliberately out of scope- No version tree, no git, no multi-step undo. One row, one inverse.-- No UI. The endpoint is for the host channel now; a History view in the memory- panel is the follow-up that consumes it.+- The history page lists and undoes single changes only; multi-step undo stays+ out.- `archive` is a different, folder-level path and stays irreversible here.diff --git a/ds-bot/client.js b/ds-bot/client.jsindex 1dcae995..185f5caf 100644--- a/ds-bot/client.js+++ b/ds-bot/client.js@@ -821,6 +821,13 @@ var ZH = {"{name}'s memory": "{name} 的记忆","Memory summary": "记忆摘要","All entries": "全部记忆",+ "Change history": "更改记录",+ "No changes yet": "还没有更改",+ "Load more": "加载更多",+ Undo: "撤销",+ Undone: "已撤销",+ "Undo this change": "撤销这条更改",+ "Click again to undo": "再点一次撤销","Memory options": "记忆选项","Close memory": "关闭记忆","Back to the summary": "返回摘要",@@ -1782,6 +1789,8 @@ function teamActions({ call: call2, after, partFor, roster, ui: ui2, live, cardsmemoryView: (id, flags = {}) => call2("memory-view", { ...memoryOf(id), ...flags }),memoryAsk: (id, text) => call2("memory-ask", { ...memoryOf(id), text }),memoryForget: (id, entry) => call2("memory-forget", { ...memoryOf(id), scope: entry.scope, topic: entry.topic, text: entry.text }),+ memoryHistory: (id, before) => call2("memory-history", { ...memoryOf(id), ...before === void 0 ? {} : { before } }),+ memoryRestore: (id, rowId) => call2("memory-restore", { ...memoryOf(id), id: rowId }),diagnostics: (payload) => call2("diagnostics", payload),diagnosticsLog: () => call2("diagnostics-log"),diagnosticsClear: () => call2("diagnostics-clear"),@@ -3324,6 +3333,7 @@ body[data-ds-dark-theme] .bt-theme-chip i{background:var(--da)}.bt-mem-remove[data-confirm]{background:color-mix(in srgb,var(--bt-danger) 10%,transparent);color:var(--bt-danger);padding:0 10px}@media (hover:none){.bt-mem-remove{opacity:1}}.bt-mem-none{font-size:13px;line-height:18px;color:var(--bt-ink-3);padding:8px 4px}+.bt-mem-undone{flex:none;font-size:12px;line-height:16px;color:var(--bt-ink-3)}.bt-mem-foot{flex:none;padding:8px 20px 20px;display:flex;flex-direction:column;gap:10px}.bt-mem-reply{border-radius:16px;background:var(--bt-hover);padding:8px 8px 12px 16px;display:flex;flex-direction:column;gap:6px;max-height:36vh;max-height:36dvh;overflow-y:auto;scrollbar-width:thin;transform-origin:50% 100%;animation:bt-pop-lift ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing},bt-veil-in .2s ease-out}.bt-mem-reply-head{display:flex;align-items:center;gap:8px;min-height:24px}@@ -13790,6 +13800,85 @@ function changeLine(change) {if (change.op === "edit") return t("Updated: {text}", { text });return change.scope === "team" ? t("Added to team memory: {text}", { text }) : t("Added: {text}", { text });}+function historyLine(row) {+ const text = row.text.length > 120 ? `${row.text.slice(0, 120)}…` : row.text;+ if (row.op === "remove") return row.scope === "team" ? t("Removed from team memory: {text}", { text }) : t("Removed: {text}", { text });+ if (row.op === "replace") return t("Updated: {text}", { text });+ return row.scope === "team" ? t("Added to team memory: {text}", { text }) : t("Added: {text}", { text });+}+function HistoryRow({ row, undo, now }) {+ const [confirming, setConfirming] = (0, import_react31.useState)(false);+ const [busy, setBusy] = (0, import_react31.useState)(false);+ (0, import_react31.useEffect)(() => {+ if (!confirming) return void 0;+ const timer = setTimeout(() => setConfirming(false), 3e3);+ return () => clearTimeout(timer);+ }, [confirming]);+ const when3 = ago(Date.parse(row.time), now) ?? t("just now");+ const meta = [when3, row.by === "user" ? t("by you") : t("by {name}", { name: row.by })].join(" · ");+ const click = async () => {+ if (!confirming) {+ setConfirming(true);+ return;+ }+ setBusy(true);+ if (!await undo(row)) setBusy(false);+ };+ return (0, import_react31.createElement)(+ "li",+ { className: "bt-mem-entry", "data-busy": busy || void 0 },+ (0, import_react31.createElement)(+ "div",+ { className: "bt-mem-entry-copy" },+ (0, import_react31.createElement)("span", { className: "bt-mem-entry-text" }, historyLine(row)),+ (0, import_react31.createElement)("span", { className: "bt-mem-entry-meta" }, meta)+ ),+ row.restored ? (0, import_react31.createElement)("span", { className: "bt-mem-undone" }, t("Undone")) : (0, import_react31.createElement)("button", {+ type: "button",+ className: "bt-mem-remove",+ "data-confirm": confirming || void 0,+ disabled: busy,+ "aria-label": confirming ? t("Click again to undo") : t("Undo this change"),+ title: confirming ? void 0 : t("Undo this change"),+ onClick: click+ }, t("Undo"))+ );+}+function History({ owner, actions, undo, now }) {+ const [rows2, setRows] = (0, import_react31.useState)(null);+ const [more, setMore] = (0, import_react31.useState)(null);+ const [paging, setPaging] = (0, import_react31.useState)(false);+ const load = (0, import_react31.useCallback)(async (before) => {+ const page = await actions.memoryHistory(owner.id, before);+ setRows(before === void 0 ? page.rows : [...rows2 ?? [], ...page.rows]);+ setMore(page.more);+ }, [owner.id, rows2]);+ (0, import_react31.useEffect)(() => {+ void load();+ }, [owner.id]);+ const reload = async () => {+ setRows(null);+ setMore(null);+ await load();+ };+ const undoRow = async (row) => await undo(row) ? reload() : false;+ const moreClick = async () => {+ setPaging(true);+ try {+ await load(more);+ } finally {+ setPaging(false);+ }+ };+ if (rows2 === null) return (0, import_react31.createElement)(Skeleton);+ if (rows2.length === 0) return (0, import_react31.createElement)("div", { className: "bt-mem-none" }, t("No changes yet"));+ return (0, import_react31.createElement)(+ "div",+ { className: "bt-mem-entries" },+ (0, import_react31.createElement)("ul", { className: "bt-mem-list" }, rows2.map((row) => (0, import_react31.createElement)(HistoryRow, { key: row.id, row, undo: undoRow, now }))),+ more ? (0, import_react31.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: paging, onClick: () => void moreClick() }, t("Load more")) : null+ );+}function Reply({ answer, dismiss }) {return (0, import_react31.createElement)("div",@@ -13896,6 +13985,10 @@ function MemoryDialog({ owner, actions, leaving = false }) {setMenu(false);setPage("entries");};+ const openHistory = () => {+ setMenu(false);+ setPage("history");+ };const backToSummary = () => {setPage("summary");void load({ summarize: true });@@ -13909,6 +14002,15 @@ function MemoryDialog({ owner, actions, leaving = false }) {return false;}};+ const undo = async (row) => {+ try {+ show2(await actions.memoryRestore(owner.id, row.id));+ return true;+ } catch (failure) {+ setAnswer({ asked: row.text, error: failure?.message ?? String(failure) });+ return false;+ }+ };const ask = async (event) => {event.preventDefault();const asked = text.trim();@@ -13939,8 +14041,8 @@ function MemoryDialog({ owner, actions, leaving = false }) {(0, import_react31.createElement)("div",{ className: "bt-mem-head" },- page === "entries" ? (0, import_react31.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to the summary"), onClick: backToSummary }, (0, import_react31.createElement)(ChevronLeftIcon)) : null,- (0, import_react31.createElement)("h2", null, page === "entries" ? t("All entries") : t("Memory summary")),+ page === "summary" ? null : (0, import_react31.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to the summary"), onClick: backToSummary }, (0, import_react31.createElement)(ChevronLeftIcon)),+ (0, import_react31.createElement)("h2", null, page === "entries" ? t("All entries") : page === "history" ? t("Change history") : t("Memory summary")),(0, import_react31.createElement)("span", { className: "bt-mem-status" }, page === "summary" ? [owner.name, status].filter(Boolean).join(" · ") : status),(0, import_react31.createElement)("span", { className: "bt-mem-head-gap" }),(0, import_react31.createElement)("button", { ref: dotsRef, type: "button", className: "bt-icon-btn", "aria-label": t("Memory options"), "aria-haspopup": "menu", "aria-expanded": menu, onClick: () => setMenu((value) => !value) }, (0, import_react31.createElement)(DotsIcon)),@@ -13954,6 +14056,11 @@ function MemoryDialog({ owner, actions, leaving = false }) {(0, import_react31.createElement)("span", { className: "bt-menu-label" }, t("All entries")),(0, import_react31.createElement)("span", { className: "bt-menu-hint" }, String(count))),+ (0, import_react31.createElement)(+ "button",+ { type: "button", role: "menuitem", onClick: openHistory },+ (0, import_react31.createElement)("span", { className: "bt-menu-label" }, t("Change history"))+ ),(0, import_react31.createElement)("button",{ type: "button", role: "menuitem", disabled: count === 0 || view?.summarizing, onClick: regenerate },@@ -13965,7 +14072,7 @@ function MemoryDialog({ owner, actions, leaving = false }) {"div",{ className: "bt-mem-body" },error ? (0, import_react31.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, hostText(error)) : null,- view === null ? error ? null : (0, import_react31.createElement)(Skeleton) : page === "entries" ? (0, import_react31.createElement)(Entries, { owner, view, remove }) : (0, import_react31.createElement)(Summary, { owner, view, regenerate })+ view === null ? error ? null : (0, import_react31.createElement)(Skeleton) : page === "entries" ? (0, import_react31.createElement)(Entries, { owner, view, remove }) : page === "history" ? (0, import_react31.createElement)(History, { owner, actions, undo, now }) : (0, import_react31.createElement)(Summary, { owner, view, regenerate })),(0, import_react31.createElement)("div",diff --git a/ds-bot/src/client/i18n.js b/ds-bot/src/client/i18n.jsindex 92e235b2..dcfcd78e 100644--- a/ds-bot/src/client/i18n.js+++ b/ds-bot/src/client/i18n.js@@ -771,6 +771,13 @@ const ZH = {"{name}'s memory": '{name} 的记忆','Memory summary': '记忆摘要','All entries': '全部记忆',+ 'Change history': '更改记录',+ 'No changes yet': '还没有更改',+ 'Load more': '加载更多',+ Undo: '撤销',+ Undone: '已撤销',+ 'Undo this change': '撤销这条更改',+ 'Click again to undo': '再点一次撤销','Memory options': '记忆选项','Close memory': '关闭记忆','Back to the summary': '返回摘要',diff --git a/ds-bot/src/client/memory-panel.js b/ds-bot/src/client/memory-panel.jsindex d432c625..72cde371 100644--- a/ds-bot/src/client/memory-panel.js+++ b/ds-bot/src/client/memory-panel.js@@ -149,6 +149,63 @@ function changeLine(change) {return change.scope === 'team' ? t('Added to team memory: {text}', { text }) : t('Added: {text}', { text })}+function historyLine(row) {+ const text = row.text.length > 120 ? `${row.text.slice(0, 120)}…` : row.text+ if (row.op === 'remove') return row.scope === 'team' ? t('Removed from team memory: {text}', { text }) : t('Removed: {text}', { text })+ if (row.op === 'replace') return t('Updated: {text}', { text })+ return row.scope === 'team' ? t('Added to team memory: {text}', { text }) : t('Added: {text}', { text })+}++export function HistoryRow({ row, undo, now }) {+ const [confirming, setConfirming] = useState(false)+ const [busy, setBusy] = useState(false)+ useEffect(() => {+ if (!confirming) return undefined+ const timer = setTimeout(() => setConfirming(false), 3000)+ return () => clearTimeout(timer)+ }, [confirming])+ const when = ago(Date.parse(row.time), now) ?? t('just now')+ const meta = [when, row.by === 'user' ? t('by you') : t('by {name}', { name: row.by })].join(' · ')+ const click = async () => {+ if (!confirming) { setConfirming(true); return }+ setBusy(true)+ if (!await undo(row)) setBusy(false)+ }+ return h('li', { className: 'bt-mem-entry', 'data-busy': busy || undefined },+ h('div', { className: 'bt-mem-entry-copy' },+ h('span', { className: 'bt-mem-entry-text' }, historyLine(row)),+ h('span', { className: 'bt-mem-entry-meta' }, meta)),+ row.restored+ ? h('span', { className: 'bt-mem-undone' }, t('Undone'))+ : h('button', {+ type: 'button', className: 'bt-mem-remove', 'data-confirm': confirming || undefined, disabled: busy,+ 'aria-label': confirming ? t('Click again to undo') : t('Undo this change'), title: confirming ? undefined : t('Undo this change'), onClick: click,+ }, t('Undo')))+}++export function History({ owner, actions, undo, now }) {+ const [rows, setRows] = useState(null)+ const [more, setMore] = useState(null)+ const [paging, setPaging] = useState(false)+ const load = useCallback(async (before) => {+ const page = await actions.memoryHistory(owner.id, before)+ setRows(before === undefined ? page.rows : [...(rows ?? []), ...page.rows])+ setMore(page.more)+ }, [owner.id, rows])+ useEffect(() => { void load() }, [owner.id])+ const reload = async () => { setRows(null); setMore(null); await load() }+ const undoRow = async row => (await undo(row) ? reload() : false)+ const moreClick = async () => {+ setPaging(true)+ try { await load(more) } finally { setPaging(false) }+ }+ if (rows === null) return h(Skeleton)+ if (rows.length === 0) return h('div', { className: 'bt-mem-none' }, t('No changes yet'))+ return h('div', { className: 'bt-mem-entries' },+ h('ul', { className: 'bt-mem-list' }, rows.map(row => h(HistoryRow, { key: row.id, row, undo: undoRow, now }))),+ more ? h('button', { type: 'button', className: 'bt-soft bt-soft-sm', disabled: paging, onClick: () => void moreClick() }, t('Load more')) : null)+}+function Reply({ answer, dismiss }) {return h('div', { className: 'bt-mem-reply', role: 'status' },h('div', { className: 'bt-mem-reply-head' },@@ -235,6 +292,7 @@ export function MemoryDialog({ owner, actions, leaving = false }) {}, [menu])const regenerate = () => { setMenu(false); setPage('summary'); void load({ regenerate: true }) }const openEntries = () => { setMenu(false); setPage('entries') }+ const openHistory = () => { setMenu(false); setPage('history') }const backToSummary = () => { setPage('summary'); void load({ summarize: true }) }const remove = async (entry) => {try {@@ -245,6 +303,15 @@ export function MemoryDialog({ owner, actions, leaving = false }) {return false}}+ const undo = async (row) => {+ try {+ show(await actions.memoryRestore(owner.id, row.id))+ return true+ } catch (failure) {+ setAnswer({ asked: row.text, error: failure?.message ?? String(failure) })+ return false+ }+ }const ask = async (event) => {event.preventDefault()const asked = text.trim()@@ -274,8 +341,8 @@ export function MemoryDialog({ owner, actions, leaving = false }) {h('div', { className: 'bt-scrim bt-mem-scrim', onMouseDown: close }),h('div', { className: 'bt-mem', role: 'dialog', 'aria-modal': true, 'aria-label': t("{name}'s memory", { name: owner.name }) },h('div', { className: 'bt-mem-head' },- page === 'entries' ? h('button', { type: 'button', className: 'bt-icon-btn', 'aria-label': t('Back to the summary'), onClick: backToSummary }, h(ChevronLeftIcon)) : null,- h('h2', null, page === 'entries' ? t('All entries') : t('Memory summary')),+ page === 'summary' ? null : h('button', { type: 'button', className: 'bt-icon-btn', 'aria-label': t('Back to the summary'), onClick: backToSummary }, h(ChevronLeftIcon)),+ h('h2', null, page === 'entries' ? t('All entries') : page === 'history' ? t('Change history') : t('Memory summary')),h('span', { className: 'bt-mem-status' }, page === 'summary' ? [owner.name, status].filter(Boolean).join(' · ') : status),h('span', { className: 'bt-mem-head-gap' }),h('button', { ref: dotsRef, type: 'button', className: 'bt-icon-btn', 'aria-label': t('Memory options'), 'aria-haspopup': 'menu', 'aria-expanded': menu, onClick: () => setMenu(value => !value) }, h(DotsIcon)),@@ -283,13 +350,16 @@ export function MemoryDialog({ owner, actions, leaving = false }) {menuShown ? h('div', { ref: menuRef, className: 'bt-menu bt-mem-menu', role: 'menu', 'aria-label': t('Memory options'), 'data-leaving': menuLeaving || undefined },h('button', { type: 'button', role: 'menuitem', onClick: openEntries },h('span', { className: 'bt-menu-label' }, t('All entries')), h('span', { className: 'bt-menu-hint' }, String(count))),+ h('button', { type: 'button', role: 'menuitem', onClick: openHistory },+ h('span', { className: 'bt-menu-label' }, t('Change history'))),h('button', { type: 'button', role: 'menuitem', disabled: count === 0 || view?.summarizing, onClick: regenerate },h('span', { className: 'bt-menu-label' }, t('Regenerate summary')))) : null),h('div', { className: 'bt-mem-body' },error ? h('div', { className: 'bt-error', role: 'alert', style: { padding: 0 } }, hostText(error)) : null,view === null ? (error ? null : h(Skeleton)): page === 'entries' ? h(Entries, { owner, view, remove })- : h(Summary, { owner, view, regenerate })),+ : page === 'history' ? h(History, { owner, actions, undo, now })+ : h(Summary, { owner, view, regenerate })),h('div', { className: 'bt-mem-foot' },answer ? h(Reply, { answer, dismiss: () => setAnswer(null) }) : null,h('form', { className: 'bt-mem-ask', onSubmit: ask },diff --git a/ds-bot/src/client/styles.js b/ds-bot/src/client/styles.jsindex 5461ac03..f415c004 100644--- a/ds-bot/src/client/styles.js+++ b/ds-bot/src/client/styles.js@@ -878,6 +878,7 @@ body[data-ds-dark-theme] .bt-theme-chip i{background:var(--da)}.bt-mem-remove[data-confirm]{background:color-mix(in srgb,var(--bt-danger) 10%,transparent);color:var(--bt-danger);padding:0 10px}@media (hover:none){.bt-mem-remove{opacity:1}}.bt-mem-none{font-size:13px;line-height:18px;color:var(--bt-ink-3);padding:8px 4px}+.bt-mem-undone{flex:none;font-size:12px;line-height:16px;color:var(--bt-ink-3)}.bt-mem-foot{flex:none;padding:8px 20px 20px;display:flex;flex-direction:column;gap:10px}.bt-mem-reply{border-radius:16px;background:var(--bt-hover);padding:8px 8px 12px 16px;display:flex;flex-direction:column;gap:6px;max-height:36vh;max-height:36dvh;overflow-y:auto;scrollbar-width:thin;transform-origin:50% 100%;animation:bt-pop-lift ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing},bt-veil-in .2s ease-out}.bt-mem-reply-head{display:flex;align-items:center;gap:8px;min-height:24px}diff --git a/ds-bot/src/client/team-actions.js b/ds-bot/src/client/team-actions.jsindex f3ce4b33..52c69ec5 100644--- a/ds-bot/src/client/team-actions.js+++ b/ds-bot/src/client/team-actions.js@@ -148,6 +148,8 @@ export function teamActions({ call, after, partFor, roster, ui, live, cards, helmemoryView: (id, flags = {}) => call('memory-view', { ...memoryOf(id), ...flags }),memoryAsk: (id, text) => call('memory-ask', { ...memoryOf(id), text }),memoryForget: (id, entry) => call('memory-forget', { ...memoryOf(id), scope: entry.scope, topic: entry.topic, text: entry.text }),+ memoryHistory: (id, before) => call('memory-history', { ...memoryOf(id), ...(before === undefined ? {} : { before }) }),+ memoryRestore: (id, rowId) => call('memory-restore', { ...memoryOf(id), id: rowId }),diagnostics: payload => call('diagnostics', payload),diagnosticsLog: () => call('diagnostics-log'),diagnosticsClear: () => call('diagnostics-clear'),diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex d495c73d..7fa4518f 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -414,6 +414,7 @@ export function install(rt) {case 'memory-view':case 'memory-ask':case 'memory-forget':+ case 'memory-history':case 'memory-restore':await rt.load()return ok(await rt.memoryEndpoint(endpoint, body))diff --git a/ds-bot/src/host/memory.js b/ds-bot/src/host/memory.jsindex 14a9586e..3d2cd0f6 100644--- a/ds-bot/src/host/memory.js+++ b/ds-bot/src/host/memory.js@@ -1489,6 +1489,59 @@ export function install(rt) {: typeof key === 'string' && key.startsWith('bot:') ? ownScope(key.slice(4)): typeof key === 'string' && key.startsWith('group:') ? groupScope(key.slice(6)): undefined)++ // The logs a panel's scopes write to: the shared log, plus a private Bot's own+ // for its `bot:` scope. journalFor decides which, exactly as it does for writes.+ const journalPathsOf = panel => [...new Set(Object.values(panel.scopes).map(scope => journalFor(scopeKey(scope), 'restore').path))]++ const journalRows = (path) => {+ const rows = []+ for (const line of readJournal(path).split('\n')) {+ try {+ const row = JSON.parse(line)+ if (row !== null && typeof row === 'object') rows.push(row)+ } catch { /* a half-written or foreign line is not a row */ }+ }+ return rows+ }++ // Every change the owner's scopes made, oldest first across the logs they+ // landed in. A row outside those scopes is not the owner's to see or undo.+ function ownerRows(panel) {+ const keys = new Set(Object.values(panel.scopes).map(scopeKey))+ const rows = []+ for (const path of journalPathsOf(panel)) {+ for (const row of journalRows(path)) if (keys.has(row.scope)) rows.push(row)+ }+ return rows.sort((a, b) => String(a.time).localeCompare(String(b.time)))+ }++ const HISTORY_PAGE = 50++ async function memoryHistory(body) {+ const panel = panelOf(body)+ const rows = await settled(() => ownerRows(panel))+ const undone = new Set(rows.map(row => row.restored).filter(id => typeof id === 'string'))+ const newest = rows.filter(row => row.op === 'add' || row.op === 'remove' || row.op === 'replace').reverse()+ let slice = newest+ if (body.before !== undefined && body.before !== null) {+ const at = newest.findIndex(row => row.id === body.before)+ slice = at === -1 ? [] : newest.slice(at + 1)+ }+ const page = slice.slice(0, HISTORY_PAGE)+ return {+ rows: page.map(row => ({+ id: row.id,+ time: row.time,+ op: row.op,+ scope: row.scope === 'team' ? 'team' : typeof row.scope === 'string' && row.scope.startsWith('group:') ? 'group' : 'own',+ text: splitMeta(String((row.op === 'remove' ? row.before : row.after) ?? '').replace(/^\s*[-*]\s+/, '')).text,+ by: row.actor === 'user' ? 'user' : String(row.actorName ?? row.actor ?? ''),+ restored: undone.has(row.id),+ })),+ more: slice.length > HISTORY_PAGE ? page.at(-1).id : null,+ }+ }// The entry lines a file still has exactly as a row recorded them; restoring on// less than a whole line would undo a different change than the one it reads.const exactLines = (file, line) => file.entries.filter(entry => file.lines[entry.line] === line)@@ -1505,26 +1558,24 @@ export function install(rt) {const entryLine = line => typeof line === 'string' && !/[\r\n]/.test(line) && /^\s*[-*]\s+\S/.test(line)async function memoryRestore(body) {- const line = Number(body.line)- if (!Number.isInteger(line) || line < 1) throw new Error('Give the change log line of the change to restore, 1 being the first line.')- return queued(async () => {+ const panel = panelOf(body)+ const id = String(body.id ?? '')+ if (id === '') throw new Error('Give the change log id of the change to restore.')+ await queued(async () => {await recoverPending()- // `botId` picks a private Bot's own log; every other change is in the shared- // log, which journalFor resolves for a public or unknown Bot too.- const { path } = journalFor(body.botId === undefined ? 'team' : `bot:${body.botId}`, 'restore')- const raw = readJournal(path).split('\n')[line - 1]- let row- try { row = raw === undefined ? undefined : JSON.parse(raw) } catch { row = null }- if (row === undefined || row === null || typeof row !== 'object') {- throw new Error(`Line ${line} of the change log is not a change that can be restored.`)- }+ // Only a change the owner's own scopes made can be undone: the row comes+ // from the same logs memory-history reads.+ const rows = ownerRows(panel)+ const row = rows.find(record => record.id === id)+ if (row === undefined) throw new Error('That change is not in the change log of this memory.')+ if (rows.some(record => record.restored === id)) throw new Error('That change is already restored.')const scope = journalScope(row.scope)if (scope === undefined || !flatFile(row.file)) {- throw new Error(`Line ${line} of the change log is not a change that can be restored.`)+ throw new Error('That change is not a change that can be restored.')}if (row.op === 'archive') throw new Error('An archived memory cannot be restored from the change log.')if (row.op !== 'add' && row.op !== 'remove' && row.op !== 'replace') {- throw new Error(`Line ${line} of the change log is not a change that can be restored.`)+ throw new Error('That change is not a change that can be restored.')}writable(scope, USER)const label = labelOf(scope)@@ -1537,14 +1588,14 @@ export function install(rt) {// Undoing an add takes the line back out. It must still read as it was// written; a topic left with only its title goes, and its link with it.if (target === undefined || typeof row.after !== 'string') {- throw noMatch(`The entry that line ${line} added is not where the change log left it; it may have changed or been removed since.`)+ throw noMatch(`The entry the change added is not where the change log left it; it may have changed or been removed since.`)}const found = exactLines(target, row.after)- if (found.length === 0) throw noMatch(`The entry that line ${line} added is no longer in ${label}; it may have changed or been removed since.`)- if (found.length > 1) throw noMatch(`The line that line ${line} added is in ${label} more than once; restore it by hand so the wrong one is not removed.`)+ if (found.length === 0) throw noMatch(`The entry the change added is no longer in ${label}; it may have changed or been removed since.`)+ if (found.length > 1) throw noMatch(`The line the change added is in ${label} more than once; restore it by hand so the wrong one is not removed.`)// The line comes out of the file but goes into the change log as this// row's before: a value that became a saved secret since is not journaled.- if (secretEntry(row.after)) throw new Error(`The entry that line ${line} added cannot be taken out: it looks like a key, token, password, or ID number, which memory never keeps.`)+ if (secretEntry(row.after)) throw new Error(`The entry the change added cannot be taken out: it looks like a key, token, password, or ID number, which memory never keeps.`)const lines = target.lines.filter((_line, index) => index !== found[0].line)const empty = target.topic !== undefined && lines.every(item => item.trim() === '' || HEADING.test(item))if (empty) {@@ -1555,22 +1606,22 @@ export function install(rt) {steps.push(writeStep(target.path, joinLines(lines)))}await publish({ op: 'remove', scope: scopeKey(scope), steps, row: { op: 'remove', ...base, before: row.after, ...(empty ? { removedTopic: true } : {}) } })- return { restored: row.id, op: 'remove', scope: row.scope, file: row.file, text: splitMeta(row.after.replace(/^\s*[-*]\s+/, '')).text }+ return}if (row.op === 'remove') {// Undoing a remove puts the line back. The original place is not in the// row, so it goes where a new entry would; a topic the remove took away// is made again with its link, and a line already back is not duplicated.- if (!entryLine(row.before)) throw new Error(`Line ${line} of the change log is not a change that can be restored.`)+ if (!entryLine(row.before)) throw new Error(`That change is not a change that can be restored.`)// The whole line, metadata included, must still be keepable: a value// anywhere in it may be a saved secret since the row was written.- if (secretEntry(row.before)) throw new Error(`The entry that line ${line} removed cannot be put back: it looks like a key, token, password, or ID number, which memory never keeps.`)+ if (secretEntry(row.before)) throw new Error(`The entry the change removed cannot be put back: it looks like a key, token, password, or ID number, which memory never keeps.`)const back = splitMeta(row.before.replace(/^\s*[-*]\s+/, '')).textconst problem = entryProblem(back)- if (problem !== undefined) throw new Error(`The entry that line ${line} removed cannot be put back: ${problem}`)+ if (problem !== undefined) throw new Error(`The entry the change removed cannot be put back: ${problem}`)const [same] = matchEntries(allEntries(files), back).filter(entry => squash(entry.text) === squash(back))- if (same !== undefined) throw noMatch(`The entry that line ${line} removed is already in ${label} (${fileName(same.file)}); there is nothing to restore.`)+ if (same !== undefined) throw noMatch(`The entry the change removed is already in ${label} (${fileName(same.file)}); there is nothing to restore.`)let file = targetif (file === undefined) {// The file may still be there under another case: a file system that folds@@ -1581,13 +1632,13 @@ export function install(rt) {// this row finds it again.if (existsSync(join(dirOf(scope), row.file))) {file = files.find(item => item.file.toLowerCase() === row.file.toLowerCase())- if (file === undefined) throw noMatch(`A file named ${row.file} is already in ${label}; the entry that line ${line} took out can be restored by hand.`)+ if (file === undefined) throw noMatch(`A file named ${row.file} is already in ${label}; the entry the change took out can be restored by hand.`)} else {const topic = row.removedTopic === true && row.file.endsWith('.md') && row.file !== MAIN ? row.file.slice(0, -3) : undefined- if (topic === undefined) throw noMatch(`The file that line ${line} took the entry from is gone; restore it by hand.`)+ if (topic === undefined) throw noMatch(`The file the change took the entry from is gone; restore it by hand.`)// The rebuilt topic carries its name into a heading and the Index link:// a name that is a saved secret now must not come back either.- if (secretEntry(topic)) throw new Error(`The topic that line ${line} removed cannot be put back: its name looks like a key, token, password, or ID number, which memory never keeps.`)+ if (secretEntry(topic)) throw new Error(`The topic the change removed cannot be put back: its name looks like a key, token, password, or ID number, which memory never keeps.`)if (files.length - 1 >= MEMORY_LIMITS.topics) throw Object.assign(new Error(`${capital(label)} already has ${MEMORY_LIMITS.topics} topics, the most it holds. Add to one of them (recall lists them), or forget one.`), { code: FULL })file = { topic, file: row.file, path: join(dirOf(scope), row.file), content: '', ...parseMemory(`# ${topic}\n`) }}@@ -1603,39 +1654,39 @@ export function install(rt) {steps.push(writeStep(main.path, index))}await publish({ op: 'add', scope: scopeKey(scope), steps, row: { op: 'add', ...base, file: file.file, after: row.before } })- return { restored: row.id, op: 'add', scope: row.scope, file: row.file, text: splitMeta(row.before.replace(/^\s*[-*]\s+/, '')).text }+ return}// row.op === 'replace': the recorded after-line is put back to before.- if (!entryLine(row.before)) throw new Error(`Line ${line} of the change log is not a change that can be restored.`)+ if (!entryLine(row.before)) throw new Error(`That change is not a change that can be restored.`)// The whole before-line, metadata included, must still be keepable.- if (secretEntry(row.before)) throw new Error(`The entry that line ${line} changed cannot be put back: it looks like a key, token, password, or ID number, which memory never keeps.`)+ if (secretEntry(row.before)) throw new Error(`The entry the change changed cannot be put back: it looks like a key, token, password, or ID number, which memory never keeps.`)if (target === undefined || typeof row.after !== 'string') {- throw noMatch(`The entry that line ${line} changed is not where the change log left it; it may have changed or been removed since.`)+ throw noMatch(`The entry the change changed is not where the change log left it; it may have changed or been removed since.`)}const found = exactLines(target, row.after)- if (found.length === 0) throw noMatch(`The entry that line ${line} changed is no longer in ${label}; it may have changed or been removed since.`)- if (found.length > 1) throw noMatch(`The line that line ${line} changed is in ${label} more than once; restore it by hand so the wrong one is not changed.`)+ if (found.length === 0) throw noMatch(`The entry the change changed is no longer in ${label}; it may have changed or been removed since.`)+ if (found.length > 1) throw noMatch(`The line the change changed is in ${label} more than once; restore it by hand so the wrong one is not changed.`)// The before-line passes the checks a new entry does, so a restore does not// write — into the file or the change log — what memory no longer keeps.const back = splitMeta(row.before.replace(/^\s*[-*]\s+/, '')).textconst problem = entryProblem(back)- if (problem !== undefined) throw new Error(`The entry that line ${line} changed cannot be put back: ${problem}`)+ if (problem !== undefined) throw new Error(`The entry the change changed cannot be put back: ${problem}`)// Nor does it come back twice: the same fact may have been saved again since,// under another topic or new metadata. The matched entry itself does not// count: an after that squashes to the before text is no duplicate.const same = matchEntries(allEntries(files), back).find(entry => squash(entry.text) === squash(back) && !(entry.file === target && entry.line === found[0].line))- if (same !== undefined) throw noMatch(`The entry that line ${line} changed is already in ${label} (${fileName(same.file)}); there is nothing to restore.`)+ if (same !== undefined) throw noMatch(`The entry the change changed is already in ${label} (${fileName(same.file)}); there is nothing to restore.`)// The recorded after-line is journaled as this row's before, so it faces// the same check the line going back did.- if (secretEntry(row.after)) throw new Error(`The entry that line ${line} wrote cannot be taken out: it looks like a key, token, password, or ID number, which memory never keeps.`)+ if (secretEntry(row.after)) throw new Error(`The entry the change wrote cannot be taken out: it looks like a key, token, password, or ID number, which memory never keeps.`)const lines = [...target.lines]lines[found[0].line] = row.beforeconst next = joinLines(lines)checkSize(target, next, label)await publish({ op: 'replace', scope: scopeKey(scope), steps: [writeStep(target.path, next)], row: { op: 'replace', ...base, before: row.after, after: row.before } })- return { restored: row.id, op: 'replace', scope: row.scope, file: row.file, text: splitMeta(row.before.replace(/^\s*[-*]\s+/, '')).text }})+ return await memoryView(panelBody(panel))}// ---------------------------------------------------------------------------@@ -1986,6 +2037,7 @@ export function install(rt) {if (endpoint === 'memory-view') return memoryView(body)if (endpoint === 'memory-ask') return memoryAsk(body)if (endpoint === 'memory-forget') return memoryForget(body)+ if (endpoint === 'memory-history') return memoryHistory(body)if (endpoint === 'memory-restore') return memoryRestore(body)throw new Error(`Unknown endpoint ${endpoint}`)}diff --git a/ds-bot/test/memory-history.test.js b/ds-bot/test/memory-history.test.jsnew file mode 100644index 00000000..284388ba--- /dev/null+++ b/ds-bot/test/memory-history.test.js@@ -0,0 +1,124 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { createRequire } from 'node:module'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { runInNewContext } from 'node:vm'+import { build } from 'esbuild'++// jsdom comes from the harness that test/harness-resolve.mjs found, like the dsh packages.+const PLUGIN = dirname(dirname(fileURLToPath(import.meta.url)))+const { JSDOM } = createRequire(join(process.env.DSH_HARNESS ?? join(PLUGIN, '..', 'deepseek-harness'), 'package.json'))('jsdom')++// The memory dialog's history page, bundled once and run with a minimal React+// stand-in; state comes back from a seed list so each render is deterministic.+const { outputFiles } = await build({+ stdin: {+ contents: "export { History, HistoryRow } from './src/client/memory-panel.js'",+ resolveDir: PLUGIN,+ },+ bundle: true, format: 'cjs', platform: 'browser', write: false, logLevel: 'silent',+ external: ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives'],+})+let seeds = []+let setters = []+const react = {+ createContext: (initial) => { const ctx = { value: initial }; ctx.Provider = ({ value, children }) => { ctx.value = value; return children }; return ctx },+ useContext: ctx => ctx.value,+ useCallback: fn => fn,+ useSyncExternalStore: (subscribe, getSnapshot) => getSnapshot(),+ createElement: (type, props, ...children) => ({ type, props: { ...props, children } }),+ Fragment: Symbol('Fragment'),+ useEffect() {}, useLayoutEffect() {},+ useState: (initial) => {+ const index = setters.length+ setters.push([])+ const value = index < seeds.length ? seeds[index] : initial+ return [value, next => setters[index].push(next)]+ },+ useMemo: make => make(), useRef: current => ({ current }), useId: () => 'id',+}+const dom = new JSDOM('<!doctype html><body></body>')+const module = { exports: {} }+runInNewContext(outputFiles[0].text, {+ module, exports: module.exports,+ document: dom.window.document,+ window: { matchMedia: () => ({ matches: false }) },+ MutationObserver: dom.window.MutationObserver,+ requestAnimationFrame: fn => setTimeout(fn, 0),+ cancelAnimationFrame: id => clearTimeout(id),+ require: name => (name === 'react' ? react : name === 'react-dom' ? { createPortal: node => node } : {}),+})+const { History, HistoryRow } = module.exports++// A vnode tree's function components are run as they are found, so text and+// handlers read as they would in the DOM.+function* walk(node) {+ if (node === null || node === undefined || node === false) return+ if (Array.isArray(node)) { for (const item of node) yield* walk(item); return }+ if (typeof node === 'object' && node.type !== undefined) {+ if (typeof node.type === 'function') { yield* walk(node.type(node.props)); return }+ yield node+ yield* walk(node.props?.children)+ return+ }+ yield node+}+const render = (component, props, stateSeeds) => {+ seeds = stateSeeds ?? []+ setters = []+ return component(props)+}+const texts = tree => [...walk(tree)].filter(node => typeof node === 'string').join(' ')+const buttons = tree => [...walk(tree)].filter(node => typeof node === 'object' && node?.type === 'button')++const owner = { id: 'b2', name: 'Writer', group: false }+const NOW = new Date('2026-11-02T12:00:00Z').getTime()+const row = (over) => ({ id: `r-${Math.random()}`, time: '2026-11-02T11:00:00Z', op: 'add', scope: 'own', text: 'Likes tea', by: 'user', restored: false, ...over })++test('a history row shows the change, who made it, and an undo button', () => {+ const tree = render(HistoryRow, { row: row({ op: 'add', scope: 'team', by: 'Coder' }), undo: async () => true, now: NOW })+ const text = texts(tree)+ assert.match(text, /Added to team memory: Likes tea/)+ assert.match(text, /an hour ago · by Coder|1 hour ago · by Coder|hour.*by Coder/)+ const undo = buttons(tree)[0]+ assert.equal(undo.props['aria-label'], 'Undo this change')+})++test('an undone row shows the muted label instead of the button', () => {+ const tree = render(HistoryRow, { row: row({ restored: true, op: 'remove' }), undo: async () => true, now: NOW })+ const text = texts(tree)+ assert.match(text, /Removed: Likes tea/)+ assert.match(text, /Undone/)+ assert.equal(buttons(tree).length, 0)+})++test('undo asks for a second click before it calls memoryRestore', async () => {+ const calls = []+ // confirming=false, busy=false: the first click only arms the confirm state.+ let tree = render(HistoryRow, { row: row(), undo: async r => calls.push(r) ?? true, now: NOW }, [false, false])+ await buttons(tree)[0].props.onClick()+ assert.deepEqual(calls, [])+ assert.deepEqual(setters[0], [true])+ // confirming=true: the second click runs the undo.+ tree = render(HistoryRow, { row: row({ id: 'row-9' }), undo: async r => calls.push(r.id) ?? true, now: NOW }, [true, false])+ await buttons(tree)[0].props.onClick()+ assert.deepEqual(calls, ['row-9'])+})++test('the page lists rows, an empty state, and Load more asks for the next page', async () => {+ const asked = []+ const actions = { memoryHistory: async (id, before) => { asked.push([id, before]); return { rows: [row()], more: null } } }+ const rows = [row({ text: 'Kept one' }), row({ op: 'replace', text: 'Kept two' })]+ const tree = render(History, { owner, actions, undo: async () => true, now: NOW }, [rows, 'cursor-1', false])+ const text = texts(tree)+ assert.match(text, /Added: Kept one/)+ assert.match(text, /Updated: Kept two/)+ const more = buttons(tree).find(node => node.props.className === 'bt-soft bt-soft-sm')+ assert.ok(more, 'Load more renders while more is set')+ await more.props.onClick()+ assert.deepEqual(asked, [['b2', 'cursor-1']])++ const empty = render(History, { owner, actions, undo: async () => true, now: NOW }, [[], null, false])+ assert.match(texts(empty), /No changes yet/)+})diff --git a/ds-bot/test/memory.test.js b/ds-bot/test/memory.test.jsindex 38a7d914..90ba492e 100644--- a/ds-bot/test/memory.test.js+++ b/ds-bot/test/memory.test.js@@ -265,35 +265,31 @@ test('a journal line restores its change: remove, replace, and add undone', asynconst removed = journal().at(-1)assert.equal(removed.op, 'remove')assert.equal(parseMemory(read('bots', 'b2', 'MEMORY.md')).entries.length, 0)- const line = journal().length- const restored = await call('memory-restore', { line })+ const restored = await call('memory-restore', { botId: 'b2', id: removed.id })assert.equal(restored.ok, true, JSON.stringify(restored))- assert.equal(restored.value.op, 'add')- assert.equal(restored.value.restored, removed.id)assert.match(read('bots', 'b2', 'MEMORY.md'), /- User prefers short replies \[/)assert.equal(journal().at(-1).op, 'add')assert.equal(journal().at(-1).restored, removed.id)// A remove already undone is not undone twice: the line is back, so NO_MATCH.- const twice = await call('memory-restore', { line })+ const twice = await call('memory-restore', { botId: 'b2', id: removed.id })assert.equal(twice.ok, false)- assert.match(twice.error.message, /already in/)+ assert.match(twice.error.message, /already restored/)// Undoing an add takes the line back out, while it still reads as written.- const addLine = journal().findIndex(record => record.id === added.id) + 1- const undone = await call('memory-restore', { line: addLine })+ const undone = await call('memory-restore', { botId: 'b2', id: added.id })assert.equal(undone.ok, true, JSON.stringify(undone))- assert.equal(undone.value.op, 'remove')+ assert.equal(journal().at(-1).op, 'remove')assert.equal(parseMemory(read('bots', 'b2', 'MEMORY.md')).entries.length, 0)// A replace puts the before-line back.await tool('remember', { text: 'Lives in Hangzhou' }, 'b2')await tool('remember', { text: 'Lives in Shanghai', replace: 'Hangzhou' }, 'b2')const replaced = journal().at(-1)- const back = await call('memory-restore', { line: journal().length })+ const back = await call('memory-restore', { botId: 'b2', id: replaced.id })assert.equal(back.ok, true, JSON.stringify(back))- assert.equal(back.value.op, 'replace')- assert.equal(back.value.restored, replaced.id)+ assert.equal(journal().at(-1).op, 'replace')+ assert.equal(journal().at(-1).restored, replaced.id)assert.match(read('bots', 'b2', 'MEMORY.md'), /- Lives in Hangzhou \[/)assert.doesNotMatch(read('bots', 'b2', 'MEMORY.md'), /Shanghai/)})@@ -302,23 +298,23 @@ test('a restore refuses drift and rows that are not restorable', async (t) => {const { tool, call, read, journal, stop } = start()t.after(() => stop())await tool('remember', { text: 'User prefers short replies' }, 'b2')- const addLine = journal().length+ const added = journal().at(-1)// The entry the add wrote was replaced since: undoing it now is a NO_MATCH,// not a delete of the newer text.await tool('remember', { text: 'User prefers very short replies', replace: 'short replies' }, 'b2')- const drift = await call('memory-restore', { line: addLine })+ const drift = await call('memory-restore', { botId: 'b2', id: added.id })assert.equal(drift.ok, false)assert.match(drift.error.message, /no longer in|not where the change log left it/)assert.match(read('bots', 'b2', 'MEMORY.md'), /very short replies/)- for (const body of [{ line: 0 }, { line: -2 }, { line: 'three' }, {}]) {+ for (const body of [{ botId: 'b2', id: '' }, { botId: 'b2' }]) {const bad = await call('memory-restore', body)assert.equal(bad.ok, false, JSON.stringify(body))- assert.match(bad.error.message, /line/)+ assert.match(bad.error.message, /change log id/)}- const pastEnd = await call('memory-restore', { line: journal().length + 10 })- assert.equal(pastEnd.ok, false)- assert.match(pastEnd.error.message, /not a change that can be restored/)+ const missing = await call('memory-restore', { botId: 'b2', id: 'row-that-is-not-there' })+ assert.equal(missing.ok, false)+ assert.match(missing.error.message, /not in the change log of this memory/)})test('restoring a remove that took a topic with it makes the topic again', async (t) => {@@ -330,7 +326,7 @@ test('restoring a remove that took a topic with it makes the topic again', asyncassert.equal(removed.removedTopic, true)assert.equal(existsSync(join(home, 'memory', 'bots', 'b2', 'travel.md')), false)- const restored = await call('memory-restore', { line: journal().length })+ const restored = await call('memory-restore', { botId: 'b2', id: removed.id })assert.equal(restored.ok, true, JSON.stringify(restored))assert.match(read('bots', 'b2', 'travel.md'), /^# travel\n\n- Flies from Hangzhou \[/)assert.match(read('bots', 'b2', 'MEMORY.md'), /- \[\[travel\]\]/)@@ -352,12 +348,12 @@ test('a restore does not put back a value that is a saved secret now', async (t)const saved = await call('secret-set', { name: 'CLUB_CODE', value: 'bricksparrow72' })assert.equal(saved.ok, true, JSON.stringify(saved))- const back = await call('memory-restore', { line: journal().findIndex(record => record.id === removed.id) + 1 })+ const back = await call('memory-restore', { botId: 'b2', id: removed.id })assert.equal(back.ok, false)assert.match(back.error.message, /cannot be put back/)assert.match(back.error.message, /never keeps/)assert.doesNotMatch(back.error.message, /bricksparrow72/)- const backReplace = await call('memory-restore', { line: journal().findIndex(record => record.id === replaced.id) + 1 })+ const backReplace = await call('memory-restore', { botId: 'b2', id: replaced.id })assert.equal(backReplace.ok, false)assert.match(backReplace.error.message, /cannot be put back/)assert.doesNotMatch(backReplace.error.message, /bricksparrow72/)@@ -371,21 +367,22 @@ test('the row a restore wrote passes the same guards when it is restored', asynct.after(() => stop())await tool('remember', { text: 'Wears a green coat' }, 'b2')// Undoing the add leaves a remove row of its own.- const undone = await call('memory-restore', { line: journal().length })+ const undone = await call('memory-restore', { botId: 'b2', id: journal().at(-1).id })assert.equal(undone.ok, true, JSON.stringify(undone))assert.equal(journal().at(-1).op, 'remove')const line = journal().length+ const rid = journal().at(-1).id// The fact is back under another topic: the restore row is not duplicated back.await tool('remember', { text: 'wears a green coat', topic: 'Style' }, 'b2')- const again = await call('memory-restore', { line })+ const again = await call('memory-restore', { botId: 'b2', id: rid })assert.equal(again.ok, false)assert.match(again.error.message, /already in/)// And once the value is a saved secret, the same row cannot put it back either.const saved = await call('secret-set', { name: 'COAT_COLOR', value: 'green coat' })assert.equal(saved.ok, true, JSON.stringify(saved))- const refused = await call('memory-restore', { line })+ const refused = await call('memory-restore', { botId: 'b2', id: rid })assert.equal(refused.ok, false)assert.match(refused.error.message, /cannot be put back/)assert.doesNotMatch(refused.error.message, /green coat/)@@ -397,10 +394,10 @@ test('a restore does not duplicate a fact remembered again', async (t) => {t.after(() => stop())await tool('remember', { text: 'Lives in Hangzhou', topic: 'Home' }, 'b2')await tool('forget', { entry: 'Hangzhou' }, 'b2')- const line = journal().length+ const removed = journal().at(-1).id// The same fact is back, in MEMORY.md this time and under new metadata.await tool('remember', { text: 'lives in hangzhou' }, 'b2')- const restored = await call('memory-restore', { line })+ const restored = await call('memory-restore', { botId: 'b2', id: removed })assert.equal(restored.ok, false)assert.match(restored.error.message, /already in/)assert.equal(parseMemory(read('bots', 'b2', 'MEMORY.md')).entries.length, 1)@@ -413,9 +410,9 @@ test('a restore cannot rebuild a topic past the count the memory holds', async (for (let i = 1; i <= 40; i += 1) await tool('remember', { text: `detail ${i}`, topic: `topic-${i}` }, 'b2')// topic-40 goes when its last entry does; a fresh topic takes the room meanwhile.await tool('forget', { entry: 'detail 40', topic: 'topic-40' }, 'b2')- const line = journal().length+ const removed = journal().at(-1).idawait tool('remember', { text: 'a fresh fact', topic: 'fresh' }, 'b2')- const restored = await call('memory-restore', { line })+ const restored = await call('memory-restore', { botId: 'b2', id: removed })assert.equal(restored.ok, false)assert.match(restored.error.message, /already has 40 topics/)})@@ -428,7 +425,7 @@ test('a restore of a replace does not duplicate a fact remembered again', asyncconst replaced = journal().at(-1)// The old fact is remembered again since, under a topic and new metadata.await tool('remember', { text: 'lives in hangzhou', topic: 'Home' }, 'b2')- const restored = await call('memory-restore', { line: journal().findIndex(record => record.id === replaced.id) + 1 })+ const restored = await call('memory-restore', { botId: 'b2', id: replaced.id })assert.equal(restored.ok, false)assert.match(restored.error.message, /already in/)// The entry it replaced stays put, and the remembered copy is not doubled.@@ -443,7 +440,7 @@ test('a restore of a replace whose after reads like its before is no duplicate',await tool('remember', { text: 'drinks tea daily', replace: 'tea' }, 'b2')// The after-line squashes to the before text: the matched entry itself is no// duplicate, so the restore still puts the recorded before-line back.- const restored = await call('memory-restore', { line: journal().length })+ const restored = await call('memory-restore', { botId: 'b2', id: journal().at(-1).id })assert.equal(restored.ok, true, JSON.stringify(restored))assert.match(read('bots', 'b2', 'MEMORY.md'), /- Drinks tea daily \[/)assert.doesNotMatch(read('bots', 'b2', 'MEMORY.md'), /- drinks tea daily/)@@ -459,48 +456,130 @@ test('a restore refuses a change-log row whose file is not a flat name', async (const forge = (file) => {const row = { id: `forged-${file}`, time: new Date().toISOString(), op: 'remove', scope: 'bot:b2', file, actor: 'user', actorName: 'user', removedTopic: true, before: '- forged entry' }writeFileSync(journalPath, `${read('journal.jsonl')}${JSON.stringify(row)}\n`)- return journal().length+ return row.id}for (const file of ['../../team/MEMORY.md', '..\\..\\team\\MEMORY.md', 'topics/deep.md', '..', '.', 'C:\\out\\x.md']) {- const line = forge(file)- const denied = await call('memory-restore', { line })+ const rid = forge(file)+ const count = journal().length+ const denied = await call('memory-restore', { botId: 'b2', id: rid })assert.equal(denied.ok, false, file)assert.match(denied.error.message, /not a change that can be restored/, file)// The file the row pointed at is untouched, and no restore row was logged.assert.match(read('team', 'MEMORY.md'), /- Team drinks tea \[/)assert.doesNotMatch(read('team', 'MEMORY.md'), /forged/)assert.doesNotMatch(read('bots', 'b2', 'MEMORY.md'), /forged|\.\./)- assert.equal(journal().length, line)+ assert.equal(journal().length, count)}})-test('a restore line counts physical lines of the change log, blanks included', async (t) => {- const { tool, call, read, stop, home } = start()+test('a restore finds a change by row id, blank and foreign lines aside', async (t) => {+ const { tool, call, read, journal, stop, home } = start()t.after(() => stop())await tool('remember', { text: 'Fact A' }, 'b2')+ const addedA = journal().at(-1)await tool('remember', { text: 'Fact B' }, 'b2')await tool('forget', { entry: 'Fact A' }, 'b2')+ const removed = journal().at(-1)const journalPath = join(home, 'memory', 'journal.jsonl')- const physical = () => read('journal.jsonl').split('\n')-- // A blank first line does not renumber the rows: line 2 is the remove of A,- // not the add of B, so restoring it cannot delete B.- writeFileSync(journalPath, `\n${read('journal.jsonl')}`)- const blank = await call('memory-restore', { line: 1 })- assert.equal(blank.ok, false)- assert.match(blank.error.message, /not a change that can be restored/)- const removed = await call('memory-restore', { line: 2 })- assert.equal(removed.ok, false)- assert.match(removed.error.message, /not where the change log left it|no longer in/)- assert.match(read('bots', 'b2', 'MEMORY.md'), /- Fact B \[/)- assert.doesNotMatch(read('bots', 'b2', 'MEMORY.md'), /Fact A/)- // The add of A is the third physical line: restoring it takes A out again.- const undone = await call('memory-restore', { line: 3 })+ // Blank and half-written lines sit in the log: the row's own id still finds it.+ writeFileSync(journalPath, `\nnot json\n${read('journal.jsonl')}`)+ const restored = await call('memory-restore', { botId: 'b2', id: removed.id })+ assert.equal(restored.ok, true, JSON.stringify(restored))+ assert.match(read('bots', 'b2', 'MEMORY.md'), /- Fact A \[/)++ // The add of A goes by its id too: restoring it takes A out again.+ const undone = await call('memory-restore', { botId: 'b2', id: addedA.id })assert.equal(undone.ok, true, JSON.stringify(undone))assert.doesNotMatch(read('bots', 'b2', 'MEMORY.md'), /Fact A/)- // The restore rows appended behind still count physical lines.- assert.equal(physical().filter(line => line !== '').length, 4)+ assert.match(read('bots', 'b2', 'MEMORY.md'), /- Fact B \[/)+})++test('memory-history lists a Bot\'s own and team changes, newest first', async (t) => {+ const { tool, call, journal, stop } = start()+ t.after(() => stop())+ await tool('remember', { text: 'Team drinks tea', scope: 'team' }, 'm1')+ await tool('remember', { text: 'Likes quiet mornings' }, 'b2')+ await tool('remember', { text: 'Another Bot fact' }, 'b4')+ const page = await call('memory-history', { botId: 'b2' })+ assert.equal(page.ok, true, JSON.stringify(page))+ assert.equal(page.value.more, null)+ assert.deepEqual(page.value.rows.map(row => [row.op, row.scope, row.by]), [+ ['add', 'own', 'Writer'],+ ['add', 'team', 'Chief'],+ ])+ assert.match(page.value.rows[0].text, /Likes quiet mornings/)+ assert.equal(page.value.rows.every(row => row.restored === false), true)+ assert.equal(journal().length, 3)+})++test('memory-history reads a private Bot\'s own log beside the shared one', async (t) => {+ const { tool, call, stop, home } = start()+ t.after(() => stop())+ const team = JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))+ team.bots.b2.private = true+ writeFileSync(join(home, 'state.json'), JSON.stringify(team))+ await tool('remember', { text: 'A private fact' }, 'b2')+ await tool('remember', { text: 'Team drinks tea', scope: 'team' }, 'm1')+ const page = await call('memory-history', { botId: 'b2' })+ assert.equal(page.ok, true, JSON.stringify(page))+ // Own rows come out of the private log, team rows out of the shared one.+ assert.equal(page.value.rows.find(row => row.scope === 'own')?.text.slice(0, 14), 'A private fact')+ assert.equal(page.value.rows.find(row => row.scope === 'team')?.text.slice(0, 14), 'Team drinks te')+ assert.equal(page.value.rows.length, 2)+ assert.equal(existsSync(join(home, 'memory', 'bots', 'b2', 'journal.jsonl')), true)+})++test('memory-history lists a group\'s changes and marks rows already undone', async (t) => {+ const { tool, call, journal, stop } = start()+ t.after(() => stop())+ await tool('remember', { text: 'Keep replies under one page' }, 'g3')+ await tool('forget', { entry: 'one page' }, 'g3')+ const removed = journal().at(-1)+ const restored = await call('memory-restore', { roomId: 'r1', id: removed.id })+ assert.equal(restored.ok, true, JSON.stringify(restored))+ const page = await call('memory-history', { roomId: 'r1' })+ assert.equal(page.ok, true, JSON.stringify(page))+ assert.deepEqual(page.value.rows.map(row => [row.op, row.scope, row.restored]), [+ ['add', 'group', false],+ ['remove', 'group', true],+ ['add', 'group', false],+ ])+ assert.equal(page.value.rows.at(-1).restored, false)+ // A row that is itself a restore is listed like any other, and can be undone.+ assert.equal(page.value.rows[0].id, journal().at(-1).id)+ const undone = await call('memory-restore', { roomId: 'r1', id: journal().at(-1).id })+ assert.equal(undone.ok, true, JSON.stringify(undone))+})++test('a restore refuses a row outside the owner\'s scopes', async (t) => {+ const { tool, call, journal, stop } = start()+ t.after(() => stop())+ await tool('remember', { text: 'A Bot fact' }, 'b4')+ const row = journal().at(-1)+ const denied = await call('memory-restore', { botId: 'b2', id: row.id })+ assert.equal(denied.ok, false)+ assert.match(denied.error.message, /not in the change log of this memory/)+})++test('memory-history pages oldest rows behind before', async (t) => {+ const { tool, call, journal, stop, home } = start()+ t.after(() => stop())+ const journalPath = join(home, 'memory', 'journal.jsonl')+ await tool('remember', { text: 'First fact' }, 'b2')+ const base = journal()+ const forged = Array.from({ length: 60 }, (_, i) => ({ id: `old-${i}`, time: new Date(Date.now() - (60 - i) * 1000).toISOString(), op: 'add', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', after: `- forged ${i}` }))+ writeFileSync(journalPath, `${journal().map(row => JSON.stringify(row)).join('\n')}\n${forged.map(row => JSON.stringify(row)).join('\n')}\n`)+ const first = await call('memory-history', { botId: 'b2' })+ assert.equal(first.ok, true, JSON.stringify(first))+ assert.equal(first.value.rows.length, 50)+ assert.notEqual(first.value.more, null)+ const second = await call('memory-history', { botId: 'b2', before: first.value.more })+ assert.equal(second.ok, true, JSON.stringify(second))+ assert.equal(second.value.rows.length, 11)+ assert.equal(second.value.more, null)+ assert.equal(second.value.rows.at(-1).id, 'old-0')+ assert.equal(first.value.rows[0].id, base[0].id)})test('a restore refuses a row whose before is not one entry line', async (t) => {@@ -510,17 +589,17 @@ test('a restore refuses a row whose before is not one entry line', async (t) =>const journalPath = join(home, 'memory', 'journal.jsonl')const forge = (row) => {writeFileSync(journalPath, `${read('journal.jsonl')}${JSON.stringify(row)}\n`)- return journal().length+ return JSON.parse(read('journal.jsonl').trim().split('\n').at(-1)).id}// A heading or several lines put back would corrupt the file or hide what// follows from recall; a real remove row always held one bullet.for (const before of ['## Index', '- one\n- two', 'plain text', '* ', '']) {- const removeLine = forge({ id: `rm-${JSON.stringify(before)}`, time: new Date().toISOString(), op: 'remove', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before })- const denied = await call('memory-restore', { line: removeLine })+ const removeId = forge({ id: `rm-${JSON.stringify(before)}`, time: new Date().toISOString(), op: 'remove', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before })+ const denied = await call('memory-restore', { botId: 'b2', id: removeId })assert.equal(denied.ok, false, JSON.stringify(before))assert.match(denied.error.message, /not a change that can be restored/, JSON.stringify(before))- const replaceLine = forge({ id: `rp-${JSON.stringify(before)}`, time: new Date().toISOString(), op: 'replace', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before, after: journal()[0].after })- const deniedReplace = await call('memory-restore', { line: replaceLine })+ const replaceId = forge({ id: `rp-${JSON.stringify(before)}`, time: new Date().toISOString(), op: 'replace', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before, after: journal()[0].after })+ const deniedReplace = await call('memory-restore', { botId: 'b2', id: replaceId })assert.equal(deniedReplace.ok, false, JSON.stringify(before))assert.match(deniedReplace.error.message, /not a change that can be restored/, JSON.stringify(before))}@@ -537,7 +616,7 @@ test('a restore follows a hand-named topic file', async (t) => {writeFileSync(join(home, 'memory', 'bots', 'b2', 'MEMORY.md'), '# Memory\n\n## Index\n- [[Travel]]\n')assert.match(await tool('remember', { text: 'Prefers window seats', replace: 'aisle' }, 'b2'), /is now "Prefers window seats"/)assert.equal(journal().at(-1).file, 'Travel.md')- const restored = await call('memory-restore', { line: journal().length })+ const restored = await call('memory-restore', { botId: 'b2', id: journal().at(-1).id })assert.equal(restored.ok, true, JSON.stringify(restored))assert.match(read('bots', 'b2', 'Travel.md'), /- Prefers aisle seats \[added: 2026-01-01\]/)})@@ -555,13 +634,13 @@ test('a restore checks the whole line for a saved secret, its metadata too', asy// new entry gets never sees it, but putting the line back would write it.const forge = (row) => {writeFileSync(journalPath, `${read('journal.jsonl')}${JSON.stringify(row)}\n`)- return journal().length+ return JSON.parse(read('journal.jsonl').trim().split('\n').at(-1)).id}for (const op of ['remove', 'replace']) {const before = `- Prefers window seats [note: ${secret}]`const row = { id: `sec-${op}`, time: new Date().toISOString(), op, scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before }if (op === 'replace') row.after = journal()[1].after- const denied = await call('memory-restore', { line: forge(row) })+ const denied = await call('memory-restore', { botId: 'b2', id: forge(row) })assert.equal(denied.ok, false, op)assert.match(denied.error.message, /cannot be put back/, op)assert.doesNotMatch(denied.error.message, new RegExp(secret))@@ -580,7 +659,7 @@ test('a restore refuses a file name with a control character instead of wedging'// stops on it. The row is refused before any of that is reached.const row = { id: 'bad-ctl', time: new Date().toISOString(), op: 'remove', scope: 'bot:b2', file: 'bad\0.md', actor: 'user', actorName: 'user', removedTopic: true, before: '- forged entry' }writeFileSync(journalPath, `${read('journal.jsonl')}${JSON.stringify(row)}\n`)- const denied = await call('memory-restore', { line: journal().length })+ const denied = await call('memory-restore', { botId: 'b2', id: 'bad-ctl' })assert.equal(denied.ok, false)assert.match(denied.error.message, /not a change that can be restored/)assert.equal(existsSync(join(home, 'memory', 'pending.json')), false)@@ -603,14 +682,14 @@ test('a restore dedupes a row whose before line is an indented bullet', async (t// the same entry either way.const forge = (row) => {writeFileSync(journalPath, `${read('journal.jsonl')}${JSON.stringify(row)}\n`)- return journal().length+ return JSON.parse(read('journal.jsonl').trim().split('\n').at(-1)).id}- const removeLine = forge({ id: 'ind-rm', time: new Date().toISOString(), op: 'remove', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before: ' - Drinks tea daily [added: 2026-01-01]' })- const denied = await call('memory-restore', { line: removeLine })+ const removeId = forge({ id: 'ind-rm', time: new Date().toISOString(), op: 'remove', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before: ' - Drinks tea daily [added: 2026-01-01]' })+ const denied = await call('memory-restore', { botId: 'b2', id: removeId })assert.equal(denied.ok, false)assert.match(denied.error.message, /already in/)- const replaceLine = forge({ id: 'ind-rp', time: new Date().toISOString(), op: 'replace', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before: ' - Drinks tea daily', after: journal()[1].after })- const deniedReplace = await call('memory-restore', { line: replaceLine })+ const replaceId = forge({ id: 'ind-rp', time: new Date().toISOString(), op: 'replace', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before: ' - Drinks tea daily', after: journal()[1].after })+ const deniedReplace = await call('memory-restore', { botId: 'b2', id: replaceId })assert.equal(deniedReplace.ok, false)assert.match(deniedReplace.error.message, /already in/)assert.match(read('bots', 'b2', 'MEMORY.md'), /- Lives in Hangzhou \[/)@@ -618,9 +697,9 @@ test('a restore dedupes a row whose before line is an indented bullet', async (t// An indented before that is no duplicate still restores, and reports the// entry's text, not the line's raw shape.const clean = forge({ id: 'ind-ok', time: new Date().toISOString(), op: 'remove', scope: 'bot:b2', file: 'MEMORY.md', actor: 'user', actorName: 'user', before: ' - Prefers aisle seats' })- const restored = await call('memory-restore', { line: clean })+ const restored = await call('memory-restore', { botId: 'b2', id: clean })assert.equal(restored.ok, true, JSON.stringify(restored))- assert.equal(restored.value.text, 'Prefers aisle seats')+ assert.match(journal().at(-1).after, /Prefers aisle seats/)assert.match(read('bots', 'b2', 'MEMORY.md'), /^ {2}- Prefers aisle seats$/m)})@@ -632,21 +711,21 @@ test('a restore puts a removed topic back into its case-folded file, never overwriteFileSync(join(home, 'memory', 'bots', 'b2', 'Travel.md'), '# Travel\n\n- Prefers aisle seats [added: 2026-01-01]\n')writeFileSync(join(home, 'memory', 'bots', 'b2', 'MEMORY.md'), '# Memory\n\n## Index\n- [[Travel]]\n')await tool('forget', { entry: 'aisle seats' }, 'b2')- const line = journal().length+ const removed = journal().at(-1).idconst dir = join(home, 'memory', 'bots', 'b2')// Remembering under the same words makes travel.md; on a file system that// folds case it is the file Travel.md named. A fresh Travel.md written over// it would lose the new fact.await tool('remember', { text: 'Flies on Fridays', topic: 'Travel' }, 'b2')const folded = existsSync(join(dir, 'TRAVEL.MD'))- const restored = await call('memory-restore', { line })+ const restored = await call('memory-restore', { botId: 'b2', id: removed })assert.equal(restored.ok, true, JSON.stringify(restored))if (folded) {assert.match(read('bots', 'b2', 'travel.md'), /- Flies on Fridays \[/)assert.match(read('bots', 'b2', 'travel.md'), /- Prefers aisle seats \[added: 2026-01-01\]/)assert.equal(journal().at(-1).file, 'travel.md')// Undoing the restore finds the line in the file that holds it.- const undone = await call('memory-restore', { line: journal().length })+ const undone = await call('memory-restore', { botId: 'b2', id: journal().at(-1).id })assert.equal(undone.ok, true, JSON.stringify(undone))assert.doesNotMatch(read('bots', 'b2', 'travel.md'), /Prefers aisle seats/)} else {@@ -662,7 +741,7 @@ test('a restore refuses a removed topic whose name is a saved secret now', asynct.after(() => stop())await tool('remember', { text: 'Meet at the dock', topic: 'harbor-dock-meeting-9f3k' }, 'b2')await tool('forget', { entry: 'dock', topic: 'harbor-dock-meeting-9f3k' }, 'b2')- const line = journal().length+ const rid = journal().at(-1).idconst lines = journal().lengthconst dir = join(home, 'memory', 'bots', 'b2')assert.equal(existsSync(join(dir, 'harbor-dock-meeting-9f3k.md')), false)@@ -670,7 +749,7 @@ test('a restore refuses a removed topic whose name is a saved secret now', async// topic would write it into a heading and the Index link, in the clear.const saved = await call('secret-set', { name: 'COVE_WORD', value: 'harbor-dock-meeting-9f3k' })assert.equal(saved.ok, true, JSON.stringify(saved))- const denied = await call('memory-restore', { line })+ const denied = await call('memory-restore', { botId: 'b2', id: rid })assert.equal(denied.ok, false)assert.match(denied.error.message, /cannot be put back/)assert.doesNotMatch(denied.error.message, /harbor-dock-meeting-9f3k/)@@ -692,7 +771,7 @@ test('a restore rebuilds a removed topic whose file name is near the name limit'writeFileSync(join(dir, `${stem}.md`), `# ${stem}\n\n- A fact kept for ${stem.length} characters [added: 2026-01-01]\n`)writeFileSync(join(dir, 'MEMORY.md'), `# Memory\n\n## Index\n- [[${stem}]]\n`)assert.match(await tool('forget', { entry: `${stem.length} characters` }, 'b2'), /was empty/)- const restored = await call('memory-restore', { line: journal().length })+ const restored = await call('memory-restore', { botId: 'b2', id: journal().at(-1).id })assert.equal(restored.ok, true, JSON.stringify(restored))assert.match(read('bots', 'b2', `${stem}.md`), /- A fact kept for /)assert.equal(existsSync(join(home, 'memory', 'pending.json')), false)@@ -706,10 +785,10 @@ test('a restore does not journal a line that is a saved secret now', async (t) =const { tool, call, read, journal, stop, home } = start()t.after(() => stop())await tool('remember', { text: 'Lives in Hangzhou' }, 'b2')- const addLine = journal().length+ const addId = journal().at(-1).idawait tool('remember', { text: 'Likes tea' }, 'b2')await tool('remember', { text: 'Likes green tea', replace: 'tea' }, 'b2')- const replaceLine = journal().length+ const replaceId = journal().at(-1).idconst rows = journal().length// Each restore copies the line its row wrote into a row of its own: a value// that became a saved secret since must not come back to the change log.@@ -718,11 +797,11 @@ test('a restore does not journal a line that is a saved secret now', async (t) =const keptTea = await call('secret-set', { name: 'TEA_CHOICE', value: 'Likes green tea' })assert.equal(keptTea.ok, true, JSON.stringify(keptTea))- const undoAdd = await call('memory-restore', { line: addLine })+ const undoAdd = await call('memory-restore', { botId: 'b2', id: addId })assert.equal(undoAdd.ok, false)assert.match(undoAdd.error.message, /cannot be taken out/)assert.doesNotMatch(undoAdd.error.message, /Lives in Hangzhou/)- const undoReplace = await call('memory-restore', { line: replaceLine })+ const undoReplace = await call('memory-restore', { botId: 'b2', id: replaceId })assert.equal(undoReplace.ok, false)assert.match(undoReplace.error.message, /cannot be taken out/)assert.doesNotMatch(undoReplace.error.message, /Likes green tea/)