Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
masking: Clear records… deletes what masking kept, after a confirm (maxyou2090)
yetone630fd1d69144
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex d44e51123..28cf475e5 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -101,7 +101,7 @@ recorded as a prediction failure (`noPrediction`).- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (`options` in [`internal/masking`](../../internal/masking/masking.go)), so a change applies to the next request.- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`. Insights › Masking and Settings' *Try it* mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (`maskMatches` in `plugins/redact/page.js`; #3599, masking-records and mask-actions GUI tests).- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.- - Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent, session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (`noteMaskedUntil`, `maskrec.Hold`), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`).+ - Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent, session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (`noteMaskedUntil`, `maskrec.Hold`), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`). The page's Clear records… (after a confirm) posts `/api/masking/clear`, and `maskrec.Clear` removes every day's file whole under the store's lock, with the in-memory text around placeholders; a day it can't remove stays listed and is named in the error. What the masker holds for each placeholder stays, so a placeholder still in an agent's context is put back in its answers.- `DecidesModel` gives a 400.- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model.- A model the user disabled (#1867) gets a 403 for every caller (`idOff`), before anything is sent; see [Disabled models](#disabled-models).diff --git a/internal/gui/assets/plugins/redact/i18n.js b/internal/gui/assets/plugins/redact/i18n.jsindex b24a0fb19..07de53c79 100644--- a/internal/gui/assets/plugins/redact/i18n.js+++ b/internal/gui/assets/plugins/redact/i18n.js@@ -46,6 +46,10 @@ magpie.strings({"In the answer": "回复里","Not named": "没有出现","A value itself is in this computer's memory only: shown while it is pointed at or picked, and gone once magpie restarts. The record on disk keeps its kind, length and first characters.": "原值只存在这台电脑的内存里:指向或选中时才显示,magpie 重启后就没有了。磁盘上的记录只留下种类、长度和开头几个字。",+ "Clear records…": "清空记录…",+ "Clear masking records?": "清空脱敏记录?",+ "Every request's record of what was masked is deleted from this computer. Masking stays as it is, and requests from now on are recorded again.": "这台电脑上每条请求的脱敏记录都会删除。脱敏设置不变,之后的请求照常记录。",+ "Masking records cleared": "脱敏记录已清空",},"zh-TW": {"Turn on masking": "開啟脫敏",@@ -92,6 +96,10 @@ magpie.strings({"In the answer": "回覆裡","Not named": "沒有出現","A value itself is in this computer's memory only: shown while it is pointed at or picked, and gone once magpie restarts. The record on disk keeps its kind, length and first characters.": "原值只存在這台電腦的記憶體裡:指向或選取時才顯示,magpie 重新啟動後就沒有了。磁碟上的記錄只留下種類、長度和開頭幾個字。",+ "Clear records…": "清空記錄…",+ "Clear masking records?": "清空脫敏記錄?",+ "Every request's record of what was masked is deleted from this computer. Masking stays as it is, and requests from now on are recorded again.": "這台電腦上每條請求的脫敏記錄都會刪除。脫敏設定不變,之後的請求照常記錄。",+ "Masking records cleared": "脫敏記錄已清空",},ja: {"Turn on masking": "マスクをオンにする",@@ -138,6 +146,10 @@ magpie.strings({"In the answer": "返答で","Not named": "出てこなかった","A value itself is in this computer's memory only: shown while it is pointed at or picked, and gone once magpie restarts. The record on disk keeps its kind, length and first characters.": "値そのものはこのコンピュータのメモリにだけあります:ポイントするか選んだときだけ表示され、magpie を再起動すると消えます。ディスク上の記録に残るのは種類・長さ・先頭の数文字です。",+ "Clear records…": "記録を消去…",+ "Clear masking records?": "マスクの記録を消去しますか?",+ "Every request's record of what was masked is deleted from this computer. Masking stays as it is, and requests from now on are recorded again.": "このコンピュータにある各リクエストのマスク記録がすべて削除されます。マスクの設定はそのままで、これからのリクエストはまた記録されます。",+ "Masking records cleared": "マスクの記録を消去しました",},de: {"Turn on masking": "Maskierung einschalten",@@ -184,5 +196,9 @@ magpie.strings({"In the answer": "In der Antwort","Not named": "Nicht genannt","A value itself is in this computer's memory only: shown while it is pointed at or picked, and gone once magpie restarts. The record on disk keeps its kind, length and first characters.": "Ein Wert selbst liegt nur im Speicher dieses Computers: gezeigt, solange er angezeigt oder gewählt ist, und weg, sobald magpie neu startet. Der Eintrag auf der Festplatte behält Art, Länge und erste Zeichen.",+ "Clear records…": "Einträge löschen…",+ "Clear masking records?": "Maskierungseinträge löschen?",+ "Every request's record of what was masked is deleted from this computer. Masking stays as it is, and requests from now on are recorded again.": "Der Eintrag jeder Anfrage dazu, was maskiert wurde, wird von diesem Computer gelöscht. Die Maskierung bleibt, wie sie ist, und Anfragen ab jetzt werden wieder erfasst.",+ "Masking records cleared": "Maskierungseinträge gelöscht",},});diff --git a/internal/gui/assets/plugins/redact/page.js b/internal/gui/assets/plugins/redact/page.jsindex 1ad4a863e..1aeefeb21 100644--- a/internal/gui/assets/plugins/redact/page.js+++ b/internal/gui/assets/plugins/redact/page.js@@ -471,8 +471,39 @@ function drawMaskList() {more.onclick = () => maskFetch(true);foot.append(more);}+ // what was kept goes whole, after a confirm: maxyou2090's strict masking+ // had kept far more than he wanted to keep+ if (maskL.records.length || maskSum?.requests) {+ const clear = el("button", "text msk-clear", t("Clear records…"));+ clear.type = "button";+ clear.disabled = maskL.busy || maskClearing;+ clear.onclick = maskClear;+ foot.append(clear);+ }box.append(foot);}+let maskClearing = false;+async function maskClear() {+ const ok = await confirmAction(t("Clear masking records?"),+ t("Every request's record of what was masked is deleted from this computer. Masking stays as it is, and requests from now on are recorded again."),+ t("Clear"));+ if (!ok) return;+ maskClearing = true;+ drawMaskList();+ try {+ await api("masking/clear", {});+ status(t("Masking records cleared"), "ok", 1500);+ } catch (e) {+ // what could not be deleted is still listed below+ status(t(e.message), "err");+ }+ maskClearing = false;+ if (maskO) maskOneClose();+ maskSeq++;+ Object.assign(maskL, { records: [], more: false, busy: false, read: false, error: "" });+ maskDrawn = "";+ return maskPageLoad(true);+}function maskRequestList(box) {const filtered = maskL.facet || maskL.kind || maskL.agent || maskL.provider;diff --git a/internal/gui/masking.go b/internal/gui/masking.goindex dc30040e3..1d96ea4f1 100644--- a/internal/gui/masking.go+++ b/internal/gui/masking.go@@ -69,6 +69,8 @@ func shownRecord(r maskrec.Record, t gwmw.Teller) maskedRecord {// - POST /api/masking/values {ps} what each placeholder stood for, of// those the masker still remembers, for the page to show the request// as the agent sent it;+// - POST /api/masking/clear deletes every record kept (maskrec.Clear),+// at once rather than after 30 days (maxyou2090 on Discord);// - POST /api/masking/preview {text} the text as a vendor would get it// under the settings now, and what was found, each told by its kind// and hint, never its value; nothing of it is remembered (#1977).@@ -99,6 +101,13 @@ func maskingRoutes(mux *http.ServeMux) {}writeJSON(rw, map[string]any{"text": text, "hits": out, "off": off})})+ mux.HandleFunc("POST /api/masking/clear", func(rw http.ResponseWriter, r *http.Request) {+ if err := maskrec.Clear(); err != nil {+ fail(rw, err)+ return+ }+ writeJSON(rw, map[string]bool{"cleared": true})+ })mux.HandleFunc("GET /api/masking/summary", func(rw http.ResponseWriter, r *http.Request) {days, _ := strconv.Atoi(r.URL.Query().Get("days"))writeJSON(rw, maskrec.Sum(min(max(days, 1), 30)))diff --git a/internal/gui/masking_test.go b/internal/gui/masking_test.goindex c3a2ba09a..1b497c2a4 100644--- a/internal/gui/masking_test.go+++ b/internal/gui/masking_test.go@@ -105,6 +105,39 @@ func TestMaskingRecordsAPI(t *testing.T) {if err := json.Unmarshal(rw.Body.Bytes(), &vs); err != nil || len(vs.Values) != 1 || vs.Values[p] != key || rw.Header().Get("Cache-Control") != "no-store" {t.Fatalf("values %d %s %v", rw.Code, rw.Body, rw.Header())}++ // Clear takes every record and its text, by POST alone; what a+ // placeholder stood for stays with the masker for answers to come+ // (maxyou2090 on Discord)+ rw = httptest.NewRecorder()+ srv.ServeHTTP(rw, httptest.NewRequest("GET", "/api/masking/clear", nil))+ if rw.Code == http.StatusOK {+ t.Fatalf("GET clear: %d", rw.Code)+ }+ if get("/api/masking/records?limit=5", &page); len(page.Records) == 0 {+ t.Fatal("a GET cleared the records")+ }+ rw = httptest.NewRecorder()+ srv.ServeHTTP(rw, httptest.NewRequest("POST", "/api/masking/clear", nil))+ if rw.Code != http.StatusOK || !strings.Contains(rw.Body.String(), `"cleared":true`) {+ t.Fatalf("clear: %d %s", rw.Code, rw.Body)+ }+ page.Records, page.More = nil, false+ if get("/api/masking/records?limit=5", &page); len(page.Records) != 0 || page.More {+ t.Fatalf("records after clear %+v", page)+ }+ sum = maskrec.Summary{}+ if get("/api/masking/summary?days=30", &sum); sum.Requests != 0 {+ t.Fatalf("summary after clear %+v", sum)+ }+ for _, path := range []string{"/api/masking/record?key=" + strconv.FormatInt(rec.Key, 10), "/api/masking/sent?key=" + strconv.FormatInt(whole.Key, 10)} {+ if code := get(path, nil); code != http.StatusNotFound {+ t.Fatalf("%s after clear: %d", path, code)+ }+ }+ if get("/api/masking/value?p="+url.QueryEscape(p), &v); v.Value != key {+ t.Fatalf("value after clear %q", v.Value)+ }}// Try it under Settings › Privacy shows what a request would send: withdiff --git a/internal/gui/tests/masking-records.test.cjs b/internal/gui/tests/masking-records.test.cjsindex 50ec7d377..e35b55e01 100644--- a/internal/gui/tests/masking-records.test.cjs+++ b/internal/gui/tests/masking-records.test.cjs@@ -67,6 +67,7 @@ const records = [function serve(lang, sum, asked, opts = {}) {const settings = { theme: "light", lang, tray: "panel", currency: "usd", redact: !opts.off, redactPersonal: !opts.off, redactActions: { PRIVATE_KEY: "block" }, ...opts.settings };+ let cleared = false;return async (route) => {const req = route.request(), url = new URL(req.url());const json = (data) => route.fulfill({ json: data });@@ -89,11 +90,20 @@ function serve(lang, sum, asked, opts = {}) {if (url.pathname === "/api/groups") return json({ groups: [], models: [] });if (url.pathname === "/api/plugins") return json({ plugins: [] });if (url.pathname === "/api/privacy-model") return json({ supported: true, installed: false, size: 1.6e9 });- if (url.pathname === "/api/masking/summary") return json(sum(+url.searchParams.get("days")));+ if (url.pathname === "/api/masking/clear") {+ asked.push("clear " + req.method());+ if (opts.clearFails) return route.fulfill({ status: 500, body: "remove 2026-10-26.jsonl: permission denied" });+ cleared = true;+ return json({ cleared: true });+ }+ if (url.pathname === "/api/masking/summary") {+ const s = sum(+url.searchParams.get("days"));+ return json(cleared ? { ...s, days: s.days.map((d) => ({ ...d, requests: 0, n: 0, distinct: 0 })), requests: 0, n: 0, distinct: 0, blocked: 0, kinds: [], by: {}, agents: [], providers: [], values: [] } : s);+ }if (url.pathname === "/api/masking/records") {asked.push(url.search);const q = url.searchParams, kinds = q.get("kind")?.split(",");- const rs = (opts.none ? [] : opts.records || records).filter((r) => (!kinds || r.values.some((v) => kinds.includes(v.k))) && (!q.get("by") || r.values.some((v) => v.b === q.get("by")))+ const rs = (opts.none || cleared ? [] : opts.records || records).filter((r) => (!kinds || r.values.some((v) => kinds.includes(v.k))) && (!q.get("by") || r.values.some((v) => v.b === q.get("by")))&& (!q.get("agent") || r.agent === q.get("agent")) && (!q.get("provider") || r.provider === q.get("provider")) && (!q.get("blocked") || r.blocked));return json({ records: rs, more: false });}@@ -443,3 +453,58 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",});}}++// Clear records… deletes what masking kept, after a confirm (maxyou2090:+// strict masking had kept many records): Cancel sends nothing, Clear posts+// once and the page reads again to nothing; a failed clear says why and+// lists what is still there+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {+ for (const width of [1100, 640]) {+ test(`${engine} ${lang} ${width}px: Clear records asks first, then empties the page`, async (t) => {+ const { browser, page, errors, asked } = await open(engine, lang, width, summary);+ t.after(() => browser.close());+ const list = page.locator("#maskList"), clear = list.locator(".msk-foot .msk-clear");+ await list.locator(".msk-row").first().waitFor();+ await clear.waitFor();+ assert.deepEqual(await wide(page), { page: false, over: [] });+ await shot(page, `clear-${engine}-${lang}-${width}`);+ await stillClick(page, clear);+ const dialog = page.locator("dialog.action-confirm");+ await dialog.waitFor();+ await shot(page, `confirm-${engine}-${lang}-${width}`);+ if (lang !== "en") {+ const said = await dialog.innerText();+ for (const w of ["Clear masking records", "is deleted from this computer", "Cancel"]) assert(!said.includes(w), `${w} left in English: ${said}`);+ }+ await dialog.locator("button:not(.primary)").click();+ await dialog.waitFor({ state: "detached" });+ await page.waitForTimeout(100);+ assert(!asked.some((a) => a.startsWith("clear")), "Cancel sends nothing");+ assert(await list.locator(".msk-row").count() > 0, "Cancel keeps the list");+ await clear.click();+ await dialog.locator("button.primary").click();+ await list.locator(".msk-none").waitFor();+ assert.deepEqual(asked.filter((a) => a.startsWith("clear")), ["clear POST"]);+ assert.equal(await list.locator(".msk-row").count(), 0);+ await clear.waitFor({ state: "detached" });+ await untranslated(page, lang);+ assert.deepEqual(await wide(page), { page: false, over: [] });+ assert.deepEqual(errors, []);+ });+ }+ }+ test(`${engine}: a clear that fails says why and keeps the list`, async (t) => {+ const { browser, page, errors, asked } = await open(engine, "en", 1100, summary, "", { clearFails: true });+ t.after(() => browser.close());+ const list = page.locator("#maskList");+ await list.locator(".msk-row").first().waitFor();+ await list.locator(".msk-foot .msk-clear").click();+ await page.locator("dialog.action-confirm button.primary").click();+ await until(() => asked.includes("clear POST"));+ await page.locator("#status", { hasText: "permission denied" }).waitFor();+ await list.locator(".msk-row").first().waitFor();+ assert.equal(await list.locator(".msk-row").count(), 3, "every record still listed");+ assert.deepEqual(errors, []);+ });+}diff --git a/internal/maskrec/maskrec.go b/internal/maskrec/maskrec.goindex b12339389..45804a2ad 100644--- a/internal/maskrec/maskrec.go+++ b/internal/maskrec/maskrec.go@@ -18,6 +18,7 @@ import ("bytes""cmp""encoding/json"+ "errors""os""path/filepath""slices"@@ -214,6 +215,28 @@ func settle(r Record, provider, model string) {}}+// Clear deletes every record kept: each day's file, and what memory has+// of them (their snips, the requests' text). A day goes whole, never+// rewritten, so nothing is left half-cleared for a reader; a request still+// going is written to a new day's file once it is done. A day that can't+// be removed stays, and is named in the error. What a placeholder stood+// for is the masker's, in memory alone, and stays there for the answers+// still to come.+func Clear() error {+ store.mu.Lock()+ defer store.mu.Unlock()+ var errs []error+ for _, d := range files(Dir()) {+ if err := os.Remove(d.path); err != nil && !errors.Is(err, os.ErrNotExist) {+ errs = append(errs, err)+ continue+ }+ delete(store.days, d.path)+ }+ store.snips, store.sent, store.sentBytes = nil, nil, 0+ return errors.Join(errs...)+}+// merged is vs with one Value for each placeholder, its N the sum, in the// order they first came. A value found by a finder and later only known// (masked before) keeps the finder that found it.diff --git a/internal/maskrec/maskrec_test.go b/internal/maskrec/maskrec_test.goindex d3d6821db..af61f10f6 100644--- a/internal/maskrec/maskrec_test.go+++ b/internal/maskrec/maskrec_test.go@@ -3,6 +3,7 @@ package maskrecimport ("os""path/filepath"+ "runtime""strings""testing""time"@@ -192,3 +193,73 @@ func TestHoldNamesWhoHadIt(t *testing.T) {t.Fatalf("second page %+v", page)}}++// Clear deletes every day kept and what memory has of the records, at+// once rather than after 30 days (maxyou2090 on Discord: strict masking+// recorded a lot); a file beside the days that isn't one stays, and the+// next request is recorded again.+func TestClear(t *testing.T) {+ now := time.Date(2026, 10, 26, 15, 0, 0, 0, time.Local)+ dir := sandbox(t, now)+ for back := range 3 {+ at := now.AddDate(0, 0, -back)+ Add(Record{Time: at, What: "chat", Agent: "claude", N: 1, Sent: `{"k":"{{API_KEY_aaaabbbb}}"}`,+ Values: []Value{{Placeholder: "{{API_KEY_aaaabbbb}}", Kind: "API_KEY", By: "rule", Head: "sk-", Len: 40}},+ Snips: map[string]string{"{{API_KEY_aaaabbbb}}": "key {{API_KEY_aaaabbbb}}"}})+ }+ os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("mine"), 0o600)+ last, _ := List(0, 1, Filter{})+ if s := Sum(7); s.Requests != 3 || len(last) != 1 {+ t.Fatalf("before: %d requests, %d listed", s.Requests, len(last))+ }+ if err := Clear(); err != nil {+ t.Fatal(err)+ }+ es, _ := os.ReadDir(dir)+ if len(es) != 1 || es[0].Name() != "notes.txt" {+ t.Fatalf("left in %s: %v", dir, es)+ }+ if rs, more := List(0, 10, Filter{}); len(rs) != 0 || more {+ t.Fatalf("listed after clear: %+v", rs)+ }+ if s := Sum(30); s.Requests != 0 || s.N != 0 || len(s.Values) != 0 || s.Since != "" {+ t.Fatalf("summed after clear: %+v", s)+ }+ if _, ok := Get(last[0].Key); ok {+ t.Fatal("a cleared record is still got")+ }+ if _, ok := SentOf(last[0].Key); ok {+ t.Fatal("a cleared request's text is still in memory")+ }+ r := Add(Record{Time: now, What: "chat", N: 1, Values: []Value{{Placeholder: "{{EMAIL_cccc0000}}", Kind: "EMAIL", By: "rule"}}})+ if r.Key <= last[0].Key {+ t.Fatalf("a key after clear went back: %d <= %d", r.Key, last[0].Key)+ }+ if s := Sum(7); s.Requests != 1 {+ t.Fatalf("after clear and one more: %+v", s)+ }+}++// A day that can't be removed is named in the error and stays listed:+// the page doesn't say cleared while records are left.+func TestClearSaysWhatStays(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("a folder's write bit doesn't hold a file on Windows")+ }+ now := time.Date(2026, 10, 26, 15, 0, 0, 0, time.Local)+ dir := sandbox(t, now)+ Add(Record{Time: now, What: "chat", N: 1, Values: []Value{{Placeholder: "{{EMAIL_cccc0000}}", Kind: "EMAIL", By: "rule"}}})+ os.Chmod(dir, 0o500)+ t.Cleanup(func() { os.Chmod(dir, 0o700) })+ if probe := filepath.Join(dir, "probe"); os.WriteFile(probe, nil, 0o600) == nil {+ os.Remove(probe)+ t.Skip("running as a user a folder's mode doesn't hold back")+ }+ err := Clear()+ if err == nil || !strings.Contains(err.Error(), "2026-10-26.jsonl") {+ t.Fatalf("err %v", err)+ }+ if rs, _ := List(0, 10, Filter{}); len(rs) != 1 {+ t.Fatalf("the day left isn't listed: %+v", rs)+ }+}