🌊 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(plugins): reuse captured extension points when rebuilding caches (#4451)
ordinary being5988f8e4a00a
diff --git a/v3/@claude-flow/plugins/__tests__/registry-cache-recollection-4410.test.ts b/v3/@claude-flow/plugins/__tests__/registry-cache-recollection-4410.test.tsnew file mode 100644index 0000000000..34a7438057--- /dev/null+++ b/v3/@claude-flow/plugins/__tests__/registry-cache-recollection-4410.test.ts@@ -0,0 +1,140 @@+/**+ * #4410 automation scan: invalidating extension-point caches used to call+ * every initialized plugin's register* methods again. Unregistering one+ * plugin therefore re-ran the remaining plugins' registration code and could+ * duplicate side effects or allocations.+ */+import { describe, expect, it } from 'vitest';+import { PluginRegistry } from '../src/registry/plugin-registry.js';+import { EnhancedPluginRegistry } from '../src/registry/enhanced-plugin-registry.js';+import { BasePlugin } from '../src/core/base-plugin.js';+import type { HookDefinition, MCPToolDefinition, PluginMetadata } from '../src/types/index.js';++class CountingPlugin extends BasePlugin {+ registerCalls = 0;+ hookCalls = 0;++ constructor(metadata: PluginMetadata, private readonly tools: MCPToolDefinition[]) {+ super(metadata);+ }++ protected async onInitialize(): Promise<void> {}++ protected async onShutdown(): Promise<void> {}++ registerMCPTools(): MCPToolDefinition[] {+ this.registerCalls++;+ return this.tools;+ }++ registerHooks(): HookDefinition[] {+ this.hookCalls++;+ return [];+ }+}++function tool(name: string, text: string): MCPToolDefinition {+ return {+ name,+ description: `${name} tool`,+ inputSchema: { type: 'object', properties: {} },+ handler: async () => ({ content: [{ type: 'text', text }] }),+ };+}++function plugin(name: string, tools: MCPToolDefinition[]): CountingPlugin {+ return new CountingPlugin({ name, version: '1.0.0' }, tools);+}++describe('extension cache rebuilds do not re-run plugin registration (#4410)', () => {+ it('PluginRegistry keeps surviving plugins at one registration call', async () => {+ const registry = new PluginRegistry({ coreVersion: '3.0.0', dataDir: '/tmp/test' });+ const a = plugin('plugin-a', [tool('tool-a', 'a')]);+ const b = plugin('plugin-b', [tool('tool-b', 'b')]);++ await registry.register(a);+ await registry.register(b);+ await registry.initialize();++ expect(a.registerCalls).toBe(1);+ expect(b.registerCalls).toBe(1);++ await registry.unregister('plugin-a');++ expect(a.registerCalls).toBe(1);+ expect(b.registerCalls).toBe(1);+ expect(a.hookCalls).toBe(1);+ expect(b.hookCalls).toBe(1);+ expect(registry.getMCPTools().map(t => t.name)).toEqual(['tool-b']);++ await registry.shutdown();+ });++ it('EnhancedPluginRegistry keeps surviving plugins at one registration call', async () => {+ const registry = new EnhancedPluginRegistry({ coreVersion: '3.0.0', dataDir: '/tmp/test' });+ const a = plugin('plugin-a', [tool('tool-a', 'a')]);+ const b = plugin('plugin-b', [tool('tool-b', 'b')]);++ await registry.register(a);+ await registry.register(b);+ await registry.initialize();++ expect(a.registerCalls).toBe(1);+ expect(b.registerCalls).toBe(1);++ await registry.unregister('plugin-a');++ expect(a.registerCalls).toBe(1);+ expect(b.registerCalls).toBe(1);+ expect(a.hookCalls).toBe(1);+ expect(b.hookCalls).toBe(1);+ expect(registry.getMCPTools().map(t => t.name)).toEqual(['tool-b']);++ await registry.shutdown();+ });++ it('EnhancedPluginRegistry replays conflict resolution from captured values', async () => {+ const registry = new EnhancedPluginRegistry({+ coreVersion: '3.0.0',+ dataDir: '/tmp/test',+ conflictResolution: { mcpTools: { strategy: 'first' } },+ });+ const a = plugin('plugin-a', [tool('shared-tool', 'from-a')]);+ const b = plugin('plugin-b', [tool('shared-tool', 'from-b')]);++ await registry.register(a);+ await registry.register(b);+ await registry.initialize();++ expect(registry.getMCPTools()).toHaveLength(1);+ expect(registry.getMCPTools()[0].name).toBe('shared-tool');++ await registry.unregister('plugin-a');++ expect(a.registerCalls).toBe(1);+ expect(b.registerCalls).toBe(1);+ expect(a.hookCalls).toBe(1);+ expect(b.hookCalls).toBe(1);+ expect(registry.getMCPTools()).toHaveLength(1);+ expect(registry.getMCPTools()[0].name).toBe('shared-tool');++ await registry.shutdown();+ });++ it('EnhancedPluginRegistry replaces captured values on hot reload', async () => {+ const registry = new EnhancedPluginRegistry({ coreVersion: '3.0.0', dataDir: '/tmp/test' });+ const original = plugin('plugin-a', [tool('old-tool', 'old')]);++ await registry.register(original);+ await registry.initialize();++ const replacement = plugin('plugin-a', [tool('new-tool', 'new')]);+ await registry.reload('plugin-a', replacement);++ expect(original.registerCalls).toBe(1);+ expect(replacement.registerCalls).toBe(1);+ expect(registry.getMCPTools().map(t => t.name)).toEqual(['new-tool']);++ await registry.shutdown();+ });+});diff --git a/v3/@claude-flow/plugins/src/registry/enhanced-plugin-registry.ts b/v3/@claude-flow/plugins/src/registry/enhanced-plugin-registry.tsindex 396a9882f5..5505ab3a8a 100644--- a/v3/@claude-flow/plugins/src/registry/enhanced-plugin-registry.ts+++ b/v3/@claude-flow/plugins/src/registry/enhanced-plugin-registry.ts@@ -74,6 +74,39 @@ export interface PluginEntry {loadTime: Date;initTime?: Date;error?: string;+ /**+ * Raw extension points returned by the plugin at initialization time.+ *+ * Cache invalidation replays these values through conflict resolution+ * instead of calling the plugin's register* methods again: those methods+ * may have side effects, and plugins may return a new array (or allocate+ * resources) per call.+ */+ extensionPoints?: ExtensionPointCollection;+}++interface ExtensionPointCollection {+ agentTypes: AgentTypeDefinition[];+ taskTypes: TaskTypeDefinition[];+ mcpTools: MCPToolDefinition[];+ cliCommands: CLICommandDefinition[];+ memoryBackends: MemoryBackendFactory[];+ hooks: HookDefinition[];+ workers: WorkerDefinition[];+ providers: LLMProviderDefinition[];+}++function emptyExtensionPointCollection(): ExtensionPointCollection {+ return {+ agentTypes: [],+ taskTypes: [],+ mcpTools: [],+ cliCommands: [],+ memoryBackends: [],+ hooks: [],+ workers: [],+ providers: [],+ };}export interface UnregisterOptions {@@ -503,7 +536,8 @@ export class EnhancedPluginRegistry extends EventEmitter {]);entry.initTime = new Date();- this.collectExtensionPoints(entry.plugin);+ entry.extensionPoints = this.readExtensionPoints(entry.plugin);+ this.applyExtensionPoints(entry.extensionPoints, entry.plugin.metadata.name);}/**@@ -589,7 +623,9 @@ export class EnhancedPluginRegistry extends EventEmitter {entry.initTime = new Date();entry.error = undefined;- // Recollect extension points+ // Replace the captured extension points, then rebuild all caches from+ // captured values rather than re-running any plugin's register methods.+ entry.extensionPoints = this.readExtensionPoints(resolved);this.invalidateCaches();this.logger.info(`Plugin hot reloaded: ${name} -> v${resolved.metadata.version}`);@@ -600,110 +636,128 @@ export class EnhancedPluginRegistry extends EventEmitter {// Extension Points// =========================================================================- private collectExtensionPoints(plugin: IPlugin): void {- const name = plugin.metadata.name;- const resolution = this.config.conflictResolution;+ /**+ * Read a plugin's extension points without resolving conflicts or mutating+ * caches. The raw values are stored on the entry for later rebuilds.+ */+ private readExtensionPoints(plugin: IPlugin): ExtensionPointCollection {+ const points = emptyExtensionPointCollection();- // Collect agent typesif (plugin.registerAgentTypes) {const types = plugin.registerAgentTypes();- if (types) {- for (const type of types) {- const resolvedType = this.resolveConflict(- 'agentTypes',- type.type,- type,- name,- this.agentTypeOwners,- resolution?.agentTypes- );- if (resolvedType) {- this.agentTypesCache.push(resolvedType);- }- }- }+ if (types) points.agentTypes.push(...types);}- // Collect task typesif (plugin.registerTaskTypes) {const types = plugin.registerTaskTypes();- if (types) {- for (const type of types) {- const resolvedType = this.resolveConflict(- 'taskTypes',- type.type,- type,- name,- this.taskTypeOwners,- resolution?.taskTypes- );- if (resolvedType) {- this.taskTypesCache.push(resolvedType);- }- }- }+ if (types) points.taskTypes.push(...types);}- // Collect MCP toolsif (plugin.registerMCPTools) {const tools = plugin.registerMCPTools();- if (tools) {- for (const tool of tools) {- const resolvedTool = this.resolveConflict(- 'mcpTools',- tool.name,- tool,- name,- this.toolOwners,- resolution?.mcpTools- );- if (resolvedTool) {- this.mcpToolsCache.push(resolvedTool);- }- }- }+ if (tools) points.mcpTools.push(...tools);}- // Collect CLI commandsif (plugin.registerCLICommands) {const commands = plugin.registerCLICommands();- if (commands) {- for (const command of commands) {- const resolvedCommand = this.resolveConflict(- 'cliCommands',- command.name,- command,- name,- this.commandOwners,- resolution?.cliCommands- );- if (resolvedCommand) {- this.cliCommandsCache.push(resolvedCommand);- }- }- }+ if (commands) points.cliCommands.push(...commands);}- // Collect other extension points (no conflict resolution needed)if (plugin.registerMemoryBackends) {const backends = plugin.registerMemoryBackends();- if (backends) this.memoryBackendsCache.push(...backends);+ if (backends) points.memoryBackends.push(...backends);}if (plugin.registerHooks) {const hooks = plugin.registerHooks();- if (hooks) this.hooksCache.push(...hooks);+ if (hooks) points.hooks.push(...hooks);}if (plugin.registerWorkers) {const workers = plugin.registerWorkers();- if (workers) this.workersCache.push(...workers);+ if (workers) points.workers.push(...workers);}if (plugin.registerProviders) {const providers = plugin.registerProviders();- if (providers) this.providersCache.push(...providers);+ if (providers) points.providers.push(...providers);}++ return points;+ }++ /**+ * Apply raw extension points through conflict resolution and append the+ * accepted values to the caches.+ */+ private applyExtensionPoints(points: ExtensionPointCollection, name: string): void {+ const resolution = this.config.conflictResolution;++ // Collect agent types+ for (const type of points.agentTypes) {+ const resolvedType = this.resolveConflict(+ 'agentTypes',+ type.type,+ type,+ name,+ this.agentTypeOwners,+ resolution?.agentTypes+ );+ if (resolvedType) {+ this.agentTypesCache.push(resolvedType);+ }+ }++ // Collect task types+ for (const type of points.taskTypes) {+ const resolvedType = this.resolveConflict(+ 'taskTypes',+ type.type,+ type,+ name,+ this.taskTypeOwners,+ resolution?.taskTypes+ );+ if (resolvedType) {+ this.taskTypesCache.push(resolvedType);+ }+ }++ // Collect MCP tools+ for (const tool of points.mcpTools) {+ const resolvedTool = this.resolveConflict(+ 'mcpTools',+ tool.name,+ tool,+ name,+ this.toolOwners,+ resolution?.mcpTools+ );+ if (resolvedTool) {+ this.mcpToolsCache.push(resolvedTool);+ }+ }++ // Collect CLI commands+ for (const command of points.cliCommands) {+ const resolvedCommand = this.resolveConflict(+ 'cliCommands',+ command.name,+ command,+ name,+ this.commandOwners,+ resolution?.cliCommands+ );+ if (resolvedCommand) {+ this.cliCommandsCache.push(resolvedCommand);+ }+ }++ // Collect other extension points (no conflict resolution needed)+ this.memoryBackendsCache.push(...points.memoryBackends);+ this.hooksCache.push(...points.hooks);+ this.workersCache.push(...points.workers);+ this.providersCache.push(...points.providers);}private resolveConflict<T extends { name?: string; type?: string }>(@@ -803,6 +857,12 @@ export class EnhancedPluginRegistry extends EventEmitter {}}+ /**+ * Invalidate extension point caches by replaying each initialized plugin's+ * captured values through conflict resolution. Never calls plugin+ * register* methods here: invalidation happens on unregister/reload and+ * must not re-run plugin code (#4410).+ */private invalidateCaches(): void {this.agentTypesCache = [];this.taskTypesCache = [];@@ -818,10 +878,10 @@ export class EnhancedPluginRegistry extends EventEmitter {this.agentTypeOwners.clear();this.taskTypeOwners.clear();- // Recollect from initialized plugins+ // Rebuild from initialized plugins using their captured raw values.for (const entry of this.plugins.values()) {- if (entry.plugin.state === 'initialized') {- this.collectExtensionPoints(entry.plugin);+ if (entry.plugin.state === 'initialized' && entry.extensionPoints) {+ this.applyExtensionPoints(entry.extensionPoints, entry.plugin.metadata.name);}}}diff --git a/v3/@claude-flow/plugins/src/registry/plugin-registry.ts b/v3/@claude-flow/plugins/src/registry/plugin-registry.tsindex fd142fd9a3..3a930a2564 100644--- a/v3/@claude-flow/plugins/src/registry/plugin-registry.ts+++ b/v3/@claude-flow/plugins/src/registry/plugin-registry.ts@@ -45,6 +45,38 @@ export interface PluginEntry {loadTime: Date;initTime?: Date;error?: string;+ /**+ * Extension points returned by the plugin at initialization time.+ *+ * Cache invalidation must replay these values instead of calling the+ * plugin's register* methods again: those methods may have side effects,+ * and plugins may return a new array (or allocate resources) per call.+ */+ extensionPoints?: ExtensionPointCollection;+}++interface ExtensionPointCollection {+ agentTypes: AgentTypeDefinition[];+ taskTypes: TaskTypeDefinition[];+ mcpTools: MCPToolDefinition[];+ cliCommands: CLICommandDefinition[];+ memoryBackends: MemoryBackendFactory[];+ hooks: HookDefinition[];+ workers: WorkerDefinition[];+ providers: LLMProviderDefinition[];+}++function emptyExtensionPointCollection(): ExtensionPointCollection {+ return {+ agentTypes: [],+ taskTypes: [],+ mcpTools: [],+ cliCommands: [],+ memoryBackends: [],+ hooks: [],+ workers: [],+ providers: [],+ };}export interface RegistryStats {@@ -283,7 +315,8 @@ export class PluginRegistry extends EventEmitter {const context = this.createPluginContext(entry);await this.initializeWithTimeout(entry.plugin, context);entry.initTime = new Date();- this.collectExtensionPoints(entry.plugin);+ entry.extensionPoints = this.readExtensionPoints(entry.plugin);+ this.applyExtensionPoints(entry.extensionPoints);this.logger.info(`Plugin initialized: ${name}`);} catch (error) {entry.error = error instanceof Error ? error.message : String(error);@@ -366,52 +399,72 @@ export class PluginRegistry extends EventEmitter {// =========================================================================/**- * Collect extension points from a plugin.+ * Read a plugin's extension points without mutating registry caches.+ *+ * The returned arrays are the plugin's own values and are stored on the+ * entry so cache rebuilds never invoke the plugin again.*/- private collectExtensionPoints(plugin: IPlugin): void {+ private readExtensionPoints(plugin: IPlugin): ExtensionPointCollection {+ const points = emptyExtensionPointCollection();+if (plugin.registerAgentTypes) {const types = plugin.registerAgentTypes();- if (types) this.agentTypesCache.push(...types);+ if (types) points.agentTypes.push(...types);}if (plugin.registerTaskTypes) {const types = plugin.registerTaskTypes();- if (types) this.taskTypesCache.push(...types);+ if (types) points.taskTypes.push(...types);}if (plugin.registerMCPTools) {const tools = plugin.registerMCPTools();- if (tools) this.mcpToolsCache.push(...tools);+ if (tools) points.mcpTools.push(...tools);}if (plugin.registerCLICommands) {const commands = plugin.registerCLICommands();- if (commands) this.cliCommandsCache.push(...commands);+ if (commands) points.cliCommands.push(...commands);}if (plugin.registerMemoryBackends) {const backends = plugin.registerMemoryBackends();- if (backends) this.memoryBackendsCache.push(...backends);+ if (backends) points.memoryBackends.push(...backends);}if (plugin.registerHooks) {const hooks = plugin.registerHooks();- if (hooks) this.hooksCache.push(...hooks);+ if (hooks) points.hooks.push(...hooks);}if (plugin.registerWorkers) {const workers = plugin.registerWorkers();- if (workers) this.workersCache.push(...workers);+ if (workers) points.workers.push(...workers);}if (plugin.registerProviders) {const providers = plugin.registerProviders();- if (providers) this.providersCache.push(...providers);+ if (providers) points.providers.push(...providers);}++ return points;+ }++ private applyExtensionPoints(points: ExtensionPointCollection): void {+ this.agentTypesCache.push(...points.agentTypes);+ this.taskTypesCache.push(...points.taskTypes);+ this.mcpToolsCache.push(...points.mcpTools);+ this.cliCommandsCache.push(...points.cliCommands);+ this.memoryBackendsCache.push(...points.memoryBackends);+ this.hooksCache.push(...points.hooks);+ this.workersCache.push(...points.workers);+ this.providersCache.push(...points.providers);}/**- * Invalidate extension point caches.+ * Invalidate extension point caches by replaying the values collected at+ * initialization. Never calls plugin register* methods here: invalidation+ * happens on unregister/shutdown and must not re-run plugin code (#4410).*/private invalidateCaches(): void {this.agentTypesCache = [];@@ -423,10 +476,10 @@ export class PluginRegistry extends EventEmitter {this.workersCache = [];this.providersCache = [];- // Recollect from initialized plugins+ // Rebuild from initialized plugins using their captured values.for (const entry of this.plugins.values()) {- if (entry.plugin.state === 'initialized') {- this.collectExtensionPoints(entry.plugin);+ if (entry.plugin.state === 'initialized' && entry.extensionPoints) {+ this.applyExtensionPoints(entry.extensionPoints);}}}