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:
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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),
|
||||
]);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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.');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user