Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix: tidy memory after trying it on real bots
leepokai5c14a75f1c94
diff --git a/apps/desktop/src/renderer/views/bots/MemoryView.tsx b/apps/desktop/src/renderer/views/bots/MemoryView.tsxindex 505bb5fe..c3019e34 100644--- a/apps/desktop/src/renderer/views/bots/MemoryView.tsx+++ b/apps/desktop/src/renderer/views/bots/MemoryView.tsx@@ -46,33 +46,33 @@ export function MemoryCard({ botId }: { botId: string }) {{view && bot && section === 'yours' && <Switch on={bot.sharedMemory} disabled={memory.busy} onChange={(on) => host.setSharedMemory(bot, on)}>Use what your bots share</Switch>}- {layer && <>- <p className="memory-muted">{section === 'yours'+ {layer && [+ <p key="note" className="memory-muted">{section === 'yours'? 'Your name, time zone, people and lasting preferences, shared by your bots.'- : 'What this bot learned about you.'} {layer.used} of {layer.cap} in use.</p>- {!layer.entries.length && <div className="memory-empty">+ : 'What this bot learned about you.'} {layer.used} of {layer.cap} in use.</p>,+ ...(layer.entries.length ? [] : [<div key="empty" className="memory-empty"><Icon name="brain" size={20} color="var(--tertiary)" /><span>{section === 'yours' ? 'Nothing shared yet.' : 'Nothing yet. What this bot learns about you shows up here, and you can change any of it.'}</span>- </div>}- {layer.entries.map((entry) => <EntryRow key={entry.id} entry={entry} memory={memory} edit={() => setDraft({ id: entry.id, text: entry.text })} />)}- </>}- {view && section === 'dreams' && <>- <p className="memory-muted">Between chats the bot tidies its memory from your own words. Each run can be undone.</p>- {!view.dreams.length && <div className="memory-empty"><Icon name="moon" size={20} color="var(--tertiary)" /><span>No dreams yet.</span></div>}- {view.dreams.map((dream) => <div className="memory-item fade-in" key={dream.id}>+ </div>]),+ ...layer.entries.map((entry) => <EntryRow key={entry.id} entry={entry} memory={memory} edit={() => setDraft({ id: entry.id, text: entry.text })} />),+ ]}+ {view && section === 'dreams' && [+ <p key="note" className="memory-muted">Between chats the bot tidies its memory from your own words. Each run can be undone.</p>,+ ...(view.dreams.length ? [] : [<div key="empty" className="memory-empty"><Icon name="moon" size={20} color="var(--tertiary)" /><span>No dreams yet.</span></div>]),+ ...view.dreams.map((dream) => <div className="memory-item fade-in" key={dream.id}><div className="memory-content"><strong>{relativeTime.day(dream.at)}{dream.undone ? ' · undone' : ''}</strong>{dream.added.map((c) => <span key={`a${c.id}`}>+ {c.text}</span>)}{dream.archived.map((c) => <span key={`r${c.id}`} className="memory-archived">− {c.text}</span>)}</div>{!dream.undone && <IconButton title="Undo this dream" icon="arrow.uturn.backward" disabled={memory.busy} onClick={() => void memory.mutate('undoDream', { id: dream.id })} />}- </div>)}- </>}- {view?.projectMemory && section === 'project' && <>+ </div>),+ ]}+ {view?.projectMemory && section === 'project' && <div className="memory-content"><p className="memory-muted">The project folder's own notes, kept by Claude Code. Read-only here.</p><small className="memory-muted">{view.projectMemory.path}</small><pre className="memory-history">{view.projectMemory.text}</pre>- </>}+ </div>}</CardSection><Sheet open={draft !== null} onClose={() => setDraft(null)} width={520}><ModalHeader title={draft?.id ? 'Edit memory' : section === 'yours' ? 'Add to what your bots share' : 'Add memory'} />@@ -96,7 +96,7 @@ function EntryRow({ entry, memory, edit }: { entry: MemoryEntry; memory: MemorySconst archived = entry.state === 'archived'return <div className="memory-item fade-in"><button className="press memory-content" onClick={edit}>- <span className={archived ? 'memory-archived' : undefined}>{entry.pinned && <Icon name="pin.fill" size={10} color="var(--secondary)" />} {entry.text}</span>+ <strong className={archived ? 'memory-archived' : undefined}>{entry.pinned && <Icon name="pin.fill" size={10} color="var(--secondary)" />}{entry.text}</strong><small>{authorLabel(entry, (id) => host.authorName(id))} · {relativeTime.day(entry.updatedAt)}{archived ? ' · archived' : ''}</small></button><DropdownMenu className="icon-button memory-menu" title="Memory actions" items={() => [diff --git a/apps/desktop/src/renderer/views/bots/memory.css b/apps/desktop/src/renderer/views/bots/memory.cssindex ce0aa586..5a342ffc 100644--- a/apps/desktop/src/renderer/views/bots/memory.css+++ b/apps/desktop/src/renderer/views/bots/memory.css@@ -4,7 +4,7 @@.memory-item { display: flex; align-items: flex-start; gap: 8px; }.memory-item .memory-menu { margin: -4px -6px 0 0; }.memory-content { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; text-align: left; }-.memory-content strong { display: flex; align-items: center; gap: 6px; }+.memory-content strong { display: flex; align-items: center; gap: 6px; font-weight: 500; overflow-wrap: anywhere; }.memory-content span { white-space: pre-wrap; overflow-wrap: anywhere; }.memory-content small, .memory-muted { color: var(--secondary); }.memory-archived { color: var(--tertiary); }diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex 127d6630..b4c15d15 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -69,8 +69,9 @@ the `codync-mem` crate; `chat/memory` runs them in the host.bot's `memoryRev` moves. Methods: `memory`, `saveMemory`, `pinMemory`, `archiveMemory`, `forgetMemory`,`clearMemory`, `undoDream`, `answerMemory`, `undoMemory`.- **Moving the old memory**: on the first start of this version, each bot's Engram database (or the Markdown- memory before it) moves in once. Facts about the user come in active as far as the cap allows, the rest- archived; then the old files and the Engram download go. Dreaming starts from that point in the chat.+ memory before it) moves in once. What the old opening showed comes in active as far as the cap allows (the+ profile and pinned facts first, then the newest), the rest archived; then the old files (deleted bots' too) and+ the Engram download go. Dreaming starts from that point in the chat.## Turnsdiff --git a/host/src/chat/memory/dream.rs b/host/src/chat/memory/dream.rsindex cf9b86bf..b404ec92 100644--- a/host/src/chat/memory/dream.rs+++ b/host/src/chat/memory/dream.rs@@ -130,13 +130,24 @@ fn review_due(store: &Store, bot: &str) -> bool {}store.memory_read(|c| codync_mem::store::layer(c, Some(bot))).is_ok_and(|entries| {entries.iter().any(|e| {- e.state == codync_mem::store::State::Active- && e.author != codync_mem::store::Author::User- && e.text.chars().any(|c| c.is_ascii_digit())+ e.state == codync_mem::store::State::Active && e.author != codync_mem::store::Author::User && dated(&e.text)})})}+/// Whether a memory names a date the time review may have to turn into the past: a year, a month or day in+/// Chinese, or an English month next to a number. Other numbers (prices, counts) don't count.+fn dated(text: &str) -> bool {+ const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];+ let chars: Vec<char> = text.chars().collect();+ let year =+ chars.windows(4).any(|w| matches!(w[..2], ['1', '9'] | ['2', '0']) && w[2..].iter().all(char::is_ascii_digit));+ let cjk = chars.windows(2).any(|w| w[0].is_ascii_digit() && "年月日號号".contains(w[1]));+ let lower = text.to_lowercase();+ let english = MONTHS.iter().any(|m| lower.contains(m)) && chars.iter().any(char::is_ascii_digit);+ year || cjk || english+}+fn today() -> String {chrono::Local::now().format("%Y-%m-%d").to_string()}@@ -228,3 +239,17 @@ fn message(e: &Entry) -> Option<Message> {let text: Vec<String> = text.into_iter().filter(|run| !run.trim().is_empty()).collect();(!text.is_empty()).then(|| Message { id: e.id.clone(), from_user, text, date: super::dates::ymd(e.created_at) })}++#[cfg(test)]+mod tests {+ use super::dated;++ #[test]+ fn only_dates_trigger_the_time_review() {+ assert!(dated("Going to Singapore in July 2026"));+ assert!(dated("下個月 3號 要搬家"));+ assert!(dated("Dentist on Oct 21"));+ assert!(!dated("Prompt is too long: Provided 10,389 tokens"));+ assert!(!dated("Has 2 cats"));+ }+}diff --git a/host/src/chat/memory/import.rs b/host/src/chat/memory/import.rsindex e02330a0..495611fe 100644--- a/host/src/chat/memory/import.rs+++ b/host/src/chat/memory/import.rs@@ -1,8 +1,9 @@//! A one-time move of the memory Codync kept before (an Engram database per bot, and the Markdown files before//! that) into the host's memory tables. Each bot moves once; then the old files go.//!-//! Facts the old keeper filed about the user come in active, as far as the bot's cap allows; the rest are-//! archived, still searchable. Dreaming changes moved entries only on the user's own contrary words.+//! What the old opening showed comes in active, as far as the bot's cap allows: the profile and pinned facts+//! first, then the newest. The rest is archived, still searchable. Dreaming changes moved entries only on the+//! user's own contrary words.use crate::hub::Hub;use crate::store::Store;@@ -33,15 +34,20 @@ pub fn import_old_memory(hub: &Hub) {return;}};+ let mut kept = std::collections::HashSet::new();for row in rows.iter().filter(|r| !r.deleted && !r.config.is_group()) {let id = &row.config.id;- let dir = data.join("bots").join(id);- if let Err(error) = import_bot(&hub.store, id, &dir) {+ if let Err(error) = import_bot(&hub.store, id, &data.join("bots").join(id)) {tracing::warn!(bot = %id, error = format!("{error:#}"), "couldn't move the bot's old memory");- continue;+ kept.insert(id.clone());}- for old in ["engram", "memory"] {- remove(&dir.join(old));+ }+ // Every bot folder, deleted bots' too, loses what the old memory left there.+ for dir in std::fs::read_dir(data.join("bots")).into_iter().flatten().flatten() {+ if !kept.contains(&*dir.file_name().to_string_lossy()) {+ for old in ["engram", "memory"] {+ remove(&dir.path().join(old));+ }}}if hub.store.kv_get("memory.moved").is_none() {@@ -86,7 +92,7 @@ fn import_bot(store: &Store, bot: &str, dir: &Path) -> Result<()> {mem::pin(c, entry.id, true, fact.at, rev)?;}let size = codync_mem::tokens::estimate(&entry.text);- if fact.profile && used + size <= codync_mem::tokens::BOT_CAP {+ if used + size <= codync_mem::tokens::BOT_CAP {used += size;} else {mem::archive(c, Writer::Import, entry.id, None, fact.at, rev)?;diff --git a/host/src/chat/memory/notices.rs b/host/src/chat/memory/notices.rsindex fcbaa768..7efaead3 100644--- a/host/src/chat/memory/notices.rs+++ b/host/src/chat/memory/notices.rs@@ -106,6 +106,15 @@ pub fn answer(hub: &Hub, notice_id: &str, accept: bool) -> Result<Value> {card.previous = previous.or(card.previous);super::changed(hub, entry.bot.as_deref(), Change::User);}+ // Dreaming may have learned it meanwhile: it's remembered either way.+ Err(error)+ if matches!(+ error.downcast_ref::<Error>(),+ Some(Error::Refused(codync_mem::check::Refusal::Duplicate))+ ) =>+ {+ card.status = Status::Accepted;+ }Err(error) => {card.status = Status::Failed;card.error = Some(format!("{error:#}"));diff --git a/host/src/chat/memory/tools.rs b/host/src/chat/memory/tools.rsindex 8febfc79..03a21a4f 100644--- a/host/src/chat/memory/tools.rs+++ b/host/src/chat/memory/tools.rs@@ -111,7 +111,7 @@ async fn write(hub: &Arc<Hub>, cfg: &BotConfig, action: Action) -> Result<Value>Ok(json!({"status": "saved", "id": entry.id}))} else {notices::propose(&hub, &cfg, turn.lane, turn.message, &action)?;- Ok(json!({"status": "waitingForUser", "note": "The user approves or declines this in the chat. Don't say it's saved."}))+ Ok(json!({"status": "waitingForUser", "note": "Not saved yet: the user approves or declines it in the chat. Don't tell them it's remembered."}))}}).await?diff --git a/host/src/tui/sheets/memory_view.rs b/host/src/tui/sheets/memory_view.rsindex eac0ffd6..6901c63a 100644--- a/host/src/tui/sheets/memory_view.rs+++ b/host/src/tui/sheets/memory_view.rs@@ -60,7 +60,7 @@ fn tabs(buf: &mut Buffer, inner: Rect, memory: &MemorySheet) {} else {palette.secondary.patch(palette.panel)};- x += put(buf, x, inner.y, inner.right().saturating_sub(x), &format!(" {label} "), style) + 1;+ x = put(buf, x, inner.y, inner.right().saturating_sub(x), &format!(" {label} "), style) + 1;}if memory.busy {put(buf, x, inner.y, inner.right().saturating_sub(x), "Loading…", palette.dim.patch(palette.panel));diff --git a/host/tests/memory_e2e.rs b/host/tests/memory_e2e.rsindex 737f4c58..5a1c00ab 100644--- a/host/tests/memory_e2e.rs+++ b/host/tests/memory_e2e.rs@@ -134,13 +134,11 @@ async fn moves_old_memory_once_and_keeps_the_layers_apart() {.await;let view = host.memory(&a).await;- assert_eq!(texts(&view["bot"], "active"), ["Lives in Taipei", "偏好繁體中文"]);- assert_eq!(texts(&view["bot"], "archived"), ["Shipped Codync"], "log entries stay searchable");+ assert_eq!(texts(&view["bot"], "active"), ["Shipped Codync", "Lives in Taipei", "偏好繁體中文"]);assert_eq!(view["bot"]["entries"][0]["author"], "imported");assert!(!legacy.exists(), "the old files go once moved");let view = host.memory(&b).await;- assert_eq!(texts(&view["bot"], "active"), ["Has a daughter named Mei"]);- assert_eq!(texts(&view["bot"], "archived"), ["Uses vim keybindings"]);+ assert_eq!(texts(&view["bot"], "active"), ["Has a daughter named Mei", "Uses vim keybindings"]);assert_eq!(view["bot"]["entries"][0]["pinned"], true);assert!(!engram.exists());host.restart(|_| {}).await;@@ -158,7 +156,7 @@ async fn moves_old_memory_once_and_keeps_the_layers_apart() {host.call("pinMemory", json!({"botId": b, "id": own, "pinned": true})).await;host.call("archiveMemory", json!({"botId": b, "id": own, "archived": true})).await;- assert_eq!(texts(&host.memory(&b).await["bot"], "archived").len(), 2);+ assert_eq!(texts(&host.memory(&b).await["bot"], "archived"), ["Reviews PRs on Fridays"]);host.call("archiveMemory", json!({"botId": b, "id": own, "archived": false})).await;assert_eq!(texts(&host.memory(&b).await["bot"], "active")[0], "Reviews PRs on Fridays", "pinned first");host.call("forgetMemory", json!({"botId": b, "id": own})).await;