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(codex): finish Codex ↔ Ruflo integration β€” real `codex exec`, `dual run --worker`, tests, CI guard (#1909) (#1911)

rUv511b2ac0704c
diff --git a/.claude/agents/dual-mode/codex-coordinator.md b/.claude/agents/dual-mode/codex-coordinator.md
index b423fbac00..62190d6389 100644
--- a/.claude/agents/dual-mode/codex-coordinator.md
+++ b/.claude/agents/dual-mode/codex-coordinator.md
@@ -5,7 +5,12 @@ description: Coordinates multiple headless Codex workers for parallel execution
# Codex Parallel Coordinator
-You coordinate multiple headless Codex workers for parallel task execution. You run interactively and spawn background workers using `claude -p`.
+You coordinate multiple headless Codex workers for parallel task execution. You run interactively and spawn background workers using `codex exec`.
+
+> Worker spawn syntax: `codex exec --sandbox workspace-write --skip-git-repo-check "<prompt>" &`.
+> `codex exec` is non-interactive and runs to completion; `&` backgrounds it so workers run
+> in parallel β€” `wait` blocks until all finish. (If you mix platforms, *Claude* workers use
+> `claude -p "<prompt>" --output-format text &` instead β€” but `codex-worker`s always use `codex exec`.)
## Architecture
@@ -37,7 +42,7 @@ You coordinate multiple headless Codex workers for parallel task execution. You
## Core Responsibilities
1. **Task Decomposition**: Break complex tasks into parallelizable units
-2. **Worker Spawning**: Launch headless Codex instances via `claude -p`
+2. **Worker Spawning**: Launch headless Codex instances via `codex exec`
3. **Coordination**: Track progress through shared memory
4. **Result Aggregation**: Collect and combine worker outputs
@@ -45,16 +50,16 @@ You coordinate multiple headless Codex workers for parallel task execution. You
### Step 1: Initialize Swarm
```bash
-npx claude-flow@v3alpha swarm init --topology hierarchical --max-agents 6
+npx ruflo@latest swarm init --topology hierarchical --max-agents 6
```
### Step 2: Spawn Parallel Workers
```bash
# Spawn all workers in parallel
-claude -p "Implement core auth logic" --session-id auth-core &
-claude -p "Implement auth middleware" --session-id auth-middleware &
-claude -p "Write auth tests" --session-id auth-tests &
-claude -p "Document auth API" --session-id auth-docs &
+codex exec --sandbox workspace-write --skip-git-repo-check "Implement core auth logic. Store result in 'results' namespace as result-auth-core." &
+codex exec --sandbox workspace-write --skip-git-repo-check "Implement auth middleware. Store result as result-auth-middleware." &
+codex exec --sandbox workspace-write --skip-git-repo-check "Write auth tests. Store result as result-auth-tests." &
+codex exec --sandbox workspace-write --skip-git-repo-check "Document auth API. Store result as result-auth-docs." &
# Wait for all to complete
wait
@@ -62,7 +67,7 @@ wait
### Step 3: Collect Results
```bash
-npx claude-flow@v3alpha memory list --namespace results
+npx ruflo@latest memory list --namespace results
```
## Coordination Patterns
@@ -107,21 +112,21 @@ const workers = [
// Spawn all workers
workers.forEach(w => {
- console.log(`claude -p "${w.task}" --session-id ${w.id} &`);
+ console.log(`codex exec --sandbox workspace-write --skip-git-repo-check "${w.task}. Store result as result-${w.id}." &`);
});
```
### Worker Spawn Template
```bash
-claude -p "
-You are {{worker_name}}.
+codex exec --sandbox workspace-write --skip-git-repo-check "
+You are {{worker_name}} ({{worker_id}}).
TASK: {{worker_task}}
1. Search memory: memory_search(query='{{task_keywords}}')
2. Execute your task
-3. Store results: memory_store(key='result-{{session_id}}', namespace='results', upsert=true)
-" --session-id {{session_id}} &
+3. Store results: memory_store(key='result-{{worker_id}}', namespace='results', upsert=true)
+" &
```
## MCP Tool Integration
@@ -129,7 +134,7 @@ TASK: {{worker_task}}
### Initialize Coordination
```javascript
// Initialize swarm tracking
-mcp__ruv-swarm__swarm_init {
+mcp__ruflo__swarm_init {
topology: "hierarchical",
maxAgents: 8,
strategy: "specialized"
@@ -139,7 +144,7 @@ mcp__ruv-swarm__swarm_init {
### Track Worker Status
```javascript
// Store coordination state
-mcp__claude-flow__memory_store {
+mcp__ruflo__memory_store {
key: "coordination/parallel-task",
value: JSON.stringify({
workers: ["worker-1", "worker-2", "worker-3"],
@@ -153,7 +158,7 @@ mcp__claude-flow__memory_store {
### Aggregate Results
```javascript
// Collect all worker results
-mcp__claude-flow__memory_list {
+mcp__ruflo__memory_list {
namespace: "results"
}
```
@@ -165,37 +170,37 @@ mcp__claude-flow__memory_list {
FEATURE="user-auth"
# Initialize
-npx claude-flow@v3alpha swarm init --topology hierarchical --max-agents 4
+npx ruflo@latest swarm init --topology hierarchical --max-agents 4
# Spawn workers in parallel
-claude -p "Architect: Design $FEATURE" --session-id ${FEATURE}-arch &
-claude -p "Coder: Implement $FEATURE" --session-id ${FEATURE}-code &
-claude -p "Tester: Test $FEATURE" --session-id ${FEATURE}-test &
-claude -p "Docs: Document $FEATURE" --session-id ${FEATURE}-docs &
+codex exec --sandbox workspace-write --skip-git-repo-check "Architect: Design $FEATURE. Store result as result-${FEATURE}-arch." &
+codex exec --sandbox workspace-write --skip-git-repo-check "Coder: Implement $FEATURE. Store result as result-${FEATURE}-code." &
+codex exec --sandbox workspace-write --skip-git-repo-check "Tester: Test $FEATURE. Store result as result-${FEATURE}-test." &
+codex exec --sandbox workspace-write --skip-git-repo-check "Docs: Document $FEATURE. Store result as result-${FEATURE}-docs." &
# Wait for all
wait
# Collect results
-npx claude-flow@v3alpha memory list --namespace results
+npx ruflo@latest memory list --namespace results
```
## Best Practices
1. **Size Workers Appropriately**: Each worker should complete in < 5 minutes
-2. **Use Meaningful IDs**: Session IDs should identify the worker's purpose
+2. **Use Meaningful IDs**: result keys should identify the worker's purpose
3. **Share Context**: Store shared context in memory before spawning
-4. **Budget Limits**: Use `--max-budget-usd` to control costs
+4. **Pick a Sandbox**: `workspace-write` for code changes, `read-only` for audits/reviews
5. **Error Handling**: Check for partial failures when collecting results
## Worker Types Reference
| Type | Purpose | Spawn Command |
|------|---------|---------------|
-| `coder` | Implement code | `claude -p "Implement [feature]"` |
-| `tester` | Write tests | `claude -p "Write tests for [module]"` |
-| `reviewer` | Review code | `claude -p "Review [files]"` |
-| `docs` | Documentation | `claude -p "Document [component]"` |
-| `architect` | Design | `claude -p "Design [system]"` |
+| `coder` | Implement code | `codex exec --sandbox workspace-write --skip-git-repo-check "Implement [feature]"` |
+| `tester` | Write tests | `codex exec --sandbox workspace-write --skip-git-repo-check "Write tests for [module]"` |
+| `reviewer` | Review code | `codex exec --sandbox read-only --skip-git-repo-check "Review [files]"` |
+| `docs` | Documentation | `codex exec --sandbox workspace-write --skip-git-repo-check "Document [component]"` |
+| `architect` | Design | `codex exec --sandbox read-only --skip-git-repo-check "Design [system]"` |
Remember: You coordinate, workers execute. Use memory for all communication between processes.
diff --git a/.claude/agents/dual-mode/codex-worker.md b/.claude/agents/dual-mode/codex-worker.md
index 292e9860d3..c9c82d8497 100644
--- a/.claude/agents/dual-mode/codex-worker.md
+++ b/.claude/agents/dual-mode/codex-worker.md
@@ -5,7 +5,13 @@ description: Headless Codex background worker for parallel task execution with s
# Codex Headless Worker
-You are a headless Codex worker executing in background mode. You run independently via `claude -p` and coordinate with other workers through shared memory.
+You are a headless Codex worker executing in background mode. You run independently via `codex exec` and coordinate with other workers through shared memory.
+
+> Spawn syntax: `codex exec --sandbox workspace-write --skip-git-repo-check "<prompt>"`.
+> `codex exec` is non-interactive β€” it runs to completion and prints the agent's final
+> message to stdout. Append `&` to run several workers in parallel. (When the dual-mode
+> orchestrator mixes platforms, *Claude* workers use `claude -p "<prompt>" --output-format text`
+> instead β€” but a `codex-worker` is always launched with `codex exec`.)
## Execution Model
@@ -23,7 +29,8 @@ You are a headless Codex worker executing in background mode. You run independen
β”‚ β”œβ”€ worker-2 ───── Run in parallel β”‚
β”‚ └─ worker-3 β”€β”€β”˜ β”‚
β”‚ β”‚
-β”‚ Each: claude -p "task" --session-id X & β”‚
+β”‚ Each: codex exec --sandbox workspace-write β”‚
+β”‚ --skip-git-repo-check "task" & β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```
@@ -39,7 +46,7 @@ You are a headless Codex worker executing in background mode. You run independen
### Before Starting Task
```javascript
// 1. Search for relevant patterns
-mcp__claude-flow__memory_search {
+mcp__ruflo__memory_search {
query: "keywords from task",
namespace: "patterns",
limit: 5
@@ -52,7 +59,7 @@ mcp__claude-flow__memory_search {
### After Completing Task
```javascript
// 3. Store what worked for future workers
-mcp__claude-flow__memory_store {
+mcp__ruflo__memory_store {
key: "pattern-[task-type]",
value: JSON.stringify({
approach: "what worked",
@@ -63,8 +70,8 @@ mcp__claude-flow__memory_store {
}
// 4. Store result for coordinator
-mcp__claude-flow__memory_store {
- key: "result-[session-id]",
+mcp__ruflo__memory_store {
+ key: "result-[worker-id]",
value: JSON.stringify({
status: "complete",
summary: "what was done"
@@ -78,66 +85,66 @@ mcp__claude-flow__memory_store {
### Basic Worker
```bash
-claude -p "
-You are codex-worker.
+codex exec --sandbox workspace-write --skip-git-repo-check "
+You are codex-worker (worker-1).
TASK: [task description]
1. Search memory for patterns
2. Execute the task
-3. Store results
-" --session-id worker-1 &
+3. Store results in the 'results' namespace
+" &
```
-### With Budget Limit
+### Pin a Model
```bash
-claude -p "Implement user auth" --max-budget-usd 0.50 --session-id auth-worker &
+codex exec --sandbox workspace-write --skip-git-repo-check -m gpt-5.3-codex "Implement user auth" &
```
-### With Specific Tools
+### Read-only Worker (no file writes)
```bash
-claude -p "Write tests for api.ts" --allowedTools "Read,Write,Bash" --session-id test-worker &
+codex exec --sandbox read-only --skip-git-repo-check "Audit src/api.ts for security issues" &
```
## Worker Types
### Coder Worker
```bash
-claude -p "
+codex exec --sandbox workspace-write --skip-git-repo-check "
You are a coder worker.
Implement: [feature]
Path: src/[module]/
Store results when complete.
-" --session-id coder-1 &
+" &
```
### Tester Worker
```bash
-claude -p "
+codex exec --sandbox workspace-write --skip-git-repo-check "
You are a tester worker.
Write tests for: [module]
Path: tests/
Run tests and store coverage results.
-" --session-id tester-1 &
+" &
```
### Documenter Worker
```bash
-claude -p "
+codex exec --sandbox workspace-write --skip-git-repo-check "
You are a documentation writer.
Document: [component]
Output: docs/
Store completion status.
-" --session-id docs-1 &
+" &
```
### Reviewer Worker
```bash
-claude -p "
+codex exec --sandbox read-only --skip-git-repo-check "
You are a code reviewer.
Review: [files]
Check for: security, performance, best practices
Store findings in memory.
-" --session-id reviewer-1 &
+" &
```
## MCP Tool Integration
@@ -145,13 +152,13 @@ Store findings in memory.
### Available Tools
```javascript
// Search for patterns before starting
-mcp__claude-flow__memory_search {
+mcp__ruflo__memory_search {
query: "[task keywords]",
namespace: "patterns"
}
// Store results and patterns
-mcp__claude-flow__memory_store {
+mcp__ruflo__memory_store {
key: "[result-key]",
value: "[json-value]",
namespace: "results",
@@ -159,25 +166,25 @@ mcp__claude-flow__memory_store {
}
// Check swarm status (optional)
-mcp__ruv-swarm__swarm_status {
+mcp__ruflo__swarm_status {
verbose: true
}
```
## Important Notes
-1. **Always Background**: Run with `&` for parallel execution
-2. **Use Session IDs**: Track workers with `--session-id`
-3. **Store Results**: Coordinator needs to collect your output
-4. **Budget Limits**: Use `--max-budget-usd` for cost control
-5. **Upsert Pattern**: Always use `upsert: true` to avoid duplicate key errors
+1. **Always Background**: append `&` so workers run in parallel
+2. **Pick a Sandbox**: `workspace-write` for code changes, `read-only` for audits/reviews
+3. **Store Results**: the coordinator collects your output from the `results` namespace
+4. **Git Check**: `--skip-git-repo-check` lets Codex run outside a git repo
+5. **Upsert Pattern**: always use `upsert: true` to avoid duplicate key errors
## Best Practices
- Keep tasks focused and small (< 5 minutes each)
- Search memory before starting to leverage past patterns
- Store patterns that worked for future workers
-- Use meaningful session IDs for tracking
+- Use a clear worker id in your result keys for tracking
- Store completion status even on partial success
-Remember: You run headlessly in background. The coordinator will collect your results via shared memory.
+Remember: You run headlessly in background. The coordinator collects your results via shared memory.
diff --git a/.github/workflows/codex-integration-audit.yml b/.github/workflows/codex-integration-audit.yml
new file mode 100644
index 0000000000..42968d903d
--- /dev/null
+++ b/.github/workflows/codex-integration-audit.yml
@@ -0,0 +1,41 @@
+name: codex-integration-audit
+
+# Guards the Codex ↔ Ruflo integration invariants (issue #1909):
+# - the `codex` MCP backend uses the real `mcp-server` subcommand
+# - @claude-flow/codex VERSION const tracks its package.json
+# - the dual-mode orchestrator / agent defs drive real `codex exec`
+# - CLI refs are standardized to `ruflo`, `dual run` exposes `--worker`,
+# generated SKILL.md frontmatter is complete, config.toml emits a
+# working `ruflo` MCP server.
+# Pure-Node static checks β€” no install needed. Build + unit tests are
+# covered by the main CI workflow.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'v3/@claude-flow/codex/**'
+ - 'ruflo/src/mcp-bridge/**'
+ - 'ruflo/src/ruvocal/mcp-bridge/**'
+ - '.claude/agents/dual-mode/**'
+ - 'scripts/audit-codex-integration.mjs'
+ - '.github/workflows/codex-integration-audit.yml'
+ pull_request:
+ paths:
+ - 'v3/@claude-flow/codex/**'
+ - 'ruflo/src/mcp-bridge/**'
+ - 'ruflo/src/ruvocal/mcp-bridge/**'
+ - '.claude/agents/dual-mode/**'
+ - 'scripts/audit-codex-integration.mjs'
+ - '.github/workflows/codex-integration-audit.yml'
+
+jobs:
+ audit:
+ name: Codex integration audit
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ - run: node scripts/audit-codex-integration.mjs
diff --git a/ruflo/src/mcp-bridge/index.js b/ruflo/src/mcp-bridge/index.js
index 3c43c680a5..848ce96e5e 100644
--- a/ruflo/src/mcp-bridge/index.js
+++ b/ruflo/src/mcp-bridge/index.js
@@ -256,7 +256,7 @@ const BACKEND_DEFS = [
{ name: "agentic-flow", command: "npx", args: ["-y", "agentic-flow@alpha", "mcp", "start"], groups: ["agentic-flow"] },
{ name: "claude", command: "claude", args: ["mcp", "serve"], groups: ["claude-code"] },
{ name: "gemini-mcp", command: "npx", args: ["-y", "gemini-mcp-server"], groups: ["gemini"] },
- { name: "codex", command: "npx", args: ["-y", "@openai/codex", "mcp", "serve"], groups: ["codex"] },
+ { name: "codex", command: "npx", args: ["-y", "@openai/codex", "mcp-server"], groups: ["codex"] },
];
const mcpBackends = new Map();
diff --git a/ruflo/src/ruvocal/mcp-bridge/index.js b/ruflo/src/ruvocal/mcp-bridge/index.js
index 592809e40f..00cf7f8a0e 100644
--- a/ruflo/src/ruvocal/mcp-bridge/index.js
+++ b/ruflo/src/ruvocal/mcp-bridge/index.js
@@ -261,7 +261,7 @@ const BACKEND_DEFS = [
{ name: "agentic-flow", command: "npx", args: ["-y", "agentic-flow@alpha", "mcp", "start"], groups: ["agentic-flow"] },
{ name: "claude", command: "claude", args: ["mcp", "serve"], groups: ["claude-code"] },
{ name: "gemini-mcp", command: "npx", args: ["-y", "gemini-mcp-server"], groups: ["gemini"] },
- { name: "codex", command: "npx", args: ["-y", "@openai/codex", "mcp", "serve"], groups: ["codex"] },
+ { name: "codex", command: "npx", args: ["-y", "@openai/codex", "mcp-server"], groups: ["codex"] },
];
const mcpBackends = new Map();
diff --git a/scripts/audit-codex-integration.mjs b/scripts/audit-codex-integration.mjs
new file mode 100755
index 0000000000..f8e2f2a85d
--- /dev/null
+++ b/scripts/audit-codex-integration.mjs
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+/**
+ * Codex ↔ Ruflo integration audit (issue #1909).
+ *
+ * Static invariants that must hold for the OpenAI Codex integration to work.
+ * Build + unit tests are covered by the main CI; this guards the
+ * integration-specific contracts that a regular test run won't catch.
+ *
+ * Usage: node scripts/audit-codex-integration.mjs
+ * Exits non-zero on any failure.
+ */
+import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
+import { resolve, dirname, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const read = (p) => readFileSync(resolve(ROOT, p), 'utf8');
+const rel = (p) => relative(ROOT, p);
+
+let failures = 0;
+const C = { g: '\x1b[32m', r: '\x1b[31m', dim: '\x1b[2m', x: '\x1b[0m' };
+const ok = (m) => console.log(` ${C.g}βœ“${C.x} ${m}`);
+const fail = (m) => { console.log(` ${C.r}βœ—${C.x} ${m}`); failures++; };
+const check = (cond, passMsg, failMsg) => (cond ? ok(passMsg) : fail(failMsg ?? passMsg));
+const section = (t) => console.log(`\n${t}`);
+
+console.log('Codex ↔ Ruflo integration audit (#1909)\n' + '─'.repeat(48));
+
+// ── 1. Codex MCP backend uses the real `mcp-server` subcommand ──────────────
+section('MCP backend registration (`codex` group):');
+for (const p of ['ruflo/src/mcp-bridge/index.js', 'ruflo/src/ruvocal/mcp-bridge/index.js']) {
+ if (!existsSync(resolve(ROOT, p))) { fail(`${p}: file missing`); continue; }
+ const src = read(p);
+ const codexLine = (src.match(/.*@openai\/codex.*/g) ?? [])[0]?.trim() ?? '(no @openai/codex entry)';
+ check(/@openai\/codex"\s*,\s*"mcp-server"/.test(src),
+ `${p}: codex backend uses "mcp-server"`,
+ `${p}: codex backend must use "mcp-server" β€” found: ${codexLine}`);
+ check(!/@openai\/codex"\s*,\s*"mcp"\s*,\s*"serve"/.test(src),
+ `${p}: no invalid "mcp serve" subcommand`,
+ `${p}: still uses "mcp serve" (not a valid \`codex\` subcommand) β€” ${codexLine}`);
+}
+
+// ── 2. @claude-flow/codex VERSION const tracks package.json ─────────────────
+section('@claude-flow/codex version sync:');
+const cfPkg = JSON.parse(read('v3/@claude-flow/codex/package.json'));
+const versionMatch = read('v3/@claude-flow/codex/src/index.ts').match(/export const VERSION\s*=\s*'([^']+)'/);
+check(versionMatch && versionMatch[1] === cfPkg.version,
+ `VERSION const === package.json version ("${cfPkg.version}")`,
+ `VERSION const (${versionMatch ? `"${versionMatch[1]}"` : 'not found'}) != package.json ("${cfPkg.version}")`);
+
+// ── 3. Dual-mode orchestrator drives a real `codex exec` for codex workers ──
+section('Dual-mode orchestrator:');
+const orch = read('v3/@claude-flow/codex/src/dual-mode/orchestrator.ts');
+check(/codexCommand:\s*config\.codexCommand\s*\?\?\s*'codex'/.test(orch),
+ `codexCommand defaults to 'codex'`,
+ `codexCommand must default to 'codex' (it was 'claude' β€” "Both use claude CLI")`);
+check(!/codexCommand:\s*config\.codexCommand\s*\?\?\s*'claude'/.test(orch),
+ `codexCommand no longer falls back to 'claude'`);
+check(/\['exec',\s*'--sandbox'/.test(orch),
+ `codex workers spawn \`codex exec --sandbox …\``,
+ `codex worker branch must build \`['exec', '--sandbox', …]\` args`);
+
+// ── 4. Dual-mode agent defs invoke `codex exec`, not `claude -p` ────────────
+section('Dual-mode agent definitions:');
+for (const p of ['.claude/agents/dual-mode/codex-worker.md', '.claude/agents/dual-mode/codex-coordinator.md']) {
+ if (!existsSync(resolve(ROOT, p))) { fail(`${p}: file missing`); continue; }
+ const src = read(p);
+ check(/codex exec /.test(src), `${p}: references \`codex exec\``);
+ // The legacy worker examples all used `claude -p "<task>" --session-id <id>`.
+ // (A generic `claude -p "<prompt>"` mention in the mixed-platform note is fine.)
+ check(!/--session-id/.test(src) && !/(via|using) `claude -p`/.test(src),
+ `${p}: no legacy \`claude -p … --session-id\` worker spawns`,
+ `${p}: still uses the legacy \`claude -p\` worker pattern (should be \`codex exec\`)`);
+}
+
+// ── 5. No stale claude-flow CLI refs left in the codex package source ───────
+section('CLI references standardized to ruflo:');
+const walk = (dir) => readdirSync(dir).flatMap((e) => {
+ const f = resolve(dir, e);
+ return statSync(f).isDirectory() ? walk(f) : [f];
+});
+const stale = walk(resolve(ROOT, 'v3/@claude-flow/codex/src'))
+ .filter((f) => f.endsWith('.ts'))
+ .filter((f) => /claude-flow@alpha|@claude-flow\/cli@latest/.test(readFileSync(f, 'utf8')))
+ .map(rel);
+check(stale.length === 0,
+ `no \`claude-flow@alpha\` / \`@claude-flow/cli@latest\` in codex src`,
+ `stale CLI refs remain in: ${stale.join(', ')}`);
+
+// ── 6. `dual run` CLI surface (W2) ─────────────────────────────────────────
+section('`dual run` CLI surface:');
+const dualCli = read('v3/@claude-flow/codex/src/dual-mode/cli.ts');
+check(/'-w, --worker <spec>'/.test(dualCli), `\`dual run\` exposes \`--worker <spec>\``);
+check(/\.argument\('\[template\]'/.test(dualCli), `\`dual run\` accepts positional \`[template]\``);
+check(/export function parseWorkerSpecs/.test(dualCli), `\`parseWorkerSpecs\` exported (so it's unit-testable)`);
+
+// ── 7. Generated SKILL.md frontmatter (W5) ─────────────────────────────────
+section('SKILL.md generator frontmatter:');
+const skillGen = read('v3/@claude-flow/codex/src/generators/skill-md.ts');
+check(/version: "\$\{version\}"/.test(skillGen) && /author: \$\{author\}/.test(skillGen) && /tags: \[\$\{tagList/.test(skillGen),
+ `generateSkillMd emits version/author/tags frontmatter`,
+ `generateSkillMd must emit version/author/tags so generated skills validate clean`);
+
+// ── 8. config.toml generator emits a working `ruflo` MCP server ────────────
+section('config.toml generator MCP default:');
+const cfgGen = read('v3/@claude-flow/codex/src/generators/config-toml.ts');
+check(/name:\s*'ruflo'/.test(cfgGen) && /args:\s*\['-y',\s*'ruflo@latest',\s*'mcp',\s*'start'\]/.test(cfgGen),
+ `default MCP server is \`ruflo\` with \`mcp start\` subcommand`,
+ `default MCP server must be \`{ name: 'ruflo', args: ['-y','ruflo@latest','mcp','start'] }\` (was \`claude-flow\` w/o \`mcp start\`)`);
+
+console.log('\n' + '─'.repeat(48));
+if (failures > 0) {
+ console.error(`${C.r}${failures} check(s) failed${C.x}`);
+ process.exit(1);
+}
+console.log(`${C.g}All codex-integration checks passed${C.x}`);
diff --git a/v3/@claude-flow/codex/README.md b/v3/@claude-flow/codex/README.md
index e848a5309c..506e8705ef 100644
--- a/v3/@claude-flow/codex/README.md
+++ b/v3/@claude-flow/codex/README.md
@@ -7,7 +7,7 @@
<p align="center">
<a href="https://www.npmjs.com/package/@claude-flow/codex"><img src="https://img.shields.io/npm/v/@claude-flow/codex?label=npm&color=blue" alt="npm version"></a>
- <a href="https://github.com/ruvnet/claude-flow"><img src="https://img.shields.io/badge/license-MIT-green" alt="license"></a>
+ <a href="https://github.com/ruvnet/ruflo"><img src="https://img.shields.io/badge/license-MIT-green" alt="license"></a>
<a href="https://agentics.org"><img src="https://img.shields.io/badge/standard-Agentics-purple" alt="Agentics Standard"></a>
</p>
@@ -653,6 +653,25 @@ npx claude-flow-codex dual run --template refactor --task "src/legacy/"
npx claude-flow-codex dual status
```
+### Codex Loop Runner
+
+Codex does not expose Claude Code's `ScheduleWakeup`, so `@claude-flow/codex` provides a process-based equivalent:
+
+```bash
+# Run Codex repeatedly until it creates .codex/loop/default.complete or reaches 10 iterations
+npx claude-flow-codex loop run "Fix failing tests and create the completion marker when done"
+
+# Use command mode for recurring Ruflo workers or custom scripts
+npx claude-flow-codex loop run --name testgaps --interval 270 --max-iterations 0 \
+ --command "npx claude-flow hooks worker dispatch --trigger testgaps"
+
+# Inspect or stop a loop from another terminal
+npx claude-flow-codex loop status --name testgaps
+npx claude-flow-codex loop stop --name testgaps
+```
+
+Loop state is stored in `.codex/loop/<name>.json`; `loop stop` writes `.codex/loop/<name>.stop`, which the runner observes between iterations.
+
### Pre-Built Templates
| Template | Pipeline | Platforms |
@@ -1020,5 +1039,5 @@ MIT
## Support
-- Documentation: https://github.com/ruvnet/claude-flow
-- Issues: https://github.com/ruvnet/claude-flow/issues
+- Documentation: https://github.com/ruvnet/ruflo
+- Issues: https://github.com/ruvnet/ruflo/issues
diff --git a/v3/@claude-flow/codex/package.json b/v3/@claude-flow/codex/package.json
index c24769cd3a..7e4834a44e 100644
--- a/v3/@claude-flow/codex/package.json
+++ b/v3/@claude-flow/codex/package.json
@@ -1,7 +1,7 @@
{
"name": "@claude-flow/codex",
"version": "3.0.0-alpha.9",
- "description": "Codex CLI integration for Claude Flow - OpenAI Codex platform adapter",
+ "description": "Codex CLI integration for Ruflo (claude-flow) - OpenAI Codex platform adapter",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -34,11 +34,15 @@
"types": "./dist/dual-mode/index.d.ts",
"import": "./dist/dual-mode/index.js",
"require": "./dist/dual-mode/index.js"
+ },
+ "./loop": {
+ "types": "./dist/loop/index.d.ts",
+ "import": "./dist/loop/index.js",
+ "require": "./dist/loop/index.js"
}
},
"files": [
- "dist",
- "templates"
+ "dist"
],
"scripts": {
"build": "tsc",
@@ -61,12 +65,12 @@
"license": "MIT",
"repository": {
"type": "git",
- "url": "https://github.com/ruvnet/claude-flow.git",
+ "url": "https://github.com/ruvnet/ruflo.git",
"directory": "v3/@claude-flow/codex"
},
- "homepage": "https://github.com/ruvnet/claude-flow#readme",
+ "homepage": "https://github.com/ruvnet/ruflo#readme",
"bugs": {
- "url": "https://github.com/ruvnet/claude-flow/issues"
+ "url": "https://github.com/ruvnet/ruflo/issues"
},
"engines": {
"node": ">=18"
diff --git a/v3/@claude-flow/codex/src/cli.ts b/v3/@claude-flow/codex/src/cli.ts
index 5c0b85b40c..143ddcb517 100644
--- a/v3/@claude-flow/codex/src/cli.ts
+++ b/v3/@claude-flow/codex/src/cli.ts
@@ -692,6 +692,10 @@ program
import { createDualModeCommand } from './dual-mode/index.js';
program.addCommand(createDualModeCommand());
+// Codex /loop-compatible runner
+import { createLoopCommand } from './loop/cli.js';
+program.addCommand(createLoopCommand());
+
// Error handling for unknown commands
program.on('command:*', () => {
console.error(chalk.red(`Invalid command: ${program.args.join(' ')}`));
diff --git a/v3/@claude-flow/codex/src/dual-mode/cli.ts b/v3/@claude-flow/codex/src/dual-mode/cli.ts
index f1ddab6068..f17eb36670 100644
--- a/v3/@claude-flow/codex/src/dual-mode/cli.ts
+++ b/v3/@claude-flow/codex/src/dual-mode/cli.ts
@@ -32,13 +32,21 @@ export function createDualModeCommand(): Command {
function createRunCommand(): Command {
return new Command('run')
.description('Run a collaborative dual-mode swarm')
+ .argument('[template]', 'Pre-built template name (feature, security, refactor) β€” positional alias for --template')
.option('-t, --template <name>', 'Use a pre-built template (feature, security, refactor)')
+ .option(
+ '-w, --worker <spec>',
+ 'Worker spec "<platform>:<role>:<prompt>" (platform = claude|codex). Repeatable. Workers chain sequentially unless --parallel-workers.',
+ (val: string, acc: string[]) => { acc.push(val); return acc; },
+ [] as string[],
+ )
+ .option('--parallel-workers', 'Run --worker specs in parallel instead of chaining them sequentially', false)
.option('-c, --config <path>', 'Path to collaboration config JSON')
.option('--task <description>', 'Task description for the swarm')
.option('--max-concurrent <n>', 'Maximum concurrent workers', '4')
.option('--timeout <ms>', 'Worker timeout in milliseconds', '300000')
.option('--namespace <name>', 'Shared memory namespace', 'collaboration')
- .action(async (options) => {
+ .action(async (templateArg: string | undefined, options) => {
console.log(chalk.cyan('═══════════════════════════════════════════════════════════════'));
console.log(chalk.cyan.bold(' DUAL-MODE COLLABORATIVE EXECUTION'));
console.log(chalk.cyan(' Claude Code + Codex workers with shared memory'));
@@ -75,21 +83,30 @@ function createRunCommand(): Command {
let workers: WorkerConfig[];
let taskContext: string;
- if (options.template) {
+ const workerSpecs: string[] = (options.worker as string[] | undefined) ?? [];
+ const templateName: string | undefined = options.template ?? templateArg;
+
+ if (workerSpecs.length > 0) {
+ workers = parseWorkerSpecs(workerSpecs, options.parallelWorkers === true);
+ taskContext = options.task || `Custom dual-mode swarm: ${workers.map(w => `${w.platform}:${w.role}`).join(' -> ')}`;
+ } else if (templateName) {
const task = options.task || 'Complete the assigned task';
- workers = getTemplateWorkers(options.template, task);
- taskContext = `Template: ${options.template}, Task: ${task}`;
+ workers = getTemplateWorkers(templateName, task);
+ taskContext = `Template: ${templateName}, Task: ${task}`;
} else if (options.config) {
const configData = await import(options.config);
workers = configData.workers;
taskContext = configData.taskContext || options.task || 'Collaborative task';
} else {
- console.log(chalk.yellow('Please specify --template or --config'));
+ console.log(chalk.yellow('Please specify --template <name>, a [template] argument, --worker <spec> (repeatable), or --config <path>'));
+ console.log();
+ console.log('Templates:');
+ console.log(' feature - Feature development (architect -> coder -> tester -> reviewer)');
+ console.log(' security - Security audit (scanner -> analyzer -> fixer)');
+ console.log(' refactor - Code refactoring (analyzer -> planner -> refactorer -> validator)');
console.log();
- console.log('Available templates:');
- console.log(' feature - Feature development (architect β†’ coder β†’ tester β†’ reviewer)');
- console.log(' security - Security audit (scanner β†’ analyzer β†’ fixer)');
- console.log(' refactor - Code refactoring (analyzer β†’ planner β†’ refactorer β†’ validator)');
+ console.log('Custom workers:');
+ console.log(' --worker "claude:architect:Design the API" --worker "codex:coder:Implement it"');
return;
}
@@ -170,7 +187,7 @@ function createStatusCommand(): Command {
const { spawn } = await import('child_process');
const proc = spawn('npx', [
- 'claude-flow@alpha', 'memory', 'list',
+ 'ruflo@alpha', 'memory', 'list',
'--namespace', options.namespace
], { stdio: 'inherit' });
@@ -180,6 +197,50 @@ function createStatusCommand(): Command {
});
}
+/**
+ * Parse `--worker "<platform>:<role>:<prompt>"` specs into WorkerConfig[].
+ * Splits on the first two `:` so the prompt may itself contain colons.
+ * Workers chain sequentially (each depends on the previous) unless `parallel`.
+ */
+export function parseWorkerSpecs(specs: string[], parallel: boolean): WorkerConfig[] {
+ const usedIds = new Set<string>();
+ const workers: WorkerConfig[] = [];
+
+ specs.forEach((spec, index) => {
+ const firstColon = spec.indexOf(':');
+ const secondColon = firstColon >= 0 ? spec.indexOf(':', firstColon + 1) : -1;
+ if (firstColon < 0 || secondColon < 0) {
+ throw new Error(`Invalid --worker spec "${spec}". Expected "<platform>:<role>:<prompt>" (platform = claude|codex).`);
+ }
+ const platformRaw = spec.slice(0, firstColon).trim().toLowerCase();
+ const role = spec.slice(firstColon + 1, secondColon).trim() || `worker-${index + 1}`;
+ const prompt = spec.slice(secondColon + 1).trim();
+ if (!prompt) {
+ throw new Error(`Invalid --worker spec "${spec}". Missing prompt after "<platform>:<role>:".`);
+ }
+ if (platformRaw !== 'claude' && platformRaw !== 'codex') {
+ throw new Error(`Invalid platform "${platformRaw}" in --worker spec "${spec}". Use "claude" or "codex".`);
+ }
+ const platform: 'claude' | 'codex' = platformRaw;
+
+ // Derive a unique id from the role.
+ const base = role.replace(/\s+/g, '-');
+ let id = base;
+ let suffix = 2;
+ while (usedIds.has(id)) { id = `${base}-${suffix++}`; }
+ usedIds.add(id);
+
+ const worker: WorkerConfig = { id, platform, role, prompt };
+ const prev = workers[workers.length - 1];
+ if (!parallel && prev) {
+ worker.dependsOn = [prev.id];
+ }
+ workers.push(worker);
+ });
+
+ return workers;
+}
+
/**
* Get workers for a template
*/
@@ -227,5 +288,5 @@ function printResults(result: CollaborationResult): void {
}
console.log();
- console.log(chalk.gray('View shared memory: npx claude-flow@alpha memory list --namespace collaboration'));
+ console.log(chalk.gray('View shared memory: npx ruflo@alpha memory list --namespace collaboration'));
}
diff --git a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts b/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts
index f6504032a4..0f15514cb6 100644
--- a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts
+++ b/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts
@@ -64,7 +64,7 @@ export class DualModeOrchestrator extends EventEmitter {
sharedNamespace: config.sharedNamespace ?? 'collaboration',
timeout: config.timeout ?? 300000, // 5 minutes
claudeCommand: config.claudeCommand ?? 'claude',
- codexCommand: config.codexCommand ?? 'claude', // Both use claude CLI
+ codexCommand: config.codexCommand ?? 'codex',
};
}
@@ -77,7 +77,7 @@ export class DualModeOrchestrator extends EventEmitter {
// Initialize memory database
await this.runCommand(
'npx',
- ['claude-flow@alpha', 'memory', 'init', '--force'],
+ ['ruflo@alpha', 'memory', 'init', '--force'],
projectPath
);
@@ -85,7 +85,7 @@ export class DualModeOrchestrator extends EventEmitter {
await this.runCommand(
'npx',
[
- 'claude-flow@alpha', 'memory', 'store',
+ 'ruflo@alpha', 'memory', 'store',
'--key', 'task-context',
'--value', taskContext,
'--namespace', sharedNamespace
@@ -142,17 +142,25 @@ export class DualModeOrchestrator extends EventEmitter {
// Build the prompt with memory integration
const enhancedPrompt = this.buildCollaborativePrompt(config);
- const args = [
- '-p', enhancedPrompt,
- '--output-format', 'text',
- ];
-
- if (config.maxTurns) {
- args.push('--max-turns', String(config.maxTurns));
- }
-
- if (config.model) {
- args.push('--model', config.model);
+ // Each platform has its own non-interactive entry point and flag set:
+ // Claude Code: claude -p <prompt> --output-format text [--max-turns N] [--model M]
+ // OpenAI Codex: codex exec --sandbox workspace-write --skip-git-repo-check [-m M] <prompt>
+ // (`codex exec` runs autonomously; PROMPT is a positional arg and must come last.)
+ let args: string[];
+ if (config.platform === 'claude') {
+ args = ['-p', enhancedPrompt, '--output-format', 'text'];
+ if (config.maxTurns) {
+ args.push('--max-turns', String(config.maxTurns));
+ }
+ if (config.model) {
+ args.push('--model', config.model);
+ }
+ } else {
+ args = ['exec', '--sandbox', 'workspace-write', '--skip-git-repo-check'];
+ if (config.model) {
+ args.push('-m', config.model);
+ }
+ args.push(enhancedPrompt);
}
return new Promise((resolve, reject) => {
@@ -211,9 +219,9 @@ Working Directory: ${projectPath}
Shared Memory Namespace: ${sharedNamespace}
COLLABORATION PROTOCOL:
-1. Search shared memory for context: npx claude-flow@alpha memory search --query "<relevant terms>" --namespace ${sharedNamespace}
+1. Search shared memory for context: npx ruflo@alpha memory search --query "<relevant terms>" --namespace ${sharedNamespace}
2. Complete your assigned task
-3. Store your results: npx claude-flow@alpha memory store --key "${config.id}-result" --value "<your summary>" --namespace ${sharedNamespace}
+3. Store your results: npx ruflo@alpha memory store --key "${config.id}-result" --value "<your summary>" --namespace ${sharedNamespace}
YOUR TASK:
${config.prompt}
@@ -330,7 +338,7 @@ Remember: Other agents depend on your results in shared memory. Be concise and s
try {
const output = await this.runCommand(
'npx',
- ['claude-flow@alpha', 'memory', 'list', '--namespace', sharedNamespace, '--format', 'json'],
+ ['ruflo@alpha', 'memory', 'list', '--namespace', sharedNamespace, '--format', 'json'],
projectPath
);
return JSON.parse(output);
diff --git a/v3/@claude-flow/codex/src/generators/agents-md.ts b/v3/@claude-flow/codex/src/generators/agents-md.ts
index f65d1c4593..0b1a219dc1 100644
--- a/v3/@claude-flow/codex/src/generators/agents-md.ts
+++ b/v3/@claude-flow/codex/src/generators/agents-md.ts
@@ -85,7 +85,7 @@ ${testCommand}
## Links
-- Documentation: https://github.com/ruvnet/claude-flow
+- Documentation: https://github.com/ruvnet/ruflo
`;
}
@@ -279,8 +279,8 @@ npx @claude-flow/cli hooks pre-task --description "task summary"
## Links
-- Documentation: https://github.com/ruvnet/claude-flow
-- Issues: https://github.com/ruvnet/claude-flow/issues
+- Documentation: https://github.com/ruvnet/ruflo
+- Issues: https://github.com/ruvnet/ruflo/issues
`;
}
@@ -336,10 +336,10 @@ Claude Flow exposes tools via Model Context Protocol:
\`\`\`bash
# Start MCP server
-npx @claude-flow/cli mcp start
+npx ruflo mcp start
# List available tools
-npx @claude-flow/cli mcp tools
+npx ruflo mcp tools
\`\`\`
### Available Tools
diff --git a/v3/@claude-flow/codex/src/generators/config-toml.ts b/v3/@claude-flow/codex/src/generators/config-toml.ts
index a5091ec4f7..7f2b4a4a99 100644
--- a/v3/@claude-flow/codex/src/generators/config-toml.ts
+++ b/v3/@claude-flow/codex/src/generators/config-toml.ts
@@ -79,7 +79,7 @@ export async function generateConfigToml(options: ExtendedConfigTomlOptions = {}
lines.push('# Claude Flow V3 - Codex Configuration');
lines.push('# =============================================================================');
lines.push('# Generated by: @claude-flow/codex');
- lines.push('# Documentation: https://github.com/ruvnet/claude-flow');
+ lines.push('# Documentation: https://github.com/ruvnet/ruflo');
lines.push('# ');
lines.push('# This file configures the Codex CLI for Claude Flow integration.');
lines.push('# Place in .agents/config.toml (project) or .codex/config.toml (user).');
@@ -156,12 +156,12 @@ export async function generateConfigToml(options: ExtendedConfigTomlOptions = {}
lines.push('');
// Default claude-flow server
- const hasClaudeFlow = mcpServers.some(s => s.name === 'claude-flow');
- if (!hasClaudeFlow) {
+ const hasRuflo = mcpServers.some(s => s.name === 'ruflo' || s.name === 'claude-flow');
+ if (!hasRuflo) {
lines.push(...generateMcpServer({
- name: 'claude-flow',
+ name: 'ruflo',
command: 'npx',
- args: ['-y', '@claude-flow/cli@latest'],
+ args: ['-y', 'ruflo@latest', 'mcp', 'start'],
enabled: true,
toolTimeout: 120,
}));
@@ -532,9 +532,9 @@ model = "${model}"
approval_policy = "${approvalPolicy}"
sandbox_mode = "${sandboxMode}"
-[mcp_servers.claude-flow]
+[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "@claude-flow/cli@latest"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
`;
}
@@ -565,9 +565,9 @@ remote_compaction = false
child_agents_md = true
request_rule = false
-[mcp_servers.claude-flow]
+[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "@claude-flow/cli@latest"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
tool_timeout_sec = 300
@@ -643,13 +643,13 @@ remote_compaction = true
# MCP Servers
# =============================================================================
-[mcp_servers.claude-flow]
+[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "@claude-flow/cli@latest"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
tool_timeout_sec = 120
-[mcp_servers.claude-flow.env]
+[mcp_servers.ruflo.env]
CLAUDE_FLOW_LOG_LEVEL = "info"
# =============================================================================
@@ -848,9 +848,9 @@ shell_snapshot = true
request_rule = false
remote_compaction = true
-[mcp_servers.claude-flow]
+[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "@claude-flow/cli@latest"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
tool_timeout_sec = 120
@@ -929,9 +929,9 @@ shell_snapshot = false
request_rule = true
remote_compaction = false
-[mcp_servers.claude-flow]
+[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "@claude-flow/cli@latest"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
tool_timeout_sec = 60
diff --git a/v3/@claude-flow/codex/src/generators/skill-md.ts b/v3/@claude-flow/codex/src/generators/skill-md.ts
index 36a82ba574..8d6beb9f83 100644
--- a/v3/@claude-flow/codex/src/generators/skill-md.ts
+++ b/v3/@claude-flow/codex/src/generators/skill-md.ts
@@ -14,6 +14,9 @@ export async function generateSkillMd(options: SkillMdOptions): Promise<string>
const {
name,
description,
+ version = '1.0.0',
+ author = 'rUv',
+ tags,
triggers = [],
skipWhen = [],
scripts = [],
@@ -21,6 +24,9 @@ export async function generateSkillMd(options: SkillMdOptions): Promise<string>
commands = [],
} = options;
+ // Derive discovery tags from the skill name when not supplied explicitly.
+ const tagList = tags && tags.length > 0 ? tags : name.split('-').filter(Boolean);
+
// Build YAML frontmatter
const triggerText = triggers.length > 0
? `Use when: ${triggers.join(', ')}.`
@@ -31,6 +37,9 @@ export async function generateSkillMd(options: SkillMdOptions): Promise<string>
const frontmatter = `---
name: ${name}
+version: "${version}"
+author: ${author}
+tags: [${tagList.join(', ')}]
description: >
${description}
${triggerText}
@@ -167,8 +176,8 @@ export async function generateBuiltInSkill(
{
name: 'Initialize Swarm',
description: 'Start a new swarm with hierarchical topology (anti-drift)',
- command: 'npx @claude-flow/cli swarm init --topology hierarchical --max-agents 8 --strategy specialized',
- example: 'npx @claude-flow/cli swarm init --topology hierarchical --max-agents 6 --strategy specialized',
+ command: 'npx ruflo swarm init --topology hierarchical --max-agents 8 --strategy specialized',
+ example: 'npx ruflo swarm init --topology hierarchical --max-agents 6 --strategy specialized',
},
{
name: 'Route Task',
@@ -719,7 +728,7 @@ function generateHelperScript(skillName: string, scriptName: string): string {
set -e
echo "Initializing hierarchical swarm..."
-npx @claude-flow/cli swarm init \\
+npx ruflo swarm init \\
--topology hierarchical \\
--max-agents 8 \\
--strategy specialized
diff --git a/v3/@claude-flow/codex/src/index.ts b/v3/@claude-flow/codex/src/index.ts
index f456efbc18..d3527106be 100644
--- a/v3/@claude-flow/codex/src/index.ts
+++ b/v3/@claude-flow/codex/src/index.ts
@@ -47,6 +47,18 @@ export { CodexInitializer, initializeCodexProject } from './initializer.js';
export { DualModeOrchestrator, CollaborationTemplates, createDualModeCommand } from './dual-mode/index.js';
export type { DualModeConfig, WorkerConfig, WorkerResult, CollaborationResult } from './dual-mode/index.js';
+// Codex /loop-compatible runner
+export {
+ buildCodexLoopPrompt,
+ loadLoopState,
+ normalizeLoopName,
+ requestLoopStop,
+ resolveLoopPaths,
+ runCodexLoop,
+} from './loop/index.js';
+export { createLoopCommand } from './loop/cli.js';
+export type { LoopCommandResult, LoopEvent, LoopPaths, LoopRunOptions, LoopState } from './loop/index.js';
+
// Template utilities
export {
getTemplate,
@@ -63,7 +75,7 @@ export {
/**
* Package version
*/
-export const VERSION = '3.0.0-alpha.8';
+export const VERSION = '3.0.0-alpha.9';
/**
* Package metadata
@@ -73,7 +85,7 @@ export const PACKAGE_INFO = {
version: VERSION,
description: 'Codex CLI integration for Claude Flow',
futureUmbrella: 'coflow',
- repository: 'https://github.com/ruvnet/claude-flow',
+ repository: 'https://github.com/ruvnet/ruflo',
} as const;
/**
diff --git a/v3/@claude-flow/codex/src/initializer.ts b/v3/@claude-flow/codex/src/initializer.ts
index 11bb43e29b..871438ed00 100644
--- a/v3/@claude-flow/codex/src/initializer.ts
+++ b/v3/@claude-flow/codex/src/initializer.ts
@@ -152,7 +152,7 @@ export class CodexInitializer {
// Register MCP server with Codex
const mcpResult = await this.registerMCPServer();
if (mcpResult.registered) {
- filesCreated.push('MCP server (claude-flow) registered');
+ filesCreated.push('MCP server (ruflo) registered');
}
if (mcpResult.warning) {
warnings.push(mcpResult.warning);
@@ -326,14 +326,14 @@ export class CodexInitializer {
} catch {
return {
registered: false,
- warning: 'Codex CLI not found. Run: codex mcp add claude-flow -- npx claude-flow mcp start',
+ warning: 'Codex CLI not found. Run: codex mcp add ruflo -- npx ruflo mcp start',
};
}
// Check if already registered
try {
const list = execSync('codex mcp list 2>&1', { encoding: 'utf-8' });
- if (list.includes('claude-flow')) {
+ if (list.includes('ruflo')) {
return { registered: true }; // Already registered
}
} catch {
@@ -342,7 +342,7 @@ export class CodexInitializer {
// Register the MCP server
try {
- execSync('codex mcp add claude-flow -- npx claude-flow mcp start', {
+ execSync('codex mcp add ruflo -- npx ruflo mcp start', {
stdio: 'pipe',
timeout: 10000,
});
@@ -351,13 +351,13 @@ export class CodexInitializer {
const errorMessage = err instanceof Error ? err.message : String(err);
return {
registered: false,
- warning: `Failed to register MCP server: ${errorMessage}. Run manually: codex mcp add claude-flow -- npx claude-flow mcp start`,
+ warning: `Failed to register MCP server: ${errorMessage}. Run manually: codex mcp add ruflo -- npx ruflo mcp start`,
};
}
} catch {
return {
registered: false,
- warning: 'Could not register MCP server. Run manually: codex mcp add claude-flow -- npx claude-flow mcp start',
+ warning: 'Could not register MCP server. Run manually: codex mcp add ruflo -- npx ruflo mcp start',
};
}
}
@@ -541,7 +541,7 @@ Skills are invoked using \`$skill-name\` syntax. Each skill has:
- Main instructions: \`AGENTS.md\` (project root)
- Local overrides: \`.codex/AGENTS.override.md\` (gitignored)
-- Claude Flow: https://github.com/ruvnet/claude-flow
+- Ruflo: https://github.com/ruvnet/ruflo
`;
}
@@ -614,7 +614,7 @@ ${this.skills.map(s => `- \`$${s}\` (Codex) / \`/${s}\` (Claude Code)`).join('\n
\`\`\`bash
# Start MCP server
-npx @claude-flow/cli mcp start
+npx ruflo mcp start
\`\`\`
## Swarm Orchestration
diff --git a/v3/@claude-flow/codex/src/loop/cli.ts b/v3/@claude-flow/codex/src/loop/cli.ts
new file mode 100644
index 0000000000..5ff25691fd
--- /dev/null
+++ b/v3/@claude-flow/codex/src/loop/cli.ts
@@ -0,0 +1,130 @@
+import { Command } from 'commander';
+import chalk from 'chalk';
+import path from 'node:path';
+import {
+ loadLoopState,
+ requestLoopStop,
+ resolveLoopPaths,
+ runCodexLoop,
+ type LoopState,
+} from './index.js';
+
+export function createLoopCommand(): Command {
+ const loop = new Command('loop')
+ .description('Run Codex in a bounded /loop-compatible iteration cycle');
+
+ loop
+ .command('run')
+ .description('Start a Codex loop')
+ .argument('[prompt...]', 'Prompt for Codex. Omit when using --command.')
+ .option('-n, --name <name>', 'Loop name', 'default')
+ .option('-p, --path <path>', 'Project path', process.cwd())
+ .option('-i, --interval <seconds>', 'Seconds between iterations', '270')
+ .option('-m, --max-iterations <count>', 'Maximum iterations; 0 means unbounded', '10')
+ .option('--timeout <ms>', 'Per-iteration timeout in milliseconds', '1800000')
+ .option('--until-file <path>', 'Stop when this file exists. Defaults to .codex/loop/<name>.complete')
+ .option('--command <command>', 'Run a shell command each iteration instead of codex exec')
+ .option('--codex-command <command>', 'Codex executable', 'codex')
+ .option('--model <model>', 'Model passed to codex exec')
+ .option('--sandbox <mode>', 'Sandbox passed to codex exec', 'workspace-write')
+ .option('--no-skip-git-repo-check', 'Do not pass --skip-git-repo-check to codex exec')
+ .option('--dry-run', 'Write planned state and print what would run without executing')
+ .action(async (promptParts: string[], options) => {
+ try {
+ const prompt = promptParts.join(' ').trim();
+ const state = await runCodexLoop({
+ name: options.name,
+ projectPath: options.path,
+ prompt,
+ command: options.command,
+ codexCommand: options.codexCommand,
+ model: options.model,
+ sandbox: options.sandbox,
+ skipGitRepoCheck: options.skipGitRepoCheck,
+ intervalSeconds: parseInteger(options.interval, 270),
+ maxIterations: parseInteger(options.maxIterations, 10),
+ timeoutMs: parseInteger(options.timeout, 1_800_000),
+ untilFile: options.untilFile,
+ dryRun: options.dryRun,
+ onEvent: event => {
+ if (event.type === 'iteration-start') {
+ console.log(chalk.cyan(`iteration ${event.state.iteration} starting`));
+ } else if (event.type === 'iteration-complete') {
+ console.log(chalk.gray(event.message ?? `iteration ${event.state.iteration} complete`));
+ } else if (event.type === 'sleep') {
+ console.log(chalk.gray(event.message));
+ } else if (event.type === 'error') {
+ console.log(chalk.red(event.message));
+ }
+ },
+ });
+
+ printState(state);
+ if (state.status === 'failed') process.exitCode = 1;
+ } catch (error) {
+ console.error(chalk.red(error instanceof Error ? error.message : String(error)));
+ process.exitCode = 1;
+ }
+ });
+
+ loop
+ .command('status')
+ .description('Show loop state')
+ .option('-n, --name <name>', 'Loop name', 'default')
+ .option('-p, --path <path>', 'Project path', process.cwd())
+ .option('--json', 'Print raw JSON state')
+ .action(async (options) => {
+ const projectPath = path.resolve(options.path);
+ const state = await loadLoopState(projectPath, options.name);
+ if (!state) {
+ const paths = resolveLoopPaths(projectPath, options.name);
+ console.log(chalk.yellow(`No loop state found at ${paths.statePath}`));
+ return;
+ }
+ if (options.json) {
+ console.log(JSON.stringify(state, null, 2));
+ return;
+ }
+ printState(state);
+ });
+
+ loop
+ .command('stop')
+ .description('Request a running loop to stop after the current iteration')
+ .option('-n, --name <name>', 'Loop name', 'default')
+ .option('-p, --path <path>', 'Project path', process.cwd())
+ .action(async (options) => {
+ const projectPath = path.resolve(options.path);
+ const paths = await requestLoopStop(projectPath, options.name);
+ console.log(chalk.green(`Stop requested: ${paths.stopPath}`));
+ });
+
+ return loop;
+}
+
+function printState(state: LoopState): void {
+ const color = state.status === 'failed'
+ ? chalk.red
+ : state.status === 'running'
+ ? chalk.cyan
+ : chalk.green;
+
+ console.log(color(`Loop ${state.name}: ${state.status}`));
+ console.log(chalk.gray(` mode: ${state.mode}`));
+ console.log(chalk.gray(` iteration: ${state.iteration}/${state.maxIterations === 0 ? 'unbounded' : state.maxIterations}`));
+ console.log(chalk.gray(` interval: ${state.intervalSeconds}s`));
+ console.log(chalk.gray(` until file: ${state.untilFile}`));
+ if (state.lastExitCode !== undefined) {
+ console.log(chalk.gray(` last exit: ${state.lastExitCode}`));
+ }
+ if (state.lastError) {
+ console.log(chalk.red(` last error: ${state.lastError.split('\n')[0]}`));
+ }
+}
+
+function parseInteger(value: string | number | undefined, fallback: number): number {
+ if (typeof value === 'number') return value;
+ if (!value) return fallback;
+ const parsed = Number.parseInt(value, 10);
+ return Number.isFinite(parsed) ? parsed : fallback;
+}
diff --git a/v3/@claude-flow/codex/src/loop/index.ts b/v3/@claude-flow/codex/src/loop/index.ts
new file mode 100644
index 0000000000..dd9cd51413
--- /dev/null
+++ b/v3/@claude-flow/codex/src/loop/index.ts
@@ -0,0 +1,310 @@
+import { spawn } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import fs from 'fs-extra';
+import path from 'node:path';
+
+export interface LoopRunOptions {
+ name?: string;
+ projectPath?: string;
+ prompt?: string;
+ command?: string;
+ codexCommand?: string;
+ model?: string;
+ intervalSeconds?: number;
+ maxIterations?: number;
+ timeoutMs?: number;
+ untilFile?: string;
+ stateDir?: string;
+ sandbox?: string;
+ skipGitRepoCheck?: boolean;
+ dryRun?: boolean;
+ onEvent?: (event: LoopEvent) => void;
+}
+
+export interface LoopState {
+ name: string;
+ projectPath: string;
+ mode: 'codex' | 'command';
+ prompt?: string;
+ command?: string;
+ status: 'idle' | 'running' | 'stopping' | 'completed' | 'failed' | 'stopped';
+ iteration: number;
+ maxIterations: number;
+ intervalSeconds: number;
+ startedAt: string;
+ updatedAt: string;
+ lastExitCode?: number | null;
+ lastOutput?: string;
+ lastError?: string;
+ untilFile: string;
+}
+
+export interface LoopEvent {
+ type: 'start' | 'iteration-start' | 'iteration-complete' | 'sleep' | 'stop' | 'complete' | 'error' | 'dry-run';
+ state: LoopState;
+ message?: string;
+}
+
+export interface LoopPaths {
+ stateDir: string;
+ statePath: string;
+ stopPath: string;
+ completePath: string;
+}
+
+export interface LoopCommandResult {
+ code: number | null;
+ signal: NodeJS.Signals | null;
+ stdout: string;
+ stderr: string;
+}
+
+export function normalizeLoopName(name = 'default'): string {
+ const normalized = name.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '');
+ return normalized || 'default';
+}
+
+export function resolveLoopPaths(projectPath: string, name = 'default', stateDir?: string): LoopPaths {
+ const safeName = normalizeLoopName(name);
+ const resolvedStateDir = path.resolve(projectPath, stateDir ?? path.join('.codex', 'loop'));
+ return {
+ stateDir: resolvedStateDir,
+ statePath: path.join(resolvedStateDir, `${safeName}.json`),
+ stopPath: path.join(resolvedStateDir, `${safeName}.stop`),
+ completePath: path.join(resolvedStateDir, `${safeName}.complete`),
+ };
+}
+
+export async function loadLoopState(projectPath: string, name = 'default', stateDir?: string): Promise<LoopState | null> {
+ const paths = resolveLoopPaths(projectPath, name, stateDir);
+ if (!await fs.pathExists(paths.statePath)) return null;
+ return await fs.readJson(paths.statePath) as LoopState;
+}
+
+export async function requestLoopStop(projectPath: string, name = 'default', stateDir?: string): Promise<LoopPaths> {
+ const paths = resolveLoopPaths(projectPath, name, stateDir);
+ await fs.ensureDir(paths.stateDir);
+ await fs.writeFile(paths.stopPath, new Date().toISOString());
+
+ const state = await loadLoopState(projectPath, name, stateDir);
+ if (state && state.status === 'running') {
+ state.status = 'stopping';
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ }
+
+ return paths;
+}
+
+export function buildCodexLoopPrompt(state: LoopState): string {
+ const max = state.maxIterations > 0 ? state.maxIterations : 'unbounded';
+ return [
+ 'You are running inside a Codex /loop-compatible iteration.',
+ `Loop: ${state.name}`,
+ `Iteration: ${state.iteration}/${max}`,
+ `Project: ${state.projectPath}`,
+ '',
+ 'Task:',
+ state.prompt ?? '',
+ '',
+ 'Work autonomously for this iteration. Make concrete progress, run relevant checks, and stop before broad unrelated refactors.',
+ `If the task is fully complete, create this marker file: ${state.untilFile}`,
+ 'If more work remains, leave the marker absent so the next loop iteration can continue.',
+ ].join('\n');
+}
+
+export async function runCodexLoop(options: LoopRunOptions = {}): Promise<LoopState> {
+ const projectPath = path.resolve(options.projectPath ?? process.cwd());
+ const name = normalizeLoopName(options.name);
+ const paths = resolveLoopPaths(projectPath, name, options.stateDir);
+ const intervalSeconds = clampInteger(options.intervalSeconds ?? 270, 0, 86_400);
+ const maxIterations = clampInteger(options.maxIterations ?? 10, 0, 100_000);
+ const timeoutMs = clampInteger(options.timeoutMs ?? 30 * 60_000, 1_000, 24 * 60 * 60_000);
+ const untilFile = path.resolve(projectPath, options.untilFile ?? paths.completePath);
+ const mode: LoopState['mode'] = options.command ? 'command' : 'codex';
+
+ if (mode === 'codex' && !options.prompt?.trim()) {
+ throw new Error('loop run requires a prompt unless --command is provided');
+ }
+
+ await fs.ensureDir(paths.stateDir);
+ await fs.remove(paths.stopPath);
+
+ const startedAt = new Date().toISOString();
+ const state: LoopState = {
+ name,
+ projectPath,
+ mode,
+ status: 'running',
+ iteration: 0,
+ maxIterations,
+ intervalSeconds,
+ startedAt,
+ updatedAt: startedAt,
+ untilFile,
+ };
+ if (options.prompt !== undefined) state.prompt = options.prompt;
+ if (options.command !== undefined) state.command = options.command;
+
+ await saveLoopState(paths.statePath, state);
+ emit(options, 'start', state, `Loop ${name} started`);
+
+ if (options.dryRun) {
+ state.status = 'idle';
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ emit(options, 'dry-run', state, 'Dry run complete');
+ return state;
+ }
+
+ try {
+ while (shouldContinue(state, paths)) {
+ state.iteration += 1;
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ emit(options, 'iteration-start', state, `Iteration ${state.iteration} starting`);
+
+ const result = mode === 'command'
+ ? await runShellCommand(options.command!, projectPath, timeoutMs)
+ : await runCodexExec(options, state, timeoutMs);
+
+ state.lastExitCode = result.code;
+ state.lastOutput = truncate(result.stdout || result.stderr, 8_000);
+ if (result.code === 0 || result.code === null) {
+ delete state.lastError;
+ } else {
+ state.lastError = truncate(result.stderr || result.stdout, 8_000);
+ }
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ emit(options, 'iteration-complete', state, `Iteration ${state.iteration} exited with ${result.code ?? result.signal ?? 'unknown'}`);
+
+ if (existsSync(untilFile)) {
+ state.status = 'completed';
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ emit(options, 'complete', state, `Completion marker found: ${untilFile}`);
+ return state;
+ }
+
+ if (result.code !== 0 && result.code !== null) {
+ state.status = 'failed';
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ emit(options, 'error', state, `Iteration failed with exit code ${result.code}`);
+ return state;
+ }
+
+ if (!shouldContinue(state, paths)) break;
+ emit(options, 'sleep', state, `Sleeping ${intervalSeconds}s`);
+ await sleep(intervalSeconds * 1000);
+ }
+
+ state.status = existsSync(paths.stopPath) ? 'stopped' : 'completed';
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ emit(options, state.status === 'stopped' ? 'stop' : 'complete', state);
+ return state;
+ } catch (error) {
+ state.status = 'failed';
+ state.lastError = error instanceof Error ? error.message : String(error);
+ state.updatedAt = new Date().toISOString();
+ await saveLoopState(paths.statePath, state);
+ emit(options, 'error', state, state.lastError);
+ return state;
+ }
+}
+
+async function runCodexExec(options: LoopRunOptions, state: LoopState, timeoutMs: number): Promise<LoopCommandResult> {
+ const args = ['exec', '--sandbox', options.sandbox ?? 'workspace-write'];
+ if (options.skipGitRepoCheck !== false) args.push('--skip-git-repo-check');
+ if (options.model) args.push('-m', options.model);
+ args.push(buildCodexLoopPrompt(state));
+ return runProcess(options.codexCommand ?? 'codex', args, state.projectPath, timeoutMs);
+}
+
+async function runShellCommand(command: string, cwd: string, timeoutMs: number): Promise<LoopCommandResult> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, {
+ cwd,
+ shell: true,
+ env: { ...process.env, FORCE_COLOR: '0' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+
+ collectChild(child, timeoutMs, resolve, reject);
+ });
+}
+
+async function runProcess(command: string, args: string[], cwd: string, timeoutMs: number): Promise<LoopCommandResult> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, {
+ cwd,
+ env: { ...process.env, FORCE_COLOR: '0' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+
+ collectChild(child, timeoutMs, resolve, reject);
+ });
+}
+
+function collectChild(
+ child: ReturnType<typeof spawn>,
+ timeoutMs: number,
+ resolve: (result: LoopCommandResult) => void,
+ reject: (error: Error) => void
+): void {
+ let stdout = '';
+ let stderr = '';
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ child.kill('SIGTERM');
+ }, timeoutMs);
+
+ child.stdout?.on('data', data => { stdout += data.toString(); });
+ child.stderr?.on('data', data => { stderr += data.toString(); });
+ child.on('error', err => {
+ clearTimeout(timer);
+ reject(err);
+ });
+ child.on('close', (code, signal) => {
+ clearTimeout(timer);
+ if (timedOut) {
+ resolve({ code: 124, signal, stdout, stderr: stderr || `Timed out after ${timeoutMs}ms` });
+ return;
+ }
+ resolve({ code, signal, stdout, stderr });
+ });
+}
+
+async function saveLoopState(statePath: string, state: LoopState): Promise<void> {
+ await fs.ensureDir(path.dirname(statePath));
+ await fs.writeJson(statePath, state, { spaces: 2 });
+}
+
+function shouldContinue(state: LoopState, paths: LoopPaths): boolean {
+ if (state.status !== 'running') return false;
+ if (existsSync(paths.stopPath)) return false;
+ if (existsSync(state.untilFile)) return false;
+ return state.maxIterations === 0 || state.iteration < state.maxIterations;
+}
+
+function emit(options: LoopRunOptions, type: LoopEvent['type'], state: LoopState, message?: string): void {
+ const event: LoopEvent = { type, state: { ...state } };
+ if (message !== undefined) event.message = message;
+ options.onEvent?.(event);
+}
+
+function clampInteger(value: number, min: number, max: number): number {
+ if (!Number.isFinite(value)) return min;
+ return Math.min(max, Math.max(min, Math.floor(value)));
+}
+
+function truncate(value: string, max: number): string {
+ return value.length <= max ? value : `${value.slice(0, max)}\n...[truncated]`;
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, ms));
+}
diff --git a/v3/@claude-flow/codex/src/migrations/index.ts b/v3/@claude-flow/codex/src/migrations/index.ts
index 0666700494..2557975091 100644
--- a/v3/@claude-flow/codex/src/migrations/index.ts
+++ b/v3/@claude-flow/codex/src/migrations/index.ts
@@ -776,9 +776,9 @@ export function convertSettingsToToml(settings: Record<string, unknown>): string
}
} else {
// Add default claude-flow server
- lines.push('[mcp_servers.claude-flow]');
+ lines.push('[mcp_servers.ruflo]');
lines.push('command = "npx"');
- lines.push('args = ["-y", "@claude-flow/cli@latest"]');
+ lines.push('args = ["-y", "ruflo@latest", "mcp", "start"]');
lines.push('enabled = true');
lines.push('');
}
@@ -852,9 +852,9 @@ export function generateConfigTomlFromParsed(parsed: ParsedClaudeMd): string {
}
} else {
// Default claude-flow server
- lines.push('[mcp_servers.claude_flow]');
+ lines.push('[mcp_servers.ruflo]');
lines.push('command = "npx"');
- lines.push('args = ["-y", "@claude-flow/cli@latest"]');
+ lines.push('args = ["-y", "ruflo@latest", "mcp", "start"]');
lines.push('enabled = true');
lines.push('');
}
diff --git a/v3/@claude-flow/codex/src/types.ts b/v3/@claude-flow/codex/src/types.ts
index 637a3a915c..fb456e6553 100644
--- a/v3/@claude-flow/codex/src/types.ts
+++ b/v3/@claude-flow/codex/src/types.ts
@@ -46,6 +46,12 @@ export interface AgentsMdOptions {
export interface SkillMdOptions {
name: string;
description: string;
+ /** Skill version (default: "1.0.0") */
+ version?: string;
+ /** Skill author (default: "rUv") */
+ author?: string;
+ /** Discovery tags (default: derived from the skill name) */
+ tags?: string[];
triggers?: string[];
skipWhen?: string[];
scripts?: SkillScript[];
diff --git a/v3/@claude-flow/codex/src/validators/index.ts b/v3/@claude-flow/codex/src/validators/index.ts
index ea9743ea5b..071dd3d91c 100644
--- a/v3/@claude-flow/codex/src/validators/index.ts
+++ b/v3/@claude-flow/codex/src/validators/index.ts
@@ -466,7 +466,7 @@ export async function validateConfigToml(content: string): Promise<ValidationRes
warnings.push({
path: 'config.toml',
message: 'No MCP servers configured',
- suggestion: 'Add [mcp_servers.claude-flow] for Claude Flow integration',
+ suggestion: 'Add [mcp_servers.ruflo] for Claude Flow integration',
});
} else {
// Validate MCP server configurations
diff --git a/v3/@claude-flow/codex/tests/dual-mode.test.ts b/v3/@claude-flow/codex/tests/dual-mode.test.ts
new file mode 100644
index 0000000000..7bd445c4ac
--- /dev/null
+++ b/v3/@claude-flow/codex/tests/dual-mode.test.ts
@@ -0,0 +1,151 @@
+/**
+ * @claude-flow/codex - Dual-Mode Tests
+ *
+ * Covers parseWorkerSpecs (W2), CollaborationTemplates, the `dual`
+ * command wiring, and DualModeOrchestrator dependency leveling.
+ * No real workers are spawned β€” only pure logic is exercised.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseWorkerSpecs, createDualModeCommand } from '../src/dual-mode/cli.js';
+import { DualModeOrchestrator, CollaborationTemplates } from '../src/dual-mode/index.js';
+import type { WorkerConfig } from '../src/dual-mode/index.js';
+
+describe('parseWorkerSpecs', () => {
+ it('parses a single spec into a WorkerConfig', () => {
+ const [w] = parseWorkerSpecs(['claude:architect:Design the API'], false);
+ expect(w).toMatchObject({ id: 'architect', platform: 'claude', role: 'architect', prompt: 'Design the API' });
+ expect(w.dependsOn).toBeUndefined();
+ });
+
+ it('chains workers sequentially by default', () => {
+ const ws = parseWorkerSpecs(['claude:architect:Design', 'codex:coder:Build', 'codex:tester:Test'], false);
+ expect(ws.map(w => w.id)).toEqual(['architect', 'coder', 'tester']);
+ expect(ws.map(w => w.platform)).toEqual(['claude', 'codex', 'codex']);
+ expect(ws[0].dependsOn).toBeUndefined();
+ expect(ws[1].dependsOn).toEqual(['architect']);
+ expect(ws[2].dependsOn).toEqual(['coder']);
+ });
+
+ it('runs workers in parallel when parallel=true (no dependsOn)', () => {
+ const ws = parseWorkerSpecs(['claude:a:x', 'codex:b:y'], true);
+ expect(ws.every(w => w.dependsOn === undefined)).toBe(true);
+ });
+
+ it('keeps colons inside the prompt (splits on the first two only)', () => {
+ const [w] = parseWorkerSpecs(['codex:coder:Fix bug: handle null in foo:bar'], false);
+ expect(w.prompt).toBe('Fix bug: handle null in foo:bar');
+ expect(w.role).toBe('coder');
+ });
+
+ it('deduplicates ids for repeated roles', () => {
+ const ws = parseWorkerSpecs(['codex:coder:a', 'codex:coder:b', 'codex:coder:c'], true);
+ expect(ws.map(w => w.id)).toEqual(['coder', 'coder-2', 'coder-3']);
+ });
+
+ it('trims whitespace around platform/role/prompt', () => {
+ const [w] = parseWorkerSpecs([' claude : architect : Design it '], false);
+ expect(w).toMatchObject({ platform: 'claude', role: 'architect', prompt: 'Design it' });
+ });
+
+ it('throws on a spec with fewer than two colons', () => {
+ expect(() => parseWorkerSpecs(['claude:architect'], false)).toThrow(/Expected/);
+ expect(() => parseWorkerSpecs(['justaprompt'], false)).toThrow(/Expected/);
+ });
+
+ it('throws on an empty prompt', () => {
+ expect(() => parseWorkerSpecs(['claude:architect: '], false)).toThrow(/Missing prompt/);
+ });
+
+ it('throws on an unknown platform', () => {
+ expect(() => parseWorkerSpecs(['gemini:coder:do it'], false)).toThrow(/claude.*codex/);
+ });
+});
+
+describe('CollaborationTemplates', () => {
+ it('featureDevelopment: architect -> coder -> tester -> reviewer', () => {
+ const ws = CollaborationTemplates.featureDevelopment('Add OAuth');
+ expect(ws.map(w => w.id)).toEqual(['architect', 'coder', 'tester', 'reviewer']);
+ expect(ws.find(w => w.id === 'architect')!.platform).toBe('claude');
+ expect(ws.find(w => w.id === 'coder')!.platform).toBe('codex');
+ expect(ws.find(w => w.id === 'coder')!.dependsOn).toEqual(['architect']);
+ expect(ws.find(w => w.id === 'tester')!.dependsOn).toEqual(['coder']);
+ expect(ws.find(w => w.id === 'reviewer')!.dependsOn).toEqual(['coder', 'tester']);
+ expect(ws.some(w => w.prompt.includes('Add OAuth'))).toBe(true);
+ });
+
+ it('securityAudit: scanner -> analyzer -> fixer', () => {
+ const ws = CollaborationTemplates.securityAudit('./src');
+ expect(ws.map(w => w.id)).toEqual(['scanner', 'analyzer', 'fixer']);
+ expect(ws.find(w => w.id === 'analyzer')!.dependsOn).toEqual(['scanner']);
+ expect(ws.find(w => w.id === 'fixer')!.dependsOn).toEqual(['analyzer']);
+ });
+
+ it('refactoring: analyzer -> planner -> refactorer -> validator', () => {
+ const ws = CollaborationTemplates.refactoring('./src/legacy');
+ expect(ws.map(w => w.id)).toEqual(['analyzer', 'planner', 'refactorer', 'validator']);
+ expect(ws.find(w => w.id === 'planner')!.dependsOn).toEqual(['analyzer']);
+ expect(ws.find(w => w.id === 'validator')!.dependsOn).toEqual(['refactorer']);
+ });
+});
+
+describe('dual command wiring', () => {
+ it('exposes run / templates / status subcommands', () => {
+ const cmd = createDualModeCommand();
+ expect(cmd.name()).toBe('dual');
+ const subs = cmd.commands.map(c => c.name()).sort();
+ expect(subs).toEqual(['run', 'status', 'templates']);
+ });
+
+ it('`run` accepts a positional [template] and a repeatable --worker', () => {
+ const run = createDualModeCommand().commands.find(c => c.name() === 'run')!;
+ const optionNames = run.options.map(o => o.long);
+ expect(optionNames).toContain('--worker');
+ expect(optionNames).toContain('--parallel-workers');
+ expect(optionNames).toContain('--template');
+ // a positional argument is registered for [template]
+ expect((run as unknown as { _args: unknown[] })._args.length).toBeGreaterThan(0);
+ });
+});
+
+describe('DualModeOrchestrator', () => {
+ const orch = () => new DualModeOrchestrator({ projectPath: '/tmp' });
+
+ it('uses safe defaults (codex command, not claude)', () => {
+ const o = orch() as unknown as { config: Record<string, unknown> };
+ expect(o.config.codexCommand).toBe('codex');
+ expect(o.config.claudeCommand).toBe('claude');
+ expect(o.config.maxConcurrent).toBe(4);
+ expect(o.config.sharedNamespace).toBe('collaboration');
+ });
+
+ it('buildDependencyLevels groups a linear pipeline one-per-level', () => {
+ const ws: WorkerConfig[] = [
+ { id: 'a', platform: 'claude', role: 'a', prompt: 'x' },
+ { id: 'b', platform: 'codex', role: 'b', prompt: 'y', dependsOn: ['a'] },
+ { id: 'c', platform: 'codex', role: 'c', prompt: 'z', dependsOn: ['b'] },
+ ];
+ const levels = (orch() as unknown as { buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][] }).buildDependencyLevels(ws);
+ expect(levels.map(l => l.map(w => w.id))).toEqual([['a'], ['b'], ['c']]);
+ });
+
+ it('buildDependencyLevels puts independent workers in the same level', () => {
+ const ws: WorkerConfig[] = [
+ { id: 'a', platform: 'claude', role: 'a', prompt: 'x' },
+ { id: 'b', platform: 'codex', role: 'b', prompt: 'y' },
+ { id: 'c', platform: 'codex', role: 'c', prompt: 'z', dependsOn: ['a', 'b'] },
+ ];
+ const levels = (orch() as unknown as { buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][] }).buildDependencyLevels(ws);
+ expect(levels.length).toBe(2);
+ expect(new Set(levels[0].map(w => w.id))).toEqual(new Set(['a', 'b']));
+ expect(levels[1].map(w => w.id)).toEqual(['c']);
+ });
+
+ it('buildDependencyLevels breaks a circular dependency instead of looping forever', () => {
+ const ws: WorkerConfig[] = [
+ { id: 'a', platform: 'claude', role: 'a', prompt: 'x', dependsOn: ['b'] },
+ { id: 'b', platform: 'codex', role: 'b', prompt: 'y', dependsOn: ['a'] },
+ ];
+ const levels = (orch() as unknown as { buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][] }).buildDependencyLevels(ws);
+ expect(levels.flat().map(w => w.id).sort()).toEqual(['a', 'b']);
+ });
+});
diff --git a/v3/@claude-flow/codex/tests/generators.test.ts b/v3/@claude-flow/codex/tests/generators.test.ts
index 057605f4bc..9664a410e4 100644
--- a/v3/@claude-flow/codex/tests/generators.test.ts
+++ b/v3/@claude-flow/codex/tests/generators.test.ts
@@ -529,7 +529,7 @@ describe('generateBuiltInSkill', () => {
expect(result.skillMd).toContain('name: swarm-orchestration');
expect(result.skillMd).toContain('Multi-agent swarm coordination');
expect(result.skillMd).toContain('Initialize Swarm');
- expect(result.skillMd).toContain('npx @claude-flow/cli swarm init');
+ expect(result.skillMd).toContain('npx ruflo swarm init');
});
it('should generate memory-management skill', async () => {
@@ -613,7 +613,7 @@ describe('generateConfigToml', () => {
expect(result).toContain('# Claude Flow V3 - Codex Configuration');
expect(result).toContain('# Generated by: @claude-flow/codex');
- expect(result).toContain('# Documentation: https://github.com/ruvnet/claude-flow');
+ expect(result).toContain('# Documentation: https://github.com/ruvnet/ruflo');
});
it('should include core settings section', async () => {
@@ -645,12 +645,12 @@ describe('generateConfigToml', () => {
expect(result).toContain('remote_compaction = true');
});
- it('should include default claude-flow MCP server', async () => {
+ it('should include default ruflo MCP server', async () => {
const result = await generateConfigToml();
- expect(result).toContain('[mcp_servers.claude-flow]');
+ expect(result).toContain('[mcp_servers.ruflo]');
expect(result).toContain('command = "npx"');
- expect(result).toContain('args = ["-y", "@claude-flow/cli@latest"]');
+ expect(result).toContain('args = ["-y", "ruflo@latest", "mcp", "start"]');
expect(result).toContain('enabled = true');
});
@@ -881,7 +881,7 @@ describe('generateMinimalConfigToml', () => {
expect(result).toContain('model = "gpt-5.3-codex"');
expect(result).toContain('approval_policy = "on-request"');
expect(result).toContain('sandbox_mode = "workspace-write"');
- expect(result).toContain('[mcp_servers.claude-flow]');
+ expect(result).toContain('[mcp_servers.ruflo]');
});
it('should accept custom options', async () => {
diff --git a/v3/@claude-flow/codex/tests/loop.test.ts b/v3/@claude-flow/codex/tests/loop.test.ts
new file mode 100644
index 0000000000..e1a7e39e0d
--- /dev/null
+++ b/v3/@claude-flow/codex/tests/loop.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest';
+import fs from 'fs-extra';
+import os from 'node:os';
+import path from 'node:path';
+import {
+ buildCodexLoopPrompt,
+ loadLoopState,
+ normalizeLoopName,
+ requestLoopStop,
+ resolveLoopPaths,
+ runCodexLoop,
+} from '../src/loop/index.js';
+
+describe('Codex loop runner', () => {
+ it('normalizes loop names for state file paths', () => {
+ expect(normalizeLoopName(' Feature Loop! ')).toBe('feature-loop');
+ expect(normalizeLoopName('')).toBe('default');
+ });
+
+ it('runs a bounded shell-command loop and persists state', async () => {
+ const projectPath = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-loop-'));
+ const marker = path.join(projectPath, '.codex', 'loop', 'demo.complete');
+ const script = `const fs=require('fs');const path=require('path');const marker=${JSON.stringify(marker)};fs.mkdirSync(path.dirname(marker),{recursive:true});fs.writeFileSync(marker,'done');console.log('completed');`;
+ const command = `node -e ${JSON.stringify(script)}`;
+
+ const state = await runCodexLoop({
+ name: 'demo',
+ projectPath,
+ command,
+ intervalSeconds: 0,
+ maxIterations: 3,
+ timeoutMs: 10_000,
+ });
+
+ expect(state.status).toBe('completed');
+ expect(state.iteration).toBe(1);
+ expect(state.lastExitCode).toBe(0);
+ expect(await fs.pathExists(marker)).toBe(true);
+
+ const persisted = await loadLoopState(projectPath, 'demo');
+ expect(persisted?.status).toBe('completed');
+ expect(persisted?.iteration).toBe(1);
+ });
+
+ it('writes stop requests that running loops can observe', async () => {
+ const projectPath = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-loop-stop-'));
+ const paths = await requestLoopStop(projectPath, 'demo');
+ expect(await fs.pathExists(paths.stopPath)).toBe(true);
+ });
+
+ it('builds a prompt with the completion marker contract', () => {
+ const projectPath = '/tmp/project';
+ const paths = resolveLoopPaths(projectPath, 'demo');
+ const prompt = buildCodexLoopPrompt({
+ name: 'demo',
+ projectPath,
+ mode: 'codex',
+ prompt: 'Fix the tests',
+ status: 'running',
+ iteration: 2,
+ maxIterations: 5,
+ intervalSeconds: 270,
+ startedAt: '2026-05-11T00:00:00.000Z',
+ updatedAt: '2026-05-11T00:00:00.000Z',
+ untilFile: paths.completePath,
+ });
+
+ expect(prompt).toContain('Codex /loop-compatible iteration');
+ expect(prompt).toContain('Fix the tests');
+ expect(prompt).toContain(paths.completePath);
+ });
+});
diff --git a/v3/@claude-flow/codex/tests/migrations.test.ts b/v3/@claude-flow/codex/tests/migrations.test.ts
index 6dccde64f8..985ed708a4 100644
--- a/v3/@claude-flow/codex/tests/migrations.test.ts
+++ b/v3/@claude-flow/codex/tests/migrations.test.ts
@@ -487,15 +487,15 @@ describe('convertSettingsToToml', () => {
expect(result).toContain('command = "node"');
});
- it('should add default claude-flow server when no mcpServers', () => {
+ it('should add default ruflo server when no mcpServers', () => {
const settings = {
model: 'gpt-4',
};
const result = convertSettingsToToml(settings);
- // The implementation adds a default claude-flow server when none specified
- expect(result).toContain('[mcp_servers.claude-flow]');
+ // The implementation adds a default ruflo server when none specified
+ expect(result).toContain('[mcp_servers.ruflo]');
expect(result).toContain('command = "npx"');
});