🌊 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(learning): create skills from validated task patterns
Rudy Celekli53f2275495b2
diff --git a/v3/@claude-flow/cli/__tests__/feedback-cli-patterns-3445.test.ts b/v3/@claude-flow/cli/__tests__/feedback-cli-patterns-3445.test.tsnew file mode 100644index 0000000000..8acffec0e6--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/feedback-cli-patterns-3445.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it, vi } from 'vitest';+const callMCPTool = vi.fn(async () => ({ success: true }));+vi.mock('../src/mcp-client.js', () => ({ callMCPTool, MCPClientError: class extends Error {} }));+const { hooksCommand } = await import('../src/commands/hooks.js');+const command = hooksCommand.subcommands!.find(c => c.name === 'post-task')!;++describe('post-task CLI patterns (#3445)', () => {+ it('declares the patterns option and forwards parsed JSON', async () => {+ expect(command.options?.some(option => option.name === 'patterns')).toBe(true);+ await command.action!({ args: [], flags: { taskId: '3445', patterns: '["validate first"]', format: 'json' } } as any);+ expect(callMCPTool).toHaveBeenCalledWith('hooks_post-task', expect.objectContaining({ patterns: ['validate first'] }));+ });+ it('rejects malformed JSON without calling MCP', async () => {+ callMCPTool.mockClear();+ expect(await command.action!({ args: [], flags: { patterns: '{' } } as any)).toMatchObject({ success: false });+ expect(callMCPTool).not.toHaveBeenCalled();+ });+});diff --git a/v3/@claude-flow/cli/__tests__/feedback-pattern-inputs-3445.test.ts b/v3/@claude-flow/cli/__tests__/feedback-pattern-inputs-3445.test.tsnew file mode 100644index 0000000000..c840470e08--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/feedback-pattern-inputs-3445.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it, vi } from 'vitest';+const feedback = vi.fn(async () => ({ success: true, controller: 'test', updated: 1 }));+vi.mock('../src/memory/memory-bridge.js', () => ({ bridgeRecordFeedback: feedback, bridgeRecordCausalEdge: vi.fn(), bridgeStoreEntry: vi.fn() }));+vi.mock('../src/memory/intelligence.js', () => ({ recordTrajectory: vi.fn(async () => false) }));+vi.mock('../src/memory/graph-edge-writer.js', () => ({ insertGraphEdge: vi.fn() }));+const { hooksPostTask } = await import('../src/mcp-tools/hooks-tools.js');+const { agentdbFeedback } = await import('../src/mcp-tools/agentdb-tools.js');++describe('feedback pattern inputs (#3445)', () => {+ for (const tool of [hooksPostTask, agentdbFeedback]) {+ it(`${tool.name} advertises and forwards learned patterns`, async () => {+ expect(tool.inputSchema.properties?.patterns).toMatchObject({ type: 'array', items: { type: 'string' } });+ feedback.mockClear();+ await tool.handler({ taskId: 'task-3445', success: true, quality: 0.95, patterns: ['validate first'] });+ expect(feedback).toHaveBeenCalledWith(expect.objectContaining({ patterns: ['validate first'] }));+ });+ it.each([{ patterns: 'bad' }, { patterns: [42] }, { patterns: [' '] }, { patterns: ['x'.repeat(10001)] }])(`${tool.name} rejects malformed patterns before feedback`, async ({ patterns }) => {+ feedback.mockClear();+ expect(await tool.handler({ taskId: 'task-3445', patterns })).toMatchObject({ success: false });+ expect(feedback).not.toHaveBeenCalled();+ });+ }+});diff --git a/v3/@claude-flow/cli/__tests__/feedback-skill-promotion-3445.test.ts b/v3/@claude-flow/cli/__tests__/feedback-skill-promotion-3445.test.tsnew file mode 100644index 0000000000..af997611d8--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/feedback-skill-promotion-3445.test.ts@@ -0,0 +1,34 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+vi.mock('../src/memory/intelligence.js', () => ({ recordTrajectory: vi.fn(async () => false) }));+import { __setMemoryBridgeRegistryForTests, bridgeRecordFeedback } from '../src/memory/memory-bridge.js';++const createSkill = vi.fn(async () => 1);+beforeEach(() => {+ createSkill.mockClear();+ __setMemoryBridgeRegistryForTests({ getAgentDB: () => null, get: (name: string) => name === 'skills' ? { createSkill } : null });+});+afterEach(() => __setMemoryBridgeRegistryForTests(null));+const feedback = { taskId: 'task-3445', success: true, quality: 0.95, agent: 'coder', patterns: ['Validate input before storing it'] };++describe('feedback skill promotion (#3445)', () => {+ it('creates a SkillLibrary skill with the observed reward and full pattern', async () => {+ const result = await bridgeRecordFeedback(feedback);+ expect(createSkill).toHaveBeenCalledWith(expect.objectContaining({+ description: feedback.patterns[0], successRate: 1, avgReward: 0.95,+ metadata: expect.objectContaining({ taskId: feedback.taskId, agent: 'coder' }),+ }));+ expect(result?.controller).toContain('skills');+ expect(result?.updated).toBe(1);+ });+ it.each([{ success: false, quality: 0.95 }, { success: true, quality: 0.89 }])('does not promote ineligible outcomes %j', async (outcome) => {+ await bridgeRecordFeedback({ ...feedback, ...outcome });+ expect(createSkill).not.toHaveBeenCalled();+ });+ it('does not claim skill updates when the controller rejects a write', async () => {+ createSkill.mockRejectedValueOnce(new Error('write failed'));+ const result = await bridgeRecordFeedback(feedback);+ expect(createSkill).toHaveBeenCalledOnce();+ expect(result?.controller).not.toContain('skills');+ expect(result?.updated).toBe(0);+ });+});diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.tsindex a9585659f0..64b9d53fd8 100644--- a/v3/@claude-flow/cli/src/commands/hooks.ts+++ b/v3/@claude-flow/cli/src/commands/hooks.ts@@ -1,3 +1,4 @@+import { validateFeedbackPatterns } from '../memory/feedback-patterns.js';/*** V3 CLI Hooks Command* Self-learning hooks system for intelligent workflow automation@@ -2095,6 +2096,7 @@ const postTaskCommand: Command = {name: 'post-task',description: 'Record task completion for learning',options: [+ { name: 'patterns', description: 'JSON array of learned pattern strings for feedback and skill creation', type: 'string' },{name: 'task-id',short: 'i',@@ -2182,6 +2184,7 @@ const postTaskCommand: Command = {output.printInfo(`Recording outcome for task: ${output.highlight(taskId)}`);try {+ const patterns = validateFeedbackPatterns(ctx.flags.patterns === undefined ? undefined : JSON.parse(ctx.flags.patterns as string));const result = await callMCPTool<{taskId: string;success: boolean;@@ -2196,6 +2199,7 @@ const postTaskCommand: Command = {trajectory?: { recorded: boolean };}>('hooks_post-task', {taskId,+ patterns,success,quality: ctx.flags.quality,agent: ctx.flags.agent,diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.tsindex c421b5674a..f30085e96a 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts@@ -1,3 +1,4 @@+import { feedbackPatternsSchema, validateFeedbackPatterns } from '../memory/feedback-patterns.js';/*** AgentDB MCP Tools — Phase 6 of ADR-053*@@ -389,6 +390,7 @@ export const agentdbFeedback: MCPTool = {type: 'object',properties: {taskId: { type: 'string', description: 'Task identifier' },+ patterns: feedbackPatternsSchema,success: { type: 'boolean', description: 'Whether task succeeded' },quality: { type: 'number', description: 'Quality score (0-1)' },agent: { type: 'string', description: 'Agent that performed the task' },@@ -402,9 +404,11 @@ export const agentdbFeedback: MCPTool = {if (params.agent) { const vAgent = validateIdentifier(params.agent, 'agent'); if (!vAgent.valid) return { success: false, error: vAgent.error }; }const taskId = validateString(params.taskId, 'taskId', 500);if (!taskId) return { success: false, error: 'taskId is required (non-empty string, max 500 chars)' };+ const patterns = validateFeedbackPatterns(params.patterns);const bridge = await getBridge();const result = await bridge.bridgeRecordFeedback({taskId,+ patterns,success: params.success === true,quality: validateScore(params.quality, 0.85),agent: validateString(params.agent, 'agent', 200) ?? undefined,diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.tsindex 32cf57dbc4..f76574a017 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts@@ -1,3 +1,4 @@+import { feedbackPatternsSchema, validateFeedbackPatterns } from '../memory/feedback-patterns.js';/*** Hooks MCP Tools* Provides intelligent hooks functionality via MCP protocol@@ -1654,6 +1655,7 @@ export const hooksPostTask: MCPTool = {type: 'object',properties: {taskId: { type: 'string', description: 'Task identifier' },+ patterns: feedbackPatternsSchema,success: { type: 'boolean', description: 'Whether task was successful' },agent: { type: 'string', description: 'Agent that completed the task' },quality: { type: 'number', description: 'Quality score (0-1)' },@@ -1675,6 +1677,9 @@ export const hooksPostTask: MCPTool = {const agent = params.agent as string | undefined;const quality = (params.quality as number) || (success ? 0.85 : 0.3);const startTime = Date.now();+ let patterns: string[] | undefined;+ try { patterns = validateFeedbackPatterns(params.patterns); }+ catch (error) { return { success: false, error: (error as Error).message }; }{ const v = validateIdentifier(taskId, 'taskId'); if (!v.valid) return { success: false, error: v.error }; }if (agent) { const v = validateIdentifier(agent, 'agent'); if (!v.valid) return { success: false, error: v.error }; }@@ -1706,7 +1711,7 @@ export const hooksPostTask: MCPTool = {quality,agent,duration: (params.duration as number) || undefined,- patterns: (params.patterns as string[]) || undefined,+ patterns,// ADR-147 P2: forward spawn-tree lineage so it lands in feedback + memoryparentAgentId,depth,diff --git a/v3/@claude-flow/cli/src/memory/feedback-patterns.ts b/v3/@claude-flow/cli/src/memory/feedback-patterns.tsnew file mode 100644index 0000000000..6c548df81f--- /dev/null+++ b/v3/@claude-flow/cli/src/memory/feedback-patterns.ts@@ -0,0 +1,15 @@+/** Shared input contract for learned patterns supplied by feedback callers. */+export const feedbackPatternsSchema = {+ type: 'array', items: { type: 'string', minLength: 1, maxLength: 10_000 }, maxItems: 100,+ description: 'Learned patterns to retain; successful tasks with quality >= 0.9 may create reusable skills',+};++export function validateFeedbackPatterns(value: unknown): string[] | undefined {+ if (value === undefined) return undefined;+ if (!Array.isArray(value) || value.length > 100 || value.some(+ item => typeof item !== 'string' || !item.trim() || item.length > 10_000,+ )) {+ throw new Error('patterns must be an array of at most 100 non-empty strings (maximum 10000 characters each)');+ }+ return value;+}diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.tsindex 9935b51e35..52d50e096d 100644--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts@@ -20,6 +20,7 @@import * as path from 'path';import * as crypto from 'crypto';import { createRequire } from 'node:module';+import { validateFeedbackPatterns } from './feedback-patterns.js';// ===== Lazy registry cache, keyed by database path =====@@ -293,11 +294,13 @@ async function getRegistry(dbPath?: string): Promise<any | null> {try { agentdb = (await import('agentdb')) as unknown as Record<string, unknown>; }catch { return; /* AgentDB not available */ }- // SkillLibrary (no db required)+ // SkillLibrary requires the same database and passage embedder as AgentDB.try {- const SkillCtor = agentdb.SkillLibrary as (new () => unknown) | undefined;- if (SkillCtor && !reg.get('skills')) {- const sk = new SkillCtor();+ const SkillCtor = agentdb.SkillLibrary as (new (db: unknown, embedder: unknown) => unknown) | undefined;+ const backing = reg.getAgentDB?.();+ if (SkillCtor && !reg.get('skills') && backing?.database+ && typeof backing.embedder?.embedPassage === 'function') {+ const sk = new SkillCtor(backing.database, backing.embedder);if (typeof reg.set === 'function') reg.set('skills', sk);else reg._controllers = { ...(reg._controllers || {}), skills: sk };}@@ -2418,6 +2421,7 @@ export async function bridgeRecordFeedback(options: {parentAgentId?: string;depth?: number;}): Promise<{ success: boolean; controller: string; updated: number } | null> {+ const patterns = validateFeedbackPatterns(options.patterns);const registry = await getRegistry(options.dbPath);if (!registry) return null;@@ -2474,8 +2478,8 @@ export async function bridgeRecordFeedback(options: {// add them to LocalReasoningBank via its real `.store()` method (the// one method that DOES exist on the class).const reasoningBank = registry.get('reasoningBank');- if (reasoningBank && Array.isArray(options.patterns) && options.patterns.length) {- for (const pattern of options.patterns) {+ if (reasoningBank && Array.isArray(patterns) && patterns.length) {+ for (const pattern of patterns) {try {if (typeof reasoningBank.store === 'function') {reasoningBank.store({@@ -2493,14 +2497,27 @@ export async function bridgeRecordFeedback(options: {else if (updated > 0 && controller === 'none') controller = 'reasoningBank';}- // Phase 4: SkillLibrary promotion for high-quality patterns- if (options.success && options.quality >= 0.9 && options.patterns?.length) {+ // SkillLibrary's public API is createSkill(Skill), not promote().+ if (options.success && options.quality >= 0.9 && patterns?.length) {const skills = registry.get('skills');- if (skills && typeof skills.promote === 'function') {- for (const pattern of options.patterns) {- try { await skills.promote(pattern, options.quality); updated++; } catch { /* skip */ }+ let created = 0;+ if (skills && typeof skills.createSkill === 'function') {+ for (const [index, pattern] of patterns.entries()) {+ try {+ await skills.createSkill({+ name: `feedback-${options.taskId}-${index}`,+ description: pattern,+ successRate: 1,+ uses: 1,+ avgReward: options.quality,+ avgLatencyMs: options.duration,+ metadata: { taskId: options.taskId, task: options.task, agent: options.agent, source: 'bridge-feedback' },+ });+ updated++;+ created++;+ } catch { /* failed promotion must not count as an update */ }}- controller += '+skills';+ if (created > 0) controller = controller === 'none' ? 'skills' : `${controller}+skills`;}}