Files
rUv d012042800 feat: review-driven upgrades — perf, security, SOTA capabilities (6-agent concurrent implementation) (#2547)
* chore(arch): untrack the prepublish plugin mirror — build artifact, not source

v3/@claude-flow/cli/plugins/ is regenerated by prepublishOnly from
plugins/ruflo-metaharness/ at publish time. Keeping it committed caused
silent drift between publishes (4 files diverged this week alone) and
every source edit required a manual mirror sync. npm pack still bundles
it — the files array + prepublish copy are unaffected by gitignore.

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

* feat(gaia): submission integrity checklist — fail-closed pre-submit audit (Berkeley RDI hardening)

Adds a 4-part integrity section to the gaia-validate pre-submit gate,
motivated by UC Berkeley RDI's 'Agents' Last Exam' (April 2026), which
gamed all 8 major agent benchmarks to near-100% without solving tasks.

- scripts/gaia-integrity.mjs: (A) answer-key-shaped path reads outside
  the sanctioned dataset dir — FAIL-CLOSED exit 2; (B) eval()/new
  Function()/exec-of-non-literal strings in gaia-bench runner code
  paths — FAIL-CLOSED exit 2; (C) judge-prompt-injection markers in
  produced answers/trajectories — WARN; (D) provenance stamp (results
  + git SHA + dataset content hash) written for gaia-submit to embed.
- --allow-integrity-override suppresses the exit code but records
  'overridden: true' in the stamp — never silent.
- --self-test plants a fake answer-key read, an eval-of-task runner,
  and injection markers in temp fixtures and proves fail-closed/pass/warn.
- gaia-validate.md: new check 7 documenting the checklist + flags.
- gaia-submit.md: package now embeds integrity.json under the Ed25519
  witness manifest (tamper-evident attestation); stale/failed stamps block
  packaging.
- smoke-gaia.sh: 3 new steps (script wired, self-test green, repo scan
  clean); plugin bumped to 0.5.0.

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

* perf(cli): lazy ONNX embedder init + local-first ruvector resolution

Fix 1 — lazy ONNX init (measured, biggest win):
neural-tools.ts had a module-level try/catch with TOP-LEVEL AWAIT that ran
`await import('ruvector')` + `initOnnxEmbedder()` + a probe embed at import
time. Because mcp-client statically imports neural-tools, this added the
full ONNX startup to every CLI command. The block is now a memoized
`ensureEmbeddings()` (module-level promise guard) invoked from
generateEmbedding() and from the three handlers that report the provider
without embedding (neural_compress / neural_status / neural_optimize), so
degraded/fallback semantics and provider reporting are byte-identical.
The probe embed moved inside ensureEmbeddings() — it still guards the
ADR-086 type-load-success-but-runtime-fails trap, but only on first use.

Measured (warm, darwin-arm64):
  node bin/cli.js --help   0.50s -> 0.09s
  node bin/cli.js status   0.64s -> 0.24s
  import(mcp-client.js)    438ms -> 30ms
  "Loading ONNX model" no longer appears on non-embedding commands;
  appears exactly once on first embed (neural_predict / memory search).

Fix 2 — ruvector pin + local-first resolution:
browser-session-tools.ts pinned `npx -y ruvector@0.2.25` while 0.2.27 is
what the package installs, forcing cold npx downloads of a second version
(4 per browser session). The pin is now 0.2.27 and a memoized
resolveLocalRuvectorCli() (createRequire + package.json bin walk) spawns
`node <local-cli>` directly, falling back to the npx pin only when no
local install exists.

While verifying the 0.2.27 subcommand surface (required before bumping),
found the trajectory-* flags passed here were never valid on 0.2.25 OR
0.2.27 (`--session-id/--task/--args/--verdict` vs the real
`--context/--agent`, `--action/--result`, `--success/--quality`) — every
trajectory call exited with commander "unknown option", same bug class as
the #2015 `rvf create --kind` fix documented in this file. Flags are now
mapped correctly; browser_session_record and browser_session_end verified
end-to-end (rvf create + trajectory-begin/step/end + rvf compact all pass).

Fix 3 — lazy heavy MCP tool groups: profiled and NOT converted.
Per-module timed dynamic imports of all 36 tool modules show neural-tools
was 469.6ms and every other group is 0.3-5.5ms (hooks-tools 3.5ms,
agentdb-tools 2.5ms, embeddings 0.9ms, wasm-agent 0.6ms). After fix 1 the
whole registry builds in ~30ms; converting handler dispatch to lazy
import() would add risk for <6ms of residual win, so mcp-client.ts is
intentionally untouched.

Validation:
- tsc build clean
- plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs: 171/171 passed
- memory search / neural predict still work; ONNX loads lazily then

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

* security(deps): lift OTel floor-became-ceiling pins — core >=2.8.0, otlp family >=0.220.0

The exact pins @opentelemetry/{core,resources,sdk-trace-base}@1.25.1 and
the otlp exporter/transformer family@0.52.1 (root + ruflo wrapper
overrides) were added in #1997/#2112 as a 'fewer-knobs-for-arborist'
defense against the npm arborist Invalid Version crash (empty-version
placeholder from optionalDependencies/peerDependencies overlap). They
were never API-compat pins — but they became a ceiling that forces the
tree onto @opentelemetry/core <2.8.0, which npm audit flags for
GHSA-8988-4f7v-96qf (unbounded memory allocation in W3C Baggage
parsing), and they blocked every upstream fix.

Convert to floors while keeping the lockstep families coherent:
  - stable line:   core / resources / sdk-trace-base  ->  >=2.8.0
  - otlp line:     sdk-node, exporter-prometheus, the three
    exporter-trace-otlp-* packages, otlp-exporter-base,
    otlp-grpc-exporter-base, otlp-transformer  ->  >=0.220.0
(sdk-node@0.220.0 declares exactly core@2.9.0 + otlp@0.220.0, so the
floors resolve to one mutually consistent set; verified in both the
root lockfile and a fresh ruflo/ resolution: core 2.9.0 everywhere,
otlp 0.220.0 everywhere.)

The arborist defense is preserved — every package in both families is
still forced to a single resolution via overrides; the override set is
now broader (whole otlp family at root too), which gives arborist fewer
ambiguous nodes than before, not more.

Also adds the exporter family overrides to the root manifest so root
and the published ruflo wrapper stay aligned (#2112 lesson: root
overrides do not propagate to the published wrapper).

Validation:
  - root:  npm audit --omit=dev  30 moderate -> 0 vulnerabilities
  - ruflo: npm install --package-lock-only succeeds, 0 vulnerabilities
  - runtime probe: new NodeSDK({}) via @opentelemetry/sdk-node@0.220.0
    with core@2.9.0 loads and exposes start(); OTLPTraceExporter loads

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* security(deps): npm audit fix on v3 workspace lock — grpc-js, hono/node-server, brace-expansion

Plain `npm audit fix --omit=dev --package-lock-only` (no --force) on the
v3 npm workspace lockfile. Clears the three targeted advisories:

  - @grpc/grpc-js        1.14.3 -> 1.14.4   GHSA-5375-pq7m-f5r2 (+GHSA-99f4-grh7-6pcq)
  - @hono/node-server    1.19.9 -> 1.19.14  GHSA-wc8c-qw6v-h7f6 (+GHSA-92pp-h63x-v22m)
  - @isaacs/brace-expansion  5.0.0 removed/deduped  GHSA-7h2j-956f-4vf2

Audit summary: 82 vulnerabilities (2 low, 56 moderate, 24 high)
            -> 55 vulnerabilities (50 moderate, 5 high).
The remainder needs --force / dependency swaps and is out of scope for
this pass.

Note: the reify was run with the two pnpm-style `workspace:*` devDep
specs (plugin-agent-federation, plugin-iot-cognitum) temporarily
substituted with the registry pins the lockfile already records
(@claude-flow/shared@3.0.0-alpha.8, @claude-flow/security@3.0.0-alpha.10),
because npm's arborist does not support the workspace: protocol; the
manifests themselves are unchanged. The v3 workspace is otherwise
pnpm-driven (`pnpm -r build`).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* security(deps): align agentdb floor in @claude-flow/memory — ^3.0.0-alpha.17

Root overrides force agentdb >=3.0.0-alpha.17, but @claude-flow/memory
declared ^3.0.0-alpha.16, so its nested/published tree could still
resolve alpha.16 (the #2112 lesson: overrides do not propagate to
nested or published trees). The v3 pnpm lock indeed had memory pinned
to agentdb 3.0.0-alpha.16 — bumping the package's own floor makes both
branches resolve the same version regardless of the consumer's
override set.

pnpm-lock.yaml is regenerated by `pnpm install`; besides the
agentdb 3.0.0-alpha.16 -> 3.0.0-alpha.17 move under memory, it also
reconciles previously committed manifest bumps (metaharness family)
that had drifted from the stale lock.

Verified: `npm ls agentdb` from root shows a single deduped
agentdb@3.0.0-alpha.17 across direct, @claude-flow/memory,
@claude-flow/neural, and agentic-flow branches.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* security(deps): correct FEDERATION_BIND_HOST doc default — 127.0.0.1 (ADR-166 Phase 3d)

The bin.ts header JSDoc still advertised `default: 0.0.0.0`, but the
code (makeContext) has defaulted to 127.0.0.1 since the ADR-166
Phase 3d loopback-by-default hardening. Doc-only change.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(memory): drop vitest-4 style vi.fn generic that breaks tsc build

The hoisted vitest 1.x types Mock as Mock<Args extends any[], Returns>,
so the single-generic vi.fn<SearchFn> form fails the package build
(pre-existing baseline failure). Annotate the variable instead — the
inferred mock signature is identical.

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

* perf(memory): batch embeddings in the migration import path

MemoryMigrator.processBatch batched entries (batchSize=100) but then
awaited this.embeddingGenerator(content) ONE ENTRY AT A TIME inside the
loop — N sequential ONNX inferences per batch on the
memory_import_claude hot path.

Now:
- New BatchEmbeddingGenerator type ((contents: string[]) =>
  Promise<Float32Array[]>) accepted as an optional 4th constructor /
  factory param — one true batch call per migration batch when the
  embedder supports it (e.g. bge-embedder's single padded forward pass).
- Fallback: bounded concurrency over the single-text generator
  (MigrationConfig.embeddingConcurrency, default 8 — never unbounded;
  set 1 to restore sequential behavior).
- If the batch call fails, falls back to per-entry embedding so one
  backend hiccup doesn't strand the batch.

Per-entry error semantics preserved: validation failures skip, store
failures fail, embedding failures warn and store the entry without a
vector — one bad entry never fails the batch.

Measured (200 synthetic entries, 5ms simulated single-embed latency):
sequential 1220ms -> concurrency-8 156ms (7.8x) -> true batch 115ms
(10.6x).

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

* feat(memory): temporal validity on hierarchical memory (Zep/Graphiti-style)

Facts in hierarchical memory can now carry validity windows and are
INVALIDATED on conflict instead of overwritten:

- New TieredMemoryStore module (@claude-flow/memory) promotes the inline
  controller-registry stub to a first-class, tested store with optional
  validFrom / validUntil (ISO) + supersededBy fields.
- store accepts supersedes=<entryId|key>: the old entry is stamped
  validUntil=now + supersededBy=<newId> and archived — never deleted.
- recall filters temporally-invalid entries (expired, superseded, or
  not-yet-valid) by default; includeExpired=true is the audit escape
  hatch.
- Backward compatible: entries without the fields behave exactly as
  before (always valid); legacy store(key,value,tier) / recall(query,
  topK) call shapes unchanged; same-key stores still overwrite; the
  bridge's real-vs-stub detection signal (getStats+promote) is
  preserved.
- CLI bridge passes the new optional fields through
  bridgeHierarchicalStore/-Recall. On the native agentdb
  HierarchicalMemory backend, validFrom/validUntil ride in metadata and
  are filtered at recall; supersedes is reported as unsupported there
  (no public update API) rather than silently dropped.
- MCP inputSchemas for agentdb_hierarchical-store (validFrom,
  validUntil, supersedes) and agentdb_hierarchical-recall
  (includeExpired) expose the fields to agents, with ISO-8601
  validation.

Tests: supersede flow (including same-key supersede preserving
history), expired + not-yet-valid filtering, includeExpired escape
hatch, legacy entries untouched, unparseable timestamps fail open.

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

* feat(routing): confidence-gated tier escalation — hooks_model-verify ($0 post-generation verifier)

ADR-026/143 classify BEFORE generation only. This adds the 2026-SOTA
post-generation gate: attempt the cheap tier, verify the output with
CHEAP structural signals (no LLM call), escalate only on failure.

- src/ruvector/output-verifier.ts — pure verifier: empty/truncated
  output, refusal patterns, degenerate repetition, unbalanced
  delimiters, and a real syntax parse for code/JSON tasks (TypeScript
  transpileModule diagnostics / JSON.parse, graceful degradation when
  typescript is absent). Returns {confident, reasons[], suggestedTier,
  suggestedModel, escalate}; ladder haiku→sonnet→opus, tier 2→3.
- hooks_model-verify MCP tool (hooks-tools.ts, surgical) — wraps the
  verifier and feeds the verdict into the SAME learning stream as
  hooks_model-outcome (ModelRouter.recordOutcome: success when
  confident, escalated when not) so the Thompson priors learn which
  task shapes the cheap tier fails on. A dedicated tool (not a verify
  mode on hooks_model-outcome) because verify is a mid-loop decision
  point returning a verdict the agent acts on, while outcome is a
  terminal write — the sequence is route → generate → verify →
  (escalate) → outcome.
- __tests__/output-verifier.test.ts — refusal/truncation/parse/
  escalation-ladder coverage + MCP handler tests (18 tests).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* feat(federation): A2A Agent Cards — spec-1.0 discovery adapter over the bespoke federation schema

Implements the Agent2Agent (A2A, Linux Foundation) Agent Card layer as an
ADAPTER over the existing federation registration/discovery shapes. Cards
only — A2A Tasks/messaging are deliberately out of scope this iteration.

Spec: A2A Protocol 1.0.0 (a2a-protocol.org; schema source of truth
specification/a2a.proto in a2aproject/A2A). Required AgentCard fields per
spec 4.4.1: name, description, supportedInterfaces, version, capabilities,
defaultInputModes, defaultOutputModes, skills. Well-known discovery path
per 8.2 + IANA registration: /.well-known/agent-card.json.

- src/a2a/agent-card.ts: toAgentCard() maps FederationManifest -> spec-
  compliant card (agent types -> AgentSkills; federation endpoint -> open-
  form RUFLO-FEDERATION AgentInterface; bespoke identity rides in a spec
  4.6 extension urn:ruflo:federation:manifest:v1 for lossless round-trip);
  validateAgentCard() enforces the 1.0 required-field shape;
  fromAgentCard() maps a remote card into a FederationNode — ALWAYS
  TrustLevel.UNTRUSTED (cards are self-asserted metadata; trust is earned
  via the normal handshake + TrustEvaluator path).
- src/a2a/well-known.ts: minimal node:http endpoint serving GET/HEAD on
  the exact well-known path with spec 8.6 Cache-Control + ETag/304.
  Binds 127.0.0.1 by default and REFUSES non-loopback binds without an
  explicit allowNonLoopback opt-in (ADR-166 posture preserved — no
  loosening of federation bind or auth).
- src/a2a/consume.ts: fetchAgentCard (injectable fetch, timeout, size cap,
  structural validation) + consumeAgentCard registering the peer into
  DiscoveryService so A2A peers appear in federation discovery.
- DiscoveryService: new 'a2a-card' discovery mechanism +
  registerExternalPeer() (refresh-not-replace preserves trust state).
- plugin.ts: opt-in wiring via config.a2aCard/a2aCardPort/a2aCardHost;
  bind failure degrades gracefully; server closed on shutdown.
- 40 new unit tests incl. golden-file card fixture
  (__tests__/fixtures/a2a-agent-card.golden.json), foreign-card mapping,
  round-trip, loopback guard, and a live serve->consume e2e over HTTP.
- plugin.test.ts: fixed pre-existing stale assertion (10 -> 11 CLI
  commands; 'federation trust elevate' was added without updating the
  count) — baseline suite failed before this change.

Build clean; 600/600 tests green.

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

* feat(intelligence): execution-state-tree retrieval prototype (MAGE-style positional recall)

Research basis: MAGE (arXiv 2606.06090) — semantic-similarity retrieval
fragments decision trajectories on long-horizon tasks; retrieving by
POSITION in a hierarchical execution-state tree (root→current path)
preserves coherence.

- src/ruvector/trajectory-tree.ts — TrajectoryTree prototype:
  trajectory-start opens a node under the session root (nesting under
  the deepest open trajectory), steps append children, end closes and
  pops the current position. recallPath({sessionId, depth}) returns
  the exact root→current path + recent siblings — no embedding search.
  Best-effort JSON snapshot at .claude-flow/intelligence/
  trajectory-tree.json, ALONGSIDE existing trajectory storage (no
  migration). Limitations documented in the module header.
- hooks-tools.ts (surgical): non-fatal tree mirrors in
  hooks_intelligence_trajectory-start/step/end (+ optional sessionId
  param on start), and an opt-in strategy:"state-tree" on
  hooks_intelligence_pattern-search (+ sessionId/depth params).
  Default strategy stays "semantic" — zero behavior change unless
  opted in.
- __tests__/trajectory-tree.test.ts — synthetic 3-level trajectory
  path assertions, nesting/pop, sibling window, persistence
  round-trip, and default-strategy-untouched checks (12 tests).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(metaharness): kill third-party @latest, extract shared _invoke.mjs, derive smoke counts

Three of the four converged security/perf/arch review fixes:

1. SECURITY (HIGH) + PERF — _harness.mjs no longer shells to
   `npx -y metaharness@latest` (a compromised upstream publish would have
   executed arbitrary code on user machines, and @latest forced a registry
   check per call). Resolution is now: (a) locally installed metaharness
   satisfying the PINNED range ~0.3.0 (walk-up node_modules), then (b) a
   one-time `npm install --prefix ~/.ruflo/metaharness-cache-0.3.0`, then
   plain `node <abs-path-to-cli>` spawns — zero network per call. Both bins
   (metaharness + harness) are read from the resolved package.json bin map.
   The {stdout, stderr, exitCode, json, degraded, reason, durationMs}
   contract and ADR-150 graceful degradation are preserved; timeouts now
   report 'metaharness-timeout' (matching _darwin/_redblue) instead of being
   conflated with 'metaharness-not-available'.
   Measured: `score.mjs --path .` completes in ~0.35s via the cache.

2. ARCH — new scripts/_invoke.mjs consolidates the copy-pasted plumbing:
   DEGRADED_RX (superset incl. `npm ERR`), classifyDegraded (keeps the
   -timeout vs -not-available distinction), injectJson, parseTrailingJson
   (the LAST-{...}-block variant from _darwin — the old _harness first-block
   parse was a live bug), ensureCachedInstall (generalizes gepa/_redblue,
   cache-dir naming kept compatible so existing caches keep serving),
   importOptionalLibrary, findLocalPackageDir, makeDegradedEmitter.
   _harness/_darwin/_redblue/gepa are now thin adapters with IDENTICAL
   exported signatures; their genuinely-different parts stay (redblue's
   node-direct isMain workaround, darwin's async streaming for evolve,
   harness's dual binaries). test-graceful-degradation.mjs gains
   RUFLO_METAHARNESS_CACHE_BASE / RUFLO_METAHARNESS_SKIP_LOCAL seams so the
   ADR-150 drill still exercises the degraded path on warm-cache machines.

3. ARCH — smoke.sh derives EXPECTED_TOOLS / EXPECTED_SUBS once from
   metaharness-tools.ts / metaharness.ts and replaces the 7 independently
   hardcoded literals (15 at :750/:829/:2046, 13 at :725/:851, 16 footnote,
   15 success-pattern). Cross-surface value preserved: independent surfaces
   (CLAUDE.md catalog, test-mcp-tools' own `tools.length === 15` literal,
   footnote appends, runScript refs) are compared against the derived count,
   never a surface against itself; a >=15/>=13 floor step catches
   extraction-regex rot.

Validation: smoke.sh 122/122, test-graceful-degradation 16/16,
test-mcp-tools 171/171.

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

* fix(metaharness): add --diagnose GEPA failure diagnosis to evolve

GEPA's key trick — natural-language failure diagnosis from execution traces
feeding the next mutation, not just scalar fitness — scoped modestly into
the evolve wrapper as an opt-in flag.

`evolve.mjs --diagnose` now appends a `diagnosis` section to the emitted
JSON after the run completes: losing/failed variants' transcripts are run
through darwin's gepa `analyzeTranscript` + `classifyFailure` ops (via the
shared importGepa resolver, moved to _darwin.mjs because gepa.mjs runs
main() on import) and aggregated into failure classes + counts + dominant
class per variant.

Upstream shape findings (verified against @metaharness/darwin@0.8.0 with a
tiny mock-sandbox evolve):
- `metaharness-darwin evolve --json` emits a TEXT leaderboard — stdout
  carries no JSON and no transcripts (r.json has always been null here).
- Per-variant run records live at <repo>/.metaharness/runs/<id>.json as
  sandbox exec traces ({taskId, exitCode, stdout, stderr}) — NOT gepa
  {actionRaw, obs} transcripts.
Diagnosis therefore layers: gepa-shaped transcripts when a run record
embeds them (agent sandbox / future upstream) → champion-transcript
fallback → `diagnosis: {available: false, reason, traceSummary}` with a
mechanical per-variant tally. Never fails the run — internal errors
degrade to {available: false, reason: 'diagnosis-failed: ...'}.

Both paths exercised end-to-end: mock evolve yields the traceSummary
fallback; a seeded gepa-shaped run record yields
{available: true, scope: 'losing-variants', failureClasses:
{exploration-loop: 1, edit-mechanics: 1}, dominantClass: 'exploration-loop'}.

Documented in skills/harness-evolve/SKILL.md.

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

* Revert "feat(gaia): submission integrity checklist — fail-closed pre-submit audit (Berkeley RDI hardening)"

This reverts commit af185fcccd.

* fix(hooks): ADR-112 guidance clause on hooks_model-verify description

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

* fix(ci): retune #1921 fix-invariant to the >=2.8.0 OTel override floor

The PR deliberately raised the @opentelemetry/core override from the exact
1.25.1 pin to a >=2.8.0 floor (OTel 2.x audit fix), but the #1921 invariant
in audit-fix-invariants.mjs still asserted the old pin substring, failing
the 'Hook-command install safety (#1921)' job. Per the audit's own guidance,
the invariant is updated to point at the new location of the fix — the
override entry itself — preserving the regression guard (arborist Invalid
Version placeholder) rather than deleting it.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(ci): register RUFLO_METAHARNESS_CACHE_BASE as env-var escape hatch

The metaharness _invoke.mjs consolidation introduced cacheBaseDir(), whose
RUFLO_METAHARNESS_CACHE_BASE read is a CI/test seam for relocating the
~/.ruflo pinned-cache root in smoke tests — there is no CLI-flag surface in
plugin scripts to take precedence. Register it in KNOWN_ESCAPE_HATCHES per
ADR-125/ADR-130 remediation Option B, unblocking the 'Plugin package
install-safety (#1902/#1903/#1904)' job.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(ci): linear-time dash trim in A2A slugify — resolves js/polynomial-redos

CodeQL flagged /^-+|-+$/g in slugify() (agent-card.ts:281) as polynomial
ReDoS: the anchored quantifier backtracks O(n^2) on adversarial all-dash
card names, and card names are remote library input. Replace the trim regex
with an index-scan (charCodeAt) that is strictly linear. Behavior verified
equivalent against the old implementation over edge cases plus 5000-input
fuzz; package typechecks and all 600 tests pass.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(ci): no-metaharness drill uses the _invoke.mjs test seams

The pinned-cache resolution defeats the drill's registry-blackhole absence
simulation (metaharness resolves locally / from the warm ~/.ruflo cache).
RUFLO_METAHARNESS_SKIP_LOCAL=1 + an empty RUFLO_METAHARNESS_CACHE_BASE make
'absent' mean absent again. Reproduced locally: exit 0 + degraded:true.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-07-03 16:52:09 -04:00

419 lines
21 KiB
TypeScript

/**
* Browser Session Lifecycle MCP Tools (ADR-0001 ruflo-browser §7).
*
* Five lifecycle tools that wrap the 23 raw `browser_*` interaction tools
* with RVF cognitive containers, ruvector trajectory recording, AgentDB
* indexing, and AIDefence gates. Implements the contract from
* `plugins/ruflo-browser/docs/adrs/0001-browser-skills-architecture.md`.
*
* Design notes:
* - These tools orchestrate at the *primitive* level — they shell out to
* the existing `agent-browser` CLI (for browser actions), `ruvector` CLI
* (for trajectory hooks + RVF), and the bridged `memory` namespace (for
* AgentDB index). They do not inline a replay engine; replay
* enumerates trajectory steps and returns them for the caller to dispatch.
* - ruvector resolution is local-first: if a locally installed `ruvector`
* package is found (the CLI already depends on ruvector@0.2.27), its bin
* is spawned directly with `node`; otherwise we fall back to
* `npx -y ruvector@0.2.27`. The previous 0.2.25 pin forced cold npx
* downloads of a *second* ruvector version — 4 per browser session.
* - Best-effort: missing dependencies (no `ruvector`, no `agent-browser`,
* no AgentDB controller) degrade gracefully with a structured error
* rather than a process crash.
*/
import type { MCPTool, MCPToolResult } from './types.js';
import { validateIdentifier, validateText } from './validate-input.js';
// Pin matches the version in this package's own dependency tree so the npx
// fallback never downloads a second ruvector. Subcommand surface verified
// against ruvector@0.2.27 --help: `rvf create/compact/status/derive/segments`
// and `hooks trajectory-begin/step/end` all exist with the flags used below.
const RUVECTOR_PIN = 'ruvector@0.2.27';
const RVF_DIR_DEFAULT = '.ruflo/browser-sessions';
interface ShellResult {
success: boolean;
stdout?: string;
stderr?: string;
error?: string;
}
async function shell(cmd: string, args: string[], opts: { timeout?: number } = {}): Promise<ShellResult> {
const { execFile } = await import('node:child_process');
const { promisify } = await import('node:util');
const run = promisify(execFile);
try {
const { stdout, stderr } = await run(cmd, args, {
timeout: opts.timeout ?? 30000,
encoding: 'utf-8',
});
return { success: true, stdout, stderr };
} catch (error) {
const err = error as NodeJS.ErrnoException & { stdout?: string; stderr?: string };
return {
success: false,
error: err.code === 'ENOENT' ? `command not found: ${cmd}` : err.message,
stdout: err.stdout,
stderr: err.stderr,
};
}
}
/**
* Resolve the locally installed ruvector CLI (memoized). Returns the absolute
* path to its bin script, or null when ruvector is not installed locally.
* Spawning `node <bin>` directly avoids the ~2-8s cold `npx -y ruvector@…`
* download that previously hit every ruvector shell-out (4 per session).
*/
let ruvectorCliPromise: Promise<string | null> | null = null;
function resolveLocalRuvectorCli(): Promise<string | null> {
if (ruvectorCliPromise) return ruvectorCliPromise;
ruvectorCliPromise = (async () => {
try {
const { createRequire } = await import('node:module');
const path = await import('node:path');
const { readFile } = await import('node:fs/promises');
const req = createRequire(import.meta.url);
const entry = req.resolve('ruvector');
// Walk up from the resolved entry to the package root (package.json
// itself may not be exported, so we can't require.resolve it directly).
let dir = path.dirname(entry);
for (let i = 0; i < 6; i++) {
try {
const pkg = JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf-8')) as {
name?: string;
bin?: string | Record<string, string>;
};
if (pkg.name === 'ruvector') {
const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.ruvector;
return bin ? path.join(dir, bin) : null;
}
} catch {
// no package.json at this level — keep walking
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
} catch {
// ruvector not installed locally
}
return null;
})();
return ruvectorCliPromise;
}
/** Run a ruvector CLI command: local install first, npx pin as fallback. */
async function ruvector(args: string[], opts: { timeout?: number } = {}): Promise<ShellResult> {
const cli = await resolveLocalRuvectorCli();
if (cli) return shell(process.execPath, [cli, ...args], opts);
return shell('npx', ['-y', RUVECTOR_PIN, ...args], opts);
}
async function ensureSessionsDir(): Promise<string> {
const { mkdir } = await import('node:fs/promises');
const path = await import('node:path');
const dir = path.resolve(process.cwd(), RVF_DIR_DEFAULT);
await mkdir(dir, { recursive: true });
return dir;
}
function makeSessionId(taskSlug: string): string {
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);
const slug = taskSlug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 32) || 'session';
return `${stamp}-${slug}`;
}
function ok(payload: Record<string, unknown>): MCPToolResult {
return { content: [{ type: 'text', text: JSON.stringify({ success: true, ...payload }, null, 2) }] };
}
function fail(error: string, extra: Record<string, unknown> = {}): MCPToolResult {
return {
content: [{ type: 'text', text: JSON.stringify({ success: false, error, ...extra }, null, 2) }],
isError: true,
};
}
export const browserSessionTools: MCPTool[] = [
// ==========================================================================
// browser_session_record — open a recorded session
// ==========================================================================
{
name: 'browser_session_record',
description: 'Open a named, traced browser session: allocate an RVF cognitive container, begin a ruvector trajectory, then open the URL via agent-browser. Returns the session id and rvf path. Use when native WebFetch is wrong because you need real browser automation — JS-heavy SPA scraping, login flows with cookie reuse, replay against DOM-drifted versions, AIDefence PII gating before content reaches Claude. For static HTML pages, native WebFetch is faster and free.',
category: 'browser-session',
tags: ['session', 'rvf', 'trajectory', 'lifecycle'],
inputSchema: {
type: 'object',
properties: {
url: { type: 'string', description: 'Target URL to open' },
task: { type: 'string', description: 'Human-readable task description (recorded in trajectory)' },
session: { type: 'string', description: 'Optional explicit session id; otherwise auto-generated' },
rvf_dir: { type: 'string', description: 'Override the default .ruflo/browser-sessions directory' },
},
required: ['url', 'task'],
},
handler: async (input) => {
const vUrl = validateText(input.url as string, 'url');
if (!vUrl.valid) return fail(vUrl.error || 'invalid url');
const vTask = validateText(input.task as string, 'task');
if (!vTask.valid) return fail(vTask.error || 'invalid task');
const path = await import('node:path');
const explicitSession = input.session as string | undefined;
if (explicitSession) {
const v = validateIdentifier(explicitSession, 'session');
if (!v.valid) return fail(v.error || 'invalid session');
}
const sessionId = explicitSession ?? makeSessionId(input.task as string);
const dir = (input.rvf_dir as string | undefined) ?? (await ensureSessionsDir());
const rvfPath = path.join(dir, `${sessionId}.rvf`);
// 1. RVF allocate.
// Issue #2015: ruvector@0.2.25's `rvf create` accepts only
// `-d/--dimension <n>` (required) and `-m/--metric <metric>`.
// The wrapper previously passed `--kind browser-session` and
// omitted `--dimension`, so commander hit the required-option
// check first and the wrapper returned `rvf create failed` for
// every call. The second round of the fix strips the bogus
// `--kind` flag — when round 1 only added `--dimension`, the
// next call surfaced `error: unknown option '--kind'`.
//
// 384 matches the MiniLM-L6 default used elsewhere in the
// toolchain (ONNX embedder + AgentDB vector indexes).
const rvf = await ruvector(
['rvf', 'create', rvfPath, '--dimension', '384'],
{ timeout: 60000 },
);
if (!rvf.success) return fail('rvf create failed', { detail: rvf.error, stderr: rvf.stderr, sessionId, rvfPath });
// 2. trajectory-begin.
// Flag names verified against ruvector 0.2.25 AND 0.2.27 --help:
// trajectory-begin takes `-c/--context` + `-a/--agent` — the
// `--session-id`/`--task` flags previously passed here were never
// valid on either version (commander exited with "unknown option"),
// so every trajectory call failed. Same bug class as the #2015
// `rvf create --kind` fix documented above. The session id is folded
// into the context string since ruvector tracks a single current
// trajectory per project.
const tb = await ruvector(['hooks', 'trajectory-begin',
'--context', `${sessionId}: ${input.task as string}`,
'--agent', 'browser-session']);
if (!tb.success) return fail('trajectory-begin failed', { detail: tb.error, stderr: tb.stderr, sessionId, rvfPath });
// 3. browser_open via agent-browser
const bo = await shell('agent-browser', ['--session', sessionId, '--json', 'open', input.url as string], { timeout: 30000 });
if (!bo.success) {
const npxBo = await shell('npx', ['--yes', 'agent-browser', '--session', sessionId, '--json', 'open', input.url as string], { timeout: 60000 });
if (!npxBo.success) {
return fail('browser open failed', { detail: npxBo.error, stderr: npxBo.stderr, sessionId, rvfPath });
}
}
// 4. log the open as the first trajectory step.
// trajectory-step takes `--action`/`--result` only (no --session-id /
// --args on 0.2.25 or 0.2.27) — args are folded into the action string.
await ruvector(['hooks', 'trajectory-step',
'--action', `browser_open ${JSON.stringify({ url: input.url })}`,
'--result', 'ok']);
return ok({
sessionId,
rvfPath,
url: input.url,
task: input.task,
ruvectorPin: RUVECTOR_PIN,
});
},
},
// ==========================================================================
// browser_session_end — commit a recorded session
// ==========================================================================
{
name: 'browser_session_end',
description: 'End a recorded browser session: trajectory-end with verdict, rvf compact, AIDefence pre-store gate (best-effort), and AgentDB index in the browser-sessions namespace. Use when native WebFetch is wrong because you need real browser automation — JS-heavy SPA scraping, login flows with cookie reuse, replay against DOM-drifted versions, AIDefence PII gating before content reaches Claude. For static HTML pages, native WebFetch is faster and free.',
category: 'browser-session',
tags: ['session', 'rvf', 'trajectory', 'lifecycle', 'agentdb'],
inputSchema: {
type: 'object',
properties: {
session: { type: 'string', description: 'Session id (returned from browser_session_record)' },
rvf_path: { type: 'string', description: 'Path to the .rvf container' },
verdict: { type: 'string', enum: ['pass', 'fail', 'partial'], description: 'Outcome verdict' },
host: { type: 'string', description: 'Host (for namespace key); inferred from manifest if omitted' },
task: { type: 'string', description: 'Task description (recorded for index)' },
tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags for AgentDB index' },
},
required: ['session', 'rvf_path', 'verdict'],
},
handler: async (input) => {
const vS = validateIdentifier(input.session as string, 'session');
if (!vS.valid) return fail(vS.error || 'invalid session');
const verdict = input.verdict as string;
if (!['pass', 'fail', 'partial'].includes(verdict)) return fail(`invalid verdict: ${verdict}`);
// 1. trajectory-end.
// trajectory-end takes `--success` + `--quality <0-1>` (no
// --session-id / --verdict on 0.2.25 or 0.2.27) — the verdict maps to
// quality: pass=1 (+ --success), partial=0.5, fail=0.
const teArgs = ['hooks', 'trajectory-end',
'--quality', verdict === 'pass' ? '1' : verdict === 'partial' ? '0.5' : '0'];
if (verdict === 'pass') teArgs.push('--success');
const te = await ruvector(teArgs);
if (!te.success) return fail('trajectory-end failed', { detail: te.error, stderr: te.stderr });
// 2. rvf compact
const compact = await ruvector(['rvf', 'compact', input.rvf_path as string]);
if (!compact.success) return fail('rvf compact failed', { detail: compact.error, stderr: compact.stderr });
// 3. AgentDB index — best-effort via memory store (claude-flow bridges)
const indexValue = JSON.stringify({
rvf_id: input.session,
rvf_path: input.rvf_path,
host: input.host ?? null,
task: input.task ?? null,
verdict,
tags: input.tags ?? [],
ended_at: new Date().toISOString(),
});
const idx = await shell('npx', ['-y', '@claude-flow/cli@latest', 'memory', 'store',
'--namespace', 'browser-sessions',
'--key', input.session as string,
'--value', indexValue], { timeout: 60000 });
// Index failure is non-fatal — the RVF container is the source of truth.
return ok({
sessionId: input.session,
rvfPath: input.rvf_path,
verdict,
indexed: idx.success,
indexError: idx.success ? undefined : (idx.stderr || idx.error),
});
},
},
// ==========================================================================
// browser_session_replay — load a trajectory for caller-level dispatch
// ==========================================================================
{
name: 'browser_session_replay',
description: 'Load a recorded session trajectory and return its steps so the caller can dispatch them through the 23 browser_* tools. Does NOT itself drive the browser — replay execution is caller-orchestrated to keep this tool a primitive (ADR-0001 §7). Use when native WebFetch is wrong because you need real browser automation — JS-heavy SPA scraping, login flows with cookie reuse, replay against DOM-drifted versions, AIDefence PII gating before content reaches Claude. For static HTML pages, native WebFetch is faster and free.',
category: 'browser-session',
tags: ['session', 'replay', 'trajectory', 'lifecycle'],
inputSchema: {
type: 'object',
properties: {
session: { type: 'string', description: 'Source session id to replay' },
rvf_path: { type: 'string', description: 'Path to source .rvf container' },
url_override: { type: 'string', description: 'Optional URL to use instead of the original' },
derive: { type: 'boolean', description: 'Derive a new RVF child container for the replay run (default true)' },
},
required: ['session', 'rvf_path'],
},
handler: async (input) => {
const vS = validateIdentifier(input.session as string, 'session');
if (!vS.valid) return fail(vS.error || 'invalid session');
// 1. Verify RVF container exists
const status = await ruvector(['rvf', 'status', input.rvf_path as string]);
if (!status.success) return fail('rvf status failed', { detail: status.error, stderr: status.stderr });
// 2. Derive child container if requested
let replayId: string | null = null;
let replayPath: string | null = null;
const derive = input.derive !== false;
if (derive) {
const path = await import('node:path');
const dir = path.dirname(input.rvf_path as string);
replayId = `${input.session}-replay-${Date.now()}`;
replayPath = path.join(dir, `${replayId}.rvf`);
const dr = await ruvector(['rvf', 'derive', input.rvf_path as string, replayPath]);
if (!dr.success) return fail('rvf derive failed', { detail: dr.error, stderr: dr.stderr });
}
// 3. Surface the trajectory steps from the segments listing — the caller is
// expected to read trajectory.ndjson from the RVF container and dispatch.
const segments = await ruvector(['rvf', 'segments', input.rvf_path as string]);
return ok({
sourceSession: input.session,
sourceRvfPath: input.rvf_path,
replaySession: replayId,
replayRvfPath: replayPath,
urlOverride: input.url_override ?? null,
rvfStatus: status.stdout?.slice(0, 4000) ?? null,
rvfSegments: segments.stdout?.slice(0, 4000) ?? null,
nextStep: 'Caller MUST: (a) read trajectory.ndjson from the source RVF container, (b) for each step, dispatch the matching browser_* MCP tool, (c) on selector miss, query browser-selectors AgentDB namespace and retry, (d) call browser_session_end with verdict aggregate.',
});
},
},
// ==========================================================================
// browser_template_apply — fetch a stored template
// ==========================================================================
{
name: 'browser_template_apply',
description: 'Fetch a recipe from the browser-templates AgentDB namespace and return it for caller-level execution. Use when native WebFetch is wrong because you need real browser automation — JS-heavy SPA scraping, login flows with cookie reuse, replay against DOM-drifted versions, AIDefence PII gating before content reaches Claude. For static HTML pages, native WebFetch is faster and free.',
category: 'browser-session',
tags: ['template', 'agentdb', 'extract'],
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Template name (key in browser-templates namespace)' },
},
required: ['name'],
},
handler: async (input) => {
const vN = validateText(input.name as string, 'name');
if (!vN.valid) return fail(vN.error || 'invalid name');
const r = await shell('npx', ['-y', '@claude-flow/cli@latest', 'memory', 'retrieve',
'--namespace', 'browser-templates',
'--key', input.name as string], { timeout: 60000 });
if (!r.success) return fail('template fetch failed', { detail: r.error, stderr: r.stderr });
return ok({
templateName: input.name,
recipe: r.stdout,
nextStep: 'Caller dispatches the recipe via browser_* tools; persist updated selectors to browser-selectors on success.',
});
},
},
// ==========================================================================
// browser_cookie_use — fetch a vaulted cookie handle
// ==========================================================================
{
name: 'browser_cookie_use',
description: 'Fetch a vault handle for a host from the browser-cookies AgentDB namespace. Raw cookie values are NEVER returned — only the opaque handle plus expiry / AIDefence verdict. Use when native WebFetch is wrong because you need real browser automation — JS-heavy SPA scraping, login flows with cookie reuse, replay against DOM-drifted versions, AIDefence PII gating before content reaches Claude. For static HTML pages, native WebFetch is faster and free.',
category: 'browser-session',
tags: ['cookie', 'agentdb', 'aidefence', 'auth'],
inputSchema: {
type: 'object',
properties: {
host: { type: 'string', description: 'Host (e.g. "example.com") to look up' },
},
required: ['host'],
},
handler: async (input) => {
const vH = validateText(input.host as string, 'host');
if (!vH.valid) return fail(vH.error || 'invalid host');
const r = await shell('npx', ['-y', '@claude-flow/cli@latest', 'memory', 'retrieve',
'--namespace', 'browser-cookies',
'--key', input.host as string], { timeout: 60000 });
if (!r.success) return fail('cookie lookup failed', { detail: r.error, stderr: r.stderr });
// The contract: the value blob includes a vault_handle, expiry, aidefence_verdict.
// Raw values do not enter this namespace (browser-login is responsible).
return ok({
host: input.host,
vault: r.stdout,
nextStep: 'Caller mounts the handle via the browser runner; the raw cookie is materialized only inside the browser process, never returned to the model.',
});
},
},
];
export default browserSessionTools;