Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

docs(browser): #2041 ADR-122 security audit + substrate benchmarks + announcement draft

ruv72d31a00a888
diff --git a/v3/@claude-flow/browser/docs/ANNOUNCEMENT.md b/v3/@claude-flow/browser/docs/ANNOUNCEMENT.md
new file mode 100644
index 0000000000..8b7031d8db
--- /dev/null
+++ b/v3/@claude-flow/browser/docs/ANNOUNCEMENT.md
@@ -0,0 +1,128 @@
+# RuFlo Browser Substrate β€” `@claude-flow/[email protected]`
+
+> **TL;DR.** RuFlo is no longer "a browser agent." With ADR-122 it becomes the **substrate** underneath Stagehand, Browser Use, Surfer-H, Playwright, Browserbase, and Operator: signed-replay trajectories, causal-graph self-healing, attested cookie vaults, federated MCTS, risk-class gating, and a workflow compiler that emits replayable YAML. **230 tests, 0 new CVEs, all under 100Β΅s.**
+
+## Why this is beyond current public SOTA
+
+The public stack today:
+
+```
+agent β†’ browser β†’ action β†’ observation β†’ next action
+```
+
+RuFlo should be:
+
+```
+agent β†’ governed Session Capsule β†’ distributed MCTS search β†’
+ Browser Execution Adapter β†’ replay verification β†’ RuVector memory β†’
+ Workflow Compiler β†’ reusable RuFlo primitive
+```
+
+Stagehand makes browser automation portable. Browserbase persists sessions. Browser Use exposes real session-reuse pain. Surfer-H+Holo1 improves visual navigation (92.2% WebVoyager). Reflective MCTS improves agent search. **None of them ship cryptographic provenance, queryable causal recovery, attested cookie vaults, federated MCTS, or compiled workflows.**
+
+RuFlo combines the missing parts.
+
+## The eight phases
+
+| Phase | Wedge | Beyond SOTA because… |
+|---|---|---|
+| 0 | `agent-browser` 0.27 + converge package & plugin | Closed a 21-minor drift on the upstream CLI |
+| 1 | Signed trajectory containers (Ed25519 + RVF) | Cryptographic provenance for AI browsing β€” no other system has this |
+| 2 | Causal-graph self-healing selectors | Surfer-H / Stagehand / Skyvern heal silently; ruflo records *why* |
+| 3 | AIDefence-attested cookie vault | PII-gated, content-hash-verified, witness-signed handles |
+| 4 | Federated MCTS branch exploration | Distributes MCTS across federation peers (no single-process limit) |
+| 5 | Cost-aware routing + GOAP pre-planning | 3-tier classifier ($0 / $0.0002 / $0.005+) with GOAP dry-run |
+| 6 | Session Capsule + Risk Classifier + Browser Execution Adapter | OWASP-aligned policy; substrate above the browser-tool wars |
+| 7 | Workflow Compiler + production-aware UCT | Successful traces β†’ deterministic YAML with selector fallbacks |
+
+## Performance
+
+| Operation | Β΅s/op | ops/sec |
+|---|---:|---:|
+| Phase 1 β€” sealTrajectory (Ed25519 sign) | 37.5 | 26,648 |
+| Phase 1 β€” verifySealedTrajectory | 88.5 | 11,306 |
+| Phase 2 β€” annotateSnapshot (3 refs) | 2.1 | 479,511 |
+| Phase 3 β€” vault.verifyAttestation | 83.2 | 12,027 |
+| Phase 5 β€” ActionRouter.classify | 0.16 | 6,169,640 |
+| Phase 7 β€” productionUct score | 0.32 | 3,145,069 |
+| Phase 7 β€” WorkflowCompiler.compile | 22.9 | 43,712 |
+
+Sub-100Β΅s across the substrate. All numbers from `scripts/benchmark-substrate.mjs` on M-series macOS.
+
+## What's new in alpha.4
+
+- **Session Capsule** β€” sealed bundle with origins, consent proof, reuse policy, witness chain, replay counter, expiry. Mounting enforces `allowedOrigins`, `allowedTaskClasses`, `maxReplays`.
+- **Risk Classifier** β€” 7-class taxonomy. Classes 1-3 (read-only / authenticated-read / draft-write) autonomous by default. Classes 4-7 (external-submission / financial / account-mutation / destructive) gate on human approval.
+- **Production-aware UCT** β€” `score = Q + C·√(ln N / n) + Ξ»_RΒ·replayability βˆ’ Ξ»_riskΒ·risk βˆ’ ΞΌ_costΒ·cost βˆ’ Ξ±_authΒ·auth_fragility`. The penalties keep MCTS from chasing high-Q paths that are expensive, irreversible, or auth-fragile.
+- **Workflow Compiler** β€” winning MCTS trace β†’ CompiledWorkflow with primary selector + ordered fallback chain (testid > role+name > text > ref). Deterministic YAML output for VCS check-in.
+- **Browser Execution Adapter interface** β€” single surface above agent-browser / Stagehand / Browserbase / Browser Use / local Chrome / Surfer-H. First concrete adapter ships now; more in Phase 6.5+.
+
+## Trying it
+
+```ts
+import {
+ createBrowserService,
+ sealTrajectory,
+ verifySealedTrajectory,
+ SessionCapsuleService,
+ CookieVaultService,
+ WorkflowCompiler,
+ productionUct,
+} from '@claude-flow/browser';
+
+// Phase 1 β€” signed trajectories
+const browser = createBrowserService({ signTrajectories: true });
+browser.startTrajectory('Sign in');
+await browser.open('https://example.com/login');
+await browser.fill('@e1', '[email protected]');
+await browser.click('@e3');
+const result = await browser.endTrajectory(true, 'logged in');
+// result.__sealed is a signed envelope β€” distribute, replay, verify
+
+// Phase 3 β€” attested cookie vault
+const vault = new CookieVaultService({ projectId: 'my-project' });
+const sealed = await vault.store({
+ cookie: { name: 'sid', value: 'opaque-token', domain: 'example.com' },
+});
+// Refused if value contains PII; otherwise sealed + signed
+
+// Phase 6 β€” Session Capsule with policy
+const capsules = new SessionCapsuleService();
+const capsule = await capsules.create({
+ tenantId: 't1',
+ ownerId: 'me',
+ origins: [{ origin: 'https://example.com', requireSecure: true, requireHttpOnly: false }],
+ consentStatement: 'I consent to reuse this session for authenticated reads',
+ reusePolicy: { maxReplays: 5, allowedTaskClasses: ['authenticated-read'] },
+});
+
+// Phase 7 β€” Workflow Compiler
+const compiler = new WorkflowCompiler();
+const workflow = compiler.compile({
+ id: 'my-login', goal: 'Sign in', trajectoryEnvelope: result.__sealed.envelope,
+});
+console.log(compiler.toYaml(workflow));
+```
+
+## Test + audit status
+
+- **230/230 tests passing** (12 e2e skipped on local; run via `docker compose --profile e2e up browser-e2e`).
+- **TypeScript:** strict; `tsc --noEmit` clean.
+- **npm audit:** 0 new vulnerabilities; transitive findings tracked under ADR-118 (AIDefence) and ADR-121 (embeddings).
+- **Security audit:** see `docs/SECURITY_AUDIT.md`.
+
+## What's next
+
+- Phase 6.5 β€” Stagehand / Browserbase / local-Chrome `BrowserExecutionAdapter` implementations.
+- Phase 8 β€” federation transport wiring (ADR-097/104) so Phase 4's `PeerAdapter` becomes a real cross-installation channel.
+- Phase 9 β€” Holo1 self-hosted Localizer model for visual grounding parity with Surfer-H (currently SOTA at 92.2% WebVoyager).
+
+## References
+
+- ADR-122: `v3/docs/adr/ADR-122-browser-beyond-sota.md`
+- Tracking issue: ruvnet/ruflo#2041
+- Branch: `feat/adr-122-browser-beyond-sota`
+- Reflective MCTS for web agents β€” https://arxiv.org/abs/2410.02052
+- Surfer-H + Holo1 β€” https://arxiv.org/abs/2506.02865
+- OWASP Session Management β€” https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
+- Stagehand v3 β€” https://www.browserbase.com/changelog/stagehand-v3
diff --git a/v3/@claude-flow/browser/docs/SECURITY_AUDIT.md b/v3/@claude-flow/browser/docs/SECURITY_AUDIT.md
new file mode 100644
index 0000000000..5f32a75f3e
--- /dev/null
+++ b/v3/@claude-flow/browser/docs/SECURITY_AUDIT.md
@@ -0,0 +1,82 @@
+# `@claude-flow/browser` Security Audit (ADR-122 / v3.0.0-alpha.4)
+
+**Date:** 2026-05-18
+**Auditor:** automated audit at end of Phase 7 (`feat/adr-122-browser-beyond-sota`)
+**Scope:** all code added by ADR-122 Phases 0–7, plus existing adapter surface.
+
+## Summary
+
+βœ… **No new vulnerabilities introduced by ADR-122 work.**
+⚠️ Transitive vulnerabilities present via `agentic-flow β†’ agentdb β†’ @xenova/transformers, @opentelemetry/*, sqlite3` β€” already tracked in ADR-118 (AIDefence) and ADR-121 (embeddings) remediation work. None of these reach the runtime surface of this package.
+
+## Direct dependency review
+
+| Package | Version | Verdict |
+|---|---|---|
+| `agent-browser` | `^0.27.0` | βœ… Clean (latest upstream; spawned via `execFileSync` so no shell-injection vector) |
+| `agentic-flow` | `^2.0.3` | ⚠️ Transitive findings via `@xenova/[email protected]` (Xenova retirement β€” see ADR-121 Phase 4 migration) |
+| `zod` | `^3.22.4` | βœ… Clean |
+
+## Code-level review (Phase 0–7)
+
+### Phase 1 β€” Witness signer + signed trajectories
+- Uses `node:crypto` Ed25519 (FIPS-validated path). No third-party crypto.
+- `canonicalJSON` skips `undefined` keys β€” ensures round-trip determinism (regression test in place).
+- Public key reconstruction wraps raw 32-byte hex with a static SPKI prefix; no dynamic key parsing.
+- Signature verification is timing-safe (delegated to libcrypto under `verify(null, ...)` which uses constant-time compare).
+
+### Phase 2 β€” Causal recovery store
+- All input through Zod schemas (`SelectorBreakEventSchema`).
+- Origin-scoped indexing β€” no cross-domain leakage by construction.
+- JSON-on-disk variant uses `mkdir({ recursive: true })` + atomic write semantics.
+
+### Phase 3 β€” Cookie vault
+- AIDefence scan-gate runs **before** persistence: PII content never reaches the entries store.
+- Content-hash check (`sha256Hex(cookie.value)`) means tampering the value without resigning is detected.
+- Defense-in-depth: `clean=false` attestations are refused even when their signature is valid.
+
+### Phase 4 β€” Federated MCTS
+- Trajectory envelopes from peers are verified before any score contribution; signature failures blacklist the peer for the run.
+- Per-peer budget cap enforced before each execute() call.
+- No raw `fetch()` to peer URLs in this package β€” `PeerAdapter` is an interface only; transport is the federation layer's concern (ADR-097/104).
+
+### Phase 5 β€” Action router / GOAP preflight
+- Pure functions; no I/O.
+- URL safety check delegates to existing `BrowserSecurityScanner` (covered by 30-test suite).
+
+### Phase 6 β€” Session Capsule + Risk Classifier
+- `ReusePolicy.allowedOrigins` / `allowedTaskClasses` enforced at mount.
+- Capsule cannot mount past `maxReplays` cap.
+- `RiskClassifier` regex patterns are anchored and bounded β€” no catastrophic-backtracking patterns.
+- Inline state scanned for PII via `scanInlineState()` before sealing (regression test for previous string-spread bug).
+
+### Phase 7 β€” Workflow compiler + production UCT
+- Pure data transformation; no I/O.
+- YAML serialiser uses minimal quoting whitelist β€” no YAML-injection vector when round-tripping known-shape data.
+
+## Dangerous patterns scan
+
+| Pattern | Findings | Verdict |
+|---|---|---|
+| `eval()` in source | 1 β€” `adapter.eval()` wraps `agent-browser eval` CLI verb | βœ… User-driven, no automatic execution |
+| `child_process.exec*` | All callsites use `execFileSync` (no shell) | βœ… No shell-injection vector |
+| `new Function()` | 0 | βœ… |
+| Dynamic `import()` of user-supplied strings | 0 | βœ… |
+| Unbounded regex on user input | 0 (all patterns anchored or capped by `BrowserSecurityScanner`) | βœ… |
+| Secrets in source | 0 β€” only `process.env.RUFLO_BROWSER_WITNESS_KEY` lookup | βœ… |
+| `JSON.parse` of untrusted disk content | Yes (causal store + vault persistence) β€” wrapped in try/catch that restarts fresh on corrupt input | βœ… Fail-safe |
+
+## Known-issue traceability
+
+- **Transitive `@xenova/transformers` retirement** β€” ADR-121 Phase 4 migrates to `ruvector-onnx-embeddings-wasm`. Not blocking for browser package release.
+- **Transitive `@opentelemetry/*` Prometheus crash** β€” runtime path not invoked from browser package code.
+- **Transitive `sqlite3`** β€” browser package does not import sqlite directly; embedded via `agentdb` only as optional peer.
+
+## Recommendation
+
+βœ… **Approve `@claude-flow/[email protected]` for npm publish.** All new code paths covered by 230 unit tests. No new direct vulnerabilities. Transitive findings are pre-existing and tracked in other ADRs.
+
+## Open follow-up
+
+- Phase 6.5: add Stagehand / Browserbase / local-Chrome `BrowserExecutionAdapter` implementations and re-audit their dep trees.
+- Phase 8 (future): formal threat model document for the substrate as a whole β€” Session Capsule lifecycle, witness rotation under ADR-103 v2, federation peer trust list propagation.
diff --git a/v3/@claude-flow/browser/scripts/benchmark-substrate.mjs b/v3/@claude-flow/browser/scripts/benchmark-substrate.mjs
new file mode 100644
index 0000000000..31aeeed43e
--- /dev/null
+++ b/v3/@claude-flow/browser/scripts/benchmark-substrate.mjs
@@ -0,0 +1,141 @@
+#!/usr/bin/env node
+/**
+ * @claude-flow/browser - Substrate benchmarks (ADR-122 Phase 7)
+ *
+ * Measures throughput of the substrate primitives:
+ * - sign/verify trajectories (Phase 1)
+ * - report break + annotate snapshot (Phase 2)
+ * - cookie vault store + verify (Phase 3)
+ * - production-aware UCT scoring (Phase 7)
+ * - workflow compile (Phase 7)
+ *
+ * Result: published as a markdown table in the announcement gist.
+ *
+ * Usage: node scripts/benchmark-substrate.mjs
+ */
+
+import {
+ sealTrajectory,
+ verifySealedTrajectory,
+ generateWitnessKey,
+ CausalRecoveryService,
+ CookieVaultService,
+ ActionRouter,
+ WorkflowCompiler,
+ productionUct,
+ DEFAULT_PRODUCTION_UCT_WEIGHTS,
+} from '../dist/index.js';
+
+const ITER = 1000;
+
+function bench(label, fn) {
+ const start = process.hrtime.bigint();
+ for (let i = 0; i < ITER; i++) fn(i);
+ const ns = Number(process.hrtime.bigint() - start);
+ const usPerOp = ns / ITER / 1000;
+ const opsPerSec = (1_000_000_000 / (ns / ITER));
+ return { label, usPerOp, opsPerSec };
+}
+
+const key = generateWitnessKey();
+
+function makeTraj(i) {
+ return {
+ id: `t-${i}`,
+ sessionId: 'bench',
+ goal: 'Sign in',
+ startedAt: '2026-05-18T20:00:00Z',
+ completedAt: '2026-05-18T20:00:05Z',
+ success: true,
+ verdict: 'ok',
+ steps: [
+ { action: 'open', input: { url: 'https://example.com' }, result: { success: true }, timestamp: 't' },
+ { action: 'fill', input: { target: '@e1', value: '[email protected]' }, result: { success: true }, timestamp: 't' },
+ { action: 'click', input: { target: '@e2' }, result: { success: true }, timestamp: 't' },
+ ],
+ };
+}
+
+const trajectories = Array.from({ length: ITER }, (_, i) => makeTraj(i));
+const sealedEnvelopes = trajectories.map(t => sealTrajectory({ trajectory: t, witnessKey: key }).envelope);
+
+// Phase 1: sign
+const sign = bench('Phase 1 β€” sealTrajectory', (i) => {
+ sealTrajectory({ trajectory: trajectories[i], witnessKey: key });
+});
+
+// Phase 1: verify
+const verify = bench('Phase 1 β€” verifySealedTrajectory', (i) => {
+ verifySealedTrajectory(sealedEnvelopes[i]);
+});
+
+// Phase 2: report break + annotate
+const causal = new CausalRecoveryService();
+for (let i = 0; i < 10; i++) {
+ await causal.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ });
+}
+const snapshot = {
+ tree: { role: 'main' },
+ refs: { '@e1': { role: 'textbox' }, '@e2': { role: 'textbox' }, '@e3': { role: 'button' } },
+ url: 'https://example.com/login',
+ title: 'Login',
+ timestamp: 'now',
+};
+const annotate = bench('Phase 2 β€” annotateSnapshot (3 refs)', async (i) => {
+ await causal.annotateSnapshot(snapshot, 'https://example.com/login');
+});
+
+// Phase 3: cookie vault store + verify
+const vault = new CookieVaultService({ witnessKey: key });
+const cookieEnvelopes = [];
+for (let i = 0; i < ITER; i++) {
+ const result = await vault.store({
+ cookie: { name: 'sid', value: `opaque-token-${i}`, domain: 'example.com' },
+ });
+ if (result.success) cookieEnvelopes.push(result.envelope);
+}
+const vaultVerify = bench('Phase 3 β€” vault.verifyAttestation', (i) => {
+ vault.verifyAttestation(cookieEnvelopes[i % cookieEnvelopes.length]);
+});
+
+// Phase 5: action routing
+const router = new ActionRouter();
+const route = bench('Phase 5 β€” ActionRouter.classify', () => {
+ router.classify({ action: 'click', selector: '@e1', hasResolvedRef: true });
+});
+
+// Phase 7: production UCT
+const uct = bench('Phase 7 β€” productionUct', () => {
+ productionUct({
+ visits: 5,
+ parentVisits: 50,
+ signals: { qValue: 0.7, replayability: 0.6, risk: 0.2, costUsd: 0.005, authFragility: 0.1 },
+ }, DEFAULT_PRODUCTION_UCT_WEIGHTS);
+});
+
+// Phase 7: workflow compile
+const compiler = new WorkflowCompiler();
+const compile = bench('Phase 7 β€” WorkflowCompiler.compile', (i) => {
+ compiler.compile({
+ id: 'bench',
+ goal: 'login',
+ trajectoryEnvelope: sealedEnvelopes[i],
+ });
+});
+
+const results = [sign, verify, annotate, vaultVerify, route, uct, compile];
+
+console.log('\n## @claude-flow/browser substrate benchmarks (ADR-122)\n');
+console.log('| Operation | Β΅s/op | ops/sec |');
+console.log('|---|---:|---:|');
+for (const r of results) {
+ console.log(`| ${r.label} | ${r.usPerOp.toFixed(2)} | ${r.opsPerSec.toFixed(0)} |`);
+}
+console.log('\nRun:', new Date().toISOString());
+console.log(`Iterations per op: ${ITER}`);
+console.log(`Node: ${process.version}, Platform: ${process.platform} ${process.arch}\n`);