Files
ruflo/v3/@claude-flow/cli/scripts/sign-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

112 lines
5.1 KiB
JavaScript

#!/usr/bin/env node
/**
* Sign the critical helpers → .claude/helpers/helpers.manifest.json (ADR-174).
*
* Run at publish time WHENEVER a critical helper changes. NEVER commit the
* private key. The public half is baked into src/init/helper-signing.ts
* (RUFLO_HELPERS_PUBKEY).
*
* Private-key resolution (first that is set wins):
* 1. GCP Secret Manager (PREFERRED for CI/publish):
* RUFLO_HELPERS_SIGNING_SECRET=<secret-name> (e.g. ruflo-helpers-signing-key)
* RUFLO_HELPERS_SIGNING_PROJECT=<gcp-project> (optional; defaults to the
* active gcloud project)
* Fetched via `gcloud secrets versions access latest`.
* 2. RUFLO_HELPERS_SIGNING_KEY=<pem-file-path> (local / air-gapped)
* 3. ~/.ruflo/helpers-signing.key (dev default)
*
* Stdin fallback (the PEM never appears in shell output or argv):
* gcloud secrets versions access latest --secret=... | node scripts/sign-helpers.mjs --stdin-key
*
* Usage: RUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key node scripts/sign-helpers.mjs
*/
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { createHash, createPrivateKey, sign as edSign } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = join(__dirname, '..');
const HELPERS_DIR = join(PKG_ROOT, '.claude', 'helpers');
// Keep in sync with src/init/helper-refresh.ts:CRITICAL_HELPERS.
const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.js'];
function loadPrivateKey() {
if (process.argv.includes('--stdin-key')) {
if (process.stdin.isTTY) {
console.error(
'[sign-helpers] --stdin-key requires piped stdin; refusing interactive key entry. ' +
'Pipe Secret Manager output directly or use RUFLO_HELPERS_SIGNING_KEY=<pem-file-path>.',
);
process.exit(1);
}
const key = readFileSync(0, 'utf-8');
if (!key.trim()) {
console.error('[sign-helpers] --stdin-key received empty input');
process.exit(1);
}
return key;
}
const secret = process.env.RUFLO_HELPERS_SIGNING_SECRET;
if (secret) {
const args = ['secrets', 'versions', 'access', 'latest', '--secret', secret];
const project = process.env.RUFLO_HELPERS_SIGNING_PROJECT;
if (project) args.push('--project', project);
try {
const gcloudBin = process.platform === 'win32' ? 'gcloud.cmd' : 'gcloud';
// stdio: key on stdout (captured), stderr captured too — NOT inherited.
// Inheriting would forward gcloud's stderr verbatim into whatever log
// is capturing this process's output (CI, terminal); this key material
// is sensitive enough that we never want an uncontrolled passthrough,
// even though gcloud's normal error paths don't echo secret payloads.
return execFileSync(gcloudBin, args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
} catch {
console.error(`[sign-helpers] failed to read GCP secret '${secret}'. Is gcloud authed? (gcloud auth login)`);
process.exit(1);
}
}
const keyPath = process.env.RUFLO_HELPERS_SIGNING_KEY || join(homedir(), '.ruflo', 'helpers-signing.key');
if (!existsSync(keyPath)) {
console.error(
`[sign-helpers] no signing key. Set RUFLO_HELPERS_SIGNING_SECRET (GCP) ` +
`or RUFLO_HELPERS_SIGNING_KEY (PEM path); tried ${keyPath}.`,
);
process.exit(1);
}
return readFileSync(keyPath, 'utf-8');
}
const privateKeyPem = loadPrivateKey();
try {
const key = createPrivateKey(privateKeyPem);
if (key.asymmetricKeyType !== 'ed25519') throw new Error('wrong-key-type');
} catch {
// Never include the PEM or the crypto parser's input in diagnostics.
console.error('[sign-helpers] signing key is not a valid Ed25519 private key');
process.exit(1);
}
const version = JSON.parse(readFileSync(join(PKG_ROOT, 'package.json'), 'utf-8')).version;
const files = {};
for (const name of CRITICAL) {
const p = join(HELPERS_DIR, name);
if (!existsSync(p)) { console.error(`[sign-helpers] missing helper: ${p}`); process.exit(1); }
files[name] = createHash('sha256').update(readFileSync(p)).digest('hex');
}
const manifest = { version, files };
// Canonical bytes: sorted file keys — MUST match helper-signing.ts.
const sortedFiles = {};
for (const k of Object.keys(manifest.files).sort()) sortedFiles[k] = manifest.files[k];
const canonical = Buffer.from(JSON.stringify({ version: manifest.version, files: sortedFiles }), 'utf-8');
const signature = edSign(null, canonical, privateKeyPem).toString('base64');
const signed = { manifest, signature, algorithm: 'ed25519' };
const outPath = join(HELPERS_DIR, 'helpers.manifest.json');
writeFileSync(outPath, JSON.stringify(signed, null, 2) + '\n', 'utf-8');
console.log(`[sign-helpers] signed ${CRITICAL.length} helpers → ${outPath}`);
for (const [n, h] of Object.entries(files)) console.log(` ${n}: ${h.slice(0, 16)}…`);