mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
* fix(codex): correct codex MCP server subcommand + sync package version - mcp-bridge: `@openai/codex mcp serve` → `@openai/codex mcp-server`. `codex mcp` manages *external* MCP servers (list/get/add/remove); `codex mcp-server` is the "start Codex as an MCP server (stdio)" command. `codex mcp serve` errors with "unrecognized subcommand 'serve'", so the `codex` MCP backend never started. Fixed in both ruflo/src/mcp-bridge/index.js and ruflo/src/ruvocal/mcp-bridge/index.js. - @claude-flow/codex: VERSION const was '3.0.0-alpha.8' while package.json is '3.0.0-alpha.9' — `--version`/`info` reported the wrong version. Synced to alpha.9. Verified: `codex mcp serve` → error; `codex mcp-server` is valid. @claude-flow/codex builds clean (tsc), 162 unit tests pass, `claude-flow-codex` CLI (init/validate/doctor/templates/skills/dual) all functional. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(codex): W1 — dual-mode orchestrator spawns real `codex exec` for codex workers Previously `codexCommand` defaulted to `'claude'` ("Both use claude CLI") and every worker — claude or codex — was launched with Claude-CLI flags (`-p`, `--output-format text`, `--max-turns`), so "dual-mode" was two Claude instances. Now: - `codexCommand` defaults to `'codex'` - `executeHeadless` builds platform-specific args: - claude: `-p <prompt> --output-format text [--max-turns N] [--model M]` - codex: `exec --sandbox workspace-write --skip-git-repo-check [-m M] <prompt>` (PROMPT is positional -> last; `codex exec` runs autonomously) Remaining in W1 (next iterations): update `.claude/agents/dual-mode/ codex-worker.md` + `codex-coordinator.md` to invoke `codex exec` instead of `claude -p`; add mocked-spawn smoke test (W4). Tracked: #1909. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(codex): W1 (cont.) — dual-mode agent defs invoke `codex exec`, not `claude -p` codex-worker.md / codex-coordinator.md described "headless Codex workers" but every spawn example was `claude -p "..." --session-id X` with Claude-only flags (--max-budget-usd, --allowedTools, --output-format). Updated to match the W1 orchestrator change: - spawn syntax → `codex exec --sandbox <workspace-write|read-only> --skip-git-repo-check "<prompt>" &` - dropped Claude-only flags; note that mixed-platform runs still use `claude -p` for Claude workers - swarm/memory CLI refs `claude-flow@v3alpha` → `ruflo@latest` - MCP tool refs `mcp__claude-flow__*` / `mcp__ruv-swarm__*` → `mcp__ruflo__*` W1 now complete (orchestrator + agent defs). dual-orchestrator.md left as-is — it correctly documents the mixed Claude+Codex split. Smoke test is W4. Tracked: #1909. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(codex): W2 — `dual run --worker "<platform>:<role>:<prompt>"` + positional template `dual run` only accepted `--template <name>` / `--config <path>`, so the custom-worker syntax documented in CLAUDE.md (`dual run --worker "claude:architect:..." --worker "codex:coder:..."`) didn't exist, and `dual run feature` (positional) silently fell through to "specify --template". Now: - `dual run [template]` — positional alias for `--template` - `-w, --worker "<platform>:<role>:<prompt>"` (repeatable; platform = claude|codex; prompt may contain `:` — split on first two only). Workers chain sequentially (each `dependsOn` the previous) unless `--parallel-workers`. Unique ids derived from role. - `parseWorkerSpecs()` exported for testing; clear errors on malformed specs / bad platform. - improved no-args usage text. build clean (tsc), 162 tests pass. Tracked: #1909 (W2). Tests for parseWorkerSpecs land in W4. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(codex): W3 — standardize CLI ref claude-flow@alpha -> ruflo; fix MCP-server registration The dual-mode orchestrator/CLI shelled out to `npx claude-flow@alpha memory ...`, `claude-flow-codex init` registered the MCP server as `codex mcp add claude-flow -- npx claude-flow mcp start`, and the config.toml / migration generators emitted `[mcp_servers.claude-flow]` with `args = ["-y", "@claude-flow/cli@latest"]` — the wrong package, an inner-package name, and (in config-toml) **missing the `mcp start` subcommand** so the server never actually started. - dual-mode/{orchestrator,cli}.ts: `claude-flow@alpha` -> `ruflo@alpha` - initializer.ts: `codex mcp add claude-flow -- npx claude-flow mcp start` -> `codex mcp add ruflo -- npx ruflo mcp start`; "MCP server (ruflo) registered"; `npx @claude-flow/cli mcp start` -> `npx ruflo mcp start` - generators/config-toml.ts: default server `name: 'ruflo'`, `args: ['-y', 'ruflo@latest', 'mcp', 'start']` (adds the missing subcommand); `[mcp_servers.ruflo]` in all examples; the already-configured check accepts both `ruflo` and legacy `claude-flow` - generators/{agents-md,skill-md}.ts: `npx @claude-flow/cli ...` -> `npx ruflo ...` - migrations/index.ts: default emitted server -> `[mcp_servers.ruflo]` / `args = ["-y", "ruflo@latest", "mcp", "start"]` (user-provided servers pass through unchanged) - validators/index.ts: suggestion text -> `[mcp_servers.ruflo]` - tests: updated generator/migration assertions to the new output `npx vitest run` 162/162 pass. Note: `npm run build` (tsc) currently fails on an UNRELATED uncommitted WIP file `src/loop/index.ts` (exactOptionalPropertyTypes on prompt/command) — not from this change; my files compile clean. Branding-only refs (config-toml header, repo URLs in generated docs, remaining `@claude-flow/cli` in skill-md examples) deferred to W7. Tracked: #1909 (W3). Co-Authored-By: RuFlo <ruv@ruv.net> * test(codex): W4 — dual-mode tests (parseWorkerSpecs, templates, orchestrator leveling, `dual` wiring) New tests/dual-mode.test.ts (18 tests, no real workers spawned): - parseWorkerSpecs: single spec, sequential chaining, --parallel-workers, colons-in-prompt, id dedup, whitespace trim, and the 3 error paths (too-few-colons / empty-prompt / unknown-platform) - CollaborationTemplates: feature/security/refactor pipelines — ids, platforms, dependsOn chains, task interpolation - `dual` command wiring: run/templates/status subcommands; `run` exposes --worker / --parallel-workers / --template and a positional [template] - DualModeOrchestrator: safe defaults (codexCommand === 'codex'), buildDependencyLevels for linear / fan-in / circular cases Full suite: 184/184 pass (162 prior + 18 new + 4 loop). `npm run build` still blocked on the unrelated uncommitted `src/loop/index.ts`. Deferred: a full `CodexInitializer.initialize()` integration test (it shells out `codex mcp add`, which would touch the user's real codex config — needs a mock first). Tracked: #1909 (W4). Co-Authored-By: RuFlo <ruv@ruv.net> * feat(codex): W5 — generated SKILL.md frontmatter gets version/author/tags `claude-flow-codex init` / `generate-skill` produced SKILL.md files with only `name` + `description`, so `claude-flow-codex validate` flagged 3 "Consider adding field: version/author/tags" warnings per skill. - SkillMdOptions: optional `version` ("1.0.0"), `author` ("rUv"), `tags` (defaults to the skill name split on `-`) - generateSkillMd emits `version: "..."`, `author: ...`, `tags: [...]` in the frontmatter; built-in skills (via generateBuiltInSkill) inherit the defaults automatically Verified: a generated built-in skill validates with 0 warnings (was 3); a bare `generate-skill` stub now has 1 warning ("No examples provided", expected for a skill with no commands — out of scope here). `init → validate → doctor` clean on the local build. `npm run build` + 184/184 tests pass. (The ~150 repo `.agents/skills/*/SKILL.md` are generated by @claude-flow/cli, not this generator — out of scope.) Tracked: #1909 (W5). Co-Authored-By: RuFlo <ruv@ruv.net> * ci(codex): W6 — codex-integration-audit guard + workflow `scripts/audit-codex-integration.mjs` — pure-Node static checks for the Codex ↔ Ruflo invariants (issue #1909), exits non-zero on any failure: - `codex` MCP backend uses `mcp-server` (not the invalid `mcp serve`) in both ruflo/src/mcp-bridge and ruvocal/mcp-bridge - @claude-flow/codex VERSION const === its package.json version - dual-mode orchestrator: `codexCommand` defaults to 'codex', codex workers spawn `codex exec --sandbox …`, no 'claude' fallback - dual-mode agent defs reference `codex exec`, no legacy `claude -p … --session-id` worker pattern - no `claude-flow@alpha` / `@claude-flow/cli@latest` left in codex src - `dual run` exposes `--worker <spec>` + positional `[template]`, `parseWorkerSpecs` exported - generateSkillMd emits version/author/tags frontmatter - config.toml generator default MCP server = `ruflo` w/ `mcp start` `.github/workflows/codex-integration-audit.yml` runs it on PRs / pushes touching the codex package, mcp-bridge, dual-mode agents, or the script. No `npm install` needed — build + tests stay in the main CI. Audit passes on current branch. `npm run build` + 184/184 tests pass. Tracked: #1909 (W6). Co-Authored-By: RuFlo <ruv@ruv.net> * feat(codex): claude-flow-codex loop runner — Codex-native /loop equivalent Codex doesn't expose Claude Code's ScheduleWakeup, so this is a process-based runner with the same behaviour: - `loop run [prompt]` — repeated `codex exec` runs (or a custom `--command`), bounded by `--max-iterations`/`--interval`, with `--dry-run`, model/sandbox options, and a completion-marker-file contract - `loop status [--name <name>]` / `loop stop [--name <name>]` - state persisted to `.codex/loop/<name>.json`; stop-file aware - wired into the CLI (`src/cli.ts`), exported (`src/index.ts`), with a `./loop` package export and README docs (Implemented by rUv; landing it here so it isn't sitting dirty in the worktree while the #1909 loop commits around it. `npm run build` + 184/184 tests pass; `git diff --check` clean.) Co-Authored-By: RuFlo <ruv@ruv.net> * chore(codex): W7 — package.json hygiene + repo URLs ruvnet/claude-flow -> ruvnet/ruflo - package.json: drop dead `"templates"` from `files` (no templates/ dir at the package root — templates compile to dist/templates/); repository / homepage / bugs URLs -> ruvnet/ruflo; description -> "Ruflo (claude-flow)" - src/index.ts: PACKAGE_INFO.repository -> ruvnet/ruflo - src/initializer.ts, generators/{agents-md,config-toml}.ts: generated AGENTS.md / config.toml doc URLs -> ruvnet/ruflo (+ "Ruflo:" label) - README.md: badge + footer URLs -> ruvnet/ruflo - tests: assertion for the config.toml Documentation line `npm run build` + 184/184 tests pass; codex-integration audit passes. (Committed `.agents/AGENTS.md` / `.agents/config.toml` in the repo still carry old URLs — generated artifacts; the generators are now fixed so re-init produces ruvnet/ruflo. The published `claude-flow-codex` package name stays as-is.) Tracked: #1909 (W7). Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
311 lines
11 KiB
TypeScript
311 lines
11 KiB
TypeScript
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));
|
|
}
|