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:
shumeiko.it
2026-10-24 12:50:07 +02:00
parent 4a1c4c4c8e
commit e9ed8c0765
23 changed files with 823 additions and 857 deletions

View File

@@ -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();