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:
@@ -7,12 +7,13 @@
|
||||
* toast system picks them up.
|
||||
*
|
||||
* Separate from the Team proactive service (ProactiveService) which uses
|
||||
* Drizzle/PostgreSQL. These handlers operate on local workspace/mind data.
|
||||
* 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, type WorkspaceConfig } from '@waggle/core';
|
||||
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 ──────────────────────────────────────────────────────────────
|
||||
@@ -32,8 +33,7 @@ export interface ProactiveMessage {
|
||||
export interface ProactiveContext {
|
||||
dataDir: string;
|
||||
workspaceManager: WorkspaceManager;
|
||||
/** Get a cached workspace MindDB (opens on demand). Returns null if workspace not found. */
|
||||
getWorkspaceMindDb: (workspaceId: string) => import('@waggle/core').MindDB | null;
|
||||
memory: MemoryStore;
|
||||
/** waggle.db, which holds awareness items. */
|
||||
waggleDb: import('@waggle/core').WaggleDB;
|
||||
}
|
||||
@@ -68,14 +68,21 @@ function countPendingAwareness(ctx: ProactiveContext, workspaceId: string): numb
|
||||
}
|
||||
}
|
||||
|
||||
/** Count memory frames in a workspace mind. */
|
||||
function countMemoryFrames(ctx: ProactiveContext, workspaceId: string): number {
|
||||
const db = ctx.getWorkspaceMindDb(workspaceId);
|
||||
if (!db) 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 {
|
||||
const raw = db.getDatabase();
|
||||
const row = raw.prepare('SELECT COUNT(*) as cnt FROM memory_frames').get() as { cnt: number } | undefined;
|
||||
return row?.cnt ?? 0;
|
||||
return await ctx.memory.count({ scopes: [workspaceScope(workspaceId)] });
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
@@ -96,7 +103,7 @@ function hasInstalledCapabilities(dataDir: string): boolean {
|
||||
// ── Handlers ───────────────────────────────────────────────────────────
|
||||
|
||||
/** Generate morning briefing across all workspaces. */
|
||||
export function generateMorningBriefing(ctx: ProactiveContext): ProactiveMessage | null {
|
||||
export async function generateMorningBriefing(ctx: ProactiveContext): Promise<ProactiveMessage | null> {
|
||||
const workspaces = ctx.workspaceManager.list();
|
||||
if (workspaces.length === 0) return null;
|
||||
|
||||
@@ -120,21 +127,19 @@ export function generateMorningBriefing(ctx: ProactiveContext): ProactiveMessage
|
||||
}
|
||||
}
|
||||
|
||||
// W5.8: Also extract recent decisions and memory highlights per workspace
|
||||
// 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
|
||||
const db = ctx.getWorkspaceMindDb(ws.id);
|
||||
if (!db) continue;
|
||||
try {
|
||||
const raw = db.getDatabase();
|
||||
const decisions = raw.prepare(
|
||||
`SELECT content FROM memory_frames
|
||||
WHERE (importance IN ('critical', 'important') OR content LIKE 'Decision%' OR content LIKE '%decided%')
|
||||
AND created_at > datetime('now', '-7 day')
|
||||
ORDER BY id DESC LIMIT 2`
|
||||
).all() as Array<{ content: string }>;
|
||||
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.content.slice(0, 80)).join(' | ')}`);
|
||||
decisionParts.push(`**${ws.name}**: ${decisions.map(d => d.text.slice(0, 80)).join(' | ')}`);
|
||||
}
|
||||
} catch { /* non-blocking */ }
|
||||
}
|
||||
@@ -177,7 +182,7 @@ export function generateMorningBriefing(ctx: ProactiveContext): ProactiveMessage
|
||||
}
|
||||
|
||||
/** Check for stale workspaces (not visited in 14+ days). */
|
||||
export function checkStaleWorkspaces(ctx: ProactiveContext): ProactiveMessage[] {
|
||||
export async function checkStaleWorkspaces(ctx: ProactiveContext): Promise<ProactiveMessage[]> {
|
||||
const workspaces = ctx.workspaceManager.list();
|
||||
if (workspaces.length === 0) return [];
|
||||
|
||||
@@ -193,13 +198,13 @@ export function checkStaleWorkspaces(ctx: ProactiveContext): ProactiveMessage[]
|
||||
const idleDays = Math.floor((now - referenceDate.getTime()) / (24 * 60 * 60 * 1000));
|
||||
|
||||
if (idleDays >= 14) {
|
||||
const frameCount = countMemoryFrames(ctx, ws.id);
|
||||
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} memory frame${frameCount === 1 ? '' : 's'} that may need attention.`
|
||||
? `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}`,
|
||||
@@ -207,7 +212,7 @@ export function checkStaleWorkspaces(ctx: ProactiveContext): ProactiveMessage[]
|
||||
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 frame count changes.
|
||||
// reference time) or its memory count changes.
|
||||
materialHash: materialFingerprint({ wsId: ws.id, frameCount, referenceMs: referenceDate.getTime() }),
|
||||
});
|
||||
}
|
||||
@@ -243,7 +248,7 @@ export function checkPendingTasks(ctx: ProactiveContext): ProactiveMessage[] {
|
||||
}
|
||||
|
||||
/** Suggest capabilities based on usage patterns. */
|
||||
export function suggestCapabilities(ctx: ProactiveContext): ProactiveMessage | null {
|
||||
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 {
|
||||
@@ -264,7 +269,7 @@ export function suggestCapabilities(ctx: ProactiveContext): ProactiveMessage | n
|
||||
// Count total memories across all workspaces
|
||||
let totalFrames = 0;
|
||||
for (const ws of workspaces) {
|
||||
totalFrames += countMemoryFrames(ctx, ws.id);
|
||||
totalFrames += await countMemories(ctx, ws.id);
|
||||
}
|
||||
|
||||
// If accumulating significant memories but no connectors, suggest connectors
|
||||
|
||||
Reference in New Issue
Block a user