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:
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Workspace State — structured current-state reconstruction for a workspace.
|
||||
*
|
||||
* Assembles typed, classified items from memory frames, session files,
|
||||
* Assembles typed, classified items from workspace memory, session files,
|
||||
* and awareness layer into a coherent model of "what's going on now."
|
||||
*
|
||||
* Design principles:
|
||||
@@ -12,7 +12,13 @@
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { AwarenessLayer, MindDB, WaggleDB, workspaceDataScope } from '@waggle/core';
|
||||
import { AwarenessLayer, WaggleDB, workspaceDataScope } from '@waggle/core';
|
||||
import {
|
||||
workspaceScope,
|
||||
type MemoryRecord,
|
||||
type MemoryScope,
|
||||
type MemoryStore,
|
||||
} from '@waggle/memory-contract';
|
||||
import {
|
||||
extractProgressItems,
|
||||
extractOpenQuestions,
|
||||
@@ -72,42 +78,62 @@ export function computeFreshness(dateStr: string): Freshness {
|
||||
return 'stale';
|
||||
}
|
||||
|
||||
// ── Decision extraction from memory frames ─────────────────────────────
|
||||
// ── Workspace memory reads ─────────────────────────────────────────────
|
||||
|
||||
interface DecisionFrame {
|
||||
id: number;
|
||||
content: string;
|
||||
created_at: string;
|
||||
/** Recent memories scanned for decisions. */
|
||||
const DECISION_SCAN = 200;
|
||||
/** Wording that marks a note as a decision when its kind does not. */
|
||||
const DECISION_WORDING = /^decision|decided|decision made|chose |selected |agreed /i;
|
||||
|
||||
/** A decision: its kind says so, it is critical, or its wording records one. */
|
||||
function isDecision(record: MemoryRecord): boolean {
|
||||
return record.kind === 'decision' || record.importance === 'critical' || DECISION_WORDING.test(record.text);
|
||||
}
|
||||
|
||||
function extractDecisionItems(
|
||||
raw: ReturnType<MindDB['getDatabase']>,
|
||||
/** The newest decisions of a scope, temporary memories excluded. */
|
||||
export async function listDecisions(
|
||||
memory: MemoryStore,
|
||||
scope: MemoryScope,
|
||||
max: number,
|
||||
): StateItem[] {
|
||||
const frames = raw.prepare(
|
||||
`SELECT id, content, created_at FROM memory_frames
|
||||
WHERE importance != 'deprecated' AND importance != 'temporary'
|
||||
AND (content LIKE 'Decision%' OR content LIKE '%decided%'
|
||||
OR content LIKE '%decision made%' OR content LIKE '%chose %'
|
||||
OR content LIKE '%selected %' OR content LIKE '%agreed %'
|
||||
OR importance = 'critical')
|
||||
ORDER BY id DESC LIMIT ?`,
|
||||
).all(max + 2) as DecisionFrame[];
|
||||
): Promise<MemoryRecord[]> {
|
||||
const recent = await memory.list({ scopes: [scope], minImportance: 'normal', limit: DECISION_SCAN });
|
||||
return recent.filter(isDecision).slice(0, max);
|
||||
}
|
||||
|
||||
return frames.slice(0, max).map(f => {
|
||||
const firstLine = f.content.split('\n')[0];
|
||||
const sentenceMatch = firstLine.match(/^(.+?\.\s)(?=[A-Z])/);
|
||||
const text = sentenceMatch ? sentenceMatch[1] : firstLine;
|
||||
/**
|
||||
* Up to `limit` memories of a scope, most important first and newest first
|
||||
* within one importance level; temporary memories are excluded.
|
||||
*/
|
||||
export async function listByImportance(
|
||||
memory: MemoryStore,
|
||||
scope: MemoryScope,
|
||||
limit: number,
|
||||
): Promise<MemoryRecord[]> {
|
||||
const records: MemoryRecord[] = [];
|
||||
for (const level of ['critical', 'important', 'normal'] as const) {
|
||||
if (records.length >= limit) break;
|
||||
// Every memory above `level` is already in `records`, so the newest
|
||||
// `limit + records.length` memories at or above `level` contain the
|
||||
// newest `limit` memories at `level`.
|
||||
const candidates = await memory.list({ scopes: [scope], minImportance: level, limit: limit + records.length });
|
||||
records.push(...candidates.filter(r => r.importance === level).slice(0, limit - records.length));
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
return {
|
||||
// Strip cursor/markdown artifacts (leaking `|` pipes etc.) + tail-truncate.
|
||||
content: sanitizeExtracted(text, 150),
|
||||
freshness: computeFreshness(f.created_at),
|
||||
source: 'memory' as StateSource,
|
||||
sourceId: String(f.id),
|
||||
dateLastTouched: f.created_at.slice(0, 10),
|
||||
};
|
||||
});
|
||||
function toDecisionItem(record: MemoryRecord): StateItem {
|
||||
const firstLine = record.text.split('\n')[0];
|
||||
const sentenceMatch = firstLine.match(/^(.+?\.\s)(?=[A-Z])/);
|
||||
const text = sentenceMatch ? sentenceMatch[1] : firstLine;
|
||||
|
||||
return {
|
||||
// Strip cursor/markdown artifacts (leaking `|` pipes etc.) + tail-truncate.
|
||||
content: sanitizeExtracted(text, 150),
|
||||
freshness: computeFreshness(record.createdAt),
|
||||
source: 'memory',
|
||||
sourceId: record.id,
|
||||
dateLastTouched: record.createdAt.slice(0, 10),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Active items from awareness layer ──────────────────────────────────
|
||||
@@ -209,8 +235,7 @@ function deriveNextActions(state: Omit<WorkspaceState, 'nextActions'>, max: numb
|
||||
// ── Main builder ───────────────────────────────────────────────────────
|
||||
|
||||
interface WsManagerLike {
|
||||
get: (id: string) => { id: string; name: string } | null;
|
||||
getMindPath: (id: string) => string;
|
||||
get: (id: string) => { id: string; name: string } | null | undefined;
|
||||
}
|
||||
|
||||
export interface BuildWorkspaceStateOpts {
|
||||
@@ -219,40 +244,25 @@ export interface BuildWorkspaceStateOpts {
|
||||
wsManager: WsManagerLike;
|
||||
/** waggle.db, which holds the workspace's awareness items. */
|
||||
waggleDb: WaggleDB;
|
||||
/** @deprecated Read-only state construction no longer mutates global workspace state. */
|
||||
activateWorkspaceMind?: (id: string) => boolean;
|
||||
memory: MemoryStore;
|
||||
}
|
||||
|
||||
export function buildWorkspaceState(opts: BuildWorkspaceStateOpts): WorkspaceState | null {
|
||||
const { dataDir, workspaceId, wsManager, waggleDb } = opts;
|
||||
/** Null when the workspace is unknown, has no memories yet, or its memory cannot be read. */
|
||||
export async function buildWorkspaceState(opts: BuildWorkspaceStateOpts): Promise<WorkspaceState | null> {
|
||||
const { dataDir, workspaceId, wsManager, waggleDb, memory } = opts;
|
||||
|
||||
const ws = wsManager.get(workspaceId);
|
||||
if (!ws) return null;
|
||||
|
||||
const mindPath = wsManager.getMindPath(workspaceId);
|
||||
if (!fs.existsSync(mindPath)) return null;
|
||||
|
||||
// ── Memory-sourced state ─────────────────────────────────────────
|
||||
let recentDecisions: StateItem[] = [];
|
||||
let awarenessItems: StateItem[] = [];
|
||||
let wsDb: MindDB | null = null;
|
||||
|
||||
try {
|
||||
wsDb = new MindDB(mindPath);
|
||||
const raw = wsDb.getDatabase();
|
||||
|
||||
const memoryCount = (raw.prepare('SELECT COUNT(*) as cnt FROM memory_frames').get() as { cnt: number }).cnt;
|
||||
if (memoryCount === 0) {
|
||||
wsDb.close();
|
||||
return null;
|
||||
}
|
||||
|
||||
recentDecisions = extractDecisionItems(raw, 5);
|
||||
|
||||
wsDb.close();
|
||||
wsDb = null;
|
||||
const scope = workspaceScope(workspaceId);
|
||||
if (await memory.count({ scopes: [scope] }) === 0) return null;
|
||||
recentDecisions = (await listDecisions(memory, scope, 5)).map(toDecisionItem);
|
||||
} catch {
|
||||
if (wsDb) { try { wsDb.close(); } catch { /* ignore */ } }
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user