mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 06:06:02 +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>
714 lines
25 KiB
JavaScript
714 lines
25 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* @claude-flow/codex - CLI
|
|
*
|
|
* Command-line interface for Codex integration
|
|
* Part of the coflow rebranding initiative
|
|
*/
|
|
|
|
import { Command } from 'commander';
|
|
import chalk from 'chalk';
|
|
import { CodexInitializer } from './initializer.js';
|
|
import { validateAgentsMd, validateSkillMd, validateConfigToml } from './validators/index.js';
|
|
import { migrateFromClaudeCode, analyzeClaudeMd, generateMigrationReport } from './migrations/index.js';
|
|
import { listTemplates, BUILT_IN_SKILLS } from './templates/index.js';
|
|
import { generateSkillMd } from './generators/skill-md.js';
|
|
import { VERSION, PACKAGE_INFO } from './index.js';
|
|
import fs from 'fs-extra';
|
|
import path from 'path';
|
|
|
|
const program = new Command();
|
|
|
|
// Custom error handler for better output
|
|
function handleError(error: unknown, message?: string): never {
|
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
console.error(chalk.red.bold('\nError:'), chalk.red(message ?? errorMessage));
|
|
|
|
if (error instanceof Error && error.stack && process.env.DEBUG) {
|
|
console.error(chalk.gray('\nStack trace:'));
|
|
console.error(chalk.gray(error.stack));
|
|
}
|
|
|
|
process.exit(1);
|
|
}
|
|
|
|
// Validate project path exists and is accessible
|
|
async function validatePath(projectPath: string): Promise<string> {
|
|
const resolvedPath = path.resolve(projectPath);
|
|
|
|
try {
|
|
const stats = await fs.stat(resolvedPath);
|
|
if (!stats.isDirectory()) {
|
|
throw new Error(`Path is not a directory: ${resolvedPath}`);
|
|
}
|
|
return resolvedPath;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
|
// Directory doesn't exist, try to create it
|
|
console.log(chalk.yellow(`Creating directory: ${resolvedPath}`));
|
|
await fs.ensureDir(resolvedPath);
|
|
return resolvedPath;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Validate skill name format
|
|
function validateSkillName(name: string): boolean {
|
|
const validPattern = /^[a-z][a-z0-9-]*$/;
|
|
return validPattern.test(name);
|
|
}
|
|
|
|
// Print banner
|
|
function printBanner(): void {
|
|
console.log(chalk.cyan.bold('\n Claude Flow Codex'));
|
|
console.log(chalk.gray(' OpenAI Codex integration for Claude Flow'));
|
|
console.log(chalk.gray(' ----------------------------------------\n'));
|
|
}
|
|
|
|
program
|
|
.name('claude-flow-codex')
|
|
.description('OpenAI Codex integration for Claude Flow - Part of the coflow ecosystem')
|
|
.version(VERSION, '-v, --version', 'Display version number')
|
|
.option('--debug', 'Enable debug mode', false)
|
|
.hook('preAction', (thisCommand) => {
|
|
if (thisCommand.opts().debug) {
|
|
process.env.DEBUG = 'true';
|
|
}
|
|
});
|
|
|
|
// Init command
|
|
program
|
|
.command('init')
|
|
.description('Initialize a new Codex project with AGENTS.md and skills')
|
|
.option('-t, --template <template>', 'Template to use (minimal, default, full, enterprise)', 'default')
|
|
.option('-s, --skills <skills>', 'Comma-separated list of skills to include')
|
|
.option('-f, --force', 'Overwrite existing files', false)
|
|
.option('--dual', 'Generate both Codex and Claude Code configurations', false)
|
|
.option('-p, --path <path>', 'Project path', process.cwd())
|
|
.option('-q, --quiet', 'Suppress verbose output', false)
|
|
.action(async (options) => {
|
|
try {
|
|
if (!options.quiet) {
|
|
printBanner();
|
|
}
|
|
|
|
// Validate template
|
|
const validTemplates = ['minimal', 'default', 'full', 'enterprise'];
|
|
if (!validTemplates.includes(options.template)) {
|
|
console.error(chalk.red(`Invalid template: ${options.template}`));
|
|
console.log(chalk.gray(`Valid templates: ${validTemplates.join(', ')}`));
|
|
process.exit(1);
|
|
}
|
|
|
|
const projectPath = await validatePath(options.path);
|
|
|
|
console.log(chalk.blue('Initializing Codex project...'));
|
|
console.log(chalk.gray(` Path: ${projectPath}`));
|
|
console.log(chalk.gray(` Template: ${options.template}`));
|
|
if (options.skills) {
|
|
console.log(chalk.gray(` Skills: ${options.skills}`));
|
|
}
|
|
if (options.force) {
|
|
console.log(chalk.yellow(' Force: enabled (will overwrite existing files)'));
|
|
}
|
|
if (options.dual) {
|
|
console.log(chalk.gray(' Mode: dual (Codex + Claude Code)'));
|
|
}
|
|
|
|
const initializer = new CodexInitializer();
|
|
const skills = options.skills?.split(',').map((s: string) => s.trim()).filter(Boolean);
|
|
|
|
// Validate skill names if provided
|
|
if (skills) {
|
|
for (const skill of skills) {
|
|
if (!validateSkillName(skill)) {
|
|
console.error(chalk.red(`Invalid skill name: ${skill}`));
|
|
console.log(chalk.gray('Skill names must be kebab-case (lowercase letters, numbers, hyphens)'));
|
|
process.exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
const result = await initializer.initialize({
|
|
projectPath,
|
|
template: options.template,
|
|
skills,
|
|
force: options.force,
|
|
dual: options.dual,
|
|
});
|
|
|
|
if (result.success) {
|
|
console.log(chalk.green.bold('\n Project initialized successfully!'));
|
|
|
|
if (result.filesCreated.length > 0) {
|
|
console.log(chalk.white('\n Files created:'));
|
|
for (const file of result.filesCreated) {
|
|
console.log(chalk.gray(` ${chalk.green('+')} ${file}`));
|
|
}
|
|
}
|
|
|
|
if (result.skillsGenerated.length > 0) {
|
|
console.log(chalk.white('\n Skills generated:'));
|
|
for (const skill of result.skillsGenerated) {
|
|
console.log(chalk.gray(` ${chalk.cyan('$')}${skill}`));
|
|
}
|
|
}
|
|
|
|
if (result.warnings && result.warnings.length > 0) {
|
|
console.log(chalk.yellow('\n Warnings:'));
|
|
for (const warning of result.warnings) {
|
|
console.log(chalk.yellow(` ! ${warning}`));
|
|
}
|
|
}
|
|
|
|
console.log(chalk.blue.bold('\n Next steps:'));
|
|
console.log(chalk.gray(' 1. Review AGENTS.md and customize for your project'));
|
|
console.log(chalk.gray(' 2. Review .agents/config.toml settings'));
|
|
console.log(chalk.gray(' 3. Start using skills with $skill-name syntax'));
|
|
console.log();
|
|
} else {
|
|
console.log(chalk.red.bold('\n Initialization failed'));
|
|
if (result.errors) {
|
|
for (const error of result.errors) {
|
|
console.log(chalk.red(` - ${error}`));
|
|
}
|
|
}
|
|
process.exit(1);
|
|
}
|
|
} catch (error) {
|
|
handleError(error, 'Failed to initialize project');
|
|
}
|
|
});
|
|
|
|
// Generate skill command
|
|
program
|
|
.command('generate-skill')
|
|
.alias('gs')
|
|
.description('Generate a new SKILL.md file')
|
|
.requiredOption('-n, --name <name>', 'Skill name (kebab-case)')
|
|
.option('-d, --description <description>', 'Skill description')
|
|
.option('-t, --triggers <triggers>', 'Comma-separated trigger conditions')
|
|
.option('-s, --skip <skip>', 'Comma-separated skip conditions')
|
|
.option('-p, --path <path>', 'Output path', process.cwd())
|
|
.option('--dry-run', 'Show what would be generated without writing', false)
|
|
.action(async (options) => {
|
|
try {
|
|
printBanner();
|
|
|
|
// Validate skill name
|
|
if (!validateSkillName(options.name)) {
|
|
console.error(chalk.red(`Invalid skill name: ${options.name}`));
|
|
console.log(chalk.gray('Skill names must be kebab-case (lowercase letters, numbers, hyphens)'));
|
|
console.log(chalk.gray('Examples: my-skill, code-analyzer, data-processor'));
|
|
process.exit(1);
|
|
}
|
|
|
|
const projectPath = await validatePath(options.path);
|
|
|
|
console.log(chalk.blue(`Generating skill: ${chalk.white(options.name)}`));
|
|
|
|
const triggers = options.triggers?.split(',').map((s: string) => s.trim()).filter(Boolean);
|
|
const skipWhen = options.skip?.split(',').map((s: string) => s.trim()).filter(Boolean);
|
|
|
|
const skillMd = await generateSkillMd({
|
|
name: options.name,
|
|
description: options.description ?? `Custom skill: ${options.name}`,
|
|
triggers: triggers ?? ['Define when to trigger this skill'],
|
|
skipWhen: skipWhen ?? ['Define when to skip this skill'],
|
|
});
|
|
|
|
if (options.dryRun) {
|
|
console.log(chalk.yellow('\nDry run - would generate:'));
|
|
console.log(chalk.gray('---'));
|
|
console.log(skillMd);
|
|
console.log(chalk.gray('---'));
|
|
return;
|
|
}
|
|
|
|
const skillDir = path.join(projectPath, '.agents', 'skills', options.name);
|
|
await fs.ensureDir(skillDir);
|
|
const skillPath = path.join(skillDir, 'SKILL.md');
|
|
|
|
// Check if skill already exists
|
|
if (await fs.pathExists(skillPath)) {
|
|
console.log(chalk.yellow(`Skill already exists: ${skillPath}`));
|
|
console.log(chalk.gray('Use --force to overwrite (not yet implemented)'));
|
|
process.exit(1);
|
|
}
|
|
|
|
await fs.writeFile(skillPath, skillMd);
|
|
|
|
console.log(chalk.green.bold(`\n Skill created successfully!`));
|
|
console.log(chalk.gray(` Path: ${skillPath}`));
|
|
console.log(chalk.gray(` Use: ${chalk.cyan('$' + options.name)}`));
|
|
console.log();
|
|
} catch (error) {
|
|
handleError(error, 'Failed to generate skill');
|
|
}
|
|
});
|
|
|
|
// Validate command
|
|
program
|
|
.command('validate')
|
|
.alias('check')
|
|
.description('Validate AGENTS.md, SKILL.md, or config.toml files')
|
|
.option('-f, --file <file>', 'File to validate')
|
|
.option('-p, --path <path>', 'Project path to validate all files', process.cwd())
|
|
.option('--fix', 'Attempt to fix issues (not yet implemented)', false)
|
|
.option('--strict', 'Treat warnings as errors', false)
|
|
.action(async (options) => {
|
|
try {
|
|
printBanner();
|
|
|
|
const projectPath = path.resolve(options.path);
|
|
const filesToValidate: Array<{ path: string; type: 'agents' | 'skill' | 'config' }> = [];
|
|
|
|
if (options.file) {
|
|
// Validate specific file
|
|
const filePath = path.resolve(options.file);
|
|
|
|
if (!await fs.pathExists(filePath)) {
|
|
console.error(chalk.red(`File not found: ${filePath}`));
|
|
process.exit(1);
|
|
}
|
|
|
|
const fileName = path.basename(filePath).toLowerCase();
|
|
if (fileName === 'agents.md') {
|
|
filesToValidate.push({ path: filePath, type: 'agents' });
|
|
} else if (fileName === 'skill.md') {
|
|
filesToValidate.push({ path: filePath, type: 'skill' });
|
|
} else if (fileName === 'config.toml') {
|
|
filesToValidate.push({ path: filePath, type: 'config' });
|
|
} else {
|
|
console.error(chalk.red(`Unknown file type: ${fileName}`));
|
|
console.log(chalk.gray('Supported files: AGENTS.md, SKILL.md, config.toml'));
|
|
process.exit(1);
|
|
}
|
|
} else {
|
|
// Validate all files in project
|
|
console.log(chalk.blue(`Scanning project: ${projectPath}`));
|
|
|
|
const agentsMd = path.join(projectPath, 'AGENTS.md');
|
|
const configToml = path.join(projectPath, '.agents', 'config.toml');
|
|
|
|
if (await fs.pathExists(agentsMd)) {
|
|
filesToValidate.push({ path: agentsMd, type: 'agents' });
|
|
}
|
|
if (await fs.pathExists(configToml)) {
|
|
filesToValidate.push({ path: configToml, type: 'config' });
|
|
}
|
|
|
|
// Find skill files
|
|
const skillsDir = path.join(projectPath, '.agents', 'skills');
|
|
if (await fs.pathExists(skillsDir)) {
|
|
try {
|
|
const skills = await fs.readdir(skillsDir);
|
|
for (const skill of skills) {
|
|
const skillPath = path.join(skillsDir, skill);
|
|
const skillStats = await fs.stat(skillPath);
|
|
if (skillStats.isDirectory()) {
|
|
const skillMd = path.join(skillPath, 'SKILL.md');
|
|
if (await fs.pathExists(skillMd)) {
|
|
filesToValidate.push({ path: skillMd, type: 'skill' });
|
|
}
|
|
}
|
|
}
|
|
} catch {
|
|
// Ignore errors reading skills directory
|
|
}
|
|
}
|
|
}
|
|
|
|
if (filesToValidate.length === 0) {
|
|
console.log(chalk.yellow('No files found to validate'));
|
|
console.log(chalk.gray('Run `claude-flow-codex init` to create a project'));
|
|
return;
|
|
}
|
|
|
|
console.log(chalk.blue(`\nValidating ${filesToValidate.length} file(s)...\n`));
|
|
|
|
let hasErrors = false;
|
|
let hasWarnings = false;
|
|
let totalErrors = 0;
|
|
let totalWarnings = 0;
|
|
|
|
for (const file of filesToValidate) {
|
|
let content: string;
|
|
try {
|
|
content = await fs.readFile(file.path, 'utf-8');
|
|
} catch (error) {
|
|
console.log(chalk.red(` ! Cannot read: ${file.path}`));
|
|
hasErrors = true;
|
|
continue;
|
|
}
|
|
|
|
let result;
|
|
|
|
switch (file.type) {
|
|
case 'agents':
|
|
result = await validateAgentsMd(content);
|
|
break;
|
|
case 'skill':
|
|
result = await validateSkillMd(content);
|
|
break;
|
|
case 'config':
|
|
result = await validateConfigToml(content);
|
|
break;
|
|
}
|
|
|
|
const relativePath = path.relative(projectPath, file.path);
|
|
|
|
if (result.valid && result.warnings.length === 0) {
|
|
console.log(chalk.green(` ${chalk.green.bold('PASS')} ${relativePath}`));
|
|
} else if (result.valid) {
|
|
console.log(chalk.yellow(` ${chalk.yellow.bold('WARN')} ${relativePath}`));
|
|
hasWarnings = true;
|
|
} else {
|
|
console.log(chalk.red(` ${chalk.red.bold('FAIL')} ${relativePath}`));
|
|
hasErrors = true;
|
|
}
|
|
|
|
for (const error of result.errors) {
|
|
totalErrors++;
|
|
const lineInfo = error.line ? chalk.gray(` (line ${error.line})`) : '';
|
|
console.log(chalk.red(` ${chalk.red('x')} ${error.message}${lineInfo}`));
|
|
}
|
|
|
|
for (const warning of result.warnings) {
|
|
totalWarnings++;
|
|
console.log(chalk.yellow(` ${chalk.yellow('!')} ${warning.message}`));
|
|
if (warning.suggestion) {
|
|
console.log(chalk.gray(` ${warning.suggestion}`));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Summary
|
|
console.log();
|
|
if (hasErrors) {
|
|
console.log(chalk.red.bold(` ${totalErrors} error(s), ${totalWarnings} warning(s)`));
|
|
process.exit(1);
|
|
} else if (hasWarnings && options.strict) {
|
|
console.log(chalk.yellow.bold(` ${totalWarnings} warning(s) (strict mode)`));
|
|
process.exit(1);
|
|
} else if (hasWarnings) {
|
|
console.log(chalk.yellow(` All files valid with ${totalWarnings} warning(s)`));
|
|
} else {
|
|
console.log(chalk.green.bold(' All files valid!'));
|
|
}
|
|
} catch (error) {
|
|
handleError(error, 'Validation failed');
|
|
}
|
|
});
|
|
|
|
// Migrate command
|
|
program
|
|
.command('migrate')
|
|
.description('Migrate from Claude Code (CLAUDE.md) to Codex (AGENTS.md)')
|
|
.option('-f, --from <file>', 'Source CLAUDE.md file', 'CLAUDE.md')
|
|
.option('-o, --output <path>', 'Output directory', process.cwd())
|
|
.option('--analyze-only', 'Only analyze, do not generate files', false)
|
|
.option('--generate-skills', 'Generate skill files from detected patterns', true)
|
|
.option('--preserve-comments', 'Preserve comments from original file', true)
|
|
.action(async (options) => {
|
|
try {
|
|
printBanner();
|
|
|
|
const sourcePath = path.resolve(options.from);
|
|
|
|
if (!await fs.pathExists(sourcePath)) {
|
|
console.error(chalk.red(`Source file not found: ${sourcePath}`));
|
|
console.log(chalk.gray('\nLooking for CLAUDE.md in the current directory.'));
|
|
console.log(chalk.gray('Use --from <path> to specify a different source file.'));
|
|
process.exit(1);
|
|
}
|
|
|
|
let content: string;
|
|
try {
|
|
content = await fs.readFile(sourcePath, 'utf-8');
|
|
} catch (error) {
|
|
handleError(error, `Cannot read source file: ${sourcePath}`);
|
|
}
|
|
|
|
if (options.analyzeOnly) {
|
|
console.log(chalk.blue('Analyzing CLAUDE.md...'));
|
|
console.log(chalk.gray(`Source: ${sourcePath}\n`));
|
|
|
|
const analysis = await analyzeClaudeMd(content);
|
|
|
|
console.log(chalk.white.bold('Sections found:'));
|
|
if (analysis.sections.length > 0) {
|
|
for (const section of analysis.sections) {
|
|
console.log(chalk.gray(` - ${section}`));
|
|
}
|
|
} else {
|
|
console.log(chalk.gray(' (none)'));
|
|
}
|
|
|
|
console.log(chalk.white.bold('\nSkills detected:'));
|
|
if (analysis.skills.length > 0) {
|
|
for (const skill of analysis.skills) {
|
|
console.log(chalk.gray(` - /${skill} ${chalk.cyan('->')} $${skill}`));
|
|
}
|
|
} else {
|
|
console.log(chalk.gray(' (none)'));
|
|
}
|
|
|
|
console.log(chalk.white.bold('\nHooks used:'));
|
|
if (analysis.hooks.length > 0) {
|
|
for (const hook of analysis.hooks) {
|
|
console.log(chalk.gray(` - ${hook}`));
|
|
}
|
|
} else {
|
|
console.log(chalk.gray(' (none)'));
|
|
}
|
|
|
|
console.log(chalk.white.bold('\nCustom instructions:'));
|
|
if (analysis.customInstructions.length > 0) {
|
|
for (const instruction of analysis.customInstructions.slice(0, 5)) {
|
|
console.log(chalk.gray(` - ${instruction.substring(0, 60)}...`));
|
|
}
|
|
if (analysis.customInstructions.length > 5) {
|
|
console.log(chalk.gray(` ... and ${analysis.customInstructions.length - 5} more`));
|
|
}
|
|
} else {
|
|
console.log(chalk.gray(' (none)'));
|
|
}
|
|
|
|
if (analysis.warnings.length > 0) {
|
|
console.log(chalk.yellow.bold('\nMigration warnings:'));
|
|
for (const warning of analysis.warnings) {
|
|
console.log(chalk.yellow(` ! ${warning}`));
|
|
}
|
|
}
|
|
|
|
console.log();
|
|
} else {
|
|
console.log(chalk.blue('Migrating to Codex...'));
|
|
console.log(chalk.gray(`Source: ${sourcePath}`));
|
|
console.log(chalk.gray(`Output: ${path.resolve(options.output)}\n`));
|
|
|
|
const result = await migrateFromClaudeCode({
|
|
sourcePath,
|
|
targetPath: options.output,
|
|
generateSkills: options.generateSkills,
|
|
preserveComments: options.preserveComments,
|
|
});
|
|
|
|
const report = generateMigrationReport(result);
|
|
console.log(report);
|
|
|
|
if (result.success) {
|
|
console.log(chalk.green.bold('\n Migration completed successfully!'));
|
|
console.log(chalk.gray('\n Next steps:'));
|
|
console.log(chalk.gray(' 1. Review the generated AGENTS.md'));
|
|
console.log(chalk.gray(' 2. Check skill invocation syntax (/ -> $)'));
|
|
console.log(chalk.gray(' 3. Run `claude-flow-codex validate` to verify'));
|
|
console.log();
|
|
} else {
|
|
console.log(chalk.red.bold('\n Migration failed'));
|
|
process.exit(1);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
handleError(error, 'Migration failed');
|
|
}
|
|
});
|
|
|
|
// Templates command
|
|
program
|
|
.command('templates')
|
|
.alias('list-templates')
|
|
.description('List available templates')
|
|
.option('--json', 'Output as JSON', false)
|
|
.action((options) => {
|
|
try {
|
|
const templates = listTemplates();
|
|
|
|
if (options.json) {
|
|
console.log(JSON.stringify(templates, null, 2));
|
|
return;
|
|
}
|
|
|
|
printBanner();
|
|
console.log(chalk.white.bold('Available templates:\n'));
|
|
|
|
for (const template of templates) {
|
|
console.log(chalk.cyan.bold(` ${template.name}`));
|
|
console.log(chalk.gray(` ${template.description}`));
|
|
console.log(chalk.gray(` Skills: ${template.skillCount} included`));
|
|
console.log();
|
|
}
|
|
|
|
console.log(chalk.gray('Use: claude-flow-codex init --template <name>'));
|
|
console.log();
|
|
} catch (error) {
|
|
handleError(error, 'Failed to list templates');
|
|
}
|
|
});
|
|
|
|
// Skills command
|
|
program
|
|
.command('skills')
|
|
.alias('list-skills')
|
|
.description('List available built-in skills')
|
|
.option('--json', 'Output as JSON', false)
|
|
.action((options) => {
|
|
try {
|
|
if (options.json) {
|
|
console.log(JSON.stringify(BUILT_IN_SKILLS, null, 2));
|
|
return;
|
|
}
|
|
|
|
printBanner();
|
|
console.log(chalk.white.bold('Built-in skills:\n'));
|
|
|
|
for (const [name, info] of Object.entries(BUILT_IN_SKILLS)) {
|
|
console.log(chalk.cyan(` $${name}`));
|
|
console.log(chalk.gray(` ${info.description}`));
|
|
console.log(chalk.gray(` Category: ${info.category}`));
|
|
console.log();
|
|
}
|
|
|
|
console.log(chalk.gray('Use: claude-flow-codex generate-skill -n <name> to create a custom skill'));
|
|
console.log();
|
|
} catch (error) {
|
|
handleError(error, 'Failed to list skills');
|
|
}
|
|
});
|
|
|
|
// Info command
|
|
program
|
|
.command('info')
|
|
.description('Show package information')
|
|
.option('--json', 'Output as JSON', false)
|
|
.action((options) => {
|
|
try {
|
|
if (options.json) {
|
|
console.log(JSON.stringify(PACKAGE_INFO, null, 2));
|
|
return;
|
|
}
|
|
|
|
console.log(chalk.cyan.bold('\n @claude-flow/codex'));
|
|
console.log(chalk.gray(' ' + '='.repeat(40)));
|
|
console.log(chalk.white(` Version: ${PACKAGE_INFO.version}`));
|
|
console.log(chalk.white(` Description: ${PACKAGE_INFO.description}`));
|
|
console.log(chalk.white(` Future: ${PACKAGE_INFO.futureUmbrella} (umbrella package)`));
|
|
console.log(chalk.white(` Repository: ${PACKAGE_INFO.repository}`));
|
|
console.log(chalk.gray(' ' + '='.repeat(40)));
|
|
console.log(chalk.gray('\n Part of the coflow rebranding initiative'));
|
|
console.log();
|
|
} catch (error) {
|
|
handleError(error, 'Failed to show info');
|
|
}
|
|
});
|
|
|
|
// Doctor command - check system health
|
|
program
|
|
.command('doctor')
|
|
.description('Check system health and dependencies')
|
|
.action(async () => {
|
|
try {
|
|
printBanner();
|
|
console.log(chalk.blue('Running health checks...\n'));
|
|
|
|
const checks: Array<{ name: string; status: 'pass' | 'warn' | 'fail'; message: string }> = [];
|
|
|
|
// Check Node.js version
|
|
const nodeVersion = process.version;
|
|
const nodeMajor = parseInt(nodeVersion.slice(1).split('.')[0] ?? '0', 10);
|
|
if (nodeMajor >= 18) {
|
|
checks.push({ name: 'Node.js', status: 'pass', message: `${nodeVersion} (>= 18 required)` });
|
|
} else {
|
|
checks.push({ name: 'Node.js', status: 'fail', message: `${nodeVersion} (>= 18 required)` });
|
|
}
|
|
|
|
// Check for AGENTS.md in current directory
|
|
const agentsMdExists = await fs.pathExists(path.join(process.cwd(), 'AGENTS.md'));
|
|
if (agentsMdExists) {
|
|
checks.push({ name: 'AGENTS.md', status: 'pass', message: 'Found in current directory' });
|
|
} else {
|
|
checks.push({ name: 'AGENTS.md', status: 'warn', message: 'Not found - run init to create' });
|
|
}
|
|
|
|
// Check for .agents directory
|
|
const agentsDir = await fs.pathExists(path.join(process.cwd(), '.agents'));
|
|
if (agentsDir) {
|
|
checks.push({ name: '.agents/', status: 'pass', message: 'Directory exists' });
|
|
} else {
|
|
checks.push({ name: '.agents/', status: 'warn', message: 'Not found - run init to create' });
|
|
}
|
|
|
|
// Check for config.toml
|
|
const configExists = await fs.pathExists(path.join(process.cwd(), '.agents', 'config.toml'));
|
|
if (configExists) {
|
|
checks.push({ name: 'config.toml', status: 'pass', message: 'Found in .agents/' });
|
|
} else {
|
|
checks.push({ name: 'config.toml', status: 'warn', message: 'Not found' });
|
|
}
|
|
|
|
// Check for git
|
|
try {
|
|
const gitExists = await fs.pathExists(path.join(process.cwd(), '.git'));
|
|
if (gitExists) {
|
|
checks.push({ name: 'Git', status: 'pass', message: 'Repository detected' });
|
|
} else {
|
|
checks.push({ name: 'Git', status: 'warn', message: 'Not a git repository' });
|
|
}
|
|
} catch {
|
|
checks.push({ name: 'Git', status: 'warn', message: 'Cannot check' });
|
|
}
|
|
|
|
// Print results
|
|
let hasFailures = false;
|
|
for (const check of checks) {
|
|
const icon = check.status === 'pass' ? chalk.green('PASS')
|
|
: check.status === 'warn' ? chalk.yellow('WARN')
|
|
: chalk.red('FAIL');
|
|
|
|
console.log(` ${icon} ${chalk.white(check.name)}`);
|
|
console.log(chalk.gray(` ${check.message}`));
|
|
|
|
if (check.status === 'fail') {
|
|
hasFailures = true;
|
|
}
|
|
}
|
|
|
|
console.log();
|
|
if (hasFailures) {
|
|
console.log(chalk.red.bold(' Some checks failed'));
|
|
process.exit(1);
|
|
} else {
|
|
console.log(chalk.green.bold(' All checks passed!'));
|
|
}
|
|
console.log();
|
|
} catch (error) {
|
|
handleError(error, 'Health check failed');
|
|
}
|
|
});
|
|
|
|
// Dual-mode command - collaborative Claude Code + Codex execution
|
|
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(' ')}`));
|
|
console.log(chalk.gray(`Run ${chalk.white('claude-flow-codex --help')} for available commands.`));
|
|
process.exit(1);
|
|
});
|
|
|
|
// Parse and run
|
|
program.parse();
|
|
|
|
// If no command provided, show help
|
|
if (!process.argv.slice(2).length) {
|
|
printBanner();
|
|
program.outputHelp();
|
|
}
|