diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index 2228afcca..a6a89e111 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -16,6 +16,7 @@ These pages describe current responsibilities, runtime paths, state, and contrac | Providers, keys, subscription accounts, refresh and allowance | [Providers and accounts](providers-accounts.md) | | Instructions, MCP servers, skills and RTK written into agents | [Library](library.md) | | One MCP server, magpie, given to every agent in place of the Library's servers | [MCP router](mcp-router.md) | +| Memory shared by every agent: the memory MCP server, the digest in instructions, the Memory tab | [Memory](memory.md) | | One skill, magpie-skills, listing the Library's skills in place of each agent's own | [Skill router](skill-router.md) | | Tray, panel, window, `magpie web` and the page's JSON API | [GUI app shell](gui-shell.md) | | Encrypted backups and setup synchronization over WebDAV, S3 or GitHub | [Sync and backup](sync-backup.md) | diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md new file mode 100644 index 000000000..567df85e8 --- /dev/null +++ b/docs/subsystems/memory.md @@ -0,0 +1,112 @@ +# Memory + +What the agents know from earlier conversations, kept once for all of +them: a preference the user states in Claude Code is known to Codex the +next day. It is read and written three ways: an MCP server every agent can +mount, a digest written into the instructions of the agents ticked under +Library → Instructions, and the Library's Memory tab. + +## Source of truth + +`memory.json` in magpie's config folder ([internal/memory/memory.go](../../internal/memory/memory.go)). + +- One writer at a time across magpies (`filelock`), written through a temp + file, the last good generation kept beside it (`lastgood`). +- A file that can't be read is unknown, never empty: nothing is written + over it, searches fail, and `Digest` returns an error so the instructions + keep what the agent has (`TestUnreadableFileIsNeverWrittenOver`, + `TestCutShortFileReadFromItsBackup`). + +A memory is one short text (`MaxText` runes) with: + +| Field | Values | Meaning | +| --- | --- | --- | +| `scope` | `global`, `project:`, `agent:` | where it holds. A project is the git repository, keyed by its remote (`ProjectOf`, `RemoteKey`), so every clone and worktree shares it. An agent id has no `@wsl:…` suffix. | +| `kind` | profile, preference, rule, reference, fact, procedure, episode | how long it stays true and where it goes in the digest. A field of its own, not a tag. | +| `tags` | free words (`CleanTags`) | the user's own grouping. | +| `origin` | user, agent, imported, inferred | who wrote it. An agent's save never changes text the user wrote (`TestUsersMemoryNotChangedByAnAgentsSave`). | +| `status` | active, candidate, archived, superseded | only active ones are searched by default and digested. Candidates wait under "To review". | +| `pinned` | bool | first in lists and digests. | + +`Save` keeps one memory per scope and text (`TestSaveKeepsOneOfTheSameText`) +and refuses empty or over-long text, an unknown kind and a bad scope +(`TestSaveRefusesWhatIsntAMemory`). +`Forget` archives; `Remove` deletes. + +## Runtime paths + +### MCP server + +[internal/gateway/memory_mcp.go](../../internal/gateway/memory_mcp.go): +`memory_search`, `memory_save`, `memory_forget`, Streamable HTTP at +`MemoryMCPPath` (`/mcp/magpie/memory`), served and guarded like the search +server (`serveMCP`): another computer reaches it only while magpie is +shared, with a gateway key, and has no folder here for a project +(`TestMemoryMCPGuarded`). + +- The Library offers it in the market as `magpie-memory` + ([market.go](../../internal/library/market.go)), run as + `magpie mcp memory` ([browsermcp.RunMemory](../../internal/browsermcp/browsermcp.go)), + which relays stdio to the gateway with the folder the agent started it in + (`X-Magpie-Cwd`) and the client name from `initialize` + (`X-Magpie-Mcp-Client`). +- Behind the [MCP router](mcp-router.md) the hub passes the caller in the + call's `_meta` instead (`HubRootsMeta`, `HubClientMeta`; + `TestMemoryMCPHubMetaNamesTheProject`). +- Without a folder the server can't name the project, nor the agent without + a client name: such a save says so instead of guessing, and a save with + no scope is kept for everyone (`TestMemoryMCPSaysWhatItCantKnow`). +- A save through MCP is active at once, origin `agent`. + +### Digest in the instructions + +[internal/memory/digest.go](../../internal/memory/digest.go) renders one +digest per scope within a budget (global 4000, project 1500, agent 1000, +the whole 8000 characters), pinned and longer-lived kinds first, no memory +cut in the middle. The text goes to every agent's vendor: it names neither +magpie nor any vendor. + +The digest changes only when published, so an agent's instructions — and +the prompt cache built on them — change mid-session only then +(`TestDigestChangesOnlyWhenPublished`): + +- a change the user makes in the GUI publishes at once + (`library.PublishMemory(false)` from [internal/gui/memory.go](../../internal/gui/memory.go)); +- `KeepLinked`'s loop publishes once a day for what agents saved meanwhile + (`PublishMemory(true)` → `memory.PublishDue`, which writes nothing while + memory has never held anything). + +`Library.memoryDigest` adds the agent's digest (global, its own, and each +project's under the folders it was seen in) to the instructions of the +agents ticked under Instructions, unless `Instructions.NoMemory` +(`TestMemoryDigestInInstructions`). The Memory tab's switch sets it. + +### GUI + +[internal/gui/memory.go](../../internal/gui/memory.go): + +| Route | Does | +| --- | --- | +| `GET /api/memory` | `{memories, projects, digest, agents}` | +| `POST /api/memory` | `{id?, …Input}`: `Edit` with an id, else `Save` as the user's | +| `POST /api/memory/remove` | `{ids}` | +| `POST /api/memory/digest` | `{on}` | + +A reply after a change carries `problem` when publishing the digest +failed. The tab is in [plugins/library/client.js](../../internal/gui/assets/plugins/library/client.js) +(`renderMemory`), tested by `internal/gui/tests/library-memory.test.cjs`. + +## Not built yet + +Distilling sessions into candidates, a nightly pass that archives stale +memories and merges duplicates, and semantic search are planned; today +search is by words (`Search`, CJK split per character, `TestSearch`). + +## Verification + +```sh +mote-run go test ./internal/memory ./internal/library +mote-run go test -tags nogui -run 'MemoryMCP|OwnMCP' ./internal/gateway +mote-run go test ./internal/browsermcp ./internal/cli +mote-run node --test internal/gui/tests/library-memory.test.cjs +``` diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 55dd1ab33..3cbfefbc6 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,22 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "Archived": "已归档", + "Everywhere": "所有地方", + "Preference": "偏好", + "Rule": "规则", + "Reference": "参考", + "Fact": "事实", + "Decision": "决定", + "from {agent}": "来自 {agent}", + "Pinned": "已置顶", + "Pin": "置顶", + "Keep": "保留", + "Kept": "已保留", + "Archive": "归档", + "Restored": "已恢复", + "Remember": "记住", + "Remembered": "已记住", "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "下限:首字后 {ms} 输出 {n} 个正文 token,{r} 个推理 token 不计。没有记录首个正文的时间,首字后的推理时间也算在里面", "At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "下限:从收到请求到最后一个 token,{ms} 输出 {n} 个 token,等首字的时间也算在里面", "Collapse all": "全部收起", @@ -4792,6 +4808,22 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。", }, "zh-TW": { + "Archived": "已封存", + "Everywhere": "所有地方", + "Preference": "偏好", + "Rule": "規則", + "Reference": "參考", + "Fact": "事實", + "Decision": "決定", + "from {agent}": "來自 {agent}", + "Pinned": "已置頂", + "Pin": "置頂", + "Keep": "保留", + "Kept": "已保留", + "Archive": "封存", + "Restored": "已還原", + "Remember": "記住", + "Remembered": "已記住", "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "下限:首字後 {ms} 輸出 {n} 個正文 token,{r} 個推理 token 不計。沒有記錄首個正文的時間,首字後的推理時間也算在裡面", "At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "下限:從收到請求到最後一個 token,{ms} 輸出 {n} 個 token,等首字的時間也算在裡面", "Collapse all": "全部收起", @@ -9565,6 +9597,22 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。", }, ja: { + "Archived": "アーカイブ済み", + "Everywhere": "どこでも", + "Preference": "好み", + "Rule": "ルール", + "Reference": "参考", + "Fact": "事実", + "Decision": "決定", + "from {agent}": "{agent} から", + "Pinned": "ピン留め", + "Pin": "ピン留め", + "Keep": "残す", + "Kept": "残しました", + "Archive": "アーカイブ", + "Restored": "元に戻しました", + "Remember": "覚える", + "Remembered": "覚えました", "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "下限:最初のトークン後 {ms} で回答 {n} トークン(推論 {r} トークンは含めず)。最初の本文の時刻が記録されていないため、最初のトークン後の推論の時間も含まれます", "At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "下限:リクエストを受けてから最後のトークンまで {ms} で {n} トークンを出力。最初のトークンを待つ時間も含まれます", "Collapse all": "すべて折りたたむ", @@ -14340,6 +14388,22 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。", }, de: { + "Archived": "Archiviert", + "Everywhere": "Überall", + "Preference": "Vorliebe", + "Rule": "Regel", + "Reference": "Verweis", + "Fact": "Fakt", + "Decision": "Entscheidung", + "from {agent}": "von {agent}", + "Pinned": "Angeheftet", + "Pin": "Anheften", + "Keep": "Behalten", + "Kept": "Behalten", + "Archive": "Archivieren", + "Restored": "Wiederhergestellt", + "Remember": "Merken", + "Remembered": "Gemerkt", "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "Mindestens: {n} Antwort-Token in {ms} nach dem ersten Token, ohne die {r} Reasoning-Token. Kein erster Text aufgezeichnet, also zählt Reasoning nach dem ersten Token mit", "At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "Mindestens: {n} Ausgabe-Token in {ms}, von der Anfrage bis zu ihrem letzten Token, das Warten auf das erste mitgezählt", "Collapse all": "Alle einklappen", diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index f6390de78..3aa8a5965 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -810,6 +810,8 @@ magpie.plugin("library", (ctx) => { box.append(card, head("60px"), rows(6, true)); } else if (which === "rtk") { box.append(rows(1, false), head("60px"), rows(5, true)); + } else if (which === "memory") { + box.append(rows(1, true), rows(6, false)); } else if (which === "pi") { box.append(head("60px"), rows(4, true)); } else { @@ -826,6 +828,8 @@ magpie.plugin("library", (ctx) => { if (id === "rtk" && rtk) loadRTK(); // Pi's extensions too: one installed or changed outside magpie since if (id === "pi" && piView) loadPi(); + // memory too: agents save to it while the page is open + if (id === "memory" && mem) loadMemory(); if (!lib) return page.querySelector(":scope > .lib-skel")?.replaceWith(skeleton(id)); render(); syncLists(); } @@ -837,6 +841,7 @@ magpie.plugin("library", (ctx) => { const n = (k) => (counts?.[k] ? " · " + counts[k] : ""); const tabs = segs(agentless() ? [["mcp", t("MCP servers") + n("mcp")]] : [ ["instructions", t("Instructions")], + ["memory", t("Memory")], ["mcp", t("MCP servers") + n("mcp")], ["skills", t("Skills") + n("skills")], ["hooks", t("Hooks") + n("hooks")], @@ -910,6 +915,7 @@ magpie.plugin("library", (ctx) => { if (tab === "instructions") renderInstructions(body); else if (tab === "mcp") renderServers(body); else if (tab === "rtk") renderRTK(body); + else if (tab === "memory") renderMemory(body); else if (tab === "pi") renderPi(body); else if (tab === "hooks") renderHooks(body); else if (tab === "subagents") renderSubagents(body); @@ -934,6 +940,227 @@ magpie.plugin("library", (ctx) => { function intro(text) { return el("p", "lib-intro", text); } + // ---------- memory ---------- + + // What the agents know about the user and their projects, shared by all + // of them (internal/memory): agents search it and save to it through the + // Magpie Memory server, and the ones ticked for instructions read its + // digest. A memory an agent only guessed waits under Suggested until the + // user keeps it. + let mem = null; // /api/memory + let memLoading = false; + let memQ = ""; // the search typed + let memStatus = "active"; + let memScope = ""; // "" every scope + let memOpen = null; // the memory open to edit, or "new" + let memDraft = null; // its fields as typed + let memRemoving = null; // the memory whose Delete was clicked once + const MEM_KINDS = ["profile", "preference", "rule", "reference", "fact", "procedure", "episode"]; + const kindName = (k) => ({ profile: t("About you"), preference: t("Preference"), rule: t("Rule"), reference: t("Reference"), fact: t("Fact"), procedure: t("How-to"), episode: t("Decision") })[k] || k; + function scopeName(s) { + if (!s || s === "global") return t("Everywhere"); + if (s.startsWith("project:")) { + const k = s.slice(8), p = mem?.projects?.[k]; + return p?.name || k; + } + if (s.startsWith("agent:")) return t("Only {agent}", { agent: nameOf(s.slice(6)) }); + return s; + } + async function loadMemory() { + if (memLoading) return; + memLoading = true; + try { + mem = await api("memory"); + } catch (e) { + status(e.message, "err"); + } + memLoading = false; + if (tab === "memory" && mem) render(); + } + function memDirty() { + if (!memOpen || !memDraft) return false; + const m = mem?.memories.find((x) => x.id === memOpen); + if (!m) return !!memDraft.text.trim(); + return memDraft.text !== m.text || memDraft.why !== (m.why || "") || memDraft.tags !== (m.tags || []).join(", ") || memDraft.kind !== m.kind || memDraft.scope !== m.scope; + } + let memBusy = false; + async function memChange(path, body, done) { + if (memBusy) return false; + memBusy = true; + page.setAttribute("aria-busy", "true"); + try { + const v = await api(path, body); + mem = v; + if (v.problem) status(v.problem, "err", 10000); + else if (done) status(done, "", 4000); + return true; + } catch (e) { + status(e.message, "err", 6000); + return false; + } finally { + memBusy = false; + page.removeAttribute("aria-busy"); + render(); + } + } + // a picker: the app's menu, never a ), kept and deleted. Every language, wide and narrow, Chromium +// and WebKit; no backend, the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/mem"; +const library = { + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [{ id: "claude", name: "Claude Code", icon: "", instructions: `${HOME}/.claude/CLAUDE.md` }, { id: "codex", name: "Codex", icon: "", instructions: `${HOME}/.codex/AGENTS.md` }], + instructions: { shared: "", sets: [{ id: "default", name: "", active: true, text: "" }], agents: [] }, + foundServers: [], projects: [], foundSkills: [], skills: [], servers: [], +}; +const at = (d) => `2026-11-0${d}T10:00:00Z`; +function memories() { + return { + memories: [ + { id: "m1", text: "Use pnpm, never npm, in this repo", kind: "rule", scope: "project:p1", origin: "user", status: "active", created: at(1), updated: at(5) }, + { id: "m2", text: "Answers in Chinese, code comments in English", kind: "preference", scope: "global", origin: "user", status: "active", pinned: true, created: at(1), updated: at(2) }, + { id: "m3", text: "Deploys go out on Fridays", kind: "fact", scope: "global", origin: "inferred", status: "candidate", sources: [{ agent: "codex", at: at(3) }], created: at(3), updated: at(3) }, + ], + projects: { p1: { key: "p1", name: "magpie", roots: [`${HOME}/magpie`] } }, + digest: true, + agents: ["claude"], + }; +} + +function server(lang, state, sent) { + return async (route) => { + const url = new URL(route.request().url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: library }); + if (url.pathname.startsWith("/api/library/")) { + sent.push({ path: url.pathname, body: route.request().postDataJSON() }); + return route.fulfill({ json: { ...library, result: { changed: [] } } }); + } + if (url.pathname.startsWith("/api/memory")) { + if (route.request().method() === "POST") { + const body = route.request().postDataJSON(); + sent.push({ path: url.pathname, body }); + if (url.pathname === "/api/memory/digest") state.digest = body.on; + else if (url.pathname === "/api/memory/remove") state.memories = state.memories.filter((m) => !body.ids.includes(m.id)); + else if (body.id) Object.assign(state.memories.find((m) => m.id === body.id), body, { id: body.id }); + else state.memories.push({ id: "m" + (state.memories.length + 1), kind: "preference", scope: "global", origin: "user", status: "active", created: at(6), updated: at(6), ...body }); + } + return route.fulfill({ json: state }); + } + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const view = "#view-library"; +const words = { + en: { tab: "Memory", review: "To review", rule: "Rule", fact: "Fact" }, + zh: { tab: "记忆", review: "待确认", rule: "规则", fact: "事实" }, + "zh-TW": { tab: "記憶", review: "待確認", rule: "規則", fact: "事實" }, + ja: { tab: "メモリ", review: "確認待ち", rule: "ルール", fact: "事実" }, + de: { tab: "Memory", review: "Zu prüfen", rule: "Regel", fact: "Fakt" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Library's Memory tab lists, searches, adds, edits, keeps and deletes memories", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of Object.keys(words)) for (const width of [980, 420]) { + await t.test(`${lang} ${width}`, async () => { + const w = words[lang]; + const ctx = await browser.newContext({ viewport: { width, height: 860 }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "memory"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + const sent = []; + const state = memories(); + await page.route("**/*", server(lang, state, sent)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const rows = page.locator(`${view} .lib-mems .lib-mem`); + await rows.first().waitFor(); + + // the tab is named, after Instructions + const tabs = await page.locator(`${view} .lib-tabs .opt`).allTextContents(); + assert.equal(tabs[1].trim(), w.tab); + assert.ok((await page.locator(`${view} .lib-tabs .opt.on`).textContent()).includes(w.tab)); + // the page is in the reader's language and fits the window + if (lang !== "en") assert.doesNotMatch(await page.locator(`${view} .lib-intro`).textContent(), /What your agents know/); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), "the page scrolls sideways"); + const body = await page.locator(`${view} .lib-body`).boundingBox(); + for (const b of await page.locator(`${view} .lib-membar > *`).all()) { + const r = await b.boundingBox(); + assert.ok(r.x + r.width <= body.x + body.width + 1, "a control of the bar is cut off"); + } + + // in use: the pinned one first, then the newer one; the one guessed waits + assert.equal(await rows.count(), 2); + assert.match(await rows.nth(0).textContent(), /Answers in Chinese/); + assert.match(await rows.nth(1).textContent(), /Use pnpm/); + assert.match(await rows.nth(1).textContent(), /magpie/); + assert.match(await rows.nth(1).textContent(), new RegExp(w.rule)); + // Magpie Memory isn't in the library: it is offered + assert.equal(await page.locator(`${view} .lib-memtools`).count(), 1); + + // the search narrows the list + await page.locator(`${view} input.lib-memq`).fill("pnpm"); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 1); + await page.locator(`${view} input.lib-memq`).fill(""); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 2); + + if (width === 980) { + // edited: the kind through the app's menu + await rows.nth(1).click(); + const ta = page.locator(`${view} textarea[data-lib="mem:m1"]`); + await ta.waitFor(); + assert.equal(await page.locator(`${view} select`).count(), 0, "a native select"); + await ta.fill("Use pnpm in this repo"); + await page.locator(`${view} .lib-memdetail .lib-mempick`).first().click(); + await page.locator(".proto-menu .pm-item", { hasText: w.fact }).click(); + await page.locator(`${view} .lib-memdetail .primary`).click(); + await page.waitForFunction(() => !document.querySelector("#view-library .lib-memdetail")); + let s = sent.findLast((x) => x.path === "/api/memory"); + assert.deepEqual({ id: s.body.id, text: s.body.text, kind: s.body.kind, scope: s.body.scope }, { id: "m1", text: "Use pnpm in this repo", kind: "fact", scope: "project:p1" }); + + // added: everywhere by default, the user's own + await page.locator(`${view} .lib-memadd`).click(); + const nt = page.locator(`${view} textarea[data-lib="mem:new"]`); + await nt.waitFor(); + await nt.fill("Never push to main"); + await page.locator(`${view} input.lib-memtags`).fill("git, 规则"); + await page.locator(`${view} .lib-memdetail .primary`).click(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 3); + s = sent.findLast((x) => x.path === "/api/memory"); + assert.equal(s.body.id, undefined); + assert.deepEqual([s.body.text, s.body.scope, s.body.tags], ["Never push to main", "global", ["git", "规则"]]); + + // the one guessed is kept + await page.locator(`${view} .lib-memstatus .opt`, { hasText: w.review }).click(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 1); + const guessed = page.locator(`${view} .lib-mems .lib-mem`).first(); + assert.match(await guessed.textContent(), /Codex/); + await guessed.click(); + await page.locator(`${view} .lib-memdetail .lib-acts button`).nth(1).click(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 0); + s = sent.findLast((x) => x.path === "/api/memory"); + assert.deepEqual(s.body, { id: "m3", status: "active" }); + + // deleted, on a second click + await page.locator(`${view} .lib-memstatus .opt`).first().click(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 4); + await page.locator(`${view} .lib-mems .lib-mem`, { hasText: "Never push" }).click(); + const del = page.locator(`${view} .lib-memdetail .danger`); + await del.click(); + assert.equal(sent.filter((x) => x.path === "/api/memory/remove").length, 0); + await page.locator(`${view} .lib-memdetail .danger-fill`).click(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 3); + assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/remove").body, { ids: ["m4"] }); + + // the summary switched off + await page.locator(`${view} .lib-memcard button.lib-switch`).click(); + await page.waitForFunction(() => document.querySelector("#view-library .lib-memcard button.lib-switch")?.getAttribute("aria-checked") === "false"); + assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/digest").body, { on: false }); + } + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +}