Files
waggle-os/packages/server/src/local/proactive-handlers.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

303 lines
11 KiB
TypeScript

/**
* Proactive Behavior Handlers — Solo mode proactive agent behaviors.
*
* These handlers generate contextual notifications based on workspace state,
* memory activity, and usage patterns. They are triggered by cron schedules
* and emit results through the notification eventBus so the desktop app's
* toast system picks them up.
*
* Separate from the Team proactive service (ProactiveService) which uses
* Drizzle/PostgreSQL. These handlers operate on local workspace and memory data.
*/
import fs from 'node:fs';
import path from 'node:path';
import { AwarenessLayer, workspaceDataScope, type WorkspaceManager } from '@waggle/core';
import { workspaceScope, type MemoryRecord, type MemoryStore } from '@waggle/memory-contract';
import { materialFingerprint } from './notification-gate.js';
// ── Types ──────────────────────────────────────────────────────────────
export interface ProactiveMessage {
type: 'morning_briefing' | 'stale_workspace' | 'task_reminder' | 'capability_suggestion';
title: string;
body: string;
workspaceId?: string;
actionUrl?: string;
priority: 'low' | 'medium' | 'high';
/** Anti-nag: stable key + fingerprint so an unchanged nag is suppressed on re-emit. */
dedupeKey?: string;
materialHash?: string;
}
export interface ProactiveContext {
dataDir: string;
workspaceManager: WorkspaceManager;
memory: MemoryStore;
/** waggle.db, which holds awareness items. */
waggleDb: import('@waggle/core').WaggleDB;
}
// ── Helpers ────────────────────────────────────────────────────────────
/** Get the most recent session file modification time for a workspace. */
function getLastSessionActivity(dataDir: string, workspaceId: string): Date | null {
const sessionsDir = path.join(dataDir, 'workspaces', workspaceId, 'sessions');
if (!fs.existsSync(sessionsDir)) return null;
const files = fs.readdirSync(sessionsDir).filter(f => f.endsWith('.jsonl'));
if (files.length === 0) return null;
let latest = 0;
for (const file of files) {
try {
const stat = fs.statSync(path.join(sessionsDir, file));
if (stat.mtimeMs > latest) latest = stat.mtimeMs;
} catch { /* skip unreadable files */ }
}
return latest > 0 ? new Date(latest) : null;
}
/** Count open task and pending awareness items of a workspace. */
function countPendingAwareness(ctx: ProactiveContext, workspaceId: string): number {
try {
return new AwarenessLayer(ctx.waggleDb, workspaceDataScope(workspaceId)).countOpen();
} catch {
return 0;
}
}
/** Recent memories scanned for the morning briefing's highlights. */
const HIGHLIGHT_SCAN = 200;
/** A briefing highlight: a decision or an important memory. */
function isHighlight(record: MemoryRecord): boolean {
return record.kind === 'decision'
|| record.importance === 'critical'
|| record.importance === 'important'
|| /^decision|decided/i.test(record.text);
}
/** Count the memories of a workspace. */
async function countMemories(ctx: ProactiveContext, workspaceId: string): Promise<number> {
try {
return await ctx.memory.count({ scopes: [workspaceScope(workspaceId)] });
} catch {
return 0;
}
}
/** Check if any capability packs are installed. */
function hasInstalledCapabilities(dataDir: string): boolean {
const skillsDir = path.join(dataDir, 'skills');
if (!fs.existsSync(skillsDir)) return false;
try {
const entries = fs.readdirSync(skillsDir);
return entries.length > 0;
} catch {
return false;
}
}
// ── Handlers ───────────────────────────────────────────────────────────
/** Generate morning briefing across all workspaces. */
export async function generateMorningBriefing(ctx: ProactiveContext): Promise<ProactiveMessage | null> {
const workspaces = ctx.workspaceManager.list();
if (workspaces.length === 0) return null;
const summaryParts: string[] = [];
let totalPending = 0;
let staleCount = 0;
const now = Date.now();
const STALE_THRESHOLD_MS = 14 * 24 * 60 * 60 * 1000; // 14 days
for (const ws of workspaces) {
const pending = countPendingAwareness(ctx, ws.id);
totalPending += pending;
const lastActivity = getLastSessionActivity(ctx.dataDir, ws.id);
if (lastActivity && (now - lastActivity.getTime()) > STALE_THRESHOLD_MS) {
staleCount++;
}
if (pending > 0) {
summaryParts.push(`${ws.name}: ${pending} pending item${pending === 1 ? '' : 's'}`);
}
}
// W5.8: Also extract this week's decisions and memory highlights per workspace
const decisionParts: string[] = [];
const weekAgo = new Date(now - 7 * 24 * 60 * 60 * 1000).toISOString();
for (const ws of workspaces.slice(0, 5)) { // cap at 5 workspaces for brevity
try {
const recent = await ctx.memory.list({
scopes: [workspaceScope(ws.id)],
since: weekAgo,
limit: HIGHLIGHT_SCAN,
});
const decisions = recent.filter(isHighlight).slice(0, 2);
if (decisions.length > 0) {
decisionParts.push(`**${ws.name}**: ${decisions.map(d => d.text.slice(0, 80)).join(' | ')}`);
}
} catch { /* non-blocking */ }
}
// Nothing noteworthy — skip the briefing
if (totalPending === 0 && staleCount === 0 && decisionParts.length === 0) return null;
const bodyParts: string[] = [];
bodyParts.push(`${workspaces.length} workspace${workspaces.length === 1 ? '' : 's'} total.`);
if (totalPending > 0) {
bodyParts.push(`${totalPending} pending item${totalPending === 1 ? '' : 's'} across workspaces.`);
}
if (staleCount > 0) {
bodyParts.push(`${staleCount} workspace${staleCount === 1 ? '' : 's'} not visited in 14+ days.`);
}
if (summaryParts.length > 0) {
bodyParts.push(summaryParts.slice(0, 3).join('; '));
}
// W5.8: Include recent decisions in briefing
if (decisionParts.length > 0) {
bodyParts.push('\n\nRecent decisions:\n' + decisionParts.join('\n'));
}
return {
type: 'morning_briefing',
title: 'Good morning — here\'s your workspace briefing',
body: bodyParts.join(' '),
priority: totalPending > 5 ? 'high' : 'medium',
actionUrl: '/',
dedupeKey: 'proactive:morning_briefing',
materialHash: materialFingerprint({
wsCount: workspaces.length,
totalPending,
staleCount,
summary: summaryParts,
decisions: decisionParts,
}),
};
}
/** Check for stale workspaces (not visited in 14+ days). */
export async function checkStaleWorkspaces(ctx: ProactiveContext): Promise<ProactiveMessage[]> {
const workspaces = ctx.workspaceManager.list();
if (workspaces.length === 0) return [];
const messages: ProactiveMessage[] = [];
const now = Date.now();
const STALE_THRESHOLD_MS = 14 * 24 * 60 * 60 * 1000;
for (const ws of workspaces) {
const lastActivity = getLastSessionActivity(ctx.dataDir, ws.id);
// If no sessions at all, check workspace creation date
const referenceDate = lastActivity ?? new Date(ws.created);
const idleDays = Math.floor((now - referenceDate.getTime()) / (24 * 60 * 60 * 1000));
if (idleDays >= 14) {
const frameCount = await countMemories(ctx, ws.id);
messages.push({
type: 'stale_workspace',
title: `"${ws.name}" hasn't been visited in ${idleDays} days`,
body: frameCount > 0
? `This workspace has ${frameCount} memor${frameCount === 1 ? 'y' : 'ies'} that may need attention.`
: 'Consider archiving or revisiting this workspace.',
workspaceId: ws.id,
actionUrl: `/workspaces/${ws.id}`,
priority: idleDays > 30 ? 'medium' : 'low',
dedupeKey: `proactive:stale_workspace:${ws.id}`,
// Fingerprint on identity, not idleDays — so a still-stale workspace
// doesn't re-nag every day. Re-fires only if it's touched (new
// reference time) or its memory count changes.
materialHash: materialFingerprint({ wsId: ws.id, frameCount, referenceMs: referenceDate.getTime() }),
});
}
}
return messages;
}
/** Check for pending tasks across workspaces. */
export function checkPendingTasks(ctx: ProactiveContext): ProactiveMessage[] {
const workspaces = ctx.workspaceManager.list();
if (workspaces.length === 0) return [];
const messages: ProactiveMessage[] = [];
for (const ws of workspaces) {
const pending = countPendingAwareness(ctx, ws.id);
if (pending === 0) continue;
messages.push({
type: 'task_reminder',
title: `${ws.name}: ${pending} pending item${pending === 1 ? '' : 's'}`,
body: `You have ${pending} unresolved task${pending === 1 ? '' : 's'} or pending item${pending === 1 ? '' : 's'} in "${ws.name}".`,
workspaceId: ws.id,
actionUrl: `/workspaces/${ws.id}`,
priority: pending > 3 ? 'high' : 'medium',
dedupeKey: `proactive:task_reminder:${ws.id}`,
materialHash: materialFingerprint({ wsId: ws.id, pending }),
});
}
return messages;
}
/** Suggest capabilities based on usage patterns. */
export async function suggestCapabilities(ctx: ProactiveContext): Promise<ProactiveMessage | null> {
// If the user has no installed capabilities, suggest exploring the catalog
if (!hasInstalledCapabilities(ctx.dataDir)) {
return {
type: 'capability_suggestion',
title: 'Boost your workflow with capability packs',
body: 'You haven\'t installed any capability packs yet. Explore Research, Writing, and Planning packs to supercharge your agent.',
priority: 'low',
actionUrl: '/skills',
dedupeKey: 'proactive:capability_suggestion',
materialHash: materialFingerprint({ kind: 'no_caps' }),
};
}
// Check workspace count and memory size for growth-based suggestions
const workspaces = ctx.workspaceManager.list();
if (workspaces.length === 0) return null;
// Count total memories across all workspaces
let totalFrames = 0;
for (const ws of workspaces) {
totalFrames += await countMemories(ctx, ws.id);
}
// If accumulating significant memories but no connectors, suggest connectors
if (totalFrames > 50) {
const hasConnectors = (() => {
try {
const vaultPath = path.join(ctx.dataDir, 'vault.db');
return fs.existsSync(vaultPath);
} catch {
return false;
}
})();
if (!hasConnectors) {
return {
type: 'capability_suggestion',
title: 'Connect your external tools',
body: `You have ${totalFrames} memories across ${workspaces.length} workspace${workspaces.length === 1 ? '' : 's'}. Consider connecting GitHub, Slack, or other tools for richer context.`,
priority: 'low',
actionUrl: '/connectors',
dedupeKey: 'proactive:capability_suggestion',
// Fingerprint on the trigger kind only — showing this once is the point;
// it re-fires when the suggestion itself changes (or the condition clears).
materialHash: materialFingerprint({ kind: 'connectors' }),
};
}
}
return null;
}