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

feat: #2105 CLAUDE_FLOW_DB_PATH + #2058 team gateway checklist (#2146)

rUv427308308ca6
diff --git a/README.md b/README.md
index 38129ed0e9..d1e6974743 100644
--- a/README.md
+++ b/README.md
@@ -382,6 +382,7 @@ Four docs for four audiences:
| **[User Guide](docs/USERGUIDE.md)** | Daily reference β€” every command, every config flag, every plugin. The *how-do-I* doc. |
| **[Benchmarks](https://gist.github.com/ruvnet/298f8c668c8859b369f91734a0e9cbbe)** | v3.8.0 SOTA matrix vs LangGraph / AutoGen / CrewAI on darwin-arm64 + linux-x64. ruflo wins cold start, single turn, RSS by 1.3×–1953Γ—. The *is-it-fast* doc. |
| **[Verification](verification.md)** | Cryptographically prove your installed bytes match the signed witness β€” `ruflo verify`. The *trust-but-verify* doc. |
+| **[Team Gateway Checklist](docs/TEAM-GATEWAY-CHECKLIST.md)** | Before-merge gates, dual-mode handoff, memory namespace sharing, and witness manifest entry per merge. The *safer-team-workflows* doc. |
Benchmark internals (for reproduction): [`sota-workload-spec.md`](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/sota-workload-spec.md) Β· [`SOTA-PROGRESS.md`](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/SOTA-PROGRESS.md) Β· [raw matrix JSON: darwin](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/sota-matrix.json) Β· [linux](https://github.com/ruvnet/ruflo/blob/perf/sota-comparator-benchmarks/docs/benchmarks/sota-matrix-linux.json)
diff --git a/docs/TEAM-GATEWAY-CHECKLIST.md b/docs/TEAM-GATEWAY-CHECKLIST.md
new file mode 100644
index 0000000000..716bcd9d41
--- /dev/null
+++ b/docs/TEAM-GATEWAY-CHECKLIST.md
@@ -0,0 +1,120 @@
+# Team Gateway Checklist
+
+This checklist covers governance and safety gates for teams running Claude Code / Codex-style agent workflows through a shared gateway or proxy. It supersedes ad-hoc runbooks and is enforced by the before-merge CI gates listed below.
+
+Related: [#2058](https://github.com/ruvnet/ruflo/issues/2058)
+
+---
+
+## 1. Before-Merge Gates
+
+Run these checks before every merge to main:
+
+| Gate | Command | Blocks merge if |
+|------|---------|-----------------|
+| Lint | `npm run lint` | Any lint error |
+| Type-check | `npx tsc --noEmit` | Any TypeScript error |
+| Unit tests | `npm test` | Fewer than 1999 passing |
+| Smoke tests | `node scripts/smoke-*.mjs` | Any exit code != 0 |
+| Witness manifest | `npx ruflo@latest verify` | Checksum mismatch |
+| Semver bump | `npm version <patch\|minor\|major>` | No version bump on API change |
+
+Every merge to main **must** record a new witness manifest entry. Generate it with:
+
+```bash
+npx ruflo@latest sign --message "merge: <PR title>"
+```
+
+---
+
+## 2. Dual-Mode Handoff (Claude Code + Codex)
+
+When handing work between Claude Code and OpenAI Codex workers:
+
+1. **Shared memory namespace**: use `collaboration` β€” all cross-platform writes go here.
+2. **Store design decisions before switching platforms**:
+ ```bash
+ npx @claude-flow/cli@latest memory store \
+ --namespace collaboration \
+ --key "design-<feature>" \
+ --value "<design decisions as JSON or markdown>"
+ ```
+3. **Kick off Codex worker** after Claude Code produces the design:
+ ```bash
+ npx claude-flow-codex dual run \
+ --worker "codex:coder:Implement based on design-<feature>" \
+ --namespace collaboration
+ ```
+4. **Validate compatibility before shipping** β€” OpenAI-compatible and Anthropic-compatible endpoints are verified subsets. Always smoke-test streaming, tool calling / MCP, and reasoning blocks independently before putting them in an autonomous workflow.
+5. **Keep provider keys separate** β€” gateway or proxy keys must be distinct from upstream provider keys and must be rotatable / revocable without rotating the upstream secret.
+
+---
+
+## 3. Memory Namespace Sharing
+
+All agents in a team workflow share state through named namespaces. Conventions:
+
+| Namespace | Owner | Contents |
+|-----------|-------|----------|
+| `collaboration` | All cross-platform agents | Design decisions, code paths, review findings |
+| `patterns` | All agents | Reusable solution patterns (stored after each successful task) |
+| `tasks` | Coordinator | Task assignments and status |
+| `security` | Security auditor | Vulnerability findings, remediation status |
+
+Rules:
+- Never write credentials or raw API keys to any namespace β€” store only key names or rotation identifiers.
+- Namespaces are **not** access-controlled by default; treat all shared namespaces as readable by every agent in the swarm.
+- Use `--ttl` to expire ephemeral coordination messages (e.g., handoff signals):
+ ```bash
+ npx @claude-flow/cli@latest memory store \
+ --namespace collaboration \
+ --key "handoff-signal-<run-id>" \
+ --value "ready" \
+ --ttl 300
+ ```
+
+---
+
+## 4. Witness Manifest Entry Per Merge
+
+Each merge to main must include a signed witness manifest entry so `npx ruflo@latest verify` can confirm the installed dist matches the audited fix footprint.
+
+### Generating a manifest entry
+
+```bash
+# Sign the current dist with a descriptive message
+npx ruflo@latest sign --message "merge: <PR-number> β€” <one-line description>"
+
+# Commit the updated manifest alongside code changes
+git add verification.md verification.md.json
+git commit -m "chore: update witness manifest for <PR-number>"
+```
+
+### Verifying an installation
+
+```bash
+# After npm install / npx ruflo@latest
+npx ruflo@latest verify
+# Expected output: "Verification passed β€” dist matches audited footprint"
+```
+
+If `verify` reports a mismatch, do **not** use the installation in a shared gateway until the discrepancy is investigated and a new manifest is signed.
+
+---
+
+## 5. Gateway Logging and Audit Scope
+
+Be explicit with teammates about what your gateway logs contain:
+
+- **Logged**: usage metadata (tokens, model, latency), route, HTTP status, error class.
+- **Not logged by default**: prompt content or completion content (check your gateway config).
+- Avoid unauthenticated shared gateway access outside local experiments.
+- Review `CLAUDE_FLOW_LOG_LEVEL=debug` output before sharing logs β€” debug level may include request bodies.
+
+---
+
+## See Also
+
+- [AGENT_CONTRIBUTOR.md](../docs/AGENT_CONTRIBUTOR.md) β€” how to contribute as an agent or swarm participant
+- [USERGUIDE.md](../docs/USERGUIDE.md) β€” full usage documentation
+- [ADR index](../docs/) β€” architectural decision records
diff --git a/scripts/smoke-memory-db-path.mjs b/scripts/smoke-memory-db-path.mjs
new file mode 100644
index 0000000000..cadef32e15
--- /dev/null
+++ b/scripts/smoke-memory-db-path.mjs
@@ -0,0 +1,191 @@
+#!/usr/bin/env node
+/**
+ * Smoke: #2105 β€” CLAUDE_FLOW_DB_PATH env var + --path flag on memory subcommands.
+ *
+ * Verifies the three-tier path resolution in resolveDbPath():
+ * 1. --path flag wins over everything
+ * 2. CLAUDE_FLOW_DB_PATH env var is honoured when --path is absent
+ * 3. Default path (cwd/.swarm/memory.db) used when neither is set
+ *
+ * Tests both the exported resolveDbPath() function directly and the
+ * CLI-level --path flag wiring on memory init / store / retrieve / list /
+ * search / delete / stats.
+ *
+ * Exit codes:
+ * 0 β€” all checks passed
+ * 1 β€” one or more checks failed
+ *
+ * Usage:
+ * node scripts/smoke-memory-db-path.mjs
+ */
+
+import { strictEqual, ok } from 'node:assert';
+import { mkdirSync, rmSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve as pathResolve } from 'node:path';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = fileURLToPath(new URL('.', import.meta.url));
+const ROOT = pathResolve(__dirname, '..');
+
+let passed = 0;
+let failed = 0;
+
+function check(label, fn) {
+ try {
+ fn();
+ console.log(` [PASS] ${label}`);
+ passed++;
+ } catch (err) {
+ console.error(` [FAIL] ${label}: ${err.message}`);
+ failed++;
+ }
+}
+
+async function checkAsync(label, fn) {
+ try {
+ await fn();
+ console.log(` [PASS] ${label}`);
+ passed++;
+ } catch (err) {
+ console.error(` [FAIL] ${label}: ${err.message}`);
+ failed++;
+ }
+}
+
+// ─── 1. Unit-test resolveDbPath() directly ──────────────────────────────────
+console.log('\n[smoke-memory-db-path] 1. resolveDbPath() unit tests');
+
+const require = createRequire(import.meta.url);
+// Build the CLI if dist doesn't exist
+let resolveDbPath;
+try {
+ const mod = await import(
+ join(ROOT, 'v3/@claude-flow/cli/dist/src/memory/memory-initializer.js')
+ );
+ resolveDbPath = mod.resolveDbPath;
+} catch {
+ // Try source fallback
+ try {
+ const mod = await import(
+ join(ROOT, 'v3/@claude-flow/cli/src/memory/memory-initializer.js')
+ );
+ resolveDbPath = mod.resolveDbPath;
+ } catch (e) {
+ console.error('[SKIP] resolveDbPath not importable β€” skipping unit tests:', e.message);
+ resolveDbPath = null;
+ }
+}
+
+const tmpDir = join(tmpdir(), `smoke-2105-${Date.now()}`);
+mkdirSync(tmpDir, { recursive: true });
+
+try {
+ if (resolveDbPath) {
+ // Save and restore env vars
+ const origDbPath = process.env.CLAUDE_FLOW_DB_PATH;
+ const origMemPath = process.env.CLAUDE_FLOW_MEMORY_PATH;
+
+ // Test 1a: --path flag wins
+ delete process.env.CLAUDE_FLOW_DB_PATH;
+ delete process.env.CLAUDE_FLOW_MEMORY_PATH;
+ const cliResult = resolveDbPath(join(tmpDir, 'flag.db'));
+ check('--path flag overrides everything', () => {
+ ok(cliResult.endsWith('flag.db'), `Expected flag.db, got: ${cliResult}`);
+ });
+
+ // Test 1b: CLAUDE_FLOW_DB_PATH env var used when no --path
+ process.env.CLAUDE_FLOW_DB_PATH = join(tmpDir, 'env.db');
+ delete process.env.CLAUDE_FLOW_MEMORY_PATH;
+ const envResult = resolveDbPath(undefined);
+ check('CLAUDE_FLOW_DB_PATH env var honoured without --path flag', () => {
+ ok(envResult.endsWith('env.db'), `Expected env.db, got: ${envResult}`);
+ });
+
+ // Test 1c: --path wins over CLAUDE_FLOW_DB_PATH
+ process.env.CLAUDE_FLOW_DB_PATH = join(tmpDir, 'env.db');
+ const flagWinsResult = resolveDbPath(join(tmpDir, 'flag2.db'));
+ check('--path flag wins over CLAUDE_FLOW_DB_PATH env var', () => {
+ ok(flagWinsResult.endsWith('flag2.db'), `Expected flag2.db, got: ${flagWinsResult}`);
+ });
+
+ // Test 1d: default path used when neither set
+ delete process.env.CLAUDE_FLOW_DB_PATH;
+ delete process.env.CLAUDE_FLOW_MEMORY_PATH;
+ const defaultResult = resolveDbPath(undefined);
+ check('default path used when no flag or env var', () => {
+ ok(
+ defaultResult.includes('memory.db'),
+ `Expected path to include memory.db, got: ${defaultResult}`,
+ );
+ });
+
+ // Test 1e: CLAUDE_FLOW_MEMORY_PATH provides directory, memory.db appended
+ process.env.CLAUDE_FLOW_MEMORY_PATH = tmpDir;
+ delete process.env.CLAUDE_FLOW_DB_PATH;
+ // Reset cache so CLAUDE_FLOW_MEMORY_PATH takes effect
+ const { _resetMemoryRootCache } = await import(
+ join(ROOT, 'v3/@claude-flow/cli/dist/src/memory/memory-initializer.js')
+ ).catch(() => import(join(ROOT, 'v3/@claude-flow/cli/src/memory/memory-initializer.js')));
+ if (_resetMemoryRootCache) _resetMemoryRootCache();
+ const memPathResult = resolveDbPath(undefined);
+ check('CLAUDE_FLOW_MEMORY_PATH provides directory, memory.db appended', () => {
+ ok(
+ memPathResult === pathResolve(tmpDir, 'memory.db') ||
+ memPathResult.endsWith('memory.db'),
+ `Expected memory.db in tmpDir, got: ${memPathResult}`,
+ );
+ });
+
+ // Restore env
+ if (origDbPath !== undefined) process.env.CLAUDE_FLOW_DB_PATH = origDbPath;
+ else delete process.env.CLAUDE_FLOW_DB_PATH;
+ if (origMemPath !== undefined) process.env.CLAUDE_FLOW_MEMORY_PATH = origMemPath;
+ else delete process.env.CLAUDE_FLOW_MEMORY_PATH;
+ if (_resetMemoryRootCache) _resetMemoryRootCache();
+ }
+
+ // ─── 2. Verify option is declared on memory subcommands ──────────────────
+ console.log('\n[smoke-memory-db-path] 2. --path option declared on subcommands');
+
+ // Import the memoryCommand and check its subcommands for the --path option
+ let memoryCommand;
+ try {
+ const mod = await import(
+ join(ROOT, 'v3/@claude-flow/cli/dist/src/commands/memory.js')
+ );
+ memoryCommand = mod.memoryCommand || mod.default;
+ } catch {
+ try {
+ const mod = await import(
+ join(ROOT, 'v3/@claude-flow/cli/src/commands/memory.js')
+ );
+ memoryCommand = mod.memoryCommand || mod.default;
+ } catch (e) {
+ console.warn('[WARN] Cannot import memory command:', e.message);
+ }
+ }
+
+ if (memoryCommand) {
+ const subcommands = memoryCommand.subcommands || [];
+ const targetSubs = ['store', 'retrieve', 'search', 'list', 'delete', 'stats'];
+ for (const subName of targetSubs) {
+ const sub = subcommands.find(s => s.name === subName);
+ check(`memory ${subName} has --path option`, () => {
+ ok(sub, `Subcommand '${subName}' not found`);
+ const opts = sub.options || [];
+ const pathOpt = opts.find(o => o.name === 'path');
+ ok(pathOpt, `--path option missing from 'memory ${subName}'`);
+ });
+ }
+ } else {
+ console.warn('[WARN] Memory command not available β€” skipping subcommand option checks');
+ }
+} finally {
+ rmSync(tmpDir, { recursive: true, force: true });
+}
+
+// ─── Summary ────────────────────────────────────────────────────────────────
+console.log(`\n[smoke-memory-db-path] ${passed} passed, ${failed} failed`);
+if (failed > 0) process.exit(1);
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index 66cce73ac3..fe0afe4fa4 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -15,6 +15,15 @@ const BACKENDS = [
{ value: 'hybrid', label: 'Hybrid', hint: 'SQLite + AgentDB (recommended)' },
{ value: 'memory', label: 'In-Memory', hint: 'Fast but non-persistent' }
];
+// #2105: shared --path option for memory subcommands.
+// Precedence: --path > CLAUDE_FLOW_DB_PATH env var > default root
+const DB_PATH_OPTION = {
+ name: 'path',
+ description:
+ 'Override DB file path (also: CLAUDE_FLOW_DB_PATH env var). ' +
+ 'Precedence: --path > CLAUDE_FLOW_DB_PATH > CLAUDE_FLOW_MEMORY_PATH/memory.db > cwd/.swarm/memory.db',
+ type: 'string' as const,
+};
// Store command
const storeCommand: Command = {
@@ -63,7 +72,8 @@ const storeCommand: Command = {
description: 'Update if key exists (insert or replace)',
type: 'boolean',
default: false
- }
+ },
+ DB_PATH_OPTION
],
examples: [
{ command: 'claude-flow memory store -k "api/auth" -v "JWT implementation"', description: 'Store text' },
@@ -111,7 +121,8 @@ const storeCommand: Command = {
// Use direct sql.js storage with automatic embedding generation
try {
- const { storeEntry } = await import('../memory/memory-initializer.js');
+ const { storeEntry, resolveDbPath: _rdbStore } = await import('../memory/memory-initializer.js');
+ const dbPath = _rdbStore(ctx.flags.path as string | undefined);
if (asVector) {
output.writeln(output.dim(' Generating embedding vector...'));
@@ -124,7 +135,8 @@ const storeCommand: Command = {
generateEmbeddingFlag: true, // Always generate embeddings for semantic search
tags,
ttl,
- upsert
+ upsert,
+ dbPath
});
if (!result.success) {
@@ -191,7 +203,8 @@ const retrieveCommand: Command = {
description: 'Print only the stored value to stdout (no wrapper)',
type: 'boolean',
default: false
- }
+ },
+ DB_PATH_OPTION
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const key = ctx.flags.key as string || ctx.args[0];
@@ -204,8 +217,9 @@ const retrieveCommand: Command = {
// Use sql.js directly for consistent data access
try {
- const { getEntry } = await import('../memory/memory-initializer.js');
- const result = await getEntry({ key, namespace });
+ const { getEntry, resolveDbPath: _rdbRetrieve } = await import('../memory/memory-initializer.js');
+ const dbPathRetrieve = _rdbRetrieve(ctx.flags.path as string | undefined);
+ const result = await getEntry({ key, namespace, dbPath: dbPathRetrieve });
if (!result.success) {
output.printError(`Failed to retrieve: ${result.error}`);
@@ -310,7 +324,8 @@ const searchCommand: Command = {
description: 'Use SmartRetrieval pipeline (query expansion, RRF, MMR, recency)',
type: 'boolean',
default: false
- }
+ },
+ DB_PATH_OPTION
],
examples: [
{ command: 'claude-flow memory search -q "authentication patterns"', description: 'Semantic search' },
@@ -362,7 +377,8 @@ const searchCommand: Command = {
// Use direct sql.js search with vector similarity
try {
- const { searchEntries } = await import('../memory/memory-initializer.js');
+ const { searchEntries, resolveDbPath: _rdbSearch } = await import('../memory/memory-initializer.js');
+ const dbPathSearch = _rdbSearch(ctx.flags.path as string | undefined);
const useSmart = (ctx.flags.smart || ctx.flags.s) as boolean;
let results: { key: string; score: number; namespace: string; preview: string }[];
@@ -400,6 +416,7 @@ const searchCommand: Command = {
namespace: req.namespace || namespace,
limit: req.limit || limit * 3,
threshold: req.threshold ?? threshold,
+ dbPath: dbPathSearch,
});
return {
results: r.results.map(e => ({
@@ -433,7 +450,8 @@ const searchCommand: Command = {
query,
namespace,
limit,
- threshold
+ threshold,
+ dbPath: dbPathSearch
});
if (!searchResult.success) {
@@ -514,7 +532,8 @@ const listCommand: Command = {
description: 'Maximum entries',
type: 'number',
default: 20
- }
+ },
+ DB_PATH_OPTION
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const namespace = ctx.flags.namespace as string;
@@ -522,8 +541,9 @@ const listCommand: Command = {
// Use sql.js directly for consistent data access
try {
- const { listEntries } = await import('../memory/memory-initializer.js');
- const listResult = await listEntries({ namespace, limit, offset: 0 });
+ const { listEntries, resolveDbPath: _rdbList } = await import('../memory/memory-initializer.js');
+ const dbPathList = _rdbList(ctx.flags.path as string | undefined);
+ const listResult = await listEntries({ namespace, limit, offset: 0, dbPath: dbPathList });
if (!listResult.success) {
output.printError(`Failed to list: ${listResult.error}`);
@@ -620,7 +640,8 @@ const deleteCommand: Command = {
description: 'Skip confirmation',
type: 'boolean',
default: false
- }
+ },
+ DB_PATH_OPTION
],
examples: [
{ command: 'claude-flow memory delete -k "mykey"', description: 'Delete entry with default namespace' },
@@ -652,8 +673,9 @@ const deleteCommand: Command = {
// Use sql.js directly for consistent data access (Issue #980)
try {
- const { deleteEntry } = await import('../memory/memory-initializer.js');
- const result = await deleteEntry({ key, namespace });
+ const { deleteEntry, resolveDbPath: _rdbDelete } = await import('../memory/memory-initializer.js');
+ const dbPathDelete = _rdbDelete(ctx.flags.path as string | undefined);
+ const result = await deleteEntry({ key, namespace, dbPath: dbPathDelete });
if (!result.success) {
output.printError(result.error || 'Failed to delete');
@@ -679,6 +701,7 @@ const deleteCommand: Command = {
const statsCommand: Command = {
name: 'stats',
description: 'Show memory statistics',
+ options: [DB_PATH_OPTION],
action: async (ctx: CommandContext): Promise<CommandResult> => {
// Call MCP memory/stats tool for real statistics
try {
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index 0d0053c4fb..24bf4b694f 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -70,6 +70,25 @@ export function _resetMemoryRootCache(): void {
_memoryRootCache = undefined;
}
+/**
+ * #2105: Resolve the full path to the SQLite memory database.
+ * Precedence (highest to lowest):
+ * 1. cliFlag - explicit --path flag passed by a subcommand
+ * 2. CLAUDE_FLOW_DB_PATH - full file-path override (new in #2105)
+ * 3. getMemoryRoot()/memory.db - directory from CLAUDE_FLOW_MEMORY_PATH /
+ * config / default cwd/.swarm
+ */
+export function resolveDbPath(cliFlag?: string): string {
+ if (cliFlag && cliFlag.trim().length > 0) {
+ return path.resolve(cliFlag);
+ }
+ const envDb = process.env.CLAUDE_FLOW_DB_PATH;
+ if (envDb && envDb.trim().length > 0) {
+ return path.resolve(envDb);
+ }
+ return path.join(getMemoryRoot(), 'memory.db');
+}
+
// ADR-053: Lazy import of AgentDB v3 bridge
let _bridge: typeof import('./memory-bridge.js') | null | undefined;
async function getBridge(): Promise<typeof import('./memory-bridge.js') | null> {