feat(init): dual init uses AGENTS.md as the single instruction source (#2638)

`ruflo init --dual` (and `@claude-flow/codex init --dual`) wrote two divergent
instruction files. Now AGENTS.md carries the shared sections once plus the
Codex-only ones, and CLAUDE.md is Claude Code's `@AGENTS.md` import plus only
the Claude-specific sections.

- codex/src/generators/shared-instructions.ts: the shared sections (rules,
  swarm routing, memory & learning, agents, build & test, CLI reference).
  The CLI keeps a byte-identical mirror (a test compares the files) because
  it resolves @claude-flow/codex from the registry at the pinned version.
- claudemd-generator.ts builds its shared sections from that module;
  single-host output is byte-identical (snapshot recorded on origin/main).
  New generateDualClaudeMd keeps only Claude-only sections + template extras.
- Existing CLAUDE.md is only replaced when missing, generated by init and
  unedited, or under --force (backed up); otherwise kept with migration steps.
- After the Codex pass, finalizeDualInstructions keeps the import only if
  AGENTS.md carries every shared section verbatim; else the full CLAUDE.md
  is written back, so an older codex adapter cannot lose content.
- commands/init.ts (outside the lane's file list): pass instructionsSource and
  dual to the two passes, run the finalize step, never pass --dual to a
  fetched adapter of unknown version.

Fixes #2638

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
randRuFlo committed 2026-11-09 12:46:42 -05:00
1 parent 29be054e85
commit 36188f602c
19 files changed
+7515 -219

No files matched your search

@@ -77,7 +77,7 @@ describe('native dual initialization (#2636)', () => {
expect(codexMock.initialize).toHaveBeenCalledWith(expect.objectContaining({
projectPath,
template: 'minimal',
dual: false,
dual: true,
}));
});
});
@@ -0,0 +1,189 @@
/**
* #2638 — `init --dual`: AGENTS.md is the single source for the shared
* sections; CLAUDE.md is `@AGENTS.md` plus Claude-only sections.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { CommandContext } from '../src/types.js';
// The Codex package that writes AGENTS.md: its workspace source, not the
// registry copy the CLI pins.
import { generateDualAgentsMd } from '../../codex/src/generators/dual-instructions.js';
const codexMock = vi.hoisted(() => ({ initialize: vi.fn() }));
vi.mock('@claude-flow/codex', () => ({
CodexInitializer: class {
initialize = codexMock.initialize;
},
}));
import { initCommand } from '../src/commands/init.js';
import { generateClaudeMd, generateDualClaudeMd, sharedSectionsForImport } from '../src/init/claudemd-generator.js';
import { finalizeDualInstructions, writeDualClaudeMd } from '../src/init/dual-instructions.js';
import { executeInit } from '../src/init/executor.js';
import { DEFAULT_INIT_OPTIONS, MINIMAL_INIT_OPTIONS, type ClaudeMdTemplate, type InitOptions, type InitResult } from '../src/init/types.js';
const here = fileURLToPath(new URL('.', import.meta.url));
const TEMPLATES: ClaudeMdTemplate[] = ['minimal', 'standard', 'full', 'security', 'performance', 'solo'];
const h2 = (md: string) => md.split('\n').filter((l) => /^## /.test(l));
const importLine = (md: string) => md.split('\n').some((l) => l.trim() === '@AGENTS.md');
function emptyResult(): InitResult {
return {
success: true,
platform: {} as InitResult['platform'],
created: { directories: [], files: [] },
skipped: [],
errors: [],
summary: { skillsCount: 0, commandsCount: 0, agentsCount: 0, hooksEnabled: 0 },
};
}
describe('shared sections have one source (#2638)', () => {
it('the CLI mirror is byte-identical to the codex module', () => {
const canonical = readFileSync(join(here, '../../codex/src/generators/shared-instructions.ts'), 'utf-8');
const mirror = readFileSync(join(here, '../src/init/shared-instructions.ts'), 'utf-8');
expect(mirror).toBe(canonical);
});
it('the single-host CLAUDE.md contains every shared section verbatim (no drift)', () => {
const md = generateClaudeMd(DEFAULT_INIT_OPTIONS, 'standard');
// Rules and Swarm are split around Claude-only lines, so check their shared lines.
for (const section of sharedSectionsForImport().slice(2)) expect(md).toContain(section);
});
});
describe('generateDualClaudeMd (#2638)', () => {
const agents = generateDualAgentsMd({ projectName: 'demo' });
for (const template of TEMPLATES) {
it(`${template}: imports AGENTS.md, repeats no shared section, loses no line`, () => {
const dual = generateDualClaudeMd(DEFAULT_INIT_OPTIONS, template);
expect(importLine(dual)).toBe(true);
for (const section of sharedSectionsForImport()) expect(dual).not.toContain(section);
expect(h2(dual).filter((h) => h2(agents).includes(h))).toEqual([]);
// Lossless: every line of the single-host file is in CLAUDE.md or AGENTS.md.
const single = generateClaudeMd(DEFAULT_INIT_OPTIONS, template);
const missing = single.split('\n')
.filter((l) => l.trim() && !/^#{1,3} /.test(l))
.filter((l) => !dual.includes(l) && !agents.includes(l));
expect(missing).toEqual([]);
});
}
});
describe('writeDualClaudeMd + finalizeDualInstructions (#2638)', () => {
let dir: string;
const options = (): InitOptions => ({ ...structuredClone(DEFAULT_INIT_OPTIONS), targetDir: dir });
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'dual-2638-')); });
afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
it('writes the import form when CLAUDE.md does not exist', () => {
const result = emptyResult();
writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result);
expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true);
expect(result.dualInstructions).toBeDefined();
});
it('keeps a user-modified CLAUDE.md and says how to migrate', () => {
writeFileSync(join(dir, 'CLAUDE.md'), '# mine\n', 'utf-8');
const result = emptyResult();
writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result);
expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe('# mine\n');
expect(result.skipped.join('\n')).toMatch(/move your custom sections into AGENTS\.md.*@AGENTS\.md/);
expect(result.dualInstructions).toBeUndefined();
});
it('converts a CLAUDE.md that init generated and nobody edited', () => {
const opts = options();
writeFileSync(join(dir, 'CLAUDE.md'), generateClaudeMd(opts), 'utf-8');
const result = emptyResult();
writeDualClaudeMd(join(dir, 'CLAUDE.md'), opts, result);
expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true);
expect(existsSync(join(dir, 'CLAUDE.md.pre-ruflo'))).toBe(false);
});
it('--force replaces a user CLAUDE.md after backing it up', () => {
writeFileSync(join(dir, 'CLAUDE.md'), '# mine\n', 'utf-8');
const result = emptyResult();
writeDualClaudeMd(join(dir, 'CLAUDE.md'), { ...options(), force: true }, result);
expect(readFileSync(join(dir, 'CLAUDE.md.pre-ruflo'), 'utf-8')).toBe('# mine\n');
expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true);
});
it('keeps the import when AGENTS.md carries the shared sections', () => {
const result = emptyResult();
writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result);
writeFileSync(join(dir, 'AGENTS.md'), generateDualAgentsMd({ projectName: 'demo' }), 'utf-8');
expect(finalizeDualInstructions(dir, result).action).toBe('import');
expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true);
});
it('restores the full CLAUDE.md when AGENTS.md lacks the shared sections (old codex / failed pass)', () => {
const result = emptyResult();
writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result);
writeFileSync(join(dir, 'AGENTS.md'), '# Native Codex Instructions\n', 'utf-8');
expect(finalizeDualInstructions(dir, result).action).toBe('restored');
expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe(result.dualInstructions!.fullForm);
});
it('never touches a CLAUDE.md changed after the Claude pass', () => {
const result = emptyResult();
writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result);
writeFileSync(join(dir, 'CLAUDE.md'), '# edited\n', 'utf-8');
expect(finalizeDualInstructions(dir, result).action).toBe('none');
expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe('# edited\n');
});
it('single-host executeInit still writes the full CLAUDE.md', async () => {
const opts = { ...structuredClone(MINIMAL_INIT_OPTIONS), targetDir: dir, skipGlobalClaudeMd: true };
await executeInit(opts);
expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(false);
});
});
describe('ruflo init --dual end to end (#2638)', () => {
let dir: string;
let configDir: string;
let saved: string | undefined;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'dual-e2e-2638-'));
configDir = mkdtempSync(join(tmpdir(), 'dual-e2e-cfg-'));
saved = process.env.CLAUDE_CONFIG_DIR;
process.env.CLAUDE_CONFIG_DIR = configDir;
codexMock.initialize.mockImplementation(async (o: Record<string, unknown>) => {
const target = String(o.projectPath);
// Stand-in for the codex initializer: dual → the real dual AGENTS.md.
writeFileSync(join(target, 'AGENTS.md'), o.dual ? generateDualAgentsMd({ projectName: 'demo' }) : '# single\n', 'utf8');
return { success: true, filesCreated: ['AGENTS.md'], skillsGenerated: [], warnings: [] };
});
});
afterEach(() => {
vi.clearAllMocks();
if (saved === undefined) delete process.env.CLAUDE_CONFIG_DIR;
else process.env.CLAUDE_CONFIG_DIR = saved;
rmSync(dir, { recursive: true, force: true });
rmSync(configDir, { recursive: true, force: true });
});
it('CLAUDE.md imports AGENTS.md and no section is in both files', async () => {
const ctx: CommandContext = {
args: [],
flags: { _: [], dual: true, minimal: true, global: false, 'no-signup': true, 'no-skills-sh': true },
cwd: dir,
interactive: false,
};
const result = await initCommand.action!(ctx);
expect(result?.success).toBe(true);
expect(codexMock.initialize).toHaveBeenCalledWith(expect.objectContaining({ dual: true }));
const claude = readFileSync(join(dir, 'CLAUDE.md'), 'utf-8');
const agents = readFileSync(join(dir, 'AGENTS.md'), 'utf-8');
expect(importLine(claude)).toBe(true);
expect(h2(claude).filter((h) => h2(agents).includes(h))).toEqual([]);
});
});
@@ -0,0 +1,68 @@
/**
* #2638 — single-host CLAUDE.md output must not change.
*
* Recorded on origin/main before the dual-mode single-source work. Splitting
* the section generators into shared and Claude-only parts must reproduce
* these bytes exactly for every template and preset.
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { generateClaudeMd } from '../src/init/claudemd-generator.js';
import {
DEFAULT_INIT_OPTIONS,
FULL_INIT_OPTIONS,
MINIMAL_INIT_OPTIONS,
type ClaudeMdTemplate,
type InitOptions,
} from '../src/init/types.js';
import { executeInit } from '../src/init/executor.js';
const TEMPLATES: ClaudeMdTemplate[] = ['minimal', 'standard', 'full', 'security', 'performance', 'solo'];
const PRESETS: Array<[string, InitOptions]> = [
['default', DEFAULT_INIT_OPTIONS],
['minimal', MINIMAL_INIT_OPTIONS],
['full', FULL_INIT_OPTIONS],
];
describe('single-host CLAUDE.md is unchanged (#2638)', () => {
for (const [preset, options] of PRESETS) {
for (const template of TEMPLATES) {
it(`generateClaudeMd(${preset}, ${template})`, () => {
expect(generateClaudeMd(options, template)).toMatchSnapshot();
});
}
}
describe('executeInit writes the same CLAUDE.md', () => {
let dir: string;
let configDir: string;
let savedConfigDir: string | undefined;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'claudemd-snap-'));
// Hermetic: no installed Claude Code plugins visible to init.
configDir = mkdtempSync(join(tmpdir(), 'claudemd-snap-cfg-'));
savedConfigDir = process.env.CLAUDE_CONFIG_DIR;
process.env.CLAUDE_CONFIG_DIR = configDir;
});
afterEach(() => {
if (savedConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
else process.env.CLAUDE_CONFIG_DIR = savedConfigDir;
rmSync(dir, { recursive: true, force: true });
rmSync(configDir, { recursive: true, force: true });
});
for (const [preset, base] of PRESETS) {
it(`${preset} preset`, async () => {
const options: InitOptions = structuredClone(base);
options.targetDir = dir;
options.skipGlobalClaudeMd = true;
options.components = { ...options.components, helpers: false, statusline: false, settings: false };
const result = await executeInit(options);
expect(result.success).toBe(true);
expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toMatchSnapshot();
});
}
});
});
+23 -5
View File
@@ -16,7 +16,9 @@ import {
DEFAULT_INIT_OPTIONS,
MINIMAL_INIT_OPTIONS,
FULL_INIT_OPTIONS,
finalizeDualInstructions,
type InitOptions,
type InitResult,
} from '../init/index.js';
import { executeGrokInit } from '../init/grok-generator.js';
import {
@@ -592,7 +594,10 @@ async function initCodexAction(
if (!CodexInitializer) {
spinner.stop();
output.printInfo('Fetching the stable Codex adapter for this initialization...');
const success = runCodexInitializerCli(ctx.cwd, { template, force, dual: dualMode, codexTrust });
// #2638: never pass --dual to a fetched adapter of unknown version — an
// older one rewrites CLAUDE.md with its own stub under --force. Without
// it, finalizeDualInstructions keeps the full CLAUDE.md.
const success = runCodexInitializerCli(ctx.cwd, { template, force, dual: false, codexTrust });
if (!success) {
output.printError('Codex initialization failed while running @claude-flow/codex@latest.');
return { success: false, exitCode: 1 };
@@ -842,6 +847,11 @@ const initClaudeAction = async (ctx: CommandContext): Promise<CommandResult> =>
options.skipGlobalClaudeMd = true;
}
// #2638 — set by the --dual route below: CLAUDE.md imports AGENTS.md.
if (ctx.flags.instructionsSource === 'agents-md') {
options.instructionsSource = 'agents-md';
}
const riskyMode = riskyModeFromFlags(ctx.flags);
if (typeof riskyMode === 'object') {
output.printError(riskyMode.error);
@@ -1124,8 +1134,9 @@ const initClaudeAction = async (ctx: CommandContext): Promise<CommandResult> =>
/**
* Route platform initialization. Dual mode deliberately runs both native
* initializers: Claude Code first, then Codex without its compatibility
* CLAUDE.md stub so the full native Claude scaffold remains authoritative.
* initializers: Claude Code first, then Codex. #2638: AGENTS.md carries the
* shared instruction sections once and CLAUDE.md imports it (`@AGENTS.md`)
* with only the Claude-specific sections; the .claude/ scaffold is unchanged.
*/
const initAction = async (ctx: CommandContext): Promise<CommandResult> => {
const force = ctx.flags.force as boolean;
@@ -1159,6 +1170,8 @@ const initAction = async (ctx: CommandContext): Promise<CommandResult> => {
dual: false,
// The explicit Codex pass below owns Codex setup.
'no-codex-detect': true,
// #2638 — AGENTS.md owns the shared sections; CLAUDE.md imports it.
instructionsSource: 'agents-md',
},
};
const claudeResult = await initClaudeAction(claudeContext);
@@ -1166,12 +1179,17 @@ const initAction = async (ctx: CommandContext): Promise<CommandResult> => {
const codexResult = await initCodexAction(ctx, {
codexMode: true,
// Preserve the full CLAUDE.md and .claude/ scaffold just generated.
dualMode: false,
// #2638 — dual AGENTS.md (shared + Codex-only sections). Codex leaves a
// CLAUDE.md that already imports AGENTS.md alone.
dualMode: true,
force,
minimal,
full,
});
// Keep the @AGENTS.md import only if AGENTS.md really carries the shared
// sections; otherwise the full CLAUDE.md is written back.
const instructions = finalizeDualInstructions(ctx.cwd, claudeResult.data as InitResult | undefined);
if (instructions.action === 'restored' && instructions.message) output.printWarning(instructions.message);
if (!codexResult.success) {
return {
...codexResult,
@@ -7,21 +7,30 @@
*/
import type { InitOptions, ClaudeMdTemplate } from './types.js';
import {
AGENTS_MD_IMPORT,
CLAUDE_RULE_INSERT_AT,
SHARED_RULE_LINES,
SWARM_ROUTING_BODY,
sharedAgentTypes,
sharedBuildAndTest,
sharedCliQuickRef,
sharedMemoryAndLearning,
} from './shared-instructions.js';
// --- Section Generators ---
//
// #2638: sections both hosts share come from shared-instructions.ts (the
// mirror of the codex module that writes them into AGENTS.md). Everything
// left in this file is Claude-specific, or a template extra.
/** Claude-only: the Claude Code Bash tool suggests this trailer; Codex has its own commit rule. */
const CO_AUTHORED_BY_RULE = '- NEVER add a `Co-Authored-By` trailer to user commits unless this project\'s `.claude/settings.json` has `attribution.commit` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. `Co-Authored-By` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author.';
function behavioralRules(): string {
return `## Rules
- Do what has been asked; nothing more, nothing less
- NEVER create files unless absolutely necessary — prefer editing existing files
- NEVER create documentation files unless explicitly requested
- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\`
- ALWAYS read a file before editing it
- NEVER commit secrets, credentials, or .env files
- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author.
- Keep files under 500 lines
- Validate input at system boundaries`;
const lines = [...SHARED_RULE_LINES];
lines.splice(CLAUDE_RULE_INSERT_AT, 0, CO_AUTHORED_BY_RULE);
return `## Rules\n\n${lines.join('\n')}`;
}
function policyGovernedWorkflow(): string {
@@ -116,113 +125,32 @@ SendMessage({ to: "researcher", summary: "Start", message: "[task context]" })
- Give every writing agent an isolated worktree and a non-overlapping file scope`;
}
function swarmConfig(options: InitOptions): string {
return `## Swarm & Routing
### Config
function swarmRuntimeConfig(options: InitOptions): string {
return `### Config
- **Topology**: ${options.runtime.topology} (anti-drift)
- **Max Agents**: ${options.runtime.maxAgents}
- **Memory**: ${options.runtime.memoryBackend}
- **HNSW**: ${options.runtime.enableHNSW ? 'Enabled' : 'Disabled'}
- **Neural**: ${options.runtime.enableNeural ? 'Enabled' : 'Disabled'}
- **Neural**: ${options.runtime.enableNeural ? 'Enabled' : 'Disabled'}`;
}
\`\`\`bash
npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized
\`\`\`
### Agent Routing
| Task | Agents | Topology |
|------|--------|----------|
| Bug Fix | researcher, coder, tester | hierarchical |
| Feature | architect, coder, tester, reviewer | hierarchical |
| Refactor | architect, coder, reviewer | hierarchical |
| Performance | perf-engineer, coder | hierarchical |
| Security | security-architect, auditor | hierarchical |
### When to Swarm
- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance
- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions
### 3-Tier Model Routing
/** Claude-only: the tiers map onto Claude Code's Agent tool `model` choices. */
const THREE_TIER_ROUTING = `### 3-Tier Model Routing
| Tier | Handler | Use Cases |
|------|---------|-----------|
| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly |
| 2 | Haiku | Simple tasks, low complexity |
| 3 | Sonnet/Opus | Architecture, security, complex reasoning |`;
function swarmConfig(options: InitOptions): string {
return `## Swarm & Routing\n\n${swarmRuntimeConfig(options)}\n\n${SWARM_ROUTING_BODY}\n\n${THREE_TIER_ROUTING}`;
}
function memoryAndLearning(): string {
return `## Memory & Learning
### Before Any Task
\`\`\`bash
npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns
npx @claude-flow/cli@latest hooks route --task "[task description]"
\`\`\`
### After Success
\`\`\`bash
npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]"
npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true
\`\`\`
### MCP Tools (use \`ToolSearch("keyword")\` to discover)
| Category | Key Tools |
|----------|-----------|
| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` |
| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` |
| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` |
| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` |
| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` |
| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` |
| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` |
### Background Workers
| Worker | When |
|--------|------|
| \`audit\` | After security changes |
| \`optimize\` | After performance work |
| \`testgaps\` | After adding features |
| \`map\` | Every 5+ file changes |
| \`document\` | After API changes |
\`\`\`bash
npx @claude-flow/cli@latest hooks worker dispatch --trigger audit
\`\`\``;
}
function agentTypes(): string {
return `## Agents
**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\`
**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\`
**Security**: \`security-architect\`, \`security-auditor\`
**Performance**: \`performance-engineer\`, \`perf-analyzer\`
**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\`
**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\`
Any string works as a custom agent type.`;
}
function cliQuickRef(): string {
return `## CLI Quick Reference
\`\`\`bash
npx @claude-flow/cli@latest init --wizard # Setup
npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm
npx @claude-flow/cli@latest memory search --query "" # Vector search
npx @claude-flow/cli@latest hooks route --task "" # Route to agent
npx @claude-flow/cli@latest doctor --fix # Diagnostics
npx @claude-flow/cli@latest security scan # Security scan
npx @claude-flow/cli@latest performance benchmark # Benchmarks
\`\`\`
26 commands, 140+ subcommands. Use \`--help\` on any command for details.`;
}
const memoryAndLearning = sharedMemoryAndLearning;
const agentTypes = sharedAgentTypes;
const cliQuickRef = sharedCliQuickRef;
const buildAndTest = sharedBuildAndTest;
function setupAndBoundary(): string {
return `## Setup
@@ -240,17 +168,6 @@ npx ruflo@latest doctor --fix
**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash.`;
}
function buildAndTest(): string {
return `## Build & Test
- ALWAYS run tests after code changes
- ALWAYS verify build succeeds before committing
\`\`\`bash
npm run build && npm test
\`\`\``;
}
function securitySection(): string {
return `## Security
@@ -433,6 +350,41 @@ export function generateMinimalClaudeMd(options: InitOptions): string {
return generateClaudeMd(options, 'minimal');
}
/** The sections a CLAUDE.md that imports AGENTS.md must not repeat. */
export function sharedSectionsForImport(): string[] {
return [
`## Rules\n\n${SHARED_RULE_LINES.join('\n')}`,
`## Swarm & Routing\n\n${SWARM_ROUTING_BODY}`,
sharedMemoryAndLearning(),
sharedAgentTypes(),
sharedBuildAndTest(),
sharedCliQuickRef(),
];
}
/**
* #2638 dual mode: CLAUDE.md imports AGENTS.md (which carries the shared
* sections) and keeps only what is Claude-specific, plus any template extras
* the shared set does not cover. Nothing here repeats a shared section.
*/
export function generateDualClaudeMd(options: InitOptions, template?: ClaudeMdTemplate): string {
const tmpl = template ?? options.runtime.claudeMdTemplate ?? 'standard';
const sections = TEMPLATE_SECTIONS[tmpl] ?? TEMPLATE_SECTIONS.standard;
const shared = new Set(sharedSectionsForImport());
const body = sections.map((fn) => {
if (fn === behavioralRules) return `## Claude Code Rules\n\n${CO_AUTHORED_BY_RULE}`;
if (fn === swarmConfig) return `## Swarm Runtime & Model Routing\n\n${swarmRuntimeConfig(options)}\n\n${THREE_TIER_ROUTING}`;
const text = fn(options);
return shared.has(text) ? null : text;
}).filter((s): s is string => s !== null).join('\n\n');
const header = `# Ruflo — Claude Code Configuration\n\n${AGENTS_MD_IMPORT}\n\n` +
'> Shared project instructions live in `AGENTS.md`, imported above; OpenAI Codex reads the same file. ' +
'Edit shared rules there. This file holds only Claude Code–specific guidance.\n';
return `${header}\n${body}\n`;
}
export const CLAUDE_MD_TEMPLATES: Array<{ name: ClaudeMdTemplate; description: string }> = [
{ name: 'minimal', description: 'Lean start — rules, agent comms, swarm config, CLI ref (~80 lines)' },
{ name: 'standard', description: 'Recommended — adds memory, learning, agent types (~140 lines)' },
@@ -0,0 +1,101 @@
/**
* #2638 — dual-host instructions with one source.
*
* `init --dual` makes AGENTS.md the single source for the sections both hosts
* share. CLAUDE.md becomes Claude Code's `@AGENTS.md` import plus only the
* Claude-specific sections. Two steps:
*
* 1. writeDualClaudeMd (Claude pass) writes the import form, but only over a
* CLAUDE.md that is missing, already ours and unmodified, or --force.
* 2. finalizeDualInstructions (after the Codex pass) checks that AGENTS.md
* really carries every shared section. If it does not (Codex init failed,
* or an older @claude-flow/codex wrote the single-host AGENTS.md), the full
* single-host CLAUDE.md is written back, so nothing is lost.
*/
import * as fs from 'fs';
import * as path from 'path';
import type { InitOptions, InitResult } from './types.js';
import { generateClaudeMd, generateDualClaudeMd, sharedSectionsForImport } from './claudemd-generator.js';
import { importsAgentsMd } from './shared-instructions.js';
export const DUAL_MIGRATION_HINT =
'to share instructions with Codex, move your custom sections into AGENTS.md and replace the shared ones ' +
'with a line `@AGENTS.md`, or re-run with --force (the current file is backed up to CLAUDE.md.pre-ruflo)';
function inferredTemplate(options: InitOptions) {
return (!options.components.commands && !options.components.agents) ? 'minimal' as const : undefined;
}
function backup(claudeMdPath: string, result: InitResult): void {
const base = `${claudeMdPath}.pre-ruflo`;
const target = fs.existsSync(base) ? `${base}.${Date.now()}` : base;
fs.copyFileSync(claudeMdPath, target);
result.created.files.push(path.basename(target));
}
/** Claude pass of `init --dual`: write CLAUDE.md as the AGENTS.md import form when it is safe to. */
export function writeDualClaudeMd(claudeMdPath: string, options: InitOptions, result: InitResult): void {
const template = inferredTemplate(options);
const fullForm = generateClaudeMd(options, template);
const importForm = generateDualClaudeMd(options, template);
if (fs.existsSync(claudeMdPath)) {
const existing = fs.readFileSync(claudeMdPath, 'utf-8');
if (existing === importForm || (importsAgentsMd(existing) && !options.force)) {
result.skipped.push('CLAUDE.md (already imports AGENTS.md)');
return;
}
const ours = existing === fullForm;
if (!ours && !options.force) {
result.skipped.push(`CLAUDE.md (has your own content; ${DUAL_MIGRATION_HINT})`);
return;
}
if (!ours) backup(claudeMdPath, result);
}
fs.writeFileSync(claudeMdPath, importForm, 'utf-8');
result.created.files.push('CLAUDE.md (imports AGENTS.md)');
result.dualInstructions = { importForm, fullForm };
}
export interface DualFinalizeOutcome {
/** `import`: CLAUDE.md imports AGENTS.md. `restored`: full CLAUDE.md written back. `none`: nothing to do. */
action: 'import' | 'restored' | 'none';
message?: string;
}
/**
* After the Codex pass: keep the import form only when AGENTS.md carries every
* shared section verbatim. Never touches a CLAUDE.md this run did not write.
*/
export function finalizeDualInstructions(targetDir: string, claudeResult: InitResult | undefined): DualFinalizeOutcome {
const dual = claudeResult?.dualInstructions;
if (!dual) return { action: 'none' };
const claudeMdPath = path.join(targetDir, 'CLAUDE.md');
let current: string | undefined;
try {
current = fs.readFileSync(claudeMdPath, 'utf-8');
} catch {
return { action: 'none' };
}
if (current !== dual.importForm) return { action: 'none' };
let agentsMd = '';
try {
agentsMd = fs.readFileSync(path.join(targetDir, 'AGENTS.md'), 'utf-8');
} catch { /* missing AGENTS.md: handled below */ }
const missing = sharedSectionsForImport().filter((section) => !agentsMd.includes(section));
if (missing.length === 0) {
return { action: 'import', message: 'CLAUDE.md imports AGENTS.md (shared sections live once, in AGENTS.md)' };
}
fs.writeFileSync(claudeMdPath, dual.fullForm, 'utf-8');
return {
action: 'restored',
message: `AGENTS.md is missing ${missing.length} shared section(s) (Codex init failed, or an older @claude-flow/codex ran), ` +
'so the full CLAUDE.md was kept instead of the @AGENTS.md import',
};
}
+4 -1
View File
@@ -30,6 +30,7 @@ import {
} from './helpers-generator.js';
import { getInstalledCliVersion, HELPERS_STAMP_FILE } from './helper-refresh.js';
import { generateClaudeMd } from './claudemd-generator.js';
import { writeDualClaudeMd } from './dual-instructions.js';
import { recordMemoryPackagePath } from './memory-package-resolver.js';
import { COMMONJS_COMPANION_HELPERS, ensureCommonJsCompanions } from './helper-companions.js';
import { scanSettingsForRisk, formatRiskFindingsAsWarnings, RISKY_SETTINGS_HINT, type RiskySettingsMode } from './settings-risk-scanner.js';
@@ -2304,7 +2305,9 @@ async function writeClaudeMd(
): Promise<void> {
const claudeMdPath = path.join(targetDir, 'CLAUDE.md');
if (fs.existsSync(claudeMdPath) && !options.force) {
if (options.instructionsSource === 'agents-md') {
writeDualClaudeMd(claudeMdPath, options, result);
} else if (fs.existsSync(claudeMdPath) && !options.force) {
result.skipped.push('CLAUDE.md');
} else {
// #2208: if overwriting an existing CLAUDE.md (force mode), back it up first so
+4
View File
@@ -55,9 +55,13 @@ export {
export {
generateClaudeMd,
generateMinimalClaudeMd,
generateDualClaudeMd,
CLAUDE_MD_TEMPLATES,
} from './claudemd-generator.js';
// #2638 dual-host instructions (AGENTS.md is the single source)
export { finalizeDualInstructions, type DualFinalizeOutcome } from './dual-instructions.js';
// Main executor
export { executeInit, executeUpgrade, executeUpgradeWithMissing, default } from './executor.js';
export type { UpgradeResult } from './executor.js';
@@ -0,0 +1,165 @@
/**
* Shared Ruflo instruction sections (#2638).
*
* The host-neutral half of the project instructions: the text both Claude
* Code and Codex should read. In a dual project AGENTS.md carries these
* sections once, and CLAUDE.md pulls them in with Claude Code's `@AGENTS.md`
* import, adding only Claude-specific guidance.
*
* Canonical copy: v3/@claude-flow/codex/src/generators/shared-instructions.ts
* Mirror: v3/@claude-flow/cli/src/init/shared-instructions.ts
*
* The two files must stay byte-identical (a CLI test compares them). The CLI
* keeps a mirror instead of importing it because it pins a published
* @claude-flow/codex release, which cannot see unreleased exports; once the
* CLI pins a codex release that ships this module, the mirror can go.
*
* Pure: no imports, no I/O.
*/
/** Rules both hosts follow. The Claude-only commit-trailer rule is kept by the CLI. */
export const SHARED_RULE_LINES: readonly string[] = [
'- Do what has been asked; nothing more, nothing less',
'- NEVER create files unless absolutely necessary — prefer editing existing files',
'- NEVER create documentation files unless explicitly requested',
'- NEVER save working files or tests to root — use `/src`, `/tests`, `/docs`, `/config`, `/scripts`',
'- ALWAYS read a file before editing it',
'- NEVER commit secrets, credentials, or .env files',
'- Keep files under 500 lines',
'- Validate input at system boundaries',
];
/** Position of the Claude-only commit-trailer rule inside the single-host Rules list. */
export const CLAUDE_RULE_INSERT_AT = 6;
export function sharedRules(): string {
return `## Rules\n\n${SHARED_RULE_LINES.join('\n')}`;
}
/** Swarm body shared by both hosts: init command, routing table, when to swarm. */
export const SWARM_ROUTING_BODY = `\`\`\`bash
npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized
\`\`\`
### Agent Routing
| Task | Agents | Topology |
|------|--------|----------|
| Bug Fix | researcher, coder, tester | hierarchical |
| Feature | architect, coder, tester, reviewer | hierarchical |
| Refactor | architect, coder, reviewer | hierarchical |
| Performance | perf-engineer, coder | hierarchical |
| Security | security-architect, auditor | hierarchical |
### When to Swarm
- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance
- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions`;
export function sharedSwarmRouting(): string {
return `## Swarm & Routing\n\n${SWARM_ROUTING_BODY}`;
}
export function sharedMemoryAndLearning(): string {
return `## Memory & Learning
### Before Any Task
\`\`\`bash
npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns
npx @claude-flow/cli@latest hooks route --task "[task description]"
\`\`\`
### After Success
\`\`\`bash
npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]"
npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true
\`\`\`
### MCP Tools (use \`ToolSearch("keyword")\` to discover)
| Category | Key Tools |
|----------|-----------|
| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` |
| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` |
| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` |
| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` |
| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` |
| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` |
| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` |
### Background Workers
| Worker | When |
|--------|------|
| \`audit\` | After security changes |
| \`optimize\` | After performance work |
| \`testgaps\` | After adding features |
| \`map\` | Every 5+ file changes |
| \`document\` | After API changes |
\`\`\`bash
npx @claude-flow/cli@latest hooks worker dispatch --trigger audit
\`\`\``;
}
export function sharedAgentTypes(): string {
return `## Agents
**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\`
**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\`
**Security**: \`security-architect\`, \`security-auditor\`
**Performance**: \`performance-engineer\`, \`perf-analyzer\`
**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\`
**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\`
Any string works as a custom agent type.`;
}
export function sharedBuildAndTest(): string {
return `## Build & Test
- ALWAYS run tests after code changes
- ALWAYS verify build succeeds before committing
\`\`\`bash
npm run build && npm test
\`\`\``;
}
export function sharedCliQuickRef(): string {
return `## CLI Quick Reference
\`\`\`bash
npx @claude-flow/cli@latest init --wizard # Setup
npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm
npx @claude-flow/cli@latest memory search --query "" # Vector search
npx @claude-flow/cli@latest hooks route --task "" # Route to agent
npx @claude-flow/cli@latest doctor --fix # Diagnostics
npx @claude-flow/cli@latest security scan # Security scan
npx @claude-flow/cli@latest performance benchmark # Benchmarks
\`\`\`
26 commands, 140+ subcommands. Use \`--help\` on any command for details.`;
}
/**
* Every shared section, in order. AGENTS.md (dual mode) writes all of them;
* a CLAUDE.md that imports AGENTS.md must not repeat any of them.
*/
export function generateSharedInstructions(): string[] {
return [
sharedRules(),
sharedSwarmRouting(),
sharedMemoryAndLearning(),
sharedAgentTypes(),
sharedBuildAndTest(),
sharedCliQuickRef(),
];
}
/** Claude Code's import line. Must stand on its own line, outside a code block. */
export const AGENTS_MD_IMPORT = '@AGENTS.md';
/** True when the text already pulls AGENTS.md in through Claude Code's import syntax. */
export function importsAgentsMd(text: string): boolean {
return text.split(/\r?\n/).some((line) => line.trim() === AGENTS_MD_IMPORT);
}
+13
View File
@@ -364,6 +364,13 @@ export interface InitOptions {
* (--drop-risky-settings).
*/
riskySettings?: 'stop' | 'keep' | 'drop';
/**
* #2638 — where the shared project instructions live. `claude-md` (default,
* single-host) writes the full CLAUDE.md. `agents-md` (set by `init --dual`)
* writes CLAUDE.md as `@AGENTS.md` plus Claude-only sections; AGENTS.md,
* written by the Codex pass, carries the shared sections.
*/
instructionsSource?: 'claude-md' | 'agents-md';
}
/**
@@ -638,4 +645,10 @@ export interface InitResult {
riskySettings?: string[];
/** ADR-509 §2.3 — init stopped before writing anything because of riskySettings. */
stoppedOnRiskySettings?: boolean;
/**
* #2638 — set when this run wrote CLAUDE.md in its `@AGENTS.md` import form.
* `fullForm` is the single-host CLAUDE.md to restore if AGENTS.md turns out
* not to carry the shared sections (see finalizeDualInstructions).
*/
dualInstructions?: { importForm: string; fullForm: string };
}
@@ -8,7 +8,7 @@
import type { AgentsMdOptions, AgentsMdTemplate } from '../types.js';
import { BUILT_IN_SKILLS } from '../templates/index.js';
function concurrentRufloWorkflow(): string {
export function concurrentRufloWorkflow(): string {
return `## Ruflo + Codex Automated Workflow
Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation.
@@ -0,0 +1,118 @@
/**
* @claude-flow/codex - dual-host instruction files (#2638)
*
* In a project set up for both Claude Code and Codex, AGENTS.md is the single
* source: the shared sections (shared-instructions.ts) plus the Codex-only
* ones. Claude Code reads it through the `@AGENTS.md` import in CLAUDE.md, so
* CLAUDE.md carries only Claude-specific notes and repeats nothing.
*
* Single-host AGENTS.md (generateAgentsMd) is untouched by this module.
*/
import type { AgentsMdOptions } from '../types.js';
import { BUILT_IN_SKILLS } from '../templates/index.js';
import { concurrentRufloWorkflow } from './agents-md.js';
import { AGENTS_MD_IMPORT, generateSharedInstructions } from './shared-instructions.js';
const DEFAULT_SKILLS = ['swarm-orchestration', 'memory-management', 'sparc-methodology', 'security-audit'];
function codexOnlySections(options: AgentsMdOptions): string[] {
const {
description = 'A Claude Flow powered project',
techStack = 'TypeScript, Node.js',
buildCommand = 'npm run build',
testCommand = 'npm test',
devCommand = 'npm run dev',
skills = DEFAULT_SKILLS,
} = options;
const skillsTable = skills
.map((skill) => {
const info = BUILT_IN_SKILLS[skill as keyof typeof BUILT_IN_SKILLS];
return info ? `| \`$${skill}\` | ${info.description} |` : `| \`$${skill}\` | Custom skill |`;
})
.join('\n');
return [
`## Project Overview
${description}
**Tech Stack**: ${techStack}
**Architecture**: Domain-Driven Design with bounded contexts`,
`## Quick Start
\`\`\`bash
npm install
${buildCommand}
${testCommand}
${devCommand}
\`\`\``,
`## Codex Execution Model
- **claude-flow** = LEDGER (coordinates: memory, routing, swarm state)
- **Codex** = EXECUTOR (writes code, runs tests, creates files)
**Critical rule:** DON'T STOP after calling claude-flow commands. Coordination commands return instantly — continue immediately with the next implementation step.`,
concurrentRufloWorkflow().trimEnd(),
`## Codex Skills
Use \`$skill-name\` syntax to invoke (Claude Code uses \`/skill-name\` for the same skills):
| Skill | Use Case |
|-------|----------|
${skillsTable}`,
`## Commit Messages
\`\`\`
<type>(<scope>): <description>
[optional body]
\`\`\`
Types: \`feat\`, \`fix\`, \`docs\`, \`style\`, \`refactor\`, \`perf\`, \`test\`, \`chore\`
Do not add a \`Co-Authored-By\` trailer unless the repository explicitly
configures and authorizes that attribution.`,
`## Path Security
- Validate all file paths
- Prevent directory traversal (../)
- Use absolute paths internally`,
`## Links
- Documentation: https://github.com/ruvnet/ruflo
- Issues: https://github.com/ruvnet/ruflo/issues`,
];
}
/** AGENTS.md for a dual project: shared sections once, then Codex-only sections. */
export function generateDualAgentsMd(options: AgentsMdOptions): string {
const header = `# ${options.projectName}
> Shared instructions for Claude Code and OpenAI Codex. Codex reads this file
> directly; Claude Code reads it through the \`${AGENTS_MD_IMPORT}\` import in CLAUDE.md.
> Shared sections come first; the Codex-only sections follow.`;
return `${[header, ...generateSharedInstructions(), ...codexOnlySections(options)].join('\n\n')}\n`;
}
/**
* CLAUDE.md for a dual project created by the Codex initializer: the import
* plus Claude Code notes only. (`ruflo init --dual` writes a richer Claude
* overlay itself; this initializer then leaves that file alone.)
*/
export function generateDualClaudeMdStub(projectName: string, skills: string[]): string {
return `# ${projectName}
${AGENTS_MD_IMPORT}
> Project instructions live in \`AGENTS.md\`, imported above; OpenAI Codex reads the same
> file. Edit shared rules there. This file holds only Claude Code notes.
## Claude Code
- Skills in \`.agents/skills/\` are invoked as \`/skill-name\` here and \`$skill-name\` in Codex
${skills.map((s) => ` - \`/${s}\``).join('\n')}
- Local overrides: \`CLAUDE.local.md\` (gitignored)
`;
}
@@ -7,3 +7,5 @@
export { generateAgentsMd } from './agents-md.js';
export { generateSkillMd } from './skill-md.js';
export { generateConfigToml } from './config-toml.js';
export { generateDualAgentsMd, generateDualClaudeMdStub } from './dual-instructions.js';
export { generateSharedInstructions, importsAgentsMd, AGENTS_MD_IMPORT } from './shared-instructions.js';
@@ -0,0 +1,165 @@
/**
* Shared Ruflo instruction sections (#2638).
*
* The host-neutral half of the project instructions: the text both Claude
* Code and Codex should read. In a dual project AGENTS.md carries these
* sections once, and CLAUDE.md pulls them in with Claude Code's `@AGENTS.md`
* import, adding only Claude-specific guidance.
*
* Canonical copy: v3/@claude-flow/codex/src/generators/shared-instructions.ts
* Mirror: v3/@claude-flow/cli/src/init/shared-instructions.ts
*
* The two files must stay byte-identical (a CLI test compares them). The CLI
* keeps a mirror instead of importing it because it pins a published
* @claude-flow/codex release, which cannot see unreleased exports; once the
* CLI pins a codex release that ships this module, the mirror can go.
*
* Pure: no imports, no I/O.
*/
/** Rules both hosts follow. The Claude-only commit-trailer rule is kept by the CLI. */
export const SHARED_RULE_LINES: readonly string[] = [
'- Do what has been asked; nothing more, nothing less',
'- NEVER create files unless absolutely necessary — prefer editing existing files',
'- NEVER create documentation files unless explicitly requested',
'- NEVER save working files or tests to root — use `/src`, `/tests`, `/docs`, `/config`, `/scripts`',
'- ALWAYS read a file before editing it',
'- NEVER commit secrets, credentials, or .env files',
'- Keep files under 500 lines',
'- Validate input at system boundaries',
];
/** Position of the Claude-only commit-trailer rule inside the single-host Rules list. */
export const CLAUDE_RULE_INSERT_AT = 6;
export function sharedRules(): string {
return `## Rules\n\n${SHARED_RULE_LINES.join('\n')}`;
}
/** Swarm body shared by both hosts: init command, routing table, when to swarm. */
export const SWARM_ROUTING_BODY = `\`\`\`bash
npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized
\`\`\`
### Agent Routing
| Task | Agents | Topology |
|------|--------|----------|
| Bug Fix | researcher, coder, tester | hierarchical |
| Feature | architect, coder, tester, reviewer | hierarchical |
| Refactor | architect, coder, reviewer | hierarchical |
| Performance | perf-engineer, coder | hierarchical |
| Security | security-architect, auditor | hierarchical |
### When to Swarm
- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance
- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions`;
export function sharedSwarmRouting(): string {
return `## Swarm & Routing\n\n${SWARM_ROUTING_BODY}`;
}
export function sharedMemoryAndLearning(): string {
return `## Memory & Learning
### Before Any Task
\`\`\`bash
npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns
npx @claude-flow/cli@latest hooks route --task "[task description]"
\`\`\`
### After Success
\`\`\`bash
npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]"
npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true
\`\`\`
### MCP Tools (use \`ToolSearch("keyword")\` to discover)
| Category | Key Tools |
|----------|-----------|
| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` |
| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` |
| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` |
| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` |
| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` |
| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` |
| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` |
### Background Workers
| Worker | When |
|--------|------|
| \`audit\` | After security changes |
| \`optimize\` | After performance work |
| \`testgaps\` | After adding features |
| \`map\` | Every 5+ file changes |
| \`document\` | After API changes |
\`\`\`bash
npx @claude-flow/cli@latest hooks worker dispatch --trigger audit
\`\`\``;
}
export function sharedAgentTypes(): string {
return `## Agents
**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\`
**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\`
**Security**: \`security-architect\`, \`security-auditor\`
**Performance**: \`performance-engineer\`, \`perf-analyzer\`
**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\`
**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\`
Any string works as a custom agent type.`;
}
export function sharedBuildAndTest(): string {
return `## Build & Test
- ALWAYS run tests after code changes
- ALWAYS verify build succeeds before committing
\`\`\`bash
npm run build && npm test
\`\`\``;
}
export function sharedCliQuickRef(): string {
return `## CLI Quick Reference
\`\`\`bash
npx @claude-flow/cli@latest init --wizard # Setup
npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm
npx @claude-flow/cli@latest memory search --query "" # Vector search
npx @claude-flow/cli@latest hooks route --task "" # Route to agent
npx @claude-flow/cli@latest doctor --fix # Diagnostics
npx @claude-flow/cli@latest security scan # Security scan
npx @claude-flow/cli@latest performance benchmark # Benchmarks
\`\`\`
26 commands, 140+ subcommands. Use \`--help\` on any command for details.`;
}
/**
* Every shared section, in order. AGENTS.md (dual mode) writes all of them;
* a CLAUDE.md that imports AGENTS.md must not repeat any of them.
*/
export function generateSharedInstructions(): string[] {
return [
sharedRules(),
sharedSwarmRouting(),
sharedMemoryAndLearning(),
sharedAgentTypes(),
sharedBuildAndTest(),
sharedCliQuickRef(),
];
}
/** Claude Code's import line. Must stand on its own line, outside a code block. */
export const AGENTS_MD_IMPORT = '@AGENTS.md';
/** True when the text already pulls AGENTS.md in through Claude Code's import syntax. */
export function importsAgentsMd(text: string): boolean {
return text.split(/\r?\n/).some((line) => line.trim() === AGENTS_MD_IMPORT);
}
+24 -95
View File
@@ -15,6 +15,8 @@ import type {
BuiltInSkill,
} from './types.js';
import { generateAgentsMd } from './generators/agents-md.js';
import { generateDualAgentsMd, generateDualClaudeMdStub } from './generators/dual-instructions.js';
import { importsAgentsMd } from './generators/shared-instructions.js';
import {
BUILT_IN_SKILL_NAMES,
generateSkillMd,
@@ -570,6 +572,11 @@ export class CodexInitializer {
private async generateAgentsMd(): Promise<string> {
const projectName = path.basename(this.projectPath);
// #2638: a dual project keeps the shared sections once, here.
if (this.dual) {
return generateDualAgentsMd({ projectName, skills: this.skills });
}
return generateAgentsMd({
projectName,
template: this.template,
@@ -781,108 +788,30 @@ Skills are invoked using \`$skill-name\` syntax. Each skill has:
const files: string[] = [];
const warnings: string[] = [];
// Check if CLAUDE.md already exists
// #2638: AGENTS.md is the single source. CLAUDE.md is Claude Code's
// `@AGENTS.md` import plus Claude-only notes — never a second copy.
const claudeMdPath = path.join(this.projectPath, 'CLAUDE.md');
const claudeMdExists = await fs.pathExists(claudeMdPath);
const existing = claudeMdExists ? await fs.readFile(claudeMdPath, 'utf-8') : '';
if (claudeMdExists && !this.force) {
warnings.push('CLAUDE.md already exists - not overwriting. Use --force to replace.');
// Already single-source (e.g. written by `ruflo init --dual`): leave it, even under --force.
if (claudeMdExists && importsAgentsMd(existing)) {
return { files, warnings };
}
const projectName = path.basename(this.projectPath);
if (claudeMdExists && !this.force) {
warnings.push(
'CLAUDE.md already exists - not overwriting. To share instructions with Claude Code, move your custom ' +
'sections into AGENTS.md and add a line `@AGENTS.md` to CLAUDE.md, or use --force to replace it.',
);
return { files, warnings };
}
// Generate a CLAUDE.md that references AGENTS.md
const claudeMd = `# ${projectName}
> This project supports both Claude Code and OpenAI Codex.
## Platform Compatibility
| Platform | Config File | Skill Syntax |
|----------|-------------|--------------|
| Claude Code | CLAUDE.md | /skill-name |
| OpenAI Codex | AGENTS.md | $skill-name |
## Instructions
**Primary instructions are in \`AGENTS.md\`** (Agentic AI Foundation standard).
Read and follow that file before starting work; it contains the live
\`guidance_brain\` routing workflow, concurrency ownership rules, and authority
boundaries.
This file provides compatibility for Claude Code users.
## Quick Start
\`\`\`bash
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
\`\`\`
## Available Skills
Both platforms share the same skills in \`.agents/skills/\`:
${this.skills.map(s => `- \`$${s}\` (Codex) / \`/${s}\` (Claude Code)`).join('\n')}
## Configuration
### Codex Configuration
- Main: \`.agents/config.toml\`
- Local: \`.codex/config.toml\` (gitignored)
### Claude Code Configuration
- This file: \`CLAUDE.md\`
- Local: \`CLAUDE.local.md\` (gitignored)
## MCP Integration
\`\`\`bash
# Start Ruflo's MCP server over stdio (dedicated entry point — the
# management \`ruflo mcp start\` CLI does NOT answer JSON-RPC on stdio).
npx -y ruflo@latest mcp start
\`\`\`
## Swarm Orchestration
This project uses hierarchical swarm coordination:
| Setting | Value |
|---------|-------|
| Topology | hierarchical |
| Max Agents | 8 |
| Strategy | specialized |
## Code Standards
- Files under 500 lines
- No hardcoded secrets
- Input validation at boundaries
- Typed interfaces for APIs
## Security
- NEVER commit .env files or secrets
- Always validate user input
- Use parameterized queries for SQL
## Full Documentation
For complete instructions, see \`AGENTS.md\`.
---
*Generated by @claude-flow/codex - Dual platform mode*
`;
await fs.writeFile(claudeMdPath, claudeMd, 'utf-8');
await fs.writeFile(
claudeMdPath,
generateDualClaudeMdStub(path.basename(this.projectPath), this.skills),
'utf-8',
);
files.push('CLAUDE.md');
// Generate CLAUDE.local.md template
@@ -0,0 +1,86 @@
/**
* #2638 — dual projects get one instruction source: AGENTS.md carries the
* shared sections once, CLAUDE.md imports it with `@AGENTS.md`.
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { CodexInitializer } from '../src/initializer.js';
import { generateDualAgentsMd } from '../src/generators/dual-instructions.js';
import { generateSharedInstructions, importsAgentsMd } from '../src/generators/shared-instructions.js';
const headings = (md: string) => md.split('\n').filter((l) => /^#{2,3} /.test(l));
const h2 = (md: string) => md.split('\n').filter((l) => /^## /.test(l));
describe('generateDualAgentsMd', () => {
const md = generateDualAgentsMd({ projectName: 'demo' });
it('carries every shared section verbatim', () => {
for (const section of generateSharedInstructions()) expect(md).toContain(section);
});
it('repeats no section heading', () => {
const hs = h2(md);
expect(new Set(hs).size).toBe(hs.length);
});
it('keeps the Codex-only sections', () => {
for (const h of ['## Quick Start', '## Codex Execution Model', '## Ruflo + Codex Automated Workflow', '## Commit Messages', '## Path Security', '## Links']) {
expect(md).toContain(h);
}
expect(md).toContain('$swarm-orchestration');
});
});
describe('CodexInitializer --dual', () => {
let dir: string;
let originalPath: string | undefined;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'dual-2638-'));
originalPath = process.env.PATH;
process.env.PATH = '';
});
afterEach(() => {
if (originalPath === undefined) delete process.env.PATH;
else process.env.PATH = originalPath;
rmSync(dir, { recursive: true, force: true });
});
it('writes AGENTS.md as the single source and CLAUDE.md as the @AGENTS.md import', async () => {
const result = await new CodexInitializer().initialize({ projectPath: dir, template: 'default', dual: true });
expect(result.success).toBe(true);
const agents = readFileSync(join(dir, 'AGENTS.md'), 'utf-8');
const claude = readFileSync(join(dir, 'CLAUDE.md'), 'utf-8');
for (const section of generateSharedInstructions()) expect(agents).toContain(section);
expect(importsAgentsMd(claude)).toBe(true);
// No section appears in both files.
const shared = headings(claude).filter((h) => headings(agents).includes(h));
expect(shared).toEqual([]);
for (const section of generateSharedInstructions()) expect(claude).not.toContain(section);
});
it('never overwrites a user CLAUDE.md without --force, and says how to migrate', async () => {
writeFileSync(join(dir, 'CLAUDE.md'), '# My rules\n\n- keep me\n', 'utf-8');
const result = await new CodexInitializer().initialize({ projectPath: dir, template: 'minimal', dual: true });
expect(result.success).toBe(true);
expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe('# My rules\n\n- keep me\n');
expect(result.filesCreated).not.toContain('CLAUDE.md');
expect(result.warnings.join('\n')).toMatch(/@AGENTS\.md/);
});
it('leaves a CLAUDE.md that already imports AGENTS.md alone, even with --force', async () => {
const mine = '# Ruflo — Claude Code Configuration\n\n@AGENTS.md\n\n## Claude Code Rules\n\n- custom\n';
writeFileSync(join(dir, 'CLAUDE.md'), mine, 'utf-8');
const result = await new CodexInitializer().initialize({ projectPath: dir, template: 'minimal', dual: true, force: true });
expect(result.success).toBe(true);
expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe(mine);
});
it('does not write CLAUDE.md without --dual', async () => {
await new CodexInitializer().initialize({ projectPath: dir, template: 'minimal' });
expect(existsSync(join(dir, 'CLAUDE.md'))).toBe(false);
});
});
@@ -0,0 +1,51 @@
/**
* #2638 — single-host AGENTS.md output must not change.
*
* The snapshot was recorded on origin/main before the dual-mode single-source
* work landed. Dual mode (`--dual`) gets its own composition; a Codex-only
* init keeps writing exactly these bytes.
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { generateAgentsMd } from '../src/generators/index.js';
import { CodexInitializer } from '../src/initializer.js';
import type { AgentsMdTemplate } from '../src/types.js';
const TEMPLATES: AgentsMdTemplate[] = ['minimal', 'default', 'full', 'enterprise'];
describe('single-host AGENTS.md is unchanged (#2638)', () => {
for (const template of TEMPLATES) {
it(`generateAgentsMd(${template})`, async () => {
const md = await generateAgentsMd({ projectName: 'snapshot-project', template });
expect(md).toMatchSnapshot();
});
}
describe('CodexInitializer without --dual', () => {
let dir: string;
let originalPath: string | undefined;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'snapshot-project-'));
// No `codex`/`claude` binaries: MCP registration and plugin install are skipped.
originalPath = process.env.PATH;
process.env.PATH = '';
});
afterEach(() => {
if (originalPath === undefined) delete process.env.PATH;
else process.env.PATH = originalPath;
rmSync(dir, { recursive: true, force: true });
});
for (const template of ['minimal', 'default'] as const) {
it(`writes the same AGENTS.md and no CLAUDE.md (${template})`, async () => {
const result = await new CodexInitializer().initialize({ projectPath: dir, template });
expect(result.success).toBe(true);
const agents = readFileSync(join(dir, 'AGENTS.md'), 'utf-8').split(dir.split('/').pop()!).join('<project>');
expect(agents).toMatchSnapshot();
expect(result.filesCreated).not.toContain('CLAUDE.md');
});
}
});
});