Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

fix([email protected]): real impl for stub helpers

Reuvene7a11f26f543
diff --git a/v3/plugins/code-intelligence/package.json b/v3/plugins/code-intelligence/package.json
index c071345772..16e2c02484 100644
--- a/v3/plugins/code-intelligence/package.json
+++ b/v3/plugins/code-intelligence/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/plugin-code-intelligence",
- "version": "3.0.0-alpha.1",
+ "version": "3.0.0-alpha.2",
"description": "Advanced code intelligence plugin for Claude Flow V3 - semantic search, architecture analysis, refactoring impact, module splitting, and pattern learning",
"type": "module",
"main": "./dist/index.js",
diff --git a/v3/plugins/code-intelligence/src/mcp-tools.ts b/v3/plugins/code-intelligence/src/mcp-tools.ts
index d0f249dc18..f599e0f45a 100644
--- a/v3/plugins/code-intelligence/src/mcp-tools.ts
+++ b/v3/plugins/code-intelligence/src/mcp-tools.ts
@@ -15,6 +15,7 @@
import { z } from 'zod';
import path from 'path';
+import fs from 'fs';
import type {
SemanticSearchResult,
ArchitectureAnalysisResult,
@@ -644,30 +645,254 @@ export const learnPatternsTool: MCPTool<
// Helper Functions
// ============================================================================
+// #1554/#1553: Real implementations replacing the previous `return []` stubs.
+// Kept dep-free (no fast-glob, no @claude-flow/embeddings) so the plugin can
+// ship without runtime peer-dep churn — semantic search uses a token-overlap
+// score that returns real ranked results, with a TODO to upgrade to ONNX
+// embeddings when the embeddings package is loadable. Architecture analysis
+// and refactor-impact pull file lists via getFilesInPath and import edges via
+// getAllRelatedFiles, which is enough to lift `0 edges / 0 results` to real
+// non-empty data across all 5 tools.
+
+const DEFAULT_CODE_EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']);
+const SKIP_DIR_NAMES = new Set([
+ 'node_modules', 'dist', 'build', '.git', 'coverage', 'vendor',
+ '.next', '.nuxt', '.turbo', '.cache', 'tmp', '.pnpm-store',
+]);
+const MAX_FILE_BYTES = 100 * 1024; // 100KB cap, matches issue suggestion
+
+async function getFilesInPath(rootPath: string): Promise<string[]> {
+ const out: string[] = [];
+ const visited = new Set<string>();
+
+ const walk = (dir: string) => {
+ let realDir: string;
+ try {
+ realDir = fs.realpathSync(dir);
+ } catch {
+ return;
+ }
+ if (visited.has(realDir)) return; // protect against symlink loops
+ visited.add(realDir);
+
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') && entry.name !== '.') {
+ // skip dot-prefixed entries except the root marker
+ if (SKIP_DIR_NAMES.has(entry.name)) continue;
+ continue;
+ }
+ if (SKIP_DIR_NAMES.has(entry.name)) continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full);
+ } else if (entry.isFile()) {
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!DEFAULT_CODE_EXTS.has(ext)) continue;
+ if (entry.name.endsWith('.min.js') || entry.name.endsWith('.min.mjs')) continue;
+ try {
+ const stat = fs.statSync(full);
+ if (stat.size > MAX_FILE_BYTES) continue;
+ } catch { continue; }
+ out.push(full);
+ }
+ }
+ };
+
+ walk(rootPath);
+ return out;
+}
+
+function tokenize(text: string): Map<string, number> {
+ const tokens = text
+ .toLowerCase()
+ .replace(/[^a-z0-9_]+/g, ' ')
+ .split(/\s+/)
+ .filter((t) => t.length >= 3 && t.length <= 32);
+ const counts = new Map<string, number>();
+ for (const t of tokens) counts.set(t, (counts.get(t) ?? 0) + 1);
+ return counts;
+}
+
+function cosineFromCounts(a: Map<string, number>, b: Map<string, number>): number {
+ let dot = 0;
+ for (const [tok, ca] of a) {
+ const cb = b.get(tok);
+ if (cb !== undefined) dot += ca * cb;
+ }
+ if (dot === 0) return 0;
+ let na = 0; for (const v of a.values()) na += v * v;
+ let nb = 0; for (const v of b.values()) nb += v * v;
+ return dot / (Math.sqrt(na) * Math.sqrt(nb));
+}
+
async function performSemanticSearch(
- _query: string,
- _paths: string[],
+ query: string,
+ paths: string[],
_searchType: string,
topK: number,
- _languages: string[] | undefined,
- _excludeTests: boolean,
- _context: ToolContext
+ languages: string[] | undefined,
+ excludeTests: boolean,
+ _context: ToolContext,
): Promise<CodeSearchResult[]> {
- // Simplified implementation
- const results: CodeSearchResult[] = [];
+ // Discover candidate files across all requested roots.
+ const candidates: string[] = [];
+ for (const root of paths) {
+ const files = await getFilesInPath(root);
+ for (const f of files) candidates.push(f);
+ }
+
+ // Filter by language extension if requested.
+ const langExt = (() => {
+ if (!languages || languages.length === 0) return null;
+ const exts = new Set<string>();
+ for (const l of languages) {
+ const k = l.toLowerCase();
+ if (k === 'typescript' || k === 'ts') { exts.add('.ts'); exts.add('.tsx'); }
+ else if (k === 'javascript' || k === 'js') { exts.add('.js'); exts.add('.jsx'); exts.add('.mjs'); exts.add('.cjs'); }
+ }
+ return exts;
+ })();
- // In production, would use vector index
- return results.slice(0, topK);
+ const queryTokens = tokenize(query);
+ const scored: Array<{ file: string; score: number; preview: string }> = [];
+
+ for (const file of candidates) {
+ if (langExt && !langExt.has(path.extname(file).toLowerCase())) continue;
+ if (excludeTests && /(\.|^)(test|spec)\.[mc]?[jt]sx?$/i.test(path.basename(file))) continue;
+
+ let content: string;
+ try {
+ content = fs.readFileSync(file, 'utf-8');
+ } catch { continue; }
+ const head = content.split('\n').slice(0, 200).join('\n');
+ const score = cosineFromCounts(queryTokens, tokenize(head));
+ if (score < 0.05) continue;
+ scored.push({ file, score, preview: head.slice(0, 240) });
+ }
+
+ scored.sort((a, b) => b.score - a.score);
+ const langFromExt = (file: string): 'typescript' | 'javascript' => {
+ const ext = path.extname(file).toLowerCase();
+ return ext === '.ts' || ext === '.tsx' ? 'typescript' : 'javascript';
+ };
+ return scored.slice(0, topK).map((r) => ({
+ filePath: r.file,
+ lineNumber: 1,
+ snippet: r.preview,
+ matchType: 'semantic',
+ score: r.score,
+ context: r.preview,
+ language: langFromExt(r.file),
+ explanation: `Token-overlap cosine similarity ${(r.score * 100).toFixed(1)}% over first 200 lines.`,
+ } satisfies CodeSearchResult));
}
-async function getFilesInPath(_rootPath: string): Promise<string[]> {
- // Simplified - in production would use glob
- return [];
+const IMPORT_RX = /^\s*(?:import\s+[^'"]+from\s+|import\s+|export\s+\*?\s*from\s+|export\s+\{[^}]*\}\s+from\s+)['"]([^'"]+)['"]|^\s*(?:const|let|var)\s+[^=]+=\s*require\(\s*['"]([^'"]+)['"]\s*\)/gm;
+
+function extractImportSpecifiers(filePath: string): string[] {
+ let content: string;
+ try { content = fs.readFileSync(filePath, 'utf-8'); } catch { return []; }
+ const out: string[] = [];
+ IMPORT_RX.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = IMPORT_RX.exec(content)) !== null) {
+ const spec = m[1] ?? m[2];
+ if (spec && (spec.startsWith('./') || spec.startsWith('../') || spec.startsWith('/'))) {
+ out.push(spec);
+ }
+ }
+ return out;
+}
+
+function resolveImportToFile(fromFile: string, spec: string): string | null {
+ const baseDir = path.dirname(fromFile);
+ const candidates: string[] = [];
+ if (spec.startsWith('/')) {
+ candidates.push(spec);
+ } else {
+ candidates.push(path.resolve(baseDir, spec));
+ }
+ // Try .ts/.tsx/.js/.jsx, plus index.* under a directory
+ const exts = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
+ for (const c of [...candidates]) {
+ for (const e of exts) {
+ candidates.push(c + e);
+ candidates.push(path.join(c, `index${e}`));
+ }
+ }
+ for (const c of candidates) {
+ try { if (fs.statSync(c).isFile()) return c; } catch { /* try next */ }
+ }
+ return null;
}
async function getAllRelatedFiles(changedFiles: string[]): Promise<string[]> {
- // Simplified - would traverse dependencies
- return changedFiles;
+ if (changedFiles.length === 0) return [];
+
+ // Forward BFS — what does each changed file (transitively) import?
+ const result = new Set<string>();
+ const queue: string[] = [];
+ for (const f of changedFiles) {
+ const abs = path.resolve(f);
+ result.add(abs);
+ queue.push(abs);
+ }
+ const MAX_DEPTH = 3;
+ let depth = 0;
+ while (queue.length > 0 && depth < MAX_DEPTH) {
+ const levelSize = queue.length;
+ for (let i = 0; i < levelSize; i++) {
+ const file = queue.shift()!;
+ const specs = extractImportSpecifiers(file);
+ for (const spec of specs) {
+ const resolved = resolveImportToFile(file, spec);
+ if (resolved && !result.has(resolved)) {
+ result.add(resolved);
+ queue.push(resolved);
+ }
+ }
+ }
+ depth++;
+ }
+
+ // Reverse scan — what files import any of the changed files? Use the
+ // common ancestor directory of the changed files as the search root.
+ const commonRoot = (() => {
+ if (changedFiles.length === 0) return process.cwd();
+ const parts = changedFiles.map((f) => path.resolve(f).split(path.sep));
+ const minLen = Math.min(...parts.map((p) => p.length));
+ const out: string[] = [];
+ for (let i = 0; i < minLen; i++) {
+ const seg = parts[0]?.[i];
+ if (seg === undefined) break;
+ if (parts.every((p) => p[i] === seg)) out.push(seg);
+ else break;
+ }
+ const dir = out.length > 0 ? out.join(path.sep) || path.sep : process.cwd();
+ try { return fs.statSync(dir).isDirectory() ? dir : path.dirname(dir); }
+ catch { return path.dirname(dir); }
+ })();
+
+ const allFiles = await getFilesInPath(commonRoot);
+ for (const file of allFiles) {
+ if (result.has(path.resolve(file))) continue;
+ const specs = extractImportSpecifiers(file);
+ for (const spec of specs) {
+ const resolved = resolveImportToFile(file, spec);
+ if (resolved && result.has(resolved)) {
+ result.add(path.resolve(file));
+ break;
+ }
+ }
+ }
+ return Array.from(result);
}
function detectLayerViolations(