- Workspace state, the "Workspace Now" block, the home briefing and the proactive handlers read the workspace's memory through server.memory: decisions are memories of kind 'decision', critical ones or ones worded as decisions; summaries list memories most important first. They no longer open workspace .mind files, so the builders are async and ProactiveContext carries `memory` instead of `getWorkspaceMindDb`. - The home briefing counts extracted personal facts that are neither confirmed nor archived as awaiting review (memory-status.ts). - Workspace routes count memories through the contract, seed template starter memories with remember() in the background (origin 'workspace-template'), export memories through list(), and deleting a workspace forgets its memory scope and clears its awareness items before the directory is removed; the delete is refused if forgetting fails. agentState.releaseWorkspace() replaces closeWorkspaceMind for callers. - The command palette searches personal memory and the active workspace's memory (UF-033). - chat.ts drops the MindDB-flake diagnostics; the mind cache they guarded no longer serves chat turns.
277 lines
10 KiB
TypeScript
277 lines
10 KiB
TypeScript
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import { WaggleDB } from '@waggle/core';
|
|
import {
|
|
createInMemoryMemoryStore,
|
|
workspaceScope,
|
|
type MemoryImportance,
|
|
type MemoryStore,
|
|
} from '@waggle/memory-contract';
|
|
import { buildWorkspaceNowBlock, formatWorkspaceNowPrompt, type WorkspaceNowBlock } from '../../src/local/routes/workspace-context.js';
|
|
|
|
describe('workspace-context', () => {
|
|
let tmpDir: string;
|
|
let waggleDb: WaggleDB;
|
|
let memory: MemoryStore;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-ctx-test-'));
|
|
waggleDb = WaggleDB.openInDataDir(tmpDir);
|
|
memory = createInMemoryMemoryStore();
|
|
});
|
|
|
|
afterEach(() => {
|
|
waggleDb.close();
|
|
// On Windows, SQLite WAL files may keep handles open briefly; best-effort cleanup
|
|
try {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
} catch {
|
|
// Non-critical — OS will clean temp dir
|
|
}
|
|
});
|
|
|
|
// Helper: create a workspace directory structure with memories
|
|
async function setupWorkspace(id: string, opts?: {
|
|
memories?: Array<{ text: string; importance: MemoryImportance }>;
|
|
sessions?: Array<{ title: string; messages: Array<{ role: string; content: string }> }>;
|
|
}) {
|
|
const wsDir = path.join(tmpDir, 'workspaces', id);
|
|
fs.mkdirSync(wsDir, { recursive: true });
|
|
|
|
// Write workspace.json
|
|
fs.writeFileSync(
|
|
path.join(wsDir, 'workspace.json'),
|
|
JSON.stringify({ id, name: `Test Workspace ${id}`, group: 'test', created: new Date().toISOString() }),
|
|
);
|
|
|
|
for (const memo of opts?.memories ?? []) {
|
|
await memory.remember({ scope: workspaceScope(id), text: memo.text, importance: memo.importance });
|
|
}
|
|
|
|
// Create session files
|
|
if (opts?.sessions) {
|
|
const sessDir = path.join(wsDir, 'sessions');
|
|
fs.mkdirSync(sessDir, { recursive: true });
|
|
|
|
for (let i = 0; i < opts.sessions.length; i++) {
|
|
const sess = opts.sessions[i];
|
|
const sessionId = `session-${i}`;
|
|
const lines: string[] = [
|
|
JSON.stringify({ type: 'meta', title: sess.title, created: new Date().toISOString() }),
|
|
];
|
|
for (const msg of sess.messages) {
|
|
lines.push(JSON.stringify({ role: msg.role, content: msg.content }));
|
|
}
|
|
fs.writeFileSync(path.join(sessDir, `${sessionId}.jsonl`), lines.join('\n') + '\n');
|
|
}
|
|
}
|
|
|
|
return { wsDir };
|
|
}
|
|
|
|
function makeManager(workspaces: Map<string, { id: string; name: string }>) {
|
|
return {
|
|
get: (id: string) => workspaces.get(id) ?? null,
|
|
};
|
|
}
|
|
|
|
// ── Test 1: Returns null for non-existent workspace ──────────────
|
|
|
|
it('returns null for non-existent workspace', async () => {
|
|
const wsManager = makeManager(new Map());
|
|
|
|
const result = await buildWorkspaceNowBlock({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'does-not-exist',
|
|
wsManager,
|
|
memory,
|
|
});
|
|
|
|
expect(result).toBeNull();
|
|
});
|
|
|
|
// ── Test 2: Returns null for workspace with no data ──────────────
|
|
|
|
it('returns null for workspace without memories', async () => {
|
|
const wsManager = makeManager(new Map([
|
|
['empty-ws', { id: 'empty-ws', name: 'Empty Workspace' }],
|
|
]));
|
|
await setupWorkspace('empty-ws', {
|
|
sessions: [{ title: 'Chat only', messages: [{ role: 'user', content: 'Hello there' }] }],
|
|
});
|
|
|
|
const result = await buildWorkspaceNowBlock({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'empty-ws',
|
|
wsManager,
|
|
memory,
|
|
});
|
|
|
|
expect(result).toBeNull();
|
|
});
|
|
|
|
// ── Test 3: Returns correctly shaped block ───────────────────────
|
|
|
|
it('returns correctly shaped block for workspace with data', async () => {
|
|
const wsManager = makeManager(new Map([
|
|
['rich-ws', { id: 'rich-ws', name: 'Rich Workspace' }],
|
|
]));
|
|
|
|
await setupWorkspace('rich-ws', {
|
|
memories: [
|
|
{ text: 'Working on the Waggle project, a workspace-native AI agent platform.', importance: 'important' },
|
|
{ text: 'Decision: Use SQLite for local storage instead of PostgreSQL.', importance: 'critical' },
|
|
{ text: 'Implemented the memory frame system with FTS5 search.', importance: 'normal' },
|
|
],
|
|
sessions: [
|
|
{
|
|
title: 'Planning session',
|
|
messages: [
|
|
{ role: 'user', content: 'Let us plan the architecture for the next milestone' },
|
|
{ role: 'assistant', content: 'I have reviewed the current state and here is my recommendation.' },
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
const result = await buildWorkspaceNowBlock({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'rich-ws',
|
|
wsManager,
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
expect(result!.workspaceName).toBe('Rich Workspace');
|
|
expect(result!.summary).toBeTruthy();
|
|
expect(result!.summary.length).toBeGreaterThan(10);
|
|
expect(Array.isArray(result!.recentDecisions)).toBe(true);
|
|
expect(Array.isArray(result!.activeThreads)).toBe(true);
|
|
expect(Array.isArray(result!.progressItems)).toBe(true);
|
|
expect(Array.isArray(result!.nextActions)).toBe(true);
|
|
// Should have at least one thread from the session
|
|
expect(result!.activeThreads.length).toBeGreaterThanOrEqual(1);
|
|
// Should have at least one decision (the critical frame)
|
|
expect(result!.recentDecisions.length).toBeGreaterThanOrEqual(1);
|
|
});
|
|
|
|
// ── Test 4: Caps at correct limits ───────────────────────────────
|
|
|
|
it('caps decisions at 3, threads at 3, progress at 5', async () => {
|
|
const wsManager = makeManager(new Map([
|
|
['capped-ws', { id: 'capped-ws', name: 'Capped Workspace' }],
|
|
]));
|
|
|
|
// Create many decisions and sessions
|
|
const memories: Array<{ text: string; importance: MemoryImportance }> = [];
|
|
for (let i = 0; i < 10; i++) {
|
|
memories.push({ text: `Decision: chose option ${i} for the architecture component ${i}`, importance: 'critical' as const });
|
|
}
|
|
|
|
const sessions = [];
|
|
for (let i = 0; i < 8; i++) {
|
|
sessions.push({
|
|
title: `Thread ${i}: discussing component ${i}`,
|
|
messages: [
|
|
{ role: 'user', content: `Tell me about component ${i}` },
|
|
{ role: 'assistant', content: `Here is info about component ${i}` },
|
|
],
|
|
});
|
|
}
|
|
|
|
await setupWorkspace('capped-ws', { memories, sessions });
|
|
|
|
const result = await buildWorkspaceNowBlock({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'capped-ws',
|
|
wsManager,
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
expect(result!.recentDecisions.length).toBeLessThanOrEqual(3);
|
|
expect(result!.activeThreads.length).toBeLessThanOrEqual(3);
|
|
expect(result!.progressItems.length).toBeLessThanOrEqual(5);
|
|
expect(result!.nextActions.length).toBeLessThanOrEqual(3);
|
|
});
|
|
|
|
// ── Test 5: formatWorkspaceNowPrompt produces clean markdown ─────
|
|
|
|
describe('formatWorkspaceNowPrompt', () => {
|
|
it('produces clean markdown with all sections', () => {
|
|
const block: WorkspaceNowBlock = {
|
|
workspaceName: 'My Project',
|
|
summary: 'Working on an AI agent platform. Active today with 42 memories across 5 sessions.',
|
|
recentDecisions: ['Use SQLite for local storage', 'Deploy via Tauri'],
|
|
activeThreads: ['Architecture planning (2h ago)', 'Memory model design (yesterday)'],
|
|
progressItems: ['[blocker] Waiting for API key', '[task] Implement search', '[completed] Setup CI'],
|
|
nextActions: ['Resolve: Waiting for API key', 'Implement search'],
|
|
};
|
|
|
|
const result = formatWorkspaceNowPrompt(block);
|
|
|
|
expect(result).toContain('# Workspace Now — My Project');
|
|
expect(result).toContain('Working on an AI agent platform');
|
|
expect(result).toContain('## Recent Decisions');
|
|
expect(result).toContain('- Use SQLite for local storage');
|
|
expect(result).toContain('- Deploy via Tauri');
|
|
expect(result).toContain('## Active Threads');
|
|
expect(result).toContain('- Architecture planning (2h ago)');
|
|
expect(result).toContain('## Progress');
|
|
expect(result).toContain('- [blocker] Waiting for API key');
|
|
expect(result).toContain('## Likely Next Actions');
|
|
expect(result).toContain('- Resolve: Waiting for API key');
|
|
// No trailing whitespace
|
|
expect(result).toBe(result.trimEnd());
|
|
});
|
|
|
|
it('omits empty sections', () => {
|
|
const block: WorkspaceNowBlock = {
|
|
workspaceName: 'Minimal',
|
|
summary: 'A minimal workspace.',
|
|
recentDecisions: [],
|
|
activeThreads: [],
|
|
progressItems: [],
|
|
nextActions: [],
|
|
};
|
|
|
|
const result = formatWorkspaceNowPrompt(block);
|
|
|
|
expect(result).toContain('# Workspace Now — Minimal');
|
|
expect(result).toContain('A minimal workspace.');
|
|
expect(result).not.toContain('## Recent Decisions');
|
|
expect(result).not.toContain('## Active Threads');
|
|
expect(result).not.toContain('## Progress');
|
|
expect(result).not.toContain('## Likely Next Actions');
|
|
});
|
|
|
|
it('omits summary section if empty', () => {
|
|
const block: WorkspaceNowBlock = {
|
|
workspaceName: 'No Summary',
|
|
summary: '',
|
|
recentDecisions: ['Some decision'],
|
|
activeThreads: [],
|
|
progressItems: [],
|
|
nextActions: [],
|
|
};
|
|
|
|
const result = formatWorkspaceNowPrompt(block);
|
|
|
|
expect(result).toContain('# Workspace Now — No Summary');
|
|
expect(result).toContain('## Recent Decisions');
|
|
// Should not have blank lines between heading and decisions (no empty summary block)
|
|
const lines = result.split('\n');
|
|
const headingIdx = lines.findIndex(l => l.startsWith('# Workspace Now'));
|
|
const decisionsIdx = lines.findIndex(l => l === '## Recent Decisions');
|
|
// There should be only one blank line between heading and decisions section
|
|
expect(decisionsIdx - headingIdx).toBeLessThanOrEqual(2);
|
|
});
|
|
});
|
|
});
|