🌊 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(cli,integration): never import the agentic-flow root entry
Dragan Spiridonov74669662f773
diff --git a/v3/@claude-flow/cli/__tests__/agentic-flow-root-import.test.ts b/v3/@claude-flow/cli/__tests__/agentic-flow-root-import.test.tsnew file mode 100644index 0000000000..f5a5fdb2f3--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/agentic-flow-root-import.test.ts@@ -0,0 +1,80 @@+/**+ * Never import the agentic-flow root entry.+ *+ * agentic-flow 3.0.0-alpha.1/.2 call their CLI `main()` at the bottom of+ * dist/index.js, so `import('agentic-flow')` parses *our* process.argv and,+ * with no agentic-flow flag in it, runs its demo agents (with whatever model+ * credentials the environment has) and starts a health server on :8080. Only+ * library subpaths (`agentic-flow/reasoningbank`, `/router`, ...) are safe.+ *+ * The vitest config externalizes `agentic-flow*`, so vi.mock cannot observe+ * these imports; the source runs in a child process under tsx with loader+ * hooks that swap in a fake root entry which only reports its evaluation.+ */+import { describe, expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';++const CLI = resolve(__dirname, '..');+const PROBE = join(__dirname, 'fixtures', 'agentic-flow-root-probe', 'register.mjs');+const ROOT_EVALUATED = 'AGENTIC_FLOW_ROOT_EVALUATED';++function runProbe(script: string, env: Record<string, string> = {}) {+ const child = spawnSync(process.execPath, ['--import', 'tsx', '--import', pathToFileURL(PROBE).href, '--input-type=module', '-e', script], {+ cwd: CLI,+ env: { ...process.env, ...env, CLAUDE_FLOW_DISABLE_BRIDGE: '1' },+ encoding: 'utf8',+ timeout: 120_000,+ });+ return { status: child.status, stdout: child.stdout, stderr: child.stderr };+}++const srcUrl = (path: string): string => pathToFileURL(join(CLI, 'src', path)).href;++describe('agentic-flow root entry is never imported', () => {+ it('local embedding chain reaches the hash fallback without it', () => {+ const run = runProbe(`+ const { generateLocalEmbedding } = await import(${JSON.stringify(srcUrl('memory/memory-initializer.ts'))});+ const result = await generateLocalEmbedding('probe');+ console.log('MODEL=' + result.model);+ `);++ expect(run.stdout).toContain('MODEL=hash-fallback');+ expect(run.stderr).not.toContain(ROOT_EVALUATED);+ }, 150_000);++ it('hooks token-optimize does not fall back to it when reasoningbank is missing', () => {+ const run = runProbe(`+ const { hooksCommand } = await import(${JSON.stringify(srcUrl('commands/hooks.ts'))});+ const command = hooksCommand.subcommands.find((c) => c.name === 'token-optimize');+ const result = await command.action({ args: [], flags: { agents: '6' } });+ console.log('AVAILABLE=' + result.data.stats.agenticFlowAvailable);+ process.exit(0);+ `, { PROBE_REASONINGBANK: 'throw' });++ expect(run.stdout).toContain('AVAILABLE=false');+ expect(run.stderr).not.toContain(ROOT_EVALUATED);+ }, 150_000);++ it('no v3 source file imports the root entry', () => {+ const v3 = resolve(CLI, '../..');+ const rootImport = /(?:import\s*\(|require\s*\(|from\s+|safeImport<[^>]*>\s*\()\s*['"`]agentic-flow['"`]/;+ const offenders: string[] = [];+ const walk = (dir: string): void => {+ for (const name of readdirSync(dir)) {+ if (name === 'node_modules' || name === 'dist' || name === '__tests__' || name.startsWith('.')) continue;+ const path = join(dir, name);+ if (statSync(path).isDirectory()) { walk(path); continue; }+ if (!/\.(ts|mts|cts|js|mjs|cjs)$/.test(name) || /\.test\.|\.spec\./.test(name)) continue;+ readFileSync(path, 'utf8').split('\n').forEach((line, i) => {+ if (rootImport.test(line.replace(/\/\/.*$/, ''))) offenders.push(`${relative(v3, path)}:${i + 1}`);+ });+ }+ };+ walk(v3);++ expect(offenders).toEqual([]);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/fixtures/agentic-flow-root-probe/hooks.mjs b/v3/@claude-flow/cli/__tests__/fixtures/agentic-flow-root-probe/hooks.mjsnew file mode 100644index 0000000000..d9fb9d162f--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/fixtures/agentic-flow-root-probe/hooks.mjs@@ -0,0 +1,26 @@+// Loader hooks for agentic-flow-root-import.test.ts. Replaces agentic-flow and the+// embedders ahead of it with in-memory modules, so the test never loads (or runs)+// the real agentic-flow CLI. The fake root entry only reports that it was evaluated.+const FAKES = {+ 'agentic-flow': "process.stderr.write('AGENTIC_FLOW_ROOT_EVALUATED\\n'); export const embeddings = undefined;",+ 'agentic-flow/reasoningbank': process.env.PROBE_REASONINGBANK === 'throw'+ ? "throw new Error('reasoningbank unavailable');"+ : 'export const computeEmbedding = undefined; export const retrieveMemories = undefined;',+ '@huggingface/transformers': 'export const pipeline = undefined;',+ '@xenova/transformers': 'export const pipeline = undefined;',+ ruvector: 'export const initOnnxEmbedder = undefined; export const getOptimizedOnnxEmbedder = undefined;',+};++export async function resolve(specifier, context, next) {+ if (Object.hasOwn(FAKES, specifier)) {+ return { url: `probe:${specifier}`, shortCircuit: true };+ }+ return next(specifier, context);+}++export async function load(url, context, next) {+ if (url.startsWith('probe:')) {+ return { format: 'module', source: FAKES[url.slice('probe:'.length)], shortCircuit: true };+ }+ return next(url, context);+}diff --git a/v3/@claude-flow/cli/__tests__/fixtures/agentic-flow-root-probe/register.mjs b/v3/@claude-flow/cli/__tests__/fixtures/agentic-flow-root-probe/register.mjsnew file mode 100644index 0000000000..2006bfcafd--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/fixtures/agentic-flow-root-probe/register.mjs@@ -0,0 +1,2 @@+import { register } from 'node:module';+register('./hooks.mjs', import.meta.url);diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.tsindex 978e4cb8ae..b1acf74773 100644--- a/v3/@claude-flow/cli/src/commands/hooks.ts+++ b/v3/@claude-flow/cli/src/commands/hooks.ts@@ -4944,15 +4944,14 @@ const tokenOptimizeCommand: Command = {try {// Check if agentic-flow v3 is availableconst rb = await import('agentic-flow/reasoningbank').catch(() => null);+ // No root-entry fallback: importing 'agentic-flow' runs its CLI main()+ // in 3.0.0-alpha.x, and the root re-exports this same reasoningbank+ // module, so it cannot load when this subpath did not.if (rb) {agenticFlowAvailable = true;if (typeof rb.retrieveMemories === 'function') {reasoningBank = rb;}- } else {- // Legacy check for older agentic-flow- const af = await import('agentic-flow').catch(() => null);- if (af) agenticFlowAvailable = true;}const versionLabel = agenticFlowAvailable ? `agentic-flow v3 detected (ReasoningBank: ${reasoningBank ? 'active' : 'unavailable'})` : 'agentic-flow not available (using fallbacks)';diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.tsindex b6a24a9d22..e105b7814b 100644--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts@@ -2460,28 +2460,8 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now()):}}- // Legacy fallback: Check for agentic-flow core embeddings- const agenticFlow = await import('agentic-flow').catch(() => null);-- if (agenticFlow && (agenticFlow as any).embeddings) {- if (verbose) {- console.log('Loading agentic-flow embedding model...');- }-- embeddingModelState = {- loaded: true,- model: (agenticFlow as any).embeddings,- tokenizer: null,- dimensions: 768- };-- return {- success: true,- dimensions: 768,- modelName: 'agentic-flow',- loadTime: Date.now() - startTime- };- }+ // No agentic-flow root-entry fallback: no published root exports+ // `embeddings`, and importing it runs its CLI main() in 3.0.0-alpha.x.// No ONNX model available - use fallbackembeddingModelState = {diff --git a/v3/@claude-flow/integration/src/__tests__/token-optimizer.test.ts b/v3/@claude-flow/integration/src/__tests__/token-optimizer.test.tsindex c77f2a2abc..6d917a3a11 100644--- a/v3/@claude-flow/integration/src/__tests__/token-optimizer.test.ts+++ b/v3/@claude-flow/integration/src/__tests__/token-optimizer.test.ts@@ -34,8 +34,11 @@ describe('TokenOptimizer', () => {});async function canLoadAgenticFlow(): Promise<boolean> {- try { await import('agentic-flow'); return true; }- catch { return false; }+ for (const subpath of ['agentic-flow/reasoningbank', 'agentic-flow/agent-booster']) {+ try { await import(subpath); return true; }+ catch { /* try the next one */ }+ }+ return false;}});diff --git a/v3/@claude-flow/integration/src/agent-adapter.ts b/v3/@claude-flow/integration/src/agent-adapter.tsindex 911480f995..5840364ea2 100644--- a/v3/@claude-flow/integration/src/agent-adapter.ts+++ b/v3/@claude-flow/integration/src/agent-adapter.ts@@ -437,38 +437,17 @@ export class AgentAdapter extends EventEmitter {// ===== Private Methods =====/**- * Connect to agentic-flow package dynamically+ * agentic-flow core is not connected: no published agentic-flow exports `createAgenticFlow` (2.0.14,+ * 2.1.4, 3.0.0-alpha.1/.2), and importing its root entry runs its CLI+ * `main()` in 3.0.0-alpha.x — demo agents and a health server, inside our+ * process. Use local implementations.*/private async connectToAgenticFlow(): Promise<void> {- try {- // Dynamic import to handle optional dependency- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const agenticFlowModule: any = await import('agentic-flow').catch(() => null);-- if (agenticFlowModule && typeof agenticFlowModule.createAgenticFlow === 'function') {- this.agenticFlowCore = await agenticFlowModule.createAgenticFlow({});-- this.emit('agentic-flow-connected', {- version: this.agenticFlowCore.version,- });-- this.logDebug('Connected to agentic-flow', {- version: this.agenticFlowCore.version,- });- } else {- this.agenticFlowCore = null;- this.emit('agentic-flow-unavailable', {- reason: 'package not found or incompatible',- });- this.logDebug('agentic-flow not available, using local implementations');- }- } catch (error) {- this.agenticFlowCore = null;- this.emit('agentic-flow-connection-failed', {- error: (error as Error).message,- });- this.logDebug('agentic-flow connection failed', error);- }+ this.agenticFlowCore = null;+ this.emit('agentic-flow-unavailable', {+ reason: 'package not found or incompatible',+ });+ this.logDebug('agentic-flow not available, using local implementations');}/**diff --git a/v3/@claude-flow/integration/src/agentic-flow-bridge.ts b/v3/@claude-flow/integration/src/agentic-flow-bridge.tsindex 5f2f1f3894..8a23d085e6 100644--- a/v3/@claude-flow/integration/src/agentic-flow-bridge.ts+++ b/v3/@claude-flow/integration/src/agentic-flow-bridge.ts@@ -215,56 +215,19 @@ export class AgenticFlowBridge extends EventEmitter {* - Flash Attention (using native optimized implementations)* - AgentDB (leveraging 150x-12,500x faster HNSW search)*- * If agentic-flow is not installed, falls back to local implementations- * to maintain backward compatibility.+ * Until agentic-flow publishes that factory, the local implementations+ * are used.*/private async connectToAgenticFlow(): Promise<void> {- try {- // Dynamic import to handle optional dependency- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const agenticFlowModule: any = await import('agentic-flow').catch(() => null);-- if (agenticFlowModule && typeof agenticFlowModule.createAgenticFlow === 'function') {- const factory: AgenticFlowFactory = agenticFlowModule.createAgenticFlow;-- this.agenticFlowCore = await factory({- sona: this.config.sona,- attention: this.config.attention,- agentdb: this.config.agentdb,- });-- this.agenticFlowAvailable = true;- this.updateComponentHealth('agentic-flow', 'healthy');-- this.emit('agentic-flow:connected', {- version: this.agenticFlowCore.version,- features: {- sona: true,- attention: true,- agentdb: true,- },- });-- this.logDebug('Connected to agentic-flow', {- version: this.agenticFlowCore.version,- });- } else {- // Package not found or doesn't export expected factory- this.agenticFlowAvailable = false;- this.emit('agentic-flow:fallback', {- reason: 'package not found or incompatible',- });- this.logDebug('agentic-flow not available, using local implementations');- }- } catch (error) {- // Fallback to local implementation if agentic-flow fails to load- this.agenticFlowAvailable = false;- this.emit('agentic-flow:fallback', {- reason: 'initialization error',- error: (error as Error).message,- });- this.logDebug('agentic-flow initialization failed, using fallback', error);- }+ // Not connected: no published agentic-flow exports `createAgenticFlow` (2.0.14,+ // 2.1.4, 3.0.0-alpha.1/.2), and importing its root entry runs its CLI+ // `main()` in 3.0.0-alpha.x — demo agents and a health server, inside our+ // process. Use local implementations.+ this.agenticFlowAvailable = false;+ this.emit('agentic-flow:fallback', {+ reason: 'package not found or incompatible',+ });+ this.logDebug('agentic-flow not available, using local implementations');}/**diff --git a/v3/@claude-flow/integration/src/sdk-bridge.ts b/v3/@claude-flow/integration/src/sdk-bridge.tsindex ff3277902a..97487721d8 100644--- a/v3/@claude-flow/integration/src/sdk-bridge.ts+++ b/v3/@claude-flow/integration/src/sdk-bridge.ts@@ -334,16 +334,8 @@ export class SDKBridge extends EventEmitter {}private async detectVersion(): Promise<SDKVersion> {- // Detect agentic-flow version dynamically- try {- const af = await import('agentic-flow');- const version = (af as Record<string, unknown>)['VERSION'] as string | undefined;- if (version) {- return this.parseVersion(version);- }- } catch {- // agentic-flow not available, use fallback version- }+ // No published agentic-flow root exports `VERSION`, and importing the root+ // entry runs its CLI `main()` in 3.0.0-alpha.x, so use the baseline version.return this.parseVersion('2.0.1-alpha.50');}diff --git a/v3/@claude-flow/integration/src/swarm-adapter.ts b/v3/@claude-flow/integration/src/swarm-adapter.tsindex cd3452d778..39dcb89a90 100644--- a/v3/@claude-flow/integration/src/swarm-adapter.ts+++ b/v3/@claude-flow/integration/src/swarm-adapter.ts@@ -845,48 +845,22 @@ export class SwarmAdapter extends EventEmitter {// Private Methods// ==========================================================================+ /**+ * agentic-flow core is not connected: no published agentic-flow exports `createAgenticFlow` (2.0.14,+ * 2.1.4, 3.0.0-alpha.1/.2), and importing its root entry runs its CLI+ * `main()` in 3.0.0-alpha.x — demo agents and a health server, inside our+ * process. Use local implementations.+ */private async connectToAgenticFlow(): Promise<void> {- try {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const agenticFlowModule: any = await import('agentic-flow').catch(() => null);-- if (- agenticFlowModule &&- typeof agenticFlowModule.createAgenticFlow === 'function'- ) {- this.agenticFlowCore = await agenticFlowModule.createAgenticFlow({});-- // Check for AttentionCoordinator- if (this.agenticFlowCore.attention) {- this.attentionCoordinator = this.agenticFlowCore.attention;- }-- this.emit('agentic-flow-connected', {- version: this.agenticFlowCore.version,- hasAttention: !!this.attentionCoordinator,- hasMoE: !!this.agenticFlowCore.moe,- });-- this.logDebug('Connected to agentic-flow', {- version: this.agenticFlowCore.version,- });- } else {- this.agenticFlowCore = null;- this.emit('agentic-flow-unavailable', {- reason: 'package not found or incompatible',- });- }- } catch (error) {- this.agenticFlowCore = null;- this.emit('agentic-flow-connection-failed', {- error: (error as Error).message,- });- }+ this.agenticFlowCore = null;+ this.emit('agentic-flow-unavailable', {+ reason: 'package not found or incompatible',+ });}private generateAgentEmbedding(agent: V3AgentState): number[] {// Generate hash-based embedding from agent properties- // For ML embeddings, use: import('agentic-flow').computeEmbedding+ // For ML embeddings, use: import('agentic-flow/reasoningbank').computeEmbeddingconst embedding = new Array(128).fill(0);// Encode agent typediff --git a/v3/@claude-flow/integration/src/token-optimizer.ts b/v3/@claude-flow/integration/src/token-optimizer.tsindex a1bb05c715..c998317cdf 100644--- a/v3/@claude-flow/integration/src/token-optimizer.ts+++ b/v3/@claude-flow/integration/src/token-optimizer.ts@@ -80,31 +80,21 @@ export class TokenOptimizer extends EventEmitter {async initialize(): Promise<void> {try {- // Dynamic import of agentic-flow main module- const af = await safeImport<any>('agentic-flow');-- if (af) {- this.agenticFlowAvailable = true;-- // Load ReasoningBank (exported path)- const rb = await safeImport<any>('agentic-flow/reasoningbank');- if (rb && rb.retrieveMemories) {- this.reasoningBank = rb;- }-- // Load Agent Booster (exported path)- const ab = await safeImport<any>('agentic-flow/agent-booster');- if (ab) {- // Agent booster may export different API- this.agentBooster = ab.agentBooster || ab.AgentBooster || ab;- }-- // Config tuning is part of main module or agent-booster- // Use our fallback with anti-drift defaults- if (af.configTuning) {- this.configTuning = af.configTuning;- }+ // Only library subpaths: importing the agentic-flow root entry runs its+ // CLI main() in 3.0.0-alpha.x. No published root exports configTuning,+ // so the anti-drift defaults below are used.+ const rb = await safeImport<any>('agentic-flow/reasoningbank');+ if (rb && rb.retrieveMemories) {+ this.reasoningBank = rb;}++ const ab = await safeImport<any>('agentic-flow/agent-booster');+ if (ab) {+ // Agent booster may export different API+ this.agentBooster = ab.agentBooster || ab.AgentBooster || ab;+ }++ this.agenticFlowAvailable = rb !== null || ab !== null;} catch {this.agenticFlowAvailable = false;}diff --git a/v3/@claude-flow/swarm/src/queen-coordinator.ts b/v3/@claude-flow/swarm/src/queen-coordinator.tsindex 1065112139..31e3e63669 100644--- a/v3/@claude-flow/swarm/src/queen-coordinator.ts+++ b/v3/@claude-flow/swarm/src/queen-coordinator.ts@@ -1018,7 +1018,7 @@ export class QueenCoordinator extends EventEmitter {*/private createSimpleEmbedding(text: string): Float32Array {// Hash-based embedding - lightweight and fast for local similarity matching- // For production ML embeddings, use: import('agentic-flow').computeEmbedding+ // For production ML embeddings, use: import('agentic-flow/reasoningbank').computeEmbeddingconst embedding = new Float32Array(768);const words = text.toLowerCase().split(/\s+/);diff --git a/v3/mcp/tools/hooks-tools.ts b/v3/mcp/tools/hooks-tools.tsindex bca7e13ef9..2f9bbf49f2 100644--- a/v3/mcp/tools/hooks-tools.ts+++ b/v3/mcp/tools/hooks-tools.ts@@ -321,7 +321,7 @@ interface ListHooksResult {/*** Generate hash-based embedding from text.- * For ML embeddings, use: import('agentic-flow').computeEmbedding+ * For ML embeddings, use: import('agentic-flow/reasoningbank').computeEmbedding*/function generateSimpleEmbedding(text: string, dim: number = 768): Float32Array {const embedding = new Float32Array(dim);