Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(memory): snapshot only selected team search results
Afloat4ce12fe881db
diff --git a/docs/verification/memory-layer.md b/docs/verification/memory-layer.mdindex c7c4cd57de..1ef64a5b17 100644--- a/docs/verification/memory-layer.md+++ b/docs/verification/memory-layer.md@@ -14,6 +14,8 @@ pnpm exec vitest run server/memory-forget.test.ts server/drivers/agents-call.tespnpm exec vitest run server/memory-capture-restart.e2e.test.tspnpm exec vitest run server/thread-memory.e2e.test.ts server/thread-notes.test.tspnpm exec vitest run server/spend-cap-api.test.ts+pnpm exec vitest run server/team-memory-search-cost.test.ts server/team-memory.test.ts server/team-memory-integrity.e2e.test.ts+node scripts/bench-team-memory-search.tspnpm exec vitest run server/memory-entries.test.ts server/recall.test.ts server/memory-upkeep.test.ts server/workspace.test.tspnpm exec vitest run server/side-jobs.test.ts server/helper-model.e2e.test.tspnpm exec vitest run src/components/bot-settings/MemorySection.test.ts src/lib/memory.test.ts server/drivers/agents-catalog-wire.test.tsdiff --git a/scripts/bench-team-memory-search.ts b/scripts/bench-team-memory-search.tsnew file mode 100644index 0000000000..c38ceb936e--- /dev/null+++ b/scripts/bench-team-memory-search.ts@@ -0,0 +1,46 @@+import { createHash } from "node:crypto";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { performance } from "node:perf_hooks";++const directory = mkdtempSync(join(tmpdir(), "omb-memory-search-bench-"));+process.env.OMB_BENCH = "1";+process.env.OMB_DATA_DIR = directory;+const { TeamMemory } = await import("../server/team-memory.ts");+try {+ const entries = Array.from({ length: 2_000 }, (_, i) => ({+ id: `note-${i}`, key: `term:${i}`, kind: "term", name: `Project ${i}`,+ detail: i % 2 === 0 ? "amber exposure" : "amber logistics", aliases: ["shared"],+ status: i % 5 === 0 ? "proposed" : "accepted", updatedAt: i,+ source: { botId: "b1", botName: "Scout", threadId: "t1", at: i },+ history: Array.from({ length: 20 }, (_, n) => ({ name: `Old project ${n}`, detail: "Earlier shared project detail", at: n })),+ }));+ const file = join(directory, "team-memory.json");+ writeFileSync(file, JSON.stringify({ version: 2, sections: { "": entries } }));+ const memory = new TeamMemory(file);+ const queries = ["", "amber", "amber exposure"];+ const search = () => queries.map(query => memory.search("", query, 12));+ const output = JSON.stringify(search());+ const milliseconds: number[] = [];+ for (let run = 0; run < 5; run++) {+ const start = performance.now();+ if (JSON.stringify(search()) !== output) throw new Error("Search results changed between runs");+ milliseconds.push(performance.now() - start);+ }+ const originalClone = globalThis.structuredClone;+ let clones = 0;+ globalThis.structuredClone = (value, options) => {+ clones++;+ return originalClone(value, options);+ };+ try { search(); } finally { globalThis.structuredClone = originalClone; }+ console.log(JSON.stringify({+ notes: entries.length, historyPerNote: 20, queries, limit: 12,+ milliseconds, medianMilliseconds: [...milliseconds].sort((a, b) => a - b)[2],+ snapshotsPerThreeQueries: clones,+ sha256: createHash("sha256").update(output).digest("hex"),+ }, null, 2));+} finally {+ rmSync(directory, { recursive: true, force: true });+}diff --git a/server/team-memory-search-cost.test.ts b/server/team-memory-search-cost.test.tsnew file mode 100644index 0000000000..f531fd821a--- /dev/null+++ b/server/team-memory-search-cost.test.ts@@ -0,0 +1,55 @@+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, it, vi } from "vitest";+import { TeamMemory, teamMemoryRevision, type TeamMemoryEntry } from "./team-memory.ts";+import { removeTempDir } from "./testing/cleanup.ts";++const directories: string[] = [];+afterEach(async () => {+ vi.restoreAllMocks();+ for (const directory of directories.splice(0)) await removeTempDir(directory);+});++function fixture(): { memory: TeamMemory; entries: TeamMemoryEntry[] } {+ const directory = mkdtempSync(join(tmpdir(), "omb-memory-search-"));+ directories.push(directory);+ const entries: TeamMemoryEntry[] = Array.from({ length: 240 }, (_, i) => ({+ id: `note-${i}`, key: `term:${i}`, kind: "term", name: `Project ${i}`,+ detail: i % 2 === 0 ? "amber exposure" : "amber missing", aliases: ["shared"],+ status: i % 5 === 0 ? "proposed" : "accepted", updatedAt: Math.floor(i / 2),+ source: { botId: "b1", botName: "Scout", threadId: "t1", at: i },+ history: [{ name: "Earlier name", detail: "Earlier detail", at: i - 1 }],+ replaces: [{ id: `old-${i}`, revision: "previous" }],+ }));+ const file = join(directory, "team-memory.json");+ writeFileSync(file, JSON.stringify({ version: 2, sections: { "": entries } }));+ return { memory: new TeamMemory(file), entries };+}++it("snapshots only the requested matching notes, with full revisions and independent results", () => {+ const { memory, entries } = fixture();+ const clones = vi.spyOn(globalThis, "structuredClone");+ const result = memory.search("", "amber exposure", 4, { since: 80, until: 100 });+ expect(result.map(entry => entry.id)).toEqual(["note-198", "note-196", "note-194", "note-192"]);+ expect(clones).toHaveBeenCalledTimes(4);+ for (const entry of result) {+ expect(entry.revision).toBe(teamMemoryRevision(entries.find(item => item.id === entry.id)!));+ expect(entry).not.toHaveProperty("history");+ expect(entry).not.toHaveProperty("replaces");+ }+ result[0].source.botName = "Changed outside the store";+ result[0].aliases.push("Changed outside the store");+ const again = memory.search("", "amber exposure", 4, { since: 80, until: 100 });+ expect(again[0].source.botName).toBe("Scout");+ expect(again[0].aliases).toEqual(["shared"]);+});++it("preserves stable time ordering, blank-query semantics and the result cap", () => {+ const { memory } = fixture();+ const result = memory.search("", "", 1000);+ expect(result).toHaveLength(25);+ expect(result.slice(0, 4).map(entry => entry.id)).toEqual(["note-238", "note-239", "note-236", "note-237"]);+ expect(memory.search("", "amber missing", 0)).toHaveLength(1);+ expect(memory.search("", "amber exposure missing")).toEqual([]);+});diff --git a/server/team-memory.ts b/server/team-memory.tsindex ea3ece8bd2..ae2d69fb6b 100644--- a/server/team-memory.ts+++ b/server/team-memory.ts@@ -315,16 +315,19 @@ export class TeamMemory {search(section: string | null | undefined, query: string, limit = 12, range?: { since?: number; until?: number }): TeamMemoryEntry[] {const terms = [...new Set(recallTerms(query))];- const score = (entry: TeamMemoryEntry) => {+ const matches = (entry: TeamMemoryEntry) => {const words = new Set(recallTerms([entry.name, entry.detail, entry.key, ...entry.aliases].join(" ")));- return terms.filter(term => words.has(term)).length;+ return terms.every(term => words.has(term));};- return this.list(section).filter(entry => entry.status === "accepted"- && (!terms.length || score(entry) === terms.length)+ return this.entries(section).filter(entry => entry.status === "accepted"&& (range?.since === undefined || entry.updatedAt >= range.since)- && (range?.until === undefined || entry.updatedAt <= range.until))- .sort((a, b) => score(b) - score(a) || b.updatedAt - a.updatedAt).slice(0, Math.min(25, Math.max(1, limit)))- .map(({ history: _history, replaces: _replaces, ...entry }) => entry);+ && (range?.until === undefined || entry.updatedAt <= range.until)+ && (!terms.length || matches(entry)))+ .sort((a, b) => b.updatedAt - a.updatedAt).slice(0, Math.min(25, Math.max(1, limit)))+ .map(entry => {+ const { history: _history, replaces: _replaces, ...snapshot } = structuredClone(entry);+ return { ...snapshot, revision: teamMemoryRevision(entry) };+ });}promptSelection(section: string | null | undefined): { text: string; loadedIds: string[]; total: number } {