π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
/**
* V3 CLI MetaHarness Command β ADR-150 deep integration entry point.
*
* Top-level dispatcher that delegates each subcommand to the matching
* `plugins/ruflo-metaharness/scripts/<name>.mjs` via spawnSync. This is
* the user-facing wrapper around the upstream `metaharness` / `harness`
* CLIs.
*
* SUBCOMMANDS
* score β 5-dim readiness scorecard
* genome β 7-section categorical report
* mcp-scan β static MCP security findings
* threat-model β enterprise-grade threat model
* mint β scaffold custom harness (DRY-RUN by default)
*
* Each subcommand is a thin subprocess invocation β the plugin scripts
* own the actual logic. This command exists so users can run:
*
* npx ruflo metaharness score
* npx ruflo metaharness mcp-scan --fail-on high
* npx ruflo metaharness mint --name foo --template vertical:coding
*
* instead of:
*
* node plugins/ruflo-metaharness/scripts/score.mjs
*
* ADR-150 ARCHITECTURAL CONSTRAINT
* --------------------------------
* This command file MUST NOT statically import any `@metaharness/*`
* package. The plugin scripts handle all metaharness invocation;
* here we only spawn the local Node script (which then handles
* `npx metaharness` + graceful degradation).
*
* Created with ruv.io
*/
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
import { spawnSync } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import { join, dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import { homedir } from 'os';
import { ownPluginDirs } from '../plugins/own-install.js';
import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js';
import {
listFlywheelReceipts,
promoteFlywheelCandidate,
readFlywheelTransactionState,
resetSequentialEvidence,
verifyFlywheelLedger,
} from '../services/flywheel-transaction.js';
import { evaluatePolicyRequest } from '../services/policy-runtime.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
// Subcommand β plugin script filename
const SUBCOMMANDS: Record<string, string> = {
score: 'score.mjs',
genome: 'genome.mjs',
'mcp-scan': 'mcp-scan.mjs',
'threat-model': 'threat-model.mjs',
// iter 7 β composite Phase-2 weekly audit worker
'oia-audit': 'oia-audit.mjs',
// iter 15 β diff two oia-audit records (drift detection)
'audit-trend': 'audit-trend.mjs',
// iter 16 β enumerate metaharness-audit records
'audit-list': 'audit-list.mjs',
// iter 36 β ADR-152 Β§3.1 weighted similarity between two harness fingerprints
similarity: 'similarity.mjs',
// iter 53 β one-command drift detection (compose audit-list + oia-audit + audit-trend)
'drift-from-history': 'drift-from-history.mjs',
mint: 'mint.mjs',
// @metaharness/redblue@~0.1.4 β adversarial red/blue LLM testing
// (init|run|patch|attack|report sub-subcommands handled by redblue.mjs)
redblue: 'redblue.mjs',
// [email protected] β upstream ADR-235 GEPA learning run ($0 dry-run
// default; --run to spend; needs a metaharness repo checkout)
learn: 'learn.mjs',
// @metaharness/[email protected] β GEPA library surface (genome ops; the
// gepaOptimize loop itself stays library-only / behind evolve)
gepa: 'gepa.mjs',
// ADR-153 Darwin evolution and stable benchmark-corpus operations.
evolve: 'evolve.mjs',
bench: 'bench.mjs',
// ADR-322 evaluation receipt + atomic promotion loop; handled in-process.
flywheel: '__internal__',
};
function flywheelFlag<T>(flags: Record<string, unknown>, name: string, fallback?: T): T | undefined {
const value = flags[name];
return (value === undefined ? fallback : value) as T | undefined;
}
async function dispatchFlywheel(
operation: string | undefined,
positional: string[],
flags: Record<string, unknown>,
): Promise<CommandResult> {
const projectRoot = resolve(String(flywheelFlag(flags, 'projectRoot', process.cwd())));
let data: unknown;
if (!operation || operation === 'status') {
data = {
state: readFlywheelTransactionState(projectRoot),
ledger: verifyFlywheelLedger(projectRoot),
};
} else if (operation === 'run') {
const privateKeyPath = flywheelFlag<string>(flags, 'privateKey');
const publicKeyPath = flywheelFlag<string>(flags, 'publicKey');
if (!!privateKeyPath !== !!publicKeyPath) {
data = { success: false, reason: '--private-key and --public-key must be supplied together' };
} else {
data = await runFlywheelWorker(projectRoot, {
optInOverride: true,
sample: Number(flywheelFlag(flags, 'sample', 40)),
proposer: String(flywheelFlag(flags, 'proposer', 'auto')) as 'auto' | 'local' | 'darwin',
receiptPrivateKeyPem: privateKeyPath ? readFileSync(resolve(privateKeyPath), 'utf8') : undefined,
receiptPublicKeyPem: publicKeyPath ? readFileSync(resolve(publicKeyPath), 'utf8') : undefined,
maxConcurrency: Number(flywheelFlag(flags, 'maxConcurrency', 2)),
evaluationTimeoutMs: Number(flywheelFlag(flags, 'timeoutMs', 120_000)),
anchorPath: flywheelFlag<string>(flags, 'anchorPath'),
anchorHash: flywheelFlag<string>(flags, 'anchorHash'),
anchorManifestPath: flywheelFlag<string>(flags, 'anchorManifest'),
});
}
} else if (operation === 'receipts') {
data = listFlywheelReceipts(projectRoot).map(({ receipt, state }) => ({
receiptId: receipt.payload.receiptId,
anchorRef: receipt.payload.anchorRef,
candidateId: receipt.payload.candidateId,
baselineRef: receipt.payload.baselineRef,
decision: receipt.payload.decision,
signed: !!receipt.signature,
issuedAt: receipt.payload.issuedAt,
state,
}));
} else if (operation === 'history') {
const state = readFlywheelTransactionState(projectRoot);
data = { ledgerHead: state.ledgerHead, commits: state.commits };
} else if (operation === 'evidence-reset') {
// ADR-381 Β§2 β start a new evidence epoch. Same policy gate as promote:
// this reopens the family-wise alpha budget, so it is a governance action.
const reason = String(flywheelFlag(flags, 'reason', '')).trim();
if (!reason) {
data = { success: false, reason: 'evidence-reset requires --reason "<why>" β the reset audit trail records intent' };
} else {
const policy = await evaluatePolicyRequest({
identity: { id: process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'metaharness-local', type: 'agent', roles: ['optimizer'] },
action: {
type: 'metaharness.evidence.reset',
resource: projectRoot,
environment: 'production',
destructive: true,
},
context: {
approvalIds: String(flywheelFlag(flags, 'approvalId', '')).split(',').filter(Boolean),
},
}, projectRoot);
if (policy.enforcedOutcome !== 'allowed') {
data = { success: false, reason: `policy-${policy.enforcedOutcome}:${policy.reason}`, policyReceiptId: policy.receiptId };
} else {
data = await resetSequentialEvidence(projectRoot, {
confirm: flywheelFlag<boolean>(flags, 'confirm', false) === true,
reason,
});
}
}
} else if (operation === 'promote') {
const receiptId = positional[0];
const publicKeyPath = flywheelFlag<string>(flags, 'publicKey');
if (!receiptId || !publicKeyPath) {
data = { success: false, reason: 'promote requires <receipt-id> and --public-key <PEM path>' };
} else {
const policy = await evaluatePolicyRequest({
identity: { id: process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'metaharness-local', type: 'agent', roles: ['optimizer'] },
action: {
type: 'metaharness.candidate.promote',
resource: receiptId,
environment: 'production',
destructive: true,
},
context: {
approvalIds: String(flywheelFlag(flags, 'approvalId', '')).split(',').filter(Boolean),
},
}, projectRoot);
if (policy.enforcedOutcome !== 'allowed') {
data = { success: false, reason: `policy-${policy.enforcedOutcome}:${policy.reason}`, policyReceiptId: policy.receiptId };
} else {
const publicKey = readFileSync(resolve(publicKeyPath), 'utf8');
data = await promoteFlywheelCandidate(projectRoot, receiptId, {
confirm: flywheelFlag<boolean>(flags, 'confirm', false) === true,
trustedPublicKeys: new Set([publicKey]),
// --allow-aggregate-evidence: explicit migration escape hatch for
// pre-upgrade receipts without task-level pairedOutcomes. Default
// is strict β aggregate-only evidence is refused.
requirePairedEvidence: flywheelFlag<boolean>(flags, 'allowAggregateEvidence', false) !== true,
});
}
}
} else {
data = { success: false, reason: `unknown flywheel operation: ${operation}` };
}
output.writeln(JSON.stringify(data, null, 2));
const success = !(data && typeof data === 'object' && (data as { success?: boolean }).success === false);
return { success, exitCode: success ? 0 : 1, data };
}
/**
* Walk up from the current dirname to find the ruflo repo root that
* contains plugins/ruflo-metaharness/. Handles three install layouts:
* 1. ruflo dev tree (cwd / ../plugins/...)
* 2. ruflo wrapper (ruflo/node_modules/@claude-flow/cli/...)
* 3. npx (npm-cache/__npx/... β fall back to cwd-scan)
*
* `requiredScript`, if provided, narrows the match: the returned dir must
* contain BOTH `_harness.mjs` (proves it's a plugin-scripts dir) AND the
* named script. This guards against the publish-artifact mirror at
* `v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/` getting picked
* over the source `plugins/ruflo-metaharness/scripts/` when the mirror
* lags the source (the mirror is regenerated only at publish time by
* `prepublishOnly`).
*/
function locatePluginScripts(requiredScript?: string): string | null {
// Up from the cli dist dir, bounded at node_modules: a project-local install
// must not reach the project.
const candidates: string[] = ownPluginDirs(__dirname, 'ruflo-metaharness', 'scripts');
// The scripts are executed, so they come from this CLI's own install (or the
// user's marketplace checkout), never from the cwd: scoring a repo must not
// run plugin code that repo supplies. The repo is still the scoring target.
candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-metaharness', 'scripts'));
for (const c of candidates) {
if (!existsSync(join(c, '_harness.mjs'))) continue;
if (requiredScript && !existsSync(join(c, requiredScript))) continue;
return c;
}
return null;
}
function dispatchPluginScript(scriptDir: string, scriptName: string, extraArgs: string[]): CommandResult {
const scriptPath = join(scriptDir, scriptName);
const r = spawnSync('node', [scriptPath, ...extraArgs], {
stdio: 'inherit',
env: process.env,
timeout: 5 * 60 * 1000,
});
return {
success: (r.status ?? 0) === 0,
exitCode: r.status ?? 1,
data: { scriptPath, args: extraArgs },
};
}
export const metaharnessCommand: Command = {
name: 'metaharness',
description:
'MetaHarness integration (ADR-150) β score / genome / mcp-scan / threat-model / mint. Subprocess-invoked plugin skills with graceful degradation.',
options: [
{
name: 'subcommand',
// iter 73 β list reflects all dispatchable subcommands (was
// stale at the iter-3 list of 5). Keep this synced with the
// SUBCOMMANDS map above.
description: 'One of: score | genome | mcp-scan | threat-model | oia-audit | audit-list | audit-trend | similarity | drift-from-history | mint | redblue | learn | gepa | evolve | bench | flywheel',
type: 'string' as const,
},
],
async action(context: CommandContext): Promise<CommandResult> {
const args = (context as { args?: string[] }).args || [];
const subcommand = args[0];
const positionalRest = args.slice(1);
// iter 42 β round-trip parsed flags back into argv so the
// subprocess receives them. Without this the CLI parser consumes
// `--a foo` into `flags.a` and the script sees an empty argv,
// emitting a graceful-but-wrong "missing arg" payload (the iter-36
// bug surfaced during iter-42 dispatcher round-trip testing).
const ctxFlags = (context as { flags?: Record<string, unknown> }).flags || {};
const reconstructedFlags: string[] = [];
const SKIP_KEYS = new Set([
'_', // parser's positional bucket
'config', // global CLI flag (--config <path>); consumed before dispatch
'verbose', 'v',
'quiet', 'q',
'help', 'h',
'interactive', 'i', // CLI-only default; plugin scripts are non-interactive
]);
// Parser normalizes kebab-case β camelCase (--per-dimension β perDimension).
// Plugin scripts expect kebab-case at argv, so we re-kebab here.
const toKebab = (s: string): string =>
s.replace(/([A-Z])/g, (m) => `-${m.toLowerCase()}`);
for (const [key, value] of Object.entries(ctxFlags)) {
if (SKIP_KEYS.has(key)) continue;
if (value === undefined || value === null) continue;
// Always use --kebab even for single-char keys: similarity.mjs
// matches literal `--a` / `--b` via argv loop, not via a parser.
// Reconstructing as short-form (`-a`) would silently misroute.
const flag = `--${toKebab(key)}`;
if (typeof value === 'boolean') {
if (value === true) reconstructedFlags.push(flag);
// false β omit (--no-X handled by users invoking explicit --no- form)
} else if (Array.isArray(value)) {
for (const v of value) reconstructedFlags.push(flag, String(v));
} else {
reconstructedFlags.push(flag, String(value));
}
}
const subArgs = [...positionalRest, ...reconstructedFlags];
if (!subcommand || subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {
output.writeln(output.bold('npx ruflo metaharness <subcommand> [options]'));
output.writeln('');
output.writeln('Subcommands:');
output.writeln(' score 5-dimension harness readiness scorecard');
output.writeln(' genome 7-section categorical readiness report');
output.writeln(' mcp-scan static security scan of declared MCP surface');
output.writeln(' threat-model enterprise-grade threat model');
output.writeln(' oia-audit composite weekly audit (oia + threat + mcp) β memory');
output.writeln(' audit-list enumerate timestamped audit records');
output.writeln(' audit-trend diff two audit records (drift detection)');
output.writeln(' similarity ADR-152 β weighted similarity between two harness fingerprints');
output.writeln(' drift-from-history iter 53 β diff current state against most recent audit (1-command drift)');
output.writeln(' mint scaffold a custom harness (dry-run by default)');
output.writeln(' redblue adversarial red/blue LLM testing (init|run|patch|attack|report)');
output.writeln(' evolve Darwin candidate evolution');
output.writeln(' bench create or verify a stable benchmark suite');
output.writeln(' flywheel receipt loop: run | status | receipts | history | promote | evidence-reset');
output.writeln('');
output.writeln('Each subcommand accepts --format json|table and --help.');
output.writeln('');
output.writeln(output.dim('ADR-150 β runs as subprocess; graceful degradation if metaharness is not installed.'));
return { success: true, exitCode: 0, data: { subcommand: null } };
}
if (!SUBCOMMANDS[subcommand]) {
output.writeln(output.error(`Unknown subcommand: ${subcommand}`));
output.writeln(`Valid: ${Object.keys(SUBCOMMANDS).join(', ')}`);
return { success: false, exitCode: 2, data: { subcommand } };
}
if (subcommand === 'flywheel') {
return dispatchFlywheel(positionalRest[0], positionalRest.slice(1), ctxFlags);
}
const scriptDir = locatePluginScripts(SUBCOMMANDS[subcommand]);
if (!scriptDir) {
output.writeln(
output.warning(
'metaharness: plugins/ruflo-metaharness/scripts/ not found. Install ruflo with `npm i ruflo` or run from the ruflo repo.'
)
);
output.writeln(
output.dim('(ADR-150 graceful degradation: this command is a thin delegator over the plugin; the plugin must be present.)')
);
// Exit 0 β this is "feature not available", not a runtime failure.
return { success: true, exitCode: 0, data: { degraded: true, reason: 'plugin-not-found' } };
}
return dispatchPluginScript(scriptDir, SUBCOMMANDS[subcommand], subArgs);
},
};
export default metaharnessCommand;