Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Check dream facts against quoted owner statements
Sebastian Bd898becec4cf
diff --git a/docs/memory.md b/docs/memory.mdindex 359db6ae6f..607c140560 100644--- a/docs/memory.md+++ b/docs/memory.md@@ -462,3 +462,15 @@ Every panel edit, delete or acceptance carries the revision it was based on.Stale writes return 409; writes without a revision return 428. Reloading after aconflict retains the unsaved draft for comparison. Pending replacement cardsalso refuse approval if the accepted fact changed since the proposal.++### Checks before a dream saves a fact++A dream must quote the person's statements in each cited conversation.+The host checks numbers, dates, months, paths, URLs, names and family+relationships against those quotes. Unsupported entries are skipped.+An outdated note stays unchanged when its replacement fails the check.+Entries that look like secrets are rejected with the existing secret detector.+Relative dates in English or Polish become dates from the quoted message,+not from the night the dream runs. Missing or ambiguous dates refuse the entry.+These checks also apply before a dream adds a fact to About me.+They do not merge notes into summaries.diff --git a/server/memory-dream.test.ts b/server/memory-dream.test.tsindex dabfe60541..43d650c7e8 100644--- a/server/memory-dream.test.ts+++ b/server/memory-dream.test.ts@@ -75,8 +75,8 @@ describe("the chats a dream reads", () => {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" }] },+ { threadId: "b", lines: [{ by: "person", text: "Too long again", at: 300 }] },+ { threadId: "a", lines: [{ by: "person", text: "Shorter please", at: 200 }] },];expect(dreamConversations(source(threads), "bot", 100)).toEqual(expected);for (const thread of Object.values(threads)) thread.path = stampOwner(thread.path, owner);@@ -105,10 +105,10 @@ describe("the chats a dream reads", () => {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." },+ { by: "person", text: "Shorter please", at: 100 },+ { by: "bot", text: "A shorter draft.", at: 110 },+ { by: "person", text: "Keep it plain too", at: 140 },+ { by: "bot", text: "A plain draft.", at: 150 },],}]);});@@ -126,7 +126,7 @@ describe("the chats a dream reads", () => {{ 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." }],+ threadId: "a", lines: [{ by: "person", text: "Shorter please", at: 100 }, { by: "bot", text: "A shorter draft.", at: 130 }],}]);});@@ -140,7 +140,7 @@ describe("the chats a dream reads", () => {];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." }],+ threadId: "a", lines: [{ by: "person", text: "Shorter please", at: 100 }, { by: "bot", text: "A shorter draft.", at: 120 }],}]);});@@ -256,7 +256,7 @@ describe("dreaming in the upkeep loop", () => {BOT.memoryUpkeep = true;clock = new Date(2026, 9, 22, 10, 0);chats = [- { threadId: "a", lines: [{ by: "person", text: "Shorter please" }] },+ { threadId: "a", lines: [{ by: "person", text: "Shorter please", at: 200 }] },{ threadId: "b", lines: [{ by: "person", text: "Too long again. Also I moved to Bangalore" }] },];engine = {@@ -273,13 +273,16 @@ describe("dreaming in the upkeep loop", () => {it("files what it learned as dream entries, updates an outdated note, journals both, and reports it", async () => {ensureWorkspace(BOT.id);writeMemoryFile(BOT.id, "# Memory\n\n- 2026-09-01 · The person lives in Pune\n");+ chats[0]!.lines[0]!.text = "I want drafts under 100 words. I review drafts with my editor. I prefer plain words.";+ chats[1]!.lines[0]!.text = "Again, drafts under 100 words. I review drafts with my editor. I prefer plain words. I moved to Bangalore.";+ const evidence = chats.map((chat) => chat.lines[0]!.text);answers.push(JSON.stringify({learned: [- { text: "The person wants drafts under 100 words", from: [1, 2], confidence: 0.9 },- { text: "The person reviews drafts with their editor", from: [1, 2], topic: "work", topicAliases: ["editor"], confidence: 0.8 },- { text: "The person prefers plain words", from: [1, 2], aboutUser: true, confidence: 0.8 },+ { text: "The person wants drafts under 100 words", from: [1, 2], evidence, confidence: 0.9 },+ { text: "The person reviews drafts with their editor", from: [1, 2], topic: "work", topicAliases: ["editor"], evidence, confidence: 0.8 },+ { text: "The person prefers plain words", from: [1, 2], evidence, aboutUser: true, confidence: 0.8 },],- outdated: [{ line: 0, now: "The person lives in Bangalore", from: [2] }],+ outdated: [{ line: 0, now: "The person lives in Bangalore", from: [2], evidence: [chats[1]!.lines[0]!.text] }],ideas: [{ text: "Keep a short-draft checklist as a skill", from: [1, 2] }],}));const report = await upkeep().dream(BOT.id);@@ -306,6 +309,21 @@ describe("dreaming in the upkeep loop", () => {expect(upkeep().status(BOT.id)).toMatchObject({ lastDream: { conversations: 2 } });});+ it("refuses invented numbers and family facts before notebook or profile writes", async () => {+ ensureWorkspace(BOT.id);+ writeMemoryFile(BOT.id, "# Memory\n\n- 2026-09-01 · The person lives in Pune\n");+ answers.push(JSON.stringify({+ learned: [{ text: "The person has 17 sisters", from: [1, 2], evidence: ["Shorter please", "Too long again. Also I moved to Bangalore"], confidence: 0.9, aboutUser: true }],+ outdated: [{ line: 0, now: "The person lives in Delhi", from: [2], evidence: ["Too long again. Also I moved to Bangalore"] }],+ }));+ const before = memory();+ const report = await upkeep().dream(BOT.id);+ expect(report.learned).toEqual([]);+ expect(report.outdated).toEqual([]);+ expect(aboutMeAdded).toEqual([]);+ expect(memory()).toBe(before);+ });+it("the next dream reads only the chats after the last one that answered", async () => {answers.push("{}");await upkeep().dream(BOT.id);@@ -321,7 +339,7 @@ describe("dreaming in the upkeep loop", () => {generateText: async (prompt) => {if (!prompt.includes(DREAM_MARKER)) return "{}";writeMemoryFile(BOT.id, "# Memory\n\n- 2026-10-22 · The person has a cat\n- 2026-09-01 · The person lives in Pune\n");- return JSON.stringify({ outdated: [{ line: 0, now: "The person lives in Bangalore", from: [2] }] });+ return JSON.stringify({ outdated: [{ line: 0, now: "The person lives in Bangalore", from: [2], evidence: [chats[1]!.lines[0]!.text] }] });},};const report = await upkeep().dream(BOT.id);diff --git a/server/memory-dream.ts b/server/memory-dream.tsindex 98baf364a5..21c1382c59 100644--- a/server/memory-dream.ts+++ b/server/memory-dream.ts@@ -23,6 +23,7 @@ const NOTEBOOK_LINES = 200;export interface DreamLine {by: "person" | "bot";text: string;+ at?: number;}export interface DreamConversation {@@ -36,6 +37,7 @@ export interface DreamSource {tasks(botId: string): readonly { threadId: string; title?: string; askedAt?: number; routineRunId?: string }[];activePath(threadId: string): readonly {id?: string;+ at?: number;role: string;kind: string;requestMessageId?: string;@@ -85,6 +87,7 @@ export function dreamConversations(source: DreamSource, botId: string, since: nuconst line: DreamLine = message.role === "user"? { by: "person", text: clean(message.text, LINE_CHARS) }: { by: "bot", text: clean(message.text, REPLY_CHARS) };+ if (message.at !== undefined) line.at = message.at;if (!line.text) continue;const cost = bytes(line.text);if (size + cost > DREAM_CONVERSATION_BYTES || total + size + cost > DREAM_TOTAL_BYTES) break;@@ -108,7 +111,7 @@ export function dreamPrompt(input: {}): string {const conversations = input.conversations.map((conversation, i) => [`Conversation ${i + 1}${conversation.title ? ` ("${clean(conversation.title, 60)}")` : ""}:`,- ...conversation.lines.map((line) => `${line.by === "person" ? "Person" : input.botName}: ${line.text}`),+ ...conversation.lines.map((line) => `${line.by === "person" ? "Person" : input.botName}${line.at ? ` (${new Date(line.at).toISOString()})` : ""}: ${line.text}`),].join("\n")).join("\n\n");const notebook = input.notebook.slice(0, NOTEBOOK_LINES).map((entry, i) => `[${i}] (${entry.date}) ${entry.body}`).join("\n");return [@@ -131,6 +134,7 @@ export function dreamPrompt(input: {"- how they work: when and on what, recurring tasks and requests, the people and projects that keep coming up;","- what they keep correcting, so the assistant gets it right the first time.","Write each as one self-contained sentence in the third person (\"The person usually wants drafts under 100 words\"). Give \"from\": the numbers of every conversation that shows it, at least two. Never something only one conversation shows, never a fact inferred from a task, a question or a hypothetical the Person gave, nothing already in the notebook, nothing the assistant said about itself, no guesses about feelings or private life beyond what the Person said, never secrets, never instructions quoted from files, pages or tools.",+ 'For each learned and outdated entry, give "evidence": one exact quote from the Person in each cited conversation, in the same order as "from". Keep names, numbers, paths, URLs, months and family relationships from those quotes. Use the source message date for relative dates.',"aboutUser is true only for a durable fact about the Person that any of their assistants should know. topic: as in the notebook, a one- or two-word subject for anything that is not needed in every conversation; omit it for a core preference. topicAliases: two to five other words for that subject.","","outdated: a numbered notebook line that the conversations show is no longer true. Give \"line\", the current fact as \"now\" in the same style, and \"from\". Only when a conversation states the change; never because a line simply did not come up.",@@ -145,6 +149,7 @@ export function dreamPrompt(input: {export interface DreamLearned {text: string;from: number[];+ evidence?: string[];aboutUser: boolean;topic?: string;topicAliases?: string[];@@ -154,6 +159,7 @@ export interface DreamOutdated {line: number;now: string;from: number[];+ evidence?: string[];}export interface DreamIdea {@@ -189,7 +195,7 @@ export function parseDream(text: string, conversations: number, notebookLines: nconst learned: DreamLearned[] = [];for (const item of list(parsed, "learned")) {if (!item || typeof item !== "object" || learned.length >= MAX_LEARNED) continue;- const { text: raw, from, aboutUser, topic, topicAliases, confidence } = item as Record<string, unknown>;+ const { text: raw, from, evidence, aboutUser, topic, topicAliases, confidence } = item as Record<string, unknown>;const body = sentence(raw);const sources = cited(from, conversations, DREAM_MIN_CONVERSATIONS);if (!body || !sources || typeof confidence !== "number" || !(confidence >= DREAM_MIN_CONFIDENCE)) continue;@@ -197,18 +203,18 @@ export function parseDream(text: string, conversations: number, notebookLines: nconst aliases = Array.isArray(topicAliases)? topicAliases.filter((a): a is string => typeof a === "string").map((a) => a.replace(/[\r\n,[\]]+/g, " ").trim().slice(0, 40)).filter(Boolean).slice(0, 8): [];- learned.push({ text: body, from: sources, aboutUser: aboutUser === true, ...(file ? { topic: file } : {}), ...(file && aliases.length ? { topicAliases: aliases } : {}) });+ learned.push({ text: body, from: sources, ...(Array.isArray(evidence) && evidence.every((q) => typeof q === "string") ? { evidence } : {}), aboutUser: aboutUser === true, ...(file ? { topic: file } : {}), ...(file && aliases.length ? { topicAliases: aliases } : {}) });}const outdated: DreamOutdated[] = [];const lines = new Set<number>();for (const item of list(parsed, "outdated")) {if (!item || typeof item !== "object" || outdated.length >= MAX_OUTDATED) continue;- const { line, now, from } = item as Record<string, unknown>;+ const { line, now, from, evidence } = item as Record<string, unknown>;const body = sentence(now);const sources = cited(from, conversations, 1);if (!Number.isInteger(line) || (line as number) < 0 || (line as number) >= Math.min(notebookLines, NOTEBOOK_LINES) || lines.has(line as number) || !body || !sources) continue;lines.add(line as number);- outdated.push({ line: line as number, now: body, from: sources });+ outdated.push({ line: line as number, now: body, from: sources, ...(Array.isArray(evidence) && evidence.every((q) => typeof q === "string") ? { evidence } : {}) });}const ideas: DreamIdea[] = [];for (const item of list(parsed, "ideas")) {diff --git a/server/memory-fact-checks.test.ts b/server/memory-fact-checks.test.tsnew file mode 100644index 0000000000..250802ae49--- /dev/null+++ b/server/memory-fact-checks.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import { checkDreamFacts } from "./memory-fact-checks.ts";+import type { DreamConversation } from "./memory-dream.ts";++const chats: DreamConversation[] = [+ { threadId: "a", lines: [{ by: "person", text: "Anna, my sister, moved yesterday to York. Her budget is 250 in March. Notes: /work/anna.md https://example.test/anna", at: Date.parse("2026-10-20T12:00:00Z") }] },+ { threadId: "b", lines: [{ by: "person", text: "Anna likes short replies too.", at: Date.parse("2026-10-21T12:00:00Z") }] },+];+const quotes = [chats[0]!.lines[0]!.text, chats[1]!.lines[0]!.text];+const check = (text: string, evidence = quotes) => checkDreamFacts(text, [1, 2], evidence, chats);++describe("dream fact checks", () => {+ it("keeps supported facts and anchors relative dates to the quoted message", () => {+ expect(check("Anna, my sister, moved yesterday to York")).toBe("Anna, my sister, moved 2026-10-19 to York");+ expect(check("Anna, my sister, has a budget of 250 in March")).toBe("Anna, my sister, has a budget of 250 in March");+ expect(check("Anna, my sister, uses /work/anna.md and https://example.test/anna")).toBeTruthy();+ });+ it.each(["Anna has 251", "Anna visits in April", "Anna moved on 2026-10-18", "Anna uses /work/bob.md", "Anna uses https://example.test/bob", "Alice likes short replies", "Anna, my mother, moved to York"])("rejects an unsupported fact: %s", (text) => {+ expect(check(text)).toBeNull();+ });+ it("requires actual owner statements in every cited chat", () => {+ expect(check("Anna likes short replies", ["Invented quotation", quotes[1]!])).toBeNull();+ expect(check("Anna likes short replies", [])).toBeNull();+ expect(checkDreamFacts("Anna likes tea", [1], ["Anna likes tea"], [{ threadId: "q", lines: [{ by: "bot", text: "Anna likes tea" }] }])).toBeNull();+ expect(checkDreamFacts("Anna likes tea", [1], ["Anna likes tea"], [{ threadId: "q", lines: [{ by: "person", text: "Suppose Anna likes tea?" }] }])).toBeNull();+ });+ it("rejects secrets even when the source contains them", () => {+ const secret = "password: synthetic-secret-123";+ expect(checkDreamFacts(secret, [1], [secret], [{ threadId: "s", lines: [{ by: "person", text: secret }] }])).toBeNull();+ });+ it.each(["dziś", "dzisiaj", "wczoraj", "jutro", "today", "yesterday", "tomorrow"])("resolves %s at a month boundary", (word) => {+ const text = `Anna ${word}`;+ const day = ["wczoraj", "yesterday"].includes(word) ? "2026-02-28" : ["jutro", "tomorrow"].includes(word) ? "2026-03-02" : "2026-03-01";+ expect(checkDreamFacts(text, [1], [text], [{ threadId: "d", lines: [{ by: "person", text, at: Date.parse("2026-03-01T12:00:00Z") }] }])).toBe(`Anna ${day}`);+ });+ it("refuses relative dates without an anchor or with ambiguous source days", () => {+ expect(checkDreamFacts("Anna today", [1], ["Anna today"], [{ threadId: "x", lines: [{ by: "person", text: "Anna today" }] }])).toBeNull();+ expect(checkDreamFacts("Anna today", [1, 2], ["Anna today", "Anna today"], [0, 1].map((i) => ({ threadId: String(i), lines: [{ by: "person" as const, text: "Anna today", at: Date.parse(`2026-10-2${i}T12:00:00Z`) }] })))).toBeNull();+ });+});diff --git a/server/memory-fact-checks.ts b/server/memory-fact-checks.tsnew file mode 100644index 0000000000..cc529bae8c--- /dev/null+++ b/server/memory-fact-checks.ts@@ -0,0 +1,57 @@+import { statedInConversation } from "./memory-capture.ts";+import type { DreamConversation } from "./memory-dream.ts";+import { memoryDate } from "./workspace.ts";+import { redactSecretsInText } from "./redact.ts";++const RELATIVE = /(?<!\p{L})(today|yesterday|tomorrow|dziś|dzisiaj|wczoraj|jutro)(?!\p{L})/giu;+const MONTH = /(?<!\p{L})(?:january|february|march|april|may|june|july|august|september|october|november|december|stycz\p{L}*|lutego|luty|marca|marzec|kwiet\p{L}*|maja|maj|czerw\p{L}*|lip\p{L}*|sierp\p{L}*|wrze\p{L}*|paździer\p{L}*|listopad\p{L}*|grud\p{L}*)(?!\p{L})/giu;+const RELATION = /(?<!\p{L})(?:mother|mom|mum|father|dad|wife|husband|partner|son|daughter|sister|brother|matk\p{L}*|mam\p{L}*|ojciec|ojca|żon\p{L}*|mąż|męża|córk\p{L}*|syn\p{L}*|siostr\p{L}*|brat\p{L}*)(?!\p{L})/giu;+const LOCATION = /https?:\/\/[^\s<>[\]()]+|(?:~\/|\/[\p{L}_.]|[A-Za-z]:\\)[^\s<>[\](),;]*/gu;+const NUMBER = /\p{N}+(?:[.,:/-]\p{N}+)*%?/gu;+const NAME = /(?<!\p{L})\p{Lu}[\p{L}\p{M}]+(?!\p{L})/gu;+const SENTENCE_WORDS = new Set("The A An I User Owner Person Client Prefers Keep New Old Uses Use Run Note Remember Works My Her His Their They He She It Shorter Too Also".toLowerCase().split(" "));+const matches = (text: string, pattern: RegExp) => [...text.matchAll(pattern)].map((m) => m[0].toLowerCase());+const subset = (a: readonly string[], b: readonly string[]) => a.every((value) => b.includes(value));++function absolute(text: string, at?: number): string | null {+ if (!matches(text, RELATIVE).length) return text;+ if (at === undefined || !Number.isFinite(at)) return null;+ return text.replace(RELATIVE, (word) => {+ const date = new Date(at);+ const lower = word.toLowerCase();+ const shift = ["yesterday", "wczoraj"].includes(lower) ? -1 : ["tomorrow", "jutro"].includes(lower) ? 1 : 0;+ date.setDate(date.getDate() + shift);+ return memoryDate(date);+ });+}++/** Validate each quote against an owner statement, then compare concrete facts with those quotes only. */+export function checkDreamFacts(text: string, from: readonly number[], evidence: readonly string[] | undefined, chats: readonly DreamConversation[]): string | null {+ if (!evidence || evidence.length !== from.length || redactSecretsInText(text) !== text) return null;+ const sources: { text: string; at?: number }[] = [];+ for (let i = 0; i < from.length; i++) {+ const quote = evidence[i];+ if (!quote?.trim()) return null;+ const lines = chats[from[i]! - 1]?.lines.filter((line) => line.by === "person" && line.text.includes(quote)+ && statedInConversation({ text, kind: "fact", aboutUser: false, evidence: quote }, [{ person: line.text, bot: "" }], true));+ if (!lines?.length) return null;+ sources.push(...lines.map((line) => ({ text: quote, at: line.at })));+ }+ const relative = matches(text, RELATIVE);+ const anchors = relative.length ? sources.filter((source) => subset(relative, matches(source.text, RELATIVE))) : sources;+ const prepared = anchors.map((source) => absolute(text, source.at));+ if (!prepared.length || prepared.some((value) => value === null || value !== prepared[0])) return null;+ const entry = prepared[0]!;+ const quoted = sources.map((source) => absolute(source.text, source.at));+ if (quoted.some((value) => value === null)) return null;+ const source = quoted.join("\n");+ for (const pattern of [NUMBER, LOCATION, MONTH, RELATION]) {+ if (!subset(matches(entry, pattern), matches(source, pattern))) return null;+ }+ const names = matches(entry, NAME).filter((name) => !SENTENCE_WORDS.has(name));+ if (!subset(names, matches(source, /[\p{L}\p{M}]+/gu))) return null;+ // Family facts must retain the relationship in the quoted statement.+ if (names.length && quoted.some((quote) => names.some((name) => matches(quote!, /[\p{L}\p{M}]+/gu).includes(name))+ && !subset(matches(quote!, RELATION), matches(entry, RELATION)))) return null;+ return entry;+}diff --git a/server/memory-upkeep.ts b/server/memory-upkeep.tsindex d3df8e498c..ab8e43c025 100644--- a/server/memory-upkeep.ts+++ b/server/memory-upkeep.ts@@ -5,6 +5,7 @@ import { writeFileAtomic } from "./atomic.ts";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 { mergeTopicText } from "./memory-topics.ts";import { isForgotten } from "./profile-learned.ts";@@ -721,6 +722,14 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {return late;}const dreamt = parseDream(answer, conversations.length, notebook.length);+ dreamt.learned = dreamt.learned.flatMap((item) => {+ const text = checkDreamFacts(item.text, item.from, item.evidence, conversations);+ return text && !isForgotten(text) ? [{ ...item, text }] : [];+ });+ dreamt.outdated = dreamt.outdated.flatMap((item) => {+ const text = checkDreamFacts(item.now, item.from, item.evidence, conversations);+ return text && !isForgotten(text) ? [{ ...item, now: text }] : [];+ });const source = `dream across ${conversations.length} chats`;// Re-read inside the write: if the notes changed after the prompt, its line numbers are stale.const written = writing(botId, () => {