Files
waggle-os/packages/server/tests/local/home.test.ts
shumeiko.it 16eaf01e14 chore: scrub personal names, maintainer URLs and local paths (P2.2)
Sample data in tests, prompts and UI placeholders uses Alex Morgan
instead of the maintainer's name; decision attributions say "owner".
Personal details in two test fixtures are replaced. Local paths
(D:/Projects/...) and paths into the maintainer's planning repository
are reworded. Clone and install URLs in CONTRIBUTING.md and the getting
started guide use placeholders until the public repository location is
decided (Q9). The Benchmarks page no longer names the maintainer's
hive-mind repository, and the upstream fixes log names the main Waggle
repository instead of an internal git host.
2026-11-01 00:50:13 +01:00

294 lines
12 KiB
TypeScript

/**
* Home Cockpit route tests (P2 — verify + J08).
*
* Covers the P2 additions to GET /api/home/briefing:
* - personalizeGreeting(): user name spliced into the first greeting clause
* (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): extracted personal facts that are neither
* confirmed nor archived are counted.
*
* 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
* emitAuditEvent stays a safe no-op.
*/
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Fastify from 'fastify';
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 {
buildUpcomingSchedules,
type CronScheduleLike,
} from '../../src/local/routes/workspace-context.js';
interface TestWorkspace {
id: string;
name: string;
group: string;
created: string;
status?: string;
teamId?: string;
}
function createTestServer(
memory: MemoryStore,
workspaces: TestWorkspace[] = [],
cronSchedules: CronScheduleLike[] = [],
) {
const server = Fastify({ logger: false });
const waggleDb = new WaggleDB(':memory:');
server.decorate('waggleDb', waggleDb);
server.addHook('onClose', async () => waggleDb.close());
server.decorate('memory', memory);
server.decorate('workspaceManager', {
list: () => workspaces,
get: (id: string) => workspaces.find((w) => w.id === id),
});
server.decorate('cronStore', {
list: () => cronSchedules,
getExecutionHistory: () => [],
});
// localConfig intentionally absent — see file header.
server.register(homeRoutes);
return server;
}
const card = (id: string, pendingCount: number, rankTs: number): { card: RecentWorkspaceCard; rankTs: number } => ({
rankTs,
card: { id, name: id, group: 'Personal', lastActive: new Date(rankTs).toISOString(), pendingCount },
});
describe('personalizeGreeting (P2 — B8 name in greeting)', () => {
it('splices the name before the first sentence break', () => {
expect(personalizeGreeting("Good morning. Here's your day", 'Alex'))
.toBe("Good morning, Alex. Here's your day");
});
it('handles the em-dash fresh-state greeting', () => {
expect(personalizeGreeting('Welcome — anything you discuss here will be remembered.', 'Alex'))
.toBe('Welcome, Alex — anything you discuss here will be remembered.');
});
it('passes through without a name', () => {
expect(personalizeGreeting("Good morning. Here's your day"))
.toBe("Good morning. Here's your day");
});
it('passes through greetings with no sentence break', () => {
expect(personalizeGreeting('Hello there', 'Alex')).toBe('Hello there');
});
});
describe('applyPriorityRanking (P2 — recency + pending boost)', () => {
const HOUR = 3_600_000;
const T0 = Date.parse('2026-06-11T12:00:00Z');
it('pending items boost an older workspace past a fresher empty one within the cap window', () => {
const fresh = card('fresh', 0, T0);
const blocked = card('blocked', 3, T0 - 2 * HOUR); // 3 pending → +3h ≥ 2h gap
const ranked = applyPriorityRanking([fresh, blocked]);
expect(ranked.map((c) => c.id)).toEqual(['blocked', 'fresh']);
});
it('the boost is capped — a stale workspace cannot leapfrog on pending count alone', () => {
const fresh = card('fresh', 0, T0);
const stale = card('stale', 50, T0 - 24 * HOUR); // cap 5 → +5h < 24h gap
const ranked = applyPriorityRanking([fresh, stale]);
expect(ranked.map((c) => c.id)).toEqual(['fresh', 'stale']);
});
it('slices to the display cap of 6', () => {
const cards = Array.from({ length: 8 }, (_, i) => card(`w${i}`, 0, T0 - i * HOUR));
expect(applyPriorityRanking(cards)).toHaveLength(6);
});
});
describe('GET /api/home/briefing (P2 — J08 needsReviewCount + greeting)', () => {
let memory: MemoryStore;
let server: ReturnType<typeof Fastify>;
afterEach(async () => {
await server.close();
});
function boot(workspaces: TestWorkspace[] = []) {
memory = createInMemoryMemoryStore();
server = createTestServer(memory, workspaces);
}
it('empty mind → needsReviewCount 0, isFirstRun true', async () => {
boot();
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.statusCode).toBe(200);
const briefing = res.json();
expect(briefing.isFirstRun).toBe(true);
expect(briefing.needsReviewCount).toBe(0);
});
it('counts extracted personal facts that are neither confirmed nor archived', async () => {
boot();
const extracted = (text: string, metadata: Record<string, unknown> = {}) => memory.remember({
scope: PERSONAL_SCOPE, text, origin: 'extraction', source: 'agent_inferred', kind: 'profile', metadata,
});
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',
});
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.statusCode).toBe(200);
expect(res.json().needsReviewCount).toBe(2);
});
it('briefing slices recent workspaces to 6, newest first (route-level ranking wiring)', async () => {
const T0 = Date.parse('2026-06-11T12:00:00Z');
const workspaces = Array.from({ length: 8 }, (_, i) => ({
id: `w${i}`,
name: `Workspace ${i}`,
group: 'Personal',
// w0 oldest … w7 newest
created: new Date(T0 + i * 3_600_000).toISOString(),
}));
boot(workspaces);
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.statusCode).toBe(200);
const cards = res.json().recentWorkspaces;
expect(cards).toHaveLength(6);
expect(cards.map((c: { id: string }) => c.id)).toEqual(['w7', 'w6', 'w5', 'w4', 'w3', 'w2']);
});
it('greets by name when identity is seeded (B8)', async () => {
boot([{ id: 'w1', name: 'Alpha', group: 'Personal', created: new Date().toISOString() }]);
new IdentityLayer(server.waggleDb).create({
name: 'Alex', role: 'Founder', department: 'Egzakta',
personality: '', capabilities: '', system_prompt: '',
});
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.statusCode).toBe(200);
const briefing = res.json();
expect(briefing.userName).toBe('Alex');
expect(briefing.greeting).toContain(', Alex');
});
it('greeting stays name-free when no identity exists', async () => {
boot([{ id: 'w1', name: 'Alpha', group: 'Personal', created: new Date().toISOString() }]);
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.json().userName).toBeUndefined();
expect(res.json().greeting).not.toContain(',');
});
function seedAssistantIdentity() {
new IdentityLayer(server.waggleDb).create({
name: 'Waggle', role: 'AI assistant with persistent memory and web access', department: '',
personality: '', capabilities: '', system_prompt: '',
});
}
it('UF-055: never greets the user by the assistant\'s default name', async () => {
boot();
seedAssistantIdentity();
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.json().userName).toBeUndefined();
expect(res.json().greeting).not.toContain('Waggle');
});
it('UF-055: greets by the name the user gave in their profile', async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-home-profile-'));
try {
fs.writeFileSync(path.join(dataDir, 'profile.json'), JSON.stringify({ name: 'Ana' }));
boot();
server.decorate('localConfig', { dataDir } as never);
seedAssistantIdentity();
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.json().userName).toBe('Ana');
expect(res.json().greeting).toContain(', Ana');
} finally {
fs.rmSync(dataDir, { recursive: true, force: true });
}
});
});
describe('upNext schedule aggregation (global jobs dedup + future-only)', () => {
let memory: MemoryStore;
let server: ReturnType<typeof Fastify>;
afterEach(async () => {
await server.close();
});
const FUTURE = new Date(Date.now() + 60 * 60 * 1000).toISOString();
const PAST = new Date(Date.now() - 60 * 60 * 1000).toISOString();
const globalSchedule = (id: number, name: string, nextRunAt: string): CronScheduleLike => ({
id,
name,
cron_expr: '30 3 * * *',
enabled: 1,
workspace_id: null,
next_run_at: nextRunAt,
} as CronScheduleLike);
const threeWorkspaces: TestWorkspace[] = ['a', 'b', 'c'].map((id, i) => ({
id,
name: `Workspace ${id}`,
group: 'Personal',
created: new Date(Date.parse('2026-06-11T12:00:00Z') + i * 3_600_000).toISOString(),
}));
it('a global schedule surfaces once across multiple workspaces, not once per workspace', async () => {
server = createTestServer(createInMemoryMemoryStore(), threeWorkspaces, [
globalSchedule(1, 'Memory compaction', FUTURE),
]);
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
expect(res.statusCode).toBe(200);
const labels = (res.json().upNext as Array<{ label: string }>).map((u) => u.label);
const compactions = labels.filter((l) => l.startsWith('Memory compaction'));
expect(compactions).toHaveLength(1);
});
it('past-due schedules never display as upcoming', async () => {
server = createTestServer(createInMemoryMemoryStore(), threeWorkspaces, [
globalSchedule(1, 'Memory compaction', PAST),
globalSchedule(2, 'Harvest sync', FUTURE),
]);
const res = await server.inject({ method: 'GET', url: '/api/home/briefing' });
const labels = (res.json().upNext as Array<{ label: string }>).map((u) => u.label);
expect(labels.some((l) => l.startsWith('Memory compaction'))).toBe(false);
expect(labels.filter((l) => l.startsWith('Harvest sync'))).toHaveLength(1);
});
it('buildUpcomingSchedules unit: filters past, keeps future, scopes by workspace', () => {
const out = buildUpcomingSchedules(
[
globalSchedule(1, 'Past job', PAST),
globalSchedule(2, 'Future job', FUTURE),
{ ...globalSchedule(3, 'Other ws job', FUTURE), workspace_id: 'other' } as CronScheduleLike,
],
'mine',
);
expect(out.some((l) => l.startsWith('Past job'))).toBe(false);
expect(out.some((l) => l.startsWith('Future job'))).toBe(true);
expect(out.some((l) => l.startsWith('Other ws job'))).toBe(false);
});
});