Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(memory): upkeep stops writing after stop(); dreaming counts the My Cloud owner's lines (#3714)
zicochaos82c41f8a15ae
diff --git a/server/index.ts b/server/index.tsindex 7ec06dbcc0..192f75ac7b 100644--- a/server/index.ts+++ b/server/index.ts@@ -5284,7 +5284,7 @@ const memoryUpkeep = createMemoryUpkeep({return captureTurnFor(threadId, turnId);},...(lendingMemory ? { writing: <T>(botId: string, write: () => T): T => lendingMemory.trustedWrite(botId, write) } : {}),- conversations: (botId, since) => CLOUD_TEAM ? [] : dreamConversations(store, teamHost.baseBotId(botId), since, (threadId) => !routines?.runForThread(threadId) && (!CLOUD_PERSONAL || cloudOwnerOnlyThread(threadId))),+ conversations: (botId, since) => CLOUD_TEAM ? [] : dreamConversations(store, teamHost.baseBotId(botId), since, (threadId) => !routines?.runForThread(threadId) && (!CLOUD_PERSONAL || cloudOwnerOnlyThread(threadId)), CLOUD_PERSONAL ? (sender) => cloudProvenOwnerPerson(sender?.id) : undefined),quietMs: () => captureQuietMs(cfg), tidyHour: () => tidyHour(cfg), dreamer: () => proactive.dreamer(),log: (line) => console.log(line),});diff --git a/server/memory-dream.test.ts b/server/memory-dream.test.tsindex eab6702fd5..dabfe60541 100644--- a/server/memory-dream.test.ts+++ b/server/memory-dream.test.ts@@ -3,6 +3,8 @@ import { join } from "node:path";import { beforeEach, describe, expect, it } from "vitest";import { DATA_DIR } from "./config.ts";+import { ownerOnlyConversation } from "./cloud-lending.ts";+import { stampOwner } from "./cloud-owner-lines.ts";import {DREAM_CONVERSATION_BYTES, DREAM_MARKER, DREAM_TOTAL_BYTES, MAX_IDEAS, MAX_LEARNED,dreamConversations, dreamPrompt, parseDream, type DreamConversation, type DreamSource,@@ -10,6 +12,7 @@ import {import { parseMemoryEntries } from "./memory-entries.ts";import { flushMemoryJournal, readMemoryJournal } from "./memory-journal.ts";import { closeMessageDb } from "./message-db.ts";+import type { Message } from "./store.ts";import { createMemoryUpkeep, NO_DREAM_ENGINE, type UpkeepBot, type UpkeepEngine } from "./memory-upkeep.ts";import { ensureWorkspace, readMemoryTopic, workspaceDir, writeMemoryFile, WORKSPACES_DIR } from "./workspace.ts";@@ -64,6 +67,103 @@ describe("the chats a dream reads", () => {it("skips a chat with nothing the person said", () => {expect(dreamConversations(source({ a: { askedAt: 10, path: [replied("Hello!")] } }), "bot", 0)).toEqual([]);});++ it("keeps both owner-only conversations after their move to My Cloud stamps the owner", () => {+ const owner = { person: "p_owner", name: "Amit" };+ const threads: Record<string, { askedAt: number; path: Message[] }> = {+ a: { askedAt: 200, path: [{ id: "a1", at: 200, role: "user", kind: "text", text: "Shorter please" }] },+ b: { askedAt: 300, path: [{ id: "b1", at: 300, role: "user", kind: "text", text: "Too long again" }] },+ };+ const expected = [+ { threadId: "b", lines: [{ by: "person", text: "Too long again" }] },+ { threadId: "a", lines: [{ by: "person", text: "Shorter please" }] },+ ];+ expect(dreamConversations(source(threads), "bot", 100)).toEqual(expected);+ for (const thread of Object.values(threads)) thread.path = stampOwner(thread.path, owner);+ const ownerPerson = (person: string | undefined) => person === owner.person;+ const after = dreamConversations(source(threads), "bot", 100,+ (id) => ownerOnlyConversation(threads[id]!.path, ownerPerson, () => undefined),+ (sender) => ownerPerson(sender?.id));+ expect(after).toEqual(expected);+ });++ it.each(["relay", "API"] as const)("omits replies to a filtered %s request in an owner-only Cloud conversation", (origin) => {+ const owner = { name: "Amit", id: "p_owner" };+ const path: Message[] = [+ { id: "owner", at: 100, role: "user", kind: "text", text: "Shorter please", sender: owner },+ { id: "owner-reply", at: 110, role: "bot", kind: "text", text: "A shorter draft.", requestMessageId: "owner" },+ { id: "external", at: 120, role: "user", kind: "text", text: "Prepare a long report", sender: owner,+ ...(origin === "relay" ? { relayed: true } : { via: "api" }) },+ { id: "external-reply", at: 130, role: "bot", kind: "text", text: "A long external report.", requestMessageId: "external" },+ { id: "next", at: 140, role: "user", kind: "text", text: "Keep it plain too", sender: owner },+ { id: "next-reply", at: 150, role: "bot", kind: "text", text: "A plain draft.", requestMessageId: "next" },+ { id: "continuation", at: 160, role: "bot", kind: "text", text: "More of the external report.", requestMessageId: "external" },+ ];+ const ownerPerson = (person: string | undefined) => person === owner.id;+ const allowed = () => ownerOnlyConversation(path, ownerPerson, () => undefined);+ expect(allowed()).toBe(true);+ expect(dreamConversations(source({ a: { askedAt: 140, path } }), "bot", 0, allowed,+ (sender) => ownerPerson(sender?.id))).toEqual([{+ threadId: "a", lines: [+ { by: "person", text: "Shorter please" },+ { by: "bot", text: "A shorter draft." },+ { by: "person", text: "Keep it plain too" },+ { by: "bot", text: "A plain draft." },+ ],+ }]);+ });++ it.each<[string, Partial<Message>]>([+ ["guest", { sender: { name: "Guest", id: "p_guest" } }],+ ["peer", { peerAsk: { botId: "peer", name: "Teammate" } }],+ ["aside", { aside: true }],+ ["webhook", { webhookPost: true }],+ ])("omits replies associated with an excluded %s request", (_kind, extra) => {+ const path: Message[] = [+ { id: "owner", at: 100, role: "user", kind: "text", text: "Shorter please" },+ { id: "excluded", at: 110, role: "user", kind: "text", text: "Prepare a long report", ...extra },+ { id: "excluded-reply", at: 120, role: "bot", kind: "text", text: "A long report.", requestMessageId: "excluded" },+ { id: "owner-reply", at: 130, role: "bot", kind: "text", text: "A shorter draft.", requestMessageId: "owner" },+ ];+ expect(dreamConversations(source({ a: { askedAt: 100, path } }), "bot", 0)).toEqual([{+ threadId: "a", lines: [{ by: "person", text: "Shorter please" }, { by: "bot", text: "A shorter draft." }],+ }]);+ });++ it("omits automation reports from an owner conversation", () => {+ const owner = { name: "Amit", id: "p_owner" };+ const path: Message[] = [+ { id: "owner", at: 100, role: "user", kind: "text", text: "Shorter please", sender: owner },+ { id: "report", at: 110, role: "bot", kind: "text", text: "The routine prepared a long report.",+ automation: { routineId: "r1", runId: "run1", name: "Daily report", executionThreadId: "execution", trigger: "schedule", scheduledFor: 110 } },+ { id: "reply", at: 120, role: "bot", kind: "text", text: "A shorter draft.", requestMessageId: "owner" },+ ];+ expect(dreamConversations(source({ a: { askedAt: 100, path } }), "bot", 0, () => true,+ (sender) => sender?.id === owner.id)).toEqual([{+ threadId: "a", lines: [{ by: "person", text: "Shorter please" }, { by: "bot", text: "A shorter draft." }],+ }]);+ });++ it("requires the owner's identity and still excludes peers, asides and automation", () => {+ const owner = { name: "Amit", id: "p_owner" };+ const read = dreamConversations(source({+ a: { askedAt: 200, path: [+ said("Shorter please", { sender: owner }),+ said("A guest", { sender: { name: "Amit", id: "p_guest" } }),+ said("An unidentified guest", { sender: { name: "Amit" } }),+ said("Unproven words"),+ said("A peer", { sender: owner, peerAsk: { botId: "peer" } }),+ said("An aside", { sender: owner, aside: true }),+ said("A webhook", { sender: owner, webhookPost: true }),+ said("Relayed words", { sender: owner, relayed: true }),+ said("An API request", { sender: owner, via: "api" }),+ replied("Done."),+ ] },+ run: { askedAt: 300, routineRunId: "routine", path: [said("A routine", { sender: owner })] },+ guest: { askedAt: 400, path: [said("Guest only", { sender: { name: "Guest", id: "p_guest" } }), replied("Hello")] },+ }), "bot", 100, () => true, (sender) => sender?.id === owner.id);+ expect(read).toEqual([{ threadId: "a", lines: [{ by: "person", text: "Shorter please" }, { by: "bot", text: "Done." }] }]);+ });});describe("the dream prompt and its answer", () => {diff --git a/server/memory-dream.ts b/server/memory-dream.tsindex 0ae978b1ae..98baf364a5 100644--- a/server/memory-dream.ts+++ b/server/memory-dream.ts@@ -1,6 +1,7 @@// The DREAM step: one call that reads a bot's recent chats together, so it can notice what only shows across them// (after the Dreams of Claude Managed Agents, which does the same over hosted sessions). Capture reads one chat at a// time and tidy reads only the notebook; a dream keeps nothing a single chat could have told it.+import type { ResolvedSender } from "../shared/wire.ts";import { jsonPayload, topicFileName } from "./memory-capture.ts";import type { MemoryEntryLine } from "./memory-entries.ts";@@ -34,13 +35,18 @@ export interface DreamConversation {export interface DreamSource {tasks(botId: string): readonly { threadId: string; title?: string; askedAt?: number; routineRunId?: string }[];activePath(threadId: string): readonly {+ id?: string;role: string;kind: string;+ requestMessageId?: string;+ automation?: unknown;text?: string;- sender?: unknown;+ sender?: ResolvedSender;peerAsk?: unknown;aside?: boolean;webhookPost?: boolean;+ relayed?: boolean;+ via?: string;}[];}@@ -52,7 +58,8 @@ const clean = (text: string, max: number) => text.replace(/<attached-image\b[^>]* The chats the person wrote in since `since`, newest first, each cut to its latest lines that fit. Only the owner's* own lines count as the person's; a teammate's ask, an aside, a webhook post or another sender is left out.*/-export function dreamConversations(source: DreamSource, botId: string, since: number, allow: (threadId: string) => boolean = () => true): DreamConversation[] {+export function dreamConversations(source: DreamSource, botId: string, since: number, allow: (threadId: string) => boolean = () => true,+ isOwner: (sender: ResolvedSender | undefined) => boolean = (sender) => !sender): DreamConversation[] {const threads = source.tasks(botId).filter((task) => !task.routineRunId && (task.askedAt ?? 0) > since && allow(task.threadId)).sort((a, b) => (b.askedAt ?? 0) - (a.askedAt ?? 0))@@ -62,11 +69,18 @@ export function dreamConversations(source: DreamSource, botId: string, since: nufor (const task of threads) {const lines: DreamLine[] = [];let size = 0;- const path = source.activePath(task.threadId);+ const excludedRequests = new Set<string>();+ const path = source.activePath(task.threadId).filter((message) => {+ if (message.automation || (message.role === "user" && (!isOwner(message.sender) || message.peerAsk || message.aside || message.webhookPost || message.relayed || message.via === "api"))) {+ if (message.id) excludedRequests.add(message.id);+ return false;+ }+ return true;+ });for (let i = path.length - 1; i >= 0; i--) {const message = path[i]!;if (message.kind !== "text" || !message.text?.trim()) continue;- if (message.role === "user" && (message.sender || message.peerAsk || message.aside || message.webhookPost)) continue;+ if (message.role === "bot" && message.requestMessageId && excludedRequests.has(message.requestMessageId)) continue;if (message.role !== "user" && message.role !== "bot") continue;const line: DreamLine = message.role === "user"? { by: "person", text: clean(message.text, LINE_CHARS) }diff --git a/server/memory-upkeep-lifecycle.test.ts b/server/memory-upkeep-lifecycle.test.tsnew file mode 100644index 0000000000..07712b1bc5--- /dev/null+++ b/server/memory-upkeep-lifecycle.test.ts@@ -0,0 +1,195 @@+import { existsSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { DATA_DIR } from "./config.ts";+import { DREAM_MARKER } from "./memory-dream.ts";+import { ORGANIZE_MARKER } from "./memory-organize.ts";+import { TIDY_MARKER } from "./memory-tidy.ts";+import { createMemoryUpkeep, TIDY_CHECK_MS, type MemoryUpkeep } from "./memory-upkeep.ts";+import { createMoveFreeze } from "./move-freeze.ts";+import { ensureWorkspace, readMemoryTopic, workspaceDir, writeMemoryFile, writeMemoryTopic } from "./workspace.ts";++const BOT = { id: "upkeep-lifecycle", name: "Scout" };+const NOTEBOOK = "- 2026-09-01 · Trip · until 2026-09-02\n";+const memory = () => readFileSync(join(workspaceDir(BOT.id), "MEMORY.md"), "utf8");++describe("scheduled memory upkeep", () => {+ let loop: MemoryUpkeep;++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 8, 25, 10));+ rmSync(DATA_DIR, { recursive: true, force: true });+ ensureWorkspace(BOT.id);+ writeMemoryFile(BOT.id, NOTEBOOK);+ loop = createMemoryUpkeep({+ bots: () => [BOT], bot: () => BOT, engine: () => null, busy: () => false,+ addToAboutMe: () => 0, sourceLabel: () => "chat", quietMs: () => 60_000, tidyHour: () => 3,+ });+ });++ afterEach(async () => {+ loop.stop();+ await loop.idle();+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it("keeps a moved desktop's memory unchanged when frozen before the first tick", async () => {+ const freeze = createMoveFreeze({ dataDir: DATA_DIR });+ freeze.hold(() => loop.start(), () => loop.stop());+ freeze.freeze("https://fixture.example");+ await vi.advanceTimersByTimeAsync(TIDY_CHECK_MS);+ expect(memory()).toBe(NOTEBOOK);+ expect(readMemoryTopic(BOT.id, "archive.md")).toBeNull();+ expect(loop.status(BOT.id).lastTidy).toBeUndefined();+ freeze.unfreeze();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(memory()).not.toContain("Trip");+ expect(loop.status(BOT.id).lastTidy?.expired).toBe(1);+ });++ it("waits a full startup delay again after restarting", async () => {+ loop.start();+ await vi.advanceTimersByTimeAsync(30_000);+ loop.stop();+ loop.start();+ await vi.advanceTimersByTimeAsync(30_000);+ expect(memory()).toBe(NOTEBOOK);+ await vi.advanceTimersByTimeAsync(30_000);+ expect(memory()).not.toContain("Trip");+ });++ it.each(["startup", "interval"] as const)("ignores an already queued %s callback from a stopped generation", async (kind) => {+ const timeout = vi.spyOn(globalThis, "setTimeout");+ const interval = vi.spyOn(globalThis, "setInterval");+ loop.start();+ const callback = (kind === "startup" ? timeout.mock.calls[0]![0] : interval.mock.calls[0]![0]) as () => void;+ loop.stop();+ loop.start();+ callback();+ await loop.idle();+ expect(memory()).toBe(NOTEBOOK);+ expect(loop.status(BOT.id).lastTidy).toBeUndefined();+ });++ it("starts a fresh dream after restart while the old response is pending and keeps it single-flight", async () => {+ let releaseOld!: (answer: string) => void;+ let releaseNew!: (answer: string) => void;+ const oldResponse = new Promise<string>((resolve) => { releaseOld = resolve; });+ const newResponse = new Promise<string>((resolve) => { releaseNew = resolve; });+ const generateText = vi.fn().mockReturnValueOnce(oldResponse).mockReturnValue(newResponse);+ loop = createMemoryUpkeep({+ bots: () => [BOT], bot: () => BOT, engine: () => ({ generateText }), busy: () => false,+ addToAboutMe: () => 0, sourceLabel: () => "chat", quietMs: () => 60_000, tidyHour: () => 3,+ dreamer: () => BOT.id,+ conversations: () => ["a", "b"].map((threadId) => ({ threadId, lines: [{ by: "person", text: "Keep project updates brief." }] })),+ });+ try {+ loop.start();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(generateText).toHaveBeenCalledTimes(1);+ expect(generateText.mock.calls[0]![0]).toContain(DREAM_MARKER);+ loop.stop();+ loop.start();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(generateText).toHaveBeenCalledTimes(2);+ expect(generateText.mock.calls[1]![0]).toContain(DREAM_MARKER);+ const current = loop.dream(BOT.id);+ releaseOld('{"learned":[{"text":"Prefers detailed project updates","from":[1,2],"confidence":0.9}]}');+ await vi.advanceTimersByTimeAsync(0);+ expect(loop.status(BOT.id).lastDream).toBeUndefined();+ expect(memory()).not.toContain("Prefers detailed project updates");+ expect(loop.dream(BOT.id)).toBe(current);+ expect(generateText).toHaveBeenCalledTimes(2);+ releaseNew('{"learned":[{"text":"Prefers brief project updates","from":[1,2],"confidence":0.9}]}');+ await current;+ await loop.idle();+ expect(loop.status(BOT.id).lastDream).toMatchObject({+ at: new Date(2026, 8, 25, 10, 2).getTime(),+ learned: [{ text: "Prefers brief project updates", where: "MEMORY.md" }],+ });+ expect(memory()).toContain("Prefers brief project updates");+ expect(memory()).not.toContain("Prefers detailed project updates");+ } finally {+ releaseOld("{}");+ releaseNew("{}");+ }+ });++ describe.each(["freeze", "restart"] as const)("%s during a scheduled model call", (action) => {+ it.each(["organize", "notebook", "topic", "dream"] as const)("discards the active %s continuation and the rest of its tick", async (step) => {+ const other = { id: "next-bot", name: "Pixel" };+ ensureWorkspace(other.id);+ writeMemoryFile(other.id, NOTEBOOK);+ const core = ["Is vegetarian", "Is allergic to peanuts", "Has asthma", "Uses a wheelchair", "Takes medication"]+ .map((text) => `- 2026-09-03 · ${text}\n`).join("");+ writeMemoryFile(BOT.id, step === "organize" ? NOTEBOOK + "- 2026-09-03 · Acme launches Friday\n" : step === "notebook" ? NOTEBOOK + core : NOTEBOOK);+ if (step === "topic") writeMemoryTopic(BOT.id, "project.md", NOTEBOOK + core);+ const marker = step === "organize" ? ORGANIZE_MARKER : step === "dream" ? DREAM_MARKER : TIDY_MARKER;+ let release!: (answer: string) => void;+ const held = new Promise<string>((resolve) => { release = resolve; });+ const generateText = vi.fn((prompt: string) => prompt.startsWith(marker) ? held : Promise.resolve("{}"));+ loop = createMemoryUpkeep({+ bots: () => [BOT, other], bot: (id) => id === BOT.id ? BOT : other,+ engine: () => ({ generateText }), busy: () => false,+ addToAboutMe: () => 0, sourceLabel: () => "chat", quietMs: () => 60_000, tidyHour: () => 3,+ dreamer: () => BOT.id,+ conversations: () => ["a", "b"].map((threadId) => ({ threadId, lines: [{ by: "person", text: "Keep project updates brief." }] })),+ });+ const freeze = createMoveFreeze({ dataDir: DATA_DIR });+ freeze.hold(() => loop.start(), () => loop.stop());+ await vi.advanceTimersByTimeAsync(60_000);+ expect(generateText).toHaveBeenCalledTimes(1);+ expect(generateText.mock.calls[0]![0]).toContain(marker);+ const stateFile = join(DATA_DIR, "memory-upkeep.json");+ const snapshot = () => ({+ notebook: memory(), topic: readMemoryTopic(BOT.id, "project.md"), archive: readMemoryTopic(BOT.id, "archive.md"),+ state: existsSync(stateFile) ? readFileSync(stateFile, "utf8") : null,+ });+ const before = snapshot();+ if (action === "freeze") freeze.freeze("https://fixture.example");+ else { loop.stop(); loop.start(); }+ release(step === "organize" ? '{"moves":[{"i":0,"topic":"project"}]}' : step === "dream"+ ? '{"learned":[{"text":"Prefers brief project updates","from":[1,2],"confidence":0.9}]}' : '{"pairs":[]}');+ await vi.advanceTimersByTimeAsync(0);+ await loop.idle();+ expect(snapshot()).toEqual(before);+ expect(readFileSync(join(workspaceDir(other.id), "MEMORY.md"), "utf8")).toBe(NOTEBOOK);+ expect(generateText).toHaveBeenCalledTimes(1);+ if (action === "freeze") freeze.unfreeze();+ await vi.advanceTimersByTimeAsync(60_000);+ await loop.idle();+ expect(loop.status(BOT.id).lastTidy).toBeDefined();+ expect(readFileSync(join(workspaceDir(other.id), "MEMORY.md"), "utf8")).not.toContain("Trip");+ });+ });++ it.each(["capture", "organize"] as const)("discards an active capture stopped during its %s call", async (step) => {+ let release!: (answer: string) => void;+ const held = new Promise<string>((resolve) => { release = resolve; });+ const addToAboutMe = vi.fn(() => 0);+ const generateText = vi.fn((prompt: string) => step === "capture" || prompt.startsWith(ORGANIZE_MARKER)+ ? held : Promise.resolve('[{"text":"Acme launches Friday","kind":"fact","evidence":"Acme launches Friday"}]'));+ loop = createMemoryUpkeep({+ bots: () => [BOT], bot: () => BOT, engine: () => ({ generateText }), busy: () => false,+ addToAboutMe, sourceLabel: () => "chat", quietMs: () => 60_000, tidyHour: () => 3,+ });+ loop.start();+ const capture = loop.capture({ botId: BOT.id, threadId: "chat", turns: [{ person: "Acme launches Friday. I prefer brief updates.", bot: "Noted" }] });+ await vi.advanceTimersByTimeAsync(0);+ expect(generateText).toHaveBeenCalledTimes(step === "capture" ? 1 : 2);+ const before = memory();+ loop.stop();+ loop.start();+ release(step === "capture" ? '[{"text":"Prefers brief updates","kind":"preference","aboutUser":true,"evidence":"I prefer brief updates"}]'+ : '{"moves":[{"i":0,"topic":"project"}]}');+ await capture;+ await loop.idle();+ expect(memory()).toBe(before);+ expect(readMemoryTopic(BOT.id, "project.md")).toBeNull();+ expect(loop.status(BOT.id).lastCapture).toBeUndefined();+ expect(addToAboutMe).not.toHaveBeenCalled();+ });+});diff --git a/server/memory-upkeep.ts b/server/memory-upkeep.tsindex a0c40b46be..d3df8e498c 100644--- a/server/memory-upkeep.ts+++ b/server/memory-upkeep.ts@@ -272,9 +272,12 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {const log = (line: string) => deps.log?.(line);const inflight = new Set<Promise<unknown>>();const tidying = new Map<string, Promise<TidyReport>>();- const dreaming = new Map<string, Promise<DreamReport>>();+ const dreaming = new Map<string, { generation: number; promise: Promise<DreamReport> }>();let timer: ReturnType<typeof setInterval> | null = null;+ let first: ReturnType<typeof setTimeout> | null = null;+ let generation = 0;let paused = false;+ const cancelled = (started: number) => started !== generation || paused;// Flushed chats wait here, also through a backup; one worker drains it, one capture call at a time.const queue: Waiting[] = [];let worker: Promise<void> | null = null;@@ -364,6 +367,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {/** One model call for one bot's waiting chats, each read as its own conversation. */async function captureCall(batches: readonly CaptureBatch[]): Promise<CaptureReport> {+ const started = generation;// The batch names where the facts go (a bot's own memory, or one of its layers on a Team Cloud); the bot record says whose.const id = batches[0]!.botId;const bot = deps.bot(id);@@ -395,6 +399,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {today,topics: memoryTopicIndex(id),}));+ if (started !== generation) return { ...off, note: "upkeep stopped" };if (answer === null) {const report = { at, added: 0, topics: 0, aboutMe: 0, note: "The capture call did not answer in time." };record(id, { lastCapture: report });@@ -429,6 +434,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {const aboutMe = learned.length ? deps.addToAboutMe({ botId: id, botName: bot.name }, learned) : 0;const organized = await organize(id);const report: CaptureReport = { at, added, topics, aboutMe, organized };+ if (cancelled(started)) return report;record(id, { lastCapture: report });if (added || topics || aboutMe) log(`memory upkeep: noticed ${added} fact(s) for MEMORY.md, ${topics} for topic files and ${aboutMe} for About me — ${bot.name} (${id}) from ${conversations.map((conversation) => conversation.threadId).join(", ")}`);return report;@@ -453,10 +459,11 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {}async function work(): Promise<void> {+ const started = generation;try {// chats flushed together are all queued before the first call takes its shareawait Promise.resolve();- while (!paused && queue.length) {+ while (!cancelled(started) && queue.length) {const call = takeCall();try {const report = await captureCall(call.map((entry) => entry.batch));@@ -468,6 +475,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {}} finally {worker = null;+ kick();}}@@ -499,6 +507,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {});async function organize(botId: string): Promise<number> {+ const started = generation;const engine = deps.engine(botId);if (!engine?.generateText) return 0;const today = memoryDate(now());@@ -508,7 +517,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {const candidates = organizeCandidates(first, today, core);if (!candidates.length) return 0;const answer = await askModel(engine, organizePrompt(candidates, memoryTopicIndex(botId)));- if (answer === null || paused || !upkeepEnabled(deps.bot(botId))) return 0;+ if (answer === null || cancelled(started) || !upkeepEnabled(deps.bot(botId))) return 0;const before = readRaw(botId, "MEMORY.md") ?? "";if (before !== first) return 0;const proposed = parseMoves(answer, candidates);@@ -560,14 +569,15 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {}async function runTidy(botId: string): Promise<TidyReport> {+ const started = generation;const bot = deps.bot(botId);const at = now().getTime();const today = memoryDate(now());const stopped: TidyReport = { at, expired: 0, duplicates: 0, superseded: 0, deferred: 0, contradictionsChecked: false, note: "Memory upkeep is off or paused; no further changes were made." };- if (paused || !upkeepEnabled(bot)) return stopped;+ if (cancelled(started) || !upkeepEnabled(bot)) return stopped;ensureWorkspace(botId);const organized = await organize(botId);- if (paused || !upkeepEnabled(deps.bot(botId))) return stopped;+ if (cancelled(started) || !upkeepEnabled(deps.bot(botId))) return stopped;const first = readRaw(botId, "MEMORY.md") ?? "";const engine = deps.engine(botId);const candidates = contradictionCandidates(first, today);@@ -584,7 +594,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {contradictionsChecked = true;}}- if (paused || !upkeepEnabled(deps.bot(botId))) return stopped;+ if (cancelled(started) || !upkeepEnabled(deps.bot(botId))) return stopped;// Re-read after the await: if the notes changed, the model's line numbers are stale.const before = readRaw(botId, "MEMORY.md") ?? "";if (before !== first && contradictions.length) {@@ -624,7 +634,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {topicChecks++;topicCursor = topic.name;const answer = await askModel(engine, contradictionPrompt(topicCandidates), remaining);- if (paused || !upkeepEnabled(deps.bot(botId))) return stopped;+ if (cancelled(started) || !upkeepEnabled(deps.bot(botId))) return stopped;if (readRaw(botId, path) !== topicBefore) {topicsDeferred++;continue;@@ -681,10 +691,11 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {}async function runDream(botId: string): Promise<DreamReport> {+ const started = generation;const bot = deps.bot(botId);const at = now().getTime();const report = (note: string, conversations = 0): DreamReport => ({ at, conversations, learned: [], outdated: [], ideas: [], aboutMe: 0, note });- if (paused || !upkeepEnabled(bot)) return report("Memory upkeep is off or paused, so nothing was read.");+ if (cancelled(started) || !upkeepEnabled(bot)) return report("Memory upkeep is off or paused, so nothing was read.");if (!deps.conversations) return report("Dreaming is not available here.");const engine = deps.engine(botId);if (!engine?.generateText) {@@ -703,12 +714,12 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {const first = readRaw(botId, "MEMORY.md") ?? "";const notebook = contradictionCandidates(first, today);const answer = await askModel(engine, dreamPrompt({ botName: bot.name, today, conversations, notebook, topics: memoryTopicIndex(botId) }), DREAM_TIMEOUT_MS);+ if (cancelled(started) || !upkeepEnabled(deps.bot(botId))) return report("Memory upkeep was stopped, switched off or paused during the dream; no changes were made.", conversations.length);if (answer === null) {const late = report("The dream did not answer in time.", conversations.length);record(botId, { lastDream: late });return late;}- if (paused || !upkeepEnabled(deps.bot(botId))) return report("Memory upkeep was switched off or paused during the dream; no changes were made.", conversations.length);const dreamt = parseDream(answer, conversations.length, notebook.length);const source = `dream across ${conversations.length} chats`;// Re-read inside the write: if the notes changed after the prompt, its line numbers are stale.@@ -750,10 +761,13 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {}function dream(botId: string): Promise<DreamReport> {+ const started = generation;const running = dreaming.get(botId);- if (running) return running;- const promise = track(runDream(botId)).finally(() => dreaming.delete(botId));- dreaming.set(botId, promise);+ if (running?.generation === started) return running.promise;+ const promise = track(runDream(botId)).finally(() => {+ if (dreaming.get(botId)?.promise === promise) dreaming.delete(botId);+ });+ dreaming.set(botId, { generation: started, promise });return promise;}@@ -773,9 +787,10 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {}async function tick(): Promise<void> {- if (paused) return;+ const started = generation;+ if (cancelled(started)) return;for (const bot of deps.bots()) {- if (paused) return;+ if (cancelled(started)) return;if (!upkeepEnabled(bot) || deps.busy(bot.id)) continue;if (due(bot.id)) {try {@@ -784,7 +799,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {log(`memory upkeep: tidy failed for ${bot.id}: ${(error as Error).message}`);}}- if (paused) return;+ if (cancelled(started)) return;try {if (deps.busy(bot.id) || !dreamDue(bot.id)) continue;await dream(bot.id);@@ -841,14 +856,19 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {log(`memory upkeep: could not queue turns saved at the last shutdown: ${(error as Error).message}`);}}- timer = setInterval(() => void tick(), TIDY_CHECK_MS);+ const started = ++generation;+ const scheduledTick = () => { if (started === generation) void tick(); };+ timer = setInterval(scheduledTick, TIDY_CHECK_MS);timer.unref?.();- const first = setTimeout(() => void tick(), 60_000);+ first = setTimeout(scheduledTick, 60_000);first.unref?.();},stop() {+ generation++;if (timer) clearInterval(timer);timer = null;+ if (first) clearTimeout(first);+ first = null;const queued = queue.splice(0);for (const entry of queued) entry.done?.resolve({ at: now().getTime(), added: 0, topics: 0, aboutMe: 0, note: "kept for the next start" });const waiting = [...queued.map((entry) => entry.batch), ...buffer.drain()];