- 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.
494 lines
18 KiB
TypeScript
494 lines
18 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 { 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(() => {
|
|
waggleDb.close();
|
|
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* */ }
|
|
});
|
|
|
|
async function setupWorkspace(id: string, opts?: {
|
|
memories?: Array<{ text: string; importance: MemoryImportance; kind?: MemoryKind }>;
|
|
sessions?: Array<{
|
|
title: string;
|
|
messages: Array<{ role: string; content: string }>;
|
|
ageMs?: number;
|
|
}>;
|
|
awareness?: Array<{ category: AwarenessCategory; content: string; priority: number }>;
|
|
}) {
|
|
const wsDir = path.join(tmpDir, 'workspaces', id);
|
|
fs.mkdirSync(wsDir, { recursive: true });
|
|
|
|
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.
|
|
if (opts?.awareness) {
|
|
const awareness = new AwarenessLayer(waggleDb, workspaceDataScope(id));
|
|
for (const item of opts.awareness) {
|
|
awareness.add(item.category, item.content, item.priority);
|
|
}
|
|
}
|
|
|
|
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 created = new Date(Date.now() - (sess.ageMs ?? 0)).toISOString();
|
|
const lines: string[] = [
|
|
JSON.stringify({ type: 'meta', title: sess.title, created }),
|
|
];
|
|
for (const msg of sess.messages) {
|
|
lines.push(JSON.stringify({ role: msg.role, content: msg.content }));
|
|
}
|
|
const filePath = path.join(sessDir, `${sessionId}.jsonl`);
|
|
fs.writeFileSync(filePath, lines.join('\n') + '\n');
|
|
if (sess.ageMs) {
|
|
const pastTime = new Date(Date.now() - sess.ageMs);
|
|
fs.utimesSync(filePath, pastTime, pastTime);
|
|
}
|
|
}
|
|
}
|
|
|
|
return { wsDir };
|
|
}
|
|
|
|
function makeManager(workspaces: Map<string, { id: string; name: string }>) {
|
|
return {
|
|
get: (id: string) => workspaces.get(id) ?? null,
|
|
};
|
|
}
|
|
|
|
// ── computeFreshness ──────────────────────────────────────────
|
|
|
|
describe('computeFreshness', () => {
|
|
it('returns fresh for today', () => {
|
|
expect(computeFreshness(new Date().toISOString())).toBe('fresh');
|
|
});
|
|
|
|
it('returns fresh for 1 day ago', () => {
|
|
const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
|
|
expect(computeFreshness(yesterday)).toBe('fresh');
|
|
});
|
|
|
|
it('returns aging for 3 days ago', () => {
|
|
const threeDays = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString();
|
|
expect(computeFreshness(threeDays)).toBe('aging');
|
|
});
|
|
|
|
it('returns stale for 10 days ago', () => {
|
|
const tenDays = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString();
|
|
expect(computeFreshness(tenDays)).toBe('stale');
|
|
});
|
|
});
|
|
|
|
// ── 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', async () => {
|
|
const result = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'nonexistent',
|
|
wsManager: makeManager(new Map()),
|
|
memory,
|
|
});
|
|
expect(result).toBeNull();
|
|
});
|
|
|
|
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 = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'empty',
|
|
wsManager: makeManager(new Map([['empty', { id: 'empty', name: 'Empty' }]])),
|
|
memory,
|
|
});
|
|
expect(result).toBeNull();
|
|
});
|
|
|
|
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 = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'ws1',
|
|
wsManager: makeManager(new Map([['ws1', { id: 'ws1', name: 'Project Alpha' }]])),
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
expect(result!.recentDecisions.length).toBeGreaterThanOrEqual(1);
|
|
expect(result!.recentDecisions[0].content).toContain('SQLite');
|
|
expect(result!.recentDecisions[0].source).toBe('memory');
|
|
});
|
|
|
|
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: [
|
|
{ role: 'user', content: 'We need to implement the rate limiting middleware for the API' },
|
|
{ role: 'assistant', content: 'I will add that to the plan.' },
|
|
{ role: 'user', content: 'Also, we should add comprehensive error handling to the service layer' },
|
|
],
|
|
}],
|
|
});
|
|
|
|
const result = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'ws2',
|
|
wsManager: makeManager(new Map([['ws2', { id: 'ws2', name: 'API Project' }]])),
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
// pending items come from TASK_PATTERNS in extractProgressItems
|
|
// "need to" triggers task pattern
|
|
expect(result!.pending.length).toBeGreaterThanOrEqual(1);
|
|
});
|
|
|
|
it('extracts open questions from sessions', async () => {
|
|
await setupWorkspace('ws3', {
|
|
memories: [{ text: 'Working on infrastructure', importance: 'normal' }],
|
|
sessions: [{
|
|
title: 'Infra discussion',
|
|
messages: [
|
|
{ role: 'user', content: 'Should we use containers or bare metal for the deployment?' },
|
|
{ role: 'assistant', content: 'Both have tradeoffs.' },
|
|
{ role: 'user', content: 'We still need to decide on the hosting provider strategy.' },
|
|
],
|
|
}],
|
|
});
|
|
|
|
const result = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'ws3',
|
|
wsManager: makeManager(new Map([['ws3', { id: 'ws3', name: 'Infra' }]])),
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
expect(result!.openQuestions.length).toBeGreaterThanOrEqual(1);
|
|
});
|
|
|
|
it('classifies fresh and stale threads', async () => {
|
|
const tenDays = 10 * 24 * 60 * 60 * 1000;
|
|
await setupWorkspace('ws4', {
|
|
memories: [{ text: 'Multi-thread workspace', importance: 'normal' }],
|
|
sessions: [
|
|
{
|
|
title: 'Fresh thread',
|
|
messages: [
|
|
{ role: 'user', content: 'Working on fresh stuff right now.' },
|
|
{ role: 'assistant', content: 'On it.' },
|
|
],
|
|
},
|
|
{
|
|
title: 'Old thread',
|
|
messages: [
|
|
{ role: 'user', content: 'This was from ten days ago.' },
|
|
{ role: 'assistant', content: 'Noted.' },
|
|
],
|
|
ageMs: tenDays,
|
|
},
|
|
],
|
|
});
|
|
|
|
const result = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'ws4',
|
|
wsManager: makeManager(new Map([['ws4', { id: 'ws4', name: 'Multi' }]])),
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
// Fresh session should appear in active
|
|
expect(result!.active.some(a => a.content === 'Fresh thread')).toBe(true);
|
|
// Stale session should appear in stale
|
|
expect(result!.stale.some(s => s.content === 'Old thread')).toBe(true);
|
|
});
|
|
|
|
it('derives nextActions from blockers and pending items', async () => {
|
|
await setupWorkspace('ws5', {
|
|
memories: [{ text: 'Active project', importance: 'normal' }],
|
|
sessions: [{
|
|
title: 'Work session',
|
|
messages: [
|
|
{ role: 'user', content: 'We are blocked by the missing SSL certificate for the staging server' },
|
|
{ role: 'assistant', content: 'That is a critical blocker.' },
|
|
{ role: 'user', content: 'We need to update the CI pipeline configuration as well' },
|
|
],
|
|
}],
|
|
});
|
|
|
|
const result = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'ws5',
|
|
wsManager: makeManager(new Map([['ws5', { id: 'ws5', name: 'Blocked' }]])),
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
expect(result!.nextActions.length).toBeGreaterThanOrEqual(1);
|
|
// Blockers should appear first in nextActions
|
|
if (result!.blocked.length > 0) {
|
|
expect(result!.nextActions[0]).toContain('Resolve:');
|
|
}
|
|
});
|
|
|
|
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',
|
|
messages: [
|
|
{ role: 'user', content: 'Let us set up the project structure.' },
|
|
{ role: 'assistant', content: 'I will create the scaffold.' },
|
|
],
|
|
}],
|
|
});
|
|
|
|
const result = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'ws6',
|
|
wsManager: makeManager(new Map([['ws6', { id: 'ws6', name: 'Full' }]])),
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
expect(result).toHaveProperty('active');
|
|
expect(result).toHaveProperty('openQuestions');
|
|
expect(result).toHaveProperty('pending');
|
|
expect(result).toHaveProperty('blocked');
|
|
expect(result).toHaveProperty('completed');
|
|
expect(result).toHaveProperty('stale');
|
|
expect(result).toHaveProperty('recentDecisions');
|
|
expect(result).toHaveProperty('nextActions');
|
|
expect(Array.isArray(result!.active)).toBe(true);
|
|
expect(Array.isArray(result!.nextActions)).toBe(true);
|
|
});
|
|
|
|
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 },
|
|
],
|
|
});
|
|
new AwarenessLayer(waggleDb).add('task', 'Personal errand', 5);
|
|
new AwarenessLayer(waggleDb, workspaceDataScope('other')).add('task', 'Other workspace task', 5);
|
|
|
|
const result = await buildWorkspaceState({
|
|
dataDir: tmpDir,
|
|
waggleDb,
|
|
workspaceId: 'ws7',
|
|
wsManager: makeManager(new Map([['ws7', { id: 'ws7', name: 'Tasks' }]])),
|
|
memory,
|
|
});
|
|
|
|
expect(result).not.toBeNull();
|
|
const fromAwareness = result!.active.filter(a => a.source === 'awareness');
|
|
expect(fromAwareness.map(a => a.content)).toEqual(['Ship the installer']);
|
|
});
|
|
});
|
|
|
|
// ── formatWorkspaceStatePrompt ────────────────────────────────
|
|
|
|
describe('formatWorkspaceStatePrompt', () => {
|
|
it('formats empty state with just the header', () => {
|
|
const state: WorkspaceState = {
|
|
active: [],
|
|
openQuestions: [],
|
|
pending: [],
|
|
blocked: [],
|
|
completed: [],
|
|
stale: [],
|
|
recentDecisions: [],
|
|
nextActions: [],
|
|
};
|
|
const result = formatWorkspaceStatePrompt(state, 'Test Workspace');
|
|
expect(result).toContain('# Workspace Now — Test Workspace');
|
|
expect(result).not.toContain('## Active');
|
|
});
|
|
|
|
it('includes Active section when there are active items', () => {
|
|
const state: WorkspaceState = {
|
|
active: [{
|
|
content: 'Working on auth',
|
|
freshness: 'fresh',
|
|
source: 'session',
|
|
dateLastTouched: '2026-03-14',
|
|
}],
|
|
openQuestions: [],
|
|
pending: [],
|
|
blocked: [],
|
|
completed: [],
|
|
stale: [],
|
|
recentDecisions: [],
|
|
nextActions: [],
|
|
};
|
|
const result = formatWorkspaceStatePrompt(state, 'Auth Project');
|
|
expect(result).toContain('## Active');
|
|
expect(result).toContain('Working on auth');
|
|
});
|
|
|
|
it('annotates aging items', () => {
|
|
const state: WorkspaceState = {
|
|
active: [{
|
|
content: 'Database migration',
|
|
freshness: 'aging',
|
|
source: 'session',
|
|
dateLastTouched: '2026-03-10',
|
|
}],
|
|
openQuestions: [],
|
|
pending: [],
|
|
blocked: [],
|
|
completed: [],
|
|
stale: [],
|
|
recentDecisions: [],
|
|
nextActions: [],
|
|
};
|
|
const result = formatWorkspaceStatePrompt(state, 'DB');
|
|
expect(result).toContain('(aging)');
|
|
});
|
|
|
|
it('includes all populated sections', () => {
|
|
const state: WorkspaceState = {
|
|
active: [{ content: 'Thread A', freshness: 'fresh', source: 'session', dateLastTouched: '2026-03-14' }],
|
|
openQuestions: [{ content: 'Which DB?', freshness: 'fresh', source: 'session', dateLastTouched: '2026-03-14' }],
|
|
pending: [{ content: 'Add tests', freshness: 'fresh', source: 'session', dateLastTouched: '2026-03-14' }],
|
|
blocked: [{ content: 'Missing API key', freshness: 'fresh', source: 'session', dateLastTouched: '2026-03-14' }],
|
|
completed: [{ content: 'Setup done', freshness: 'fresh', source: 'session', dateLastTouched: '2026-03-14' }],
|
|
stale: [{ content: 'Old thread', freshness: 'stale', source: 'session', dateLastTouched: '2026-03-01' }],
|
|
recentDecisions: [{ content: 'Use React', freshness: 'fresh', source: 'memory', dateLastTouched: '2026-03-14' }],
|
|
nextActions: ['Resolve: Missing API key', 'Add tests'],
|
|
};
|
|
const result = formatWorkspaceStatePrompt(state, 'Full');
|
|
expect(result).toContain('## Active');
|
|
expect(result).toContain('## Open Questions');
|
|
expect(result).toContain('## Blocked');
|
|
expect(result).toContain('## Pending');
|
|
expect(result).toContain('## Completed');
|
|
expect(result).toContain('## Needs Attention (stale)');
|
|
expect(result).toContain('## Recent Decisions');
|
|
expect(result).toContain('## Likely Next Actions');
|
|
});
|
|
|
|
it('marks stale items as not touched recently', () => {
|
|
const state: WorkspaceState = {
|
|
active: [],
|
|
openQuestions: [],
|
|
pending: [],
|
|
blocked: [],
|
|
completed: [],
|
|
stale: [{ content: 'Forgotten thread', freshness: 'stale', source: 'session', dateLastTouched: '2026-02-01' }],
|
|
recentDecisions: [],
|
|
nextActions: [],
|
|
};
|
|
const result = formatWorkspaceStatePrompt(state, 'Stale');
|
|
expect(result).toContain('not touched recently');
|
|
});
|
|
});
|
|
});
|