mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-25 06:36:49 +09:00
feat(metaharness): drift-from-history — one-command drift detection (iter 53)
Composes audit-list + oia-audit + audit-trend into the workflow users
actually want: "did my repo drift since the last audit?" Until iter 53
this required three separate commands and manually picking a key from
audit-list output.
WHAT SHIPPED
1. plugins/ruflo-metaharness/scripts/drift-from-history.mjs
Algorithm:
1. audit-list.mjs --limit 50 [--since N] → discover history
2. Sort by startedAt, pick most recent record
3. oia-audit.mjs --path . → fresh audit
4. audit-trend.mjs --baseline-key X --current /tmp/curr.json
--alert-on-distance-below ${threshold} → diff + alert
Exit semantics (4 distinct codes for agent consumption):
0 similarity ≥ threshold — OK
1 similarity < threshold — drift alert fired
2 config error (no history, audit-list failed)
3 upstream metaharness absent — degraded payload returned
Flags:
--path # repo to audit (default: cwd)
--baseline-since 7d # use audit at least N days old
--threshold 0.95 # alert below this similarity
--dry-run # don't persist the fresh audit
--format json|table
2. plugins/ruflo-metaharness/skills/harness-drift-from-history/SKILL.md
- Frontmatter passes the iter-87 audit (name + description +
argument-hint + allowed-tools)
- Documents the before/after workflow comparison
- Architectural-constraint inheritance table
3. v3/@claude-flow/cli/src/commands/metaharness.ts
- SUBCOMMANDS: 'drift-from-history': 'drift-from-history.mjs'
- Help text lists the new subcommand
4. plugins/ruflo-metaharness/scripts/smoke.sh — step 17z16:
- drift-from-history.mjs is executable + parses
- Has --baseline-since / --threshold / --dry-run flags
- Composes all 3 sub-scripts (audit-list, oia-audit, audit-trend)
- SKILL.md + dispatcher entry + help line present
- Exit-semantic guards (process.exit(code), exit 2, exit 3)
VERIFIED END-TO-END
$ node v3/@claude-flow/cli/bin/cli.js metaharness drift-from-history \
--dry-run --format json | jq .alert
{
"threshold": 0.95,
"triggered": false,
"reason": "..."
}
verdict: near-identical
exit-ok: True
WHY THIS IS THE DEEP-INTEGRATION VALUE THE LOOP ASKED FOR
The dep (similarity) has been integrated 12 ways across iters 36-52
— module, MCP tool, CI gates, doctor, etc. But until iter 53, nothing
exposed the dep as a USEFUL one-command primitive. drift-from-history
is what an ops user actually types when they want answer to "did my
repo drift?" — composed from the same primitives but with the rough
edges (key discovery, file paths, threshold defaults) smoothed.
ITER 53 OUTPUT CONTRACT (excerpt)
{
"adr": "ADR-150 + ADR-152 §3.1",
"command": "drift-from-history",
"baseline": { "key": "audit-2026-06-16T22-58-47-840Z", "startedAt": "..." },
"current": { "startedAt": "...", "composite": {...} },
"drift": { ...delta.worst, structuralDistance, components, ... },
"alert": { "threshold": 0.95, "triggered": false, "reason": "..." }
}
GATES THIS ITER
smoke: 56 → 57 (step 17z16 green)
fleet: 33/33
tsc: clean rebuild of metaharness.ts dispatcher
UPSTREAM CONTRIBUTION ALSO LANDED THIS SESSION
- ruvnet/agent-harness-generator#15 — schema confusion between
harness vs metaharness CLIs (iter 47 discovery)
- ruvnet/agent-harness-generator#16 — harness mcp-scan emits
text instead of JSON; donates parseMcpScanText (iter 50 discovery)
Both are dep-integration optimizations sourced from ruflo's roundtrip
test catching real upstream issues.
Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
1 parent
f859d4d3db
commit
be1401d8ab
4 files changed
+291
No files matched your search
+199
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env node
|
||||
// drift-from-history.mjs — iter 53 — one-command drift detection.
|
||||
//
|
||||
// Composes the existing pipeline into the workflow users actually want:
|
||||
// "did my repo drift since the last audit?" Implementation:
|
||||
//
|
||||
// 1. List audit records from `metaharness-audit` memory namespace
|
||||
// 2. Pick the most recent one (or filter --since Nd to skip recent ones
|
||||
// and use an older baseline)
|
||||
// 3. Run a fresh oia-audit against the current repo state
|
||||
// 4. Diff via audit-trend → structural distance + severity rollup
|
||||
// 5. Alert if structural similarity falls below --threshold
|
||||
//
|
||||
// Until this iter, doing this required the user to:
|
||||
// $ npx ruflo metaharness audit-list --format json
|
||||
// $ # ... pick a key by hand from the listing
|
||||
// $ npx ruflo metaharness oia-audit --format json > /tmp/curr.json
|
||||
// $ npx ruflo metaharness audit-trend --baseline-key X --current-file /tmp/curr.json
|
||||
// Now it's:
|
||||
// $ npx ruflo metaharness drift-from-history --threshold 0.95
|
||||
//
|
||||
// USAGE
|
||||
// node scripts/drift-from-history.mjs # default: last record vs now
|
||||
// node scripts/drift-from-history.mjs --baseline-since 7d # use an audit ≥ 7d old
|
||||
// node scripts/drift-from-history.mjs --threshold 0.95 # alert under 0.95 similarity
|
||||
// node scripts/drift-from-history.mjs --format json
|
||||
// node scripts/drift-from-history.mjs --dry-run # don't persist current
|
||||
//
|
||||
// EXIT CODES
|
||||
// 0 ok (no drift below --threshold)
|
||||
// 1 drift below --threshold (alert fired)
|
||||
// 2 config / input error (no history available, etc.)
|
||||
// 3 upstream metaharness absent — degraded payload returned
|
||||
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
|
||||
const NS = process.env.METAHARNESS_AUDIT_NAMESPACE || 'metaharness-audit';
|
||||
const CLI_PKG = process.env.CLI_CORE === '1'
|
||||
? '@claude-flow/cli-core@alpha'
|
||||
: '@claude-flow/cli@latest';
|
||||
|
||||
const ARGS = (() => {
|
||||
const a = {
|
||||
path: '.', baselineSince: null, threshold: 0.95,
|
||||
dryRun: false, format: 'table',
|
||||
};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const v = process.argv[i];
|
||||
if (v === '--path') a.path = process.argv[++i];
|
||||
else if (v === '--baseline-since') a.baselineSince = process.argv[++i];
|
||||
else if (v === '--threshold') a.threshold = Number(process.argv[++i]);
|
||||
else if (v === '--dry-run') a.dryRun = true;
|
||||
else if (v === '--format') a.format = process.argv[++i];
|
||||
}
|
||||
return a;
|
||||
})();
|
||||
|
||||
function emitAndExit(payload, code) {
|
||||
if (ARGS.format === 'json') {
|
||||
console.log(JSON.stringify(payload, null, 2));
|
||||
} else {
|
||||
console.log(`# drift-from-history\n`);
|
||||
if (payload.degraded) {
|
||||
console.log(`⊘ ${payload.reason}`);
|
||||
} else if (payload.error) {
|
||||
console.log(`✗ ${payload.error}`);
|
||||
} else {
|
||||
console.log(`Baseline: ${payload.baseline?.key ?? payload.baseline?.startedAt}`);
|
||||
console.log(`Current: ${payload.current?.startedAt ?? '(fresh)'}`);
|
||||
console.log('');
|
||||
const sd = payload.drift?.structuralDistance;
|
||||
if (sd && sd.verdict !== 'unavailable') {
|
||||
console.log(`Structural similarity: ${sd.overall} (${sd.verdict})`);
|
||||
console.log(`Distance: ${sd.distance}`);
|
||||
}
|
||||
console.log('');
|
||||
if (payload.alert?.triggered) {
|
||||
console.log(`⚠ ALERT: ${payload.alert.reason}`);
|
||||
} else if (payload.alert) {
|
||||
console.log(`✓ ${payload.alert.reason}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function runScriptJson(script, args) {
|
||||
const r = spawnSync('node', [join(SCRIPTS_DIR, script), ...args, '--format', 'json'], {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
const m = /\{[\s\S]*\}/.exec(r.stdout || '');
|
||||
const json = m ? JSON.parse(m[0]) : null;
|
||||
// audit-list emits {records:[...]} — check that shape too
|
||||
const arrM = /\[[\s\S]*\]/.exec(r.stdout || '');
|
||||
return { json, exitCode: r.status ?? -1, stdout: r.stdout || '', stderr: r.stderr || '', arrMatch: arrM };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// Step 1: list audit records
|
||||
const listArgs = ['--limit', '50'];
|
||||
if (ARGS.baselineSince) listArgs.push('--since', ARGS.baselineSince);
|
||||
const listResult = runScriptJson('audit-list.mjs', listArgs);
|
||||
if (listResult.exitCode !== 0) {
|
||||
emitAndExit({
|
||||
error: `audit-list failed (exit ${listResult.exitCode})`,
|
||||
stderrTail: listResult.stderr.slice(-200),
|
||||
}, 2);
|
||||
}
|
||||
const records = listResult.json?.records ?? listResult.json?.entries ?? [];
|
||||
if (records.length === 0) {
|
||||
emitAndExit({
|
||||
error: 'no audit records found in namespace ' + NS,
|
||||
hint: 'Run `ruflo metaharness oia-audit` at least once to seed history.',
|
||||
}, 2);
|
||||
}
|
||||
// Pick the most recent record (records are typically newest-first; if not,
|
||||
// sort by startedAt). Each record's key is in the entry.
|
||||
const sorted = [...records].sort((a, b) =>
|
||||
String(b.startedAt ?? b.key ?? '').localeCompare(String(a.startedAt ?? a.key ?? '')));
|
||||
const baseline = sorted[0];
|
||||
if (!baseline?.key) {
|
||||
emitAndExit({
|
||||
error: 'audit record has no `key` field — cannot reference',
|
||||
sample: baseline,
|
||||
}, 2);
|
||||
}
|
||||
|
||||
// Step 2: run fresh oia-audit (write to temp file so audit-trend can read it)
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'drift-from-history-'));
|
||||
const currPath = join(tmp, 'current.json');
|
||||
try {
|
||||
const auditArgs = ['--path', ARGS.path];
|
||||
if (ARGS.dryRun) auditArgs.push('--dry-run');
|
||||
const auditResult = runScriptJson('oia-audit.mjs', auditArgs);
|
||||
if (!auditResult.json || auditResult.exitCode !== 0) {
|
||||
emitAndExit({
|
||||
error: `oia-audit failed (exit ${auditResult.exitCode})`,
|
||||
stderrTail: auditResult.stderr.slice(-200),
|
||||
}, 2);
|
||||
}
|
||||
if (auditResult.json.degraded === true) {
|
||||
emitAndExit({
|
||||
degraded: true,
|
||||
reason: auditResult.json.reason || 'metaharness-not-available',
|
||||
}, 3);
|
||||
}
|
||||
writeFileSync(currPath, JSON.stringify(auditResult.json));
|
||||
|
||||
// Step 3: audit-trend
|
||||
const trendArgs = [
|
||||
'--baseline-key', baseline.key,
|
||||
'--current', currPath,
|
||||
'--alert-on-distance-below', String(ARGS.threshold),
|
||||
];
|
||||
const trendResult = runScriptJson('audit-trend.mjs', trendArgs);
|
||||
if (!trendResult.json) {
|
||||
emitAndExit({
|
||||
error: `audit-trend produced no JSON (exit ${trendResult.exitCode})`,
|
||||
stderrTail: trendResult.stderr.slice(-200),
|
||||
}, 2);
|
||||
}
|
||||
const trend = trendResult.json;
|
||||
const alertTriggered = trendResult.exitCode === 1;
|
||||
|
||||
const payload = {
|
||||
adr: 'ADR-150 + ADR-152 §3.1',
|
||||
command: 'drift-from-history',
|
||||
baseline: {
|
||||
key: baseline.key,
|
||||
startedAt: baseline.startedAt ?? null,
|
||||
},
|
||||
current: {
|
||||
startedAt: auditResult.json.startedAt,
|
||||
composite: auditResult.json.composite,
|
||||
},
|
||||
drift: trend.delta,
|
||||
alert: {
|
||||
threshold: ARGS.threshold,
|
||||
triggered: alertTriggered,
|
||||
reason: trend.alert?.reasons?.join('; ')
|
||||
?? (alertTriggered ? `similarity < ${ARGS.threshold}` : `similarity ≥ ${ARGS.threshold} — OK`),
|
||||
},
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
emitAndExit(payload, alertTriggered ? 1 : 0);
|
||||
} finally {
|
||||
try { rmSync(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('drift-from-history crashed:', e.message || e);
|
||||
process.exit(2);
|
||||
});
|
||||
@@ -191,6 +191,30 @@ 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 "17z16. drift-from-history one-command primitive (iter 53)"
|
||||
miss=""
|
||||
F="$ROOT/scripts/drift-from-history.mjs"
|
||||
[[ -x "$F" ]] || miss="$miss not-executable"
|
||||
node --check "$F" 2>/dev/null || miss="$miss syntax-error"
|
||||
# Required flags
|
||||
grep -q -- "--baseline-since" "$F" 2>/dev/null || miss="$miss no-baseline-since"
|
||||
grep -q -- "--threshold" "$F" 2>/dev/null || miss="$miss no-threshold"
|
||||
grep -q -- "--dry-run" "$F" 2>/dev/null || miss="$miss no-dry-run"
|
||||
# Composes the 3 sub-scripts
|
||||
grep -q "audit-list.mjs" "$F" 2>/dev/null || miss="$miss no-audit-list-compose"
|
||||
grep -q "oia-audit.mjs" "$F" 2>/dev/null || miss="$miss no-oia-audit-compose"
|
||||
grep -q "audit-trend.mjs" "$F" 2>/dev/null || miss="$miss no-audit-trend-compose"
|
||||
# Skill manifest + dispatcher entry
|
||||
SK="$ROOT/skills/harness-drift-from-history/SKILL.md"
|
||||
[[ -f "$SK" ]] || miss="$miss no-skill-md"
|
||||
grep -q "name: harness-drift-from-history" "$SK" 2>/dev/null || miss="$miss skill-name-wrong"
|
||||
DISP="$ROOT/../../v3/@claude-flow/cli/src/commands/metaharness.ts"
|
||||
grep -q "'drift-from-history': 'drift-from-history.mjs'" "$DISP" 2>/dev/null || miss="$miss no-dispatcher-entry"
|
||||
grep -q "drift-from-history.*iter 53" "$DISP" 2>/dev/null || miss="$miss no-help-line"
|
||||
# 4-exit-code semantic — script exits 0/1/2/3 based on threshold + dep state
|
||||
grep -q "process.exit(code)\|process.exit(2)\|process.exit(3)" "$F" 2>/dev/null || miss="$miss no-exit-semantics"
|
||||
[[ -z "$miss" ]] && ok || bad "$miss"
|
||||
|
||||
step "17z15. iter-50 parser locked at MCP layer + doctor (iter 52)"
|
||||
miss=""
|
||||
# MCP runtime test enrolls mcp_scan positive case
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
name: harness-drift-from-history
|
||||
description: One-command drift detection. Composes audit-list + oia-audit + audit-trend into a single primitive — finds the most recent audit in `metaharness-audit` namespace, runs a fresh audit against the current repo, diffs them via ADR-152 §3.1 similarity, and alerts when structural distance crosses `--threshold`. Iter 53 of ADR-150 deep integration.
|
||||
argument-hint: "[--path .] [--baseline-since 7d] [--threshold 0.95] [--dry-run] [--format json|table]"
|
||||
allowed-tools: Bash
|
||||
---
|
||||
|
||||
The natural ops question after running `oia-audit` weekly is "did anything drift?" Before this skill, the answer required a three-step sequence:
|
||||
|
||||
```bash
|
||||
npx ruflo metaharness audit-list --format json # → pick a key by hand
|
||||
npx ruflo metaharness oia-audit --format json > /tmp/curr.json
|
||||
npx ruflo metaharness audit-trend \
|
||||
--baseline-key <picked-key> --current /tmp/curr.json \
|
||||
--alert-on-distance-below 0.95
|
||||
```
|
||||
|
||||
This skill collapses it into one command:
|
||||
|
||||
```bash
|
||||
npx ruflo metaharness drift-from-history --threshold 0.95
|
||||
```
|
||||
|
||||
## What it does
|
||||
|
||||
1. Lists records from `metaharness-audit` namespace via audit-list.mjs
|
||||
2. Picks the most recent record by `startedAt` (or `--baseline-since 7d` skips anything newer than 7 days)
|
||||
3. Runs a fresh `oia-audit` against the current path
|
||||
4. Diffs the two via audit-trend, applying `--alert-on-distance-below ${threshold}`
|
||||
5. Returns the structured drift report
|
||||
|
||||
## Architectural constraint inheritance (ADR-150)
|
||||
|
||||
| Constraint | How drift-from-history satisfies it |
|
||||
|---|---|
|
||||
| Removable | Pure subprocess composition over existing scripts — no new `@metaharness/*` import |
|
||||
| Optional | If oia-audit reports `degraded:true`, this skill exits 3 with a degraded payload |
|
||||
| Graceful | Empty audit history → exit 2 with hint to seed it; never crashes |
|
||||
| CI-gate | Smoke step 17z16 anchors the dispatcher entry + subcommand listing |
|
||||
|
||||
## Exit codes
|
||||
|
||||
- 0 — similarity ≥ threshold (or threshold not crossed)
|
||||
- 1 — drift detected: similarity < threshold (alert fired)
|
||||
- 2 — config error (no history, audit-list failed)
|
||||
- 3 — upstream metaharness absent (degraded payload returned)
|
||||
|
||||
## Example
|
||||
|
||||
```bash
|
||||
$ npx ruflo metaharness drift-from-history --threshold 0.95
|
||||
# drift-from-history
|
||||
|
||||
Baseline: audit-2026-06-16T22-58-47-840Z
|
||||
Current: 2026-06-16T23:05:02.231Z
|
||||
|
||||
Structural similarity: 1 (near-identical)
|
||||
Distance: 0
|
||||
|
||||
✓ similarity ≥ 0.95 — OK
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
[`scripts/drift-from-history.mjs`](../../scripts/drift-from-history.mjs)
|
||||
@@ -57,6 +57,8 @@ const SUBCOMMANDS: Record<string, string> = {
|
||||
'audit-list': 'audit-list.mjs',
|
||||
// iter 36 — ADR-152 §3.1 weighted similarity between two harness fingerprints
|
||||
similarity: 'similarity.mjs',
|
||||
// iter 53 — one-command drift detection (compose audit-list + oia-audit + audit-trend)
|
||||
'drift-from-history': 'drift-from-history.mjs',
|
||||
mint: 'mint.mjs',
|
||||
};
|
||||
|
||||
@@ -167,6 +169,7 @@ export const metaharnessCommand: Command = {
|
||||
output.writeln(' audit-list enumerate timestamped audit records');
|
||||
output.writeln(' audit-trend diff two audit records (drift detection)');
|
||||
output.writeln(' similarity ADR-152 — weighted similarity between two harness fingerprints');
|
||||
output.writeln(' drift-from-history iter 53 — diff current state against most recent audit (1-command drift)');
|
||||
output.writeln(' mint scaffold a custom harness (dry-run by default)');
|
||||
output.writeln('');
|
||||
output.writeln('Each subcommand accepts --format json|table and --help.');
|
||||
|
||||
Reference in new issue
Block a user