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

@@ -35,7 +35,7 @@ describe('local server default workspace wiring', () => {
const defaultWorkspaceId = server.workspaceManager.getDefault();
expect(defaultWorkspaceId).toBeTruthy();
expect(server.agentState.activeWorkspaceId).toBe(defaultWorkspaceId);
expect(server.agentState.getWorkspaceMindDb(defaultWorkspaceId!)).toBeTruthy();
expect(server.agentState.getWorkspaceMindDb('default')).toBeNull();
expect(server.agentState.orchestrator.getWorkspaceId()).toBe(defaultWorkspaceId);
expect(server.workspaceManager.get('default')).toBeNull();
});
});

View File

@@ -6,12 +6,11 @@
* (B8 / PRD §12.1 "greeting with user name") — unit + via inject.
* - applyPriorityRanking(): recency + bounded pending-item boost
* (PRD §12.1 "ranked by recency and priority") — unit.
* - needsReviewCount (J08/D6): personal-mind frames with metadata status
* 'unreviewed' are counted; the count matches what the Memory Center
* "Needs review" view lists.
* - needsReviewCount (J08/D6): extracted personal facts that are neither
* confirmed nor archived are counted.
*
* Scaffolding follows memory-center.test.ts: Fastify inject + MindDB(':memory:')
* + plain-object decorators, plus an in-memory waggle.db for the profile card.
* Scaffolding: Fastify inject + an in-memory memory store + plain-object
* decorators, plus an in-memory waggle.db for the profile card.
* localConfig is intentionally absent → the
* buildWorkspaceState call inside the briefing loop throws and is absorbed by
* the route's per-workspace try/catch (pendingCount degrades to 0), and
@@ -20,14 +19,14 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Fastify from 'fastify';
import { MindDB, IdentityLayer, WaggleDB } from '@waggle/core';
import { IdentityLayer, WaggleDB } from '@waggle/core';
import { createInMemoryMemoryStore, PERSONAL_SCOPE, workspaceScope, type MemoryStore } from '@waggle/memory-contract';
import {
homeRoutes,
personalizeGreeting,
applyPriorityRanking,
type RecentWorkspaceCard,
} from '../../src/local/routes/home.js';
import { memoryCenterRoutes } from '../../src/local/routes/memory-center.js';
import {
buildUpcomingSchedules,
type CronScheduleLike,
@@ -43,7 +42,7 @@ interface TestWorkspace {
}
function createTestServer(
db: MindDB,
memory: MemoryStore,
workspaces: TestWorkspace[] = [],
cronSchedules: CronScheduleLike[] = [],
) {
@@ -51,18 +50,7 @@ function createTestServer(
const waggleDb = new WaggleDB(':memory:');
server.decorate('waggleDb', waggleDb);
server.addHook('onClose', async () => waggleDb.close());
server.decorate('multiMind', {
personal: db,
getFrameStore: () => undefined,
search: () => [],
workspace: undefined,
setWorkspace: () => {},
});
server.decorate('agentState', {
getWorkspaceMindDb: () => undefined,
activateWorkspaceMind: () => undefined,
listWorkspaces: () => [],
});
server.decorate('memory', memory);
server.decorate('workspaceManager', {
list: () => workspaces,
get: (id: string) => workspaces.find((w) => w.id === id),
@@ -73,7 +61,6 @@ function createTestServer(
});
// localConfig intentionally absent — see file header.
server.register(homeRoutes);
server.register(memoryCenterRoutes);
return server;
}
@@ -128,17 +115,16 @@ describe('applyPriorityRanking (P2 — recency + pending boost)', () => {
});
describe('GET /api/home/briefing (P2 — J08 needsReviewCount + greeting)', () => {
let db: MindDB;
let memory: MemoryStore;
let server: ReturnType<typeof Fastify>;
afterEach(async () => {
await server.close();
db.close();
});
function boot(workspaces: TestWorkspace[] = []) {
db = new MindDB(':memory:');
server = createTestServer(db, workspaces);
memory = createInMemoryMemoryStore();
server = createTestServer(memory, workspaces);
}
it('empty mind → needsReviewCount 0, isFirstRun true', async () => {
@@ -150,35 +136,25 @@ describe('GET /api/home/briefing (P2 — J08 needsReviewCount + greeting)', () =
expect(briefing.needsReviewCount).toBe(0);
});
it('counts only personal-mind memories with status unreviewed', async () => {
it('counts extracted personal facts that are neither confirmed nor archived', async () => {
boot();
// Seed via the same routes the product uses: create (status active) then
// flip one to unreviewed — the C33 harvest lifecycle state.
const m1 = await server.inject({
method: 'POST', url: '/api/memory',
payload: { content: 'Imported fact awaiting review.' },
const extracted = (text: string, metadata: Record<string, unknown> = {}) => memory.remember({
scope: PERSONAL_SCOPE, text, origin: 'extraction', source: 'agent_inferred', kind: 'profile', metadata,
});
expect(m1.statusCode).toBe(200);
const m2 = await server.inject({
method: 'POST', url: '/api/memory',
payload: { content: 'Already-reviewed fact.' },
await extracted('Prefers short answers.');
await extracted('Lives in Belgrade.');
await extracted('Works on Waggle.', { confirmedAt: '2026-10-24T10:00:00.000Z' });
await extracted('Used to live in Novi Sad.', { archived: true });
// Memories the user saved are not up for review.
await memory.remember({ scope: PERSONAL_SCOPE, text: 'Saved by the user.', source: 'user_stated' });
// Workspace memories are not counted: the "Needs review" view is personal.
await memory.remember({
scope: workspaceScope('w1'), text: 'Workspace fact.', origin: 'extraction', source: 'agent_inferred',
});
expect(m2.statusCode).toBe(200);
const patch = await server.inject({
method: 'PATCH', url: `/api/memory/${m1.json().id}`,
payload: { status: 'unreviewed' },
});
expect(patch.statusCode).toBe(200);
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.statusCode).toBe(200);
expect(res.json().needsReviewCount).toBe(1);
// The count must agree with what the deep-linked "Needs review" view shows
// — same query the Memory Center fires (status filter + limit=200).
const list = await server.inject({ method: 'GET', url: '/api/memory?status=unreviewed&limit=200' });
expect(list.json().count).toBe(1);
expect(res.json().needsReviewCount).toBe(2);
});
it('briefing slices recent workspaces to 6, newest first (route-level ranking wiring)', async () => {
@@ -220,12 +196,11 @@ describe('GET /api/home/briefing (P2 — J08 needsReviewCount + greeting)', () =
});
describe('upNext schedule aggregation (global jobs dedup + future-only)', () => {
let db: MindDB;
let memory: MemoryStore;
let server: ReturnType<typeof Fastify>;
afterEach(async () => {
await server.close();
db.close();
});
const FUTURE = new Date(Date.now() + 60 * 60 * 1000).toISOString();
@@ -248,8 +223,7 @@ describe('upNext schedule aggregation (global jobs dedup + future-only)', () =>
}));
it('a global schedule surfaces once across multiple workspaces, not once per workspace', async () => {
db = new MindDB(':memory:');
server = createTestServer(db, threeWorkspaces, [
server = createTestServer(createInMemoryMemoryStore(), threeWorkspaces, [
globalSchedule(1, 'Memory compaction', FUTURE),
]);
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
@@ -260,8 +234,7 @@ describe('upNext schedule aggregation (global jobs dedup + future-only)', () =>
});
it('past-due schedules never display as upcoming', async () => {
db = new MindDB(':memory:');
server = createTestServer(db, threeWorkspaces, [
server = createTestServer(createInMemoryMemoryStore(), threeWorkspaces, [
globalSchedule(1, 'Memory compaction', PAST),
globalSchedule(2, 'Harvest sync', FUTURE),
]);

View File

@@ -2,43 +2,47 @@ import { describe, it, expect, vi } from 'vitest';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { WaggleDB } from '@waggle/core';
import { createInMemoryMemoryStore } from '@waggle/memory-contract';
import { buildWorkspaceNowBlock } from '../../src/local/routes/workspace-context.js';
/**
* R6-006 path-traversal regression.
*
* `buildWorkspaceNowBlock` builds session-directory paths from an unvalidated
* `workspaceId` (getMindPath + dataDir/workspaces/<workspaceId>/sessions),
* `workspaceId` (dataDir/workspaces/<workspaceId>/sessions),
* enabling an existence/count probe outside the workspaces root. A guard
* (assertSafeSegment) now runs at the entry of the helper and THROWS a
* { statusCode: 400 } error before the value touches the filesystem; the
* calling route handlers propagate that to Fastify's default error handler.
*
* These are unit tests against the exported helper directly (a full route
* inject is impractical — the route needs heavy mind/wsManager decorators).
* inject is impractical — the route needs heavy memory/wsManager decorators).
*/
describe('R6-006 workspace-context path traversal', () => {
// A throwaway data dir; the guard fires before this is ever read for the
// malicious cases, and the valid case short-circuits on a null wsManager.get.
const tmpDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wctx-traversal-'));
const waggleDb = new WaggleDB(':memory:');
const maliciousIds = ['../evil', '..%2f..', '../../etc', 'ws/../../secret', '..\\evil'];
for (const bad of maliciousIds) {
it(`rejects traversal workspaceId ${JSON.stringify(bad)} with a 400 error before any fs access`, () => {
it(`rejects traversal workspaceId ${JSON.stringify(bad)} with a 400 error before any fs access`, async () => {
const wsManager = {
get: vi.fn(() => ({ id: bad, name: 'evil' })),
getMindPath: vi.fn(() => path.join(tmpDataDir, 'mind.sqlite')),
};
const activateWorkspaceMind = vi.fn(() => true);
const memory = createInMemoryMemoryStore();
const count = vi.spyOn(memory, 'count');
let thrown: unknown;
try {
buildWorkspaceNowBlock({
await buildWorkspaceNowBlock({
dataDir: tmpDataDir,
workspaceId: bad,
wsManager,
activateWorkspaceMind,
waggleDb,
memory,
});
} catch (e) {
thrown = e;
@@ -46,32 +50,27 @@ describe('R6-006 workspace-context path traversal', () => {
expect(thrown).toBeInstanceOf(Error);
expect((thrown as { statusCode?: number }).statusCode).toBe(400);
// Guard short-circuits BEFORE the path-building dependencies are touched.
// Guard short-circuits BEFORE the workspace and its memory are touched.
expect(wsManager.get).not.toHaveBeenCalled();
expect(wsManager.getMindPath).not.toHaveBeenCalled();
expect(activateWorkspaceMind).not.toHaveBeenCalled();
expect(count).not.toHaveBeenCalled();
});
}
it('does NOT reject a normal valid workspaceId', () => {
it('does NOT reject a normal valid workspaceId', async () => {
const validId = 'workspace-123_AB';
const wsManager = {
// Return null so the helper cleanly returns null after the guard passes —
// proving the guard did not reject a valid segment.
get: vi.fn(() => null),
getMindPath: vi.fn(() => path.join(tmpDataDir, 'mind.sqlite')),
};
const activateWorkspaceMind = vi.fn(() => true);
let result: unknown;
expect(() => {
result = buildWorkspaceNowBlock({
dataDir: tmpDataDir,
workspaceId: validId,
wsManager,
activateWorkspaceMind,
});
}).not.toThrow();
const result = await buildWorkspaceNowBlock({
dataDir: tmpDataDir,
workspaceId: validId,
wsManager,
waggleDb,
memory: createInMemoryMemoryStore(),
});
// Guard passed, so execution proceeded to the (mocked) wsManager.get.
expect(wsManager.get).toHaveBeenCalledWith(validId);

View File

@@ -5,7 +5,9 @@
* - PATCH/PUT accept `status` (archive/restore/pause) and `description`,
* persist via WorkspaceManager, and reject invalid status values with 400.
* - Rename round-trips.
* - DELETE closes the workspace mind before removing the directory.
* - DELETE forgets the workspace's memories and awareness items, releases
* the workspace, then removes the directory.
* - POST with a template seeds its starter memories in the background.
*
* Scaffolding follows home.test.ts: Fastify inject + plain-object decorators,
* but with a REAL WorkspaceManager on a tmp dir so persistence is verified.
@@ -17,7 +19,13 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Fastify, { type FastifyInstance } from 'fastify';
import { WorkspaceManager } from '@waggle/core';
import { AwarenessLayer, WaggleDB, WorkspaceManager, workspaceDataScope } from '@waggle/core';
import {
createInMemoryMemoryStore,
PERSONAL_SCOPE,
workspaceScope,
type MemoryStore,
} from '@waggle/memory-contract';
import { workspaceRoutes, toStateItemViews } from '../../src/local/routes/workspaces.js';
import type { StateItem } from '../../src/local/workspace-state.js';
@@ -25,7 +33,9 @@ describe('workspace lifecycle routes', () => {
let tmpDir: string;
let manager: WorkspaceManager;
let server: FastifyInstance;
let closeWorkspaceMind: ReturnType<typeof vi.fn>;
let releaseWorkspace: ReturnType<typeof vi.fn>;
let memory: MemoryStore;
let waggleDb: WaggleDB;
let wsId: string;
beforeEach(async () => {
@@ -33,12 +43,16 @@ describe('workspace lifecycle routes', () => {
manager = new WorkspaceManager(tmpDir);
wsId = manager.create({ name: 'Side Project', group: 'Personal' }).id;
closeWorkspaceMind = vi.fn();
releaseWorkspace = vi.fn();
memory = createInMemoryMemoryStore();
waggleDb = new WaggleDB(':memory:');
server = Fastify({ logger: false });
server.decorate('workspaceManager', manager);
server.decorate('memory', memory);
server.decorate('waggleDb', waggleDb);
server.decorate('agentState', {
activateWorkspaceMind: () => undefined,
closeWorkspaceMind,
releaseWorkspace,
});
// localConfig intentionally absent — see file header.
await server.register(workspaceRoutes);
@@ -46,6 +60,7 @@ describe('workspace lifecycle routes', () => {
afterEach(async () => {
await server.close();
waggleDb.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -172,14 +187,52 @@ describe('workspace lifecycle routes', () => {
expect(new Set(ids).size).toBe(ids.length);
});
it('DELETE closes the workspace mind, removes the directory, and 404s after', async () => {
it('DELETE forgets the workspace memory, releases it, removes the directory, and 404s after', async () => {
const otherId = manager.create({ name: 'Other Project', group: 'Personal' }).id;
await memory.remember({ scope: workspaceScope(wsId), text: 'Side project memory' });
await memory.remember({ scope: workspaceScope(otherId), text: 'Other project memory' });
await memory.remember({ scope: PERSONAL_SCOPE, text: 'Personal memory' });
new AwarenessLayer(waggleDb, workspaceDataScope(wsId)).add('task', 'Side project task');
new AwarenessLayer(waggleDb, workspaceDataScope(otherId)).add('task', 'Other project task');
const res = await server.inject({ method: 'DELETE', url: `/api/workspaces/${wsId}` });
expect(res.statusCode).toBe(204);
expect(closeWorkspaceMind).toHaveBeenCalledWith(wsId);
expect(releaseWorkspace).toHaveBeenCalledWith(wsId);
expect(await memory.count({ scopes: [workspaceScope(wsId)] })).toBe(0);
expect(await memory.count({ scopes: [workspaceScope(otherId), PERSONAL_SCOPE] })).toBe(2);
expect(new AwarenessLayer(waggleDb, workspaceDataScope(wsId)).getAll()).toEqual([]);
expect(new AwarenessLayer(waggleDb, workspaceDataScope(otherId)).getAll()).toHaveLength(1);
expect(manager.get(wsId)).toBeNull();
expect(fs.existsSync(path.join(tmpDir, 'workspaces', wsId))).toBe(false);
const after = await server.inject({ method: 'DELETE', url: `/api/workspaces/${wsId}` });
expect(after.statusCode).toBe(404);
});
it('DELETE keeps the workspace when its memory cannot be forgotten', async () => {
vi.spyOn(memory, 'forgetMatching').mockRejectedValueOnce(new Error('store unavailable'));
const res = await server.inject({ method: 'DELETE', url: `/api/workspaces/${wsId}` });
expect(res.statusCode).toBe(500);
expect(releaseWorkspace).not.toHaveBeenCalled();
expect(manager.get(wsId)).not.toBeNull();
});
it('POST with a template seeds its starter memories into the new workspace', async () => {
const res = await server.inject({
method: 'POST',
url: '/api/workspaces',
payload: { name: 'Research Desk', group: 'Work', templateId: 'research-project' },
});
expect(res.statusCode).toBe(201);
const id = res.json().id as string;
await vi.waitFor(async () => {
expect(await memory.count({ scopes: [workspaceScope(id)] })).toBe(3);
});
const seeded = await memory.list({ scopes: [workspaceScope(id)] });
expect(seeded.every((m) => m.origin === 'workspace-template' && m.source === 'system')).toBe(true);
expect(seeded.map((m) => m.text)).toContain('This workspace is dedicated to research and investigation.');
});
});

View File

@@ -6,7 +6,8 @@ import { EventEmitter } from 'node:events';
import { NotificationGate, materialFingerprint, getNotificationGate } from '../src/local/notification-gate.js';
import { emitNotification } from '../src/local/routes/notifications.js';
import { suggestCapabilities, type ProactiveContext } from '../src/local/proactive-handlers.js';
import { WorkspaceManager } from '@waggle/core';
import { WaggleDB, WorkspaceManager } from '@waggle/core';
import { createInMemoryMemoryStore } from '@waggle/memory-contract';
const STORE_FILE = 'notification-fingerprints.json';
@@ -156,15 +157,18 @@ describe('emitNotification anti-nag gate', () => {
expect(emitted).toHaveLength(2);
});
it('suppresses a repeated identical proactive payload on the second emit', () => {
it('suppresses a repeated identical proactive payload on the second emit', async () => {
const wsManager = new WorkspaceManager(tmpDir);
const waggleDb = new WaggleDB(':memory:');
const ctx: ProactiveContext = {
dataDir: tmpDir,
workspaceManager: wsManager,
getWorkspaceMindDb: () => null,
memory: createInMemoryMemoryStore(),
waggleDb,
};
// No skills installed → the "capability packs" suggestion, carrying a dedupeKey + hash.
const msg = suggestCapabilities(ctx);
const msg = await suggestCapabilities(ctx);
waggleDb.close();
expect(msg).not.toBeNull();
expect(msg!.dedupeKey).toBeDefined();
expect(msg!.materialHash).toBeDefined();

View File

@@ -2,7 +2,8 @@ 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, WaggleDB, WorkspaceManager, AwarenessLayer, workspaceDataScope } from '@waggle/core';
import { WaggleDB, WorkspaceManager, AwarenessLayer, workspaceDataScope } from '@waggle/core';
import { createInMemoryMemoryStore, workspaceScope, type MemoryStore } from '@waggle/memory-contract';
import {
generateMorningBriefing,
checkStaleWorkspaces,
@@ -15,7 +16,7 @@ describe('Proactive Handlers', () => {
let tmpDir: string;
let wsManager: WorkspaceManager;
let waggleDb: WaggleDB;
const mindDbs = new Map<string, MindDB>();
let memory: MemoryStore;
/** Awareness items of one workspace, kept in waggle.db under its scope. */
function workspaceAwareness(workspaceId: string): AwarenessLayer {
@@ -27,19 +28,7 @@ describe('Proactive Handlers', () => {
dataDir: tmpDir,
workspaceManager: wsManager,
waggleDb,
getWorkspaceMindDb: (workspaceId: string) => {
const existing = mindDbs.get(workspaceId);
if (existing) return existing;
const mindPath = path.join(tmpDir, 'workspaces', workspaceId, 'workspace.mind');
if (!fs.existsSync(mindPath)) return null;
try {
const db = new MindDB(mindPath);
mindDbs.set(workspaceId, db);
return db;
} catch {
return null;
}
},
memory,
};
}
@@ -47,13 +36,10 @@ describe('Proactive Handlers', () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-proactive-'));
wsManager = new WorkspaceManager(tmpDir);
waggleDb = WaggleDB.openInDataDir(tmpDir);
memory = createInMemoryMemoryStore();
});
afterEach(() => {
for (const [, db] of mindDbs) {
try { db.close(); } catch { /* already closed */ }
}
mindDbs.clear();
waggleDb.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -61,13 +47,13 @@ describe('Proactive Handlers', () => {
// ── Morning Briefing ─────────────────────────────────────────────
describe('generateMorningBriefing', () => {
it('returns null when no workspaces exist', () => {
it('returns null when no workspaces exist', async () => {
const ctx = makeContext();
const result = generateMorningBriefing(ctx);
const result = await generateMorningBriefing(ctx);
expect(result).toBeNull();
});
it('returns null when no pending items and no stale workspaces', () => {
it('returns null when no pending items and no stale workspaces', async () => {
// Create a workspace with a recent session file
const ws = wsManager.create({ name: 'Active Project', group: 'Work' });
const sessionsDir = path.join(tmpDir, 'workspaces', ws.id, 'sessions');
@@ -75,11 +61,11 @@ describe('Proactive Handlers', () => {
fs.writeFileSync(path.join(sessionsDir, '2026-03-19.jsonl'), '{"role":"user","content":"hello"}\n');
const ctx = makeContext();
const result = generateMorningBriefing(ctx);
const result = await generateMorningBriefing(ctx);
expect(result).toBeNull();
});
it('includes workspace summaries when pending items exist', () => {
it('includes workspace summaries when pending items exist', async () => {
const ws = wsManager.create({ name: 'My Research', group: 'Work' });
const awareness = workspaceAwareness(ws.id);
@@ -87,7 +73,7 @@ describe('Proactive Handlers', () => {
awareness.add('pending', 'Waiting for feedback', 0);
const ctx = makeContext();
const result = generateMorningBriefing(ctx);
const result = await generateMorningBriefing(ctx);
expect(result).not.toBeNull();
expect(result!.type).toBe('morning_briefing');
@@ -96,7 +82,7 @@ describe('Proactive Handlers', () => {
expect(result!.body).toContain('My Research');
});
it('reports stale workspaces in briefing', () => {
it('reports stale workspaces in briefing', async () => {
const ws = wsManager.create({ name: 'Old Project', group: 'Archive' });
// Create a session file with old modification time
@@ -109,23 +95,36 @@ describe('Proactive Handlers', () => {
fs.utimesSync(sessionFile, oldTime, oldTime);
const ctx = makeContext();
const result = generateMorningBriefing(ctx);
const result = await generateMorningBriefing(ctx);
expect(result).not.toBeNull();
expect(result!.body).toContain('not visited in 14+ days');
});
it("lists this week's decisions per workspace", async () => {
const ws = wsManager.create({ name: 'Decisive Project', group: 'Work' });
await memory.remember({ scope: workspaceScope(ws.id), text: 'Ship the beta on Monday', kind: 'decision' });
await memory.remember({ scope: workspaceScope(ws.id), text: 'Lunch notes from the offsite' });
const result = await generateMorningBriefing(makeContext());
expect(result).not.toBeNull();
expect(result!.body).toContain('Recent decisions');
expect(result!.body).toContain('**Decisive Project**: Ship the beta on Monday');
expect(result!.body).not.toContain('Lunch notes');
});
});
// ── Stale Workspace Check ────────────────────────────────────────
describe('checkStaleWorkspaces', () => {
it('returns empty array when no workspaces', () => {
it('returns empty array when no workspaces', async () => {
const ctx = makeContext();
const result = checkStaleWorkspaces(ctx);
const result = await checkStaleWorkspaces(ctx);
expect(result).toEqual([]);
});
it('detects stale workspaces based on session activity', () => {
it('detects stale workspaces based on session activity', async () => {
const ws = wsManager.create({ name: 'Forgotten Project', group: 'Old' });
// Create a session file with old modification time
@@ -137,7 +136,7 @@ describe('Proactive Handlers', () => {
fs.utimesSync(sessionFile, oldTime, oldTime);
const ctx = makeContext();
const result = checkStaleWorkspaces(ctx);
const result = await checkStaleWorkspaces(ctx);
expect(result.length).toBe(1);
expect(result[0].type).toBe('stale_workspace');
@@ -145,18 +144,18 @@ describe('Proactive Handlers', () => {
expect(result[0].workspaceId).toBe(ws.id);
});
it('skips recently active workspaces', () => {
it('skips recently active workspaces', async () => {
const ws = wsManager.create({ name: 'Active Project', group: 'Work' });
const sessionsDir = path.join(tmpDir, 'workspaces', ws.id, 'sessions');
fs.mkdirSync(sessionsDir, { recursive: true });
fs.writeFileSync(path.join(sessionsDir, '2026-03-19.jsonl'), '{"role":"user","content":"hello"}\n');
const ctx = makeContext();
const result = checkStaleWorkspaces(ctx);
const result = await checkStaleWorkspaces(ctx);
expect(result).toEqual([]);
});
it('uses creation date when no sessions exist', () => {
it('uses creation date when no sessions exist', async () => {
// Create workspace with backdated creation
const ws = wsManager.create({ name: 'Empty Old Workspace', group: 'Test' });
// Backdate the workspace config
@@ -166,11 +165,25 @@ describe('Proactive Handlers', () => {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
const ctx = makeContext();
const result = checkStaleWorkspaces(ctx);
const result = await checkStaleWorkspaces(ctx);
expect(result.length).toBe(1);
expect(result[0].title).toContain('Empty Old Workspace');
});
it('counts the memories of a stale workspace', async () => {
const ws = wsManager.create({ name: 'Quiet Workspace', group: 'Test' });
const configPath = path.join(tmpDir, 'workspaces', ws.id, 'workspace.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
config.created = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
await memory.remember({ scope: workspaceScope(ws.id), text: 'First memory' });
await memory.remember({ scope: workspaceScope(ws.id), text: 'Second memory' });
const result = await checkStaleWorkspaces(makeContext());
expect(result[0].body).toBe('This workspace has 2 memories that may need attention.');
});
});
// ── Task Reminder ────────────────────────────────────────────────
@@ -233,17 +246,17 @@ describe('Proactive Handlers', () => {
// ── Capability Suggestion ────────────────────────────────────────
describe('suggestCapabilities', () => {
it('returns null when no workspaces and capabilities installed', () => {
it('returns null when no workspaces and capabilities installed', async () => {
// Create a fake skills directory to simulate installed capabilities
fs.mkdirSync(path.join(tmpDir, 'skills', 'some-skill'), { recursive: true });
const ctx = makeContext();
const result = suggestCapabilities(ctx);
const result = await suggestCapabilities(ctx);
expect(result).toBeNull();
});
it('suggests capability packs when none are installed', () => {
it('suggests capability packs when none are installed', async () => {
const ctx = makeContext();
const result = suggestCapabilities(ctx);
const result = await suggestCapabilities(ctx);
expect(result).not.toBeNull();
expect(result!.type).toBe('capability_suggestion');
@@ -251,17 +264,15 @@ describe('Proactive Handlers', () => {
expect(result!.actionUrl).toBe('/skills');
});
it('returns null when capabilities installed and low memory count', () => {
it('returns null when capabilities installed and low memory count', async () => {
// Create skills dir (simulates installed capabilities)
fs.mkdirSync(path.join(tmpDir, 'skills', 'research-skill'), { recursive: true });
// Create a workspace with few frames
// Create a workspace with few memories
const ws = wsManager.create({ name: 'Small Project', group: 'Test' });
const mindPath = path.join(tmpDir, 'workspaces', ws.id, 'workspace.mind');
const db = new MindDB(mindPath);
mindDbs.set(ws.id, db);
await memory.remember({ scope: workspaceScope(ws.id), text: 'One small memory' });
const ctx = makeContext();
const result = suggestCapabilities(ctx);
const result = await suggestCapabilities(ctx);
expect(result).toBeNull();
});
});

View 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([]);
});
});

View File

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

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

View File

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

View File

@@ -25,8 +25,6 @@ describe('Workspace & Session API', () => {
'utf-8'
);
// Create personal.mind as empty file (MindDB will init schema)
// Don't create it — let MultiMind handle it
server = await buildLocalServer({ dataDir, port: 0 });
});

View File

@@ -9,7 +9,6 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { MindDB } from '@waggle/core';
import { buildLocalServer } from '../src/local/index.js';
import type { FastifyInstance } from 'fastify';
import { injectWithAuth } from './test-utils.js';
@@ -32,11 +31,6 @@ describe('Workspace Templates API', () => {
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-ws-templates-'));
// Create personal.mind (required by buildLocalServer)
const personalPath = path.join(tmpDir, 'personal.mind');
const mind = new MindDB(personalPath);
mind.close();
server = await buildLocalServer({ dataDir: tmpDir });
});