Files
ruflo/v3/@claude-flow/cli/scripts/verify-helpers.mjs
T
rUv 82dac70fd7 feat(router): ADR-389–391 — refresh router helper, opt-in MiniLM embedder, benchmark gate (no default change) (#3410)
* docs(adr): ADR-389..391 — router: refresh the helper, use the real embedder, change defaults only on a measured win

ADR-389: add router.js to CRITICAL_HELPERS + re-sign, so installed copies get
the word-boundary fix (#3401); today they are frozen at first write.
ADR-390: hooks_route embeds patterns and tasks with the local MiniLM chain
(generateLocalEmbedding), hash embedder as the reported fallback.
ADR-391: frozen, labelled 150-200 prompt corpus; A/B/C/D (current, MiniLM,
typesafe-hash, typesafe-onnx); ADR-150-style AND-gate for promotion.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(init): refresh router.js as a critical helper on upgrade (ADR-389, #3401)

Installed copies of .claude/helpers/router.js never received the #2257
word-boundary fix: helper-refresh only re-copies CRITICAL_HELPERS and
router.js was not on the list, so an April substring router kept routing
"sync and review latest issues" to tester.

- helper-refresh.ts: add router.js to CRITICAL_HELPERS; generator
  fallback also emits it (generateAgentRouter).
- sign-helpers.mjs / verify-helpers.mjs / executor.ts executeUpgrade /
  smoke-helper-signing-security.mjs: keep their copies of the list in sync.
- New test: stale April router.js is replaced by the package copy via the
  signed refresh path (throwaway key), after which the prompt no longer
  routes to tester.

helpers.manifest.json is NOT re-signed here. Until it is, verify-helpers
fails ("manifest has no entry for router.js") and the production refresh
is fail-closed blocked for all helpers.

Co-Authored-By: RuFlo <ruv@ruv.net>

* bench(router): ADR-391 labelled evaluation corpus (197 prompts, frozen)

Blind-labelled corpus for comparing routing candidates: 11 labels incl. none,
64 adversarial trap cases, deterministic stratified dev/test split (i%5 in
{0,2} -> dev), dependency-free validator that recomputes the split and prints
the sha256. Frozen at sha256 b0c1923b2813b61907304dff56c53d199b709797bfb9600a7c1f496cf0c0bf04.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(hooks): ADR-390 — semantic router can use the real MiniLM embedder

hooks_route compared tasks with pattern keywords using a character hash
(generateSimpleEmbedding), which measures spelling, not meaning. This adds a
router-embedder abstraction (src/ruvector/router-embedder.ts):

- embedForRouter(texts, kind) -> { vectors, embedder: 'minilm'|'hash', reason? }
- MiniLM path uses generateLocalEmbedding ONLY (never the bridge-first
  generateEmbedding, #2312). backend !== 'onnx', a throw, or a non-384-d
  vector degrades EVERY text in the call to the hash, with a reason.
- Selection: CLAUDE_FLOW_ROUTER_EMBEDDER=minilm|hash; DEFAULT_ROUTER_EMBEDDER
  stays 'hash' until ADR-391's benchmark decides.

getSemanticRouter builds both the native VectorDb and pure-JS indexes from one
embedder, records which one actually built the index, embeds the query with
that same embedder, rebuilds when the requested embedder changes, and shares
one in-flight build between concurrent callers. If the query fails on MiniLM
after a MiniLM index was built, the index is rebuilt with the hash so the two
spaces never mix. hooks_route results gain `embedder` (+ `embedderReason` when
degraded); existing fields are unchanged.

routeTaskForBench(task, { embedder }) is an internal, bench-only entry that
runs the same local path as hooks_route (skipping the AgentDB pre-route and
the opt-in typesafe wrapper) for ADR-391.

Co-Authored-By: RuFlo <ruv@ruv.net>

* chore(audit): register CLAUDE_FLOW_ROUTER_EMBEDDER as a known env escape hatch

ADR-390's router embedder selector is process-lifetime MCP router state, like
CLAUDE_FLOW_DISABLE_NATIVE_ROUTER; the ADR-391 bench passes the embedder
explicitly rather than through a CLI flag.

Co-Authored-By: RuFlo <ruv@ruv.net>

* bench(router): ADR-391 first run — no candidate promoted; fix typesafe-router test (e)

Benchmark (run-bench.mjs) on the frozen 197-prompt corpus
(sha256 b0c1923b…), test split n=113:
  A current (hash)   25.7% acc, p95 1.06 ms
  B MiniLM (ADR-390) 36.3% acc, p95 6.21 ms   (+10.6 pts, +485% p95)
  C typesafe hash    26.5% acc, p95 1.20 ms
  D typesafe onnx    29.2% acc, p95 8.35 ms   (raw pick 44.3%, gated to 5.6%)
No candidate passes the ADR-391 AND-gate (B fails the relative latency
bound), so DEFAULT_ROUTER_EMBEDDER stays 'hash' and typesafe stays opt-in.
Receipt committed under benchmarks/router/results/. ADR-391 gains a Results
section with the findings (structural ceiling: no pattern returns
researcher/reviewer/none; latency criterion mis-specified for a ~1 ms base;
typesafe gate too tight) as owner decisions, not applied.

ADR-389 -> Implemented; ADR-390 -> Implemented as opt-in; ADR-391 -> Implemented.

typesafe-router test (e) was red on main since #3402 made the keyword
fallback word-bounded: it still asserted the old "latest"->tester fallback.
It now asserts the typesafe override and that a legacy fallback is kept.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-23 18:39:18 +00:00

76 lines
3.5 KiB
JavaScript

#!/usr/bin/env node
/**
* Verify .claude/helpers/helpers.manifest.json against the shipped critical
* helpers (ADR-174, issue #2593). Runs in prepublishOnly AFTER sign-helpers.mjs
* so npm publish fails closed if the manifest ever drifts from disk again.
*
* Checks:
* 1. Ed25519 signature over the canonical manifest bytes is valid under
* RUFLO_HELPERS_PUBKEY (same primitive as helper-signing.ts).
* 2. manifest.version matches package.json version.
* 3. Every critical helper on disk hashes to the manifest entry.
*
* Optional arg: path to a helpers dir (e.g. an extracted `npm pack` tarball).
* Defaults to <cli-pkg>/.claude/helpers.
*/
import { readFileSync, existsSync } from 'node:fs';
import { createHash, verify as edVerify } from 'node:crypto';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = join(__dirname, '..');
const HELPERS_DIR = resolve(process.argv[2] || join(PKG_ROOT, '.claude', 'helpers'));
// Keep in sync with sign-helpers.mjs:CRITICAL and src/init/helper-refresh.ts:CRITICAL_HELPERS.
const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.js'];
function die(msg) { console.error(`[verify-helpers] ${msg}`); process.exit(1); }
// #2675 — helper-signing.ts is the sole key source. prepare-publish.mjs and
// stable-npm-release.yml both build before verification, so importing emitted
// runtime code preserves the exact key users will trust after installation.
let RUFLO_HELPERS_PUBKEY;
try {
({ RUFLO_HELPERS_PUBKEY } = await import('../dist/src/init/helper-signing.js'));
} catch {
die('compiled helper-signing.js is unavailable; run `npm run build` before verification');
}
const manifestPath = join(HELPERS_DIR, 'helpers.manifest.json');
if (!existsSync(manifestPath)) die(`missing manifest: ${manifestPath}`);
let signed;
try { signed = JSON.parse(readFileSync(manifestPath, 'utf-8')); }
catch (e) { die(`manifest is not valid JSON: ${e.message}`); }
if (!signed || signed.algorithm !== 'ed25519' || !signed.signature || !signed.manifest?.files) {
die('manifest is malformed (missing algorithm/signature/files)');
}
// Canonical bytes — sorted file keys, MUST match sign-helpers.mjs + helper-signing.ts.
const sortedFiles = {};
for (const k of Object.keys(signed.manifest.files).sort()) sortedFiles[k] = signed.manifest.files[k];
const canonical = Buffer.from(JSON.stringify({ version: signed.manifest.version, files: sortedFiles }), 'utf-8');
if (!edVerify(null, canonical, RUFLO_HELPERS_PUBKEY, Buffer.from(signed.signature, 'base64'))) {
die('Ed25519 signature does not verify against RUFLO_HELPERS_PUBKEY');
}
const pkgVersion = JSON.parse(readFileSync(join(PKG_ROOT, 'package.json'), 'utf-8')).version;
if (signed.manifest.version !== pkgVersion) {
die(`manifest version ${signed.manifest.version} != package.json ${pkgVersion} — re-run sign-helpers.mjs`);
}
for (const name of CRITICAL) {
const p = join(HELPERS_DIR, name);
if (!existsSync(p)) die(`critical helper missing on disk: ${p}`);
const actual = createHash('sha256').update(readFileSync(p)).digest('hex');
const expected = signed.manifest.files[name];
if (!expected) die(`manifest has no entry for ${name}`);
if (actual !== expected) {
die(`hash drift for ${name}\n manifest: ${expected}\n on disk: ${actual}\n → re-run sign-helpers.mjs`);
}
}
console.log(`[verify-helpers] ok — ${CRITICAL.length} helpers match signed manifest @ ${signed.manifest.version}`);