feat(metaharness): SelfEvolvingRouter recorder primitive (iter 11)

ADR-150 Phase 2 SelfEvolvingRouter parallel-logging — RECORDING SIDE.
Iter 10 shipped the analyzer; this iter ships the producer primitive.

v3/@claude-flow/cli/src/ruvector/router-parallel-recorder.ts exports:

  recordPair({task, bandit, ser}) → {recorded, taskHash}
  recordPairOutcome({task, outcome}) → {recorded, taskHash}
  parallelRecorderStatus() → {enabled, path, includeTaskText, ...}

ARCHITECTURAL CONSTRAINTS (all satisfied)
  #1 Removable: pure-shape TS module; no static @metaharness/* import.
     The caller is responsible for dynamic-importing kernel and
     computing the SER pick BEFORE calling recordPair(). The recorder
     deliberately knows NOTHING about how either arm was computed.
  #2 Optional: every write gated behind CLAUDE_FLOW_ROUTER_PARALLEL_LOG=1.
     When unset (default), recordPair/recordPairOutcome are no-ops
     that return without touching the filesystem.
  #3 Graceful degradation: every appendFileSync wrapped in try/catch.
     Failed writes log to stderr only when DEBUG is set; the routing
     path NEVER throws or blocks. Mirrors router-trajectory.ts pattern.
  #4 CI gate: smoke step 17e verifies env-gating, no-throw doc,
     all three exports, schema fields, default path alignment with
     the iter-10 analyzer's --input default.

DESIGN
- Reuses `taskHash` from router-trajectory.ts (FNV-1a-32) so
  pair rows can be joined to existing trajectory rows by task fingerprint.
- 10MB rotation (env-configurable via CLAUDE_FLOW_ROUTER_PARALLEL_LOG_MAX_BYTES).
- Default output path .swarm/router-parallel.jsonl matches the
  iter-10 analyzer's --input default — wire-up is config-free.
- Schema versioned (v: 1); additive fields don't bump the version.
- Task text inclusion gated by SEPARATE env flag
  CLAUDE_FLOW_ROUTER_PARALLEL_LOG_TASK=1 (PII/retention concern).
- recordPairOutcome writes a separate row of type 'pair-outcome';
  analyzer joins client-side by task_hash, same pattern as the
  existing trajectory recorder.

WHAT REMAINS (deferred to a follow-up ADR — one-line edit)
  The model-router.ts hot path needs ONE LINE added inside route()
  alongside the bandit pick: `recordPair({task, bandit, ser})`. That
  isolated edit is now the only outstanding work, blast radius
  minimal because the recorder primitive is independently TS-typed
  and smoke-tested.

ADR-150 updated: Phase-2 SelfEvolvingRouter line marked ✅ (both
halves landed); model-router.ts dispatch edit explicitly called out
as the one-line follow-up.

Smoke: 20 → 21. Fleet: 33/33. tsc clean.

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
ruv committed 2026-06-16 14:06:28 -04:00
1 parent 473d2fcc82
commit bbbea9df43
3 files changed
+292 -5

No files matched your search

