π 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): ADR-152 Β§3.1 production β _similarity.mjs + skill + MCP tool + dispatcher (iter 36)
ruv0b6ac8ff906f
diff --git a/plugins/ruflo-metaharness/scripts/_similarity.mjs b/plugins/ruflo-metaharness/scripts/_similarity.mjsnew file mode 100644index 0000000000..f92469b63d--- /dev/null+++ b/plugins/ruflo-metaharness/scripts/_similarity.mjs@@ -0,0 +1,161 @@+// _similarity.mjs β ADR-152 production similarity module.+//+// Graduated from `_spike-similarity.mjs` (iter 35) after both invariants+// passed on the LEGAL/SUPPORT/DEVOPS fixtures. The spike file STAYS as+// the regression-suite anchor; this file is what production callers+// (`similarity.mjs` skill, `metaharness_similarity` MCP tool) import.+//+// ADR-150 ARCHITECTURAL CONSTRAINTS PRESERVED+// Removable β pure-TS β no `@metaharness/*` import path+// Optional β no new dep on `@metaharness/*`+// Graceful β malformed input β low-confidence output, never throws+// CI-gate β standalone unit-importable; no `npx` needed+//+// CONTRACT (PUBLIC)+// projectToVec(input) β 9-dim numerical feature vector+// cosine(a, b) β [0,1]+// categoricalAgreement(a, b) β [0,1] over 4 enum fields+// jaccard(a, b) β [0,1] over agent_topology[]+// similarity(a, b, opts?) β { overall, components, perDimension? }+//+// WEIGHT DEFAULTS (from ADR-152 Β§Decision)+// overall = 0.60Β·cosine + 0.25Β·categorical + 0.15Β·jaccard+//+// ADR-152 reserves a future per-org weight override; for Β§3.1 the defaults+// are global. The opts.weights hook is here so consumers can experiment+// without forking the module β it is NOT a stable public API.++const DEFAULT_WEIGHTS = Object.freeze({ cosine: 0.6, categorical: 0.25, jaccard: 0.15 });++const CATEGORICAL_FIELDS = Object.freeze(['repo_type', 'archetype', 'template', 'recommendedMode']);++// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+// 9-dim feature vector. The mapping mirrors ADR-152 Β§Decision Table 1.+// Missing fields default to 0 β that's the graceful-degradation path.+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export function projectToVec(input) {+ const s = input?.score ?? {};+ const g = input?.genome ?? {};+ return [+ (s.harnessFit ?? 0) / 100,+ (s.compileConfidence ?? 0) / 100,+ (s.taskCoverage ?? 0) / 100,+ (s.toolSafety ?? 0) / 100,+ (s.memoryUsefulness ?? 0) / 100,+ g.risk_score ?? 0,+ g.test_confidence ?? 0,+ g.publish_readiness ?? 0,+ Math.max(0, Math.min(1, Math.log10((s.estCostPerRunUsd ?? 0) + 0.001) / Math.log10(10))),+ ];+}++export function cosine(a, b) {+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return 0;+ let dot = 0, na = 0, nb = 0;+ for (let i = 0; i < a.length; i++) {+ dot += a[i] * b[i];+ na += a[i] * a[i];+ nb += b[i] * b[i];+ }+ const denom = Math.sqrt(na) * Math.sqrt(nb);+ if (denom === 0) return 0;+ return Math.max(0, Math.min(1, dot / denom));+}++export function categoricalAgreement(a, b) {+ let matches = 0;+ for (const f of CATEGORICAL_FIELDS) {+ const av = a?.genome?.[f] ?? a?.score?.[f];+ const bv = b?.genome?.[f] ?? b?.score?.[f];+ if (av && bv && av === bv) matches++;+ }+ return matches / CATEGORICAL_FIELDS.length;+}++export function jaccard(a, b) {+ const A = new Set(a?.genome?.agent_topology ?? []);+ const B = new Set(b?.genome?.agent_topology ?? []);+ if (A.size === 0 && B.size === 0) return 1;+ const intersection = [...A].filter((x) => B.has(x)).length;+ const union = new Set([...A, ...B]).size;+ return union === 0 ? 0 : intersection / union;+}++// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+// Composite similarity with optional per-dimension breakdown.+// Returns the ADR-152 Β§"return shape": overall + components + per-dim.+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export function similarity(a, b, opts = {}) {+ const weights = { ...DEFAULT_WEIGHTS, ...(opts.weights ?? {}) };+ const va = projectToVec(a);+ const vb = projectToVec(b);+ const cos = cosine(va, vb);+ const cat = categoricalAgreement(a, b);+ const jac = jaccard(a, b);++ const overall = weights.cosine * cos + weights.categorical * cat + weights.jaccard * jac;++ const result = {+ overall: round4(overall),+ components: {+ cosine: round4(cos),+ categorical: round4(cat),+ jaccard: round4(jac),+ },+ weights,+ };++ if (opts.perDimension) {+ result.perDimension = perDimensionBreakdown(a, b, va, vb, weights);+ }+ return result;+}++function round4(x) {+ return Math.round(x * 10000) / 10000;+}++function perDimensionBreakdown(a, b, va, vb, weights) {+ // Per-dimension contribution = squared-error-normalized cosine slice + categorical/jaccard direct.+ // We surface raw a/b values + a contribution sign so callers can explain+ // why two harnesses scored as they did (used by Recommendation Engine+ // Β§3.2 confidence calc + Drift Detection Β§3.3 alert reason).+ const out = {};++ const numericKeys = [+ ['harnessFit', 'score', 100], ['compileConfidence', 'score', 100],+ ['taskCoverage', 'score', 100], ['toolSafety', 'score', 100],+ ['memoryUsefulness', 'score', 100],+ ['risk_score', 'genome', 1], ['test_confidence', 'genome', 1],+ ['publish_readiness', 'genome', 1],+ ['estCostPerRunUsd', 'score', 1],+ ];+ for (let i = 0; i < numericKeys.length; i++) {+ const [k, src] = numericKeys[i];+ const av = a?.[src]?.[k];+ const bv = b?.[src]?.[k];+ out[`numeric.${k}`] = {+ a: av ?? null, b: bv ?? null,+ contribution: round4(va[i] * vb[i] * weights.cosine / 9),+ };+ }+ for (const f of CATEGORICAL_FIELDS) {+ const av = a?.genome?.[f] ?? a?.score?.[f];+ const bv = b?.genome?.[f] ?? b?.score?.[f];+ out[`categorical.${f}`] = {+ a: av ?? null, b: bv ?? null,+ contribution: av && bv && av === bv ? round4(weights.categorical / 4) : 0,+ };+ }+ const A = new Set(a?.genome?.agent_topology ?? []);+ const B = new Set(b?.genome?.agent_topology ?? []);+ const overlap = [...A].filter((x) => B.has(x));+ const union = new Set([...A, ...B]);+ out['set.agent_topology'] = {+ a: [...A], b: [...B],+ contribution: union.size === 0 ? 0 : round4((overlap.length / union.size) * weights.jaccard),+ };+ return out;+}diff --git a/plugins/ruflo-metaharness/scripts/similarity.mjs b/plugins/ruflo-metaharness/scripts/similarity.mjsnew file mode 100755index 0000000000..5ace960046--- /dev/null+++ b/plugins/ruflo-metaharness/scripts/similarity.mjs@@ -0,0 +1,158 @@+#!/usr/bin/env node+// similarity.mjs β ADR-152 Β§3.1 CLI skill.+//+// Computes weighted similarity between two harness fingerprints (genome+// + score JSON). Production-grade companion to _spike-similarity.mjs.+//+// USAGE+// node scripts/similarity.mjs --a a.json --b b.json+// node scripts/similarity.mjs --a-key harness-X --b-key harness-Y # memory lookup+// node scripts/similarity.mjs --a a.json --b b.json --per-dimension # breakdown+// node scripts/similarity.mjs --a a.json --b b.json --format json+// node scripts/similarity.mjs --a a.json --b b.json --alert-below 0.5 # exit 1 if low+//+// EXIT CODES+// 0 ok (or overall β₯ alert-below threshold)+// 1 --alert-below AND overall < threshold+// 2 config / input error (missing args, file not found, malformed JSON)+//+// ADR-150 ARCHITECTURAL CONSTRAINTS PRESERVED+// - Pure-TS function (`_similarity.mjs`), no `@metaharness/*` import+// - No new dep; uses node:fs + node:child_process only for memory lookup+// - Graceful degradation: missing keys / malformed JSON β exit 2 with+// a structured `{ degraded: true, reason: ... }` payload on stdout+// - CI-gate ready: smoke step 17y locks this contract++import { readFileSync, existsSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { similarity } from './_similarity.mjs';++const NS = process.env.HARNESS_SIMILARITY_NAMESPACE || 'metaharness-audit';+const CLI_PKG = process.env.CLI_CORE === '1'+ ? '@claude-flow/cli-core@alpha'+ : '@claude-flow/cli@latest';++const ARGS = (() => {+ const a = {+ aFile: null, bFile: null,+ aKey: null, bKey: null,+ perDimension: false,+ format: 'table',+ alertBelow: null,+ };+ for (let i = 2; i < process.argv.length; i++) {+ const v = process.argv[i];+ if (v === '--a') a.aFile = process.argv[++i];+ else if (v === '--b') a.bFile = process.argv[++i];+ else if (v === '--a-key') a.aKey = process.argv[++i];+ else if (v === '--b-key') a.bKey = process.argv[++i];+ else if (v === '--per-dimension') a.perDimension = true;+ else if (v === '--format') a.format = process.argv[++i];+ else if (v === '--alert-below') a.alertBelow = Number(process.argv[++i]);+ }+ return a;+})();++function emitDegradedAndExit(reason, code = 2) {+ const payload = {+ degraded: true,+ reason,+ adr: 'ADR-152',+ skill: 'harness-similarity',+ generatedAt: new Date().toISOString(),+ };+ console.log(JSON.stringify(payload, null, 2));+ process.exit(code);+}++function memRetrieve(key) {+ const r = spawnSync('npx', [+ CLI_PKG, 'memory', 'retrieve',+ '--namespace', NS, '--key', key,+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });+ if (r.status !== 0) return null;+ const m = /\{[\s\S]*\}/.exec(r.stdout || '');+ if (!m) return null;+ try { return JSON.parse(m[0]); } catch { return null; }+}++function loadHarness(label, filePath, memKey) {+ if (filePath) {+ if (!existsSync(filePath)) emitDegradedAndExit(`${label}: file not found: ${filePath}`);+ try { return JSON.parse(readFileSync(filePath, 'utf-8')); }+ catch (e) { emitDegradedAndExit(`${label}: invalid JSON: ${e.message}`); }+ }+ if (memKey) {+ const rec = memRetrieve(memKey);+ if (!rec) emitDegradedAndExit(`${label}: key not found in namespace ${NS}: ${memKey}`);+ return rec;+ }+ emitDegradedAndExit(`${label}: --${label} or --${label}-key required`);+ return null; // unreachable; emitDegradedAndExit exits+}++function main() {+ if (!ARGS.aFile && !ARGS.aKey) emitDegradedAndExit('--a <file> or --a-key <memkey> required');+ if (!ARGS.bFile && !ARGS.bKey) emitDegradedAndExit('--b <file> or --b-key <memkey> required');++ const a = loadHarness('a', ARGS.aFile, ARGS.aKey);+ const b = loadHarness('b', ARGS.bFile, ARGS.bKey);++ const result = similarity(a, b, { perDimension: ARGS.perDimension });++ const payload = {+ adr: 'ADR-152',+ skill: 'harness-similarity',+ inputs: {+ a: ARGS.aFile ?? `mem:${ARGS.aKey}`,+ b: ARGS.bFile ?? `mem:${ARGS.bKey}`,+ },+ ...result,+ alert: ARGS.alertBelow != null ? {+ threshold: ARGS.alertBelow,+ triggered: result.overall < ARGS.alertBelow,+ reason: result.overall < ARGS.alertBelow+ ? `overall ${result.overall} < threshold ${ARGS.alertBelow}`+ : `overall ${result.overall} β₯ threshold ${ARGS.alertBelow}`,+ } : null,+ generatedAt: new Date().toISOString(),+ };++ if (ARGS.format === 'json') {+ console.log(JSON.stringify(payload, null, 2));+ } else {+ console.log(`# harness similarity (ADR-152)\n`);+ console.log(`Inputs:`);+ console.log(` a: ${payload.inputs.a}`);+ console.log(` b: ${payload.inputs.b}`);+ console.log('');+ console.log(`| Component | Score | Weight | Contribution |`);+ console.log(`|-------------|-------:|-------:|-------------:|`);+ const { weights, components } = payload;+ console.log(`| cosine | ${components.cosine.toFixed(4)} | ${weights.cosine} | ${(components.cosine * weights.cosine).toFixed(4)} |`);+ console.log(`| categorical | ${components.categorical.toFixed(4)} | ${weights.categorical} | ${(components.categorical * weights.categorical).toFixed(4)} |`);+ console.log(`| jaccard | ${components.jaccard.toFixed(4)} | ${weights.jaccard} | ${(components.jaccard * weights.jaccard).toFixed(4)} |`);+ console.log('');+ console.log(`**Overall:** ${payload.overall.toFixed(4)}`);+ if (payload.alert) {+ console.log('');+ console.log(payload.alert.triggered ? `β ALERT: ${payload.alert.reason}` : `β ${payload.alert.reason}`);+ }+ if (ARGS.perDimension && payload.perDimension) {+ console.log('');+ console.log('## Per-dimension breakdown');+ console.log('');+ console.log('| Dimension | a | b | contribution |');+ console.log('|---|---|---|---:|');+ for (const [k, v] of Object.entries(payload.perDimension)) {+ const av = Array.isArray(v.a) ? `[${v.a.join(',')}]` : String(v.a ?? '-');+ const bv = Array.isArray(v.b) ? `[${v.b.join(',')}]` : String(v.b ?? '-');+ console.log(`| ${k} | ${av} | ${bv} | ${Number(v.contribution).toFixed(4)} |`);+ }+ }+ }++ if (payload.alert?.triggered) process.exit(1);+}++main();diff --git a/plugins/ruflo-metaharness/scripts/smoke.sh b/plugins/ruflo-metaharness/scripts/smoke.shindex 1e0438e629..bf07f696b4 100755--- a/plugins/ruflo-metaharness/scripts/smoke.sh+++ b/plugins/ruflo-metaharness/scripts/smoke.sh@@ -191,6 +191,53 @@ grep -q "execCli(\[\s*'-y'\s*,\s*'metaharness@latest'" "$F" 2>/dev/null || \grep -q "cwd: opts" "$F" || miss="$miss no-cwd-passthrough"[[ -z "$miss" ]] && ok || bad "$miss"+step "17y. ADR-152 production β _similarity.mjs module + similarity.mjs skill + MCP tool + dispatcher (iter 36)"+miss=""+# Production module+MOD="$ROOT/scripts/_similarity.mjs"+[[ -f "$MOD" ]] || miss="$miss module-missing"+node --check "$MOD" 2>/dev/null || miss="$miss module-syntax-error"+grep -q "export function similarity" "$MOD" 2>/dev/null || miss="$miss no-export-similarity"+grep -q "export function projectToVec" "$MOD" 2>/dev/null || miss="$miss no-export-projectToVec"+grep -q "export function cosine" "$MOD" 2>/dev/null || miss="$miss no-export-cosine"+grep -q "DEFAULT_WEIGHTS" "$MOD" 2>/dev/null || miss="$miss no-default-weights"+grep -q "cosine: 0.6" "$MOD" 2>/dev/null || miss="$miss weight-cosine-drift"+grep -q "categorical: 0.25" "$MOD" 2>/dev/null || miss="$miss weight-categorical-drift"+grep -q "jaccard: 0.15" "$MOD" 2>/dev/null || miss="$miss weight-jaccard-drift"+# CLI skill+SKL="$ROOT/scripts/similarity.mjs"+[[ -x "$SKL" ]] || miss="$miss skill-not-executable"+node --check "$SKL" 2>/dev/null || miss="$miss skill-syntax-error"+grep -q "from './_similarity.mjs'" "$SKL" 2>/dev/null || miss="$miss skill-not-using-module"+grep -q -- "--per-dimension" "$SKL" 2>/dev/null || miss="$miss no-per-dimension-flag"+grep -q -- "--alert-below" "$SKL" 2>/dev/null || miss="$miss no-alert-below-flag"+# SKILL.md+SK="$ROOT/skills/harness-similarity/SKILL.md"+[[ -f "$SK" ]] || miss="$miss skill-md-missing"+grep -q "^name: harness-similarity" "$SK" 2>/dev/null || miss="$miss skill-md-name-wrong"+grep -q "^allowed-tools:" "$SK" 2>/dev/null || miss="$miss skill-md-no-allowed-tools"+# Dispatcher+DISP="$ROOT/../../v3/@claude-flow/cli/src/commands/metaharness.ts"+grep -q "similarity: 'similarity.mjs'" "$DISP" 2>/dev/null || miss="$miss no-dispatcher-entry"+# MCP tool registered+MCP="$ROOT/../../v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts"+grep -q "name: 'metaharness_similarity'" "$MCP" 2>/dev/null || miss="$miss no-mcp-tool"+# Smoke-runtime sanity: production module reproduces spike LEGALΓSUPPORT score+TMPA=$(mktemp); TMPB=$(mktemp)+cat > "$TMPA" <<'JSON'+{"score":{"harnessFit":78,"compileConfidence":92,"taskCoverage":65,"toolSafety":88,"memoryUsefulness":70,"estCostPerRunUsd":0.04,"recommendedMode":"CLI + MCP","archetype":"compliance-harness","template":"vertical:legal"},"genome":{"repo_type":"node_mcp_ci","agent_topology":["contract-analyst","redline-reviewer","risk-rater","compliance-officer"],"risk_score":0.45,"test_confidence":0.7,"publish_readiness":0.6}}+JSON+cat > "$TMPB" <<'JSON'+{"score":{"harnessFit":75,"compileConfidence":90,"taskCoverage":70,"toolSafety":90,"memoryUsefulness":72,"estCostPerRunUsd":0.05,"recommendedMode":"CLI + MCP","archetype":"compliance-harness","template":"vertical:support"},"genome":{"repo_type":"node_mcp_ci","agent_topology":["triager","kb-searcher","responder","risk-rater","compliance-officer"],"risk_score":0.40,"test_confidence":0.75,"publish_readiness":0.65}}+JSON+OUT=$(node "$SKL" --a "$TMPA" --b "$TMPB" --format json 2>/dev/null | grep '"overall"' | head -1)+echo "$OUT" | grep -q "0.8296" || miss="$miss runtime-overall-mismatch:$OUT"+# Self-similarity check via the production module+SELF=$(node "$SKL" --a "$TMPA" --b "$TMPA" --format json 2>/dev/null | grep '"overall"' | head -1)+echo "$SELF" | grep -qE '"overall": 1[,]?$' || miss="$miss runtime-self-not-one:$SELF"+rm -f "$TMPA" "$TMPB"+[[ -z "$miss" ]] && ok || bad "$miss"+step "17x. ADR-152 spike β similarity invariants verified at structural level (iter 35)"F="$ROOT/scripts/_spike-similarity.mjs"miss=""diff --git a/plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md b/plugins/ruflo-metaharness/skills/harness-similarity/SKILL.mdnew file mode 100644index 0000000000..14a89ba0f4--- /dev/null+++ b/plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md@@ -0,0 +1,67 @@+---+name: harness-similarity+description: ADR-152 β weighted similarity between two harness fingerprints (genome + score JSON). Returns overall score in [0,1] plus per-component breakdown (cosine over 9 numerics, categorical agreement over 4 enums, jaccard over agent_topology). Unblocks ADR-151 Β§3.2 Recommender, Β§3.3 Drift Detection, Β§3.5 Plugin Compat. Pure-TS, no `@metaharness/*` dep β preserves ADR-150's four architectural constraints.+argument-hint: "(--a a.json --b b.json | --a-key X --b-key Y) [--per-dimension] [--alert-below 0.5] [--format json|table]"+allowed-tools: Bash+---++Surfaces the production similarity function from [`scripts/_similarity.mjs`](../../scripts/_similarity.mjs) as a callable skill. Use when an agent needs to:++- decide whether to fork an existing harness vs scaffold a new one+- rank candidate templates against a target repo's genome+- diff two harnesses produced by different teams to find duplicate work+- generate the confidence number that ADR-151 Β§3.2's Recommender wraps++## Algorithm (from ADR-152 Β§Decision)++```+overall = 0.60Β·cosine + 0.25Β·categorical + 0.15Β·jaccard+```++- **cosine** β over a 9-dim numerical vector of normalized scorecard + genome dims+- **categorical** β fraction of 4 enum fields that match (`repo_type`, `archetype`, `template`, `recommendedMode`)+- **jaccard** β `|A β© B| / |A βͺ B|` over the `agent_topology[]` array++The 3-component design is load-bearing: numerical cosine alone is too coarse (the iter-35 spike showed LEGAL vs DEVOPS at cosine=0.97 despite being unrelated verticals). Categorical + jaccard pull the composite to the correct ordering.++## Reference outputs (iter-35 spike fixtures)++| Pair | overall | cosine | categorical | jaccard |+|---|---:|---:|---:|---:|+| `LEGAL` Γ `LEGAL` (self) | 1.0000 | 1.0000 | 1.0000 | 1.0000 |+| `LEGAL` Γ `SUPPORT` | 0.8296 | 0.9987 | 0.7500 | 0.2857 |+| `LEGAL` Γ `DEVOPS` | 0.5840 | 0.9734 | 0.0000 | 0.0000 |++Both invariants from ADR-152 Β§"Smallest demonstrable spike" hold:+1. `similarity(X, X) === 1` exactly+2. `similarity(LEGAL, DEVOPS) < similarity(LEGAL, SUPPORT)` (vertical affinity)++## Architectural constraint inheritance (ADR-150)++- **Removable** β pure-TS function, zero static `@metaharness/*` imports.+- **Optional** β no new dep in `package.json`.+- **Graceful** β malformed inputs emit `{ degraded: true, reason }` with exit code 2; never throws.+- **CI-gate** β smoke step 17y locks the contract: module exports, spike fixtures reproduce, CLI dispatcher entry registered, MCP tool registered.++## Usage++```bash+# File inputs+npx ruflo metaharness similarity --a a.json --b b.json++# Memory inputs (records persisted by oia-audit.mjs)+npx ruflo metaharness similarity --a-key harness-X --b-key harness-Y++# Per-dimension breakdown (used by ADR-151 Β§3.2 Recommender)+npx ruflo metaharness similarity --a a.json --b b.json --per-dimension++# Alert when too-dissimilar (used by ADR-151 Β§3.3 Drift Detection)+npx ruflo metaharness similarity --a a.json --b b.json --alert-below 0.5+```++## Implementation++Production module: [`scripts/_similarity.mjs`](../../scripts/_similarity.mjs)+CLI skill: [`scripts/similarity.mjs`](../../scripts/similarity.mjs)+MCP tool: `mcp__claude-flow__metaharness_similarity` (registered in `v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts`)+Spike anchor: [`scripts/_spike-similarity.mjs`](../../scripts/_spike-similarity.mjs) (regression suite β invariants locked here)diff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.tsindex ec546b38b7..e8add5ab19 100644--- a/v3/@claude-flow/cli/src/commands/metaharness.ts+++ b/v3/@claude-flow/cli/src/commands/metaharness.ts@@ -55,6 +55,8 @@ const SUBCOMMANDS: Record<string, string> = {'audit-trend': 'audit-trend.mjs',// iter 16 β enumerate metaharness-audit records'audit-list': 'audit-list.mjs',+ // iter 36 β ADR-152 Β§3.1 weighted similarity between two harness fingerprints+ similarity: 'similarity.mjs',mint: 'mint.mjs',};@@ -128,6 +130,7 @@ export const metaharnessCommand: Command = {output.writeln(' oia-audit composite weekly audit (oia + threat + mcp) β memory');output.writeln(' audit-list enumerate timestamped audit records');output.writeln(' audit-trend diff two audit records (drift detection)');+ output.writeln(' similarity ADR-152 β weighted similarity between two harness fingerprints');output.writeln(' mint scaffold a custom harness (dry-run by default)');output.writeln('');output.writeln('Each subcommand accepts --format json|table and --help.');diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.tsindex db60fa3300..061999fb3d 100644--- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts@@ -207,6 +207,33 @@ export const metaharnessTools: MCPTool[] = [return { success: !r.degraded, data: r.json, degraded: r.degraded, exitCode: r.exitCode };},},+ {+ name: 'metaharness_similarity',+ description: 'ADR-152 Β§3.1 β weighted similarity between two harness fingerprints (genome + score JSON). Returns overall β [0,1] plus per-component breakdown (cosine over 9 numerics, categorical over 4 enums, jaccard over agent_topology). Pure-TS, zero `@metaharness/*` dep. Use to (a) rank candidate templates against a target repo, (b) decide fork-vs-scaffold, (c) feed ADR-151 Β§3.2 Recommender / Β§3.3 Drift / Β§3.5 Plugin Compat.',+ category: 'metaharness',+ inputSchema: {+ type: 'object',+ properties: {+ aFile: { type: 'string', description: 'Path to harness A genome+score JSON file (mutually exclusive with aKey)' },+ bFile: { type: 'string', description: 'Path to harness B genome+score JSON file (mutually exclusive with bKey)' },+ aKey: { type: 'string', description: 'Memory key for harness A in `metaharness-audit` namespace (mutually exclusive with aFile)' },+ bKey: { type: 'string', description: 'Memory key for harness B in `metaharness-audit` namespace (mutually exclusive with bFile)' },+ perDimension: { type: 'boolean', description: 'Include per-dimension contribution breakdown (used by ADR-151 Β§3.2 Recommender)', default: false },+ alertBelow: { type: 'number', description: 'Set tool.alert.triggered when overall < N (used by ADR-151 Β§3.3 Drift Detection)' },+ },+ },+ handler: async (input) => {+ const args: string[] = [];+ if (input.aFile) args.push('--a', String(input.aFile));+ if (input.bFile) args.push('--b', String(input.bFile));+ if (input.aKey) args.push('--a-key', String(input.aKey));+ if (input.bKey) args.push('--b-key', String(input.bKey));+ if (input.perDimension === true) args.push('--per-dimension');+ if (input.alertBelow !== undefined) args.push('--alert-below', String(input.alertBelow));+ const r = await runScript('similarity.mjs', args);+ return { success: !r.degraded, data: r.json, degraded: r.degraded, exitCode: r.exitCode };+ },+ },{name: 'metaharness_audit_trend',description: 'ADR-150 iter 15 β diff two oia-audit records (drift detection). Pulls baseline + current snapshots from the `metaharness-audit` memory namespace and surfaces composite worst-severity delta + per-component status change + introduced/cleared findings.',