Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Preserve continuation details through memory upkeep
Afloataad8c0c2928f
diff --git a/server/memory-entry-continuations.test.ts b/server/memory-entry-continuations.test.tsindex 0d81f25dcf..23fc18b01e 100644--- a/server/memory-entry-continuations.test.ts+++ b/server/memory-entry-continuations.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import { parseMemoryEntries, withoutExpired } from "./memory-entries.ts";import { applyMoves } from "./memory-organize.ts";+import { applyTidy, planTidy } from "./memory-tidy.ts";const expired = ["- 2026-10-01 · Temporary deployment · until 2026-10-31",@@ -33,6 +34,17 @@ describe("whole memory entry boundaries", () => {expect(withoutExpired(text, "2026-10-31")).toEqual({ text, hidden: 0 });});+ it("archives every expired continuation before removing the entry during tidy", () => {+ const text = ["# Memory", ...expired, live, " Keep this detail.", ""].join("\n");+ const tidied = applyTidy(text, planTidy(text, "2026-11-01"), "2026-11-01");+ const kept = ["# Memory", live, " Keep this detail.", ""].join("\n");+ expect(tidied.text).toBe(kept);+ expect(tidied.archived).toEqual([+ [`${expired[0]} · expired 2026-11-01`, ...expired.slice(1)].join("\n"),+ ]);+ expect(withoutExpired(tidied.text, "2026-11-01")).toEqual({ text: kept, hidden: 0 });+ });+it("moves the full source entry into its topic without orphaning details", () => {const entry = ["- 2026-10-01 · Deploy project Cedar:", ...expired.slice(1)];const text = ["# Memory", ...entry, live, " Keep this detail.", ""].join("\n");diff --git a/server/memory-tidy.ts b/server/memory-tidy.tsindex 6dd87e9687..0d91540abc 100644--- a/server/memory-tidy.ts+++ b/server/memory-tidy.ts@@ -77,12 +77,15 @@ export function planChanges(plan: TidyPlan): number {export function applyTidy(text: string, plan: TidyPlan, today: string): { text: string; archived: string[] } {const lines = text.split("\n");- const drop = new Set<number>([...plan.expired, ...plan.duplicates].map((e) => e.line));+ const drop = new Set<number>(plan.duplicates.map((e) => e.line));+ for (const entry of plan.expired) {+ for (let index = entry.line; index < entry.end; index += 1) drop.add(index);+ }for (const { loser, remainder } of plan.superseded) {const struck = `${loser.prefix}~~${loser.body}~~ · superseded ${today}`;lines[loser.line] = remainder ? `${struck}\n- ${today} · from tidy-up · ${remainder}` : struck;}- const archived = plan.expired.map((e) => `${e.raw} · expired ${today}`);+ const archived = plan.expired.map((e) => [`${e.raw} · expired ${today}`, ...lines.slice(e.line + 1, e.end)].join("\n"));return { text: lines.filter((_, index) => !drop.has(index)).join("\n"), archived };}diff --git a/server/memory-upkeep.test.ts b/server/memory-upkeep.test.tsindex 88c0f6f61e..12ef1892fc 100644--- a/server/memory-upkeep.test.ts+++ b/server/memory-upkeep.test.ts@@ -512,6 +512,79 @@ describe("the upkeep loop", () => {expect(memory()).toContain("Release 0.1.40 shipped to every computer");});+ it.each(["MEMORY.md", "memory/travel.md"])("archives expired continuations from %s without leaving live fragments", async (path) => {+ ensureWorkspace(BOT.id);+ const expired = [+ "- 2026-09-01 · Temporary deployment · until 2026-09-07",+ " ```sh",+ " deploy --temporary",+ "",+ " ```",+ " Remove the temporary deployment.",+ ];+ const live = "- 2026-09-20 · Current deployment\n Keep this detail.\n";+ const before = `${expired.join("\n")}\n${live}`;+ if (path === "MEMORY.md") writeMemoryFile(BOT.id, before);+ else writeMemoryTopic(BOT.id, "travel.md", before);+ const report = await upkeep().tidy(BOT.id);+ await flushMemoryJournal(BOT.id);+ expect(report.expired).toBe(1);+ expect(readFileSync(join(workspaceDir(BOT.id), path), "utf8")).toBe(live);+ expect(readMemoryTopic(BOT.id, "archive.md"))+ .toContain([`${expired[0]} · expired ${TODAY}`, ...expired.slice(1)].join("\n"));+ const row = readMemoryJournal(BOT.id, 10).find((entry) => entry.path === path && entry.via === "tidy")!;+ expect(row.canRevert).toBe(true);+ const reverted = revertMemoryChange(BOT.id, row.id);+ await flushMemoryJournal(BOT.id);+ expect(reverted.ok).toBe(true);+ expect(readFileSync(join(workspaceDir(BOT.id), path), "utf8")).toBe(before);+ });++ it("keeps a source entry when its topic only shares the heading, while completing other moves", async () => {+ ensureWorkspace(BOT.id);+ const kept = "- 2026-09-25 · Deployment steps\n deploy --new-environment\n";+ const moved = "- 2026-09-25 · Release notes\n Version two is ready.\n";+ writeMemoryFile(BOT.id, `${kept}${moved}- 2026-09-25 · Short note\n`);+ writeMemoryTopic(BOT.id, "project.md", "- 2026-09-20 · Deployment steps\n deploy --old-environment\n- Short note\n");+ organizeAnswer = '{"moves":[{"i":0,"topic":"project"},{"i":1,"topic":"project"},{"i":2,"topic":"project"}]}';+ const report = await upkeep().tidy(BOT.id);+ await flushMemoryJournal(BOT.id);+ expect(report.organized).toBe(2);+ expect(memory()).toBe(kept);+ const topic = readMemoryTopic(BOT.id, "project.md")!;+ expect(topic).toContain("deploy --old-environment");+ expect(topic).not.toContain("deploy --new-environment");+ expect(topic).toContain(moved);+ expect(topic.match(/Short note/g)).toHaveLength(1);+ });++ it("completes a move without duplicating a topic that already holds the full entry", async () => {+ ensureWorkspace(BOT.id);+ const details = " ```sh\n deploy --current\n\n ```\n Keep the release tag.\n";+ writeMemoryFile(BOT.id, `- 2026-09-25 · Deployment steps\n${details}`);+ const topic = `- 2026-09-20 · Deployment steps\n${details}`;+ writeMemoryTopic(BOT.id, "project.md", topic);+ organizeAnswer = '{"moves":[{"i":0,"topic":"project"}]}';+ const report = await upkeep().tidy(BOT.id);+ await flushMemoryJournal(BOT.id);+ expect(report.organized).toBe(1);+ expect(memory()).toBe("");+ expect(readMemoryTopic(BOT.id, "project.md")).toBe(topic);+ });++ it.each(["2026-09-07", "2026-09-26"])("keeps a permanent entry when its topic copy expires on %s", async (until) => {+ ensureWorkspace(BOT.id);+ const details = " deploy --current\n";+ const source = `- 2026-09-25 · Deployment steps\n${details}`;+ writeMemoryFile(BOT.id, source);+ writeMemoryTopic(BOT.id, "project.md", `- 2026-09-01 · Deployment steps · until ${until}\n${details}`);+ organizeAnswer = '{"moves":[{"i":0,"topic":"project"}]}';+ const report = await upkeep().tidy(BOT.id);+ await flushMemoryJournal(BOT.id);+ expect(report.organized ?? 0).toBe(0);+ expect(memory()).toBe(source);+ });+it("moves detail the bot wrote itself out of MEMORY.md into topics, keeping core facts", async () => {ensureWorkspace(BOT.id);writeMemoryFile(BOT.id, [diff --git a/server/memory-upkeep.ts b/server/memory-upkeep.tsindex 11d099f1d2..e513bd5f22 100644--- a/server/memory-upkeep.ts+++ b/server/memory-upkeep.ts@@ -6,7 +6,7 @@ import { DATA_DIR } from "./config.ts";import { CaptureBuffer, captureItemLimit, capturePrompt, captureSize, newCandidates, parseCandidates, statedInConversation, worthCapturing, type Candidate, type CaptureBatch, type CaptureTurn } from "./memory-capture.ts";import { DREAM_FIRST_LOOKBACK_MS, DREAM_MIN_CONVERSATIONS, dreamPrompt, parseDream, type DreamConversation } from "./memory-dream.ts";import { checkDreamFacts } from "./memory-fact-checks.ts";-import { factIdentity, lineFactIdentity, notebookIdentities } from "./memory-entries.ts";+import { factIdentity, isExpired, lineFactIdentity, notebookIdentities, parseMemoryEntries } from "./memory-entries.ts";import { mergeTopicText } from "./memory-topics.ts";import { isForgotten } from "./profile-learned.ts";import { applyMoves, MAX_MOVES, organizeCandidates, organizePrompt, parseMoves } from "./memory-organize.ts";@@ -573,18 +573,21 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {if (!moves.length) return 0;return writing(botId, () => {const { byTopic } = applyMoves(before, moves);- const written = new Set<string>();+ const sourceLines = before.split("\n");+ const written = new Set<number>();const existing = new Map(listMemoryTopics(botId).map((topic) => [topic.name.toLowerCase(), topic.name]));- let count = 0;for (const [wanted, group] of byTopic) {const name = existing.get(wanted) ?? wanted;const path = `memory/${name}`;const current = readRaw(botId, path);const seen = notebookIdentities(current ?? "");const lines = group.lines.filter((line) => !seen.has(lineFactIdentity(line)));+ const after = lines.length+ ? mergeTopicText(current, { title: name.replace(/\.md$/, "").replace(/-/g, " "), aliases: group.aliases, lines })+ : current ?? "";if (lines.length) {try {- writeMemoryTopic(botId, name, mergeTopicText(current, { title: name.replace(/\.md$/, "").replace(/-/g, " "), aliases: group.aliases, lines }));+ writeMemoryTopic(botId, name, after);} catch (error) {log(`memory upkeep: could not write ${path}; kept its entries in MEMORY.md: ${(error as Error).message}`);continue;@@ -592,13 +595,24 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {recordMemoryChange(botId, { path, actor: "upkeep", via: "organize", before: current, after: readRaw(botId, path) });}existing.set(name.toLowerCase(), name);- written.add(wanted);- count += group.lines.length;+ const savedLines = after.split("\n");+ const savedEntries = parseMemoryEntries(after).filter((entry) => !entry.struck && !isExpired(entry, today));+ for (const { topic, entry } of moves) {+ if (topic !== wanted) continue;+ const details = sourceLines.slice(entry.line + 1, entry.end).join("\n");+ if (entry.end === entry.line + 1 || savedEntries.some((saved) =>+ factIdentity(saved.body) === factIdentity(entry.body)+ && saved.until === entry.until+ && savedLines.slice(saved.line + 1, saved.end).join("\n") === details)) {+ written.add(entry.line);+ }+ }}if (!written.size) return 0;- const { text } = applyMoves(before, moves.filter((move) => written.has(move.topic)));+ const { text } = applyMoves(before, moves.filter((move) => written.has(move.entry.line)));writeMemoryFile(botId, text);recordMemoryChange(botId, { path: "MEMORY.md", actor: "upkeep", via: "organize", before, after: readRaw(botId, "MEMORY.md") });+ const count = written.size;log(`memory upkeep: moved ${count} entr${count === 1 ? "y" : "ies"} from MEMORY.md into topic files for ${deps.bot(botId)?.name ?? botId}`);return count;});