π 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
feat(metaharness): learn + gepa integration β [email protected] / [email protected] (15 MCP tools) (#2540)
rUvae9bba523e74
diff --git a/CLAUDE.md b/CLAUDE.mdindex 56336f3f70..dc23ad7aba 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1151,6 +1151,16 @@ npx ruflo metaharness redblue attack prompt --count 3npx ruflo metaharness redblue patch --mock-judge # baseline β blue-team patch β retest deltanpx ruflo metaharness redblue report --in report.json# render existing report as markdown+npx ruflo metaharness learn --host claude-code --model haiku --slice slices/lite.json+ # [email protected] / upstream ADR-235 β+ # GEPA learning run; $0 dry-run default,+ # --run to spend; needs a metaharness+ # repo checkout (--repo / $METAHARNESS_REPO)+npx ruflo metaharness gepa --op genome # [email protected] GEPA library β load + validate+ # the shipped cand-6 genome (or --path <f>)+npx ruflo metaharness gepa --op render # genome β the system prompt it compiles to+npx ruflo metaharness gepa --op analyze --transcript run.json+ # classify failure modes in a transcript# Dedicated commandnpx ruflo eject --name my-harness # lift ruflo project β standalone harness@@ -1173,6 +1183,8 @@ mcp__claude-flow__metaharness_bench # ADR-153 β create/verify bemcp__claude-flow__metaharness_evolve # MAP-Elites driver β evolve a harness across bench suitesmcp__claude-flow__metaharness_security_bench # security-focused benchmark suite gatemcp__claude-flow__metaharness_redblue # @metaharness/redblue β adversarial red/blue LLM testing (init|run|patch|attack|report)+mcp__claude-flow__metaharness_learn # [email protected] β GEPA learning run ($0 dry-run default; run=true to spend)+mcp__claude-flow__metaharness_gepa # [email protected] β GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only```### Routing integration (ADR-148/149)diff --git a/package-lock.json b/package-lock.jsonindex 60b7d934f1..4be21f0646 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "claude-flow",- "version": "3.16.1",+ "version": "3.16.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "claude-flow",- "version": "3.16.1",+ "version": "3.16.3","license": "MIT","dependencies": {"@claude-flow/cli-core": "3.7.0-alpha.5",diff --git a/plugins/ruflo-metaharness/README.md b/plugins/ruflo-metaharness/README.mdindex e233f91e48..3fa2ca1546 100644--- a/plugins/ruflo-metaharness/README.md+++ b/plugins/ruflo-metaharness/README.md@@ -26,6 +26,8 @@ MetaHarness integration plugin for ruflo. Surfaces the upstream `metaharness` /| `harness-bench` | `/harness-bench --op create\|verify --repo <path>` | Manage `@metaharness/darwin` bench suites β fixed evaluation corpora for `harness-evolve` || `harness-evolve` | `/harness-evolve --repo <path> [--generations 3] [--sandbox real\|mock\|agent]` | Run `@metaharness/darwin evolve` β mutate seven policy surfaces, sandbox-score variants, promote measured wins || `harness-security-bench` | `/harness-security-bench [--population 2] [--cycles 1] [--alert-on-fail]` | "Darwin Shield" / ADR-155 β evolve a security-detection harness against a 10-vuln corpus |+| `harness-learn` | `/harness-learn --host <h> --model <m> --slice <manifest> [--repo <checkout>] [--run]` | [email protected] / upstream ADR-235 β GEPA learning run; $0 dry-run default, `--run` to spend; needs a metaharness repo checkout |+| `harness-gepa` | `/harness-gepa --op genome\|validate\|render\|analyze [--path <genome.json>]` | [email protected] GEPA library surface β genome load/validate/render + transcript failure analysis; `gepaOptimize` stays library-only |## Phase-0 baseline (ruflo itself, 2026-06-16)diff --git a/plugins/ruflo-metaharness/scripts/_darwin.mjs b/plugins/ruflo-metaharness/scripts/_darwin.mjsindex 2fd5bfac87..c70b607182 100644--- a/plugins/ruflo-metaharness/scripts/_darwin.mjs+++ b/plugins/ruflo-metaharness/scripts/_darwin.mjs@@ -2,9 +2,11 @@//// Mirrors `_harness.mjs` for the umbrella `metaharness` / `harness` binaries,// but targets the separate darwin binary (`metaharness-darwin`) which is-// published as its own npm package (`@metaharness/darwin@~0.3.1`).+// published as its own npm package (`@metaharness/darwin@~0.8.0`).//-// Three subcommands surfaced (matches darwin 0.3.x):+// Three subcommands surfaced (matches darwin 0.8.x β same verbs as 0.3.x,+// with GEPA-engine evolve flags added upstream: --selection modes,+// --crossover, --epistasis, --curriculum, --mutator ruvllm, --sandbox):// - `metaharness-darwin evolve <repo> [...]` β harness self-improvement// - `metaharness-darwin bench <create|verify> ...` β bench-suite lifecycle// - `metaharness-darwin security bench [...]` β Darwin Shield (upstream ADR-155)@@ -32,7 +34,7 @@ const DEFAULT_TIMEOUT_MS = 60_000;// Pinned semver range. Bump in lock-step with optionalDependencies in// @claude-flow/cli/package.json + ruflo/package.json. The `~` allows// patch upgrades without re-pinning.-const DARWIN_PIN = '@metaharness/darwin@~0.3.1';+const DARWIN_PIN = '@metaharness/darwin@~0.8.0';const DEGRADED_RX = /could not determine executable|404|not installed|MODULE_NOT_FOUND|ENOTFOUND|getaddrinfo|ECONNREFUSED|ETIMEDOUT/i;diff --git a/plugins/ruflo-metaharness/scripts/_redblue.mjs b/plugins/ruflo-metaharness/scripts/_redblue.mjsindex a0866e3af7..e59eada533 100644--- a/plugins/ruflo-metaharness/scripts/_redblue.mjs+++ b/plugins/ruflo-metaharness/scripts/_redblue.mjs@@ -1,7 +1,7 @@// _redblue.mjs β invocation helper for `@metaharness/redblue`.//// Sibling of `_darwin.mjs` / `_harness.mjs`. Targets the `redblue` binary-// from the standalone `@metaharness/redblue@~0.1.1` package.+// from the standalone `@metaharness/redblue@~0.1.4` package.//// Subcommands surfaced (matches redblue 0.1.x):// - `redblue init [--out redblue.yaml]`@@ -52,11 +52,17 @@ const INSTALL_TIMEOUT_MS = 180_000; // npm install can be slow on cold cache// Pinned semver range. Bump in lock-step with optionalDependencies in// @claude-flow/cli/package.json + ruflo/package.json.-const REDBLUE_PIN = '@metaharness/redblue@~0.1.1';+const REDBLUE_PIN = '@metaharness/redblue@~0.1.4';const REDBLUE_PKG = '@metaharness/redblue';-const REDBLUE_PIN_VERSION = '~0.1.1';+const REDBLUE_PIN_VERSION = '~0.1.4';-const CACHE_DIR = join(homedir(), '.ruflo', 'redblue-cache');+// Cache dir is versioned by the pin so bumping REDBLUE_PIN_VERSION+// invalidates stale installs β ensureInstalled() short-circuits on+// existsSync(RESOLVED_CLI), so an unversioned dir would keep serving+// the old package forever after a pin bump.+const CACHE_DIR = join(+ homedir(), '.ruflo', `redblue-cache-${REDBLUE_PIN_VERSION.replace(/[~^]/g, '')}`,+);const RESOLVED_CLI = join(CACHE_DIR, 'node_modules', '@metaharness', 'redblue', 'dist', 'cli', 'index.js',);diff --git a/plugins/ruflo-metaharness/scripts/gepa.mjs b/plugins/ruflo-metaharness/scripts/gepa.mjsnew file mode 100644index 0000000000..5f230b8000--- /dev/null+++ b/plugins/ruflo-metaharness/scripts/gepa.mjs@@ -0,0 +1,199 @@+#!/usr/bin/env node+// gepa.mjs β surfaces the `@metaharness/darwin/gepa` LIBRARY exports.+//+// Unlike every other script in this plugin, gepa has no CLI equivalent β+// GEPA (darwin 0.8.0's genetic-evolution prompt-adaptation engine) ships as+// a library entry (`import { ... } from '@metaharness/darwin/gepa'`). This+// script wraps the subprocess-safe subset:+//+// genome load + validate a genome (default: the shipped cand-6 β the+// first holdout-confirmed cheap-tier policy promotion)+// validate validateGenome(json) β structural errors[]+// render buildSystemFromGenome(genome) β the system prompt a genome+// compiles to (inspect what a policy actually says)+// analyze analyzeTranscript(entries) β failure-class breakdown+//+// NOT SURFACED: `gepaOptimize` β it takes an in-process `evaluate(candidate)`+// callback ("bring your own evaluator") which cannot cross a subprocess+// boundary. Optimization runs belong either in library consumers+// (import '@metaharness/darwin/gepa' directly) or behind the darwin CLI's+// `evolve` verb (scripts/evolve.mjs), which pairs GEPA with its sandbox+// evaluators.+//+// MODULE RESOLUTION (ADR-150 graceful degradation)+// ================================================+// 1. Try bare `import('@metaharness/darwin/gepa')` β free when the optional+// dep is installed in an ancestor node_modules.+// 2. Fall back to a ruflo-owned versioned cache install+// (~/.ruflo/darwin-cache-<pin>) β same pattern as _redblue.mjs; the+// versioned dir means pin bumps invalidate stale caches automatically.+// 3. Both fail β `{degraded: true}` exit 0. Never throws.+//+// EXIT CODES+// 0 op completed (or degraded)+// 1 --alert-on-invalid and validate found errors+// 2 config error (bad op / missing file)++import { readFileSync, existsSync, mkdirSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';++// Bump in lock-step with DARWIN_PIN in _darwin.mjs + optionalDependencies.+const DARWIN_PIN_VERSION = '~0.8.0';+const CACHE_DIR = join(+ homedir(), '.ruflo', `darwin-cache-${DARWIN_PIN_VERSION.replace(/[~^]/g, '')}`,+);+const CACHED_GEPA = join(+ CACHE_DIR, 'node_modules', '@metaharness', 'darwin', 'dist', 'gepa', 'index.js',+);++const ARGS = (() => {+ const a = {+ op: null,+ path: null, // genome JSON path (genome/validate/render); default cand-6+ transcript: null, // transcript JSON path (analyze)+ ext: undefined, // render β target file extension hint+ glob: undefined, // render β target glob hint+ alertOnInvalid: false,+ format: 'json',+ };+ for (let i = 2; i < process.argv.length; i++) {+ const v = process.argv[i];+ if (v === '--op') a.op = process.argv[++i];+ else if (v === '--path') a.path = process.argv[++i];+ else if (v === '--transcript') a.transcript = process.argv[++i];+ else if (v === '--ext') a.ext = process.argv[++i];+ else if (v === '--glob') a.glob = process.argv[++i];+ else if (v === '--alert-on-invalid') a.alertOnInvalid = true;+ else if (v === '--format') a.format = process.argv[++i];+ }+ return a;+})();++function emitDegradedAndExit(reason) {+ console.log(JSON.stringify({+ degraded: true,+ reason,+ hint: 'Install with `npm i -D @metaharness/darwin@' + DARWIN_PIN_VERSION+ + '` or verify network access β the gepa entry ships inside the darwin package.',+ generatedAt: new Date().toISOString(),+ }, null, 2));+ process.exit(0); // ADR-150 β ruflo stays operational without MetaHarness+}++async function importGepa() {+ try {+ return await import('@metaharness/darwin/gepa');+ } catch (e) {+ const msg = String(e?.message ?? e);+ // Fall back on absence AND on stale installs: a pre-0.8.0 darwin in an+ // ancestor node_modules has no './gepa' subpath, which throws+ // ERR_PACKAGE_PATH_NOT_EXPORTED rather than MODULE_NOT_FOUND.+ const recoverable = /Cannot find (module|package)|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND|ERR_PACKAGE_PATH_NOT_EXPORTED|is not defined by "exports"/i;+ if (!recoverable.test(msg)) throw e;+ }+ // Cached-install fallback.+ if (!existsSync(CACHED_GEPA)) {+ try {+ mkdirSync(CACHE_DIR, { recursive: true });+ } catch {+ return null;+ }+ const r = spawnSync('npm', [+ 'install',+ '--no-audit', '--no-fund', '--no-package-lock',+ '--prefix', CACHE_DIR,+ `@metaharness/darwin@${DARWIN_PIN_VERSION}`,+ ], {+ stdio: ['ignore', 'pipe', 'pipe'],+ encoding: 'utf-8',+ timeout: 180_000,+ shell: process.platform === 'win32',+ });+ if (r.status !== 0 || !existsSync(CACHED_GEPA)) return null;+ }+ try {+ return await import(pathToFileURL(CACHED_GEPA).href);+ } catch {+ return null;+ }+}++function readJsonFile(path, label) {+ if (!path || !existsSync(path)) {+ console.error(`gepa: ${label} file not found: ${path}`);+ process.exit(2);+ }+ try {+ return JSON.parse(readFileSync(path, 'utf8'));+ } catch (e) {+ console.error(`gepa: ${label} is not valid JSON: ${e?.message ?? e}`);+ process.exit(2);+ }+}++function loadGenomeOrExit(gepa) {+ if (ARGS.path) {+ if (!existsSync(ARGS.path)) {+ console.error(`gepa: --path genome file not found: ${ARGS.path}`);+ process.exit(2);+ }+ // upstream signature: loadGenome(readFileSync, path) β fs injected.+ return { genome: gepa.loadGenome(readFileSync, ARGS.path), source: ARGS.path };+ }+ return { genome: gepa.loadCand6Genome(), source: gepa.CAND6_GENOME_PATH };+}++async function main() {+ const OPS = ['genome', 'validate', 'render', 'analyze'];+ if (!OPS.includes(ARGS.op)) {+ console.error(`gepa: --op must be one of ${OPS.join('|')}`);+ process.exit(2);+ }++ const gepa = await importGepa();+ if (!gepa) emitDegradedAndExit('metaharness-darwin-not-available');++ const start = Date.now();+ let out;++ if (ARGS.op === 'genome') {+ const { genome, source } = loadGenomeOrExit(gepa);+ const errors = gepa.validateGenome(genome);+ out = { op: 'genome', source, valid: errors.length === 0, errors, genome };+ } else if (ARGS.op === 'validate') {+ // validate takes raw JSON (not loadGenome) so structurally-broken files+ // reach validateGenome instead of throwing in the loader.+ const raw = ARGS.path+ ? readJsonFile(ARGS.path, '--path genome')+ : gepa.loadCand6Genome();+ const errors = gepa.validateGenome(raw);+ out = { op: 'validate', source: ARGS.path ?? gepa.CAND6_GENOME_PATH, valid: errors.length === 0, errors };+ } else if (ARGS.op === 'render') {+ const { genome, source } = loadGenomeOrExit(gepa);+ const system = gepa.buildSystemFromGenome(genome, ARGS.ext, ARGS.glob);+ out = { op: 'render', source, chars: system.length, system };+ } else {+ // analyze+ const entries = readJsonFile(ARGS.transcript, '--transcript');+ if (!Array.isArray(entries)) {+ console.error('gepa: --transcript must be a JSON array of transcript entries');+ process.exit(2);+ }+ const analysis = gepa.analyzeTranscript(entries);+ out = { op: 'analyze', source: ARGS.transcript, entries: entries.length, analysis };+ }++ out.durationMs = Date.now() - start;+ console.log(JSON.stringify(out, null, 2));++ if (ARGS.alertOnInvalid && out.valid === false) process.exit(1);+ process.exit(0);+}++main().catch((e) => {+ console.error(`gepa: ${e?.message ?? e}`);+ process.exit(2);+});diff --git a/plugins/ruflo-metaharness/scripts/learn.mjs b/plugins/ruflo-metaharness/scripts/learn.mjsnew file mode 100644index 0000000000..9206a712a8--- /dev/null+++ b/plugins/ruflo-metaharness/scripts/learn.mjs@@ -0,0 +1,127 @@+#!/usr/bin/env node+// learn.mjs β wrapper around `metaharness learn` (upstream ADR-235, [email protected]).+//+// GEPA learning run: optimizes a harness genome against a SWE-bench-style+// slice manifest. $0 DRY-RUN BY DEFAULT β upstream only spends (model calls,+// Docker sandboxes) when --run is passed, and we forward that flag verbatim+// so the spend opt-in stays explicit at every layer.+//+// CHECKOUT PRECONDITION (upstream design, not a bug)+// ==================================================+// The learning harness (GEPA + SWE-bench + Docker) is too heavy to ship in+// the npm package, so `metaharness learn` requires a local clone of the+// metaharness repo, located via $METAHARNESS_REPO or by running inside the+// clone. When the checkout is absent we emit a structured+// `{status: "checkout-required"}` payload and exit 0 β the script ran as+// designed and told the agent what to do next. This is distinct from+// `degraded: true` (npm package absent). The managed-service path (gateway-+// side learn jobs, no checkout) is upstream's ADR-235 follow-up.+//+// USAGE+// node scripts/learn.mjs --host claude-code --model haiku --slice slices/lite.json+// node scripts/learn.mjs --repo ~/src/metaharness --host codex --model gpt-5-mini --slice s.json --run+//+// EXIT CODES+// 0 learn completed (or dry-run report, or degraded, or checkout-required)+// 1 --alert-on-fail and the learn run reported failure+// 2 config error (bad arg)++import { existsSync } from 'node:fs';+import { runMetaharnessAsync, emitDegradedJsonAndExit } from './_harness.mjs';++const ARGS = (() => {+ const a = {+ host: null,+ model: null,+ slice: null,+ repo: null,+ run: false,+ alertOnFail: false,+ format: 'json',+ timeoutMs: null,+ };+ for (let i = 2; i < process.argv.length; i++) {+ const v = process.argv[i];+ if (v === '--host') a.host = process.argv[++i];+ else if (v === '--model') a.model = process.argv[++i];+ else if (v === '--slice') a.slice = process.argv[++i];+ else if (v === '--repo') a.repo = process.argv[++i];+ else if (v === '--run') a.run = true;+ else if (v === '--alert-on-fail') a.alertOnFail = true;+ else if (v === '--format') a.format = process.argv[++i];+ else if (v === '--timeout-ms') a.timeoutMs = parseInt(process.argv[++i], 10);+ }+ return a;+})();++const CHECKOUT_RX = /requires a metaharness repo checkout/i;++function defaultTimeoutMs() {+ // Dry-run resolves the slice manifest + prices the run without spending β+ // bounded by repo scan, not model calls. Real runs (--run) are dominated+ // by model calls Γ slice size; callers should pass --timeout-ms matched+ // to their slice. 10 min is a floor for small slices, not a budget.+ return ARGS.run ? 600_000 : 120_000;+}++async function main() {+ if (ARGS.repo && !existsSync(ARGS.repo)) {+ console.error(`learn: --repo path does not exist: ${ARGS.repo}`);+ process.exit(2);+ }++ const cliArgs = ['learn'];+ if (ARGS.host) cliArgs.push('--host', ARGS.host);+ if (ARGS.model) cliArgs.push('--model', ARGS.model);+ if (ARGS.slice) cliArgs.push('--slice', ARGS.slice);+ if (ARGS.run) cliArgs.push('--run');++ const r = await runMetaharnessAsync(cliArgs, {+ // learn emits a human-readable report; --json support is not guaranteed+ // across 0.3.x, so we don't inject it and parse leniently instead.+ json: false,+ timeoutMs: ARGS.timeoutMs ?? defaultTimeoutMs(),+ env: ARGS.repo ? { METAHARNESS_REPO: ARGS.repo } : {},+ });++ if (r.degraded) emitDegradedJsonAndExit(r.reason);++ const combined = `${r.stdout}\n${r.stderr}`;+ if (CHECKOUT_RX.test(combined)) {+ console.log(JSON.stringify({+ status: 'checkout-required',+ hint: 'git clone https://github.com/ruvnet/metaharness.git, then re-run with '+ + '--repo /path/to/metaharness (or set METAHARNESS_REPO). The learning '+ + 'harness (GEPA + SWE-bench + Docker) is not shipped in the npm package.',+ dryRun: !ARGS.run,+ durationMs: r.durationMs,+ }, null, 2));+ process.exit(0);+ }++ // Lenient JSON extraction β grab the last {...} block if one exists.+ let json = null;+ const matches = [...r.stdout.matchAll(/\{[\s\S]*?\}/g)];+ for (let i = matches.length - 1; i >= 0; i--) {+ try { json = JSON.parse(matches[i][0]); break; } catch { /* try previous */ }+ }++ const out = {+ status: r.exitCode === 0 ? 'ok' : 'failed',+ dryRun: !ARGS.run,+ exitCode: r.exitCode,+ report: json,+ // When upstream emits no JSON, the raw report is still the deliverable.+ rawReport: json ? undefined : r.stdout.slice(0, 20_000),+ durationMs: r.durationMs,+ };+ console.log(JSON.stringify(out, null, 2));++ if (ARGS.alertOnFail && r.exitCode !== 0) process.exit(1);+ process.exit(0);+}++main().catch((e) => {+ console.error(`learn: ${e?.message ?? e}`);+ process.exit(2);+});diff --git a/plugins/ruflo-metaharness/scripts/smoke.sh b/plugins/ruflo-metaharness/scripts/smoke.shindex 3d66e6a6b3..db548c201d 100755--- a/plugins/ruflo-metaharness/scripts/smoke.sh+++ b/plugins/ruflo-metaharness/scripts/smoke.sh@@ -151,9 +151,9 @@ F="$ROOT/../../v3/@claude-flow/cli/src/commands/metaharness.ts"miss=""[[ -f "$F" ]] || miss="$miss command-file-missing"grep -q "name: 'metaharness'" "$F" 2>/dev/null || miss="$miss no-name-field"-# All 9 subcommands must each be present in the dispatch table.+# All core subcommands must each be present in the dispatch table.# Match either quoted ('mcp-scan': ...) or unquoted shorthand (score: ...) keys.-for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend mint redblue; do+for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend mint redblue learn gepa; dogrep -qE "(^|[[:space:]])'?${sub}'?:" "$F" 2>/dev/null || miss="$miss missing-$sub"done# Registered in the loader@@ -722,7 +722,7 @@ for k in $KEYS; dogrep -qE "npx ruflo metaharness ${k}([ \\\\]|$)" "$CMD" 2>/dev/null \|| miss="$miss subcommand-${k}-not-in-claude-md"done-[[ "$COUNT" == "11" ]] || miss="$miss subcommand-count-stale:$COUNT-expected-11"+[[ "$COUNT" == "13" ]] || miss="$miss subcommand-count-stale:$COUNT-expected-13"[[ -z "$miss" ]] && ok || bad "$miss"step "17z56. every MCP tool documented in CLAUDE.md (iter 93)"@@ -742,11 +742,12 @@ for t in $TOOLS; dogrep -q "mcp__claude-flow__${t}" "$CMD" 2>/dev/null \|| miss="$miss ${t}-not-in-claude-md"done-# Lock count: 13 MCP tools (mint deliberately excluded β see iter 73).+# Lock count: 15 MCP tools (mint deliberately excluded β see iter 73).# Bumped from 9 β 12 after ADR-153 added metaharness_bench,# metaharness_evolve, and metaharness_security_bench. Bumped from 12 β 13# after @metaharness/redblue integration added metaharness_redblue.-[[ "$COUNT" == "13" ]] || miss="$miss mcp-tool-count-stale:$COUNT-expected-13"+# Bumped from 13 β 15 after [email protected] learn + [email protected] gepa.+[[ "$COUNT" == "15" ]] || miss="$miss mcp-tool-count-stale:$COUNT-expected-15"[[ -z "$miss" ]] && ok || bad "$miss"step "17z55. MCP enum + SEVERITY_RANK vocabulary aligned (iter 92)"@@ -821,10 +822,11 @@ for f in $REFS; doCOUNT=$((COUNT + 1))[[ -f "$SCRIPTS_DIR/$f" ]] || miss="$miss mcp-script-${f}-missing"done-# Should be 13 unique scripts (one per MCP tool; mint deliberately excluded).+# Should be 15 unique scripts (one per MCP tool; mint deliberately excluded).# Bumped from 9 β 12 after ADR-153 added bench/evolve/security_bench tools.# Bumped from 12 β 13 after @metaharness/redblue integration added redblue.mjs.-[[ "$COUNT" == "13" ]] || miss="$miss mcp-script-count-stale:$COUNT-expected-13"+# Bumped from 13 β 15 after [email protected] learn + [email protected] gepa.+[[ "$COUNT" == "15" ]] || miss="$miss mcp-script-count-stale:$COUNT-expected-15"[[ -z "$miss" ]] && ok || bad "$miss"step "17z52. SUBCOMMANDS map entries point at existing script files (iter 89)"@@ -844,9 +846,9 @@ for f in $MAPPINGS; doCOUNT=$((COUNT + 1))[[ -f "$SCRIPTS_DIR/$f" ]] || miss="$miss script-${f}-missing"done-# Iter 73's description string + redblue addition lists 11 subcommands.-# SUBCOMMANDS map should have the same 11 entries. Lock the count at exactly 11.-[[ "$COUNT" == "11" ]] || miss="$miss mapping-count-stale:$COUNT-expected-11"+# Iter 73's description string + redblue + learn/gepa lists 13 subcommands.+# SUBCOMMANDS map should have the same 13 entries. Lock the count at exactly 13.+[[ "$COUNT" == "13" ]] || miss="$miss mapping-count-stale:$COUNT-expected-13"[[ -z "$miss" ]] && ok || bad "$miss"step "17z51. all metaharness scripts produce parseable JSON in --format json mode (iter 88)"@@ -1140,9 +1142,9 @@ step "17z36. CLI subcommand list current + mint anti-MCP guard (iter 73)"miss=""DISP="$ROOT/../../v3/@claude-flow/cli/src/commands/metaharness.ts"WRAPPER="$ROOT/../../v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts"-# All 11 dispatchable subcommands present (iter-73 had 10; @metaharness/redblue-# integration added redblue.mjs).-for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend similarity drift-from-history mint redblue; do+# All 13 dispatchable subcommands present (iter-73 had 10; @metaharness/redblue+# added redblue.mjs; [email protected]/[email protected] added learn.mjs + gepa.mjs).+for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend similarity drift-from-history mint redblue learn gepa; dogrep -q "${sub}" "$DISP" 2>/dev/null || miss="$miss subcommand-${sub}-not-listed"done# ANTI-MINT GUARD: mint is intentionally CLI-only per ADR-150 Β§Sandboxing@@ -1632,8 +1634,9 @@ WRAPPER="$ROOT/../../v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts"# Iter 46 set this at 9 (8 tools); iter 54 added the 9th β 10. ADR-153# added 3 more tools (bench/evolve/security_bench) β 1 + 12 = 13.# @metaharness/redblue integration added 1 more β 1 + 13 = 14.+# learn + gepa ([email protected] / [email protected]) added 2 more β 1 + 15 = 16.COUNT=$(grep -c "MCP_SUCCESS_SEMANTIC" "$WRAPPER" 2>/dev/null; true)-[[ "$COUNT" == "14" ]] || miss="$miss footnote-count:$COUNT-expected-14"+[[ "$COUNT" == "16" ]] || miss="$miss footnote-count:$COUNT-expected-16"# audit_trend now exposes baselineFile / currentFilegrep -q "baselineFile" "$WRAPPER" 2>/dev/null || miss="$miss no-baseline-file"grep -q "currentFile" "$WRAPPER" 2>/dev/null || miss="$miss no-current-file"@@ -1673,8 +1676,8 @@ COUNT_OLD=$(grep -c "success: !r.degraded" "$WRAPPER" 2>/dev/null; true)COUNT_NEW=$(grep -c "success: r.success" "$WRAPPER" 2>/dev/null; true)# Iter 54 added a 9th tool β 9. ADR-153 added 3 more (bench, evolve,# security_bench) β 12. @metaharness/redblue integration added 1 more β 13.-# Future iters that add tools should bump this.-[[ "$COUNT_NEW" == "13" ]] || miss="$miss new-pattern-count:$COUNT_NEW-expected-13"+# learn + gepa added 2 more β 15. Future iters that add tools should bump this.+[[ "$COUNT_NEW" == "15" ]] || miss="$miss new-pattern-count:$COUNT_NEW-expected-15"# Runtime anchors: iter 44 success assertions presentT="$ROOT/scripts/test-mcp-tools.mjs"grep -q "iter 44 fix" "$T" 2>/dev/null || miss="$miss no-iter44-anchors"@@ -2032,13 +2035,15 @@ grep -q "result has 'success'" "$F" || miss="$miss no-success-assertion"grep -q "result has 'data'" "$F" || miss="$miss no-data-assertion"grep -q "result has 'degraded'" "$F" || miss="$miss no-degraded-assertion"grep -q "result has 'exitCode'" "$F" || miss="$miss no-exitcode-assertion"-# All 13 tool names enumerated (similarity iter 36, drift_from_history iter 54,-# ADR-153 added bench/evolve/security_bench, @metaharness/redblue added redblue)-for tool in metaharness_score metaharness_genome metaharness_mcp_scan metaharness_threat_model metaharness_oia_audit metaharness_audit_list metaharness_audit_trend metaharness_similarity metaharness_drift_from_history metaharness_bench metaharness_evolve metaharness_security_bench metaharness_redblue; do+# All 15 tool names enumerated (similarity iter 36, drift_from_history iter 54,+# ADR-153 added bench/evolve/security_bench, @metaharness/redblue added redblue,+# [email protected]/[email protected] added learn + gepa)+for tool in metaharness_score metaharness_genome metaharness_mcp_scan metaharness_threat_model metaharness_oia_audit metaharness_audit_list metaharness_audit_trend metaharness_similarity metaharness_drift_from_history metaharness_bench metaharness_evolve metaharness_security_bench metaharness_redblue metaharness_learn metaharness_gepa; dogrep -q "${tool}" "$F" || miss="$miss missing-${tool}"done-# Count assertion must match iter-54 (8 β 9), then ADR-153 (9 β 12), then redblue (12 β 13)-grep -q "tools.length === 13" "$F" || miss="$miss tool-count-assertion-stale"+# Count assertion must match iter-54 (8 β 9), then ADR-153 (9 β 12), then+# redblue (12 β 13), then learn/gepa (13 β 15)+grep -q "tools.length === 15" "$F" || miss="$miss tool-count-assertion-stale"# Graceful skip when dist absent (so the script is smoke-runnable pre-build)grep -q "SKIPPED" "$F" || miss="$miss no-skip-doc"[[ -z "$miss" ]] && ok || bad "$miss"diff --git a/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs b/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjsindex f78813145a..c6db600fef 100755--- a/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs+++ b/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs@@ -74,7 +74,7 @@ async function main() {// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββconsole.log('Phase 1 β module shape');assert(Array.isArray(tools), 'metaharnessTools is an array');- assert(tools.length === 13, `13 tools registered (got ${tools.length})`);+ assert(tools.length === 15, `15 tools registered (got ${tools.length})`);const expectedNames = new Set(['metaharness_score',@@ -92,8 +92,12 @@ async function main() {'metaharness_bench','metaharness_evolve','metaharness_security_bench',- // @metaharness/redblue@~0.1.1 β adversarial red/blue LLM testing+ // @metaharness/redblue@~0.1.4 β adversarial red/blue LLM testing'metaharness_redblue',+ // [email protected] β upstream ADR-235 GEPA learning run+ 'metaharness_learn',+ // @metaharness/[email protected] β GEPA library surface (genome ops)+ 'metaharness_gepa',]);const actualNames = new Set(tools.map((t) => t.name));for (const name of expectedNames) {@@ -153,6 +157,16 @@ async function main() {// calls. Count=1 keeps cold-cache npx fetch the dominant cost.input = { subcommand: 'attack', family: 'prompt', count: 1 };}+ if (tool.name === 'metaharness_learn') {+ // No repo checkout in CI β structured {status:"checkout-required"}+ // exit-0 path. $0: without run=true upstream never spends anyway.+ input = {};+ }+ if (tool.name === 'metaharness_gepa') {+ // op is required; `genome` loads + validates the SHIPPED cand-6+ // genome β pure-local library call once darwin is cached.+ input = { op: 'genome' };+ }// iter 124 β 130 β timeouts have crept up as CI cold-cache npx// warmup costs got measured. Final budgets:@@ -167,9 +181,14 @@ async function main() {|| tool.name === 'metaharness_oia_audit'|| tool.name === 'metaharness_audit_list'// redblue: `attack prompt --count 1` is preview-only (no model- // calls) but the cold-cache `npx -y @metaharness/redblue@~0.1.1`+ // calls) but the cold-cache `npx -y @metaharness/redblue@~0.1.4`// fetch can take 30-60s. 180s gives 3x headroom.- || tool.name === 'metaharness_redblue';+ || tool.name === 'metaharness_redblue'+ // learn: cold-cache `npx -y metaharness@latest` fetch dominates.+ // gepa: one-time `npm install --prefix ~/.ruflo/darwin-cache-*`+ // fallback install can take 30-60s on cold cache.+ || tool.name === 'metaharness_learn'+ || tool.name === 'metaharness_gepa';const timeoutMs = isChainTool ? 180_000 : 60_000;const handlerPromise = tool.handler(input);const timeoutPromise = new Promise((_, reject) =>@@ -444,7 +463,7 @@ async function main() {for (const f of failures) console.log(` - ${f}`);process.exit(1);}- console.log('\nβ All 13 MCP tools satisfy the runtime contract.');+ console.log('\nβ All 15 MCP tools satisfy the runtime contract.');}main().catch((e) => {diff --git a/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md b/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.mdindex 37ede12de6..11c38c973f 100644--- a/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md+++ b/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md@@ -35,7 +35,7 @@ Implementation: [`scripts/evolve.mjs`](../../scripts/evolve.mjs).β€ 20, `--concurrency` β€ 8, sandbox/selection/mutator are known values).2. Without `--confirm`: print plan + exit 0 (mirrors `harness-mint` safetyconvention; defense in depth over the upstream `safety.ts` checks).-3. With `--confirm`: shell to `npx -y @metaharness/darwin@~0.3.1 metaharness-darwin evolve <repo> ...`+3. With `--confirm`: shell to `npx -y @metaharness/darwin@~0.8.0 metaharness-darwin evolve <repo> ...`via the shared `_darwin.mjs` async helper. Per-generation progress isforwarded to stderr; final champion JSON is captured from stdout.4. Compute timeout from `generations Γ children Γ per-variant` (per-variantdiff --git a/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md b/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.mdnew file mode 100644index 0000000000..7aa9771f28--- /dev/null+++ b/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md@@ -0,0 +1,65 @@+---+name: harness-gepa+description: Inspect and audit GEPA genomes via the `@metaharness/darwin/gepa` library entry (darwin 0.8.0) β load/validate a genome (default: the shipped cand-6 promotion), render the system prompt a genome compiles to, or classify failure modes in a run transcript. The `gepaOptimize` loop itself is library-only (bring your own evaluator) and not surfaced here β use `harness-evolve` for sandbox-scored evolution. Degrades gracefully when @metaharness/darwin is absent.+argument-hint: "--op genome|validate|render|analyze [--path <genome.json>] [--transcript <t.json>] [--alert-on-invalid]"+allowed-tools: Bash+---++Surfaces the GEPA (genetic-evolution prompt-adaptation) *library* exports+from `@metaharness/darwin/gepa`. Unlike the other skills in this plugin+there is no CLI binary behind this β the script dynamic-imports the library+(local resolution first, versioned cache install as fallback) and calls the+subprocess-safe subset.++## When to use++- **Adopting an evolved policy**: `--op render` shows the actual system+ prompt a genome compiles to β read THAT, not the raw JSON, before+ wiring a genome into a harness.+- **Auditing a promotion**: `--op genome` loads + validates the shipped+ cand-6 genome (first holdout-confirmed cheap-tier promotion; provenance+ ships in the package) or any genome file you point at.+- **CI gate on genome edits**: `--op validate --alert-on-invalid` exits 1+ on structural errors.+- **Debugging a bad run**: `--op analyze --transcript run.json` classifies+ failure modes (GEPA's failure-class taxonomy) from a transcript array.++## What is deliberately NOT here++`gepaOptimize` β the optimization loop takes an in-process+`evaluate(candidate)` callback ("bring your own evaluator") that cannot+cross a subprocess boundary. Two supported paths instead:++1. **Library consumers**: `import { gepaOptimize, loadCand6Genome } from '@metaharness/darwin/gepa'`+2. **Sandbox-scored evolution**: `harness-evolve` (darwin CLI `evolve`),+ which pairs GEPA with its own sandbox evaluators.++## Algorithm++Implementation: [`scripts/gepa.mjs`](../../scripts/gepa.mjs).++1. `import('@metaharness/darwin/gepa')`; on MODULE_NOT_FOUND fall back to a+ one-time `npm install --prefix ~/.ruflo/darwin-cache-0.8.0` and import+ the cached `dist/gepa/index.js` (versioned dir β pin bumps invalidate).+2. Dispatch `--op`:+ - `genome` β `loadGenome(fs, path)` or `loadCand6Genome()` + `validateGenome`+ - `validate` β `validateGenome(rawJson)` (raw parse so broken files reach+ the validator instead of throwing in the loader)+ - `render` β `buildSystemFromGenome(genome, ext?, glob?)`+ - `analyze` β `analyzeTranscript(entries)`+3. Emit one JSON object; exit 0 (or 1 under `--alert-on-invalid`, 2 on bad input).++## Examples++```bash+node scripts/gepa.mjs --op genome # cand-6 + validation+node scripts/gepa.mjs --op render | jq -r .system # what does cand-6 SAY?+node scripts/gepa.mjs --op validate --path my-genome.json --alert-on-invalid+node scripts/gepa.mjs --op analyze --transcript run.json+```++## Exit codes++- `0` β op completed (or degraded β darwin not installable)+- `1` β `--alert-on-invalid` and validation found errors+- `2` β config error (unknown op, missing/broken input file)diff --git a/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md b/plugins/ruflo-metaharness/skills/harness-learn/SKILL.mdnew file mode 100644index 0000000000..5b15de7be7--- /dev/null+++ b/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md@@ -0,0 +1,63 @@+---+name: harness-learn+description: Run a GEPA learning cycle via `metaharness learn` (upstream ADR-235, [email protected]) β optimizes a harness genome against a SWE-bench-style slice manifest. $0 dry-run by default; `--run` is the explicit spend opt-in. Requires a metaharness repo checkout (`--repo` or $METAHARNESS_REPO) β without one it reports `checkout-required` with clone instructions. Degrades gracefully when metaharness is absent.+argument-hint: "--host <h> --model <m> --slice <manifest> [--repo <checkout>] [--run] [--alert-on-fail]"+allowed-tools: Bash+---++Surfaces `metaharness learn` β the upstream GEPA learning harness that+evolves harness policy genomes against a scored task corpus instead of+hand-editing prompts. Candidates are scored on held-out slices and only+measured winners promote (the shipped cand-6 genome is the first such+promotion: holdout gold 2/12 β 3/12, zero regressions).++## When to use++- A harness's policy prompt underperforms on a task family and you want a+ measured improvement loop rather than manual prompt iteration.+- Pricing a learning run before committing spend β the default dry-run+ resolves the slice manifest and reports cost without any model calls.+- After a learn run promotes a genome: pair with `harness-gepa --op render`+ to inspect what the promoted policy actually says.++## Preconditions (upstream design)++The learning harness (GEPA + SWE-bench + Docker) is too heavy for the npm+package, so `learn` needs a local clone:++```bash+git clone https://github.com/ruvnet/metaharness.git+node scripts/learn.mjs --repo ./metaharness --host claude-code --model haiku --slice slices/lite.json+```++Without a checkout the script emits `{status: "checkout-required"}` and+exits 0 β a precondition report, not an error (distinct from+`degraded: true`, which means the npm package itself is absent). The+managed-service path (gateway-side learn jobs, no checkout) is upstream's+ADR-235 follow-up and not available yet.++## Algorithm++Implementation: [`scripts/learn.mjs`](../../scripts/learn.mjs).++1. Validate `--repo` exists when given; export it as `$METAHARNESS_REPO`.+2. Shell to `npx -y metaharness@latest learn --host <h> --model <m> --slice <s> [--run]`+ via `_harness.mjs` (graceful degradation, hard timeout).+3. Default timeouts: 120s dry-run, 600s with `--run` β real runs on larger+ slices need an explicit `--timeout-ms` matched to slice size Γ model cost.+4. Detect the checkout-required message β structured payload, exit 0.+5. Parse the trailing JSON report when upstream emits one; otherwise return+ the raw report text under `rawReport`.++## Cost note++`--run` is the ONLY path that spends. Everything else β dry-run, checkout+probe, degraded path β is $0. The MCP tool (`metaharness_learn`) has a 120s+subprocess budget; run real learning cycles from a terminal via+`ruflo metaharness learn ... --run --timeout-ms <big>`.++## Exit codes++- `0` β report produced (or dry-run, checkout-required, degraded)+- `1` β `--alert-on-fail` and the learn run reported failure+- `2` β config error (bad `--repo` path)diff --git a/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md b/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.mdindex c6f34dde87..e00c1e0bb0 100644--- a/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md+++ b/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md@@ -29,7 +29,7 @@ ground-truth set. Running this nightly gives us:Implementation: [`scripts/security-bench.mjs`](../../scripts/security-bench.mjs).-1. Shell to `npx -y @metaharness/darwin@~0.3.1 metaharness-darwin security bench --population N --cycles N [--seed S]`.+1. Shell to `npx -y @metaharness/darwin@~0.8.0 metaharness-darwin security bench --population N --cycles N [--seed S]`.2. Default timeout = `3s Γ 19 evaluations Γ population Γ cycles + 30s overhead`.At default `--population 2 --cycles 1` β 144s; at `--population 4 --cycles 3` β 12 min.3. Parse the markdown report β overall PASS/FAIL plus per-gatediff --git a/ruflo/package.json b/ruflo/package.jsonindex 03467490c9..de837e2bdc 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -43,11 +43,11 @@"@claude-flow/cli": "^3.10.3"},"optionalDependencies": {- "metaharness": "~0.2.6",+ "metaharness": "~0.2.8","@metaharness/router": "~0.3.2",- "@metaharness/kernel": "~0.1.0",- "@metaharness/darwin": "~0.3.1",- "@metaharness/redblue": "~0.1.1"+ "@metaharness/kernel": "~0.1.2",+ "@metaharness/darwin": "~0.8.0",+ "@metaharness/redblue": "~0.1.4"},"overrides": {"ruvector": "^0.2.27",diff --git a/ruflo/src/mcp-bridge/index.js b/ruflo/src/mcp-bridge/index.jsindex c56b7938e1..a024b90589 100644--- a/ruflo/src/mcp-bridge/index.js+++ b/ruflo/src/mcp-bridge/index.js@@ -882,6 +882,19 @@ const GROUP_DISPLAY_NAMES = {const app = express();app.use(express.json({ limit: "10mb" }));+// ---------- MCP Streamable HTTP session (#2425 djimit) ----------+// Streamable-HTTP clients (Codex/RMCP) send `DELETE /mcp` with an+// `Mcp-Session-Id` header at shutdown. We echo a stable session id back+// on every /mcp* response so those clients can attach it to the DELETE+// and to `notifications/initialized` handshakes.+const MCP_SESSION_ID = randomUUID();+app.use((req, res, next) => {+ if (req.path.startsWith("/mcp")) {+ res.setHeader("Mcp-Session-Id", MCP_SESSION_ID);+ }+ next();+});+// ---------- CORS middleware (ADR-166 Β§6 Phase 3b) ----------const CORS_ALLOWLIST = (process.env.MCP_CORS_ORIGIN || "*").split(",").map(s => s.trim()).filter(Boolean);@@ -894,8 +907,8 @@ app.use((req, res, next) => {res.setHeader("Access-Control-Allow-Origin", origin);res.setHeader("Vary", "Origin");}- res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");- res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id");if (req.method === "OPTIONS") return res.sendStatus(204);next();});@@ -944,7 +957,9 @@ function createMcpHandler(groupName) {return res.json({ jsonrpc: "2.0", id, result: mcpResult });}case "notifications/initialized":- return res.json({ jsonrpc: "2.0", id, result: {} });+ // MCP streamable-HTTP spec: notifications must return 202 Accepted+ // with an empty body (no jsonrpc envelope).+ return res.status(202).end();default:return res.json({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });}@@ -968,6 +983,8 @@ function createMcpSseHandler(groupName) {for (const groupName of Object.keys(TOOL_GROUPS)) {app.post(`/mcp/${groupName}`, createMcpHandler(groupName));app.get(`/mcp/${groupName}`, createMcpSseHandler(groupName));+ // #2425 djimit β streamable-HTTP session cleanup+ app.delete(`/mcp/${groupName}`, (_, res) => res.sendStatus(204));}// ---------- Catch-all /mcp β serves ALL enabled tools (backwards-compatible) ----------@@ -998,7 +1015,7 @@ app.post("/mcp", async (req, res) => {return res.json({ jsonrpc: "2.0", id, result: mcpResult });}case "notifications/initialized":- return res.json({ jsonrpc: "2.0", id, result: {} });+ return res.status(202).end();default:return res.json({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });}@@ -1015,6 +1032,9 @@ app.get("/mcp", (req, res) => {res.write(`data: ${JSON.stringify({ type: "endpoint", url: "/mcp" })}\n\n`);});+// #2425 djimit β streamable-HTTP session cleanup on the catch-all route.+app.delete("/mcp", (_, res) => res.sendStatus(204));+// ---------- GET /mcp-servers β returns MCP_SERVERS JSON for Chat UI config ----------app.get("/mcp-servers", (_, res) => {const servers = [];diff --git a/ruflo/src/mcp-bridge/test-runtime-security.mjs b/ruflo/src/mcp-bridge/test-runtime-security.mjsindex 2fb550be12..b57afffa16 100644--- a/ruflo/src/mcp-bridge/test-runtime-security.mjs+++ b/ruflo/src/mcp-bridge/test-runtime-security.mjs@@ -135,6 +135,37 @@ async function testBridge(label, entry) {} catch (e) {assert(false, `R4. terminal_execute threw: ${e.message}`);}++ // R6 β #2425 djimit streamable-HTTP session cleanup: DELETE /mcp β 204+ try {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: "DELETE",+ headers: {+ "Authorization": `Bearer ${TOKEN}`,+ "Mcp-Session-Id": "test-cleanup",+ },+ });+ assert(r.status === 204, `R6. DELETE /mcp β 204 (got ${r.status})`);+ assert(!!r.headers.get("Mcp-Session-Id"), "R6b. Mcp-Session-Id header echoed on /mcp*");+ } catch (e) {+ assert(false, `R6. DELETE /mcp threw: ${e.message}`);+ }++ // R7 β #2425 notifications/initialized returns 202 Accepted with empty body+ try {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Authorization": `Bearer ${TOKEN}`,+ },+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),+ });+ assert(r.status === 202, `R7. notifications/initialized β 202 (got ${r.status})`);+ assert((await r.text()) === "", "R7b. notifications/initialized has empty body");+ } catch (e) {+ assert(false, `R7. notifications/initialized threw: ${e.message}`);+ }}await killAndWait(b.child);}diff --git a/ruflo/src/mcp-bridge/test-security-lock.js b/ruflo/src/mcp-bridge/test-security-lock.jsindex 4c252f5f8a..9b5b665eee 100755--- a/ruflo/src/mcp-bridge/test-security-lock.js+++ b/ruflo/src/mcp-bridge/test-security-lock.js@@ -58,6 +58,16 @@ const CHECKS = [rx: /MCP_CORS_ORIGIN[\s\S]*?CORS_ALLOWLIST/,hint: "CORS must respect MCP_CORS_ORIGIN allowlist (Phase 3b)",},+ {+ id: "7. streamable-http-delete-handler (#2425)",+ rx: /app\.delete\(\s*["']\/mcp["']\s*,/,+ hint: "DELETE /mcp must be handled for streamable-HTTP session cleanup (#2425)",+ },+ {+ id: "8. mcp-session-id-header (#2425)",+ rx: /Mcp-Session-Id/,+ hint: "Mcp-Session-Id header must be echoed on /mcp* responses (#2425)",+ },];let hardFail = false;diff --git a/ruflo/src/ruvocal/mcp-bridge/index.js b/ruflo/src/ruvocal/mcp-bridge/index.jsindex 0dcbad521c..0d20fa77ad 100644--- a/ruflo/src/ruvocal/mcp-bridge/index.js+++ b/ruflo/src/ruvocal/mcp-bridge/index.js@@ -1057,6 +1057,19 @@ const GROUP_DISPLAY_NAMES = {const app = express();app.use(express.json({ limit: "10mb" }));+// ---------- MCP Streamable HTTP session (#2425 djimit) ----------+// Streamable-HTTP clients (Codex/RMCP) send `DELETE /mcp` with an+// `Mcp-Session-Id` header at shutdown. We echo a stable session id back+// on every /mcp* response so those clients can attach it to the DELETE+// and to `notifications/initialized` handshakes.+const MCP_SESSION_ID = randomUUID();+app.use((req, res, next) => {+ if (req.path.startsWith("/mcp")) {+ res.setHeader("Mcp-Session-Id", MCP_SESSION_ID);+ }+ next();+});+// ---------- CORS middleware (ADR-166 Β§6 Phase 3b) ----------// MCP_CORS_ORIGIN: comma-separated allowlist (e.g. "https://a.example,https://b.example").// unset β "*" for back-compat (loopback default is same-origin anyway)@@ -1074,8 +1087,8 @@ app.use((req, res, next) => {res.setHeader("Vary", "Origin");}// If no match, do NOT set the header β browser will block the request.- res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");- res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id");if (req.method === "OPTIONS") return res.sendStatus(204);next();});@@ -1125,7 +1138,9 @@ function createMcpHandler(groupName) {});}case "notifications/initialized":- return res.json({ jsonrpc: "2.0", id, result: {} });+ // MCP streamable-HTTP spec: notifications must return 202 Accepted+ // with an empty body (no jsonrpc envelope).+ return res.status(202).end();default:return res.json({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });}@@ -1149,6 +1164,8 @@ function createMcpSseHandler(groupName) {for (const groupName of Object.keys(TOOL_GROUPS)) {app.post(`/mcp/${groupName}`, createMcpHandler(groupName));app.get(`/mcp/${groupName}`, createMcpSseHandler(groupName));+ // #2425 djimit β streamable-HTTP session cleanup+ app.delete(`/mcp/${groupName}`, (_, res) => res.sendStatus(204));}// ---------- Catch-all /mcp β serves ALL enabled tools (backwards-compatible) ----------@@ -1180,7 +1197,7 @@ app.post("/mcp", async (req, res) => {});}case "notifications/initialized":- return res.json({ jsonrpc: "2.0", id, result: {} });+ return res.status(202).end();default:return res.json({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });}@@ -1197,6 +1214,9 @@ app.get("/mcp", (req, res) => {res.write(`data: ${JSON.stringify({ type: "endpoint", url: "/mcp" })}\n\n`);});+// #2425 djimit β streamable-HTTP session cleanup on the catch-all route.+app.delete("/mcp", (_, res) => res.sendStatus(204));+// ---------- GET /mcp-servers β returns MCP_SERVERS JSON for Chat UI config ----------app.get("/mcp-servers", (_, res) => {const servers = [];diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex f033c08a81..c2dec6be55 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -115,11 +115,11 @@"@claude-flow/memory": "^3.0.0-alpha.21","@claude-flow/plugin-gastown-bridge": "^0.1.3","@claude-flow/security": "^3.0.0-alpha.10",- "@metaharness/darwin": "~0.3.1",- "@metaharness/kernel": "~0.1.0",- "@metaharness/redblue": "~0.1.1",+ "@metaharness/darwin": "~0.8.0",+ "@metaharness/kernel": "~0.1.2",+ "@metaharness/redblue": "~0.1.4","@metaharness/router": "~0.3.2",- "metaharness": "~0.2.6",+ "metaharness": "~0.2.8","@ruvector/attention": "^0.1.32","@ruvector/attention-darwin-arm64": "0.1.32","@ruvector/diskann": "^0.1.0",diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/README.md b/v3/@claude-flow/cli/plugins/ruflo-metaharness/README.mdindex 37e5894523..3fa2ca1546 100644--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/README.md+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/README.md@@ -1,6 +1,6 @@# ruflo-metaharness-MetaHarness integration plugin for ruflo. Surfaces the upstream `metaharness` / `harness` CLIs through five ruflo skills, honoring [ADR-150](../../v3/docs/adr/ADR-150-metaharness-integration-surfaces.md)'s architectural constraint that MetaHarness must remain a removable augmentation β never a required runtime dependency.+MetaHarness integration plugin for ruflo. Surfaces the upstream `metaharness` / `harness` / `@metaharness/darwin` CLIs through eleven ruflo skills, honoring [ADR-150](../../v3/docs/adr/ADR-150-metaharness-integration-surfaces.md)'s architectural constraint that MetaHarness must remain a removable augmentation β never a required runtime dependency.## ADR-150 architectural constraint (load-bearing)@@ -20,6 +20,14 @@ MetaHarness integration plugin for ruflo. Surfaces the upstream `metaharness` /| `harness-mcp-scan` | `/harness-mcp-scan [--path .] [--fail-on high]` | Static MCP security findings β pure-read, no dispatch || `harness-threat-model` | `/harness-threat-model [--path .] [--fail-on high]` | Enterprise-grade threat model (clean/low/medium/high + findings) || `harness-mint` | `/harness-mint --name <id> --template <id> [--confirm]` | Scaffold a custom harness; DRY-RUN by default; refuses project-root writes |+| `harness-similarity` | `/harness-similarity --a a.json --b b.json [--per-dimension] [--alert-below 0.5]` | ADR-152 Β§3.1 weighted similarity between two harness fingerprints (cosine + categorical + jaccard) |+| `harness-oia-audit` | `/harness-oia-audit [--path .] [--alert-on-worst high] [--dry-run]` | Composite Phase-2 audit (oia-manifest + threat-model + mcp-scan) into `metaharness-audit` namespace |+| `harness-drift-from-history` | `/harness-drift-from-history [--baseline-since 7d] [--threshold 0.95]` | 1-command drift detection β composes audit-list + oia-audit + audit-trend |+| `harness-bench` | `/harness-bench --op create\|verify --repo <path>` | Manage `@metaharness/darwin` bench suites β fixed evaluation corpora for `harness-evolve` |+| `harness-evolve` | `/harness-evolve --repo <path> [--generations 3] [--sandbox real\|mock\|agent]` | Run `@metaharness/darwin evolve` β mutate seven policy surfaces, sandbox-score variants, promote measured wins |+| `harness-security-bench` | `/harness-security-bench [--population 2] [--cycles 1] [--alert-on-fail]` | "Darwin Shield" / ADR-155 β evolve a security-detection harness against a 10-vuln corpus |+| `harness-learn` | `/harness-learn --host <h> --model <m> --slice <manifest> [--repo <checkout>] [--run]` | [email protected] / upstream ADR-235 β GEPA learning run; $0 dry-run default, `--run` to spend; needs a metaharness repo checkout |+| `harness-gepa` | `/harness-gepa --op genome\|validate\|render\|analyze [--path <genome.json>]` | [email protected] GEPA library surface β genome load/validate/render + transcript failure analysis; `gepaOptimize` stays library-only |## Phase-0 baseline (ruflo itself, 2026-06-16)diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_darwin.mjs b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_darwin.mjsindex 2fd5bfac87..c70b607182 100644--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_darwin.mjs+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_darwin.mjs@@ -2,9 +2,11 @@//// Mirrors `_harness.mjs` for the umbrella `metaharness` / `harness` binaries,// but targets the separate darwin binary (`metaharness-darwin`) which is-// published as its own npm package (`@metaharness/darwin@~0.3.1`).+// published as its own npm package (`@metaharness/darwin@~0.8.0`).//-// Three subcommands surfaced (matches darwin 0.3.x):+// Three subcommands surfaced (matches darwin 0.8.x β same verbs as 0.3.x,+// with GEPA-engine evolve flags added upstream: --selection modes,+// --crossover, --epistasis, --curriculum, --mutator ruvllm, --sandbox):// - `metaharness-darwin evolve <repo> [...]` β harness self-improvement// - `metaharness-darwin bench <create|verify> ...` β bench-suite lifecycle// - `metaharness-darwin security bench [...]` β Darwin Shield (upstream ADR-155)@@ -32,7 +34,7 @@ const DEFAULT_TIMEOUT_MS = 60_000;// Pinned semver range. Bump in lock-step with optionalDependencies in// @claude-flow/cli/package.json + ruflo/package.json. The `~` allows// patch upgrades without re-pinning.-const DARWIN_PIN = '@metaharness/darwin@~0.3.1';+const DARWIN_PIN = '@metaharness/darwin@~0.8.0';const DEGRADED_RX = /could not determine executable|404|not installed|MODULE_NOT_FOUND|ENOTFOUND|getaddrinfo|ECONNREFUSED|ETIMEDOUT/i;diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_redblue.mjs b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_redblue.mjsindex a0866e3af7..e59eada533 100644--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_redblue.mjs+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/_redblue.mjs@@ -1,7 +1,7 @@// _redblue.mjs β invocation helper for `@metaharness/redblue`.//// Sibling of `_darwin.mjs` / `_harness.mjs`. Targets the `redblue` binary-// from the standalone `@metaharness/redblue@~0.1.1` package.+// from the standalone `@metaharness/redblue@~0.1.4` package.//// Subcommands surfaced (matches redblue 0.1.x):// - `redblue init [--out redblue.yaml]`@@ -52,11 +52,17 @@ const INSTALL_TIMEOUT_MS = 180_000; // npm install can be slow on cold cache// Pinned semver range. Bump in lock-step with optionalDependencies in// @claude-flow/cli/package.json + ruflo/package.json.-const REDBLUE_PIN = '@metaharness/redblue@~0.1.1';+const REDBLUE_PIN = '@metaharness/redblue@~0.1.4';const REDBLUE_PKG = '@metaharness/redblue';-const REDBLUE_PIN_VERSION = '~0.1.1';+const REDBLUE_PIN_VERSION = '~0.1.4';-const CACHE_DIR = join(homedir(), '.ruflo', 'redblue-cache');+// Cache dir is versioned by the pin so bumping REDBLUE_PIN_VERSION+// invalidates stale installs β ensureInstalled() short-circuits on+// existsSync(RESOLVED_CLI), so an unversioned dir would keep serving+// the old package forever after a pin bump.+const CACHE_DIR = join(+ homedir(), '.ruflo', `redblue-cache-${REDBLUE_PIN_VERSION.replace(/[~^]/g, '')}`,+);const RESOLVED_CLI = join(CACHE_DIR, 'node_modules', '@metaharness', 'redblue', 'dist', 'cli', 'index.js',);diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/gepa.mjs b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/gepa.mjsnew file mode 100644index 0000000000..5f230b8000--- /dev/null+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/gepa.mjs@@ -0,0 +1,199 @@+#!/usr/bin/env node+// gepa.mjs β surfaces the `@metaharness/darwin/gepa` LIBRARY exports.+//+// Unlike every other script in this plugin, gepa has no CLI equivalent β+// GEPA (darwin 0.8.0's genetic-evolution prompt-adaptation engine) ships as+// a library entry (`import { ... } from '@metaharness/darwin/gepa'`). This+// script wraps the subprocess-safe subset:+//+// genome load + validate a genome (default: the shipped cand-6 β the+// first holdout-confirmed cheap-tier policy promotion)+// validate validateGenome(json) β structural errors[]+// render buildSystemFromGenome(genome) β the system prompt a genome+// compiles to (inspect what a policy actually says)+// analyze analyzeTranscript(entries) β failure-class breakdown+//+// NOT SURFACED: `gepaOptimize` β it takes an in-process `evaluate(candidate)`+// callback ("bring your own evaluator") which cannot cross a subprocess+// boundary. Optimization runs belong either in library consumers+// (import '@metaharness/darwin/gepa' directly) or behind the darwin CLI's+// `evolve` verb (scripts/evolve.mjs), which pairs GEPA with its sandbox+// evaluators.+//+// MODULE RESOLUTION (ADR-150 graceful degradation)+// ================================================+// 1. Try bare `import('@metaharness/darwin/gepa')` β free when the optional+// dep is installed in an ancestor node_modules.+// 2. Fall back to a ruflo-owned versioned cache install+// (~/.ruflo/darwin-cache-<pin>) β same pattern as _redblue.mjs; the+// versioned dir means pin bumps invalidate stale caches automatically.+// 3. Both fail β `{degraded: true}` exit 0. Never throws.+//+// EXIT CODES+// 0 op completed (or degraded)+// 1 --alert-on-invalid and validate found errors+// 2 config error (bad op / missing file)++import { readFileSync, existsSync, mkdirSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';++// Bump in lock-step with DARWIN_PIN in _darwin.mjs + optionalDependencies.+const DARWIN_PIN_VERSION = '~0.8.0';+const CACHE_DIR = join(+ homedir(), '.ruflo', `darwin-cache-${DARWIN_PIN_VERSION.replace(/[~^]/g, '')}`,+);+const CACHED_GEPA = join(+ CACHE_DIR, 'node_modules', '@metaharness', 'darwin', 'dist', 'gepa', 'index.js',+);++const ARGS = (() => {+ const a = {+ op: null,+ path: null, // genome JSON path (genome/validate/render); default cand-6+ transcript: null, // transcript JSON path (analyze)+ ext: undefined, // render β target file extension hint+ glob: undefined, // render β target glob hint+ alertOnInvalid: false,+ format: 'json',+ };+ for (let i = 2; i < process.argv.length; i++) {+ const v = process.argv[i];+ if (v === '--op') a.op = process.argv[++i];+ else if (v === '--path') a.path = process.argv[++i];+ else if (v === '--transcript') a.transcript = process.argv[++i];+ else if (v === '--ext') a.ext = process.argv[++i];+ else if (v === '--glob') a.glob = process.argv[++i];+ else if (v === '--alert-on-invalid') a.alertOnInvalid = true;+ else if (v === '--format') a.format = process.argv[++i];+ }+ return a;+})();++function emitDegradedAndExit(reason) {+ console.log(JSON.stringify({+ degraded: true,+ reason,+ hint: 'Install with `npm i -D @metaharness/darwin@' + DARWIN_PIN_VERSION+ + '` or verify network access β the gepa entry ships inside the darwin package.',+ generatedAt: new Date().toISOString(),+ }, null, 2));+ process.exit(0); // ADR-150 β ruflo stays operational without MetaHarness+}++async function importGepa() {+ try {+ return await import('@metaharness/darwin/gepa');+ } catch (e) {+ const msg = String(e?.message ?? e);+ // Fall back on absence AND on stale installs: a pre-0.8.0 darwin in an+ // ancestor node_modules has no './gepa' subpath, which throws+ // ERR_PACKAGE_PATH_NOT_EXPORTED rather than MODULE_NOT_FOUND.+ const recoverable = /Cannot find (module|package)|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND|ERR_PACKAGE_PATH_NOT_EXPORTED|is not defined by "exports"/i;+ if (!recoverable.test(msg)) throw e;+ }+ // Cached-install fallback.+ if (!existsSync(CACHED_GEPA)) {+ try {+ mkdirSync(CACHE_DIR, { recursive: true });+ } catch {+ return null;+ }+ const r = spawnSync('npm', [+ 'install',+ '--no-audit', '--no-fund', '--no-package-lock',+ '--prefix', CACHE_DIR,+ `@metaharness/darwin@${DARWIN_PIN_VERSION}`,+ ], {+ stdio: ['ignore', 'pipe', 'pipe'],+ encoding: 'utf-8',+ timeout: 180_000,+ shell: process.platform === 'win32',+ });+ if (r.status !== 0 || !existsSync(CACHED_GEPA)) return null;+ }+ try {+ return await import(pathToFileURL(CACHED_GEPA).href);+ } catch {+ return null;+ }+}++function readJsonFile(path, label) {+ if (!path || !existsSync(path)) {+ console.error(`gepa: ${label} file not found: ${path}`);+ process.exit(2);+ }+ try {+ return JSON.parse(readFileSync(path, 'utf8'));+ } catch (e) {+ console.error(`gepa: ${label} is not valid JSON: ${e?.message ?? e}`);+ process.exit(2);+ }+}++function loadGenomeOrExit(gepa) {+ if (ARGS.path) {+ if (!existsSync(ARGS.path)) {+ console.error(`gepa: --path genome file not found: ${ARGS.path}`);+ process.exit(2);+ }+ // upstream signature: loadGenome(readFileSync, path) β fs injected.+ return { genome: gepa.loadGenome(readFileSync, ARGS.path), source: ARGS.path };+ }+ return { genome: gepa.loadCand6Genome(), source: gepa.CAND6_GENOME_PATH };+}++async function main() {+ const OPS = ['genome', 'validate', 'render', 'analyze'];+ if (!OPS.includes(ARGS.op)) {+ console.error(`gepa: --op must be one of ${OPS.join('|')}`);+ process.exit(2);+ }++ const gepa = await importGepa();+ if (!gepa) emitDegradedAndExit('metaharness-darwin-not-available');++ const start = Date.now();+ let out;++ if (ARGS.op === 'genome') {+ const { genome, source } = loadGenomeOrExit(gepa);+ const errors = gepa.validateGenome(genome);+ out = { op: 'genome', source, valid: errors.length === 0, errors, genome };+ } else if (ARGS.op === 'validate') {+ // validate takes raw JSON (not loadGenome) so structurally-broken files+ // reach validateGenome instead of throwing in the loader.+ const raw = ARGS.path+ ? readJsonFile(ARGS.path, '--path genome')+ : gepa.loadCand6Genome();+ const errors = gepa.validateGenome(raw);+ out = { op: 'validate', source: ARGS.path ?? gepa.CAND6_GENOME_PATH, valid: errors.length === 0, errors };+ } else if (ARGS.op === 'render') {+ const { genome, source } = loadGenomeOrExit(gepa);+ const system = gepa.buildSystemFromGenome(genome, ARGS.ext, ARGS.glob);+ out = { op: 'render', source, chars: system.length, system };+ } else {+ // analyze+ const entries = readJsonFile(ARGS.transcript, '--transcript');+ if (!Array.isArray(entries)) {+ console.error('gepa: --transcript must be a JSON array of transcript entries');+ process.exit(2);+ }+ const analysis = gepa.analyzeTranscript(entries);+ out = { op: 'analyze', source: ARGS.transcript, entries: entries.length, analysis };+ }++ out.durationMs = Date.now() - start;+ console.log(JSON.stringify(out, null, 2));++ if (ARGS.alertOnInvalid && out.valid === false) process.exit(1);+ process.exit(0);+}++main().catch((e) => {+ console.error(`gepa: ${e?.message ?? e}`);+ process.exit(2);+});diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/learn.mjs b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/learn.mjsnew file mode 100644index 0000000000..9206a712a8--- /dev/null+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/learn.mjs@@ -0,0 +1,127 @@+#!/usr/bin/env node+// learn.mjs β wrapper around `metaharness learn` (upstream ADR-235, [email protected]).+//+// GEPA learning run: optimizes a harness genome against a SWE-bench-style+// slice manifest. $0 DRY-RUN BY DEFAULT β upstream only spends (model calls,+// Docker sandboxes) when --run is passed, and we forward that flag verbatim+// so the spend opt-in stays explicit at every layer.+//+// CHECKOUT PRECONDITION (upstream design, not a bug)+// ==================================================+// The learning harness (GEPA + SWE-bench + Docker) is too heavy to ship in+// the npm package, so `metaharness learn` requires a local clone of the+// metaharness repo, located via $METAHARNESS_REPO or by running inside the+// clone. When the checkout is absent we emit a structured+// `{status: "checkout-required"}` payload and exit 0 β the script ran as+// designed and told the agent what to do next. This is distinct from+// `degraded: true` (npm package absent). The managed-service path (gateway-+// side learn jobs, no checkout) is upstream's ADR-235 follow-up.+//+// USAGE+// node scripts/learn.mjs --host claude-code --model haiku --slice slices/lite.json+// node scripts/learn.mjs --repo ~/src/metaharness --host codex --model gpt-5-mini --slice s.json --run+//+// EXIT CODES+// 0 learn completed (or dry-run report, or degraded, or checkout-required)+// 1 --alert-on-fail and the learn run reported failure+// 2 config error (bad arg)++import { existsSync } from 'node:fs';+import { runMetaharnessAsync, emitDegradedJsonAndExit } from './_harness.mjs';++const ARGS = (() => {+ const a = {+ host: null,+ model: null,+ slice: null,+ repo: null,+ run: false,+ alertOnFail: false,+ format: 'json',+ timeoutMs: null,+ };+ for (let i = 2; i < process.argv.length; i++) {+ const v = process.argv[i];+ if (v === '--host') a.host = process.argv[++i];+ else if (v === '--model') a.model = process.argv[++i];+ else if (v === '--slice') a.slice = process.argv[++i];+ else if (v === '--repo') a.repo = process.argv[++i];+ else if (v === '--run') a.run = true;+ else if (v === '--alert-on-fail') a.alertOnFail = true;+ else if (v === '--format') a.format = process.argv[++i];+ else if (v === '--timeout-ms') a.timeoutMs = parseInt(process.argv[++i], 10);+ }+ return a;+})();++const CHECKOUT_RX = /requires a metaharness repo checkout/i;++function defaultTimeoutMs() {+ // Dry-run resolves the slice manifest + prices the run without spending β+ // bounded by repo scan, not model calls. Real runs (--run) are dominated+ // by model calls Γ slice size; callers should pass --timeout-ms matched+ // to their slice. 10 min is a floor for small slices, not a budget.+ return ARGS.run ? 600_000 : 120_000;+}++async function main() {+ if (ARGS.repo && !existsSync(ARGS.repo)) {+ console.error(`learn: --repo path does not exist: ${ARGS.repo}`);+ process.exit(2);+ }++ const cliArgs = ['learn'];+ if (ARGS.host) cliArgs.push('--host', ARGS.host);+ if (ARGS.model) cliArgs.push('--model', ARGS.model);+ if (ARGS.slice) cliArgs.push('--slice', ARGS.slice);+ if (ARGS.run) cliArgs.push('--run');++ const r = await runMetaharnessAsync(cliArgs, {+ // learn emits a human-readable report; --json support is not guaranteed+ // across 0.3.x, so we don't inject it and parse leniently instead.+ json: false,+ timeoutMs: ARGS.timeoutMs ?? defaultTimeoutMs(),+ env: ARGS.repo ? { METAHARNESS_REPO: ARGS.repo } : {},+ });++ if (r.degraded) emitDegradedJsonAndExit(r.reason);++ const combined = `${r.stdout}\n${r.stderr}`;+ if (CHECKOUT_RX.test(combined)) {+ console.log(JSON.stringify({+ status: 'checkout-required',+ hint: 'git clone https://github.com/ruvnet/metaharness.git, then re-run with '+ + '--repo /path/to/metaharness (or set METAHARNESS_REPO). The learning '+ + 'harness (GEPA + SWE-bench + Docker) is not shipped in the npm package.',+ dryRun: !ARGS.run,+ durationMs: r.durationMs,+ }, null, 2));+ process.exit(0);+ }++ // Lenient JSON extraction β grab the last {...} block if one exists.+ let json = null;+ const matches = [...r.stdout.matchAll(/\{[\s\S]*?\}/g)];+ for (let i = matches.length - 1; i >= 0; i--) {+ try { json = JSON.parse(matches[i][0]); break; } catch { /* try previous */ }+ }++ const out = {+ status: r.exitCode === 0 ? 'ok' : 'failed',+ dryRun: !ARGS.run,+ exitCode: r.exitCode,+ report: json,+ // When upstream emits no JSON, the raw report is still the deliverable.+ rawReport: json ? undefined : r.stdout.slice(0, 20_000),+ durationMs: r.durationMs,+ };+ console.log(JSON.stringify(out, null, 2));++ if (ARGS.alertOnFail && r.exitCode !== 0) process.exit(1);+ process.exit(0);+}++main().catch((e) => {+ console.error(`learn: ${e?.message ?? e}`);+ process.exit(2);+});diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/mint.mjs b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/mint.mjsindex 7116812ccd..9c8ddab026 100755--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/mint.mjs+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/mint.mjs@@ -60,6 +60,13 @@ function safetyChecks() {function main() {safetyChecks();+ // ADR-150 architectural-constraint #3 (graceful degradation): even the+ // dry-run path must report degraded:true when metaharness is unreachable+ // β otherwise users with no network / proxy block see a happy-looking+ // plan and only hit the failure on --confirm. The no-metaharness-smoke+ // CI gate asserts every script emits a `"degraded"` field in this case.+ const probe = runMetaharness(['--version'], { json: false, timeoutMs: 15_000 });+ if (probe.degraded) { emitDegradedJsonAndExit(probe.reason); return; }const plan = {action: 'metaharness new',name: ARGS.name,diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/smoke.sh b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/smoke.shindex 63794e3c3d..db548c201d 100755--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/smoke.sh+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/smoke.sh@@ -151,9 +151,9 @@ F="$ROOT/../../v3/@claude-flow/cli/src/commands/metaharness.ts"miss=""[[ -f "$F" ]] || miss="$miss command-file-missing"grep -q "name: 'metaharness'" "$F" 2>/dev/null || miss="$miss no-name-field"-# All 8 subcommands must each be present in the dispatch table.+# All core subcommands must each be present in the dispatch table.# Match either quoted ('mcp-scan': ...) or unquoted shorthand (score: ...) keys.-for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend mint; do+for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend mint redblue learn gepa; dogrep -qE "(^|[[:space:]])'?${sub}'?:" "$F" 2>/dev/null || miss="$miss missing-$sub"done# Registered in the loader@@ -342,7 +342,7 @@ miss=""ROOTPJ="$ROOT/../../package.json"RUFLOPJ="$ROOT/../../ruflo/package.json"CLIPJ="$ROOT/../../v3/@claude-flow/cli/package.json"-for pkg in "metaharness" "@metaharness/router" "@metaharness/kernel"; do+for pkg in "metaharness" "@metaharness/router" "@metaharness/kernel" "@metaharness/redblue"; doROOT_PIN=$(node -e "console.log(JSON.parse(require('fs').readFileSync('$ROOTPJ')).optionalDependencies?.['$pkg'] || '')" 2>/dev/null)RUFLO_PIN=$(node -e "console.log(JSON.parse(require('fs').readFileSync('$RUFLOPJ')).optionalDependencies?.['$pkg'] || '')" 2>/dev/null)CLI_PIN=$(node -e "console.log(JSON.parse(require('fs').readFileSync('$CLIPJ')).optionalDependencies?.['$pkg'] || '')" 2>/dev/null)@@ -657,8 +657,13 @@ grep -q "metaharness drift-from-history" "$W" 2>/dev/null || miss="$miss no-cli-grep -q '"path": "file"' "$W" 2>/dev/null || miss="$miss no-path-file-assert"grep -q '"skippedAuditList": true' "$W" 2>/dev/null || miss="$miss no-skip-true-assert"grep -q "/tmp/drift-baseline.json" "$W" 2>/dev/null || miss="$miss no-baseline-path"-# Iter-98 step lives in the metaharness-real-data job-grep -B100 "Drift-from-history dispatcher round-trip" "$W" 2>/dev/null | grep -q "metaharness-real-data:" \+# Iter-98 step lives in the metaharness-real-data job. The brittle+# fixed-window lookback (-B100) broke once the job grew past 100 lines;+# instead use awk to find the most recent top-level job header above+# the step and check it is metaharness-real-data.+last_job=$(awk '/^ [a-zA-Z_-]+:[[:space:]]*$/ { last=$0 }+ /Drift-from-history dispatcher round-trip/ { print last; exit }' "$W" 2>/dev/null)+echo "$last_job" | grep -q "metaharness-real-data:" \|| miss="$miss not-in-real-data-job"[[ -z "$miss" ]] && ok || bad "$miss"@@ -717,7 +722,7 @@ for k in $KEYS; dogrep -qE "npx ruflo metaharness ${k}([ \\\\]|$)" "$CMD" 2>/dev/null \|| miss="$miss subcommand-${k}-not-in-claude-md"done-[[ "$COUNT" == "10" ]] || miss="$miss subcommand-count-stale:$COUNT-expected-10"+[[ "$COUNT" == "13" ]] || miss="$miss subcommand-count-stale:$COUNT-expected-13"[[ -z "$miss" ]] && ok || bad "$miss"step "17z56. every MCP tool documented in CLAUDE.md (iter 93)"@@ -737,8 +742,12 @@ for t in $TOOLS; dogrep -q "mcp__claude-flow__${t}" "$CMD" 2>/dev/null \|| miss="$miss ${t}-not-in-claude-md"done-# Lock count: 9 MCP tools (mint deliberately excluded β see iter 73)-[[ "$COUNT" == "9" ]] || miss="$miss mcp-tool-count-stale:$COUNT-expected-9"+# Lock count: 15 MCP tools (mint deliberately excluded β see iter 73).+# Bumped from 9 β 12 after ADR-153 added metaharness_bench,+# metaharness_evolve, and metaharness_security_bench. Bumped from 12 β 13+# after @metaharness/redblue integration added metaharness_redblue.+# Bumped from 13 β 15 after [email protected] learn + [email protected] gepa.+[[ "$COUNT" == "15" ]] || miss="$miss mcp-tool-count-stale:$COUNT-expected-15"[[ -z "$miss" ]] && ok || bad "$miss"step "17z55. MCP enum + SEVERITY_RANK vocabulary aligned (iter 92)"@@ -813,8 +822,11 @@ for f in $REFS; doCOUNT=$((COUNT + 1))[[ -f "$SCRIPTS_DIR/$f" ]] || miss="$miss mcp-script-${f}-missing"done-# Should be 9 unique scripts (one per MCP tool; mint deliberately excluded)-[[ "$COUNT" == "9" ]] || miss="$miss mcp-script-count-stale:$COUNT-expected-9"+# Should be 15 unique scripts (one per MCP tool; mint deliberately excluded).+# Bumped from 9 β 12 after ADR-153 added bench/evolve/security_bench tools.+# Bumped from 12 β 13 after @metaharness/redblue integration added redblue.mjs.+# Bumped from 13 β 15 after [email protected] learn + [email protected] gepa.+[[ "$COUNT" == "15" ]] || miss="$miss mcp-script-count-stale:$COUNT-expected-15"[[ -z "$miss" ]] && ok || bad "$miss"step "17z52. SUBCOMMANDS map entries point at existing script files (iter 89)"@@ -834,9 +846,9 @@ for f in $MAPPINGS; doCOUNT=$((COUNT + 1))[[ -f "$SCRIPTS_DIR/$f" ]] || miss="$miss script-${f}-missing"done-# Iter 73's description string lists 10 subcommands. SUBCOMMANDS map should-# have the same 10 entries. Lock the count at exactly 10.-[[ "$COUNT" == "10" ]] || miss="$miss mapping-count-stale:$COUNT-expected-10"+# Iter 73's description string + redblue + learn/gepa lists 13 subcommands.+# SUBCOMMANDS map should have the same 13 entries. Lock the count at exactly 13.+[[ "$COUNT" == "13" ]] || miss="$miss mapping-count-stale:$COUNT-expected-13"[[ -z "$miss" ]] && ok || bad "$miss"step "17z51. all metaharness scripts produce parseable JSON in --format json mode (iter 88)"@@ -1130,8 +1142,9 @@ step "17z36. CLI subcommand list current + mint anti-MCP guard (iter 73)"miss=""DISP="$ROOT/../../v3/@claude-flow/cli/src/commands/metaharness.ts"WRAPPER="$ROOT/../../v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts"-# iter-73 description string lists all 10 dispatchable subcommands-for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend similarity drift-from-history mint; do+# All 13 dispatchable subcommands present (iter-73 had 10; @metaharness/redblue+# added redblue.mjs; [email protected]/[email protected] added learn.mjs + gepa.mjs).+for sub in score genome mcp-scan threat-model oia-audit audit-list audit-trend similarity drift-from-history mint redblue learn gepa; dogrep -q "${sub}" "$DISP" 2>/dev/null || miss="$miss subcommand-${sub}-not-listed"done# ANTI-MINT GUARD: mint is intentionally CLI-only per ADR-150 Β§Sandboxing@@ -1618,9 +1631,12 @@ step "17z9. MCP success-semantic footnote + audit_trend file inputs (iter 46)"miss=""WRAPPER="$ROOT/../../v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts"# Success-semantic constant declared + appended to N descriptions = N+1 occurrences.-# Iter 46 set this at 9 (8 tools); iter 54 added the 9th tool β expect 10.+# Iter 46 set this at 9 (8 tools); iter 54 added the 9th β 10. ADR-153+# added 3 more tools (bench/evolve/security_bench) β 1 + 12 = 13.+# @metaharness/redblue integration added 1 more β 1 + 13 = 14.+# learn + gepa ([email protected] / [email protected]) added 2 more β 1 + 15 = 16.COUNT=$(grep -c "MCP_SUCCESS_SEMANTIC" "$WRAPPER" 2>/dev/null; true)-[[ "$COUNT" == "10" ]] || miss="$miss footnote-count:$COUNT-expected-10"+[[ "$COUNT" == "16" ]] || miss="$miss footnote-count:$COUNT-expected-16"# audit_trend now exposes baselineFile / currentFilegrep -q "baselineFile" "$WRAPPER" 2>/dev/null || miss="$miss no-baseline-file"grep -q "currentFile" "$WRAPPER" 2>/dev/null || miss="$miss no-current-file"@@ -1658,8 +1674,10 @@ grep -q "success = exitCode === 0" "$WRAPPER" 2>/dev/null || miss="$miss no-exitCOUNT_OLD=$(grep -c "success: !r.degraded" "$WRAPPER" 2>/dev/null; true)[[ "$COUNT_OLD" == "0" ]] || miss="$miss old-pattern-still-present:$COUNT_OLD"COUNT_NEW=$(grep -c "success: r.success" "$WRAPPER" 2>/dev/null; true)-# Iter 54 added a 9th tool. Future iters that add tools should bump this.-[[ "$COUNT_NEW" == "9" ]] || miss="$miss new-pattern-count:$COUNT_NEW-expected-9"+# Iter 54 added a 9th tool β 9. ADR-153 added 3 more (bench, evolve,+# security_bench) β 12. @metaharness/redblue integration added 1 more β 13.+# learn + gepa added 2 more β 15. Future iters that add tools should bump this.+[[ "$COUNT_NEW" == "15" ]] || miss="$miss new-pattern-count:$COUNT_NEW-expected-15"# Runtime anchors: iter 44 success assertions presentT="$ROOT/scripts/test-mcp-tools.mjs"grep -q "iter 44 fix" "$T" 2>/dev/null || miss="$miss no-iter44-anchors"@@ -2017,12 +2035,15 @@ grep -q "result has 'success'" "$F" || miss="$miss no-success-assertion"grep -q "result has 'data'" "$F" || miss="$miss no-data-assertion"grep -q "result has 'degraded'" "$F" || miss="$miss no-degraded-assertion"grep -q "result has 'exitCode'" "$F" || miss="$miss no-exitcode-assertion"-# All 9 tool names enumerated (similarity iter 36, drift_from_history iter 54)-for tool in metaharness_score metaharness_genome metaharness_mcp_scan metaharness_threat_model metaharness_oia_audit metaharness_audit_list metaharness_audit_trend metaharness_similarity metaharness_drift_from_history; do+# All 15 tool names enumerated (similarity iter 36, drift_from_history iter 54,+# ADR-153 added bench/evolve/security_bench, @metaharness/redblue added redblue,+# [email protected]/[email protected] added learn + gepa)+for tool in metaharness_score metaharness_genome metaharness_mcp_scan metaharness_threat_model metaharness_oia_audit metaharness_audit_list metaharness_audit_trend metaharness_similarity metaharness_drift_from_history metaharness_bench metaharness_evolve metaharness_security_bench metaharness_redblue metaharness_learn metaharness_gepa; dogrep -q "${tool}" "$F" || miss="$miss missing-${tool}"done-# Count assertion must match iter-54 expansion (8 β 9)-grep -q "tools.length === 9" "$F" || miss="$miss tool-count-assertion-stale"+# Count assertion must match iter-54 (8 β 9), then ADR-153 (9 β 12), then+# redblue (12 β 13), then learn/gepa (13 β 15)+grep -q "tools.length === 15" "$F" || miss="$miss tool-count-assertion-stale"# Graceful skip when dist absent (so the script is smoke-runnable pre-build)grep -q "SKIPPED" "$F" || miss="$miss no-skip-doc"[[ -z "$miss" ]] && ok || bad "$miss"diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjsindex 44aa474c79..c6db600fef 100755--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs@@ -74,7 +74,7 @@ async function main() {// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββconsole.log('Phase 1 β module shape');assert(Array.isArray(tools), 'metaharnessTools is an array');- assert(tools.length === 9, `9 tools registered (got ${tools.length})`);+ assert(tools.length === 15, `15 tools registered (got ${tools.length})`);const expectedNames = new Set(['metaharness_score',@@ -88,6 +88,16 @@ async function main() {'metaharness_similarity',// iter 54 β one-command drift detection (composes audit-list + oia-audit + audit-trend)'metaharness_drift_from_history',+ // ADR-153 β bench suites + evolve driver + security-focused bench+ 'metaharness_bench',+ 'metaharness_evolve',+ 'metaharness_security_bench',+ // @metaharness/redblue@~0.1.4 β adversarial red/blue LLM testing+ 'metaharness_redblue',+ // [email protected] β upstream ADR-235 GEPA learning run+ 'metaharness_learn',+ // @metaharness/[email protected] β GEPA library surface (genome ops)+ 'metaharness_gepa',]);const actualNames = new Set(tools.map((t) => t.name));for (const name of expectedNames) {@@ -141,6 +151,22 @@ async function main() {// test doesn't pollute namespaces.input = { dryRun: true };}+ if (tool.name === 'metaharness_redblue') {+ // `attack` preview is the fastest path that exercises the upstream+ // binary without needing OPENROUTER_API_KEY or running any model+ // calls. Count=1 keeps cold-cache npx fetch the dominant cost.+ input = { subcommand: 'attack', family: 'prompt', count: 1 };+ }+ if (tool.name === 'metaharness_learn') {+ // No repo checkout in CI β structured {status:"checkout-required"}+ // exit-0 path. $0: without run=true upstream never spends anyway.+ input = {};+ }+ if (tool.name === 'metaharness_gepa') {+ // op is required; `genome` loads + validates the SHIPPED cand-6+ // genome β pure-local library call once darwin is cached.+ input = { op: 'genome' };+ }// iter 124 β 130 β timeouts have crept up as CI cold-cache npx// warmup costs got measured. Final budgets:@@ -153,7 +179,16 @@ async function main() {// ONNX). 180s gives 30x headroom over the local cost.const isChainTool = tool.name === 'metaharness_drift_from_history'|| tool.name === 'metaharness_oia_audit'- || tool.name === 'metaharness_audit_list';+ || tool.name === 'metaharness_audit_list'+ // redblue: `attack prompt --count 1` is preview-only (no model+ // calls) but the cold-cache `npx -y @metaharness/redblue@~0.1.4`+ // fetch can take 30-60s. 180s gives 3x headroom.+ || tool.name === 'metaharness_redblue'+ // learn: cold-cache `npx -y metaharness@latest` fetch dominates.+ // gepa: one-time `npm install --prefix ~/.ruflo/darwin-cache-*`+ // fallback install can take 30-60s on cold cache.+ || tool.name === 'metaharness_learn'+ || tool.name === 'metaharness_gepa';const timeoutMs = isChainTool ? 180_000 : 60_000;const handlerPromise = tool.handler(input);const timeoutPromise = new Promise((_, reject) =>@@ -428,7 +463,7 @@ async function main() {for (const f of failures) console.log(` - ${f}`);process.exit(1);}- console.log('\nβ All 9 MCP tools satisfy the runtime contract.');+ console.log('\nβ All 15 MCP tools satisfy the runtime contract.');}main().catch((e) => {diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.mdindex 37ede12de6..11c38c973f 100644--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md@@ -35,7 +35,7 @@ Implementation: [`scripts/evolve.mjs`](../../scripts/evolve.mjs).β€ 20, `--concurrency` β€ 8, sandbox/selection/mutator are known values).2. Without `--confirm`: print plan + exit 0 (mirrors `harness-mint` safetyconvention; defense in depth over the upstream `safety.ts` checks).-3. With `--confirm`: shell to `npx -y @metaharness/darwin@~0.3.1 metaharness-darwin evolve <repo> ...`+3. With `--confirm`: shell to `npx -y @metaharness/darwin@~0.8.0 metaharness-darwin evolve <repo> ...`via the shared `_darwin.mjs` async helper. Per-generation progress isforwarded to stderr; final champion JSON is captured from stdout.4. Compute timeout from `generations Γ children Γ per-variant` (per-variantdiff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.mdnew file mode 100644index 0000000000..7aa9771f28--- /dev/null+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md@@ -0,0 +1,65 @@+---+name: harness-gepa+description: Inspect and audit GEPA genomes via the `@metaharness/darwin/gepa` library entry (darwin 0.8.0) β load/validate a genome (default: the shipped cand-6 promotion), render the system prompt a genome compiles to, or classify failure modes in a run transcript. The `gepaOptimize` loop itself is library-only (bring your own evaluator) and not surfaced here β use `harness-evolve` for sandbox-scored evolution. Degrades gracefully when @metaharness/darwin is absent.+argument-hint: "--op genome|validate|render|analyze [--path <genome.json>] [--transcript <t.json>] [--alert-on-invalid]"+allowed-tools: Bash+---++Surfaces the GEPA (genetic-evolution prompt-adaptation) *library* exports+from `@metaharness/darwin/gepa`. Unlike the other skills in this plugin+there is no CLI binary behind this β the script dynamic-imports the library+(local resolution first, versioned cache install as fallback) and calls the+subprocess-safe subset.++## When to use++- **Adopting an evolved policy**: `--op render` shows the actual system+ prompt a genome compiles to β read THAT, not the raw JSON, before+ wiring a genome into a harness.+- **Auditing a promotion**: `--op genome` loads + validates the shipped+ cand-6 genome (first holdout-confirmed cheap-tier promotion; provenance+ ships in the package) or any genome file you point at.+- **CI gate on genome edits**: `--op validate --alert-on-invalid` exits 1+ on structural errors.+- **Debugging a bad run**: `--op analyze --transcript run.json` classifies+ failure modes (GEPA's failure-class taxonomy) from a transcript array.++## What is deliberately NOT here++`gepaOptimize` β the optimization loop takes an in-process+`evaluate(candidate)` callback ("bring your own evaluator") that cannot+cross a subprocess boundary. Two supported paths instead:++1. **Library consumers**: `import { gepaOptimize, loadCand6Genome } from '@metaharness/darwin/gepa'`+2. **Sandbox-scored evolution**: `harness-evolve` (darwin CLI `evolve`),+ which pairs GEPA with its own sandbox evaluators.++## Algorithm++Implementation: [`scripts/gepa.mjs`](../../scripts/gepa.mjs).++1. `import('@metaharness/darwin/gepa')`; on MODULE_NOT_FOUND fall back to a+ one-time `npm install --prefix ~/.ruflo/darwin-cache-0.8.0` and import+ the cached `dist/gepa/index.js` (versioned dir β pin bumps invalidate).+2. Dispatch `--op`:+ - `genome` β `loadGenome(fs, path)` or `loadCand6Genome()` + `validateGenome`+ - `validate` β `validateGenome(rawJson)` (raw parse so broken files reach+ the validator instead of throwing in the loader)+ - `render` β `buildSystemFromGenome(genome, ext?, glob?)`+ - `analyze` β `analyzeTranscript(entries)`+3. Emit one JSON object; exit 0 (or 1 under `--alert-on-invalid`, 2 on bad input).++## Examples++```bash+node scripts/gepa.mjs --op genome # cand-6 + validation+node scripts/gepa.mjs --op render | jq -r .system # what does cand-6 SAY?+node scripts/gepa.mjs --op validate --path my-genome.json --alert-on-invalid+node scripts/gepa.mjs --op analyze --transcript run.json+```++## Exit codes++- `0` β op completed (or degraded β darwin not installable)+- `1` β `--alert-on-invalid` and validation found errors+- `2` β config error (unknown op, missing/broken input file)diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-learn/SKILL.mdnew file mode 100644index 0000000000..5b15de7be7--- /dev/null+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md@@ -0,0 +1,63 @@+---+name: harness-learn+description: Run a GEPA learning cycle via `metaharness learn` (upstream ADR-235, [email protected]) β optimizes a harness genome against a SWE-bench-style slice manifest. $0 dry-run by default; `--run` is the explicit spend opt-in. Requires a metaharness repo checkout (`--repo` or $METAHARNESS_REPO) β without one it reports `checkout-required` with clone instructions. Degrades gracefully when metaharness is absent.+argument-hint: "--host <h> --model <m> --slice <manifest> [--repo <checkout>] [--run] [--alert-on-fail]"+allowed-tools: Bash+---++Surfaces `metaharness learn` β the upstream GEPA learning harness that+evolves harness policy genomes against a scored task corpus instead of+hand-editing prompts. Candidates are scored on held-out slices and only+measured winners promote (the shipped cand-6 genome is the first such+promotion: holdout gold 2/12 β 3/12, zero regressions).++## When to use++- A harness's policy prompt underperforms on a task family and you want a+ measured improvement loop rather than manual prompt iteration.+- Pricing a learning run before committing spend β the default dry-run+ resolves the slice manifest and reports cost without any model calls.+- After a learn run promotes a genome: pair with `harness-gepa --op render`+ to inspect what the promoted policy actually says.++## Preconditions (upstream design)++The learning harness (GEPA + SWE-bench + Docker) is too heavy for the npm+package, so `learn` needs a local clone:++```bash+git clone https://github.com/ruvnet/metaharness.git+node scripts/learn.mjs --repo ./metaharness --host claude-code --model haiku --slice slices/lite.json+```++Without a checkout the script emits `{status: "checkout-required"}` and+exits 0 β a precondition report, not an error (distinct from+`degraded: true`, which means the npm package itself is absent). The+managed-service path (gateway-side learn jobs, no checkout) is upstream's+ADR-235 follow-up and not available yet.++## Algorithm++Implementation: [`scripts/learn.mjs`](../../scripts/learn.mjs).++1. Validate `--repo` exists when given; export it as `$METAHARNESS_REPO`.+2. Shell to `npx -y metaharness@latest learn --host <h> --model <m> --slice <s> [--run]`+ via `_harness.mjs` (graceful degradation, hard timeout).+3. Default timeouts: 120s dry-run, 600s with `--run` β real runs on larger+ slices need an explicit `--timeout-ms` matched to slice size Γ model cost.+4. Detect the checkout-required message β structured payload, exit 0.+5. Parse the trailing JSON report when upstream emits one; otherwise return+ the raw report text under `rawReport`.++## Cost note++`--run` is the ONLY path that spends. Everything else β dry-run, checkout+probe, degraded path β is $0. The MCP tool (`metaharness_learn`) has a 120s+subprocess budget; run real learning cycles from a terminal via+`ruflo metaharness learn ... --run --timeout-ms <big>`.++## Exit codes++- `0` β report produced (or dry-run, checkout-required, degraded)+- `1` β `--alert-on-fail` and the learn run reported failure+- `2` β config error (bad `--repo` path)diff --git a/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.mdindex c6f34dde87..e00c1e0bb0 100644--- a/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md+++ b/v3/@claude-flow/cli/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md@@ -29,7 +29,7 @@ ground-truth set. Running this nightly gives us:Implementation: [`scripts/security-bench.mjs`](../../scripts/security-bench.mjs).-1. Shell to `npx -y @metaharness/darwin@~0.3.1 metaharness-darwin security bench --population N --cycles N [--seed S]`.+1. Shell to `npx -y @metaharness/darwin@~0.8.0 metaharness-darwin security bench --population N --cycles N [--seed S]`.2. Default timeout = `3s Γ 19 evaluations Γ population Γ cycles + 30s overhead`.At default `--population 2 --cycles 1` β 144s; at `--population 4 --cycles 3` β 12 min.3. Parse the markdown report β overall PASS/FAIL plus per-gatediff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.tsindex 4223aee3b8..5406ff67d1 100644--- a/v3/@claude-flow/cli/src/commands/metaharness.ts+++ b/v3/@claude-flow/cli/src/commands/metaharness.ts@@ -60,9 +60,15 @@ const SUBCOMMANDS: Record<string, string> = {// 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.1 β adversarial red/blue LLM testing+ // @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',};/**@@ -125,10 +131,10 @@ export const metaharnessCommand: Command = {options: [{name: 'subcommand',- // iter 73 β list reflects all 10 dispatchable subcommands (was+ // 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',+ description: 'One of: score | genome | mcp-scan | threat-model | oia-audit | audit-list | audit-trend | similarity | drift-from-history | mint | redblue | learn | gepa',type: 'string' as const,},],diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.tsindex d52bebb752..22ab5126c6 100644--- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts@@ -24,6 +24,13 @@** - metaharness_redblue red-team β judge β blue-patch β retest β report*+ * [email protected] + @metaharness/[email protected] add two more:+ *+ * - metaharness_learn upstream ADR-235 GEPA learning run ($0 dry-run+ * default; run=true to spend; needs repo checkout)+ * - metaharness_gepa GEPA library surface β genome load/validate/+ * render + transcript failure analysis+ ** Every tool resolves the corresponding plugin script* (`plugins/ruflo-metaharness/scripts/<X>.mjs`) via the same locator* the commands/metaharness.ts dispatcher uses, then spawns it with@@ -532,4 +539,74 @@ export const metaharnessTools: MCPTool[] = [return { success: r.success, data: r.json, degraded: r.degraded, exitCode: r.exitCode };},},+ // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ // [email protected] `learn` + @metaharness/[email protected] GEPA (2 tools).+ //+ // learn β upstream ADR-235 GEPA learning run. $0 dry-run by default;+ // spending requires the explicit `run: true` opt-in, forwarded as --run.+ // Requires a metaharness repo checkout (the learning harness is too heavy+ // for the npm package) β absent checkout returns a structured+ // {status: "checkout-required"} payload, distinct from degraded.+ //+ // gepa β the darwin GEPA *library* surface (genome load/validate/render,+ // transcript analysis). gepaOptimize itself is deliberately NOT exposed:+ // it takes an in-process evaluate() callback that cannot cross the+ // subprocess boundary; optimization runs live behind metaharness_evolve.+ // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ {+ name: 'metaharness_learn',+ description: 'ADR-235 (upstream) β GEPA learning run via `metaharness learn`: optimizes a harness genome against a SWE-bench-style slice manifest. $0 DRY-RUN BY DEFAULT β it resolves the slice and prices the run without model calls; pass run=true to actually spend (model calls + Docker sandboxes). Requires a local metaharness repo checkout (repo param or $METAHARNESS_REPO); without one the tool returns {status:"checkout-required"} with clone instructions β that is a precondition report, not an error. Use when you want the harness policy to LEARN from a task corpus rather than hand-editing prompts; manual prompt tweaking is wrong because GEPA scores candidates against held-out slices and only promotes measured winners. Long real runs exceed the 120s MCP subprocess budget β run those via `ruflo metaharness learn` in a terminal instead. ' + MCP_SUCCESS_SEMANTIC,+ category: 'metaharness',+ inputSchema: {+ type: 'object',+ properties: {+ host: { type: 'string', description: 'Target host harness (e.g. claude-code, codex, pi-dev, hermes)' },+ model: { type: 'string', description: 'Model to learn against (upstream model id)' },+ slice: { type: 'string', description: 'Path to a slice manifest JSON' },+ repo: { type: 'string', description: 'Path to a metaharness repo checkout (sets $METAHARNESS_REPO)' },+ run: { type: 'boolean', description: 'EXPLICIT SPEND OPT-IN β without this the run is a $0 dry-run', default: false },+ alertOnFail: { type: 'boolean', description: 'Exit 1 when the learn run reports failure', default: false },+ timeoutMs: { type: 'number', description: 'Subprocess hard timeout override' },+ },+ },+ handler: async (input) => {+ const args: string[] = [];+ if (input.host) args.push('--host', String(input.host));+ if (input.model) args.push('--model', String(input.model));+ if (input.slice) args.push('--slice', String(input.slice));+ if (input.repo) args.push('--repo', String(input.repo));+ if (input.run === true) args.push('--run');+ if (input.alertOnFail === true) args.push('--alert-on-fail');+ if (input.timeoutMs !== undefined) args.push('--timeout-ms', String(input.timeoutMs));+ const r = await runScript('learn.mjs', args);+ return { success: r.success, data: r.json, degraded: r.degraded, exitCode: r.exitCode };+ },+ },+ {+ name: 'metaharness_gepa',+ description: 'GEPA genome operations from the `@metaharness/darwin/gepa` library entry (darwin 0.8.0). op=genome loads + validates a genome (default: the shipped cand-6 β first holdout-confirmed cheap-tier policy promotion, provenance in the package); op=validate returns structural errors for a genome JSON; op=render compiles a genome to the system prompt it encodes (inspect what a policy actually says before adopting it); op=analyze classifies failure modes in a transcript JSON array. Use when adopting/auditing/debugging evolved harness policies β reading genome JSON by eye is wrong because the behavior lives in the rendered system prompt and the component interactions, not the raw fields. NOTE: gepaOptimize (bring-your-own-evaluator optimization) is library-only β import @metaharness/darwin/gepa directly, or use metaharness_evolve for sandbox-scored evolution. ' + MCP_SUCCESS_SEMANTIC,+ category: 'metaharness',+ inputSchema: {+ type: 'object',+ properties: {+ op: { type: 'string', enum: ['genome', 'validate', 'render', 'analyze'], description: 'genome = load + validate; validate = structural errors only; render = genome β system prompt; analyze = transcript failure classes' },+ path: { type: 'string', description: 'Genome JSON path (genome/validate/render; default: shipped cand-6)' },+ transcript: { type: 'string', description: 'Transcript JSON array path (required for op=analyze)' },+ ext: { type: 'string', description: 'render only β target file extension hint' },+ glob: { type: 'string', description: 'render only β target glob hint' },+ alertOnInvalid: { type: 'boolean', description: 'Exit 1 when validation finds errors (gate-style)', default: false },+ },+ required: ['op'],+ },+ handler: async (input) => {+ const args: string[] = ['--op', String(input.op)];+ if (input.path) args.push('--path', String(input.path));+ if (input.transcript) args.push('--transcript', String(input.transcript));+ if (input.ext) args.push('--ext', String(input.ext));+ if (input.glob) args.push('--glob', String(input.glob));+ if (input.alertOnInvalid === true) args.push('--alert-on-invalid');+ const r = await runScript('gepa.mjs', args);+ return { success: r.success, data: r.json, degraded: r.degraded, exitCode: r.exitCode };+ },+ },];