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(config): preserve CLI documents through MCP tools

Rudy Celekli66cd10601616
diff --git a/v3/@claude-flow/cli/__tests__/config-cli-mcp-interop.test.ts b/v3/@claude-flow/cli/__tests__/config-cli-mcp-interop.test.ts
new file mode 100644
index 0000000000..4eff567572
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/config-cli-mcp-interop.test.ts
@@ -0,0 +1,139 @@
+import { beforeEach, afterEach, it, expect, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { ConfigFileManager } from '../src/services/config-file-manager.js';
+import { configTools } from '../src/mcp-tools/config-tools.js';
+import { configCommand } from '../src/commands/config.js';
+import { CommandParser } from '../src/parser.js';
+
+let root: string;
+let path: string;
+const tool = (name: string) => configTools.find(tool => tool.name === name)!;
+const invoke = async (name: string, input: Record<string, unknown>): Promise<any> => tool(name).handler(input);
+const document = () => JSON.parse(readFileSync(path, 'utf8'));
+const cliGet = (key: string) => new ConfigFileManager().get(root, key);
+async function cliSet(key: string, value: string): Promise<void> {
+ const parser = new CommandParser();
+ parser.registerCommand(configCommand);
+ const set = configCommand.subcommands!.find(command => command.name === 'set')!;
+ const parsed = parser.parse(['config', 'set', key, value]);
+ expect(parser.validateFlags(parsed.flags, set)).toEqual([]);
+ expect((await set.action!({ cwd: root, args: parsed.positional, flags: parsed.flags, interactive: false }))?.success).toBe(true);
+}
+beforeEach(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ruflo-config-interop-'));
+ mkdirSync(join(root, '.claude-flow'));
+ path = join(root, '.claude-flow', 'config.json');
+ writeFileSync(path, '{}');
+ vi.stubEnv('CLAUDE_FLOW_CWD', root);
+ vi.stubEnv('CLAUDE_FLOW_CONFIG', '');
+ for (const [key, value] of [['daemon.idleSecs', '0'], ['swarm.maxAgents', '23'], ['swarm.autoScale', 'false']]) {
+ await cliSet(key, value);
+ }
+});
+afterEach(() => {
+ vi.unstubAllEnvs();
+ rmSync(root, { recursive: true, force: true });
+});
+it('reads actual CLI-produced zero and false values', async () => {
+ expect((await invoke('config_get', { key: 'daemon.idleSecs' })).value).toBe(0);
+ expect((await invoke('config_get', { key: 'swarm.autoScale' })).value).toBe(false);
+});
+it('writes CLI-readable nested values and preserves other sections', async () => {
+ const result = await invoke('config_set', { key: 'swarm.maxAgents', value: 7 });
+ expect(result.previousValue).toBe(23);
+ expect(cliGet('swarm.maxAgents')).toBe(7);
+ expect(cliGet('daemon.idleSecs')).toBe(0);
+ expect(document()).not.toHaveProperty('values');
+});
+it('lists and exports actual CLI-produced leaves with prefix filtering', async () => {
+ const result = await invoke('config_list', { includeDefaults: false, prefix: 'swarm.' });
+ expect(result.configs).toEqual([
+ { key: 'swarm.autoScale', value: false, source: 'stored' },
+ { key: 'swarm.maxAgents', value: 23, source: 'stored' },
+ ]);
+ expect((await invoke('config_export', { includeDefaults: false })).config).toEqual({
+ 'daemon.idleSecs': 0, 'swarm.maxAgents': 23, 'swarm.autoScale': false,
+ });
+});
+it('preserves literal dotted keys and their precedence over nested values', async () => {
+ writeFileSync(path, JSON.stringify({ 'swarm.maxAgents': 12, swarm: { maxAgents: 23 } }));
+ expect((await invoke('config_get', { key: 'swarm.maxAgents' })).value).toBe(12);
+ expect((await invoke('config_export', { includeDefaults: false })).config['swarm.maxAgents']).toBe(12);
+ await invoke('config_set', { key: 'swarm.maxAgents', value: 7 });
+ expect(cliGet('swarm.maxAgents')).toBe(7);
+ expect(document()).toMatchObject({ 'swarm.maxAgents': 7, swarm: { maxAgents: 23 } });
+});
+it('reads and writes whole objects and arrays without flattening persisted values', async () => {
+ await invoke('config_set', { key: 'custom', value: { enabled: false, ports: [3, 5] } });
+ expect((await invoke('config_get', { key: 'custom' })).value).toEqual({ enabled: false, ports: [3, 5] });
+ expect(cliGet('custom.ports')).toEqual([3, 5]);
+ expect(document().custom).toEqual({ enabled: false, ports: [3, 5] });
+});
+it('can set a nested value below an existing null section', async () => {
+ writeFileSync(path, JSON.stringify({ custom: null }));
+ await invoke('config_set', { key: 'custom.enabled', value: false });
+ expect(cliGet('custom.enabled')).toBe(false);
+});
+it('resets a single plain key while preserving unrelated values', async () => {
+ const result = await invoke('config_reset', { key: 'swarm.maxAgents' });
+ expect(result.resetKeys).toEqual(['swarm.maxAgents']);
+ expect(cliGet('swarm.maxAgents')).toBeUndefined();
+ expect((await invoke('config_get', { key: 'swarm.maxAgents' })).value).toBe(10);
+ expect(cliGet('daemon.idleSecs')).toBe(0);
+});
+it('merges flat exported keys back into a CLI-readable document', async () => {
+ await invoke('config_import', { config: { 'swarm.maxAgents': 4, 'custom.enabled': false } });
+ expect(cliGet('swarm.maxAgents')).toBe(4);
+ expect(cliGet('custom.enabled')).toBe(false);
+ expect(cliGet('daemon.idleSecs')).toBe(0);
+ expect(document()).not.toHaveProperty('values');
+});
+it('replaces and resets all values while retaining the plain format', async () => {
+ await invoke('config_import', { config: { 'swarm.maxAgents': 4 }, merge: false });
+ expect(cliGet('swarm.maxAgents')).toBe(4);
+ expect(cliGet('daemon.idleSecs')).toBeUndefined();
+ await invoke('config_reset', {});
+ expect(cliGet('swarm.maxAgents')).toBe(10);
+ expect(document()).not.toHaveProperty('values');
+});
+it('persists scoped values separately from plain CLI settings', async () => {
+ await invoke('config_set', { key: 'swarm.maxAgents', value: 5, scope: 'project' });
+ expect((await invoke('config_get', { key: 'swarm.maxAgents', scope: 'project' })).value).toBe(5);
+ expect(cliGet('swarm.maxAgents')).toBe(23);
+ expect(document().scopes.project['swarm.maxAgents']).toBe(5);
+ await invoke('config_reset', { scope: 'project' });
+ expect((await invoke('config_get', { key: 'swarm.maxAgents', scope: 'project' })).value).toBe(23);
+});
+it('retains an existing MCP envelope through get, set, import and reset', async () => {
+ writeFileSync(path, JSON.stringify({ values: { 'swarm.maxAgents': 8 }, scopes: {}, version: '3.0.0', updatedAt: '' }));
+ expect((await invoke('config_get', { key: 'swarm.maxAgents' })).value).toBe(8);
+ await invoke('config_set', { key: 'swarm.maxAgents', value: 9 });
+ await invoke('config_import', { config: { 'custom.enabled': false } });
+ expect(document().values).toEqual({ 'swarm.maxAgents': 9, 'custom.enabled': false });
+ expect(document()).not.toHaveProperty('swarm');
+ await invoke('config_reset', { key: 'custom.enabled' });
+ expect(document().values).toEqual({ 'swarm.maxAgents': 9 });
+});
+it('keeps new MCP stores in the existing envelope format', async () => {
+ rmSync(path);
+ await invoke('config_set', { key: 'swarm.maxAgents', value: 9 });
+ expect(document().values['swarm.maxAgents']).toBe(9);
+ expect((await invoke('config_get', { key: 'swarm.maxAgents' })).value).toBe(9);
+});
+
+it('does not mistake an actual CLI values section for an MCP envelope', async () => {
+ await cliSet('values.enabled', 'true');
+ expect((await invoke('config_get', { key: 'values.enabled' })).value).toBe(true);
+ await invoke('config_set', { key: 'values.enabled', value: false });
+ expect(cliGet('values.enabled')).toBe(false);
+ expect(cliGet('swarm.maxAgents')).toBe(23);
+ expect(document()).not.toHaveProperty('scopes');
+});
+it('updates an actual CLI array element without dropping its siblings', async () => {
+ await cliSet('custom.ports', '[3,5]');
+ await invoke('config_set', { key: 'custom.ports.0', value: 7 });
+ expect(cliGet('custom.ports')).toEqual([7, 5]);
+ expect((await invoke('config_get', { key: 'custom.ports.1' })).value).toBe(5);
+});
diff --git a/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts
index a1d9207ce4..89f574757b 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts
@@ -49,12 +49,107 @@ function ensureConfigDir(): void {
}
}
+// Plain CLI files and legacy MCP envelopes share the same path. Keep the
+// original plain document so MCP writes remain readable by the CLI.
+const plainDocuments = new WeakMap<ConfigStore, Record<string, unknown>>();
+const STORE_METADATA = new Set(['scopes', 'version', 'updatedAt']);
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function flattenValues(document: Record<string, unknown>): Record<string, unknown> {
+ const values: Record<string, unknown> = {};
+ function visit(value: unknown, key: string): void {
+ if (isRecord(value) && Object.keys(value).length > 0) {
+ for (const [child, entry] of Object.entries(value)) visit(entry, `${key}.${child}`);
+ } else {
+ Object.defineProperty(values, key, { value, enumerable: true, configurable: true, writable: true });
+ }
+ }
+ for (const [key, value] of Object.entries(document)) {
+ if (!STORE_METADATA.has(key)) visit(value, key);
+ }
+ // CLI reads literal dotted keys before traversing nested objects.
+ for (const [key, value] of Object.entries(document)) {
+ if (key.includes('.')) Object.defineProperty(values, key, { value, enumerable: true, configurable: true, writable: true });
+ }
+ return values;
+}
+
+function readDefaultValue(store: ConfigStore, key: string): unknown {
+ const document = plainDocuments.get(store);
+ if (!document) return store.values[key];
+ return Object.hasOwn(document, key) ? document[key] : getNestedValue(document, key);
+}
+
+function writeDefaultValue(store: ConfigStore, key: string, value: unknown): void {
+ const document = plainDocuments.get(store);
+ if (!document) {
+ store.values[key] = value;
+ return;
+ }
+ // Keep existing literal dotted keys; otherwise use the CLI's nested shape.
+ if (Object.hasOwn(document, key)) {
+ // Reuse the same segment validation as nested writes.
+ setNestedValue({}, key, value);
+ document[key] = value;
+ } else {
+ setNestedValue(document, key, value);
+ }
+ store.values = flattenValues(document);
+}
+
+function deleteDefaultValue(store: ConfigStore, key: string): boolean {
+ const document = plainDocuments.get(store);
+ if (!document) return Object.hasOwn(store.values, key) && delete store.values[key];
+ let target = document;
+ let leaf = key;
+ if (!Object.hasOwn(document, key)) {
+ const parts = key.split('.');
+ leaf = parts.pop()!;
+ for (const part of parts) {
+ if (!Object.hasOwn(target, part) || !isRecord(target[part])) return false;
+ target = target[part] as Record<string, unknown>;
+ }
+ }
+ const deleted = Object.hasOwn(target, leaf) && delete target[leaf];
+ store.values = flattenValues(document);
+ return deleted;
+}
+
+function replaceDefaultValues(store: ConfigStore, values: Record<string, unknown>): void {
+ const document = plainDocuments.get(store);
+ if (!document) {
+ store.values = values;
+ return;
+ }
+ for (const key of Object.keys(document)) {
+ if (!STORE_METADATA.has(key)) delete document[key];
+ }
+ for (const [key, value] of Object.entries(values)) writeDefaultValue(store, key, value);
+}
+
function loadConfigStore(): ConfigStore {
try {
const path = getConfigPath();
if (existsSync(path)) {
const data = readFileSync(path, 'utf-8');
- return JSON.parse(data);
+ const document = JSON.parse(data);
+ const isEnvelope = isRecord(document) && isRecord(document.values)
+ && isRecord(document.scopes) && typeof document.version === 'string'
+ && typeof document.updatedAt === 'string';
+ if (isRecord(document) && !isEnvelope) {
+ const store: ConfigStore = {
+ values: flattenValues(document),
+ scopes: isRecord(document.scopes) ? document.scopes as ConfigStore['scopes'] : {},
+ version: typeof document.version === 'string' ? document.version : '3.0.0',
+ updatedAt: typeof document.updatedAt === 'string' ? document.updatedAt : '',
+ };
+ plainDocuments.set(store, document);
+ return store;
+ }
+ return document;
}
} catch {
// Return default store on error
@@ -70,14 +165,21 @@ function loadConfigStore(): ConfigStore {
function saveConfigStore(store: ConfigStore): void {
ensureConfigDir();
store.updatedAt = new Date().toISOString();
- writeFileSync(getConfigPath(), JSON.stringify(store, null, 2), 'utf-8');
+ const document = plainDocuments.get(store);
+ if (document) {
+ document.updatedAt = store.updatedAt;
+ if (Object.keys(store.scopes).length > 0 || Object.hasOwn(document, 'scopes')) {
+ document.scopes = store.scopes;
+ }
+ }
+ writeFileSync(getConfigPath(), JSON.stringify(document ?? store, null, 2), 'utf-8');
}
function getNestedValue(obj: Record<string, unknown>, key: string): unknown {
const parts = key.split('.');
let current: unknown = obj;
for (const part of parts) {
- if (current && typeof current === 'object' && part in (current as Record<string, unknown>)) {
+ if (current && typeof current === 'object' && Object.hasOwn(current, part)) {
current = (current as Record<string, unknown>)[part];
} else {
return undefined;
@@ -112,7 +214,7 @@ function setNestedValue(obj: Record<string, unknown>, key: string, value: unknow
let current = obj;
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i];
- if (!(part in current) || typeof current[part] !== 'object') {
+ if (!Object.hasOwn(current, part) || current[part] === null || typeof current[part] !== 'object') {
current[part] = {};
}
current = current[part] as Record<string, unknown>;
@@ -153,7 +255,7 @@ export const configTools: MCPTool[] = [
value = store.scopes[scope][key];
}
if (value === undefined) {
- value = store.values[key];
+ value = readDefaultValue(store, key);
}
if (value === undefined) {
value = DEFAULT_CONFIG[key];
@@ -164,7 +266,7 @@ export const configTools: MCPTool[] = [
value,
scope,
exists: value !== undefined,
- source: value !== undefined ? (store.values[key] !== undefined ? 'stored' : 'default') : 'none',
+ source: value !== undefined ? (readDefaultValue(store, key) !== undefined ? 'stored' : 'default') : 'none',
};
},
},
@@ -195,10 +297,10 @@ export const configTools: MCPTool[] = [
const value = input.value;
const scope = (input.scope as string) || 'default';
- const previousValue = store.values[key];
+ const previousValue = readDefaultValue(store, key);
if (scope === 'default') {
- store.values[key] = value;
+ writeDefaultValue(store, key, value);
} else {
if (!store.scopes[scope]) {
store.scopes[scope] = {};
@@ -323,8 +425,7 @@ export const configTools: MCPTool[] = [
if (key) {
// Reset specific key
if (scope === 'default') {
- if (key in store.values) {
- delete store.values[key];
+ if (deleteDefaultValue(store, key)) {
resetKeys.push(key);
}
} else if (store.scopes[scope] && key in store.scopes[scope]) {
@@ -335,7 +436,7 @@ export const configTools: MCPTool[] = [
// Reset all keys in scope
if (scope === 'default') {
resetKeys = Object.keys(store.values);
- store.values = { ...DEFAULT_CONFIG };
+ replaceDefaultValues(store, { ...DEFAULT_CONFIG });
} else if (store.scopes[scope]) {
resetKeys = Object.keys(store.scopes[scope]);
delete store.scopes[scope];
@@ -425,9 +526,9 @@ export const configTools: MCPTool[] = [
if (scope === 'default') {
if (merge) {
- Object.assign(store.values, config);
+ for (const [key, value] of Object.entries(config)) writeDefaultValue(store, key, value);
} else {
- store.values = { ...DEFAULT_CONFIG, ...config };
+ replaceDefaultValues(store, { ...DEFAULT_CONFIG, ...config });
}
} else {
if (!store.scopes[scope] || !merge) {