test(cli): run the CLI suites on the mem0 store and waggle.db (P1.5)

The comprehensive and hard-persistence suites open a data directory the
way the REPL does: mem0 in <dir>/memory (word embedder, no model download)
and waggle.db for the profile card and tasks. Persistence across sessions
now also checks identity and tasks after reopening.

The packaged-runtime tests install @waggle/memory-contract and
@waggle/memory-mem0 with the CLI (the weaver package is gone) and check
that the REPL creates the memory store and waggle.db instead of
default.mind.

Deleted: T4 and T18 (knowledge graph entities and their persistence) and
the knowledge-graph steps of the hard-persistence run; the graph is not in
v1 (ADR-0002).
This commit is contained in:
shumeiko.it
2026-10-24 12:37:42 +02:00
parent ac23bbd7a6
commit 424b46db19
3 changed files with 134 additions and 190 deletions

View File

@@ -2,15 +2,18 @@
* Comprehensive E2E test — exercises the same code paths as the CLI REPL
* but programmatically (no LiteLLM/API needed).
*
* Tests 14 scenarios covering identity, awareness, memory persistence,
* knowledge graph, cross-session recall, tool execution, system prompt,
* hooks, permissions, and more.
* Covers identity, awareness, memory persistence, cross-session recall, tool
* execution, system prompt, hooks, permissions, and more. Memory is the mem0
* store the REPL opens (ADR-0007), with the word embedder so no model is
* downloaded; the profile card and awareness live in waggle.db.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { MindDB } from '@waggle/core';
import { WaggleDB } from '@waggle/core';
import { PERSONAL_SCOPE, type MemoryStore } from '@waggle/memory-contract';
import { createMem0MemoryStore, createWordEmbedder } from '@waggle/memory-mem0';
import {
Orchestrator,
createSystemTools,
@@ -21,36 +24,42 @@ import {
filterToolsForContext,
needsConfirmation,
} from '@waggle/agent';
import { MockEmbedder } from '../../hive-mind-core/tests/mind/helpers/mock-embedder.js';
// Helper: create a file-backed .mind DB in temp dir
function createTmpMind(): { path: string; db: MindDB } {
const p = path.join(os.tmpdir(), `waggle-e2e-${Date.now()}-${Math.random().toString(36).slice(2)}.mind`);
return { path: p, db: new MindDB(p) };
interface Session {
memory: MemoryStore;
waggleDb: WaggleDB;
orchestrator: Orchestrator;
}
function cleanup(filePath: string) {
for (const f of [filePath, filePath + '-wal', filePath + '-shm']) {
if (fs.existsSync(f)) fs.unlinkSync(f);
}
/** Opens a data directory the way the REPL does: memory in <dir>/memory, waggle.db next to it. */
async function openSession(dataDir: string): Promise<Session> {
const memory = await createMem0MemoryStore({
directory: path.join(dataDir, 'memory'),
embedder: createWordEmbedder(),
});
const waggleDb = WaggleDB.openInDataDir(dataDir);
return { memory, waggleDb, orchestrator: new Orchestrator({ memory, waggleDb }) };
}
async function closeSession(session: Session): Promise<void> {
await session.memory.close();
session.waggleDb.close();
}
describe('Comprehensive CLI E2E Test', () => {
let mindPath: string;
let db: MindDB;
let dataDir: string;
let session: Session;
let orchestrator: Orchestrator;
const embedder = new MockEmbedder();
beforeEach(() => {
const tmp = createTmpMind();
mindPath = tmp.path;
db = tmp.db;
orchestrator = new Orchestrator({ db, embedder });
beforeEach(async () => {
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-e2e-'));
session = await openSession(dataDir);
orchestrator = session.orchestrator;
});
afterEach(() => {
db.close();
cleanup(mindPath);
afterEach(async () => {
await closeSession(session);
fs.rmSync(dataDir, { recursive: true, force: true });
});
// ─── Test 1: Identity CRUD ───
@@ -60,7 +69,7 @@ describe('Comprehensive CLI E2E Test', () => {
role: 'Personal AI Assistant',
department: 'Engineering',
personality: 'Helpful and precise',
capabilities: 'Memory, search, knowledge graph',
capabilities: 'Memory, search',
system_prompt: 'You are Waggle.',
});
@@ -103,24 +112,18 @@ describe('Comprehensive CLI E2E Test', () => {
expect(result).toContain('March 15th');
});
// ─── Test 4: Knowledge Graph ───
it('T4: Create entities and relations, query them', async () => {
const kg = orchestrator.getKnowledge();
const alice = kg.createEntity('person', 'Alice', { role: 'Tech Lead' });
const project = kg.createEntity('project', 'Phoenix', { status: 'active' });
const react = kg.createEntity('technology', 'React', { version: '18' });
kg.createRelation(alice.id, project.id, 'leads', 0.95);
kg.createRelation(project.id, react.id, 'uses', 0.9);
const result = await orchestrator.executeTool('query_knowledge', { query: 'Alice' });
expect(result).toContain('Alice');
expect(result).toContain('leads');
expect(result).toContain('Phoenix');
});
// ─── Test 5: Cross-Session Memory Persistence ───
it('T5: Memories persist across sessions (file-backed .mind)', async () => {
it('T5: Memories, identity and tasks persist across sessions (file-backed data directory)', async () => {
orchestrator.getIdentity().create({
name: 'Waggle',
role: 'Personal AI Assistant',
department: '',
personality: '',
capabilities: '',
system_prompt: '',
});
await orchestrator.executeTool('add_task', { content: 'Prepare the quarterly review', priority: 7 });
// Session 1: save memories
await orchestrator.executeTool('save_memory', {
content: 'My name is Marko and I work on the Waggle project',
@@ -135,12 +138,12 @@ describe('Comprehensive CLI E2E Test', () => {
importance: 'normal',
});
// Close DB (simulates CLI exit)
db.close();
// Close everything (simulates CLI exit)
await closeSession(session);
// Session 2: reopen same .mind file
const db2 = new MindDB(mindPath);
const orchestrator2 = new Orchestrator({ db: db2, embedder });
// Session 2: reopen the same data directory
session = await openSession(dataDir);
const orchestrator2 = session.orchestrator;
// Search for memories from previous session
const result1 = await orchestrator2.executeTool('search_memory', { query: 'Marko Waggle' });
@@ -153,15 +156,13 @@ describe('Comprehensive CLI E2E Test', () => {
const result3 = await orchestrator2.executeTool('search_memory', { query: 'Python data' });
expect(result3).toContain('Python');
db2.close();
// Reassign so afterEach cleanup works
db = new MindDB(mindPath);
orchestrator = new Orchestrator({ db, embedder });
expect(await orchestrator2.executeTool('get_identity', {})).toContain('Personal AI Assistant');
expect(await orchestrator2.executeTool('get_awareness', {})).toContain('Prepare the quarterly review');
expect((await orchestrator2.getMemoryStats()).memoryCount).toBe(3);
});
// ─── Test 6: System Prompt Builder ───
it('T6: System prompt includes identity, awareness, and tools', () => {
it('T6: System prompt includes identity, awareness, and tools', async () => {
orchestrator.getIdentity().create({
name: 'TestBot',
role: 'Tester',
@@ -172,7 +173,7 @@ describe('Comprehensive CLI E2E Test', () => {
});
orchestrator.getAwareness().add('task', 'Run integration tests', 10);
const prompt = orchestrator.buildSystemPrompt();
const prompt = await orchestrator.buildSystemPrompt();
expect(prompt).toContain('TestBot');
expect(prompt).toContain('Run integration tests');
// System prompt includes self-awareness block with tool summary
@@ -183,7 +184,7 @@ describe('Comprehensive CLI E2E Test', () => {
// ─── Test 7: Tool Definitions ───
it('T7: All required tools are defined with correct shape', () => {
const tools = orchestrator.getTools();
const required = ['get_identity', 'get_awareness', 'search_memory', 'save_memory', 'query_knowledge', 'add_task', 'correct_knowledge'];
const required = ['get_identity', 'get_awareness', 'search_memory', 'search_all_workspaces', 'save_memory', 'add_task'];
for (const name of required) {
const tool = tools.find(t => t.name === name);
@@ -191,6 +192,8 @@ describe('Comprehensive CLI E2E Test', () => {
expect(tool!.description).toBeTruthy();
expect(typeof tool!.execute).toBe('function');
}
// The knowledge graph is not part of v1 (ADR-0002).
expect(tools.map(t => t.name)).not.toContain('query_knowledge');
});
// ─── Test 8: System Tools ───
@@ -288,20 +291,14 @@ describe('Comprehensive CLI E2E Test', () => {
// ─── Test 14: Memory Stats ───
it('T14: Memory stats reflect actual data', async () => {
// Start with empty
let stats = orchestrator.getMemoryStats();
expect(stats.frameCount).toBe(0);
expect(stats.sessionCount).toBe(0);
expect(stats.entityCount).toBe(0);
expect((await orchestrator.getMemoryStats()).memoryCount).toBe(0);
// Save some memories
await orchestrator.executeTool('save_memory', { content: 'Memory one' });
await orchestrator.executeTool('save_memory', { content: 'Memory two' });
orchestrator.getKnowledge().createEntity('test', 'Entity1', {});
await orchestrator.executeTool('save_memory', { content: 'Memory one about the roadmap' });
await orchestrator.executeTool('save_memory', { content: 'Memory two about the hiring plan' });
stats = orchestrator.getMemoryStats();
expect(stats.frameCount).toBeGreaterThanOrEqual(2);
expect(stats.sessionCount).toBeGreaterThanOrEqual(1);
expect(stats.entityCount).toBeGreaterThanOrEqual(1);
expect((await orchestrator.getMemoryStats()).memoryCount).toBe(2);
expect(await session.memory.count({ scopes: [PERSONAL_SCOPE] })).toBe(2);
});
// ─── Test 15: Empty state handling ───
@@ -315,8 +312,7 @@ describe('Comprehensive CLI E2E Test', () => {
const search = await orchestrator.executeTool('search_memory', { query: 'anything' });
expect(search).toContain('No relevant memories');
const kg = await orchestrator.executeTool('query_knowledge', { query: 'nobody' });
expect(kg).toContain('No entities found');
expect(await orchestrator.recallMemory('anything')).toEqual({ text: '', count: 0, recalled: [], recalledFrames: [] });
});
// ─── Test 16: Unknown tool throws ───
@@ -329,45 +325,26 @@ describe('Comprehensive CLI E2E Test', () => {
// W2.10: save_memory is rate-limited to 50 per session to prevent flooding.
// Save 60 — first 50 succeed, remaining are rate-limited.
const RATE_LIMIT = 50;
const TOPICS = ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf', 'hotel', 'india', 'juliett'];
const AREAS = ['billing', 'search', 'onboarding', 'reporting', 'security'];
const results: string[] = [];
for (let i = 0; i < 60; i++) {
await orchestrator.executeTool('save_memory', {
content: `Observation ${i}: topic-${i % 10} with detail about area-${i % 5}`,
results.push(await orchestrator.executeTool('save_memory', {
content: `Observation ${i}: topic ${TOPICS[i % 10]} with detail about ${AREAS[i % 5]}`,
importance: i % 20 === 0 ? 'important' : 'normal',
});
}));
}
expect(results.filter(r => r.startsWith('Memory saved'))).toHaveLength(RATE_LIMIT);
expect(results.slice(RATE_LIMIT).every(r => r.includes('rate limit reached'))).toBe(true);
// Search by topic (hyphens in queries should work after FTS5 sanitization)
const result = await orchestrator.executeTool('search_memory', { query: 'topic-7' });
expect(result).toContain('topic-7');
// Search by topic and by area
const result = await orchestrator.executeTool('search_memory', { query: 'topic hotel' });
expect(result).toContain('topic hotel');
// Search by area
const result2 = await orchestrator.executeTool('search_memory', { query: 'area-3' });
expect(result2).toContain('area-3');
const result2 = await orchestrator.executeTool('search_memory', { query: 'reporting' });
expect(result2).toContain('reporting');
// Stats should show exactly the rate limit count (50 saved, rest blocked)
const stats = orchestrator.getMemoryStats();
expect(stats.frameCount).toBeGreaterThanOrEqual(RATE_LIMIT);
});
// ─── Test 18: Cross-session knowledge graph persistence ───
it('T18: Knowledge graph persists across sessions', async () => {
const kg = orchestrator.getKnowledge();
const alice = kg.createEntity('person', 'Alice', { role: 'Engineer' });
const bob = kg.createEntity('person', 'Bob', { role: 'Designer' });
kg.createRelation(alice.id, bob.id, 'collaborates_with', 0.85);
// Close and reopen
db.close();
const db2 = new MindDB(mindPath);
const orchestrator2 = new Orchestrator({ db: db2, embedder });
const result = await orchestrator2.executeTool('query_knowledge', { query: 'Alice' });
expect(result).toContain('Alice');
expect(result).toContain('collaborates_with');
expect(result).toContain('Bob');
db2.close();
db = new MindDB(mindPath);
orchestrator = new Orchestrator({ db, embedder });
// Exactly the rate limit count was saved, the rest blocked
expect((await orchestrator.getMemoryStats()).memoryCount).toBe(RATE_LIMIT);
});
});