🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(memory): pass validated episodes to context synthesis
Rudy Celekli5ae82e69b5d6
diff --git a/v3/@claude-flow/cli/__tests__/context-synthesis-3314.test.ts b/v3/@claude-flow/cli/__tests__/context-synthesis-3314.test.tsnew file mode 100644index 0000000000..cc3f1b34f3--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/context-synthesis-3314.test.ts@@ -0,0 +1,118 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ __setMemoryBridgeRegistryForTests,+ bridgeContextSynthesize,+} from '../src/memory/memory-bridge.js';++const originalDisable = process.env.CLAUDE_FLOW_DISABLE_BRIDGE;+const originalWindowsOptIn = process.env.CLAUDE_FLOW_ENABLE_NATIVE_BRIDGE_ON_WINDOWS;++beforeEach(() => {+ delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;+ process.env.CLAUDE_FLOW_ENABLE_NATIVE_BRIDGE_ON_WINDOWS = '1';+});++afterEach(() => {+ __setMemoryBridgeRegistryForTests(null);+ if (originalDisable === undefined) delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;+ else process.env.CLAUDE_FLOW_DISABLE_BRIDGE = originalDisable;+ if (originalWindowsOptIn === undefined) delete process.env.CLAUDE_FLOW_ENABLE_NATIVE_BRIDGE_ON_WINDOWS;+ else process.env.CLAUDE_FLOW_ENABLE_NATIVE_BRIDGE_ON_WINDOWS = originalWindowsOptIn;+});++function installRegistry(recall: (...args: unknown[]) => unknown, native = false) {+ const synthesize = vi.fn((episodes: unknown[]) => ({ episodes }));+ const hierarchical = { recall, ...(native ? { promote: () => {} } : {}) };+ __setMemoryBridgeRegistryForTests({+ get: (name: string) => name === 'contextSynthesizer'+ ? { synthesize }+ : name === 'hierarchicalMemory' ? hierarchical : null,+ });+ return synthesize;+}++describe('#3314 context synthesis input contract', () => {+ it('passes only validated episodes from async tiered recall, preserving failure and zero reward', async () => {+ const recall = vi.fn(async () => [+ { key: 'success', value: JSON.stringify({ task: 'Fix auth', reward: 0.8, success: true, critique: 'Use PKCE for auth' }) },+ { key: 'failure', value: JSON.stringify({ task: 'Fix auth', reward: 0, success: false, critique: 'Use PKCE for auth' }) },+ { key: 'fact', value: 'OAuth is an authorization protocol' },+ ]);+ const synthesize = installRegistry(recall);++ const result = await bridgeContextSynthesize({ query: 'auth', maxEntries: 3 });++ expect(recall).toHaveBeenCalledWith('auth', 3);+ expect(synthesize).toHaveBeenCalledWith([+ { task: 'Fix auth', reward: 0.8, success: true, critique: 'Use PKCE for auth' },+ { task: 'Fix auth', reward: 0, success: false, critique: 'Use PKCE for auth' },+ ], { includeRecommendations: true });+ expect(result).toMatchObject({ success: true, recalled: 3, eligible: 2, skipped: 1 });+ });++ it('uses the native query-object recall contract and accepts explicitly structured metadata', async () => {+ const recall = vi.fn(async () => [+ { id: 'episode', metadata: { task: 'Repair cache', reward: 0.25, success: false, input: 'stale value', output: 'cache bypass' } },+ ]);+ const synthesize = installRegistry(recall, true);++ const result = await bridgeContextSynthesize({ query: 'cache', maxEntries: 5 });++ expect(recall).toHaveBeenCalledWith({ query: 'cache', k: 5 });+ expect(synthesize.mock.calls[0][0]).toEqual([+ { task: 'Repair cache', reward: 0.25, success: false, input: 'stale value', output: 'cache bypass' },+ ]);+ expect(result).toMatchObject({ success: true, recalled: 1, eligible: 1, skipped: 0 });+ });++ it('never treats prose, malformed JSON, inherited data, or wrong-typed outcomes as episodes', async () => {+ const inherited = Object.create({ task: 'Inherited task', reward: 1, success: true });+ inherited.key = 'inherited';+ const synthesize = installRegistry(() => [+ { key: 'fact', value: 'A plain factual memory' },+ { key: 'malformed', value: '{"task":' },+ { key: 'reward-string', value: '{"task":"t","reward":"1","success":true}' },+ { key: 'success-string', value: '{"task":"t","reward":0.5,"success":"true"}' },+ { key: 'bad-critique', value: '{"task":"t","reward":0.5,"success":true,"critique":[]}' },+ inherited,+ ]);++ const result = await bridgeContextSynthesize({ query: 'anything' });++ expect(synthesize).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ success: false, reason: 'no-eligible-episodes', recalled: 6, eligible: 0, skipped: 6,+ });+ });++ it('distinguishes no recalled memories from ineligible recalled facts', async () => {+ const synthesize = installRegistry(async () => []);++ const result = await bridgeContextSynthesize({ query: 'missing' });++ expect(synthesize).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ success: false, reason: 'no-memories', recalled: 0, eligible: 0, skipped: 0,+ });+ });++ it('reports controller failure after counting eligible and skipped rows', async () => {+ __setMemoryBridgeRegistryForTests({+ get: (name: string) => name === 'contextSynthesizer'+ ? { synthesize: () => { throw new Error('controller failed'); } }+ : name === 'hierarchicalMemory'+ ? { recall: () => [+ { value: '{"task":"t","reward":0.4,"success":false}' },+ { value: 'fact' },+ ] }+ : null,+ });++ const result = await bridgeContextSynthesize({ query: 't' });++ expect(result).toMatchObject({+ success: false, reason: 'synthesizer-failed', error: 'controller failed',+ recalled: 2, eligible: 1, skipped: 1,+ });+ });+});diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.tsindex 948ef83b11..4e0315b61a 100644--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts@@ -3280,37 +3280,99 @@ export async function bridgeBatchOperation(params: { operation: string; entries:* Synthesize context from memories.* ContextSynthesizer.synthesize is a static method that takes MemoryPattern[] (not a string).*/+type ContextEpisode = {+ task: string;+ reward: number;+ success: boolean;+ critique?: string;+ input?: string;+ output?: string;+};++function contextEpisodeFrom(value: unknown): ContextEpisode | null {+ if (typeof value === 'string') {+ try { value = JSON.parse(value); }+ catch { return null; }+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;++ const record = value as Record<string, unknown>;+ const owns = (key: string) => Object.prototype.hasOwnProperty.call(record, key);+ if (!owns('task') || !owns('reward') || !owns('success')+ || typeof record.task !== 'string' || !record.task.trim()+ || typeof record.reward !== 'number' || !Number.isFinite(record.reward)+ || typeof record.success !== 'boolean') return null;++ const episode: ContextEpisode = {+ task: record.task.trim(),+ reward: record.reward,+ success: record.success,+ };+ for (const field of ['critique', 'input', 'output'] as const) {+ if (owns(field)) {+ if (typeof record[field] !== 'string') return null;+ episode[field] = record[field];+ }+ }+ return episode;+}++function contextEpisodeFromRecall(row: unknown): ContextEpisode | null {+ if (!row || typeof row !== 'object' || Array.isArray(row)) return null;+ const record = row as Record<string, unknown>;+ for (const field of [null, 'metadata', 'value', 'content'] as const) {+ const candidate = field === null ? record+ : Object.prototype.hasOwnProperty.call(record, field) ? record[field] : undefined;+ const episode = contextEpisodeFrom(candidate);+ if (episode) return episode;+ }+ return null;+}+export async function bridgeContextSynthesize(params: { query: string; maxEntries?: number }): Promise<any> {const registry = await getRegistry();if (!registry) return null;try {const CS = registry.get('contextSynthesizer');if (!CS || typeof CS.synthesize !== 'function') {- return { success: false, error: 'ContextSynthesizer not available' };+ return { success: false, reason: 'synthesizer-unavailable', error: 'ContextSynthesizer not available' };}- // Gather memory patterns from hierarchical memory as inputconst hm = registry.get('hierarchicalMemory');- let memories: any[] = [];- if (hm && typeof hm.recall === 'function') {- // Detect real HierarchicalMemory (MemoryQuery object) vs stub (string, number)- let recalled: any[];- if (typeof hm.promote === 'function') {- // Real agentdb HierarchicalMemory- recalled = await hm.recall({ query: params.query, k: params.maxEntries || 10 });- } else {- // Stub- recalled = hm.recall(params.query, params.maxEntries || 10);+ if (!hm || typeof hm.recall !== 'function') {+ return { success: false, reason: 'memory-unavailable', error: 'HierarchicalMemory not available' };+ }+ let recalled: unknown;+ try {+ // Native HierarchicalMemory accepts a query object; the tiered fallback+ // accepts positional arguments. Either implementation may be async.+ recalled = typeof hm.promote === 'function'+ ? await hm.recall({ query: params.query, k: params.maxEntries || 10 })+ : await hm.recall(params.query, params.maxEntries || 10);+ } catch (e: any) {+ return { success: false, reason: 'recall-failed', error: e.message };+ }+ if (!Array.isArray(recalled)) {+ return { success: false, reason: 'invalid-recall-result', error: 'HierarchicalMemory recall did not return an array' };+ }+ const recalledCount = recalled.length;+ if (recalledCount === 0) {+ return { success: false, reason: 'no-memories', error: 'No memories matched the query', recalled: 0, eligible: 0, skipped: 0 };+ }+ const memories = recalled.map(contextEpisodeFromRecall).filter((episode): episode is ContextEpisode => episode !== null);+ const counts = { recalled: recalledCount, eligible: memories.length, skipped: recalledCount - memories.length };+ if (memories.length === 0) {+ return { success: false, reason: 'no-eligible-episodes', error: 'Recalled memories have no validated task outcomes', ...counts };+ }+ try {+ const result = await CS.synthesize(memories, { includeRecommendations: true });+ if (!result || typeof result !== 'object') {+ return { success: false, reason: 'invalid-synthesis', error: 'ContextSynthesizer returned no result', ...counts };}- memories = (recalled || []).map((r: any) => ({- content: r.value || r.content || '',- key: r.key || r.id || '',- reward: 1,- verdict: 'success',- }));- }- const result = CS.synthesize(memories, { includeRecommendations: true });- return { success: true, synthesis: result };- } catch (e: any) { return { success: false, error: e.message }; }+ return { success: true, synthesis: result, ...counts };+ } catch (e: any) {+ return { success: false, reason: 'synthesizer-failed', error: e.message, ...counts };+ }+ } catch (e: any) { return { success: false, reason: 'bridge-error', error: e.message }; }}/**