From 0b6ac8ff906fa929bc71b13dabe4b1f24da020bb Mon Sep 17 00:00:00 2001 From: ruv Date: Tue, 16 Jun 2026 16:24:46 -0400 Subject: [PATCH] =?UTF-8?q?feat(metaharness):=20ADR-152=20=C2=A73.1=20prod?= =?UTF-8?q?uction=20=E2=80=94=20=5Fsimilarity.mjs=20+=20skill=20+=20MCP=20?= =?UTF-8?q?tool=20+=20dispatcher=20(iter=2036)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Graduates the iter-35 spike into the three production surfaces ADR-152 §"Implementation surface" enumerates. ADR-151 §3.2 / §3.3 / §3.5 are now unblocked at the dependency layer — they can import similarity() directly instead of stub-coding their own. WHAT SHIPPED 1. plugins/ruflo-metaharness/scripts/_similarity.mjs (PRODUCTION MODULE) - Exports: projectToVec, cosine, categoricalAgreement, jaccard, similarity - DEFAULT_WEIGHTS frozen at 0.60 / 0.25 / 0.15 (ADR-152 §Decision) - opts.perDimension → full attribution breakdown (numeric/categorical/set) - opts.weights → experimental override (not stable public API yet) - Pure-TS, zero deps, no `@metaharness/*` import 2. plugins/ruflo-metaharness/scripts/similarity.mjs (CLI SKILL) - Accepts --a/--b files OR --a-key/--b-key memory lookups (mem path uses CLI_CORE=1 env to swap cli-core@alpha vs cli@latest) - --per-dimension surfaces the attribution table (feeds Recommender §3.2) - --alert-below N triggers exit 1 (feeds Drift Detection §3.3) - --format json|table (default table) - Graceful: missing args / missing files emit {degraded:true,reason}, never throws 3. plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md - Frontmatter: name/description/argument-hint/allowed-tools (audit-pass) - Reference output table mirrors iter-35 spike fixtures - Inheritance section quotes ADR-150's four constraints 4. v3/@claude-flow/cli/src/commands/metaharness.ts (DISPATCHER) - SUBCOMMANDS map: similarity → similarity.mjs - Help text lists the new subcommand 5. v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts (MCP TOOL) - metaharness_similarity registered (subprocess-bridged like its 7 siblings) - InputSchema: aFile/bFile/aKey/bKey + perDimension + alertBelow - Auto-registered in TOOL_REGISTRY via existing `...metaharnessTools` spread 6. plugins/ruflo-metaharness/scripts/smoke.sh (SMOKE STEP 17y) - Module: file exists, parses, exports the 5 names, weights literal match ADR-152 §Decision (0.6 / 0.25 / 0.15 — anti-drift guard) - Skill: executable, parses, imports from _similarity.mjs, has the --per-dimension + --alert-below flags - SKILL.md: name/allowed-tools present (frontmatter audit) - Dispatcher: similarity entry present - MCP tool: name literal present - RUNTIME assertion: invokes skill on LEGAL+SUPPORT fixtures and confirms overall=0.8296 (matches spike); confirms self=1.0000 CONTRACT REPRODUCIBILITY VERIFIED similarity(LEGAL, LEGAL).overall = 1 (self-match, both invariants) similarity(LEGAL, SUPPORT).overall = 0.8296 (matches iter-35 spike) Per-component (LEGAL × SUPPORT): cosine=0.9987 categorical=0.7500 jaccard=0.2857 ARCHITECTURAL CONSTRAINTS (all four preserved) 1. Removable ✓ pure-TS, no @metaharness/* import (verified by ts grep) 2. Optional ✓ no new package.json dep added 3. Graceful ✓ malformed-input path → {degraded:true,reason}, exit 2 4. CI-gate ✓ smoke 17y has its own runtime assertion; module is standalone-importable without npx (verified inline) GATES PASSED THIS ITER smoke: 40 → 41 (step 17y green) fleet: 33/33 contracts pass tsc: v3/@claude-flow/cli compiles clean (no new errors) import: dynamic import + .similarity() call from naked node works LIFECYCLE - spike `_spike-similarity.mjs` stays — that IS the regression suite anchor - production `_similarity.mjs` is what ADR-153 / ADR-154 / ADR-156 will import - when the per-org weight-override story is decided, a follow-up ADR will stabilize opts.weights as public API; for now it is experimental PHASE-3 STATUS - §3.1 Genome Similarity Search ⬛ PRODUCTION (this iter) - §3.2 Recommendation Engine ⬛ ADR-153 scope-locked, blocked on user - §3.3 Fleet Drift Detection ⬛ ADR-154 scope-locked, blocked on user - §3.4 Capability Graph ⬛ ADR-155 scope-locked, blocked on user - §3.5 Plugin Compatibility ⬛ ADR-156 scope-locked, blocked on user Co-Authored-By: RuFlo --- .../ruflo-metaharness/scripts/_similarity.mjs | 161 ++++++++++++++++++ .../ruflo-metaharness/scripts/similarity.mjs | 158 +++++++++++++++++ plugins/ruflo-metaharness/scripts/smoke.sh | 47 +++++ .../skills/harness-similarity/SKILL.md | 67 ++++++++ .../cli/src/commands/metaharness.ts | 3 + .../cli/src/mcp-tools/metaharness-tools.ts | 27 +++ 6 files changed, 463 insertions(+) create mode 100644 plugins/ruflo-metaharness/scripts/_similarity.mjs create mode 100755 plugins/ruflo-metaharness/scripts/similarity.mjs create mode 100644 plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md diff --git a/plugins/ruflo-metaharness/scripts/_similarity.mjs b/plugins/ruflo-metaharness/scripts/_similarity.mjs new file mode 100644 index 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.mjs new file mode 100755 index 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 or --a-key required'); + if (!ARGS.bFile && !ARGS.bKey) emitDegradedAndExit('--b or --b-key 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.sh index 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.md new file mode 100644 index 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.ts index 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 = { '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.ts index 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.',