refactor(memory): run agent recall, memory tools and the server on the memory contract (P1.5)

- Orchestrator, memory tools, context loader and pattern write-back use a
  MemoryStore and a workspace scope instead of MindDB layers; the knowledge
  graph tools, cognify, memory linker and feedback handler are gone (graph
  hidden in v1, ADR-0002).
- The server opens one mem0 store in <dataDir>/memory/, embedded by the
  in-process model on first use, and extracts facts about the user in the
  background with the model the user chose (memoryExtraction setting).
- Legacy .mind memories are copied into the store once, in the background;
  the legacy files are only read.
- Weaver consolidation, harvest, wiki, memory import, memory lanes, vector
  backfill and index reconciliation are removed; agent runs, loops, sub-agent
  results, connector fetch and the failed-turn capture write through the
  contract. Workspace sessions no longer hold a mind handle.
- FileIndexer and the install audit move to waggle.db; recall date helpers and
  the reranker are copied into core.
- The CLI REPL opens the same memory store.
This commit is contained in:
shumeiko.it
2026-10-24 11:56:26 +02:00
parent f3eb6b6652
commit 784ca770b1
86 changed files with 2520 additions and 8444 deletions

View File

@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto';
import type { FastifyInstance } from 'fastify';
import { evaluateExternalMemoryIngress, FrameStore, SessionStore } from '@waggle/core';
import { evaluateExternalMemoryIngress } from '@waggle/core';
import { recordRunResult } from './run-memory.js';
import {
createSubAgentTools,
createCronTools,
@@ -379,9 +380,9 @@ export function bindChatCollaborationTools(options: BindChatCollaborationOptions
const durableResult = guardCollaborationText(result.response, 'result');
const registryResult = registryText(result.response, 'result');
const durableTools = guardTextList(result.toolsUsed);
const memoryRefs = allowDerivedPersistence
? recordResult(server, current, workspaceId, current.task, durableResult, 'Chat sub-agent')
: undefined;
if (allowDerivedPersistence) {
recordResult(server, current, workspaceId, current.task, durableResult, 'Chat sub-agent');
}
server.agentRunRegistry.update(storedCurrent.id, {
status: 'completed',
result: { summary: registryResult, sessionId: parentSessionId },
@@ -390,7 +391,6 @@ export function bindChatCollaborationTools(options: BindChatCollaborationOptions
inputTokens: result.usage.inputTokens,
outputTokens: result.usage.outputTokens,
},
...(memoryRefs ? { memoryRefs } : {}),
progress: null,
});
emitRetainedSubagentStatus(server, workspaceId, [{
@@ -616,9 +616,9 @@ export function bindChatCollaborationTools(options: BindChatCollaborationOptions
const registryResult = registryOptionalText(event.workerState.result, 'result');
const registryError = registryOptionalText(event.workerState.error, 'error');
const durableTools = guardTextList(event.workerState.toolsUsed);
const memoryRefs = allowDerivedPersistence && status === 'completed' && durableResult
? recordResult(server, current, workspaceId, current.task, durableResult, 'Workflow worker')
: undefined;
if (allowDerivedPersistence && status === 'completed' && durableResult) {
recordResult(server, current, workspaceId, current.task, durableResult, 'Workflow worker');
}
server.agentRunRegistry.update(
storedCurrent.id,
{
@@ -631,7 +631,6 @@ export function bindChatCollaborationTools(options: BindChatCollaborationOptions
inputTokens: event.workerState.usage.inputTokens,
outputTokens: event.workerState.usage.outputTokens,
},
...(memoryRefs ? { memoryRefs } : {}),
progress: status === 'running' ? { message: 'Workflow worker running', phase: 'running' } : null,
},
TERMINAL.has(status) ? { recomputeParent: false } : undefined,
@@ -665,9 +664,9 @@ export function bindChatCollaborationTools(options: BindChatCollaborationOptions
|| current.status === 'failed' || current.status === 'interrupted') return;
const durableAggregate = guardCollaborationText(output.aggregated, 'result');
const registryAggregate = registryText(output.aggregated, 'result');
const memoryRefs = allowDerivedPersistence && durableAggregate
? recordResult(server, context.room, workspaceId, context.room.task, durableAggregate, 'Workflow aggregate')
: undefined;
if (allowDerivedPersistence && durableAggregate) {
recordResult(server, context.room, workspaceId, context.room.task, durableAggregate, 'Workflow aggregate');
}
const workerRuns = [...context.workers.values()]
.map((worker) => server.agentRunRegistry.get(worker.id));
const status = workerRuns.some((worker) => worker?.status === 'completed')
@@ -676,7 +675,6 @@ export function bindChatCollaborationTools(options: BindChatCollaborationOptions
context.terminalStatus = status;
server.agentRunRegistry.update(context.room.id, {
result: { summary: registryAggregate, sessionId: parentSessionId },
...(memoryRefs ? { memoryRefs } : {}),
progress: null,
});
},
@@ -785,6 +783,10 @@ function workerRun(run: CollaborationRun | undefined): CollaborationWorkerRun |
return run?.kind === 'worker' ? run : undefined;
}
/**
* Writes the run's result to memory in the background; the run's memoryRefs
* are updated when the writes finish.
*/
function recordResult(
server: FastifyInstance,
run: CollaborationRun,
@@ -792,53 +794,27 @@ function recordResult(
task: string,
result: string,
label: string,
): CollaborationRunMemoryRefs {
const personalFrameIds: number[] = [];
const workspaceFrameIds: Record<string, number[]> = {};
const metadata = JSON.stringify({
): void {
const metadata = {
runId: run.id, roomId: run.roomId, workspaceId,
source: run.source, parent: 'chat',
});
try {
const personal = server.multiMind.personal;
new SessionStore(personal).ensure('agent-runs', 'agent-runs', 'Agent collaboration index');
const frames = new FrameStore(personal);
const personalContent = `[${label}]\nRun: ${run.id}\nWorkspace: ${workspaceId}\nSummary: ${result.slice(0, 1_000)}`;
const frame = frames.createIFrame(
'agent-runs',
guardCollaborationText(personalContent, 'result'),
'normal', 'agent_inferred',
);
frames.setMetadata(frame.id, metadata);
personalFrameIds.push(frame.id);
} catch { /* workspace result remains authoritative */ }
let acquired = false;
try {
const workspaceMind = server.mindCache.acquire(workspaceId);
acquired = true;
new SessionStore(workspaceMind).ensure('agent-runs', 'agent-runs', 'Agent collaboration results');
const frames = new FrameStore(workspaceMind);
const workspaceContent = `[${label} result]\nRun: ${run.id}\nTask:\n${task}\n\nResult:\n${result.slice(0, 100_000)}`;
const frame = frames.createIFrame(
'agent-runs',
guardCollaborationText(workspaceContent, 'result'),
'normal', 'agent_inferred',
);
frames.setMetadata(frame.id, metadata);
workspaceFrameIds[workspaceId] = [frame.id];
} catch { /* reflected in memoryRefs status */ }
finally {
if (acquired) server.mindCache.release(workspaceId);
}
const personalOk = personalFrameIds.length > 0;
const workspaceOk = (workspaceFrameIds[workspaceId]?.length ?? 0) > 0;
return {
status: personalOk && workspaceOk ? 'complete' : personalOk || workspaceOk ? 'partial' : 'failed',
personalFrameIds,
workspaceFrameIds,
run_source: run.source, parent: 'chat',
};
void recordRunResult(server.memory, {
workspaceId,
personalText: guardCollaborationText(
`[${label}]\nRun: ${run.id}\nWorkspace: ${workspaceId}\nSummary: ${result.slice(0, 1_000)}`,
'result',
),
workspaceText: guardCollaborationText(
`[${label} result]\nRun: ${run.id}\nTask:\n${task}\n\nResult:\n${result.slice(0, 100_000)}`,
'result',
),
metadata,
}).then((memoryRefs) => {
try {
server.agentRunRegistry.update(run.id, { memoryRefs });
} catch { /* the run was removed meanwhile */ }
});
}
function publishDance(

View File

@@ -105,8 +105,8 @@ export interface ConnectorHarvestState {
export interface RunConnectorFetchDeps {
connectors: ReadonlyArray<ConnectorLike>;
/** Persist one harvested item as a memory frame. */
writeFrame: (content: string) => void;
/** Persist one harvested item as a memory. */
writeFrame: (content: string) => void | Promise<void>;
loadState: () => ConnectorHarvestState;
saveState: (state: ConnectorHarvestState) => void;
/** Minimum gap between real sweeps (frequency floor); omit to disable. */
@@ -189,7 +189,7 @@ export async function runConnectorFetch(deps: RunConnectorFetchDeps): Promise<Co
// §7: external connector data is injection-scanned before it lands in
// memory (it is recalled into model context in later sessions).
if (!scanForInjection(content, 'tool_output').safe) { res.skippedUnsafe++; continue; }
deps.writeFrame(content);
await deps.writeFrame(content);
wrote++;
}
res.framesWritten += wrote;

View File

@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import type { FastifyInstance } from 'fastify';
import { FrameStore, SessionStore } from '@waggle/core';
import { recordRunResult } from './run-memory.js';
import {
TraceRecorder,
detectTaskShape,
@@ -78,7 +78,6 @@ type FleetResultRecorder = (input: {
run: CollaborationWorkerRun;
prompt: string;
result: AgentResponse;
workspaceMind: Parameters<FastifyInstance['agentState']['createSessionOrchestrator']>[0];
}) => Promise<CollaborationRunMemoryRefs>;
declare module 'fastify' {
@@ -234,14 +233,11 @@ async function executeFleetRun(
await executionSettled;
},
});
let acquired = false;
let workspaceTurnScope: WorkspaceTurnScope | undefined;
let traceId: number | undefined;
let fleetSpendMeter: ModelSpendMeter | undefined;
try {
const mind = server.mindCache.acquire(run.workspaceId);
acquired = true;
const orchestrator = server.agentState.createSessionOrchestrator(mind);
const orchestrator = server.agentState.createSessionOrchestrator(run.workspaceId);
const persona = listPersonas().find((item) => item.id === personaId) ?? null;
fleetSpendMeter = server.agentState.costTracker
? createModelSpendMeter(server.agentState.costTracker, (costUsd) => {
@@ -298,7 +294,7 @@ async function executeFleetRun(
const assembled = await orchestrator.buildAssembledPrompt(task, persona, { taskShape });
systemPrompt = assembled.system + (assembled.responseScaffold ? `\n\n## Response shape\n${assembled.responseScaffold}` : '');
} else {
systemPrompt = orchestrator.buildSystemPrompt();
systemPrompt = await orchestrator.buildSystemPrompt();
if (persona?.systemPrompt) systemPrompt += `\n\n## Active persona\n${persona.systemPrompt}`;
}
@@ -351,8 +347,8 @@ async function executeFleetRun(
});
persistMessage(server.localConfig.dataDir, run.workspaceId, sessionId, { role: 'assistant', content: result.content });
const memoryRefs = server.fleetResultRecorder
? await server.fleetResultRecorder({ run, prompt: task, result, workspaceMind: mind })
: await recordFleetResult(server, run, task, result, mind);
? await server.fleetResultRecorder({ run, prompt: task, result })
: await recordFleetResult(server, run, task, result);
const totalTokens = result.usage.inputTokens + result.usage.outputTokens;
server.agentRunRegistry.update(run.id, {
status: controller.signal.aborted ? 'cancelling' : 'completed',
@@ -418,12 +414,8 @@ async function executeFleetRun(
try {
if (workspaceTurnScope) await workspaceTurnScope.release();
} finally {
try {
if (acquired) server.mindCache.release(run.workspaceId);
} finally {
settleExecution();
unregister();
}
settleExecution();
unregister();
}
}
}
@@ -433,41 +425,13 @@ async function recordFleetResult(
run: CollaborationWorkerRun,
prompt: string,
result: AgentResponse,
workspaceMind: Parameters<FastifyInstance['agentState']['createSessionOrchestrator']>[0],
): Promise<CollaborationRunMemoryRefs> {
const personalFrameIds: number[] = [];
const workspaceFrameIds: Record<string, number[]> = {};
const meta = JSON.stringify({ runId: run.id, roomId: run.roomId, workspaceId: run.workspaceId, source: 'fleet' });
try {
const personal = server.multiMind.personal;
new SessionStore(personal).ensure('agent-runs', 'agent-runs', 'Agent collaboration index');
const frames = new FrameStore(personal);
const frame = frames.createIFrame(
'agent-runs',
`[Agent run]\nRun: ${run.id}\nWorkspace: ${run.workspaceId}\nPersona: ${run.executor.personaId}\nSummary: ${result.content.slice(0, 1_000)}`,
'normal', 'agent_inferred',
);
frames.setMetadata(frame.id, meta);
personalFrameIds.push(frame.id);
} catch { /* workspace result remains authoritative */ }
try {
new SessionStore(workspaceMind).ensure('agent-runs', 'agent-runs', 'Agent collaboration results');
const frames = new FrameStore(workspaceMind);
const frame = frames.createIFrame(
'agent-runs',
`[Agent run result]\nRun: ${run.id}\nTask:\n${prompt}\n\nResult:\n${result.content.slice(0, 100_000)}`,
'normal', 'agent_inferred',
);
frames.setMetadata(frame.id, meta);
workspaceFrameIds[run.workspaceId] = [frame.id];
} catch { /* reflected in status below */ }
const personalOk = personalFrameIds.length > 0;
const workspaceOk = (workspaceFrameIds[run.workspaceId]?.length ?? 0) > 0;
return {
status: personalOk && workspaceOk ? 'complete' : (personalOk || workspaceOk ? 'partial' : 'failed'),
personalFrameIds,
workspaceFrameIds,
};
return recordRunResult(server.memory, {
workspaceId: run.workspaceId,
personalText: `[Agent run]\nRun: ${run.id}\nWorkspace: ${run.workspaceId}\nPersona: ${run.executor.personaId}\nSummary: ${result.content.slice(0, 1_000)}`,
workspaceText: `[Agent run result]\nRun: ${run.id}\nTask:\n${prompt}\n\nResult:\n${result.content.slice(0, 100_000)}`,
metadata: { runId: run.id, roomId: run.roomId, workspaceId: run.workspaceId, run_source: 'fleet' },
});
}
function publishFleetDance(

View File

@@ -1,55 +0,0 @@
/**
* harvest-autosync-frame.ts — shared writer for auto-synced harvest summary frames.
*
* The 30-min in-process auto-sync (index.ts runHarvestAutoSync) and the cron
* `harvest_sync` both scan filesystem sources (currently claude-code) and persist
* a lighter summary frame than the manual /api/harvest route. They previously
* wrote the frame with NO metadata, so a subject-level GDPR Art.17 erasure
* (MindErasure.eraseBySourceRef) could not reach them: step 2a keys on archiveUids
* (absent here), 2b on the raw-turn conversation prefix (these paths write no
* raw-turns), and 2c on metadata.sourceId (absent) — so the distilled PII stayed
* recall-able after a DSAR. This helper stamps the subject key so 2c reaches it,
* matching the manual path (routes/harvest.ts) and the harvest_import MCP tool;
* routing both call sites through it keeps that contract from drifting between them.
*/
import {
evaluateExternalMemoryIngress,
projectExternalMemoryContent,
type FrameStore,
type MemoryFrame,
type UniversalImportItem,
} from '@waggle/core';
/** Preview cap for auto-synced summaries — intentionally lighter than the manual
* path's HARVEST_PREVIEW_CAP_CHARS (these are unattended background scans). */
export const AUTOSYNC_PREVIEW_CAP = 4000;
/**
* Write one auto-synced harvest summary frame and stamp its subject key
* (metadata.sourceId = item.id) so a subject-mode DSAR can reach it. Guarded so a
* re-synced dedup'd frame never clobbers a review status the user already set
* (createIFrame returns the existing frame on a content-hash match). Returns
* null when the exact summary projection is unsafe; no frame or metadata write
* occurs in that case.
*/
export function writeAutoSyncSummaryFrame(frames: FrameStore, item: UniversalImportItem): MemoryFrame | null {
const label = `[Harvest:${item.source}] ${item.title}`;
const content = item.content.slice(0, AUTOSYNC_PREVIEW_CAP);
const storedContent = `${label}\n\n${content}`;
const ingressContent = projectExternalMemoryContent({
content: item.content,
messages: item.messages,
parseMethod: item.metadata?.parseMethod,
maxChars: AUTOSYNC_PREVIEW_CAP,
});
if (evaluateExternalMemoryIngress({ title: label, content: ingressContent }).action === 'block') {
return null;
}
const frame = frames.createIFrame('harvest', storedContent, 'normal', 'import');
if (!frame.metadata || frame.metadata === '{}') {
frames.setMetadata(frame.id, JSON.stringify({ sourceId: item.id }));
}
return frame;
}

View File

@@ -17,7 +17,6 @@ import { fetchTeamServer } from './team-server-egress.js';
import { getStorageProvider } from './storage/index.js';
import { isLoopbackBind, resolveBindHost } from './net-config.js';
import { isLocalRequest } from './origin-guard.js';
import { MemoryWeaver } from '@waggle/weaver';
import {
Orchestrator,
createSystemTools,
@@ -67,7 +66,10 @@ import { PluginRuntimeManager, getStarterSkillsDir, validatePluginManifest } fro
import { MarketplaceDB, MarketplaceSync, seedMcpServers, seedNewSources } from '@waggle/marketplace';
import type { RiskLevel } from '@waggle/shared';
import { runConnectorFetch } from './connector-harvest.js';
import { writeAutoSyncSummaryFrame } from './harvest-autosync-frame.js';
import { openMemoryStore } from './memory-runtime.js';
import { MemoryExtractionQueue } from './memory-extraction.js';
import { importLegacyMemories, type LegacyMemorySource } from './legacy-memory-import.js';
import { PERSONAL_SCOPE, workspaceScope, type MemoryStore } from '@waggle/memory-contract';
import { runLoopTick } from './loop-executor.js';
import { enqueueHeldAction } from './held-action-executor.js';
import { workspaceRoutes } from './routes/workspaces.js';
@@ -77,11 +79,10 @@ import { memoryCenterRoutes } from './routes/memory-center.js';
import { artifactRoutes } from './routes/artifacts.js';
import { settingsRoutes } from './routes/settings.js';
import { embeddingRoutes, buildEmbeddingStatusPayload } from './routes/embedding.js';
import { sessionRoutes, findUndistilledSessions, markSessionDistilled } from './routes/sessions.js';
import { sessionRoutes } from './routes/sessions.js';
import { knowledgeRoutes } from './routes/knowledge.js';
import { litellmRoutes } from './routes/litellm.js';
import { runMemoryLaneExtraction } from './memory-lane-cron.js';
import { VectorEnrichmentService } from './services/vector-enrichment-service.js';
import { waggleDanceRoutes } from './routes/waggle-dance.js';
import { ingestRoutes, readFileRegistry } from './routes/ingest.js';
import { mindRoutes } from './routes/mind.js';
import { agentRoutes } from './routes/agent.js';
@@ -97,7 +98,6 @@ import { capabilitiesRoutes } from './routes/capabilities.js';
import { toolsRoutes } from './routes/tools.js';
import { externalToolRunRoutes } from './routes/external-tool-runs.js';
import { routeProposalRoutes } from './routes/route-proposals.js';
import { waggleDanceRoutes } from './routes/waggle-dance.js';
import { commandRoutes } from './routes/commands.js';
import { commandRoutes as commandCenterRoutes } from './routes/command.js';
import { homeRoutes } from './routes/home.js';
@@ -118,7 +118,6 @@ import { extendRoutes } from './routes/extend.js';
import { populateMcpRuntimeFromConfig } from './mcp-config.js';
import { scheduleMarketplaceBackgroundSync } from './marketplace-background-sync.js';
import { fleetRoutes } from './routes/fleet.js';
import { importRoutes } from './routes/import.js';
import { vaultRoutes } from './routes/vault.js';
import { personaRoutes } from './routes/personas.js';
import { feedbackRoutes } from './routes/feedback.js';
@@ -129,7 +128,6 @@ import { dataEraseRoutes } from './routes/data-erase.js';
import { costRoutes } from './routes/cost.js';
import { backupRoutes } from './routes/backup.js';
import { offlineRoutes } from './routes/offline.js';
import { weaverRoutes } from './routes/weaver.js';
import { eventRoutes, closeAuditDb, cleanupAuditEvents, emitAuditEvent } from './routes/events.js';
import { closeTeamsDb } from './routes/team.js';
import { pinRoutes } from './routes/pins.js';
@@ -159,8 +157,6 @@ import { agentGroupRoutes } from './routes/agent-groups.js';
import { localJobRoutes } from './routes/jobs.js';
import { agentEntityRoutes } from './routes/agents.js';
import { automationRoutes } from './routes/automations.js';
import { harvestRoutes } from './routes/harvest.js';
import { wikiRoutes } from './routes/wiki.js';
import { identityRoutes } from './routes/identity.js';
import { agentRunRoutes } from './routes/agent-run.js';
import { agentRunsRoutes } from './routes/agent-runs.js';
@@ -320,10 +316,7 @@ export interface AgentState {
* Create a fresh Orchestrator for a workspace session with the given mind mounted.
* Each session gets its own instance (Option Y fix from docs/plans/phase-a-the-room.md §9).
*/
createSessionOrchestrator: {
(): Orchestrator;
(workspaceMind: import('@waggle/core').MindDB): Orchestrator;
};
createSessionOrchestrator: (workspaceId?: string) => Orchestrator;
/**
* Build the full tool pool for a session, using the session's orchestrator for mind tools.
* When `sourceWorkspaceId` is provided, also injects Phase B.2 cross-workspace read tools
@@ -366,10 +359,6 @@ export interface AgentState {
wsSessionToken: string;
/** SHA-256 hash of the paired Browser Companion credential, or null when unpaired. */
browserCompanionCredentialHash: string | null;
/** Memory-weaver run timestamps for the personal mind. */
weaverState: { lastPersonalConsolidation: string | null; lastPersonalDecay: string | null };
/** Per-workspace memory-weaver run timestamps, keyed by workspace ID. */
workspaceWeaverStatus: Record<string, { lastConsolidation: string | null }>;
}
declare module 'fastify' {
@@ -383,6 +372,10 @@ declare module 'fastify' {
auditStore: import('@waggle/core').InstallAuditStore;
cronStore: import('@waggle/core').CronStore;
waggleDb: import('@waggle/core').WaggleDB;
/** Memory (ADR-0007): personal and workspace memories, reached only through the contract. */
memory: MemoryStore;
/** Background fact extraction from chat turns (ADR-0007, decision 6). */
memoryExtraction: MemoryExtractionQueue;
traceStore: import('@waggle/core').ExecutionTraceStore;
/** Active behavioral spec — the compiled `BEHAVIORAL_SPEC` baseline. */
activeBehavioralSpec: ReturnType<typeof import('@waggle/agent').buildActiveBehavioralSpec>;
@@ -528,7 +521,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
}
// Install audit store — persistent trail for capability install events
const auditStore = new InstallAuditStore(multiMind.personal);
const auditStore = new InstallAuditStore(waggleDb);
server.decorate('auditStore', auditStore);
// Cron store — SQLite-backed schedule persistence for Solo
@@ -710,11 +703,33 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
const waggleHome = fullConfig.dataDir || path.join(os.homedir(), '.waggle');
const rerankerCacheDir = path.join(waggleHome, 'models', 'reranker');
// Orchestrator — connects to personal .mind
// Memory (ADR-0007): one mem0 store in <dataDir>/memory/, embedded by the
// in-process model. Facts are extracted with the model the user chose,
// through the built-in proxy (or LiteLLM when the user runs it).
const memory = await openMemoryStore({
dataDir: fullConfig.dataDir,
modelCacheDir: embeddingConfig.inprocess?.cacheDir ?? path.join(waggleHome, 'models'),
embeddingModel: embeddingConfig.inprocess?.model,
extraction: {
baseURL: fullConfig.useBuiltInProxy
? `http://127.0.0.1:${fullConfig.port}/v1`
: fullConfig.litellmUrl,
apiKey: litellmApiKey,
model: () => server.agentState?.currentModel || 'claude-sonnet-4-6',
},
});
server.decorate('memory', memory);
const memoryExtraction = new MemoryExtractionQueue({
memory,
isEnabled: () => new WaggleConfig(fullConfig.dataDir).getMemoryExtraction(),
onError: (err) => log.warn(`[memory] fact extraction failed: ${err instanceof Error ? err.message : String(err)}`),
});
server.decorate('memoryExtraction', memoryExtraction);
// Orchestrator — personal memory; a workspace is added with setWorkspace()
const orchestrator = new Orchestrator({
db: multiMind.personal,
memory,
waggleDb,
embedder,
mode: 'local',
version: '0.4',
rerankerCacheDir,
@@ -858,27 +873,18 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
// main-agent-visible return path stays intact.
try {
const wsId = server.agentState.activeWorkspaceId;
const wsDb = wsId ? mindCache.getOrOpen(wsId) : null;
const targetDb = wsDb ?? multiMind.personal;
const mindLabel = wsDb ? `workspace:${wsId}` : 'personal';
const scope = wsId ? workspaceScope(wsId) : PERSONAL_SCOPE;
// Structured content: tag provenance so search can filter
// for sub-agent-derived frames and so humans can see where it came from.
// Structured content: tag provenance so humans can see where it came from.
const content = `[Sub-agent: ${result.role}] ${result.agentName}\n\n${result.response}\n\n— tools: ${result.toolsUsed.join(', ') || 'none'} · ${(result.duration / 1000).toFixed(1)}s · ${result.usage.inputTokens + result.usage.outputTokens} tokens`;
// Use raw frames — cognify requires a per-mind pipeline we don't
// construct here; the decayFrames weaver will pick these up later.
const frames = new FrameStore(targetDb);
const sessions = new SessionStore(targetDb);
const active = sessions.getActive();
const gopId = active.length > 0 ? active[0].gop_id : sessions.create().gop_id;
const latestI = frames.getLatestIFrame(gopId);
if (latestI) {
frames.createPFrame(gopId, content, latestI.id, 'normal', 'agent_inferred');
} else {
frames.createIFrame(gopId, content, 'normal', 'agent_inferred');
}
log.debug(`Gap L: persisted sub-agent result ${result.agentId} to ${mindLabel} mind`);
await memory.remember({
scope,
text: content,
kind: 'note',
source: 'agent_inferred',
origin: 'sub-agent',
});
log.debug(`Gap L: persisted sub-agent result ${result.agentId} to ${wsId ? `workspace:${wsId}` : 'personal'} memory`);
} catch (err) {
log.debug('Gap L: sub-agent persistence failed (non-blocking)', err);
}
@@ -1200,16 +1206,15 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
*
* See docs/plans/phase-a-the-room.md §9 for the Option X vs Option Y decision.
*/
const createSessionOrchestrator = (workspaceMind?: MindDB): Orchestrator => {
const createSessionOrchestrator = (workspaceId?: string): Orchestrator => {
const sessionOrch = new Orchestrator({
db: multiMind.personal,
memory,
waggleDb,
embedder,
mode: 'local',
version: '0.4',
rerankerCacheDir,
});
if (workspaceMind) sessionOrch.setWorkspaceMind(workspaceMind);
if (workspaceId) sessionOrch.setWorkspace(workspaceId);
return sessionOrch;
};
@@ -1231,8 +1236,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
const crossTools = createCrossWorkspaceTools({
sourceWorkspaceId,
embedder,
getMindForWorkspace: (id) => mindCache.getOrOpen(id),
memory,
listWorkspaces: () => wsManager.list().map(w => ({ id: w.id, name: w.name })),
listWorkspaceFiles: async (id, subPath) => {
try {
@@ -1268,14 +1272,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
allowedRoot: path.join(fullConfig.dataDir, 'workspaces'),
});
server.decorate('mindCache', mindCache);
const vectorEnrichmentService = new VectorEnrichmentService({
personalMind: multiMind.personal,
embeddingProvider,
listWorkspaceIds: () => wsManager.list().map(workspace => workspace.id),
acquireWorkspaceMind: workspaceId => mindCache.acquire(workspaceId),
releaseWorkspaceMind: workspaceId => mindCache.release(workspaceId),
log: (level, message) => log[level](message),
});
let activeWorkspaceId: string | null = null;
const setActiveWorkspaceId = (workspaceId: string | null): void => {
activeWorkspaceId = workspaceId;
@@ -1283,271 +1279,16 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
if (decorated) decorated.activeWorkspaceId = workspaceId;
};
// ── TeamSync cache — one TeamSync instance per team workspace ──
const teamSyncCache = new Map<string, { sync: TeamSync; binding: string }>();
const serializeTeamSyncBinding = (
teamServer: NonNullable<ReturnType<WaggleConfig['getTeamServer']>>,
teamId: string,
): string => JSON.stringify({
url: teamServer.url,
teamId,
token: crypto.createHash('sha256').update(teamServer.token ?? '').digest('hex'),
userId: teamServer.userId ?? 'local-user',
displayName: teamServer.displayName ?? 'You',
});
function getTeamSync(workspaceId: string, wsConfig: WorkspaceConfig | null, waggleConfig: WaggleConfig): TeamSync | null {
if (!wsConfig?.teamId || !wsConfig?.teamServerUrl) {
teamSyncCache.delete(workspaceId);
return null;
}
const teamServer = getBoundTeamServer(wsConfig.teamServerUrl, waggleConfig.getTeamServer());
if (!teamServer?.token) {
teamSyncCache.delete(workspaceId);
return null;
}
const binding = serializeTeamSyncBinding(teamServer, wsConfig.teamId);
const cached = teamSyncCache.get(workspaceId);
if (cached?.binding === binding) return cached.sync;
const sync = new TeamSync({
teamServerUrl: teamServer.url,
teamSlug: wsConfig.teamId, // teamId is used as slug
authToken: teamServer.token,
userId: teamServer.userId ?? 'local-user',
displayName: teamServer.displayName ?? 'You',
}, fetchTeamServer);
const pushFrame = sync.pushFrame.bind(sync);
sync.pushFrame = async (frame) => {
const currentWorkspace = wsManager.get(workspaceId);
const currentWaggleConfig = new WaggleConfig(fullConfig.dataDir);
const currentTeamServer = getBoundTeamServer(
currentWorkspace?.teamServerUrl,
currentWaggleConfig.getTeamServer(),
);
const currentBinding = currentWorkspace?.teamId && currentTeamServer?.token
? serializeTeamSyncBinding(currentTeamServer, currentWorkspace.teamId)
: null;
const cached = teamSyncCache.get(workspaceId);
if (cached?.sync !== sync) {
return cached && currentBinding === cached.binding
? cached.sync.pushFrame(frame)
: null;
}
if (currentBinding === binding) return pushFrame(frame);
teamSyncCache.delete(workspaceId);
if (currentWorkspace?.teamId && currentTeamServer?.token) {
const replacement = getTeamSync(workspaceId, currentWorkspace, currentWaggleConfig);
if (replacement) {
if (activeWorkspaceId === workspaceId) orchestrator.setTeamSync(replacement);
return replacement.pushFrame(frame);
}
}
if (activeWorkspaceId === workspaceId) orchestrator.setTeamSync(null);
return null;
};
teamSyncCache.set(workspaceId, { sync, binding });
return sync;
}
/**
* Activate a workspace's .mind file on the orchestrator.
* Opens the mind if not cached, then calls setWorkspaceMind().
*/
/** Make a workspace's memory active on the shared orchestrator. */
const activateWorkspaceMind = (workspaceId: string): boolean => {
if (activeWorkspaceId === workspaceId) return true; // already active
if (!wsManager.get(workspaceId)) return false;
const wsDb = mindCache.getOrOpen(workspaceId);
if (!wsDb) return false;
orchestrator.setWorkspaceMind(wsDb);
orchestrator.setWorkspace(workspaceId);
setActiveWorkspaceId(workspaceId);
return true;
};
// ── Memory Weaver — background consolidation & decay (A1 fix) ────
// Runs on the personal mind at startup. Workspace minds get weavers when activated.
const personalFrames = new FrameStore(multiMind.personal);
const personalSessions = new SessionStore(multiMind.personal);
const personalWeaver = new MemoryWeaver(multiMind.personal, personalFrames, personalSessions);
const weaverTimers: NodeJS.Timeout[] = [];
const workspaceWeavers = new Map<string, { weaver: MemoryWeaver; timers: NodeJS.Timeout[] }>();
// F2: Track weaver last-run timestamps for status endpoint
const weaverState: { lastPersonalConsolidation: string | null; lastPersonalDecay: string | null } = {
lastPersonalConsolidation: null,
lastPersonalDecay: null,
};
const workspaceWeaverStatus: Record<string, { lastConsolidation: string | null }> = {};
// Run personal mind weaver on intervals
const runPersonalConsolidation = () => {
try {
const active = personalSessions.getActive();
for (const s of active) personalWeaver.consolidateGop(s.gop_id);
weaverState.lastPersonalConsolidation = new Date().toISOString();
} catch (err) { log.debug('Personal consolidation skipped', err); }
};
const runPersonalDecay = () => {
try {
personalWeaver.decayFrames();
personalWeaver.strengthenFrames();
weaverState.lastPersonalDecay = new Date().toISOString();
} catch (err) { log.debug('Personal decay skipped', err); }
};
weaverTimers.push(setInterval(runPersonalConsolidation, 60 * 60 * 1000)); // hourly
weaverTimers.push(setInterval(runPersonalDecay, 24 * 60 * 60 * 1000)); // daily
// ── Harvest auto-sync — poll stale sources every 30 min ──
const runHarvestAutoSync = async () => {
try {
const harvestStore = new HarvestSourceStore(multiMind.personal);
const stale = harvestStore.getStale();
if (stale.length === 0) return;
const { ClaudeCodeAdapter: CCA } = await import('@waggle/core');
const personalSessionStore = new SessionStore(multiMind.personal);
personalSessionStore.ensure('harvest', 'harvest', 'Imported memory from external sources');
const personalFrameStore = new FrameStore(multiMind.personal);
// #7 sticky erasure: don't re-materialize an erased subject on auto-sync.
const suppression = new SuppressionStore(multiMind.personal);
for (const src of stale) {
try {
// Only auto-sync filesystem-scannable sources
if (src.source !== 'claude-code') continue;
const homedir = (await import('node:os')).default.homedir();
const scanDir = (await import('node:path')).default.join(homedir, '.claude');
const adapter = new CCA();
const items = adapter.scan(scanDir);
if (items.length === 0) continue;
let saved = 0;
let couldNotVerify = 0;
let skippedUnsafe = 0;
for (const item of items) {
// #7 sticky erasure: distinguish a confirmed erasure MATCH from a
// fail-closed read ERROR — both skip the write, but a broken-DB read
// must be reported as "could not verify", not silently as "erased".
const supp = suppression.checkSuppressed(item.source, item.id);
if (supp.suppressed) {
if (supp.reason === 'error') couldNotVerify++;
continue; // #7 Art.17 erased (or unverifiable — fail-closed skip)
}
// #7 Art.17: stamp the subject key (metadata.sourceId) so a subject-mode
// DSAR can reach this auto-synced summary — shared with the cron path.
if (!writeAutoSyncSummaryFrame(personalFrameStore, item)) {
skippedUnsafe++;
continue;
}
saved++;
}
// R3-004: store the content digest so the manual harvest route can
// skip an unchanged re-scan on the next sync.
harvestStore.recordSync(src.source, items.length, saved, harvestSetHash(items));
log.info(`[harvest-auto-sync] ${src.source}: imported ${saved} items`
+ (couldNotVerify > 0 ? ` (${couldNotVerify} could not be verified against the erasure list — skipped, fail-closed)` : '')
+ (skippedUnsafe > 0 ? ` (${skippedUnsafe} unsafe items skipped)` : ''));
} catch (err) {
log.debug(`[harvest-auto-sync] ${src.source} failed:`, err);
}
}
} catch (err) {
log.debug('[harvest-auto-sync] skipped:', err);
}
};
weaverTimers.push(setInterval(runHarvestAutoSync, 30 * 60 * 1000)); // every 30 min
// Extend activateWorkspaceMind to also start a weaver for the workspace
// and distill any undistilled sessions into durable memory frames.
const baseActivateWorkspaceMind = activateWorkspaceMind;
const activateWorkspaceMindWithWeaver = (workspaceId: string): boolean => {
const result = baseActivateWorkspaceMind(workspaceId);
// E4: Workspace topic tracking REMOVED — was saving to personal mind, causing
// cross-workspace leakage. Workspace names are available from workspace config
// and don't need to be duplicated into memory frames.
if (result && !workspaceWeavers.has(workspaceId)) {
const wsDb = mindCache.getIfOpen(workspaceId);
if (wsDb) {
const wsFrames = new FrameStore(wsDb);
const wsSessions = new SessionStore(wsDb);
const wsWeaver = new MemoryWeaver(wsDb, wsFrames, wsSessions);
const timers: NodeJS.Timeout[] = [];
timers.push(setInterval(() => {
try {
const active = wsSessions.getActive();
for (const s of active) wsWeaver.consolidateGop(s.gop_id);
} catch { /* non-blocking */ }
}, 60 * 60 * 1000));
timers.push(setInterval(() => {
try { wsWeaver.decayFrames(); wsWeaver.strengthenFrames(); } catch (err) { log.debug('Workspace memory decay skipped', err); }
}, 24 * 60 * 60 * 1000));
workspaceWeavers.set(workspaceId, { weaver: wsWeaver, timers });
// E2: Distill undistilled sessions into durable memory frames on activation
try {
const sessionsDir = path.join(fullConfig.dataDir, 'workspaces', workspaceId, 'sessions');
const undistilled = findUndistilledSessions(sessionsDir);
for (const session of undistilled) {
const distilled = wsWeaver.distillSessionContent(session.date, session.summary, session.keyPoints);
if (distilled) markSessionDistilled(session.filePath);
}
} catch (err) { log.debug('Workspace distillation skipped', err); }
}
}
// After mind activation for team workspaces — pull remote frames
if (result) {
const wsConfig = wsManager.get(workspaceId);
if (wsConfig?.teamId) {
const sync = getTeamSync(workspaceId, wsConfig, new WaggleConfig(fullConfig.dataDir));
if (sync) {
// Set TeamSync on the orchestrator for push-on-write
orchestrator.setTeamSync(sync);
// Pull team frames into local workspace mind
const wsDb = mindCache.getIfOpen(workspaceId);
if (wsDb) {
const wsSessionStore = new SessionStore(wsDb);
wsSessionStore.ensure('team-sync', 'team-sync', 'Frames synced from team server');
const wsFrameStore = new FrameStore(wsDb);
sync.pullFrames(sync.getLastSyncTimestamp() ?? undefined).then(pulled => {
if (pulled.length === 0) return;
let inserted = 0;
for (const f of pulled) {
try {
// Provenance is carried in the content prefix ([Team:author]); the source
// column must be schema-valid, so use 'import' (these frames are imported
// from the team server). Previously passed 'team_sync', which violated the
// memory_frames.source CHECK → every pulled frame was silently skipped.
wsFrameStore.createIFrame('team-sync', `[Team:${f.authorName}] ${f.content}`, f.importance, 'import');
inserted++;
} catch { /* duplicate or constraint — skip */ }
}
if (inserted > 0) {
log.info(`TeamSync: pulled ${inserted} new frames for workspace ${workspaceId}`);
}
}).catch(err => {
log.warn(`TeamSync pull failed:`, err.message);
});
}
} else {
orchestrator.setTeamSync(null);
}
} else {
// Non-team workspace — clear TeamSync
orchestrator.setTeamSync(null);
}
}
return result;
};
// Helper: get a cached workspace MindDB (opens on demand)
// A6: Close and remove workspace mind DB from cache before deletion
const closeWorkspaceMind = (workspaceId: string): void => {
@@ -1559,10 +1300,8 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
// and this seam closed the same MindDB.
sessionManager.close(workspaceId);
mindCache.close(workspaceId);
teamSyncCache.delete(workspaceId);
if (activeWorkspaceId === workspaceId) {
orchestrator.setTeamSync(null);
orchestrator.clearWorkspaceMind();
orchestrator.setWorkspace(null);
setActiveWorkspaceId(null);
}
};
@@ -1590,13 +1329,11 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
createSessionOrchestrator,
buildToolsForSession,
bindWorkspaceCollaborationTools,
activateWorkspaceMind: activateWorkspaceMindWithWeaver,
activateWorkspaceMind: activateWorkspaceMind,
getWorkspaceMindDb,
closeWorkspaceMind,
listWorkspaces: () => wsManager.list().map(w => ({ id: w.id, name: w.name })),
activeWorkspaceId,
weaverState,
workspaceWeaverStatus,
subagentOrchestrator: null,
pluginRuntimeManager,
mcpRuntime,
@@ -1611,7 +1348,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
wsSessionToken,
browserCompanionCredentialHash,
});
activateWorkspaceMindWithWeaver(defaultWorkspaceId);
activateWorkspaceMind(defaultWorkspaceId);
// Wire up skill hot-reload callback
const reloadSkills = (fresh: LoadedSkill[]) => {
@@ -1642,33 +1379,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
case 'memory_consolidation': {
// Check if this is a marketplace sync (uses memory_consolidation type for system-level scheduling)
const mcJobConfig = JSON.parse(schedule.job_config || '{}');
if (mcJobConfig.action === 'index_reconcile') {
try {
// Reconcile personal mind FTS/vec indexes
const result = await reconcileIndexes(multiMind.personal);
if (result.ftsFixed > 0 || result.vecFixed > 0) {
log.info(`[cron] Index reconciliation: FTS=${result.ftsFixed} vec=${result.vecFixed} fixed (personal)`);
}
// Reconcile workspace minds
let ftsTotal = result.ftsFixed;
let vecTotal = result.vecFixed;
const workspaces = wsManager.list();
for (const ws of workspaces) {
const wsDb = getWorkspaceMindDb(ws.id);
if (wsDb) {
const wsResult = await reconcileIndexes(wsDb);
if (wsResult.ftsFixed > 0 || wsResult.vecFixed > 0) {
log.info(`[cron] Index reconciliation: FTS=${wsResult.ftsFixed} vec=${wsResult.vecFixed} fixed (workspace "${ws.name}")`);
}
ftsTotal += wsResult.ftsFixed;
vecTotal += wsResult.vecFixed;
}
}
dreamJournal.record('index_reconcile', { ftsFixed: ftsTotal, vecFixed: vecTotal });
} catch (err) {
log.warn(`[cron] Index reconciliation failed: ${(err as Error).message}`);
}
} else if (mcJobConfig.action === 'marketplace_sync' && marketplaceDb) {
if (mcJobConfig.action === 'marketplace_sync' && marketplaceDb) {
try {
const vaultLookup = server.vault ? (key: string) => server.vault!.get(key)?.value ?? null : undefined;
const sync = new MarketplaceSync(marketplaceDb, vaultLookup, (url, init) => safeFetch(url, init));
@@ -1688,178 +1399,11 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
} catch (err) {
log.warn(`[cron] Marketplace sync failed: ${(err as Error).message}`);
}
} else if (mcJobConfig.action === 'harvest_sync') {
// Phase 7: Memory Harvest — scan registered filesystem sources for new data.
// Only filesystem-based sources (currently claude-code) can auto-sync; API-based
// sources like chatgpt/gemini require user-uploaded exports.
try {
// Frames have a FK to sessions(gop_id) — ensure the stable
// `harvest` session row exists before creating any frames.
new SessionStore(multiMind.personal).ensure('harvest', 'harvest', 'Imported memory from external sources');
const harvestStore = new HarvestSourceStore(multiMind.personal);
const personalFrames = new FrameStore(multiMind.personal);
// #7 sticky erasure: don't re-materialize an erased subject on cron sync.
const suppression = new SuppressionStore(multiMind.personal);
const stale = harvestStore.getStale();
let totalItems = 0;
let totalFrames = 0;
let sourcesScanned = 0;
let totalCouldNotVerify = 0;
let totalSkippedUnsafe = 0;
for (const src of stale) {
if (src.source !== 'claude-code' || !src.sourcePath) continue;
try {
const adapter = new ClaudeCodeAdapter();
const items = adapter.scan(src.sourcePath);
let saved = 0;
for (const item of items) {
// #7 sticky erasure: a fail-closed read ERROR is skipped like a
// MATCH but tallied separately (report "could not verify", not "erased").
const supp = suppression.checkSuppressed(item.source, item.id);
if (supp.suppressed) {
if (supp.reason === 'error') totalCouldNotVerify++;
continue; // #7 Art.17 erased (or unverifiable — fail-closed skip)
}
// #7 Art.17: stamp the subject key (metadata.sourceId) so a
// subject-mode DSAR reaches this cron-synced summary — shared helper.
if (!writeAutoSyncSummaryFrame(personalFrames, item)) {
totalSkippedUnsafe++;
continue;
}
saved++;
}
// R3-004: store the content digest for next-sync skip.
harvestStore.recordSync(src.source, items.length, saved, harvestSetHash(items));
totalItems += items.length;
totalFrames += saved;
sourcesScanned++;
} catch (innerErr) {
log.warn(`[cron] Harvest sync: source "${src.source}" failed: ${(innerErr as Error).message}`);
}
}
if (sourcesScanned > 0) {
log.info(`[cron] Harvest sync: ${totalFrames} frames from ${totalItems} items across ${sourcesScanned} source(s)`
+ (totalCouldNotVerify > 0 ? ` (${totalCouldNotVerify} could not be verified against the erasure list — skipped, fail-closed)` : '')
+ (totalSkippedUnsafe > 0 ? ` (${totalSkippedUnsafe} unsafe items skipped)` : ''));
}
dreamJournal.record('harvest_sync', {
framesSaved: totalFrames,
itemsScanned: totalItems,
sourcesScanned,
couldNotVerify: totalCouldNotVerify,
});
} catch (err) {
log.warn(`[cron] Harvest sync failed: ${(err as Error).message}`);
}
} else if (mcJobConfig.action === 'memory_compact') {
// Phase 9a: Memory compaction — prune temporary/deprecated frames, merge stale P-frames.
// Runs across personal mind and every workspace mind.
try {
const personalResult = new FrameStore(multiMind.personal).compact();
let wsTempPruned = 0;
let wsDepPruned = 0;
let wsMerged = 0;
for (const ws of wsManager.list()) {
const wsDb = getWorkspaceMindDb(ws.id);
if (!wsDb) continue;
try {
const r = new FrameStore(wsDb).compact();
wsTempPruned += r.temporaryPruned;
wsDepPruned += r.deprecatedPruned;
wsMerged += r.pframesMerged;
} catch (innerErr) {
log.warn(`[cron] Memory compaction: workspace "${ws.name}" failed: ${(innerErr as Error).message}`);
}
}
dreamJournal.record('memory_compact', {
temporaryPruned: personalResult.temporaryPruned + wsTempPruned,
deprecatedPruned: personalResult.deprecatedPruned + wsDepPruned,
pframesMerged: personalResult.pframesMerged + wsMerged,
});
const total =
personalResult.temporaryPruned + personalResult.deprecatedPruned + personalResult.pframesMerged +
wsTempPruned + wsDepPruned + wsMerged;
if (total > 0) {
log.info(
`[cron] Memory compaction: personal(temp=${personalResult.temporaryPruned}, dep=${personalResult.deprecatedPruned}, merged=${personalResult.pframesMerged}) ` +
`workspaces(temp=${wsTempPruned}, dep=${wsDepPruned}, merged=${wsMerged})`
);
}
} catch (err) {
log.warn(`[cron] Memory compaction failed: ${(err as Error).message}`);
}
} else if (mcJobConfig.action === 'memory_lane_extract') {
// W4.3d: extraction of the benchmark-proven recall lanes
// (facts/events/profiles) over frames written since the last run.
// Routes through the built-in proxy ('fast' tier = haiku) — the
// same internal-LLM pattern as the other cron LLM calls.
try {
const llmCall = async (prompt: string, _model: 'fast' | 'accurate'): Promise<string> => {
const proxyUrl = `http://127.0.0.1:${fullConfig.port ?? 3333}/v1/chat/completions`;
const res = await fetch(proxyUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(90_000),
body: JSON.stringify({
model: 'claude-haiku-4-5',
max_tokens: 4096,
messages: [{ role: 'user', content: prompt }],
}),
});
if (!res.ok) throw new Error(`lane-extract LLM HTTP ${res.status}`);
const data = await res.json() as unknown;
return parseOpenAiTextCompletion(data).content;
};
const minds: Array<{ label: string; db: import('@waggle/core').MindDB }> = [
{ label: 'personal', db: multiMind.personal },
];
for (const ws of wsManager.list()) {
const wsDb = getWorkspaceMindDb(ws.id);
if (wsDb) minds.push({ label: `workspace "${ws.name}"`, db: wsDb });
}
let laneFramesProcessed = 0;
let laneFacts = 0;
let laneEvents = 0;
let laneProfiles = 0;
for (const mind of minds) {
try {
const r = await runMemoryLaneExtraction(mind.db, llmCall);
if (!r.skipped) {
if (r.errors.length > 0) {
log.warn(
`[cron] Memory lanes (${mind.label}) incomplete; watermark held for retry: ` +
r.errors.join('; ').slice(0, 200)
);
continue;
}
log.info(
`[cron] Memory lanes (${mind.label}): ${r.framesProcessed} frames → ` +
`facts=${r.written?.factsWritten ?? 0} events=${r.written?.eventsWritten ?? 0} ` +
`profiles=${r.written?.profilesWritten ?? 0}` +
(r.errors.length ? ` (errors: ${r.errors.join('; ').slice(0, 200)})` : '')
);
laneFramesProcessed += r.framesProcessed;
laneFacts += r.written?.factsWritten ?? 0;
laneEvents += r.written?.eventsWritten ?? 0;
laneProfiles += r.written?.profilesWritten ?? 0;
}
} catch (innerErr) {
log.warn(`[cron] Memory lanes (${mind.label}) failed: ${(innerErr as Error).message}`);
}
}
dreamJournal.record('memory_lane_extract', {
framesProcessed: laneFramesProcessed,
factsWritten: laneFacts,
eventsWritten: laneEvents,
profilesWritten: laneProfiles,
});
} catch (err) {
log.warn(`[cron] Memory lane extraction failed: ${(err as Error).message}`);
}
} else {
// Normal memory consolidation
try { runPersonalConsolidation(); } catch { /* non-blocking */ }
}
// index_reconcile, harvest_sync, memory_compact, memory_lane_extract and
// plain consolidation maintained the legacy memory engine. mem0 indexes
// on write and background extraction replaces the lanes (ADR-0007), so
// schedules left over from the legacy data only run the retention below.
// UX-Refactor Phase 3: cron_execution_history retention. recordExecution
// now writes a row per tick (Journey 16), so prune >30-day rows on the
// same nightly consolidation cadence (mirrors optStore.pruneOlderThan).
@@ -1870,25 +1414,8 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
break;
}
case 'workspace_health':
// Log stale frame count per workspace as awareness flag
try {
const workspaces = wsManager.list();
for (const ws of workspaces) {
const wsDb = getWorkspaceMindDb(ws.id);
if (wsDb) {
const wsFrames = new FrameStore(wsDb);
const staleCount = wsFrames.list({ limit: 100 })
.filter(f => {
const age = Date.now() - new Date(f.last_accessed).getTime();
return age > 7 * 24 * 60 * 60 * 1000;
}).length;
if (staleCount > 0) {
const wsAwareness = new AwarenessLayer(waggleDb, workspaceDataScope(ws.id));
wsAwareness.add('flag', `Workspace "${ws.name}" has ${staleCount} stale memory frames (>7 days untouched)`, 0);
}
}
}
} catch { /* non-blocking */ }
// Flagged memories untouched for a week; mem0 does not track access,
// so there is nothing to flag (ADR-0007).
break;
case 'proactive': {
const proactiveConfig = JSON.parse(schedule.job_config || '{}');
@@ -2007,7 +1534,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
for (const target of targetWorkspaces) {
try {
// Activate workspace mind so agent has context
activateWorkspaceMindWithWeaver(target.id);
activateWorkspaceMind(target.id);
if (taskConfig.mode === 'ai_task') {
// #17: full agent turn through the loopback chat route —
@@ -2115,12 +1642,18 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
// Auto-fetch (§3.C): pull fresh data from opted-in connectors into the
// personal mind. Cost-free — raw frames, no LLM extraction. Free (Solo).
try {
new SessionStore(multiMind.personal).ensure('harvest', 'harvest', 'Imported memory from external sources');
const personalFrames = new FrameStore(multiMind.personal);
const statePath = path.join(fullConfig.dataDir, 'connector-harvest-state.json');
const r = await runConnectorFetch({
connectors: connectorRegistry.getConnected(),
writeFrame: (content) => { personalFrames.createIFrame('harvest', content, 'normal', 'import'); },
writeFrame: async (content) => {
await memory.remember({
scope: PERSONAL_SCOPE,
text: content,
kind: 'note',
source: 'import',
origin: 'connector-fetch',
});
},
loadState: () => {
try {
const raw = JSON.parse(fs.readFileSync(statePath, 'utf-8')) as Partial<{ lastFetchedAt: string; hashes: Record<string, string> }>;
@@ -2154,12 +1687,12 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
// here so the scheduler records the failure and auto-disables after
// repeated failures (recall/write failures are caught inside runLoopTick).
const wsId = schedule.workspace_id;
const mindDb = wsId && wsId !== '*' ? getWorkspaceMindDb(wsId) : multiMind.personal;
if (!mindDb) {
const loopWorkspace = wsId && wsId !== '*' ? wsId : null;
if (loopWorkspace && !wsManager.get(loopWorkspace)) {
log.warn(`[cron] loop "${schedule.name}" references unknown workspace "${wsId}" — skipping`);
break;
}
if (wsId && wsId !== '*') activateWorkspaceMindWithWeaver(wsId);
if (wsId && wsId !== '*') activateWorkspaceMind(wsId);
const loopModel = server.agentState.currentModel ?? 'claude-sonnet-4-6';
const loopProxyUrl = `http://127.0.0.1:${fullConfig.port ?? 3333}/v1/chat/completions`;
const loopChat = async (prompt: string, maxTokens = 2048): Promise<string> => {
@@ -2178,7 +1711,14 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
return parseOpenAiTextCompletion(body).content;
};
const loopAwareness = new AwarenessLayer(waggleDb, wsId && wsId !== '*' ? workspaceDataScope(wsId) : 'personal');
const loopResult = await runLoopTick({ schedule, mindDb, awareness: loopAwareness, embedder, chat: loopChat, log });
const loopResult = await runLoopTick({
schedule,
memory,
scope: loopWorkspace ? workspaceScope(loopWorkspace) : PERSONAL_SCOPE,
awareness: loopAwareness,
chat: loopChat,
log,
});
if (!loopResult.skipped) {
emitNotification(server, {
title: `Loop: ${schedule.name}`,
@@ -2500,7 +2040,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
await server.register(mcpRoutes);
await server.register(extendRoutes);
await server.register(fleetRoutes);
await server.register(importRoutes);
await server.register(vaultRoutes);
await server.register(personaRoutes);
await server.register(feedbackRoutes);
@@ -2510,7 +2049,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
await server.register(costRoutes);
await server.register(backupRoutes);
await server.register(offlineRoutes);
await server.register(weaverRoutes);
await server.register(eventRoutes);
await server.register(workflowRoutes);
await server.register(pinRoutes);
@@ -2569,8 +2107,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
await server.register(telemetryRoutes);
await server.register(agentGroupRoutes);
await server.register(localJobRoutes);
await server.register(harvestRoutes);
await server.register(wikiRoutes);
await server.register(identityRoutes);
await server.register(agentRunRoutes);
await server.register(agentRunsRoutes);
@@ -2887,7 +2423,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
}
const dbHealthy = (() => {
try {
multiMind.personal.getDatabase().prepare('SELECT 1').get();
waggleDb.getDatabase().prepare('SELECT 1').get();
return true;
} catch {
return false;
@@ -2915,35 +2451,23 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
? 'unavailable'
: 'degraded';
// Memory stats — frame count + mind file size
const memoryStats = (() => {
// Memory stats — memory count and the size of the memory directory.
// mem0 embeds every memory on write, so coverage is complete by design.
const memoryStats = await (async () => {
const embeddingProviderStatus = server.embeddingProvider?.getStatus?.() ?? null;
try {
const db = multiMind.personal.getDatabase();
const row = db.prepare('SELECT COUNT(*) as cnt FROM memory_frames').get() as { cnt: number } | undefined;
const frameCount = row?.cnt ?? 0;
// Get mind file size from the known personal mind path
const scopes = [PERSONAL_SCOPE, ...wsManager.list().map(ws => workspaceScope(ws.id))];
const frameCount = await memory.count({ scopes });
let mindSizeBytes = 0;
try {
const stat = fs.statSync(personalPath);
mindSizeBytes = stat.size;
} catch { /* file may not exist yet */ }
// Embedding coverage — frames with vectors vs total frames
let embeddingCoverage = 0;
try {
const totalRow = db.prepare('SELECT COUNT(*) as cnt FROM memory_frames').get() as { cnt: number };
const vecRow = db.prepare('SELECT COUNT(*) as cnt FROM memory_frames_vec').get() as { cnt: number } | undefined;
const vecCount = vecRow?.cnt ?? 0;
if (totalRow.cnt > 0) {
embeddingCoverage = Math.round((vecCount / totalRow.cnt) * 100);
const memoryDir = path.join(fullConfig.dataDir, 'memory');
for (const file of fs.readdirSync(memoryDir)) {
mindSizeBytes += fs.statSync(path.join(memoryDir, file)).size;
}
} catch { /* vec table may not exist */ }
const embeddingProviderStatus = server.embeddingProvider?.getStatus?.() ?? null;
return { frameCount, mindSizeBytes, embeddingCoverage, embeddingProvider: embeddingProviderStatus };
} catch { /* nothing stored yet */ }
return { frameCount, mindSizeBytes, embeddingCoverage: 100, embeddingProvider: embeddingProviderStatus };
} catch {
return { frameCount: 0, mindSizeBytes: 0, embeddingCoverage: 0, embeddingProvider: null };
return { frameCount: 0, mindSizeBytes: 0, embeddingCoverage: 0, embeddingProvider: embeddingProviderStatus };
}
})();
@@ -2991,22 +2515,18 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
// Stop MCP servers
await mcpRuntime.stopAll().catch(() => {});
// Stop weaver timers
for (const t of weaverTimers) clearInterval(t);
for (const [, ww] of workspaceWeavers) {
for (const t of ww.timers) clearInterval(t);
}
workspaceWeavers.clear();
// Stop collecting chat turns for fact extraction and the legacy memory copy.
memoryExtraction.stop();
legacyMemoryImport.cancel();
await legacyMemoryImport.done;
// Close all workspace sessions (new concurrent model)
sessionManager.closeAll();
// Let the active bounded pass finish before closing any borrowed mind.
await vectorEnrichmentService.stop();
// Close all cached workspace minds
mindCache.closeAll();
multiMind.close();
await memory.close();
waggleDb.close();
// Close audit DB, teams DB, and telemetry
@@ -3020,7 +2540,31 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
}
});
vectorEnrichmentService.start();
// One-time copy of memories from the legacy .mind files into the memory
// store, in the background; the legacy files are only read.
const legacyMemoryImport = (() => {
let cancelled = false;
const sources: LegacyMemorySource[] = [{ path: personalPath, scope: PERSONAL_SCOPE }];
for (const ws of wsManager.list()) {
try {
sources.push({ path: wsManager.getMindPath(ws.id), scope: workspaceScope(ws.id) });
} catch {
// A workspace whose directory fails the path checks has nothing to copy.
}
}
const done = new Promise<void>(resolve => setImmediate(resolve))
.then(() => importLegacyMemories(memory, waggleDb, sources, (report) => {
if (report.status === 'imported') {
log.info(`[memory] copied ${report.copied} legacy memories for ${report.scope} (${report.skipped} skipped)`);
} else if (report.status === 'failed') {
log.warn(`[memory] could not copy legacy memories for ${report.scope}: ${report.error}`);
}
}, () => cancelled))
.then(() => undefined, (err: unknown) => {
log.warn(`[memory] legacy memory copy stopped: ${err instanceof Error ? err.message : String(err)}`);
});
return { done, cancel: () => { cancelled = true; } };
})();
// ── Start Teams server if PostgreSQL is configured (TEAMS tier) ──
// Skip in test environment to avoid port conflicts and addHook-after-listen errors

View File

@@ -0,0 +1,173 @@
/**
* One-time copy of memories from the legacy `.mind` files into the memory
* store (P1.5). The legacy files are only read: the data directory may be
* shared with the commercial edition. Each scope is copied once; progress is
* kept in waggle.db, so an interrupted copy resumes where it stopped, and the
* store does not write identical text twice in one scope.
*/
import fs from 'node:fs';
import Database from 'better-sqlite3';
import {
MEMORY_IMPORTANCE,
MEMORY_SOURCES,
scopeKey,
type MemoryImportance,
type MemoryKind,
type MemoryScope,
type MemorySource,
type MemoryStore,
} from '@waggle/memory-contract';
import type { WaggleDB } from '@waggle/core';
export interface LegacyMemorySource {
/** A legacy `.mind` file. */
path: string;
scope: MemoryScope;
}
export interface LegacyMemoryImportReport {
scope: string;
status: 'imported' | 'already-imported' | 'missing' | 'failed';
copied: number;
skipped: number;
error?: string;
}
interface LegacyFrameRow {
id: number;
content: string;
importance: string;
source: string | null;
created_at: string | null;
}
/** Content prefixes the legacy engine used as types, mapped to contract kinds. */
const PREFIX_KINDS: ReadonlyArray<[RegExp, MemoryKind, boolean]> = [
// [pattern, kind, strip the first line (a header)]
[/^\[mind-profile [^\]]*\]/, 'profile', true],
[/^\[mind-fact\]/, 'fact', true],
[/^\[mind-event\]/, 'event', true],
[/^(User preference:|Style note:)/, 'preference', false],
[/^Decision:/, 'decision', false],
[/^(\[Session summary|Research findings:)/, 'summary', false],
[/^(\[Loop:|\[Sub-agent:|User asked:|Work completed:|Recommendation:)/, 'note', false],
];
/** Raw dialogue turns were an engine-specific recall lane; they are not memories. */
const SKIPPED_PREFIX = /^\[mind-rawturn /;
const metaKey = (scope: MemoryScope): string => `memory-import:${scopeKey(scope)}`;
const BATCH = 200;
export async function importLegacyMemories(
memory: MemoryStore,
waggleDb: WaggleDB,
sources: readonly LegacyMemorySource[],
onProgress?: (report: LegacyMemoryImportReport) => void,
isCancelled: () => boolean = () => false,
): Promise<LegacyMemoryImportReport[]> {
const reports: LegacyMemoryImportReport[] = [];
for (const source of sources) {
if (isCancelled()) break;
const report = await importOne(memory, waggleDb, source, isCancelled);
reports.push(report);
onProgress?.(report);
}
return reports;
}
async function importOne(
memory: MemoryStore,
waggleDb: WaggleDB,
source: LegacyMemorySource,
isCancelled: () => boolean,
): Promise<LegacyMemoryImportReport> {
const scope = scopeKey(source.scope);
const report: LegacyMemoryImportReport = { scope, status: 'imported', copied: 0, skipped: 0 };
const state = waggleDb.getMeta(metaKey(source.scope));
if (state === 'done') return { ...report, status: 'already-imported' };
if (!fs.existsSync(source.path) || fs.statSync(source.path).size === 0) {
waggleDb.setMeta(metaKey(source.scope), 'done');
return { ...report, status: 'missing' };
}
let db: Database.Database | null = null;
try {
db = new Database(source.path, { readonly: true, fileMustExist: true });
const hasFrames = db.prepare(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_frames'",
).get();
if (!hasFrames) {
waggleDb.setMeta(metaKey(source.scope), 'done');
return { ...report, status: 'missing' };
}
let lastId = state ? Number(state) || 0 : 0;
const page = db.prepare(
`SELECT id, content, importance, source, created_at FROM memory_frames
WHERE id > ? ORDER BY id LIMIT ?`,
);
for (;;) {
const rows = page.all(lastId, BATCH) as LegacyFrameRow[];
if (rows.length === 0) break;
for (const row of rows) {
if (isCancelled()) {
waggleDb.setMeta(metaKey(source.scope), String(lastId));
return report;
}
const mapped = mapFrame(row);
if (mapped) {
await memory.remember({
scope: source.scope,
text: mapped.text,
kind: mapped.kind,
importance: mapped.importance,
source: mapped.source,
origin: 'legacy-import',
...(row.created_at && { metadata: { legacy_created_at: row.created_at } }),
});
report.copied++;
} else {
report.skipped++;
}
lastId = row.id;
}
waggleDb.setMeta(metaKey(source.scope), String(lastId));
}
waggleDb.setMeta(metaKey(source.scope), 'done');
return report;
} catch (err) {
return { ...report, status: 'failed', error: err instanceof Error ? err.message : String(err) };
} finally {
db?.close();
}
}
/** Converts a legacy frame, or returns null for one that is not carried over. */
export function mapFrame(row: Pick<LegacyFrameRow, 'content' | 'importance' | 'source'>): {
text: string;
kind: MemoryKind;
importance: MemoryImportance;
source: MemorySource;
} | null {
const content = row.content?.trim() ?? '';
if (!content || row.importance === 'deprecated' || SKIPPED_PREFIX.test(content)) return null;
let kind: MemoryKind = 'fact';
let text = content;
for (const [pattern, mappedKind, stripHeader] of PREFIX_KINDS) {
if (!pattern.test(content)) continue;
kind = mappedKind;
if (stripHeader) {
const newline = content.indexOf('\n');
text = newline >= 0 ? content.slice(newline + 1).trim() : content.replace(pattern, '').trim();
}
break;
}
if (!text) return null;
const importance = (MEMORY_IMPORTANCE as readonly string[]).includes(row.importance)
? row.importance as MemoryImportance
: 'normal';
const source = row.source && (MEMORY_SOURCES as readonly string[]).includes(row.source)
? row.source as MemorySource
: 'import';
return { text, kind, importance, source };
}

View File

@@ -4,32 +4,26 @@
* A "Loop" is a stateful, memory-powered scheduled automation for knowledge
* work. Each tick composes pieces Waggle already ships:
*
* recall (HybridSearch) → what does this workspace's memory say about the goal?
* recall (memory search) → what does this workspace's memory say about the goal?
* prior state (Awareness)→ what did the PREVIOUS tick report? (cross-tick spine)
* maker (toolless chat) → produce a report grounded in the above
* checker (LLMJudge) → verify the report against a rubric (the gate)
* write-back (FrameStore + Awareness) → persist into the local mind
* write-back (memory + Awareness) → persist into local memory
*
* L1 / report-only guarantee: the maker is a plain text completion with NO
* tools wired, so a tick cannot send an email, write a file, or touch any
* external system — the only side effect is writing to the workspace's own
* `.mind` (local, sovereign). This is what makes Loop v0 safe by construction;
* memory (local, sovereign). This is what makes Loop v0 safe by construction;
* the headless ConfirmationGate deny-default (confirmation.ts) is the second
* line of defence for the day tools are added.
*
* Everything here is reused infrastructure — no new abstractions. The executor
* is extracted from index.ts only so it can be unit-tested with an in-memory
* MindDB + a stubbed chat function.
* memory store + a stubbed chat function.
*/
import {
AwarenessLayer,
FrameStore,
SessionStore,
HybridSearch,
type MindDB,
type Embedder,
} from '@waggle/core';
import type { AwarenessLayer } from '@waggle/core';
import type { MemoryScope, MemoryStore } from '@waggle/memory-contract';
import { LLMJudge, scanForInjection } from '@waggle/agent';
/** Minimal slice of a CronSchedule the loop executor needs (decoupled for tests). */
@@ -50,12 +44,11 @@ export interface LoopLogger {
export interface LoopTickDeps {
schedule: LoopSchedule;
/** The already-resolved workspace (or personal) mind for this loop. */
mindDb: MindDB;
memory: MemoryStore;
/** The workspace (or personal) memory this loop reads and writes. */
scope: MemoryScope;
/** Awareness items of the same scope, in waggle.db; the loop keeps its state there. */
awareness: AwarenessLayer;
/** Embedder for recall-by-meaning. */
embedder: Embedder;
/** Toolless completion against the local proxy/LiteLLM. */
chat: LoopChat;
log: LoopLogger;
@@ -196,14 +189,14 @@ export function buildMakerPrompt(opts: {
}
/**
* Run one Loop tick. Pure-ish: all I/O goes through `deps` (mindDb, embedder,
* Run one Loop tick. Pure-ish: all I/O goes through `deps` (memory, awareness,
* chat). Throws are intentionally NOT swallowed for the maker/judge LLM path so
* the scheduler records the failure in cron_execution_history and auto-disables
* after repeated failures (feeds the engine-liveness/health story); recall and
* memory-write failures ARE caught (best-effort, must not fail the whole tick).
*/
export async function runLoopTick(deps: LoopTickDeps): Promise<LoopTickResult> {
const { schedule, mindDb, awareness, embedder, chat, log } = deps;
const { schedule, memory, scope, awareness, chat, log } = deps;
const spec = parseLoopSpec(schedule.job_config);
if (!spec) {
@@ -233,8 +226,8 @@ export async function runLoopTick(deps: LoopTickDeps): Promise<LoopTickResult> {
// Recall prior context by meaning (best-effort — a recall failure must not kill the tick).
let recalled = '';
try {
const hits = await new HybridSearch(mindDb, embedder).search(spec.query, { limit: 8 });
recalled = hits.map(h => h.frame.content).join('\n---\n');
const hits = await memory.search(spec.query, { scopes: [scope], limit: 8 });
recalled = hits.map(h => h.text).join('\n---\n');
} catch (err) {
log.warn(`[loop] "${schedule.name}" recall failed: ${err instanceof Error ? err.message : String(err)}`);
}
@@ -291,17 +284,20 @@ export async function runLoopTick(deps: LoopTickDeps): Promise<LoopTickResult> {
log.warn(`[loop] "${schedule.name}" checker failed: ${err instanceof Error ? err.message : String(err)}`);
}
// Write the report into the local mind (the durable spine). Best-effort.
// Write the report into local memory (the durable spine). Best-effort.
let wrote = false;
if (spec.writeToMemory) {
try {
// FK: memory_frames.gop_id references sessions — ensure the 'loop' session
// exists before createIFrame (mirrors connector_fetch's 'harvest' ensure).
new SessionStore(mindDb).ensure('loop', 'loop', 'Loop automation outputs');
const header = `[Loop: ${schedule.name}] ${new Date().toISOString()}${score !== undefined ? ` · score ${score.toFixed(2)}` : ''}`;
// ISO timestamp in the body keeps each tick's frame distinct (defeats the
// content-hash dedup that would otherwise collapse identical reports).
new FrameStore(mindDb).createIFrame('loop', `${header}\n\n${report}`, 'normal', 'agent_inferred');
// ISO timestamp in the body keeps each tick's memory distinct (the store
// does not write identical text twice in one scope).
await memory.remember({
scope,
text: `${header}\n\n${report}`,
kind: 'note',
source: 'agent_inferred',
origin: 'loop',
});
wrote = true;
} catch (err) {
log.warn(`[loop] "${schedule.name}" memory write failed: ${err instanceof Error ? err.message : String(err)}`);

View File

@@ -0,0 +1,111 @@
/**
* Background fact extraction (ADR-0007, decision 6). Chat turns are queued per
* session and handed to the memory store in batches: after a few turns, or
* when the conversation pauses. The store extracts facts about the user with
* the model the user chose and keeps them in personal memory as kind
* 'profile'. A setting turns it off.
*/
import {
PERSONAL_SCOPE,
type ConversationMessage,
type MemoryStore,
} from '@waggle/memory-contract';
/** Messages (user + assistant) that trigger an extraction. */
const DEFAULT_BATCH_MESSAGES = 6;
/** A pause after which pending messages are extracted. */
const DEFAULT_IDLE_MS = 2 * 60 * 1000;
/** Long replies are cut; the facts about the user are in the first part. */
const MAX_MESSAGE_CHARS = 4000;
export interface MemoryExtractionOptions {
memory: MemoryStore;
/** Read before every extraction, so the setting applies at once. */
isEnabled: () => boolean;
batchMessages?: number;
idleMs?: number;
onError?: (err: unknown) => void;
}
interface PendingSession {
messages: ConversationMessage[];
timer: NodeJS.Timeout | null;
/** Extractions of one session run one after another. */
chain: Promise<void>;
}
export class MemoryExtractionQueue {
private readonly sessions = new Map<string, PendingSession>();
private readonly batchMessages: number;
private readonly idleMs: number;
private stopped = false;
constructor(private readonly options: MemoryExtractionOptions) {
this.batchMessages = options.batchMessages ?? DEFAULT_BATCH_MESSAGES;
this.idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
}
/** Whether turns are being collected at all. */
get active(): boolean {
return !this.stopped && this.options.memory.capabilities.extraction && this.options.isEnabled();
}
/** Queue one finished turn of a chat session. */
record(sessionId: string, userMessage: string, assistantMessage: string): void {
if (!this.active) return;
const session = this.sessions.get(sessionId) ?? { messages: [], timer: null, chain: Promise.resolve() };
this.sessions.set(sessionId, session);
for (const [role, content] of [['user', userMessage], ['assistant', assistantMessage]] as const) {
const text = content.trim();
if (text) session.messages.push({ role, content: text.slice(0, MAX_MESSAGE_CHARS) });
}
if (session.timer) clearTimeout(session.timer);
session.timer = null;
if (session.messages.length >= this.batchMessages) {
void this.flush(sessionId);
} else {
session.timer = setTimeout(() => void this.flush(sessionId), this.idleMs);
session.timer.unref?.();
}
}
/** Extract what is pending for one session, or for every session. */
async flush(sessionId?: string): Promise<void> {
const ids = sessionId ? [sessionId] : [...this.sessions.keys()];
await Promise.all(ids.map((id) => this.flushSession(id)));
}
/** Stops collecting; pending messages are dropped. */
stop(): void {
this.stopped = true;
for (const session of this.sessions.values()) {
if (session.timer) clearTimeout(session.timer);
}
this.sessions.clear();
}
private flushSession(sessionId: string): Promise<void> {
const session = this.sessions.get(sessionId);
if (!session) return Promise.resolve();
if (session.timer) clearTimeout(session.timer);
session.timer = null;
const messages = session.messages.splice(0);
if (messages.length === 0) return session.chain;
session.chain = session.chain.then(async () => {
if (!this.active || !messages.some((m) => m.role === 'user')) return;
try {
await this.options.memory.remember({
scope: PERSONAL_SCOPE,
conversation: messages,
kind: 'profile',
source: 'agent_inferred',
origin: 'extraction',
sessionId,
});
} catch (err) {
this.options.onError?.(err);
}
});
return session.chain;
}
}

View File

@@ -1,161 +0,0 @@
/**
* memory-lane-cron.ts — W4.3d: scheduled extraction of the benchmark-proven
* recall lanes (facts / events / profiles) over newly-written frames.
*
* Runs per mind (personal + each workspace) from the `memory_lane_extract`
* cron action. Incremental via a frame-id watermark in the mind's `meta`
* table; the extraction passes themselves are idempotent (content dedup for
* facts/events, replace-on-update for profiles), so an overlapping or
* re-run window never duplicates.
*
* W4-PRODUCTION-PORT-PLAN-2026-06-11.md components #5/#6/#8, extraction side.
*/
import {
type MindDB,
FrameStore,
SessionStore,
KnowledgeGraph,
extractMemoryLanes,
writeMemoryLaneFrames,
extractKgEntities,
writeKgEntities,
type LLMCallFn,
type WriteLaneFramesResult,
} from '@waggle/core';
const WATERMARK_KEY = 'lane_extract_last_frame_id';
/** Minimum new frames before an LLM pass is worth the cost. */
const MIN_NEW_FRAMES = 5;
/** Max frames per run (oldest-first; the rest picked up next run). */
const MAX_FRAMES_PER_RUN = 300;
/** Per-frame content cap + total input cap keep the prompt bounded. */
const PER_FRAME_CHARS = 800;
const TOTAL_INPUT_CHARS = 24_000;
/** Stable session for lane frames (frames have a FK to sessions). */
const LANE_SESSION_ID = 'memory-lanes';
export interface LaneExtractionRunResult {
skipped: boolean;
framesProcessed: number;
watermark: number;
written?: WriteLaneFramesResult;
/** KG entities written this run (created + seen_count bumps). D2 KG pass. */
kgEntitiesWritten: number;
errors: string[];
}
function getWatermark(db: MindDB): number {
const row = db.getDatabase()
.prepare('SELECT value FROM meta WHERE key = ?')
.get(WATERMARK_KEY) as { value: string } | undefined;
const n = row ? parseInt(row.value, 10) : 0;
return Number.isFinite(n) ? n : 0;
}
function setWatermark(db: MindDB, id: number): void {
db.getDatabase()
.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)')
.run(WATERMARK_KEY, String(id));
}
/**
* Run the three lane-extraction passes over frames written since the last
* run. Returns a summary; never throws (callers log, cron must not die).
*/
export async function runMemoryLaneExtraction(
db: MindDB,
llmCall: LLMCallFn,
): Promise<LaneExtractionRunResult> {
const watermark = getWatermark(db);
const raw = db.getDatabase();
// New source material: everything after the watermark EXCEPT our own lane
// frames (no self-feeding), automation loop-tick frames (#13 — scheduler
// noise must not be LLM-amplified into lanes), and temporary/deprecated
// frames.
const rows = raw.prepare(
`SELECT id, content, created_at FROM memory_frames
WHERE id > ?
AND content NOT LIKE '[mind-%'
AND content NOT LIKE '[Loop:%'
AND importance NOT IN ('temporary', 'deprecated')
ORDER BY id ASC
LIMIT ?`
).all(watermark, MAX_FRAMES_PER_RUN) as Array<{ id: number; content: string; created_at: string }>;
if (rows.length < MIN_NEW_FRAMES) {
return { skipped: true, framesProcessed: 0, watermark, kgEntitiesWritten: 0, errors: [] };
}
// Dated passages — the events pass resolves relative cues against these.
const parts: string[] = [];
let total = 0;
let lastId = watermark;
let processed = 0;
for (const r of rows) {
const piece = `[${String(r.created_at ?? '').slice(0, 10)}] ${r.content.slice(0, PER_FRAME_CHARS)}`;
if (total + piece.length > TOTAL_INPUT_CHARS) break;
parts.push(piece);
total += piece.length;
lastId = r.id;
processed++;
}
const extraction = await extractMemoryLanes(parts.join('\n\n'), llmCall);
const errors = [...extraction.errors];
// D2 — KG entity pass over the SAME frame window (only the frames the lane
// pass actually consumed, so this rides the single shared watermark).
// extractKgEntities never throws (per-batch errors collected); the write is
// belt-and-braces wrapped so a graph failure can't kill the cron.
let kgExtraction: Awaited<ReturnType<typeof extractKgEntities>> | undefined;
try {
kgExtraction = await extractKgEntities(
rows.slice(0, processed).map((r) => ({ id: r.id, content: r.content })),
llmCall,
);
errors.push(...kgExtraction.errors);
} catch (e: unknown) {
errors.push(`kg-entities: ${e instanceof Error ? e.message : String(e)}`);
}
// Advance the watermark ONLY past what we actually fed to the LLM — frames
// beyond the input cap are picked up by the next run.
// A failed pass makes this source window retryable. Partial lane writes
// combined with an advanced watermark would lose the failed lane; partial
// KG writes with a held watermark would inflate seen_count on the retry.
if (errors.length > 0 || !kgExtraction) {
return {
skipped: false,
framesProcessed: processed,
watermark,
kgEntitiesWritten: 0,
errors,
};
}
let written: WriteLaneFramesResult | undefined;
let kgEntitiesWritten = 0;
try {
raw.transaction(() => {
new SessionStore(db).ensure(LANE_SESSION_ID, 'system', 'Extracted memory lanes (facts/events/profiles)');
written = writeMemoryLaneFrames(new FrameStore(db), LANE_SESSION_ID, extraction);
const kgWritten = writeKgEntities(new KnowledgeGraph(db), kgExtraction);
kgEntitiesWritten = kgWritten.created + kgWritten.updated;
setWatermark(db, lastId);
})();
} catch (e: unknown) {
errors.push(`commit: ${e instanceof Error ? e.message : String(e)}`);
return {
skipped: false,
framesProcessed: processed,
watermark,
kgEntitiesWritten: 0,
errors,
};
}
return { skipped: false, framesProcessed: processed, watermark: lastId, written, kgEntitiesWritten, errors };
}

View File

@@ -0,0 +1,45 @@
/**
* Memory for the local server (ADR-0007): one mem0 store per data directory,
* in `<dataDir>/memory/`, reached only through the memory contract.
*/
import path from 'node:path';
import { createMemoryEmbedder, type Embedder } from '@waggle/core';
import type { MemoryStore } from '@waggle/memory-contract';
import { createMem0MemoryStore, createWordEmbedder, type ExtractionModel } from '@waggle/memory-mem0';
export const MEMORY_DIR = 'memory';
export interface OpenMemoryOptions {
dataDir: string;
/** Where the in-process embedding model is cached. */
modelCacheDir: string;
/** Overrides the in-process embedding model. */
embeddingModel?: string;
/** OpenAI-compatible endpoint used to extract facts from conversations. */
extraction?: ExtractionModel;
}
export async function openMemoryStore(options: OpenMemoryOptions): Promise<MemoryStore> {
return createMem0MemoryStore({
directory: path.join(options.dataDir, MEMORY_DIR),
embedder: memoryEmbedder(options),
extractionModel: options.extraction,
});
}
/**
* `WAGGLE_MEMORY_EMBEDDER=words` selects the word embedder, which needs no
* model download; tests use it. Otherwise memory uses the in-process model,
* loaded on first use so startup never waits for a download.
*/
function memoryEmbedder(options: OpenMemoryOptions): Embedder {
if (process.env.WAGGLE_MEMORY_EMBEDDER === 'words') {
const words = createWordEmbedder();
return {
dimensions: words.dimensions,
embed: async (text) => Float32Array.from(await words.embed(text)),
embedBatch: async (texts) => (await words.embedBatch(texts)).map((v) => Float32Array.from(v)),
};
}
return createMemoryEmbedder({ cacheDir: options.modelCacheDir, model: options.embeddingModel });
}

View File

@@ -10,7 +10,8 @@ import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
import { evaluateExternalMemoryIngress, FrameStore, SessionStore } from '@waggle/core';
import { evaluateExternalMemoryIngress } from '@waggle/core';
import { recordRunResult } from '../run-memory.js';
import type { CollaborationRunMemoryRefs, CollaborationWorkerRun, WaggleMessage } from '@waggle/shared';
import {
SubagentOrchestrator,
@@ -371,7 +372,6 @@ async function executeGroup(
const unregisterControls: Array<() => void> = [];
let settleExecution!: () => void;
const executionSettled = new Promise<void>((resolve) => { settleExecution = resolve; });
let acquired = false;
let traceId: number | undefined;
let spendMeter: ModelSpendMeter | undefined;
@@ -415,11 +415,8 @@ async function executeGroup(
: underlyingRunLoop;
let availableTools = server.agentState.allTools;
let sessionOrchestrator: ReturnType<FastifyInstance['agentState']['createSessionOrchestrator']> | undefined;
let workspaceMind: Parameters<FastifyInstance['agentState']['createSessionOrchestrator']>[0] | undefined;
if (runContext) {
workspaceMind = server.mindCache.acquire(runContext.workspaceId);
acquired = true;
sessionOrchestrator = server.agentState.createSessionOrchestrator(workspaceMind);
sessionOrchestrator = server.agentState.createSessionOrchestrator(runContext.workspaceId);
availableTools = server.agentState.buildToolsForSession(
sessionOrchestrator,
runContext.cwd,
@@ -569,14 +566,14 @@ async function executeGroup(
const aggregated = guardAgentOutput(rawAggregated, 'result');
const workers = snapshotWorkers(orchestrator);
const failed = Array.from(results.values()).some((worker) => worker.status === 'failed');
if (runContext && workspaceMind) {
if (runContext) {
for (const run of runContext.runs.values()) {
const current = server.agentRunRegistry.get(run.id);
if (current?.kind !== 'worker' || !['completed', 'failed', 'cancelled', 'interrupted'].includes(current.status)) continue;
const memoryRefs = recordGroupWorkerResult(server, workspaceMind, runContext, group, current);
const memoryRefs = await recordGroupWorkerResult(server, runContext, group, current);
server.agentRunRegistry.update(current.id, { memoryRefs });
}
const roomMemoryRefs = recordGroupAggregate(server, workspaceMind, runContext, group, task, aggregated);
const roomMemoryRefs = await recordGroupAggregate(server, runContext, group, task, aggregated);
server.agentRunRegistry.update(runContext.roomId, {
result: { summary: aggregated },
memoryRefs: roomMemoryRefs,
@@ -627,36 +624,30 @@ async function executeGroup(
} finally {
for (const unregister of unregisterControls) unregister();
try {
if (acquired && runContext) server.mindCache.release(runContext.workspaceId);
} finally {
try {
if (runContext && signal.aborted) {
const room = server.agentRunRegistry.get(runContext.roomId);
if (room?.status === 'cancelling') {
server.agentRunRegistry.finalizeRoomCancellation(runContext.roomId);
}
if (runContext && signal.aborted) {
const room = server.agentRunRegistry.get(runContext.roomId);
if (room?.status === 'cancelling') {
server.agentRunRegistry.finalizeRoomCancellation(runContext.roomId);
}
} finally {
settleExecution();
}
} finally {
settleExecution();
}
}
}
function recordGroupWorkerResult(
server: FastifyInstance,
workspaceMind: Parameters<FastifyInstance['agentState']['createSessionOrchestrator']>[0],
context: GroupRunContext,
group: AgentGroup,
run: CollaborationWorkerRun,
): CollaborationRunMemoryRefs {
): Promise<CollaborationRunMemoryRefs> {
const output = run.result?.summary ?? run.result?.error ?? `Worker finished with status ${run.status}.`;
return persistGroupMemory(
server,
workspaceMind,
context,
{
kind: 'worker', roomId: context.roomId, runId: run.id,
entry: 'worker', roomId: context.roomId, runId: run.id,
groupId: group.id, workspaceId: context.workspaceId,
personaId: run.executor.personaId ?? null, status: run.status,
},
@@ -667,17 +658,15 @@ function recordGroupWorkerResult(
function recordGroupAggregate(
server: FastifyInstance,
workspaceMind: Parameters<FastifyInstance['agentState']['createSessionOrchestrator']>[0],
context: GroupRunContext,
group: AgentGroup,
task: string,
aggregated: string,
): CollaborationRunMemoryRefs {
): Promise<CollaborationRunMemoryRefs> {
return persistGroupMemory(
server,
workspaceMind,
context,
{ kind: 'aggregate', roomId: context.roomId, groupId: group.id, workspaceId: context.workspaceId },
{ entry: 'aggregate', roomId: context.roomId, groupId: group.id, workspaceId: context.workspaceId },
`[Agent group]\nRoom: ${context.roomId}\nGroup: ${group.name}\nWorkspace: ${context.workspaceId}\nSummary: ${aggregated.slice(0, 1_000)}`,
`[Agent group result]\nRoom: ${context.roomId}\nGroup: ${group.name}\nTask:\n${task}\n\nResult:\n${aggregated.slice(0, 100_000)}`,
);
@@ -685,45 +674,17 @@ function recordGroupAggregate(
function persistGroupMemory(
server: FastifyInstance,
workspaceMind: Parameters<FastifyInstance['agentState']['createSessionOrchestrator']>[0],
context: GroupRunContext,
metadata: Record<string, unknown>,
personalContent: string,
workspaceContent: string,
): CollaborationRunMemoryRefs {
const personalFrameIds: number[] = [];
const workspaceFrameIds: Record<string, number[]> = {};
const meta = JSON.stringify(metadata);
try {
const personal = server.multiMind.personal;
new SessionStore(personal).ensure('agent-runs', 'agent-runs', 'Agent collaboration index');
const store = new FrameStore(personal);
const frame = store.createIFrame(
'agent-runs',
personalContent,
'normal', 'agent_inferred',
);
store.setMetadata(frame.id, meta);
personalFrameIds.push(frame.id);
} catch { /* workspace result remains authoritative */ }
try {
new SessionStore(workspaceMind).ensure('agent-runs', 'agent-runs', 'Agent collaboration results');
const store = new FrameStore(workspaceMind);
const frame = store.createIFrame(
'agent-runs',
workspaceContent,
'normal', 'agent_inferred',
);
store.setMetadata(frame.id, meta);
workspaceFrameIds[context.workspaceId] = [frame.id];
} catch { /* reflected below */ }
const personalOk = personalFrameIds.length > 0;
const workspaceOk = (workspaceFrameIds[context.workspaceId]?.length ?? 0) > 0;
return {
status: personalOk && workspaceOk ? 'complete' : (personalOk || workspaceOk ? 'partial' : 'failed'),
personalFrameIds,
workspaceFrameIds,
};
): Promise<CollaborationRunMemoryRefs> {
return recordRunResult(server.memory, {
workspaceId: context.workspaceId,
personalText: personalContent,
workspaceText: workspaceContent,
metadata,
});
}
function publishGroupDance(

View File

@@ -6,7 +6,7 @@ import { performance } from 'node:perf_hooks';
import type { FastifyPluginAsync } from 'fastify';
import { createLogger } from '../logger.js';
const log = createLogger('chat');
import { runAgentLoop, needsConfirmation, needsConfirmationWithAutonomy, isCriticalNeverAutopass, classifyGatedToolRisk, CapabilityRouter, lintMemoryWrite, assessTrust, formatTrustSummary, scanForInjection, AGENT_LOOP_REROUTE_PREFIX, extractEntities, IterationBudget, routeMessage, compressConversation, createDefaultCompressionConfig, needsCompression, computeInputTokenBudget, getModelContextWindow, CredentialPool, loadCredentialPool, extractStatusCode, filterAvailableTools, shouldSuggestCapture, planSkillDistillation, selectAgentRunBudget, TraceRecorder, generateTurnId, logTurnEvent, checkGrounding, READONLY_TOOLS, type ToolDefinition, type TraceHandle } from '@waggle/agent';
import { runAgentLoop, needsConfirmation, needsConfirmationWithAutonomy, isCriticalNeverAutopass, classifyGatedToolRisk, CapabilityRouter, lintMemoryWrite, assessTrust, formatTrustSummary, scanForInjection, AGENT_LOOP_REROUTE_PREFIX, IterationBudget, routeMessage, compressConversation, createDefaultCompressionConfig, needsCompression, computeInputTokenBudget, getModelContextWindow, CredentialPool, loadCredentialPool, extractStatusCode, filterAvailableTools, shouldSuggestCapture, planSkillDistillation, selectAgentRunBudget, TraceRecorder, generateTurnId, logTurnEvent, checkGrounding, READONLY_TOOLS, type ToolDefinition, type TraceHandle } from '@waggle/agent';
import type { AgentLoopConfig, AgentResponse, Orchestrator, AutonomyLevel, HookRegistry } from '@waggle/agent';
import type { WorkspaceSession } from '../workspace-sessions.js';
import { buildWorkspaceNowBlock, formatWorkspaceNowPrompt } from './workspace-context.js';
@@ -38,6 +38,7 @@ function resolvePersona(id: string) {
return listPersonas().find(p => p.id === id) ?? null;
}
import { TeamSync, WaggleConfig, type CronStore, type SavePendingActionInput } from '@waggle/core';
import { PERSONAL_SCOPE, workspaceScope } from '@waggle/memory-contract';
// ── Extracted modules ──────────────────────────────────────────────────
import { allowsAutomaticRecall, allowsConversationHistory, allowsPersistedMemoryRead, allowsPostResponseDecoration, buildTemplateWelcomePrompt, buildTurnMessageWindow, canUseBudgetModelWithoutCloudEgress, classifyExplicitTurnMutationPolicy, filterToolsByTurnMutationPolicy, isExclusiveSuppliedOnlyResponseRequest, isExplicitToolFreeAdvisoryRequest, isOfflineOllamaModelReference, isRegulatedContent, isRetryableError, isAmbiguousMessage, primeMemoryDirectiveClassifier, resolveExplicitPersistedMemoryReadDirective, resolveTurnPersistencePermissions, selectAdvisoryMaxOutputTokens, shouldSuggestSchedule, SCHEDULE_SUGGESTION, AMBIGUITY_PROMPT, describeToolUse, type TurnContextScope, type TurnMutationPolicy } from './chat-helpers.js';
@@ -726,7 +727,7 @@ const PERSONAL_CHAT_COMMAND_CONTEXT = 'Personal';
const toolContextKey = `${workspaceId}\u0000${workspacePath}`;
let runtime = cache.get(sessionId);
if (!runtime || runtime.toolContextKey !== toolContextKey) {
const runtimeOrchestrator = server.agentState.createSessionOrchestrator(workspaceSession.mind);
const runtimeOrchestrator = server.agentState.createSessionOrchestrator(workspaceSession.workspaceId);
runtime = {
orchestrator: runtimeOrchestrator,
tools: server.agentState.buildToolsForSession(runtimeOrchestrator, workspacePath, workspaceId),
@@ -781,7 +782,7 @@ const PERSONAL_CHAT_COMMAND_CONTEXT = 'Personal';
// compaction passes update that frame in place instead of stacking near-
// duplicates. In-memory like compressionSummaries (a sidecar restart just
// means the next pass creates a fresh frame — rare, benign).
const compactionFrameIds = new Map<string, number>();
const compactionFrameIds = new Map<string, string>();
// Credential pool: lazily initialized per-provider key pools for round-robin + cooldown
const credentialPools = new Map<string, CredentialPool>();
@@ -825,7 +826,7 @@ const PERSONAL_CHAT_COMMAND_CONTEXT = 'Personal';
// Phase A.2: accepts an optional `personaOverride` so different chat windows
// on the same workspace can run different personas without touching the
// workspace record.
function buildSystemPrompt(
async function buildSystemPrompt(
orch: Orchestrator,
workspacePath?: string,
sessionId?: string,
@@ -851,7 +852,7 @@ const PERSONAL_CHAT_COMMAND_CONTEXT = 'Personal';
toolFreeAdvisory = false,
includePersistedMemory = true,
includeConversationDerivedWorkspaceState = true,
): string {
): Promise<string> {
// Resolve the active persona: per-window override > workspace default.
const wsConfig = workspaceId ? server.workspaceManager?.get(workspaceId) : null;
const activePersonaId = personaOverride ?? wsConfig?.personaId ?? null;
@@ -919,7 +920,7 @@ const PERSONAL_CHAT_COMMAND_CONTEXT = 'Personal';
orch.setGoalAncestry(resolveChatAncestry(server, workspaceId));
}
prompt += assembled?.system
?? (includePersistedMemory ? orch.buildSystemPrompt(selectedModel) : '');
?? (includePersistedMemory ? await orch.buildSystemPrompt(selectedModel) : '');
// Inject user profile context (review Major #4: cached by mtime, no sync I/O per turn)
if (includePersistedMemory) {
@@ -1238,7 +1239,7 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
let executionWorkspacePath = workspacePath;
if (authorizedWorkspace && authorizedWorkspace !== workspace) {
const authorizedConfig = server.workspaceManager?.get(authorizedWorkspace);
if (!authorizedConfig || !server.agentState.getWorkspaceMindDb(authorizedWorkspace)) {
if (!authorizedConfig) {
return reply.status(409).send({
error: 'Active workspace is unavailable',
code: 'WORKSPACE_NOT_READY',
@@ -1444,13 +1445,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
let activeSessionOrch: Orchestrator | undefined;
let activeChatRuntime: { workspaceSession: WorkspaceSession; sessionId: string; runtime: ChatRuntime } | undefined;
let workspaceTurnScope: WorkspaceTurnScope | undefined;
// Turn-scoped pin for an implicit/default request-owned workspace mind.
// Hoisted so the outer finally can release it.
let pinnedSharedMindId: string | null = null;
// A named workspace session owns a long-lived pin. Each active chat turn
// takes another pin so Fleet kill cannot release/evict its mind before the
// turn observes the workspace abort signal and unwinds.
let pinnedWorkspaceMindId: string | null = null;
const activeSessionId = requestedSessionId ?? historyWorkspaceId;
const activeWorkspaceId = historyWorkspaceId;
const activeExecutionWorkspaceId = executionWorkspaceId;
@@ -1498,20 +1492,18 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
if (!effectiveWorkspace) {
throw new Error('Managed workspace identity is unavailable');
}
if (!server.agentState.getWorkspaceMindDb(effectiveWorkspace)) {
throw new Error('Workspace mind is unavailable');
if (!server.workspaceManager.get(effectiveWorkspace)) {
throw new Error('Workspace is unavailable');
}
const candidateSession = server.sessionManager.getOrCreate(
effectiveWorkspace,
() => server.mindCache.acquire(effectiveWorkspace),
(m) => server.agentState.createSessionOrchestrator(m),
(m, o) => server.agentState.buildToolsForSession(
() => server.agentState.createSessionOrchestrator(effectiveWorkspace),
(o) => server.agentState.buildToolsForSession(
o,
executionWorkspacePath ?? effectiveWorkspace,
effectiveWorkspace,
),
server.workspaceManager?.get(effectiveWorkspace)?.personaId ?? undefined,
() => server.mindCache.release(effectiveWorkspace),
);
if (candidateSession.status !== 'active') {
throw new Error(`Workspace session is ${candidateSession.status}`);
@@ -1524,8 +1516,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
throw turnSignal.reason ?? new Error('Chat or workspace cancelled');
}
server.mindCache.acquire(effectiveWorkspace);
pinnedWorkspaceMindId = effectiveWorkspace;
const runtime = acquireChatRuntime(
candidateSession,
sessionId,
@@ -1544,9 +1534,7 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
} else if (!hasCustomRunner && authorizedWorkspace !== undefined) {
try {
if (authorizedWorkspace) {
const requestMind = server.mindCache.acquire(authorizedWorkspace);
pinnedSharedMindId = authorizedWorkspace;
sessionOrch = server.agentState.createSessionOrchestrator(requestMind);
sessionOrch = server.agentState.createSessionOrchestrator(authorizedWorkspace);
} else {
sessionOrch = server.agentState.createSessionOrchestrator();
}
@@ -2705,7 +2693,7 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
}
}
const packagedSystemPrompt = buildSystemPrompt(
const packagedSystemPrompt = await buildSystemPrompt(
sessionOrch,
executionWorkspacePath,
sessionId,
@@ -3322,40 +3310,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
}
}
// ── KG auto-extraction (Item 4) ────────────────────────────
// Extract named entities from the agent response and add them to the
// knowledge graph of the active workspace mind.
// Non-blocking — KG enrichment never fails the response.
// Skipped whenever learned/derived persistence is disabled; review and
// evidence-bounded output must not inflate the knowledge graph.
if (!hasCustomRunner && allowDerivedPersistence && result.content && result.content.length > 100) {
try {
const knowledge = sessionOrch.getKnowledge();
const entities = extractEntities(result.content);
if (entities.length > 0) {
const now = new Date().toISOString();
// Cap at 10 entities per turn to avoid KG bloat
for (const entity of entities.slice(0, 10)) {
try {
knowledge.createEntity(entity.type, entity.name, { confidence: entity.confidence, source: `session:${sessionId}` }, { valid_from: now });
} catch {
// Duplicate or schema error — skip silently
}
}
}
} catch (e) {
if (isClosedDbError(e)) {
log.warn('[waggle][W4A] workspace mind handle closed mid-turn during KG extraction', {
workspaceId: effectiveWorkspace,
sessionId,
seam: 'knowledge.createEntity',
error: e instanceof Error ? e.message : String(e),
});
} else {
log.info('[waggle] KG extraction error:', e instanceof Error ? e.message : String(e));
}
}
}
// ── Auto skill capture — detect repeatable workflow patterns ──
if (!hasCustomRunner
@@ -3648,22 +3602,22 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
// exchange; when the model call fails that never runs, so the user's
// turn would be lost from memory ("remembers everything" broken). Persist
// the raw turn directly here — NOT via the conservative pattern-write-back
// (which may extract nothing) — so it's recallable (keyword half of
// HybridSearch now; embedded on the next cognify/distill pass). The 8-char
// floor skips trivial acks ("ok", "thanks"). Best-effort: a persistence
// (which may extract nothing) — so it's recallable. The 8-char floor
// skips trivial acks ("ok", "thanks"). Best-effort: a persistence
// failure must never mask the original error or break the SSE stream.
// Gated by the resolved persistence policy for automated, bounded, and
// persona-read-only turns. Persisting one of those prompts here as a
// 'user_stated' frame would bypass the happy-path memory boundary.
// 'user_stated' memory would bypass the happy-path memory boundary.
if (activeSessionOrch && allowMemoryPersistence && message.trim().length >= 8) {
try {
const frames = activeSessionOrch.getFrames();
const sessions = activeSessionOrch.getSessions();
const active = sessions.getActive();
const gopId = active.length > 0 ? active[0].gop_id : sessions.create().gop_id;
const latestI = frames.getLatestIFrame(gopId);
if (latestI) frames.createPFrame(gopId, message, latestI.id, 'normal', 'user_stated');
else frames.createIFrame(gopId, message, 'normal', 'user_stated');
const turnWorkspace = activeSessionOrch.getWorkspaceId();
await activeSessionOrch.getMemory().remember({
scope: turnWorkspace ? workspaceScope(turnWorkspace) : PERSONAL_SCOPE,
text: message,
kind: 'note',
source: 'user_stated',
origin: 'chat',
});
log.info('[chat] persisted raw user turn to memory despite generation failure');
} catch (persistErr) {
log.warn('[chat] raw-turn persistence on error path failed:', persistErr instanceof Error ? persistErr.message : String(persistErr));
@@ -3680,13 +3634,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
activeChatRuntime.runtime,
);
}
if (pinnedWorkspaceMindId) {
try { server.mindCache.release(pinnedWorkspaceMindId); } catch { /* cache already torn down */ }
}
// Un-pin the shared orchestrator's workspace mind (see acquire above).
if (pinnedSharedMindId) {
try { server.mindCache.release(pinnedSharedMindId); } catch { /* cache already torn down */ }
}
// Review Critical #2: defensive cleanup for the pre:tool hook. The happy path
// already unregisters and sets to undefined; this guarantees we never leak the
// hook into the shared hookRegistry on any exception path.

View File

@@ -229,9 +229,8 @@ export const commandRoutes: FastifyPluginAsync = async (server) => {
if (existing) {
commandOrch = existing.orchestrator;
} else {
const mind = server.agentState.getWorkspaceMindDb(workspaceId);
if (mind) {
commandOrch = server.agentState.createSessionOrchestrator(mind);
if (server.workspaceManager.get(workspaceId)) {
commandOrch = server.agentState.createSessionOrchestrator(workspaceId);
}
}
}

View File

@@ -38,9 +38,8 @@ export const commandRoutes: FastifyPluginAsync = async (server) => {
if (existing) {
commandOrch = existing.orchestrator;
} else {
const mind = server.agentState.getWorkspaceMindDb(workspaceId);
if (mind) {
commandOrch = server.agentState.createSessionOrchestrator(mind);
if (server.workspaceManager.get(workspaceId)) {
commandOrch = server.agentState.createSessionOrchestrator(workspaceId);
}
}
}

View File

@@ -4,7 +4,8 @@ import os from 'node:os';
import path from 'node:path';
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { evaluateExternalMemoryIngress, FrameStore, SessionStore } from '@waggle/core';
import { evaluateExternalMemoryIngress } from '@waggle/core';
import { recordRunResult } from '../run-memory.js';
import {
classifyRateLimitError,
detectInstalledTools,
@@ -613,7 +614,7 @@ function finalizeExternalRoom(
function mergeMemoryRefs(refs: CollaborationRunMemoryRefs[]): CollaborationRunMemoryRefs {
const personalFrameIds = [...new Set(refs.flatMap((ref) => ref.personalFrameIds))];
const workspaceFrameIds: Record<string, number[]> = {};
const workspaceFrameIds: Record<string, string[]> = {};
for (const ref of refs) {
for (const [workspaceId, ids] of Object.entries(ref.workspaceFrameIds)) {
workspaceFrameIds[workspaceId] = [...new Set([...(workspaceFrameIds[workspaceId] ?? []), ...ids])];
@@ -947,61 +948,20 @@ async function recordResultToMinds(
const safeSummary = durableIngress.action === 'allow'
? input.result.summary
: `[Quarantined external result: ${durableIngress.scan.flags.join(', ') || 'injection risk'}]`;
const metadata = JSON.stringify({
runId: input.run.id,
roomId: input.run.roomId,
return recordRunResult(server.memory, {
workspaceId: input.run.workspaceId,
toolId: input.run.executor.toolId,
externalSessionId: safeExternalSessionId(input.result.sessionId) ?? null,
...(input.run.attribution ?? {}),
injection: originalSummaryScan,
personalText: `[External agent run]\nRun: ${input.run.id}\nWorkspace: ${input.run.workspaceId}\nTool: ${input.run.executor.toolId}\nStatus: ${input.result.status}\nSummary: ${safeSummary.slice(0, 1_000)}`,
workspaceText: `[External agent result]\nRun: ${input.run.id}\nTool: ${input.run.executor.toolId}\nTask:\n${input.prompt}\n\nResult:\n${safeSummary.slice(0, RESULT_MEMORY_LIMIT)}`,
metadata: {
runId: input.run.id,
roomId: input.run.roomId,
workspaceId: input.run.workspaceId,
toolId: input.run.executor.toolId,
externalSessionId: safeExternalSessionId(input.result.sessionId) ?? null,
...(input.run.attribution ?? {}),
injection: originalSummaryScan,
},
});
const personalFrameIds: number[] = [];
const workspaceFrameIds: Record<string, number[]> = {};
let personalOk = false;
let workspaceOk = false;
try {
const personal = server.multiMind.personal;
new SessionStore(personal).ensure('agent-runs', 'agent-runs', 'Agent collaboration index');
const frames = new FrameStore(personal);
const frame = frames.createIFrame(
'agent-runs',
`[External agent run]\nRun: ${input.run.id}\nWorkspace: ${input.run.workspaceId}\nTool: ${input.run.executor.toolId}\nStatus: ${input.result.status}\nSummary: ${safeSummary.slice(0, 1_000)}`,
'normal',
'agent_inferred',
);
frames.setMetadata(frame.id, metadata);
personalFrameIds.push(frame.id);
personalOk = true;
} catch { /* workspace memory can still succeed */ }
let acquired = false;
try {
const db = server.mindCache.acquire(input.run.workspaceId);
acquired = true;
new SessionStore(db).ensure('agent-runs', 'agent-runs', 'Agent collaboration results');
const frames = new FrameStore(db);
const frame = frames.createIFrame(
'agent-runs',
`[External agent result]\nRun: ${input.run.id}\nTool: ${input.run.executor.toolId}\nTask:\n${input.prompt}\n\nResult:\n${safeSummary.slice(0, RESULT_MEMORY_LIMIT)}`,
'normal',
'agent_inferred',
);
frames.setMetadata(frame.id, metadata);
workspaceFrameIds[input.run.workspaceId] = [frame.id];
workspaceOk = true;
} catch {
// Personal index may still have succeeded; return a truthful partial state.
} finally {
if (acquired) server.mindCache.release(input.run.workspaceId);
}
return {
status: personalOk && workspaceOk ? 'complete' : (personalOk || workspaceOk ? 'partial' : 'failed'),
personalFrameIds,
workspaceFrameIds,
};
}
interface OpenClawInvocation {

View File

@@ -64,29 +64,27 @@ function resolveWorkspace(server: FastifyInstance, workspaceId: string) {
}
/**
* Resolve (lazily) a FileIndexer for the given workspace's mind.
* Returns null when the workspace mind is unavailable — indexing then becomes
* a no-op rather than failing the upload. Indexing is a best-effort side
* effect of file writes (L-20); user-facing file ops must not fail because
* of it.
* Resolve a FileIndexer for the given workspace's memory. Returns null when
* the workspace is unknown — indexing then becomes a no-op rather than failing
* the upload. Indexing is a best-effort side effect of file writes (L-20);
* user-facing file ops must not fail because of it.
*/
function resolveIndexer(server: FastifyInstance, workspaceId: string): FileIndexer | null {
try {
const cache = server.mindCache;
const mind = cache?.getOrOpen(workspaceId);
return mind ? new FileIndexer(mind) : null;
if (!server.workspaceManager.get(workspaceId)) return null;
return new FileIndexer(server.waggleDb, server.memory, workspaceId);
} catch {
return null;
}
}
function safeIndex(indexer: FileIndexer | null, op: () => void): void {
async function safeIndex(indexer: FileIndexer | null, op: () => unknown): Promise<void> {
if (!indexer) return;
try {
op();
await op();
} catch {
// Intentional: indexing is a side-effect. Failures are swallowed so a
// bad frame insert doesn't break the user's file operation. Failures
// bad memory write doesn't break the user's file operation. Failures
// here are rare (bad UTF-8, full disk, etc.) and recoverable by a
// manual re-index in the future.
}
@@ -167,7 +165,7 @@ export async function fileRoutes(server: FastifyInstance) {
const targetPath = (targetDir ?? '/').replace(/\/$/, '') + '/' + filename;
const entry = await provider.write(targetPath, fileData, lookup(filename));
const indexer = resolveIndexer(server, workspaceId);
safeIndex(indexer, () => indexer!.indexFile(targetPath, fileData, lookup(filename)));
await safeIndex(indexer, () => indexer!.indexFile(targetPath, fileData, lookup(filename)));
return reply.status(201).send(entry);
}
@@ -185,7 +183,7 @@ export async function fileRoutes(server: FastifyInstance) {
const targetPath = body.path.replace(/\/$/, '') + '/' + body.name;
const entry = await provider.write(targetPath, fileData, lookup(body.name));
const indexer = resolveIndexer(server, workspaceId);
safeIndex(indexer, () => indexer!.indexFile(targetPath, fileData, lookup(body.name)));
await safeIndex(indexer, () => indexer!.indexFile(targetPath, fileData, lookup(body.name)));
return reply.status(201).send(entry);
} catch (err: unknown) {
const message = errMessage(err);
@@ -274,7 +272,7 @@ export async function fileRoutes(server: FastifyInstance) {
const { provider } = resolveWorkspace(server, workspaceId);
await provider.delete(targetPath);
const indexer = resolveIndexer(server, workspaceId);
safeIndex(indexer, () => indexer!.removeFile(targetPath));
await safeIndex(indexer, () => indexer!.removeFile(targetPath));
return reply.status(204).send();
} catch (err: unknown) {
const message = errMessage(err);
@@ -301,7 +299,7 @@ export async function fileRoutes(server: FastifyInstance) {
const { provider } = resolveWorkspace(server, workspaceId);
const entry = await provider.move(from, to);
const indexer = resolveIndexer(server, workspaceId);
safeIndex(indexer, () => indexer!.moveFile(from, to));
await safeIndex(indexer, () => indexer!.moveFile(from, to));
return entry;
} catch (err: unknown) {
const message = errMessage(err);
@@ -352,7 +350,7 @@ export async function fileRoutes(server: FastifyInstance) {
if (indexer && entry.type === 'file' && FileIndexer.shouldIndex(to)) {
try {
const data = await targetProvider.read(to);
safeIndex(indexer, () => indexer.indexFile(to, data, lookup(to)));
await safeIndex(indexer, () => indexer.indexFile(to, data, lookup(to)));
} catch {
// Provider might not support read after copy — skip silently.
}

View File

@@ -95,13 +95,11 @@ export async function fleetRoutes(fastify: FastifyInstance) {
const sessionManager = fastify.sessionManager;
if (!sessionManager) return reply.code(503).send({ error: 'Session manager not available' });
// Acquire the workspace mind. Without it we cannot construct a session
// orchestrator, so the spawn would be a no-op against the runtime.
const mind = fastify.agentState.getWorkspaceMindDb(wsId);
if (!mind) {
// Without a known workspace the spawn would be a no-op against the runtime.
if (!fastify.workspaceManager.get(wsId)) {
return reply.code(404).send({
error: 'workspace_not_found',
message: `Workspace ${wsId} has no mind on disk; cannot spawn`,
message: `Workspace ${wsId} not found; cannot spawn`,
});
}
@@ -122,13 +120,9 @@ export async function fleetRoutes(fastify: FastifyInstance) {
try {
session = sessionManager.getOrCreate(
wsId,
// Pin the shared cache handle for this session's lifetime so an LRU
// eviction elsewhere cannot close this spawn's mind out from under it.
() => fastify.mindCache.acquire(wsId),
(m) => fastify.agentState.createSessionOrchestrator(m),
(m, o) => fastify.agentState.buildToolsForSession(o, wsId, wsId),
() => fastify.agentState.createSessionOrchestrator(wsId),
(o) => fastify.agentState.buildToolsForSession(o, wsId, wsId),
persona ?? fastify.workspaceManager?.get(wsId)?.personaId ?? undefined,
() => fastify.mindCache.release(wsId),
);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -212,10 +206,10 @@ export async function fleetRoutes(fastify: FastifyInstance) {
);
} catch (err) {
log.warn(`[fleet/spawn] prompt-assembler failed, falling back: ${(err as Error).message}`);
systemPrompt = session.orchestrator.buildSystemPrompt();
systemPrompt = await session.orchestrator.buildSystemPrompt();
}
} else {
systemPrompt = session.orchestrator.buildSystemPrompt();
systemPrompt = await session.orchestrator.buildSystemPrompt();
}
const result = await runAgentLoop({

View File

@@ -1,70 +0,0 @@
import type { ImportItemType, UniversalImportItem } from '@waggle/core';
import type { MemoryKind } from '@waggle/shared';
/**
* UX-Refactor Phase 2B.3 — server-side harvest classification.
*
* Two pure helpers used by the harvest preview/commit path:
* 1. `importItemTypeToMemoryKind` — maps the 8 harvest `ImportItemType` values
* onto the canonical PRD §15.2 `MemoryKind` vocabulary (B6). This lives in
* the server (not `@waggle/shared`) because the build order forbids shared
* from importing the hive-mind-core `ImportItemType` union; the server
* imports both. The FE display-category map is the mirror in
* `apps/web/src/lib/harvest-kind-map.ts`.
* 2. `harvestConfidence` — the B2 heuristic confidence (0-100): a blend of
* source-trust × adapter-item-type, NO per-import LLM call. (The dedup-boost
* signal and LLM scoring are reserved for the standing J08 review queue, per
* the B2 ratification — computing dedup here would re-introduce the O(n·500)
* per-item store scan the commit path deliberately avoids.)
*/
const IMPORT_ITEM_TYPE_TO_MEMORY_KIND: Record<ImportItemType, MemoryKind> = {
conversation: 'fact',
memory: 'fact',
instruction: 'preference',
preference: 'preference',
artifact: 'fact',
rule: 'preference',
decision: 'decision',
document: 'fact',
};
export function importItemTypeToMemoryKind(type: ImportItemType): MemoryKind {
return IMPORT_ITEM_TYPE_TO_MEMORY_KIND[type] ?? 'fact';
}
/** Baseline trust by adapter source — all are the user's OWN exports, so the
* floor is high; structured/curated sources edge above noisier chat dumps. */
const SOURCE_TRUST: Record<string, number> = {
claude: 85,
'claude-code': 88,
claudeCode: 88,
chatgpt: 80,
gemini: 80,
perplexity: 72,
cursor: 78,
unknown: 62,
};
/** Trust by semantic item type — an explicit decision/preference/rule carries
* more standalone signal than a raw conversation turn. */
const TYPE_TRUST: Record<ImportItemType, number> = {
decision: 95,
preference: 90,
instruction: 90,
rule: 90,
memory: 80,
document: 76,
artifact: 74,
conversation: 64,
};
/**
* Heuristic confidence in [0,100]. Lightly weights the semantic type over the
* raw source (the type is the stronger signal of standalone trustworthiness).
*/
export function harvestConfidence(item: Pick<UniversalImportItem, 'type' | 'source'>): number {
const s = SOURCE_TRUST[item.source] ?? SOURCE_TRUST.unknown;
const t = TYPE_TRUST[item.type] ?? 70;
return Math.round(0.45 * s + 0.55 * t);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,88 +0,0 @@
import type { FastifyInstance } from 'fastify';
import {
evaluateExternalMemoryIngress,
FrameStore,
processImport,
projectExternalMemoryContent,
type ImportSource,
} from '@waggle/core';
export async function importRoutes(fastify: FastifyInstance) {
// POST /api/import/preview — parse export and show what would be imported
fastify.post('/api/import/preview', async (request, reply) => {
const { data, source } = request.body as { data: unknown; source: ImportSource };
if (!data || !source) {
return reply.code(400).send({ error: 'data and source (chatgpt|claude) required' });
}
if (source !== 'chatgpt' && source !== 'claude') {
return reply.code(400).send({ error: 'source must be "chatgpt" or "claude"' });
}
const result = processImport(data, source);
return result;
});
// POST /api/import/commit — parse, extract, and save to personal memory
fastify.post('/api/import/commit', async (request, reply) => {
const { data, source } = request.body as { data: unknown; source: ImportSource };
if (!data || !source) {
return reply.code(400).send({ error: 'data and source (chatgpt|claude) required' });
}
if (source !== 'chatgpt' && source !== 'claude') {
return reply.code(400).send({ error: 'source must be "chatgpt" or "claude"' });
}
const result = processImport(data, source);
if (result.knowledgeExtracted.length === 0) {
return {
...result,
saved: 0,
message: 'No knowledge items found to import',
};
}
const sourceLabel = source === 'chatgpt' ? 'ChatGPT' : 'Claude';
const preparedItems = result.knowledgeExtracted.map((item) => {
const content = `[Import:${sourceLabel}] ${item.content}`;
return {
content,
importance: item.importance,
ingressContent: projectExternalMemoryContent({ content }),
};
});
if (preparedItems.some(({ ingressContent }) => (
evaluateExternalMemoryIngress({ content: ingressContent }).action !== 'allow'
))) {
return reply.status(422).send({ error: 'Imported content could not be saved.' });
}
// Save to personal memory
try {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) {
return reply.code(503).send({ error: 'Personal mind not available' });
}
const frameStore = new FrameStore(personalDb);
let saved = 0;
for (const item of preparedItems) {
frameStore.createIFrame('import', item.content, item.importance);
saved++;
}
return {
...result,
saved,
message: `Imported ${saved} knowledge items from ${sourceLabel} into personal memory`,
};
} catch (err: unknown) {
return reply.code(500).send({ error: `Import failed: ${err instanceof Error ? err.message : String(err)}` });
}
});
}

View File

@@ -11,7 +11,6 @@
import crypto from 'node:crypto';
import type { FastifyPluginAsync } from 'fastify';
import { escapeXml } from './harvest.js';
// ── OAuth provider configuration ─────────────────────────────────────
@@ -319,3 +318,13 @@ export const oauthRoutes: FastifyPluginAsync = async (server) => {
}
});
};
/** Escapes text for HTML/XML output. */
function escapeXml(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}

View File

@@ -2,7 +2,8 @@ import type { FastifyInstance, FastifyPluginAsync, FastifyRequest } from 'fastif
import fp from 'fastify-plugin';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import { evaluateExternalMemoryIngress, FrameStore, SessionStore } from '@waggle/core';
import { evaluateExternalMemoryIngress } from '@waggle/core';
import { PERSONAL_SCOPE } from '@waggle/memory-contract';
import {
validateMessageTypeCombo,
WaggleDanceDispatcher,
@@ -260,38 +261,11 @@ function recordAuthenticatedRunSignal(
const current = server.agentRunRegistry.get(run.id);
if (!current || current.kind !== 'worker') return;
const personalFrameIds = [...(current.memoryRefs.personalFrameIds ?? [])];
const workspaceFrameIds = { ...(current.memoryRefs.workspaceFrameIds ?? {}) };
let personalStored = false;
try {
new SessionStore(server.multiMind.personal).ensure(
'agent-signals', 'agent-signals', 'Agent collaboration signals',
);
const frames = new FrameStore(server.multiMind.personal);
const frame = frames.createIFrame(
'agent-signals',
`[Agent collaboration signal]\nRoom: ${run.roomId}\nRun: ${run.id}\nWorkspace: ${run.workspaceId}\nTool: ${run.executor.toolId ?? 'agent'}\nSubtype: ${message.subtype}\nSummary: ${safeSummary.slice(0, 1_000)}`,
'normal',
'agent_inferred',
);
frames.setMetadata(frame.id, JSON.stringify({
messageId: message.id,
roomId: run.roomId,
runId: run.id,
workspaceId: run.workspaceId,
toolId: run.executor.toolId ?? null,
subtype: message.subtype,
}));
if (!personalFrameIds.includes(frame.id)) personalFrameIds.push(frame.id);
personalStored = true;
} catch (err) {
server.log.warn({ err, runId: run.id }, 'failed to index authenticated agent signal');
}
const rawFrameId = message.content.frameId;
const frameId = typeof rawFrameId === 'number'
? rawFrameId
: typeof rawFrameId === 'string' && /^\d+$/.test(rawFrameId) ? Number(rawFrameId) : undefined;
const frameId = typeof rawFrameId === 'string' && rawFrameId.trim()
? rawFrameId.trim()
: typeof rawFrameId === 'number' ? String(rawFrameId) : undefined;
const workspaceStored = frameId !== undefined
&& message.content.memoryWorkspace === run.workspaceId;
if (workspaceStored) {
@@ -304,11 +278,36 @@ function recordAuthenticatedRunSignal(
...(['queued', 'starting'].includes(current.status) ? { status: 'running' } : {}),
progress: { phase: message.subtype, message: safeSummary.slice(0, 500) },
result: { summary: safeSummary },
memoryRefs: {
status: personalStored && workspaceStored ? 'complete' : current.memoryRefs.status,
personalFrameIds,
workspaceFrameIds,
memoryRefs: { workspaceFrameIds },
});
// Index the signal in personal memory; the run's memoryRefs follow when the write lands.
void server.memory.remember({
scope: PERSONAL_SCOPE,
text: `[Agent collaboration signal]\nRoom: ${run.roomId}\nRun: ${run.id}\nWorkspace: ${run.workspaceId}\nTool: ${run.executor.toolId ?? 'agent'}\nSubtype: ${message.subtype}\nSummary: ${safeSummary.slice(0, 1_000)}`,
kind: 'note',
source: 'agent_inferred',
origin: 'agent-signals',
metadata: {
messageId: message.id,
roomId: run.roomId,
runId: run.id,
workspaceId: run.workspaceId,
toolId: run.executor.toolId ?? null,
subtype: message.subtype,
},
}).then(([change]) => {
const latest = server.agentRunRegistry.get(run.id);
if (!change || !latest) return;
const personalFrameIds = [...new Set([...latest.memoryRefs.personalFrameIds, change.record.id])];
server.agentRunRegistry.update(run.id, {
memoryRefs: {
status: workspaceStored ? 'complete' : latest.memoryRefs.status,
personalFrameIds,
},
});
}).catch((err: unknown) => {
server.log.warn({ err, runId: run.id }, 'failed to index authenticated agent signal');
});
}

View File

@@ -1,130 +0,0 @@
/**
* Weaver REST API Routes — memory consolidation management.
*
* Endpoints:
* GET /api/weaver/status — check weaver state and last-run times
* POST /api/weaver/trigger — manually trigger a consolidation cycle
*/
import type { FastifyPluginAsync } from 'fastify';
import { FrameStore, SessionStore } from '@waggle/core';
import { MemoryWeaver } from '@waggle/weaver';
export const weaverRoutes: FastifyPluginAsync = async (server) => {
// F2: GET /api/weaver/status — check weaver state
server.get('/api/weaver/status', async () => {
const weaverState = server.agentState.weaverState ?? { lastPersonalConsolidation: null, lastPersonalDecay: null };
const workspaceWeavers = server.agentState.workspaceWeaverStatus ?? {};
return {
personalMind: {
lastConsolidation: weaverState.lastPersonalConsolidation ?? null,
lastDecay: weaverState.lastPersonalDecay ?? null,
timerActive: true,
},
workspaces: Object.entries(workspaceWeavers).map(([id, state]) => ({
id,
lastConsolidation: state?.lastConsolidation ?? null,
timerActive: true,
})),
checkedAt: new Date().toISOString(),
};
});
// POST /api/weaver/trigger — manually trigger a consolidation cycle
server.post<{
Body?: {
workspaceId?: string;
workspace?: string;
};
}>('/api/weaver/trigger', async (request, reply) => {
// P0-4: Accept both 'workspaceId' and 'workspace'
const body = request.body as { workspaceId?: string; workspace?: string } | undefined;
const workspaceId = body?.workspaceId ?? body?.workspace;
const results: {
target: string;
framesConsolidated: number;
framesDecayed: number;
framesStrengthened: number;
}[] = [];
// If no workspaceId, consolidate the personal mind
if (!workspaceId) {
try {
const personalDb = server.multiMind.personal;
const frames = new FrameStore(personalDb);
const sessions = new SessionStore(personalDb);
const weaver = new MemoryWeaver(personalDb, frames, sessions);
let consolidated = 0;
const active = sessions.getActive();
for (const s of active) {
const result = weaver.consolidateGop(s.gop_id);
if (result) consolidated++;
}
const decayed = weaver.decayFrames();
const strengthened = weaver.strengthenFrames();
results.push({
target: 'personal',
framesConsolidated: consolidated,
framesDecayed: decayed,
framesStrengthened: strengthened,
});
} catch (err) {
return reply.status(500).send({
error: `Personal mind consolidation failed: ${(err as Error).message}`,
});
}
} else {
// Consolidate a specific workspace mind
const ws = server.workspaceManager.get(workspaceId);
if (!ws) {
return reply.status(404).send({ error: 'Workspace not found' });
}
try {
// Activate workspace mind to ensure it's loaded
server.agentState.activateWorkspaceMind(workspaceId);
const wsDb = server.agentState.getWorkspaceMindDb(workspaceId);
if (!wsDb) {
return reply.status(500).send({ error: 'Could not open workspace mind database' });
}
const frames = new FrameStore(wsDb);
const sessions = new SessionStore(wsDb);
const weaver = new MemoryWeaver(wsDb, frames, sessions);
let consolidated = 0;
const active = sessions.getActive();
for (const s of active) {
const result = weaver.consolidateGop(s.gop_id);
if (result) consolidated++;
}
const decayed = weaver.decayFrames();
const strengthened = weaver.strengthenFrames();
results.push({
target: `workspace:${ws.name}`,
framesConsolidated: consolidated,
framesDecayed: decayed,
framesStrengthened: strengthened,
});
} catch (err) {
return reply.status(500).send({
error: `Workspace consolidation failed: ${(err as Error).message}`,
});
}
}
return {
ok: true,
results,
triggeredAt: new Date().toISOString(),
};
});
};

View File

@@ -1,201 +0,0 @@
import type { FastifyPluginAsync } from 'fastify';
import {
FrameStore,
KnowledgeGraph,
HybridSearch,
} from '@waggle/core';
import {
WikiCompiler, CompilationState, resolveSynthesizer,
writeToObsidianVault, writeToNotionWorkspace, extractNotionPageId,
type NotionStateHelpers,
} from '@waggle/wiki-compiler';
import * as path from 'node:path';
export const wikiRoutes: FastifyPluginAsync = async (server) => {
function getPersonalDb() {
const db = server.multiMind?.personal;
if (!db) throw new Error('Personal mind not initialized');
return db;
}
// GET /api/wiki/pages — list all compiled pages
server.get('/api/wiki/pages', async (_req, reply) => {
const db = getPersonalDb();
const state = new CompilationState(db);
return reply.send(state.getAllPages());
});
// GET /api/wiki/pages/:slug — get a single page metadata
server.get<{ Params: { slug: string } }>('/api/wiki/pages/:slug', async (req, reply) => {
const db = getPersonalDb();
const state = new CompilationState(db);
const page = state.getPage(req.params.slug);
if (!page) return reply.status(404).send({ error: 'Page not found' });
return reply.send(page);
});
// GET /api/wiki/pages/:slug/content — get full markdown content
server.get<{ Params: { slug: string } }>('/api/wiki/pages/:slug/content', async (req, reply) => {
const db = getPersonalDb();
const raw = db.getDatabase();
const row = raw.prepare(
'SELECT markdown FROM wiki_pages WHERE slug = ?',
).get(req.params.slug) as { markdown: string } | undefined;
if (!row) return reply.status(404).send({ error: 'Page not found' });
return reply.send({ slug: req.params.slug, markdown: row.markdown });
});
// POST /api/wiki/compile — trigger compilation.
// M-11 BLOCKER-5: skip compile entirely if the server has no real embedder
// (active provider is 'mock'). Running with zero-vector embeddings produces
// pages with a silently broken semantic relevance layer — explicit skip
// with a reason is the correct degraded-state response.
server.post<{ Body: { mode?: 'incremental' | 'full'; concepts?: string[] } }>('/api/wiki/compile', async (req, reply) => {
const embedder = server.embeddingProvider;
if (!embedder || embedder.getActiveProvider() === 'mock') {
return reply.status(503).send({
error: 'Wiki compile requires a real embedding provider. Configure a Voyage / OpenAI key in Vault, or an Ollama embedding model, before compiling.',
skippedReason: 'no_real_embedder',
});
}
const db = getPersonalDb();
const kg = new KnowledgeGraph(db);
const frames = new FrameStore(db);
const search = new HybridSearch(db, embedder);
const state = new CompilationState(db);
const synth = await resolveSynthesizer();
const compiler = new WikiCompiler(kg, frames, search, state, {
synthesize: synth.synthesize,
});
const result = await compiler.compile({
incremental: (req.body?.mode ?? 'incremental') === 'incremental',
concepts: req.body?.concepts,
});
return reply.send({
...result,
llmProvider: synth.provider,
llmModel: synth.model,
});
});
// GET /api/wiki/health — health report.
// M-11 BLOCKER-5: same policy as /compile — no mock embedder in a read
// path that feeds a relevance signal to the user. Report the degraded
// state explicitly so the UI can surface an actionable "add embedding
// key" prompt instead of misleading health numbers.
server.get('/api/wiki/health', async (_req, reply) => {
const embedder = server.embeddingProvider;
if (!embedder || embedder.getActiveProvider() === 'mock') {
return reply.status(503).send({
error: 'Wiki health requires a real embedding provider.',
skippedReason: 'no_real_embedder',
});
}
const db = getPersonalDb();
const kg = new KnowledgeGraph(db);
const frames = new FrameStore(db);
const search = new HybridSearch(db, embedder);
const state = new CompilationState(db);
const synth = await resolveSynthesizer();
const compiler = new WikiCompiler(kg, frames, search, state, {
synthesize: synth.synthesize,
});
return reply.send(compiler.compileHealth());
});
// GET /api/wiki/watermark — current compilation state
server.get('/api/wiki/watermark', async (_req, reply) => {
const db = getPersonalDb();
const state = new CompilationState(db);
return reply.send(state.getWatermark());
});
// POST /api/wiki/export/obsidian — M-12: write all compiled pages to a
// directory the user can drop into an Obsidian vault. The adapter shapes
// output as {outDir}/{pageType}/{slug}.md + a top-level _index.md.
server.post<{ Body: { outDir?: string } }>('/api/wiki/export/obsidian', async (req, reply) => {
const outDir = req.body?.outDir?.trim();
if (!outDir) {
return reply.status(400).send({ error: 'outDir is required' });
}
if (!path.isAbsolute(outDir)) {
return reply.status(400).send({ error: 'outDir must be an absolute path' });
}
const db = getPersonalDb();
const state = new CompilationState(db);
const pages = state.getAllPages();
if (pages.length === 0) {
return reply.status(409).send({
error: 'No compiled pages to export. Run compile first.',
});
}
try {
const result = writeToObsidianVault(pages, outDir);
return reply.send(result);
} catch (err) {
return reply.status(500).send({
error: err instanceof Error ? err.message : 'Export failed',
});
}
});
// POST /api/wiki/export/notion — M-13: write compiled pages as child
// pages under a user-chosen Notion root. Reads `notion-wiki-token` from
// Vault; root is supplied as a notion.so URL or raw page id.
server.post<{ Body: { rootPageUrl?: string } }>('/api/wiki/export/notion', async (req, reply) => {
const rootPageUrl = req.body?.rootPageUrl?.trim();
if (!rootPageUrl) {
return reply.status(400).send({ error: 'rootPageUrl is required' });
}
const rootPageId = extractNotionPageId(rootPageUrl);
if (!rootPageId) {
return reply.status(400).send({
error: 'Could not parse a Notion page id from rootPageUrl. Paste the URL of a page you shared with your integration.',
});
}
const token = server.vault?.get('notion-wiki-token')?.value;
if (!token) {
return reply.status(503).send({
error: 'notion-wiki-token not set. Create an internal integration at notion.so/my-integrations, share your root page with it, and save the token in Vault as `notion-wiki-token`.',
});
}
const db = getPersonalDb();
const state = new CompilationState(db);
const pages = state.getAllPages();
if (pages.length === 0) {
return reply.status(409).send({
error: 'No compiled pages to export. Run compile first.',
});
}
// NotionStateHelpers adapter — delegates all the delta-tracking
// bookkeeping to CompilationState so the adapter stays stateless.
const helpers: NotionStateHelpers = {
getNotionPageId: (slug) => state.getNotionPageId(slug),
setNotionPageId: (slug, id) => state.setNotionPageId(slug, id),
clearNotionPageId: (slug) => state.clearNotionPageId(slug),
getPageContentHash: (slug) => state.getPageContentHash(slug),
};
try {
const stats = await writeToNotionWorkspace(pages, { token, rootPageId }, helpers);
return reply.send(stats);
} catch (err) {
return reply.status(500).send({
error: err instanceof Error ? err.message : 'Export failed',
});
}
});
};

View File

@@ -0,0 +1,68 @@
/**
* Where agent-run results land in memory: a short index entry in personal
* memory and the full result in the workspace's memory (ADR-0007).
*/
import {
PERSONAL_SCOPE,
RESERVED_METADATA_KEYS,
workspaceScope,
type MemoryStore,
} from '@waggle/memory-contract';
import type { CollaborationRunMemoryRefs } from '@waggle/shared';
export interface RunResultMemoryInput {
workspaceId: string;
/** Short index entry kept in personal memory. */
personalText: string;
/** The full result, kept in the workspace's memory. */
workspaceText: string;
/** Run identifiers (runId, roomId…). Keys the contract reserves get a `run_` prefix. */
metadata: Record<string, unknown>;
}
function runMetadata(metadata: Record<string, unknown>): Record<string, unknown> {
const reserved: readonly string[] = RESERVED_METADATA_KEYS;
return Object.fromEntries(
Object.entries(metadata).map(([key, value]) => [reserved.includes(key) ? `run_${key}` : key, value]),
);
}
/** Writes both entries; a failed write is reflected in the returned status. */
export async function recordRunResult(
memory: MemoryStore,
input: RunResultMemoryInput,
): Promise<CollaborationRunMemoryRefs> {
const personalFrameIds: string[] = [];
const workspaceFrameIds: Record<string, string[]> = {};
const metadata = runMetadata(input.metadata);
try {
const [change] = await memory.remember({
scope: PERSONAL_SCOPE,
text: input.personalText,
kind: 'note',
source: 'agent_inferred',
origin: 'agent-runs',
metadata,
});
if (change) personalFrameIds.push(change.record.id);
} catch { /* workspace result remains authoritative */ }
try {
const [change] = await memory.remember({
scope: workspaceScope(input.workspaceId),
text: input.workspaceText,
kind: 'note',
source: 'agent_inferred',
origin: 'agent-runs',
metadata,
});
if (change) workspaceFrameIds[input.workspaceId] = [change.record.id];
} catch { /* reflected in the status below */ }
const personalOk = personalFrameIds.length > 0;
const workspaceOk = (workspaceFrameIds[input.workspaceId]?.length ?? 0) > 0;
return {
status: personalOk && workspaceOk ? 'complete' : personalOk || workspaceOk ? 'partial' : 'failed',
personalFrameIds,
workspaceFrameIds,
};
}

View File

@@ -1,191 +0,0 @@
import type { EmbeddingProviderInstance, MindDB } from '@waggle/core';
import {
runVectorBackfill,
type VectorBackfillOptions,
type VectorBackfillResult,
} from '../vector-backfill.js';
const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;
const DEFAULT_MAX_PASSES_PER_MIND = 4;
const DEFAULT_MAX_WORKSPACES_PER_RUN = 20;
export interface VectorEnrichmentServiceDeps {
personalMind: MindDB;
embeddingProvider: EmbeddingProviderInstance;
listWorkspaceIds: () => string[];
acquireWorkspaceMind: (workspaceId: string) => MindDB;
releaseWorkspaceMind: (workspaceId: string) => void;
/** Test seam; production uses runVectorBackfill. */
runPass?: (
db: MindDB,
provider: EmbeddingProviderInstance,
options?: VectorBackfillOptions,
) => Promise<VectorBackfillResult>;
log?: (level: 'info' | 'warn', message: string) => void;
}
export interface VectorEnrichmentServiceConfig extends VectorBackfillOptions {
intervalMs?: number;
maxPassesPerMind?: number;
maxWorkspacesPerRun?: number;
}
export interface VectorEnrichmentRunResult {
mindsVisited: number;
passes: number;
framesProcessed: number;
framesReembedded: number;
chunksCreated: number;
errors: string[];
}
function positiveInteger(value: number | undefined, fallback: number): number {
return Number.isFinite(value) ? Math.max(1, Math.trunc(value as number)) : fallback;
}
/**
* Single-flight background reconciler. One run starts immediately, then every
* five minutes. Each workspace mind stays cache-pinned across all of its
* bounded passes, and shutdown waits for the active run before DB teardown.
*/
export class VectorEnrichmentService {
private readonly deps: VectorEnrichmentServiceDeps;
private readonly config: Required<VectorEnrichmentServiceConfig>;
private timer: ReturnType<typeof setInterval> | null = null;
private inFlight: Promise<VectorEnrichmentRunResult> | null = null;
private workspaceCursor = 0;
private stopping = false;
constructor(deps: VectorEnrichmentServiceDeps, config: VectorEnrichmentServiceConfig = {}) {
this.deps = deps;
this.config = {
intervalMs: positiveInteger(config.intervalMs, DEFAULT_INTERVAL_MS),
maxPassesPerMind: positiveInteger(config.maxPassesPerMind, DEFAULT_MAX_PASSES_PER_MIND),
maxWorkspacesPerRun: positiveInteger(config.maxWorkspacesPerRun, DEFAULT_MAX_WORKSPACES_PER_RUN),
maxFrames: positiveInteger(config.maxFrames, 32),
batchSize: positiveInteger(config.batchSize, 8),
};
}
start(): void {
if (this.timer || this.stopping) return;
void this.runNow();
this.timer = setInterval(() => { void this.runNow(); }, this.config.intervalMs);
this.timer.unref?.();
}
runNow(): Promise<VectorEnrichmentRunResult> {
if (this.inFlight) return this.inFlight;
if (this.stopping) {
return Promise.resolve({
mindsVisited: 0,
passes: 0,
framesProcessed: 0,
framesReembedded: 0,
chunksCreated: 0,
errors: [],
});
}
const task = this.runOnce();
this.inFlight = task;
void task.finally(() => {
if (this.inFlight === task) this.inFlight = null;
}).catch(() => undefined);
return task;
}
async stop(): Promise<void> {
this.stopping = true;
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
const active = this.inFlight;
if (active) await active.catch(() => undefined);
}
private async runOnce(): Promise<VectorEnrichmentRunResult> {
const aggregate: VectorEnrichmentRunResult = {
mindsVisited: 0,
passes: 0,
framesProcessed: 0,
framesReembedded: 0,
chunksCreated: 0,
errors: [],
};
const personalLast = await this.runMind('personal', this.deps.personalMind, aggregate);
if (personalLast?.skipped === 'no_real_embedder' || personalLast?.skipped === 'provider_degraded') {
return aggregate;
}
const workspaceIds = [...new Set(this.deps.listWorkspaceIds())];
if (workspaceIds.length === 0 || this.stopping) return aggregate;
const selected: string[] = [];
const count = Math.min(workspaceIds.length, this.config.maxWorkspacesPerRun);
for (let offset = 0; offset < count; offset += 1) {
selected.push(workspaceIds[(this.workspaceCursor + offset) % workspaceIds.length]);
}
this.workspaceCursor = (this.workspaceCursor + count) % workspaceIds.length;
for (const workspaceId of selected) {
if (this.stopping) break;
let acquired = false;
try {
const mind = this.deps.acquireWorkspaceMind(workspaceId);
acquired = true;
await this.runMind(`workspace ${workspaceId}`, mind, aggregate);
} catch (err) {
const message = `workspace ${workspaceId}: ${err instanceof Error ? err.message : String(err)}`;
aggregate.errors.push(message);
this.deps.log?.('warn', `Vector enrichment failed for ${message}`);
} finally {
if (acquired) this.deps.releaseWorkspaceMind(workspaceId);
}
}
return aggregate;
}
private async runMind(
label: string,
mind: MindDB,
aggregate: VectorEnrichmentRunResult,
): Promise<VectorBackfillResult | null> {
aggregate.mindsVisited += 1;
let last: VectorBackfillResult | null = null;
const runPass = this.deps.runPass ?? runVectorBackfill;
for (let pass = 0; pass < this.config.maxPassesPerMind && !this.stopping; pass += 1) {
try {
last = await runPass(mind, this.deps.embeddingProvider, {
maxFrames: this.config.maxFrames,
batchSize: this.config.batchSize,
});
} catch (err) {
const message = `${label}: ${err instanceof Error ? err.message : String(err)}`;
aggregate.errors.push(message);
this.deps.log?.('warn', `Vector enrichment failed for ${message}`);
break;
}
aggregate.passes += 1;
aggregate.framesProcessed += last.framesProcessed;
aggregate.framesReembedded += last.framesReembedded;
aggregate.chunksCreated += last.chunksCreated;
if (last.errors.length > 0) {
const messages = last.errors.map(error => `${label}: ${error}`);
aggregate.errors.push(...messages);
this.deps.log?.('warn', `Vector enrichment deferred for ${messages.join('; ')}`);
break;
}
if (last.skipped || !last.hasMore) break;
}
if (last && !last.skipped && (last.framesProcessed > 0 || last.vectorsRepaired)) {
this.deps.log?.(
'info',
`Vector enrichment (${label}): frames=${last.framesProcessed} ` +
`whole=${last.framesReembedded} chunks=${last.chunksCreated}`,
);
}
return last;
}
}

View File

@@ -1,449 +0,0 @@
/**
* Bounded vector + chunk reconciliation for frames written by fast hook paths.
*
* The legacy `vector_backfill_v1` marker records only the destructive
* mock-fingerprint rebuild. It never suppresses incremental reconciliation:
* hook writes intentionally persist frame/FTS data first and this pass repairs
* missing semantic indexes shortly afterwards.
*/
import {
HybridSearch,
type Embedder,
type EmbeddingProviderInstance,
type EmbeddingProviderStatus,
type EmbeddingProviderType,
type MindDB,
} from '@waggle/core';
const LEGACY_FLAG_KEY = 'vector_backfill_v1';
const CURSOR_KEY = 'vector_enrichment_cursor_v1';
const DEFAULT_MAX_FRAMES = 32;
const DEFAULT_BATCH_SIZE = 8;
export interface VectorBackfillOptions {
/** Maximum incomplete frames considered by one pass. */
maxFrames?: number;
/** Maximum missing whole-frame vectors embedded in one provider batch. */
batchSize?: number;
}
export interface VectorBackfillResult {
skipped: 'no_real_embedder' | 'provider_degraded' | 'fingerprint_mismatch' | 'empty_mind' | null;
/** True when untrusted mock/unknown vector tables were rebuilt. */
vectorsRepaired: boolean;
framesReembedded: number;
chunksCreated: number;
framesProcessed: number;
/** More incomplete frames remain for a later bounded pass. */
hasMore: boolean;
errors: string[];
}
interface RepairCandidate {
id: number;
content: string;
whole_missing: 0 | 1;
}
interface ProviderFingerprint {
provider: EmbeddingProviderType;
model: string;
dim: number;
}
function emptyResult(): VectorBackfillResult {
return {
skipped: null,
vectorsRepaired: false,
framesReembedded: 0,
chunksCreated: 0,
framesProcessed: 0,
hasMore: false,
errors: [],
};
}
function clampInteger(value: number | undefined, fallback: number, max: number): number {
if (!Number.isFinite(value)) return fallback;
return Math.max(1, Math.min(max, Math.trunc(value as number)));
}
function activeFingerprint(embedder: EmbeddingProviderInstance): ProviderFingerprint {
const status = embedder.getStatus();
return {
provider: status.activeProvider,
model: status.modelName,
dim: embedder.dimensions,
};
}
function fingerprintLabel(fingerprint: ProviderFingerprint): string {
return `${fingerprint.provider}/${fingerprint.model}/${fingerprint.dim}`;
}
function providerProblem(
embedder: EmbeddingProviderInstance,
expected?: ProviderFingerprint,
): string | null {
const status = embedder.getStatus();
const current = activeFingerprint(embedder);
if (embedder.getActiveProvider() === 'mock' || status.activeProvider === 'mock') {
return 'no real embedding provider is active';
}
if (status.lastError) return `embedding provider degraded: ${status.lastError}`;
if (
expected
&& (
current.provider !== expected.provider
|| current.model !== expected.model
|| current.dim !== expected.dim
)
) {
return `embedding provider changed during enrichment: expected=${fingerprintLabel(expected)}, ` +
`active=${fingerprintLabel(current)}`;
}
return null;
}
async function prepareProvider(
embedder: EmbeddingProviderInstance,
expected?: ProviderFingerprint,
): Promise<string | null> {
let problem = providerProblem(embedder, expected);
if (!problem) return null;
try {
await embedder.reprobe();
} catch (err) {
return `embedding provider reprobe failed: ${err instanceof Error ? err.message : String(err)}`;
}
problem = providerProblem(embedder, expected);
return problem;
}
/**
* EmbeddingProvider deliberately returns deterministic mock vectors on a live
* provider failure. HybridSearch cannot distinguish those values by itself,
* so this adapter checks provider status and the captured fingerprint before
* and after every await, then exposes only that captured fingerprint to
* HybridSearch. A concurrent reprobe therefore cannot silently mix spaces.
*/
function strictEmbedder(
embedder: EmbeddingProviderInstance,
expected: ProviderFingerprint,
): Embedder {
const capturedStatus: EmbeddingProviderStatus = {
...embedder.getStatus(),
activeProvider: expected.provider,
dimensions: expected.dim,
modelName: expected.model,
lastError: undefined,
};
const assertHealthy = (): void => {
const problem = providerProblem(embedder, expected);
if (problem) throw new Error(problem);
};
return {
dimensions: expected.dim,
getActiveProvider: () => expected.provider,
getStatus: () => capturedStatus,
async embed(text: string): Promise<Float32Array> {
assertHealthy();
const value = await embedder.embed(text);
assertHealthy();
return value;
},
async embedBatch(texts: string[]): Promise<Float32Array[]> {
assertHealthy();
const values = await embedder.embedBatch(texts);
assertHealthy();
return values;
},
} as Embedder;
}
const SELECT_REPAIR_CANDIDATES_SQL = `
SELECT
f.id,
f.content,
CASE WHEN f.id IN (SELECT rowid FROM memory_frames_vec) THEN 0 ELSE 1 END AS whole_missing
FROM memory_frames f
WHERE f.importance != 'deprecated'
AND (
f.id NOT IN (SELECT rowid FROM memory_frames_vec)
OR (
length(f.content) > 0
AND (
f.id NOT IN (SELECT DISTINCT frame_id FROM memory_frame_chunks)
OR f.id IN (
SELECT c.frame_id
FROM memory_frame_chunks c
LEFT JOIN memory_frame_chunks_vec cv ON cv.rowid = c.id
WHERE cv.rowid IS NULL
)
)
)
)
AND f.id > ?
ORDER BY f.id
LIMIT ?
`;
const HAS_PENDING_CANDIDATES_SQL = `
SELECT 1 AS pending
FROM memory_frames f
WHERE f.importance != 'deprecated'
AND (
f.id NOT IN (SELECT rowid FROM memory_frames_vec)
OR (
length(f.content) > 0
AND (
f.id NOT IN (SELECT DISTINCT frame_id FROM memory_frame_chunks)
OR f.id IN (
SELECT c.frame_id
FROM memory_frame_chunks c
LEFT JOIN memory_frame_chunks_vec cv ON cv.rowid = c.id
WHERE cv.rowid IS NULL
)
)
)
)
LIMIT 1
`;
function selectCandidates(db: MindDB, limit: number, afterId: number): RepairCandidate[] {
return db.getDatabase().prepare(SELECT_REPAIR_CANDIDATES_SQL)
.all(afterId, limit) as RepairCandidate[];
}
function hasPendingCandidates(db: MindDB): boolean {
return Boolean(db.getDatabase().prepare(HAS_PENDING_CANDIDATES_SQL).get());
}
function readCursor(db: MindDB): number {
const row = db.getDatabase().prepare('SELECT value FROM meta WHERE key = ?').get(CURSOR_KEY) as
| { value: string }
| undefined;
const parsed = Number(row?.value ?? 0);
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;
}
function writeCursor(db: MindDB, frameId: number): void {
db.getDatabase().prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)')
.run(CURSOR_KEY, String(Math.max(0, Math.trunc(frameId))));
}
function chunkVectorCountForFrames(db: MindDB, frameIds: readonly number[]): number {
if (frameIds.length === 0) return 0;
const placeholders = frameIds.map(() => '?').join(', ');
const row = db.getDatabase().prepare(`
SELECT COUNT(*) AS n
FROM memory_frame_chunks c
JOIN memory_frame_chunks_vec cv ON cv.rowid = c.id
WHERE c.frame_id IN (${placeholders})
`).get(...frameIds) as { n: number };
return row.n;
}
function frameNeedsChunkRepair(db: MindDB, frame: RepairCandidate): boolean {
if (frame.content.length === 0) return false;
return Boolean(db.getDatabase().prepare(`
SELECT 1
WHERE NOT EXISTS (
SELECT 1 FROM memory_frame_chunks WHERE frame_id = ?
) OR EXISTS (
SELECT 1
FROM memory_frame_chunks c
LEFT JOIN memory_frame_chunks_vec cv ON cv.rowid = c.id
WHERE c.frame_id = ? AND cv.rowid IS NULL
)
`).get(frame.id, frame.id));
}
function hasWholeVector(db: MindDB, frameId: number): boolean {
return Boolean(db.getDatabase().prepare(
'SELECT 1 FROM memory_frames_vec WHERE rowid = ?',
).get(Math.trunc(frameId)));
}
function existingVectorCount(db: MindDB): number {
const raw = db.getDatabase();
const whole = (raw.prepare('SELECT COUNT(*) AS n FROM memory_frames_vec').get() as { n: number }).n;
const chunks = (raw.prepare('SELECT COUNT(*) AS n FROM memory_frame_chunks_vec').get() as { n: number }).n;
return whole + chunks;
}
/** Run one bounded incremental repair pass. Never throws. */
export async function runVectorBackfill(
db: MindDB,
embedder: EmbeddingProviderInstance | undefined,
options: VectorBackfillOptions = {},
): Promise<VectorBackfillResult> {
const result = emptyResult();
const maxFrames = clampInteger(options.maxFrames, DEFAULT_MAX_FRAMES, 256);
const batchSize = clampInteger(options.batchSize, DEFAULT_BATCH_SIZE, maxFrames);
try {
if (!embedder) {
result.skipped = 'no_real_embedder';
return result;
}
const raw = db.getDatabase();
const activeFrameCount = (raw.prepare(
"SELECT COUNT(*) AS n FROM memory_frames WHERE importance != 'deprecated'",
).get() as { n: number }).n;
if (activeFrameCount === 0) {
result.skipped = 'empty_mind';
return result;
}
const preparationProblem = await prepareProvider(embedder);
if (preparationProblem) {
result.skipped = embedder.getActiveProvider() === 'mock'
? 'no_real_embedder'
: 'provider_degraded';
if (result.skipped === 'provider_degraded') result.errors.push(preparationProblem);
return result;
}
const wantedFingerprint = activeFingerprint(embedder);
const storedFingerprint = db.getEmbeddingFingerprint();
if (storedFingerprint?.provider === 'mock') {
// The legacy marker is written only for a known mock-fingerprint rebuild.
db.recreateVecTables(embedder.dimensions);
db.setEmbeddingFingerprint(wantedFingerprint);
raw.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)')
.run(LEGACY_FLAG_KEY, new Date().toISOString());
result.vectorsRepaired = true;
} else if (!storedFingerprint && existingVectorCount(db) > 0) {
// Pre-fingerprint databases may contain a complete-looking index whose
// model provenance is unknowable. Never relabel or mix it: discard only
// the vector tables and refill them incrementally with verified vectors.
db.recreateVecTables(embedder.dimensions);
db.setEmbeddingFingerprint(wantedFingerprint);
result.vectorsRepaired = true;
} else if (
storedFingerprint
&& (
storedFingerprint.dim !== wantedFingerprint.dim
|| storedFingerprint.provider !== wantedFingerprint.provider
|| storedFingerprint.model !== wantedFingerprint.model
)
) {
result.skipped = 'fingerprint_mismatch';
result.errors.push(
`embedding fingerprint mismatch: stored=${storedFingerprint.provider}/${storedFingerprint.model}/` +
`${storedFingerprint.dim}, active=${fingerprintLabel(wantedFingerprint)}`,
);
return result;
}
const cursor = readCursor(db);
let candidates = selectCandidates(db, maxFrames, cursor);
if (candidates.length === 0 && cursor > 0 && hasPendingCandidates(db)) {
candidates = selectCandidates(db, maxFrames, 0);
}
if (candidates.length === 0) {
writeCursor(db, 0);
return result;
}
// Advance even when a deterministic poison frame fails. The next pass
// starts after this bounded window, preventing permanent oldest-first
// starvation while a later wrap still retries failures.
writeCursor(db, candidates[candidates.length - 1].id);
const search = new HybridSearch(db, strictEmbedder(embedder, wantedFingerprint));
const missingWhole = candidates.filter(candidate => candidate.whole_missing === 1);
const chunkOnly = candidates.filter(candidate => candidate.whole_missing === 0);
const recordProviderProblem = (problem: string, frameId?: number): void => {
const prefix = frameId === undefined ? '' : `frame ${frameId}: `;
result.errors.push(`${prefix}${problem}`);
};
const recoverProvider = async (frameId?: number): Promise<boolean> => {
const problem = await prepareProvider(embedder, wantedFingerprint);
if (!problem) return true;
recordProviderProblem(problem, frameId);
return false;
};
const repairChunks = async (frame: RepairCandidate): Promise<void> => {
if (!frameNeedsChunkRepair(db, frame)) return;
if (!await recoverProvider(frame.id)) return;
const before = chunkVectorCountForFrames(db, [frame.id]);
try {
await search.indexChunksForFrame(frame.id, frame.content);
const after = chunkVectorCountForFrames(db, [frame.id]);
result.chunksCreated += Math.max(0, after - before);
} catch (err) {
recordProviderProblem(err instanceof Error ? err.message : String(err), frame.id);
}
};
const repairSingleWhole = async (frame: RepairCandidate): Promise<void> => {
if (!await recoverProvider(frame.id)) return;
const chunksBefore = chunkVectorCountForFrames(db, [frame.id]);
try {
await search.indexFramesBatch([frame]);
} catch (err) {
recordProviderProblem(err instanceof Error ? err.message : String(err), frame.id);
return;
}
if (!hasWholeVector(db, frame.id)) return;
result.framesReembedded += 1;
result.framesProcessed += 1;
const chunksAfter = chunkVectorCountForFrames(db, [frame.id]);
result.chunksCreated += Math.max(0, chunksAfter - chunksBefore);
const postProblem = providerProblem(embedder, wantedFingerprint);
if (postProblem) recordProviderProblem(postProblem, frame.id);
await repairChunks(frame);
};
for (let offset = 0; offset < missingWhole.length; offset += batchSize) {
const batch = missingWhole.slice(offset, offset + batchSize);
if (!await recoverProvider()) break;
const ids = batch.map(frame => frame.id);
const chunksBefore = chunkVectorCountForFrames(db, ids);
try {
await search.indexFramesBatch(batch);
} catch (err) {
recordProviderProblem(err instanceof Error ? err.message : String(err));
// A failed provider batch is atomic for whole vectors. Retry its
// members independently so one poison input cannot block valid peers.
for (const frame of batch) await repairSingleWhole(frame);
continue;
}
result.framesReembedded += batch.length;
result.framesProcessed += batch.length;
const chunksAfter = chunkVectorCountForFrames(db, ids);
result.chunksCreated += Math.max(0, chunksAfter - chunksBefore);
const postProblem = providerProblem(embedder, wantedFingerprint);
if (postProblem) recordProviderProblem(postProblem);
for (const frame of batch) await repairChunks(frame);
}
for (const frame of chunkOnly) {
if (!await recoverProvider(frame.id)) continue;
const chunksBefore = chunkVectorCountForFrames(db, [frame.id]);
try {
await search.indexChunksForFrame(frame.id, frame.content);
result.framesProcessed += 1;
const chunksAfter = chunkVectorCountForFrames(db, [frame.id]);
result.chunksCreated += Math.max(0, chunksAfter - chunksBefore);
} catch (err) {
recordProviderProblem(err instanceof Error ? err.message : String(err), frame.id);
}
}
result.hasMore = hasPendingCandidates(db);
if (!result.hasMore) writeCursor(db, 0);
return result;
} catch (err) {
result.errors.push(err instanceof Error ? err.message : String(err));
result.hasMore = true;
return result;
}
}

View File

@@ -2,16 +2,16 @@
* WorkspaceSessionManager — manages concurrent workspace sessions.
*
* Replaces the single activeWorkspaceId model with a Map<workspaceId, WorkspaceSession>.
* Each session holds its own mind (MindDB), tools, **orchestrator**, abort controller,
* and persona. The per-session orchestrator is critical — it prevents two concurrent
* chat calls on different workspaces from overwriting each other's workspace mind
* state (the "Option Y" fix from docs/plans/phase-a-the-room.md §9).
* Each session holds its own tools, **orchestrator**, abort controller and persona.
* The per-session orchestrator is critical — it prevents two concurrent chat calls
* on different workspaces from overwriting each other's active workspace (the
* "Option Y" fix from docs/plans/phase-a-the-room.md §9). Memory itself is one
* shared store; a session only selects its workspace's scope.
*
* Max concurrent sessions configurable (default: 3) to prevent resource exhaustion.
* The sidecar starts the manager with MAX_WORKSPACE_SESSIONS.
*/
import type { MindDB } from '@waggle/core';
import type { ToolDefinition, Orchestrator } from '@waggle/agent';
/** Concurrent workspace sessions the sidecar allows. */
@@ -19,11 +19,10 @@ export const MAX_WORKSPACE_SESSIONS = 100;
export interface WorkspaceSession {
workspaceId: string;
mind: MindDB;
/**
* Session-owned orchestrator with this workspace's mind already mounted.
* Each session has its own instance so concurrent sessions cannot corrupt
* each other's workspace layers via orchestrator.setWorkspaceMind().
* Session-owned orchestrator with this workspace already selected.
* Each session has its own instance so concurrent sessions cannot switch
* each other's workspace via orchestrator.setWorkspace().
*/
orchestrator: Orchestrator;
tools: ToolDefinition[];
@@ -33,14 +32,6 @@ export interface WorkspaceSession {
status: 'active' | 'paused' | 'error';
/** L-17 C3: cumulative LLM tokens (prompt + completion) for this session. */
tokensUsed: number;
/**
* Optional pin-release callback. When a session borrows its mind from the
* shared MultiMindCache via `acquire()`, the cache owns the handle's lifecycle
* and the session must NOT close it. Instead `close()` calls this to drop the
* refcount pin. Absent for standalone/test sessions that own their own handle
* — those fall back to `mind.close()`.
*/
release?: () => void;
}
export class WorkspaceSessionManager {
@@ -97,15 +88,13 @@ export class WorkspaceSessionManager {
* Throws if max concurrent sessions reached or if a session already exists.
*
* The caller is responsible for constructing the orchestrator with this
* session's workspace mind already mounted via `setWorkspaceMind()`.
* session's workspace already selected via `setWorkspace()`.
*/
create(
workspaceId: string,
mind: MindDB,
orchestrator: Orchestrator,
tools: ToolDefinition[],
personaId?: string,
release?: () => void,
): WorkspaceSession {
if (this.sessions.has(workspaceId)) {
throw new Error(`Session already exists for workspace ${workspaceId}`);
@@ -116,7 +105,6 @@ export class WorkspaceSessionManager {
const session: WorkspaceSession = {
workspaceId,
mind,
orchestrator,
tools,
abortController: new AbortController(),
@@ -124,7 +112,6 @@ export class WorkspaceSessionManager {
personaId: personaId ?? null,
status: 'active',
tokensUsed: 0,
release,
};
this.sessions.set(workspaceId, session);
return session;
@@ -145,39 +132,22 @@ export class WorkspaceSessionManager {
/**
* Get an existing session or create a new one.
* Uses factories to lazily construct mind, orchestrator, and tools only when needed.
*
* The orchestrator factory receives the freshly-opened mind so it can
* call `orchestrator.setWorkspaceMind(mind)` before returning.
* Uses factories to construct the orchestrator and tools only when needed.
*/
getOrCreate(
workspaceId: string,
mindFactory: () => MindDB,
orchestratorFactory: (mind: MindDB) => Orchestrator,
toolsFactory: (mind: MindDB, orchestrator: Orchestrator) => ToolDefinition[],
orchestratorFactory: () => Orchestrator,
toolsFactory: (orchestrator: Orchestrator) => ToolDefinition[],
personaId?: string,
release?: () => void,
): WorkspaceSession {
const existing = this.sessions.get(workspaceId);
if (existing) {
existing.lastActivity = Date.now();
return existing;
}
// `mindFactory` may pin the shared cache handle (session-lifetime refcount).
// If anything downstream throws before the session is registered (e.g. the
// max-sessions cap in create()), roll the pin back via `release` so a failed
// create never leaks a pin and blocks eviction forever.
const mind = mindFactory();
try {
const orchestrator = orchestratorFactory(mind);
const tools = toolsFactory(mind, orchestrator);
return this.create(workspaceId, mind, orchestrator, tools, personaId, release);
} catch (err) {
if (release) {
try { release(); } catch { /* pin already released */ }
}
throw err;
}
const orchestrator = orchestratorFactory();
const tools = toolsFactory(orchestrator);
return this.create(workspaceId, orchestrator, tools, personaId);
}
/** Touch a session to update its activity timestamp */
@@ -208,24 +178,12 @@ export class WorkspaceSessionManager {
return true;
}
/**
* Close and clean up a session.
* Aborts the agent loop and closes the mind DB.
*/
/** Close a session: aborts its agent loop and forgets it. */
close(workspaceId: string): boolean {
const session = this.sessions.get(workspaceId);
if (!session) return false;
session.abortController.abort();
// The MultiMindCache owns the MindDB lifecycle for pinned sessions — drop the
// pin instead of closing the shared handle (closing it would poison other
// borrows of the same workspace mind). Standalone/test sessions that own
// their handle have no `release` and fall back to closing it directly.
if (session.release) {
try { session.release(); } catch { /* pin already released */ }
} else {
try { session.mind.close(); } catch { /* already closed */ }
}
this.sessions.delete(workspaceId);
return true;
}