Files
waggle-os/packages/server/tests/routes/context-injection.test.ts
shumeiko.it e9ed8c0765 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.
2026-10-24 13:19:06 +02:00

263 lines
9.4 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 { WaggleDB } from '@waggle/core';
import {
createInMemoryMemoryStore,
workspaceScope,
type MemoryImportance,
type MemoryStore,
} from '@waggle/memory-contract';
import {
buildWorkspaceNowBlock,
formatWorkspaceNowPrompt,
} from '../../src/local/routes/workspace-context.js';
/**
* Tests for workspace context injection into the agent system prompt.
*
* The actual `buildSystemPrompt` function is a closure inside the chat route plugin,
* so we test the injection logic at the boundary: buildWorkspaceNowBlock + formatWorkspaceNowPrompt
* produce the correct content, and verify the integration contract (what gets appended to the prompt).
*
* The chat route code:
* if (workspaceId) {
* 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 {
// Non-critical on Windows
}
});
// ── Helpers ───────────────────────────────────────────────────────────
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);
fs.mkdirSync(wsDir, { recursive: true });
fs.writeFileSync(
path.join(wsDir, 'workspace.json'),
JSON.stringify({ id, name: `Test ${id}`, group: 'test', created: new Date().toISOString() }),
);
for (const memo of opts?.memories ?? []) {
await memory.remember({ scope: workspaceScope(id), text: memo.text, importance: memo.importance });
}
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 lines: string[] = [
JSON.stringify({ type: 'meta', title: sess.title, created: new Date().toISOString() }),
];
for (const msg of sess.messages) {
lines.push(JSON.stringify({ role: msg.role, content: msg.content }));
}
fs.writeFileSync(path.join(sessDir, `session-${i}.jsonl`), lines.join('\n') + '\n');
}
}
}
function makeManager(workspaces: Map<string, { id: string; name: string }>) {
return {
get: (id: string) => workspaces.get(id) ?? null,
};
}
/**
* Simulate what buildSystemPrompt does: build a base prompt, then conditionally
* append the workspace context. This mirrors the injection logic in chat.ts.
*/
async function simulatePromptBuild(basePrompt: string, workspaceId?: string, wsManager?: ReturnType<typeof makeManager>) {
let prompt = basePrompt;
if (workspaceId && wsManager) {
try {
const nowBlock = await buildWorkspaceNowBlock({
dataDir: tmpDir,
workspaceId,
wsManager,
waggleDb,
memory,
});
if (nowBlock) {
prompt += '\n\n' + formatWorkspaceNowPrompt(nowBlock);
}
} catch {
// Non-blocking — mirrors the try/catch in chat.ts
}
}
return prompt;
}
// ── Test 1: No workspaceId → 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 = await simulatePromptBuild(basePrompt);
expect(result).not.toContain('# Workspace Now');
expect(result).toBe(basePrompt);
});
// ── Test 2: With workspaceId + 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' }],
]));
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: [
{
title: 'Architecture Planning',
messages: [
{ role: 'user', content: 'Plan the architecture' },
{ role: 'assistant', content: 'Here is a plan.' },
],
},
],
});
const basePrompt = '# Who You Are\n\nYou are Waggle.';
const result = await simulatePromptBuild(basePrompt, 'rich-ws', wsManager);
expect(result).toContain('# Workspace Now');
expect(result).toContain('Rich Project');
// Should still contain the base prompt
expect(result).toContain('# Who You Are');
// Workspace Now should be appended after the base prompt
const baseEnd = result.indexOf('# Who You Are');
const wsNowStart = result.indexOf('# Workspace Now');
expect(wsNowStart).toBeGreaterThan(baseEnd);
});
// ── Test 3: With workspaceId for empty/missing workspace → 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 the workspace directory but no memories
const wsDir = path.join(tmpDir, 'workspaces', 'empty-ws');
fs.mkdirSync(wsDir, { recursive: true });
fs.writeFileSync(
path.join(wsDir, 'workspace.json'),
JSON.stringify({ id: 'empty-ws', name: 'Empty Project', group: 'test', created: new Date().toISOString() }),
);
const basePrompt = '# Who You Are\n\nYou are Waggle.';
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"', async () => {
const wsManager = makeManager(new Map());
const basePrompt = '# Who You Are\n\nYou are Waggle.';
const result = await simulatePromptBuild(basePrompt, 'does-not-exist', wsManager);
expect(result).not.toContain('# Workspace Now');
expect(result).toBe(basePrompt);
});
// ── Test 4: Cache invalidation — different workspaceId → different prompt ─
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' }],
]));
await setupWorkspace('ws-a', {
memories: [
{ text: 'Alpha is a front-end framework project.', importance: 'important' },
{ text: 'Decision: Use React for Alpha.', 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 = await simulatePromptBuild(basePrompt, 'ws-a', wsManager);
const promptB = await simulatePromptBuild(basePrompt, 'ws-b', wsManager);
// Both should have Workspace Now
expect(promptA).toContain('# Workspace Now');
expect(promptB).toContain('# Workspace Now');
// But with different workspace names
expect(promptA).toContain('Project Alpha');
expect(promptA).not.toContain('Project Beta');
expect(promptB).toContain('Project Beta');
expect(promptB).not.toContain('Project Alpha');
// Prompts should be different
expect(promptA).not.toBe(promptB);
});
// ── Test 5: Verify the formatted block is positioned correctly ──────
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' }],
]));
await setupWorkspace('pos-ws', {
memories: [
{ text: 'Testing prompt positioning.', importance: 'important' },
],
});
const basePrompt = 'BASE_PROMPT_START\nSome agent instructions.\nBASE_PROMPT_END';
const result = await simulatePromptBuild(basePrompt, 'pos-ws', wsManager);
// Base prompt should appear first
expect(result.startsWith('BASE_PROMPT_START')).toBe(true);
// Workspace Now should come after base prompt
const baseEndIdx = result.indexOf('BASE_PROMPT_END');
const wsNowIdx = result.indexOf('# Workspace Now');
expect(wsNowIdx).toBeGreaterThan(baseEndIdx);
// Separated by double newline
const between = result.slice(baseEndIdx + 'BASE_PROMPT_END'.length, wsNowIdx);
expect(between).toBe('\n\n');
});
});