fix(server): keep late memory refs from completing a collaboration Room (P1.5)

Chat collaboration writes run results to memory in the background and
records the memory refs when the writes finish. That update recomputed the
parent Room, so a workflow Room turned 'completed' while its synthesis step
was still running and could no longer be cancelled. A memory-refs update
never changes a run's status, so it no longer recomputes the parent.

The collaboration tests use an in-memory memory store and wait for the
background writes before reading memory refs.
This commit is contained in:
shumeiko.it
2026-10-24 12:50:23 +02:00
parent f310333970
commit 74a4e55be0
2 changed files with 51 additions and 38 deletions

View File

@@ -812,7 +812,9 @@ function recordResult(
metadata,
}).then((memoryRefs) => {
try {
server.agentRunRegistry.update(run.id, { memoryRefs });
// Memory refs never change a run's status, so a late write must not
// recompute the Room: that would complete it while synthesis still runs.
server.agentRunRegistry.update(run.id, { memoryRefs }, { recomputeParent: false });
} catch { /* the run was removed meanwhile */ }
});
}

View File

@@ -4,7 +4,13 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { EventEmitter } from 'node:events';
import { MindDB } from '@waggle/core';
import {
createInMemoryMemoryStore,
PERSONAL_SCOPE,
workspaceScope,
type MemoryScope,
type MemoryStore,
} from '@waggle/memory-contract';
import {
createCronTools,
HookRegistry,
@@ -20,8 +26,6 @@ import { WorkspaceTurnCoordinator } from '../../src/local/workspace-turn-coordin
const resources: Array<{
dir: string;
personal: MindDB;
workspace: MindDB;
registry: AgentRunRegistry;
server: FastifyInstance;
}> = [];
@@ -50,10 +54,17 @@ async function waitFor(predicate: () => boolean, message: string): Promise<void>
throw new Error(message);
}
/** What a scope's memories hold: text and metadata, oldest first. */
async function memoryContents(memory: MemoryStore, scope: MemoryScope): Promise<unknown[]> {
const records = await memory.list({ scopes: [scope], limit: 500 });
return records.reverse().map((record) => ({ text: record.text, metadata: record.metadata }));
}
function setup() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-chat-collaboration-'));
const personal = new MindDB(path.join(dir, 'personal.mind'));
const workspace = new MindDB(path.join(dir, 'workspace.mind'));
const memory = createInMemoryMemoryStore();
const personal = { contents: () => memoryContents(memory, PERSONAL_SCOPE) };
const workspace = { contents: () => memoryContents(memory, workspaceScope('workspace-a')) };
const registry = new AgentRunRegistry(path.join(dir, 'agent-runs.json'));
const signalBus = new SignalBus();
const eventBus = new EventEmitter();
@@ -66,21 +77,14 @@ function setup() {
server.decorate('agentRunRegistry', registry);
server.decorate('signalBus', signalBus);
server.decorate('eventBus', eventBus);
server.decorate('multiMind', { personal } as never);
server.decorate('mindCache', {
acquire: (workspaceId: string) => {
if (workspaceId !== 'workspace-a') throw new Error(`wrong workspace: ${workspaceId}`);
return workspace;
},
release: () => undefined,
} as never);
server.decorate('memory', memory);
server.decorate('agentState', {
litellmApiKey: 'test-key',
skills: [],
// Deliberately wrong. The request-bound bridge must never consult it.
activeWorkspaceId: 'workspace-wrong',
} as never);
resources.push({ dir, personal, workspace, registry, server });
resources.push({ dir, registry, server });
return { dir, personal, workspace, registry, signalBus, statusEvents, server };
}
@@ -128,8 +132,6 @@ afterEach(async () => {
for (const resource of resources.splice(0)) {
try { await resource.server.close(); } catch { /* not listening */ }
resource.registry.close();
resource.workspace.close();
resource.personal.close();
fs.rmSync(resource.dir, { recursive: true, force: true });
}
});
@@ -152,6 +154,12 @@ describe('request-bound chat collaboration', () => {
const output = await spawn.execute({
name: 'Release researcher', role: 'researcher', task: 'Inspect the release evidence',
});
// The result is written to memory in the background.
await waitFor(
() => registry.list({ source: 'chat_subagent', workspaceId: 'workspace-a' })
.some((run) => run.kind === 'worker' && run.memoryRefs.status === 'complete'),
'worker memory was not written',
);
const worker = registry.list({ source: 'chat_subagent', workspaceId: 'workspace-a' })
.find((run) => run.kind === 'worker')!;
const room = registry.get(worker.roomId)!;
@@ -419,18 +427,16 @@ describe('request-bound chat collaboration', () => {
.find((run) => run.kind === 'worker')!;
expect(output).toContain(safeOutput);
expect(worker.result?.summary).toBe(safeOutput);
await waitFor(
() => registry.get(worker.id)?.memoryRefs.status === 'complete',
'worker memory was not written',
);
const registryProjection = fs.readFileSync(path.join(dir, 'agent-runs.json'), 'utf-8');
const danceProjection = JSON.stringify(signalBus.query({ teamId: `room::${worker.roomId}` }));
const statusProjection = JSON.stringify(statusEvents);
const personalProjection = JSON.stringify({
frames: personal.getDatabase().prepare('SELECT content FROM memory_frames ORDER BY id').all(),
fts: personal.getDatabase().prepare('SELECT content FROM memory_frames_fts ORDER BY rowid').all(),
});
const workspaceProjection = JSON.stringify({
frames: workspace.getDatabase().prepare('SELECT content FROM memory_frames ORDER BY id').all(),
fts: workspace.getDatabase().prepare('SELECT content FROM memory_frames_fts ORDER BY rowid').all(),
});
const personalProjection = JSON.stringify(await personal.contents());
const workspaceProjection = JSON.stringify(await workspace.contents());
const projections = [
registryProjection,
danceProjection,
@@ -476,14 +482,16 @@ describe('request-bound chat collaboration', () => {
},
});
expect(output).toContain(safeOutput);
await waitFor(
() => registry.list({ source: 'workflow', workspaceId: 'workspace-a' })
.every((run) => run.memoryRefs.status === 'complete'),
'workflow memory was not written',
);
const registryProjection = fs.readFileSync(path.join(dir, 'agent-runs.json'), 'utf-8');
const danceProjection = JSON.stringify(signalBus.query());
const statusProjection = JSON.stringify(statusEvents);
const workspaceProjection = JSON.stringify({
frames: workspace.getDatabase().prepare('SELECT content FROM memory_frames ORDER BY id').all(),
fts: workspace.getDatabase().prepare('SELECT content FROM memory_frames_fts ORDER BY rowid').all(),
});
const workspaceProjection = JSON.stringify(await workspace.contents());
for (const projection of [registryProjection, danceProjection, statusProjection, workspaceProjection]) {
expect(projection).not.toContain(encodedTask);
expect(projection).not.toContain(decodedTask);
@@ -769,6 +777,10 @@ describe('request-bound chat collaboration', () => {
const worker = registry.list({ source: 'chat_subagent', workspaceId: 'workspace-a' })
.find((run) => run.kind === 'worker')!;
expect(worker.status).toBe('completed');
await waitFor(
() => registry.get(worker.id)?.memoryRefs.status === 'complete',
'worker memory was not written',
);
const beforeAbortSeq = registry.snapshot().lastSeq;
parent.abort();
@@ -864,9 +876,7 @@ describe('request-bound chat collaboration', () => {
expect(output).not.toContain('LATE_SUCCESS_SENTINEL');
expect(registry.get(worker.id)?.status).toBe('cancelled');
expect(registry.get(worker.id)?.memoryRefs.status).not.toBe('complete');
const memoryProjection = JSON.stringify(
workspace.getDatabase().prepare('SELECT content FROM memory_frames ORDER BY id').all(),
);
const memoryProjection = JSON.stringify(await workspace.contents());
expect(memoryProjection).not.toContain('LATE_SUCCESS_SENTINEL');
});
@@ -945,9 +955,7 @@ describe('request-bound chat collaboration', () => {
expect(registry.get(completed.id)?.status).toBe('completed');
expect(registry.get(active.id)?.status).toBe('cancelled');
expect(registry.get(room.id)?.memoryRefs.status).not.toBe('complete');
const memoryProjection = JSON.stringify(
workspace.getDatabase().prepare('SELECT content FROM memory_frames ORDER BY id').all(),
);
const memoryProjection = JSON.stringify(await workspace.contents());
expect(memoryProjection).toContain('COMPLETED_WORKER_RESULT');
expect(memoryProjection).not.toContain('ACTIVE_LATE_SUCCESS_SENTINEL');
expect(memoryProjection).not.toContain('[Workflow aggregate result]');
@@ -1083,9 +1091,7 @@ describe('request-bound chat collaboration', () => {
expect(registry.get(worker.id)?.status).toBe('completed');
expect(registry.get(room.id)?.result?.summary).toBeUndefined();
expect(registry.get(room.id)?.memoryRefs.status).not.toBe('complete');
const memoryProjection = JSON.stringify(
workspace.getDatabase().prepare('SELECT content FROM memory_frames ORDER BY id').all(),
);
const memoryProjection = JSON.stringify(await workspace.contents());
expect(memoryProjection).not.toContain('[Workflow aggregate result]');
} finally {
parent.abort();
@@ -1133,6 +1139,11 @@ describe('request-bound chat collaboration', () => {
const output = await pending;
expect(output).toContain('Research result');
expect(output).toContain('Draft result');
await waitFor(
() => registry.list({ source: 'workflow', workspaceId: 'workspace-a' })
.every((run) => run.memoryRefs.status === 'complete'),
'workflow memory was not written',
);
const runs = registry.list({ source: 'workflow', workspaceId: 'workspace-a' });
const room = runs.find((run) => run.kind === 'room')!;