refactor(server): read workspace state, briefings and workspaces from the memory contract (P1.5)
- 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.
This commit is contained in:
77
packages/server/tests/routes/command-search.test.ts
Normal file
77
packages/server/tests/routes/command-search.test.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Command palette search (GET /api/command/search): the memory facet searches
|
||||
* personal memory and the active workspace's memory through the memory contract.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import {
|
||||
createInMemoryMemoryStore,
|
||||
PERSONAL_SCOPE,
|
||||
workspaceScope,
|
||||
type MemoryStore,
|
||||
} from '@waggle/memory-contract';
|
||||
import { commandRoutes } from '../../src/local/routes/command.js';
|
||||
|
||||
describe('GET /api/command/search — memory facet', () => {
|
||||
let dataDir: string;
|
||||
let memory: MemoryStore;
|
||||
let server: FastifyInstance;
|
||||
|
||||
async function boot(activeWorkspaceId: string | null): Promise<void> {
|
||||
server = Fastify({ logger: false });
|
||||
server.decorate('localConfig', { dataDir } as never);
|
||||
server.decorate('memory', memory);
|
||||
server.decorate('workspaceManager', { list: () => [] } as never);
|
||||
server.decorate('agentState', {
|
||||
activeWorkspaceId,
|
||||
commandRegistry: { search: () => [], list: () => [] },
|
||||
} as never);
|
||||
await server.register(commandRoutes);
|
||||
}
|
||||
|
||||
async function memoryTitles(url: string): Promise<string[]> {
|
||||
const res = await server.inject({ method: 'GET', url });
|
||||
expect(res.statusCode).toBe(200);
|
||||
return (res.json().results as Array<{ type: string; title: string }>)
|
||||
.filter((r) => r.type === 'memory')
|
||||
.map((r) => r.title)
|
||||
.sort();
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-command-search-'));
|
||||
memory = createInMemoryMemoryStore();
|
||||
await memory.remember({ scope: PERSONAL_SCOPE, text: 'Personal budget review notes' });
|
||||
await memory.remember({ scope: workspaceScope('alpha'), text: 'Alpha budget decision' });
|
||||
await memory.remember({ scope: workspaceScope('beta'), text: 'Beta budget draft' });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('searches personal memory and the active workspace, not other workspaces', async () => {
|
||||
await boot('alpha');
|
||||
expect(await memoryTitles('/api/command/search?q=budget'))
|
||||
.toEqual(['Alpha budget decision', 'Personal budget review notes']);
|
||||
});
|
||||
|
||||
it('narrows to one scope when asked', async () => {
|
||||
await boot('alpha');
|
||||
expect(await memoryTitles('/api/command/search?q=budget&scope=personal'))
|
||||
.toEqual(['Personal budget review notes']);
|
||||
expect(await memoryTitles('/api/command/search?q=budget&scope=workspace'))
|
||||
.toEqual(['Alpha budget decision']);
|
||||
});
|
||||
|
||||
it('searches only personal memory when no workspace is active', async () => {
|
||||
await boot(null);
|
||||
expect(await memoryTitles('/api/command/search?q=budget'))
|
||||
.toEqual(['Personal budget review notes']);
|
||||
expect(await memoryTitles('/api/command/search?q=budget&scope=workspace')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,13 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { MindDB } from '@waggle/core';
|
||||
import { WaggleDB } from '@waggle/core';
|
||||
import {
|
||||
createInMemoryMemoryStore,
|
||||
workspaceScope,
|
||||
type MemoryImportance,
|
||||
type MemoryStore,
|
||||
} from '@waggle/memory-contract';
|
||||
import {
|
||||
buildWorkspaceNowBlock,
|
||||
formatWorkspaceNowPrompt,
|
||||
@@ -17,18 +23,23 @@ import {
|
||||
*
|
||||
* The chat route code:
|
||||
* if (workspaceId) {
|
||||
* const nowBlock = buildWorkspaceNowBlock({ ... });
|
||||
* const nowBlock = await buildWorkspaceNowBlock({ ... });
|
||||
* if (nowBlock) prompt += '\n\n' + formatWorkspaceNowPrompt(nowBlock);
|
||||
* }
|
||||
*/
|
||||
describe('Context Injection — system prompt integration', () => {
|
||||
let tmpDir: string;
|
||||
let memory: MemoryStore;
|
||||
let waggleDb: WaggleDB;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-ctx-inject-'));
|
||||
memory = createInMemoryMemoryStore();
|
||||
waggleDb = WaggleDB.openInDataDir(tmpDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
waggleDb.close();
|
||||
try {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
@@ -38,8 +49,8 @@ describe('Context Injection — system prompt integration', () => {
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function setupWorkspace(id: string, opts?: {
|
||||
frames?: Array<{ content: string; importance: string }>;
|
||||
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);
|
||||
@@ -50,20 +61,8 @@ describe('Context Injection — system prompt integration', () => {
|
||||
JSON.stringify({ id, name: `Test ${id}`, group: 'test', created: new Date().toISOString() }),
|
||||
);
|
||||
|
||||
const mindPath = path.join(wsDir, 'workspace.mind');
|
||||
if (opts?.frames && opts.frames.length > 0) {
|
||||
const db = new MindDB(mindPath);
|
||||
const raw = db.getDatabase();
|
||||
raw.prepare(
|
||||
`INSERT INTO sessions (gop_id, status, started_at) VALUES ('session:test', 'active', datetime('now'))`,
|
||||
).run();
|
||||
|
||||
for (const frame of opts.frames) {
|
||||
raw.prepare(
|
||||
`INSERT INTO memory_frames (gop_id, frame_type, content, importance, created_at) VALUES ('session:test', 'I', ?, ?, datetime('now'))`,
|
||||
).run(frame.content, frame.importance);
|
||||
}
|
||||
db.close();
|
||||
for (const memo of opts?.memories ?? []) {
|
||||
await memory.remember({ scope: workspaceScope(id), text: memo.text, importance: memo.importance });
|
||||
}
|
||||
|
||||
if (opts?.sessions) {
|
||||
@@ -86,26 +85,24 @@ describe('Context Injection — system prompt integration', () => {
|
||||
function makeManager(workspaces: Map<string, { id: string; name: string }>) {
|
||||
return {
|
||||
get: (id: string) => workspaces.get(id) ?? null,
|
||||
getMindPath: (id: string) => path.join(tmpDir, 'workspaces', id, 'workspace.mind'),
|
||||
};
|
||||
}
|
||||
|
||||
const noopActivate = (_id: string) => true;
|
||||
|
||||
/**
|
||||
* Simulate what buildSystemPrompt does: build a base prompt, then conditionally
|
||||
* append the workspace context. This mirrors the injection logic in chat.ts.
|
||||
*/
|
||||
function simulatePromptBuild(basePrompt: string, workspaceId?: string, wsManager?: ReturnType<typeof makeManager>) {
|
||||
async function simulatePromptBuild(basePrompt: string, workspaceId?: string, wsManager?: ReturnType<typeof makeManager>) {
|
||||
let prompt = basePrompt;
|
||||
|
||||
if (workspaceId && wsManager) {
|
||||
try {
|
||||
const nowBlock = buildWorkspaceNowBlock({
|
||||
const nowBlock = await buildWorkspaceNowBlock({
|
||||
dataDir: tmpDir,
|
||||
workspaceId,
|
||||
wsManager,
|
||||
activateWorkspaceMind: noopActivate,
|
||||
waggleDb,
|
||||
memory,
|
||||
});
|
||||
if (nowBlock) {
|
||||
prompt += '\n\n' + formatWorkspaceNowPrompt(nowBlock);
|
||||
@@ -120,9 +117,9 @@ describe('Context Injection — system prompt integration', () => {
|
||||
|
||||
// ── Test 1: No workspaceId → no "Workspace Now" section ─────────────
|
||||
|
||||
it('buildSystemPrompt without workspaceId produces no "Workspace Now" section', () => {
|
||||
it('buildSystemPrompt without workspaceId produces no "Workspace Now" section', async () => {
|
||||
const basePrompt = '# Who You Are\n\nYou are Waggle.';
|
||||
const result = simulatePromptBuild(basePrompt);
|
||||
const result = await simulatePromptBuild(basePrompt);
|
||||
|
||||
expect(result).not.toContain('# Workspace Now');
|
||||
expect(result).toBe(basePrompt);
|
||||
@@ -130,15 +127,15 @@ describe('Context Injection — system prompt integration', () => {
|
||||
|
||||
// ── Test 2: With workspaceId + data → includes "Workspace Now" ──────
|
||||
|
||||
it('buildSystemPrompt with workspaceId for workspace with data includes "Workspace Now"', () => {
|
||||
it('buildSystemPrompt with workspaceId for workspace with data includes "Workspace Now"', async () => {
|
||||
const wsManager = makeManager(new Map([
|
||||
['rich-ws', { id: 'rich-ws', name: 'Rich Project' }],
|
||||
]));
|
||||
|
||||
setupWorkspace('rich-ws', {
|
||||
frames: [
|
||||
{ content: 'Working on the Waggle platform, a workspace-native AI agent.', importance: 'important' },
|
||||
{ content: 'Decision: Use SQLite for local persistence.', importance: 'critical' },
|
||||
await setupWorkspace('rich-ws', {
|
||||
memories: [
|
||||
{ text: 'Working on the Waggle platform, a workspace-native AI agent.', importance: 'important' },
|
||||
{ text: 'Decision: Use SQLite for local persistence.', importance: 'critical' },
|
||||
],
|
||||
sessions: [
|
||||
{
|
||||
@@ -152,7 +149,7 @@ describe('Context Injection — system prompt integration', () => {
|
||||
});
|
||||
|
||||
const basePrompt = '# Who You Are\n\nYou are Waggle.';
|
||||
const result = simulatePromptBuild(basePrompt, 'rich-ws', wsManager);
|
||||
const result = await simulatePromptBuild(basePrompt, 'rich-ws', wsManager);
|
||||
|
||||
expect(result).toContain('# Workspace Now');
|
||||
expect(result).toContain('Rich Project');
|
||||
@@ -166,12 +163,12 @@ describe('Context Injection — system prompt integration', () => {
|
||||
|
||||
// ── Test 3: With workspaceId for empty/missing workspace → graceful ─
|
||||
|
||||
it('buildSystemPrompt with workspaceId for empty workspace has no "Workspace Now" (graceful)', () => {
|
||||
it('buildSystemPrompt with workspaceId for empty workspace has no "Workspace Now" (graceful)', async () => {
|
||||
const wsManager = makeManager(new Map([
|
||||
['empty-ws', { id: 'empty-ws', name: 'Empty Project' }],
|
||||
]));
|
||||
|
||||
// Create workspace dir but no mind file
|
||||
// Create the workspace directory but no memories
|
||||
const wsDir = path.join(tmpDir, 'workspaces', 'empty-ws');
|
||||
fs.mkdirSync(wsDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
@@ -180,17 +177,17 @@ describe('Context Injection — system prompt integration', () => {
|
||||
);
|
||||
|
||||
const basePrompt = '# Who You Are\n\nYou are Waggle.';
|
||||
const result = simulatePromptBuild(basePrompt, 'empty-ws', wsManager);
|
||||
const result = await simulatePromptBuild(basePrompt, 'empty-ws', wsManager);
|
||||
|
||||
expect(result).not.toContain('# Workspace Now');
|
||||
expect(result).toBe(basePrompt);
|
||||
});
|
||||
|
||||
it('buildSystemPrompt with workspaceId for non-existent workspace has no "Workspace Now"', () => {
|
||||
it('buildSystemPrompt with workspaceId for non-existent workspace has no "Workspace Now"', async () => {
|
||||
const wsManager = makeManager(new Map());
|
||||
|
||||
const basePrompt = '# Who You Are\n\nYou are Waggle.';
|
||||
const result = simulatePromptBuild(basePrompt, 'does-not-exist', wsManager);
|
||||
const result = await simulatePromptBuild(basePrompt, 'does-not-exist', wsManager);
|
||||
|
||||
expect(result).not.toContain('# Workspace Now');
|
||||
expect(result).toBe(basePrompt);
|
||||
@@ -198,29 +195,29 @@ describe('Context Injection — system prompt integration', () => {
|
||||
|
||||
// ── Test 4: Cache invalidation — different workspaceId → different prompt ─
|
||||
|
||||
it('different workspaceId produces different prompt content', () => {
|
||||
it('different workspaceId produces different prompt content', async () => {
|
||||
const wsManager = makeManager(new Map([
|
||||
['ws-a', { id: 'ws-a', name: 'Project Alpha' }],
|
||||
['ws-b', { id: 'ws-b', name: 'Project Beta' }],
|
||||
]));
|
||||
|
||||
setupWorkspace('ws-a', {
|
||||
frames: [
|
||||
{ content: 'Alpha is a front-end framework project.', importance: 'important' },
|
||||
{ content: 'Decision: Use React for Alpha.', importance: 'critical' },
|
||||
await setupWorkspace('ws-a', {
|
||||
memories: [
|
||||
{ text: 'Alpha is a front-end framework project.', importance: 'important' },
|
||||
{ text: 'Decision: Use React for Alpha.', importance: 'critical' },
|
||||
],
|
||||
});
|
||||
|
||||
setupWorkspace('ws-b', {
|
||||
frames: [
|
||||
{ content: 'Beta is a backend API project.', importance: 'important' },
|
||||
{ content: 'Decision: Use Rust for Beta.', importance: 'critical' },
|
||||
await setupWorkspace('ws-b', {
|
||||
memories: [
|
||||
{ text: 'Beta is a backend API project.', importance: 'important' },
|
||||
{ text: 'Decision: Use Rust for Beta.', importance: 'critical' },
|
||||
],
|
||||
});
|
||||
|
||||
const basePrompt = '# Who You Are\n\nYou are Waggle.';
|
||||
const promptA = simulatePromptBuild(basePrompt, 'ws-a', wsManager);
|
||||
const promptB = simulatePromptBuild(basePrompt, 'ws-b', wsManager);
|
||||
const promptA = await simulatePromptBuild(basePrompt, 'ws-a', wsManager);
|
||||
const promptB = await simulatePromptBuild(basePrompt, 'ws-b', wsManager);
|
||||
|
||||
// Both should have Workspace Now
|
||||
expect(promptA).toContain('# Workspace Now');
|
||||
@@ -238,19 +235,19 @@ describe('Context Injection — system prompt integration', () => {
|
||||
|
||||
// ── Test 5: Verify the formatted block is positioned correctly ──────
|
||||
|
||||
it('workspace context is appended after the base prompt, not prepended', () => {
|
||||
it('workspace context is appended after the base prompt, not prepended', async () => {
|
||||
const wsManager = makeManager(new Map([
|
||||
['pos-ws', { id: 'pos-ws', name: 'Position Test' }],
|
||||
]));
|
||||
|
||||
setupWorkspace('pos-ws', {
|
||||
frames: [
|
||||
{ content: 'Testing prompt positioning.', importance: 'important' },
|
||||
await setupWorkspace('pos-ws', {
|
||||
memories: [
|
||||
{ text: 'Testing prompt positioning.', importance: 'important' },
|
||||
],
|
||||
});
|
||||
|
||||
const basePrompt = 'BASE_PROMPT_START\nSome agent instructions.\nBASE_PROMPT_END';
|
||||
const result = simulatePromptBuild(basePrompt, 'pos-ws', wsManager);
|
||||
const result = await simulatePromptBuild(basePrompt, 'pos-ws', wsManager);
|
||||
|
||||
// Base prompt should appear first
|
||||
expect(result.startsWith('BASE_PROMPT_START')).toBe(true);
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { MindDB, WaggleDB } from '@waggle/core';
|
||||
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(() => {
|
||||
@@ -24,9 +32,9 @@ describe('workspace-context', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Helper: create a workspace directory structure with a mind DB
|
||||
function setupWorkspace(id: string, opts?: {
|
||||
frames?: Array<{ content: string; importance: string }>;
|
||||
// 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);
|
||||
@@ -38,24 +46,8 @@ describe('workspace-context', () => {
|
||||
JSON.stringify({ id, name: `Test Workspace ${id}`, group: 'test', created: new Date().toISOString() }),
|
||||
);
|
||||
|
||||
// Create mind DB with frames
|
||||
const mindPath = path.join(wsDir, 'workspace.mind');
|
||||
if (opts?.frames && opts.frames.length > 0) {
|
||||
const db = new MindDB(mindPath);
|
||||
const raw = db.getDatabase();
|
||||
// Insert a session first (frames require a session via gop_id FK)
|
||||
raw.prepare(
|
||||
`INSERT INTO sessions (gop_id, status, started_at)
|
||||
VALUES ('session:test', 'active', datetime('now'))`
|
||||
).run();
|
||||
|
||||
for (const frame of opts.frames) {
|
||||
raw.prepare(
|
||||
`INSERT INTO memory_frames (gop_id, frame_type, content, importance, created_at)
|
||||
VALUES ('session:test', 'I', ?, ?, datetime('now'))`
|
||||
).run(frame.content, frame.importance);
|
||||
}
|
||||
db.close();
|
||||
for (const memo of opts?.memories ?? []) {
|
||||
await memory.remember({ scope: workspaceScope(id), text: memo.text, importance: memo.importance });
|
||||
}
|
||||
|
||||
// Create session files
|
||||
@@ -76,29 +68,26 @@ describe('workspace-context', () => {
|
||||
}
|
||||
}
|
||||
|
||||
return { mindPath, wsDir };
|
||||
return { wsDir };
|
||||
}
|
||||
|
||||
function makeManager(workspaces: Map<string, { id: string; name: string }>) {
|
||||
return {
|
||||
get: (id: string) => workspaces.get(id) ?? null,
|
||||
getMindPath: (id: string) => path.join(tmpDir, 'workspaces', id, 'workspace.mind'),
|
||||
};
|
||||
}
|
||||
|
||||
const noopActivate = (_id: string) => true;
|
||||
|
||||
// ── Test 1: Returns null for non-existent workspace ──────────────
|
||||
|
||||
it('returns null for non-existent workspace', () => {
|
||||
it('returns null for non-existent workspace', async () => {
|
||||
const wsManager = makeManager(new Map());
|
||||
|
||||
const result = buildWorkspaceNowBlock({
|
||||
const result = await buildWorkspaceNowBlock({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'does-not-exist',
|
||||
wsManager,
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
@@ -106,43 +95,20 @@ describe('workspace-context', () => {
|
||||
|
||||
// ── Test 2: Returns null for workspace with no data ──────────────
|
||||
|
||||
it('returns null for workspace with no mind file', () => {
|
||||
const wsDir = path.join(tmpDir, 'workspaces', 'empty-ws');
|
||||
fs.mkdirSync(wsDir, { recursive: true });
|
||||
|
||||
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 = buildWorkspaceNowBlock({
|
||||
const result = await buildWorkspaceNowBlock({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'empty-ws',
|
||||
wsManager,
|
||||
activateWorkspaceMind: noopActivate,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for workspace with mind file but zero frames', () => {
|
||||
const wsManager = makeManager(new Map([
|
||||
['zero-ws', { id: 'zero-ws', name: 'Zero Frames' }],
|
||||
]));
|
||||
|
||||
// Create a mind DB with no frames
|
||||
setupWorkspace('zero-ws', { frames: [] });
|
||||
// MindDB file exists but has no frames — we need the file to exist
|
||||
const mindPath = path.join(tmpDir, 'workspaces', 'zero-ws', 'workspace.mind');
|
||||
const db = new MindDB(mindPath);
|
||||
db.close();
|
||||
|
||||
const result = buildWorkspaceNowBlock({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'zero-ws',
|
||||
wsManager,
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
@@ -150,17 +116,16 @@ describe('workspace-context', () => {
|
||||
|
||||
// ── Test 3: Returns correctly shaped block ───────────────────────
|
||||
|
||||
it('returns correctly shaped block for workspace with data', () => {
|
||||
it('returns correctly shaped block for workspace with data', async () => {
|
||||
const wsManager = makeManager(new Map([
|
||||
['rich-ws', { id: 'rich-ws', name: 'Rich Workspace' }],
|
||||
]));
|
||||
const activateWorkspaceMind = vi.fn(() => true);
|
||||
|
||||
setupWorkspace('rich-ws', {
|
||||
frames: [
|
||||
{ content: 'Working on the Waggle project, a workspace-native AI agent platform.', importance: 'important' },
|
||||
{ content: 'Decision: Use SQLite for local storage instead of PostgreSQL.', importance: 'critical' },
|
||||
{ content: 'Implemented the memory frame system with FTS5 search.', importance: 'normal' },
|
||||
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: [
|
||||
{
|
||||
@@ -173,16 +138,15 @@ describe('workspace-context', () => {
|
||||
],
|
||||
});
|
||||
|
||||
const result = buildWorkspaceNowBlock({
|
||||
const result = await buildWorkspaceNowBlock({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'rich-ws',
|
||||
wsManager,
|
||||
activateWorkspaceMind,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(activateWorkspaceMind).not.toHaveBeenCalled();
|
||||
expect(result!.workspaceName).toBe('Rich Workspace');
|
||||
expect(result!.summary).toBeTruthy();
|
||||
expect(result!.summary.length).toBeGreaterThan(10);
|
||||
@@ -198,15 +162,15 @@ describe('workspace-context', () => {
|
||||
|
||||
// ── Test 4: Caps at correct limits ───────────────────────────────
|
||||
|
||||
it('caps decisions at 3, threads at 3, progress at 5', () => {
|
||||
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 frames = [];
|
||||
const memories: Array<{ text: string; importance: MemoryImportance }> = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
frames.push({ content: `Decision: chose option ${i} for the architecture component ${i}`, importance: 'critical' as const });
|
||||
memories.push({ text: `Decision: chose option ${i} for the architecture component ${i}`, importance: 'critical' as const });
|
||||
}
|
||||
|
||||
const sessions = [];
|
||||
@@ -220,14 +184,14 @@ describe('workspace-context', () => {
|
||||
});
|
||||
}
|
||||
|
||||
setupWorkspace('capped-ws', { frames, sessions });
|
||||
await setupWorkspace('capped-ws', { memories, sessions });
|
||||
|
||||
const result = buildWorkspaceNowBlock({
|
||||
const result = await buildWorkspaceNowBlock({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'capped-ws',
|
||||
wsManager,
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
|
||||
@@ -1,22 +1,32 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { AwarenessLayer, MindDB, WaggleDB, workspaceDataScope, type AwarenessCategory } from '@waggle/core';
|
||||
import { AwarenessLayer, WaggleDB, workspaceDataScope, type AwarenessCategory } from '@waggle/core';
|
||||
import {
|
||||
createInMemoryMemoryStore,
|
||||
workspaceScope,
|
||||
type MemoryImportance,
|
||||
type MemoryKind,
|
||||
type MemoryStore,
|
||||
} from '@waggle/memory-contract';
|
||||
import {
|
||||
buildWorkspaceState,
|
||||
formatWorkspaceStatePrompt,
|
||||
computeFreshness,
|
||||
listByImportance,
|
||||
type WorkspaceState,
|
||||
} from '../../src/local/workspace-state.js';
|
||||
|
||||
describe('workspace-state', () => {
|
||||
let tmpDir: string;
|
||||
let waggleDb: WaggleDB;
|
||||
let memory: MemoryStore;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-ws-state-'));
|
||||
waggleDb = WaggleDB.openInDataDir(tmpDir);
|
||||
memory = createInMemoryMemoryStore();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -24,8 +34,8 @@ describe('workspace-state', () => {
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* */ }
|
||||
});
|
||||
|
||||
function setupWorkspace(id: string, opts?: {
|
||||
frames?: Array<{ content: string; importance: string; created_at?: string }>;
|
||||
async function setupWorkspace(id: string, opts?: {
|
||||
memories?: Array<{ text: string; importance: MemoryImportance; kind?: MemoryKind }>;
|
||||
sessions?: Array<{
|
||||
title: string;
|
||||
messages: Array<{ role: string; content: string }>;
|
||||
@@ -36,24 +46,13 @@ describe('workspace-state', () => {
|
||||
const wsDir = path.join(tmpDir, 'workspaces', id);
|
||||
fs.mkdirSync(wsDir, { recursive: true });
|
||||
|
||||
const mindPath = path.join(wsDir, 'workspace.mind');
|
||||
if (opts?.frames && opts.frames.length > 0) {
|
||||
const db = new MindDB(mindPath);
|
||||
const raw = db.getDatabase();
|
||||
raw.prepare(
|
||||
`INSERT INTO sessions (gop_id, status, started_at)
|
||||
VALUES ('session:test', 'active', datetime('now'))`,
|
||||
).run();
|
||||
|
||||
for (const frame of opts.frames) {
|
||||
const createdAt = frame.created_at ?? new Date().toISOString();
|
||||
raw.prepare(
|
||||
`INSERT INTO memory_frames (gop_id, frame_type, content, importance, created_at)
|
||||
VALUES ('session:test', 'I', ?, ?, ?)`,
|
||||
).run(frame.content, frame.importance, createdAt);
|
||||
}
|
||||
|
||||
db.close();
|
||||
for (const memo of opts?.memories ?? []) {
|
||||
await memory.remember({
|
||||
scope: workspaceScope(id),
|
||||
text: memo.text,
|
||||
importance: memo.importance,
|
||||
...(memo.kind ? { kind: memo.kind } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
// Awareness items live in waggle.db under the workspace's scope, not in the mind.
|
||||
@@ -87,18 +86,15 @@ describe('workspace-state', () => {
|
||||
}
|
||||
}
|
||||
|
||||
return { mindPath, wsDir };
|
||||
return { wsDir };
|
||||
}
|
||||
|
||||
function makeManager(workspaces: Map<string, { id: string; name: string }>) {
|
||||
return {
|
||||
get: (id: string) => workspaces.get(id) ?? null,
|
||||
getMindPath: (id: string) => path.join(tmpDir, 'workspaces', id, 'workspace.mind'),
|
||||
};
|
||||
}
|
||||
|
||||
const noopActivate = (_id: string) => true;
|
||||
|
||||
// ── computeFreshness ──────────────────────────────────────────
|
||||
|
||||
describe('computeFreshness', () => {
|
||||
@@ -122,76 +118,104 @@ describe('workspace-state', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── listByImportance ──────────────────────────────────────────
|
||||
|
||||
describe('listByImportance', () => {
|
||||
it('lists the most important memories first and skips temporary ones', async () => {
|
||||
const scope = workspaceScope('ws');
|
||||
const seed: Array<[string, MemoryImportance]> = [
|
||||
['normal one', 'normal'],
|
||||
['critical one', 'critical'],
|
||||
['temporary one', 'temporary'],
|
||||
['important one', 'important'],
|
||||
['normal two', 'normal'],
|
||||
];
|
||||
for (const [text, importance] of seed) await memory.remember({ scope, text, importance });
|
||||
|
||||
expect((await listByImportance(memory, scope, 2)).map(r => r.text))
|
||||
.toEqual(['critical one', 'important one']);
|
||||
const all = (await listByImportance(memory, scope, 10)).map(r => r.text);
|
||||
expect(all.slice(0, 2)).toEqual(['critical one', 'important one']);
|
||||
expect(all.slice(2).sort()).toEqual(['normal one', 'normal two']);
|
||||
});
|
||||
});
|
||||
|
||||
// ── buildWorkspaceState ───────────────────────────────────────
|
||||
|
||||
describe('buildWorkspaceState', () => {
|
||||
it('returns null for non-existent workspace', () => {
|
||||
const result = buildWorkspaceState({
|
||||
it('returns null for non-existent workspace', async () => {
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'nonexistent',
|
||||
wsManager: makeManager(new Map()),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for workspace with no mind file', () => {
|
||||
const wsDir = path.join(tmpDir, 'workspaces', 'empty');
|
||||
fs.mkdirSync(wsDir, { recursive: true });
|
||||
it('returns null for workspace with no memories', async () => {
|
||||
await setupWorkspace('empty');
|
||||
// Another workspace's memories do not count.
|
||||
await setupWorkspace('other', { memories: [{ text: 'Other workspace memory', importance: 'normal' }] });
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'empty',
|
||||
wsManager: makeManager(new Map([['empty', { id: 'empty', name: 'Empty' }]])),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for workspace with zero memory frames', () => {
|
||||
fs.mkdirSync(path.join(tmpDir, 'workspaces', 'noframes'), { recursive: true });
|
||||
const db = new MindDB(path.join(tmpDir, 'workspaces', 'noframes', 'workspace.mind'));
|
||||
db.close();
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'noframes',
|
||||
wsManager: makeManager(new Map([['noframes', { id: 'noframes', name: 'No Frames' }]])),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns state with decisions from memory frames', () => {
|
||||
const activateWorkspaceMind = vi.fn(() => true);
|
||||
setupWorkspace('ws1', {
|
||||
frames: [
|
||||
{ content: 'Decision: Use SQLite for local storage', importance: 'critical' },
|
||||
{ content: 'Working on the authentication module', importance: 'normal' },
|
||||
it('returns state with decisions from workspace memory', async () => {
|
||||
await setupWorkspace('ws1', {
|
||||
memories: [
|
||||
{ text: 'Decision: Use SQLite for local storage', importance: 'critical' },
|
||||
{ text: 'Working on the authentication module', importance: 'normal' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws1',
|
||||
wsManager: makeManager(new Map([['ws1', { id: 'ws1', name: 'Project Alpha' }]])),
|
||||
activateWorkspaceMind,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(activateWorkspaceMind).not.toHaveBeenCalled();
|
||||
expect(result!.recentDecisions.length).toBeGreaterThanOrEqual(1);
|
||||
expect(result!.recentDecisions[0].content).toContain('SQLite');
|
||||
expect(result!.recentDecisions[0].source).toBe('memory');
|
||||
});
|
||||
|
||||
it('extracts pending tasks from sessions', () => {
|
||||
setupWorkspace('ws2', {
|
||||
frames: [{ content: 'Project context established', importance: 'normal' }],
|
||||
it('takes decisions from their kind or wording, never from temporary memories', async () => {
|
||||
await setupWorkspace('ws8', {
|
||||
memories: [
|
||||
{ text: 'Ship on Fridays only', importance: 'normal', kind: 'decision' },
|
||||
{ text: 'We agreed to keep the old API', importance: 'normal' },
|
||||
{ text: 'Decision: scratch idea', importance: 'temporary' },
|
||||
{ text: 'Lunch was good', importance: 'normal' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws8',
|
||||
wsManager: makeManager(new Map([['ws8', { id: 'ws8', name: 'Decisions' }]])),
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result!.recentDecisions.map(d => d.content).sort())
|
||||
.toEqual(['Ship on Fridays only', 'We agreed to keep the old API']);
|
||||
});
|
||||
|
||||
it('extracts pending tasks from sessions', async () => {
|
||||
await setupWorkspace('ws2', {
|
||||
memories: [{ text: 'Project context established', importance: 'normal' }],
|
||||
sessions: [{
|
||||
title: 'Planning',
|
||||
messages: [
|
||||
@@ -202,12 +226,12 @@ describe('workspace-state', () => {
|
||||
}],
|
||||
});
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws2',
|
||||
wsManager: makeManager(new Map([['ws2', { id: 'ws2', name: 'API Project' }]])),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
@@ -216,9 +240,9 @@ describe('workspace-state', () => {
|
||||
expect(result!.pending.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('extracts open questions from sessions', () => {
|
||||
setupWorkspace('ws3', {
|
||||
frames: [{ content: 'Working on infrastructure', importance: 'normal' }],
|
||||
it('extracts open questions from sessions', async () => {
|
||||
await setupWorkspace('ws3', {
|
||||
memories: [{ text: 'Working on infrastructure', importance: 'normal' }],
|
||||
sessions: [{
|
||||
title: 'Infra discussion',
|
||||
messages: [
|
||||
@@ -229,22 +253,22 @@ describe('workspace-state', () => {
|
||||
}],
|
||||
});
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws3',
|
||||
wsManager: makeManager(new Map([['ws3', { id: 'ws3', name: 'Infra' }]])),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.openQuestions.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('classifies fresh and stale threads', () => {
|
||||
it('classifies fresh and stale threads', async () => {
|
||||
const tenDays = 10 * 24 * 60 * 60 * 1000;
|
||||
setupWorkspace('ws4', {
|
||||
frames: [{ content: 'Multi-thread workspace', importance: 'normal' }],
|
||||
await setupWorkspace('ws4', {
|
||||
memories: [{ text: 'Multi-thread workspace', importance: 'normal' }],
|
||||
sessions: [
|
||||
{
|
||||
title: 'Fresh thread',
|
||||
@@ -264,12 +288,12 @@ describe('workspace-state', () => {
|
||||
],
|
||||
});
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws4',
|
||||
wsManager: makeManager(new Map([['ws4', { id: 'ws4', name: 'Multi' }]])),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
@@ -279,9 +303,9 @@ describe('workspace-state', () => {
|
||||
expect(result!.stale.some(s => s.content === 'Old thread')).toBe(true);
|
||||
});
|
||||
|
||||
it('derives nextActions from blockers and pending items', () => {
|
||||
setupWorkspace('ws5', {
|
||||
frames: [{ content: 'Active project', importance: 'normal' }],
|
||||
it('derives nextActions from blockers and pending items', async () => {
|
||||
await setupWorkspace('ws5', {
|
||||
memories: [{ text: 'Active project', importance: 'normal' }],
|
||||
sessions: [{
|
||||
title: 'Work session',
|
||||
messages: [
|
||||
@@ -292,12 +316,12 @@ describe('workspace-state', () => {
|
||||
}],
|
||||
});
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws5',
|
||||
wsManager: makeManager(new Map([['ws5', { id: 'ws5', name: 'Blocked' }]])),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
@@ -308,11 +332,11 @@ describe('workspace-state', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('returns all expected fields', () => {
|
||||
setupWorkspace('ws6', {
|
||||
frames: [
|
||||
{ content: 'Decision: Use React for frontend', importance: 'critical' },
|
||||
{ content: 'Project initialized', importance: 'normal' },
|
||||
it('returns all expected fields', async () => {
|
||||
await setupWorkspace('ws6', {
|
||||
memories: [
|
||||
{ text: 'Decision: Use React for frontend', importance: 'critical' },
|
||||
{ text: 'Project initialized', importance: 'normal' },
|
||||
],
|
||||
sessions: [{
|
||||
title: 'Setup session',
|
||||
@@ -323,12 +347,12 @@ describe('workspace-state', () => {
|
||||
}],
|
||||
});
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws6',
|
||||
wsManager: makeManager(new Map([['ws6', { id: 'ws6', name: 'Full' }]])),
|
||||
activateWorkspaceMind: noopActivate,
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
@@ -344,9 +368,9 @@ describe('workspace-state', () => {
|
||||
expect(Array.isArray(result!.nextActions)).toBe(true);
|
||||
});
|
||||
|
||||
it("lists the workspace's awareness items from waggle.db as active, not other scopes", () => {
|
||||
setupWorkspace('ws7', {
|
||||
frames: [{ content: 'Project with open tasks', importance: 'normal' }],
|
||||
it("lists the workspace's awareness items from waggle.db as active, not other scopes", async () => {
|
||||
await setupWorkspace('ws7', {
|
||||
memories: [{ text: 'Project with open tasks', importance: 'normal' }],
|
||||
awareness: [
|
||||
{ category: 'task', content: 'Ship the installer', priority: 2 },
|
||||
{ category: 'flag', content: 'Context flag only', priority: 1 },
|
||||
@@ -355,11 +379,12 @@ describe('workspace-state', () => {
|
||||
new AwarenessLayer(waggleDb).add('task', 'Personal errand', 5);
|
||||
new AwarenessLayer(waggleDb, workspaceDataScope('other')).add('task', 'Other workspace task', 5);
|
||||
|
||||
const result = buildWorkspaceState({
|
||||
const result = await buildWorkspaceState({
|
||||
dataDir: tmpDir,
|
||||
waggleDb,
|
||||
workspaceId: 'ws7',
|
||||
wsManager: makeManager(new Map([['ws7', { id: 'ws7', name: 'Tasks' }]])),
|
||||
memory,
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
|
||||
Reference in New Issue
Block a user