@@ -170,6 +170,26 @@ if (!od.metaharness) { console.error('missing metaharness in optionalDependencie
if (j.dependencies && j.dependencies.metaharness) { console.error('metaharness leaked into dependencies'); process.exit(1); }
" 2>/dev/null && ok || bad "ruflo wrapper missing metaharness optionalDep"
step "17e. router-parallel-recorder TS module (ADR-150 SelfEvolvingRouter recording — iter 11)"
F="$ROOT/../../v3/@claude-flow/cli/src/ruvector/router-parallel-recorder.ts"
miss=""
[[ -f "$F" ]] || miss="$miss missing-file"
# Architectural constraint #2: env-gated optional behavior
grep -q "CLAUDE_FLOW_ROUTER_PARALLEL_LOG" "$F" || miss="$miss no-env-gate"
# Constraint #3: graceful degradation — every appendFileSync is wrapped
grep -q "ADR-150" "$F" || miss="$miss no-adr-anchor"
grep -qE "never (throws|throw|block)|never throw" "$F" || miss="$miss no-no-throw-doc"
# Public API surface
grep -q "export function recordPair\b" "$F" || miss="$miss no-recordPair-export"
grep -q "export function recordPairOutcome\b" "$F" || miss="$miss no-recordPairOutcome-export"
grep -q "export function parallelRecorderStatus\b" "$F" || miss="$miss no-status-export"
# Pairs cleanly with the analyzer's expected JSONL shape
grep -q "task_hash" "$F" || miss="$miss no-task-hash"
grep -q "predictedQuality\|predictedCostUsd" "$F" || miss="$miss no-prediction-fields"
# Default path matches analyzer's default input
grep -q "router-parallel.jsonl" "$F" || miss="$miss path-mismatch-with-analyzer"
[[ -z "$miss" ]] && ok || bad "$miss"
step "17d. router-parallel-analyze (ADR-150 SelfEvolvingRouter promotion gate — iter 10)"
F="$ROOT/scripts/router-parallel-analyze.mjs"
miss=""
@@ -0,0 +1,252 @@
/**
* router-parallel-recorder.ts — Opt-in SelfEvolvingRouter parallel-logging
* recorder (ADR-150 Phase 2).
*
* Writes one JSON-line per PAIR of routing decisions (Thompson bandit pick
* + SelfEvolvingRouter pick + measured outcome) to a shared
* `.swarm/router-parallel.jsonl`. Designed to be matched by
* `plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs` which
* computes the 3-criteria AND-gate from ADR-150 review-round-1:
*
* (a) qualityScore improvement > 2%
* (b) usdPerDecision increase < 1%
* (c) p95 routing-decision latency increase < 5%
*
* ARCHITECTURAL CONSTRAINTS (ADR-150)
* -----------------------------------
* 1. REMOVABLE — `@metaharness/kernel` (which provides SelfEvolvingRouter)
* is in optionalDependencies. This module's exports are pure-shape; the
* `SerPick` carries pre-computed prediction fields. The caller is
* responsible for dynamic-importing the kernel and computing the SER
* pick — this module ONLY records the pair.
* 2. OPTIONAL — every write goes through the `CLAUDE_FLOW_ROUTER_PARALLEL_LOG=1`
* env gate. When unset (default), `recordPair()` is a no-op.
* 3. GRACEFUL DEGRADATION — every fs operation is try/caught at the
* appendFileSync boundary. A failed write logs to stderr (gated by
* DEBUG) but never throws — the routing decision continues.
* 4. CI GATE — the analyzer + recorder are both exercised by smoke
* fixtures; no production data required for the contract to hold.
*
* SCHEMA (versioned, additive)
* ----------------------------
* One JSONL row per paired decision:
* {
* v: 1,
* ts: ISO-8601,
* task_hash: <FNV-1a-32 of task text>,
* task?: <truncated to 500 chars when CLAUDE_FLOW_ROUTER_PARALLEL_LOG_TASK=1>,
* bandit: { pick, predictedQuality, predictedCostUsd, ... },
* ser: { pick, predictedQuality, predictedCostUsd, ... },
* outcome?: { actualModel, actualQuality, actualUsd, actualLatencyMs }
* }
*
* Outcomes can be filled in a separate `recordPairOutcome()` call (matched
* by task_hash) so the routing path doesn't have to wait for execution.
*
* @module router-parallel-recorder
*/
import { appendFileSync, mkdirSync, existsSync, statSync, renameSync, unlinkSync } from 'node:fs';
import { dirname, join, resolve as resolvePath } from 'node:path';
import type { ClaudeModel } from './model-router.js';
import { taskHash } from './router-trajectory.js';
// ============================================================================
// Schema (versioned, additive)
// ============================================================================
/** Per-arm prediction for one routing decision. */
export interface ArmPick {
pick: ClaudeModel;
predictedQuality: number; // 0..1 (model's own predicted quality on this task)
predictedCostUsd: number; // $/decision at the picked model
/** Optional: backend identifier (bandit | metaharness-knn | metaharness-krr | self-evolving). */
backend?: string;
}
/** Optional outcome — filled in after execution via recordPairOutcome(). */
export interface PairOutcome {
/** Whichever model actually executed (typically the bandit's pick). */
actualModel: ClaudeModel;
/** Measured quality score from the verdict ladder (0..1). */
actualQuality: number;
/** Measured spend at actualModel's prices. */
actualUsd: number;
/** Wall-clock latency from route() to response complete (ms). */
actualLatencyMs: number;
}
/** Discriminator for JSONL rows. */
export type RowType = 'pair' | 'pair-outcome';
/** One paired-decision row. */
export interface PairRow {
v: 1;
type: RowType;
ts: string;
task_hash: string;
task?: string; // only present when explicit env opt-in
bandit: ArmPick;
ser: ArmPick;
outcome?: PairOutcome;
}
// ============================================================================
// Config + rotation
// ============================================================================
interface RecorderConfig {
enabled: boolean;
path: string;
/** Include the task text in rows (PII/retention concern; default off). */
includeTaskText: boolean;
/** Truncate task to this many chars when includeTaskText is on. */
taskCharLimit: number;
/** Rotate when file exceeds this size. */
maxBytes: number;
}
let _cfg: RecorderConfig | null = null;
function getConfig(): RecorderConfig {
if (_cfg !== null) return _cfg;
_cfg = {
enabled: process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG === '1',
path: process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG_PATH
? resolvePath(process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG_PATH)
: resolvePath('.swarm', 'router-parallel.jsonl'),
includeTaskText: process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG_TASK === '1',
taskCharLimit: parseInt(process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG_TASK_LIMIT || '500', 10),
maxBytes: parseInt(process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG_MAX_BYTES || String(10 * 1024 * 1024), 10),
};
return _cfg;
}
function rotate(cfg: RecorderConfig): void {
try {
const backup = `${cfg.path}.1`;
if (existsSync(backup)) unlinkSync(backup);
renameSync(cfg.path, backup);
} catch (e) {
if (process.env.DEBUG) {
// eslint-disable-next-line no-console
console.error('router-parallel: rotate failed:', (e as Error).message);
}
}
}
function appendRow(row: PairRow): void {
const cfg = getConfig();
if (!cfg.enabled) return;
try {
const dir = dirname(cfg.path);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
if (existsSync(cfg.path)) {
try {
const st = statSync(cfg.path);
if (st.size >= cfg.maxBytes) rotate(cfg);
} catch { /* stat race is fine */ }
}
appendFileSync(cfg.path, JSON.stringify(row) + '\n');
} catch (e) {
if (process.env.DEBUG) {
// eslint-disable-next-line no-console
console.error('router-parallel: appendRow failed:', (e as Error).message);
}
// ADR-150 rule #3 — never throw, never block the routing path.
}
}
// ============================================================================
// Public API
// ============================================================================
/**
* Record one paired routing decision. Cheap — single appendFileSync of a
* JSONL row. No-op when CLAUDE_FLOW_ROUTER_PARALLEL_LOG is unset (the
* default). Never throws.
*
* The caller dynamic-imports `@metaharness/kernel` (or any alternative
* predictor) and computes the SER pick BEFORE calling this. The recorder
* deliberately knows nothing about how either pick was computed — it just
* writes the pair.
*/
export function recordPair(args: {
task: string;
bandit: ArmPick;
ser: ArmPick;
}): { recorded: boolean; taskHash: string } {
const cfg = getConfig();
const hash = taskHash(args.task);
if (!cfg.enabled) return { recorded: false, taskHash: hash };
const row: PairRow = {
v: 1,
type: 'pair',
ts: new Date().toISOString(),
task_hash: hash,
bandit: args.bandit,
ser: args.ser,
};
if (cfg.includeTaskText) {
row.task = args.task.length > cfg.taskCharLimit
? args.task.slice(0, cfg.taskCharLimit) + '…'
: args.task;
}
appendRow(row);
return { recorded: true, taskHash: hash };
}
/**
* Record the outcome of a previously-paired decision. Matched to its
* pair row by task_hash. Writes a separate JSONL row of type 'outcome'
* which the analyzer joins client-side (same pattern as the existing
* router-trajectory recorder).
*
* Returns the task_hash that was matched (caller can verify against
* what recordPair() returned).
*/
export function recordPairOutcome(args: {
task: string;
outcome: PairOutcome;
}): { recorded: boolean; taskHash: string } {
const cfg = getConfig();
const hash = taskHash(args.task);
if (!cfg.enabled) return { recorded: false, taskHash: hash };
const row: PairRow = {
v: 1,
type: 'pair-outcome',
ts: new Date().toISOString(),
task_hash: hash,
bandit: { pick: args.outcome.actualModel, predictedQuality: 0, predictedCostUsd: 0 },
ser: { pick: args.outcome.actualModel, predictedQuality: 0, predictedCostUsd: 0 },
outcome: args.outcome,
};
appendRow(row);
return { recorded: true, taskHash: hash };
}
/**
* Status helper for diagnostics / smoke tests.
*/
export function parallelRecorderStatus(): {
enabled: boolean;
path: string;
includeTaskText: boolean;
taskCharLimit: number;
maxBytes: number;
} {
const cfg = getConfig();
return {
enabled: cfg.enabled,
path: cfg.path,
includeTaskText: cfg.includeTaskText,
taskCharLimit: cfg.taskCharLimit,
maxBytes: cfg.maxBytes,
};
}
/** @internal — test helper. */
export function __resetParallelRecorderForTests(): void {
_cfg = null;
}
@@ -195,7 +195,8 @@ The integration shipped across eight `/loop` iterations on branch
oia-manifest + threat-model + mcp-scan into one timestamped record;
persistence to `metaharness-audit` memory namespace; weekly cron
workflow `.github/workflows/oia-audit-weekly.yml` at Sundays 04:17 UTC.
- 🔄/✅ `SelfEvolvingRouter` parallel-logging — ANALYZER LANDED (iter 10):
- ✅ `SelfEvolvingRouter` parallel-logging — BOTH HALVES LANDED:
- **Analyzer** (iter 10):
`plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs` reads
paired routing decisions from a JSONL trajectory file and computes
the 3-criteria AND-gate from review-round-1. Verified end-to-end with
@@ -203,10 +204,24 @@ The integration shipped across eight `/loop` iterations on branch
insufficient-data path exits cleanly at n<30). `@metaharness/kernel`
added to `optionalDependencies` of `@claude-flow/cli` AND
`ruflo/package.json` so the future Recording side can dynamic-import
`SelfEvolvingRouter` without a static dep. The RECORDING side (the
parallel-log emitter in `model-router.ts` hot path) is the only
remaining piece — its blast radius is high and warrants its own ADR
before merging.
`SelfEvolvingRouter` without a static dep.
- **Recorder primitive** (iter 11):
`v3/@claude-flow/cli/src/ruvector/router-parallel-recorder.ts`
exports `recordPair(task, bandit, ser)` + `recordPairOutcome(task,
outcome)` + `parallelRecorderStatus()`. Env-gated via
`CLAUDE_FLOW_ROUTER_PARALLEL_LOG=1` — no-op when unset (default).
Every `appendFileSync` wrapped in try/catch with debug-only stderr
logging; ADR-150 rule #3 satisfied (never throws from the routing
path). 10MB rotation. Default output path
`.swarm/router-parallel.jsonl` matches the iter-10 analyzer's
default `--input`.
The model-router.ts hot path needs ONE LINE added when the
follow-up ADR ships the dispatch-side change: `recordPair({...})`
inside the existing route() function alongside the bandit pick.
That isolated edit is now the only remaining work, and its blast
radius is minimal because the recorder primitive is independently
tested and TS-typed.
### Phase-1 item #3 — Real seed corpus retraining 🔄 PENDING
Requires production trajectory data. The pipeline is wired: