π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(browser): #2041 ADR-122 Phase 0 + Phase 1 β agent-browser 0.27 + signed trajectories
ruv5fedd1d0222f
diff --git a/v3/@claude-flow/browser/package-lock.json b/v3/@claude-flow/browser/package-lock.jsonnew file mode 100644index 0000000000..2d8d123a60--- /dev/null+++ b/v3/@claude-flow/browser/package-lock.json@@ -0,0 +1,336 @@+{+ "name": "@claude-flow/browser",+ "version": "3.0.0-alpha.4",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@claude-flow/browser",+ "version": "3.0.0-alpha.4",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "agent-browser": "^0.27.0",+ "agentic-flow": "^2.0.3",+ "zod": "^3.22.4"+ },+ "devDependencies": {+ "@types/node": "^20.10.0",+ "typescript": "^5.3.0",+ "vitest": "^4.0.16"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "@claude-flow/cli": ">=3.5.0"+ }+ },+ "../../node_modules/.pnpm/@[email protected]_@[email protected][email protected]/node_modules/@claude-flow/cli": {+ "version": "3.6.30",+ "extraneous": true,+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "@claude-flow/mcp": "^3.0.0-alpha.8",+ "@claude-flow/shared": "^3.0.0-alpha.7",+ "@noble/ed25519": "^2.1.0",+ "@ruvector/rabitq-wasm": "^0.1.0",+ "semver": "^7.6.0"+ },+ "bin": {+ "claude-flow": "bin/cli.js",+ "claude-flow-mcp": "bin/mcp-server.js",+ "cli": "bin/cli.js"+ },+ "devDependencies": {+ "typescript": "^5.3.0",+ "vitest": "^4.0.16"+ },+ "optionalDependencies": {+ "@claude-flow/aidefence": "^3.0.2",+ "@claude-flow/codex": "^3.0.0-alpha.8",+ "@claude-flow/embeddings": "^3.0.0-alpha.12",+ "@claude-flow/guidance": "^3.0.0-alpha.1",+ "@claude-flow/memory": "^3.0.0-alpha.12",+ "@claude-flow/plugin-gastown-bridge": "^0.1.3",+ "@claude-flow/security": "^3.0.0-alpha.1",+ "@ruvector/attention": "^0.1.32",+ "@ruvector/attention-darwin-arm64": "0.1.32",+ "@ruvector/diskann": "^0.1.0",+ "@ruvector/learning-wasm": "^0.1.29",+ "@ruvector/router": "^0.1.30",+ "@ruvector/ruvllm-wasm": "^2.0.2",+ "@ruvector/rvagent-wasm": "^0.1.0",+ "@ruvector/sona": "^0.1.5",+ "agentdb": "^3.0.0-alpha.11",+ "agentic-flow": "^3.0.0-alpha.1"+ }+ },+ "../../node_modules/.pnpm/@[email protected]/node_modules/@types/node": {+ "version": "20.19.27",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "../../node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/agentic-flow": {+ "version": "2.0.3",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "@anthropic-ai/claude-agent-sdk": "^0.1.5",+ "@anthropic-ai/sdk": "^0.65.0",+ "@google/genai": "^1.22.0",+ "@ruvector/core": "^0.1.29",+ "@ruvector/edge-full": "^0.1.0",+ "@ruvector/router": "^0.1.25",+ "@ruvector/ruvllm": "^0.2.3",+ "@ruvector/tiny-dancer": "^0.1.15",+ "@supabase/supabase-js": "^2.78.0",+ "@xenova/transformers": "^2.17.2",+ "axios": "^1.12.2",+ "dotenv": "^16.4.5",+ "express": "^5.1.0",+ "fastmcp": "^3.19.0",+ "glob": "^13.0.0",+ "gun": "^0.2020.1241",+ "http-proxy-middleware": "^3.0.5",+ "ruvector": "^0.1.85",+ "ruvector-onnx-embeddings-wasm": "^0.1.2",+ "tiktoken": "^1.0.22",+ "ulid": "^3.0.1",+ "ws": "^8.18.3",+ "yaml": "^2.8.1",+ "zod": "^3.25.76"+ },+ "bin": {+ "agentdb": "dist/agentdb/cli/agentdb-cli.js",+ "agentic-flow": "dist/cli-proxy.js"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.13",+ "@types/express": "^5.0.3",+ "@types/node": "^20.19.19",+ "@types/uuid": "^11.0.0",+ "@types/ws": "^8.18.1",+ "@vitest/coverage-v8": "^4.0.14",+ "patch-package": "^8.0.1",+ "tsx": "^4.19.0",+ "typescript": "^5.6.3",+ "vitest": "^4.0.14"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@ruvector/attention": "^0.1.4",+ "@ruvector/sona": "^0.1.4",+ "agentdb": "^2.0.0-alpha.3.4",+ "better-sqlite3": "^11.10.0",+ "onnxruntime-node": "^1.23.2",+ "sharp": "^0.32.6",+ "sql.js": "^1.11.0"+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/typescript": {+ "version": "5.9.3",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "devDependencies": {+ "@dprint/formatter": "^0.4.1",+ "@dprint/typescript": "0.93.4",+ "@esfx/canceltoken": "^1.0.0",+ "@eslint/js": "^9.20.0",+ "@octokit/rest": "^21.1.1",+ "@types/chai": "^4.3.20",+ "@types/diff": "^7.0.1",+ "@types/minimist": "^1.2.5",+ "@types/mocha": "^10.0.10",+ "@types/ms": "^0.7.34",+ "@types/node": "latest",+ "@types/source-map-support": "^0.5.10",+ "@types/which": "^3.0.4",+ "@typescript-eslint/rule-tester": "^8.24.1",+ "@typescript-eslint/type-utils": "^8.24.1",+ "@typescript-eslint/utils": "^8.24.1",+ "azure-devops-node-api": "^14.1.0",+ "c8": "^10.1.3",+ "chai": "^4.5.0",+ "chokidar": "^4.0.3",+ "diff": "^7.0.0",+ "dprint": "^0.49.0",+ "esbuild": "^0.25.0",+ "eslint": "^9.20.1",+ "eslint-formatter-autolinkable-stylish": "^1.4.0",+ "eslint-plugin-regexp": "^2.7.0",+ "fast-xml-parser": "^4.5.2",+ "glob": "^10.4.5",+ "globals": "^15.15.0",+ "hereby": "^1.10.0",+ "jsonc-parser": "^3.3.1",+ "knip": "^5.44.4",+ "minimist": "^1.2.8",+ "mocha": "^10.8.2",+ "mocha-fivemat-progress-reporter": "^0.1.0",+ "monocart-coverage-reports": "^2.12.1",+ "ms": "^2.1.3",+ "picocolors": "^1.1.1",+ "playwright": "^1.50.1",+ "source-map-support": "^0.5.21",+ "tslib": "^2.8.1",+ "typescript": "^5.7.3",+ "typescript-eslint": "^8.24.1",+ "which": "^3.0.1"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]/node_modules/vitest": {+ "version": "4.0.16",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/expect": "4.0.16",+ "@vitest/mocker": "4.0.16",+ "@vitest/pretty-format": "4.0.16",+ "@vitest/runner": "4.0.16",+ "@vitest/snapshot": "4.0.16",+ "@vitest/spy": "4.0.16",+ "@vitest/utils": "4.0.16",+ "es-module-lexer": "^1.7.0",+ "expect-type": "^1.2.2",+ "magic-string": "^0.30.21",+ "obug": "^2.1.1",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.3",+ "std-env": "^3.10.0",+ "tinybench": "^2.9.0",+ "tinyexec": "^1.0.2",+ "tinyglobby": "^0.2.15",+ "tinyrainbow": "^3.0.3",+ "vite": "^6.0.0 || ^7.0.0",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "devDependencies": {+ "@antfu/install-pkg": "^1.1.0",+ "@edge-runtime/vm": "^5.0.0",+ "@jridgewell/trace-mapping": "0.3.31",+ "@opentelemetry/api": "^1.9.0",+ "@sinonjs/fake-timers": "14.0.0",+ "@types/estree": "^1.0.8",+ "@types/istanbul-lib-coverage": "^2.0.6",+ "@types/istanbul-reports": "^3.0.4",+ "@types/jsdom": "^27.0.0",+ "@types/node": "^24.10.1",+ "@types/picomatch": "^4.0.2",+ "@types/prompts": "^2.4.9",+ "@types/sinonjs__fake-timers": "^8.1.5",+ "acorn-walk": "^8.3.4",+ "birpc": "^4.0.0",+ "cac": "^6.7.14",+ "empathic": "^2.0.0",+ "flatted": "^3.3.3",+ "happy-dom": "^20.0.11",+ "jsdom": "^27.2.0",+ "local-pkg": "^1.1.2",+ "mime": "^4.1.0",+ "prompts": "^2.4.2",+ "strip-literal": "^3.1.0",+ "ws": "^8.18.3"+ },+ "engines": {+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@opentelemetry/api": "^1.9.0",+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",+ "@vitest/browser-playwright": "4.0.16",+ "@vitest/browser-preview": "4.0.16",+ "@vitest/browser-webdriverio": "4.0.16",+ "@vitest/ui": "4.0.16",+ "happy-dom": "*",+ "jsdom": "*"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@opentelemetry/api": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser-playwright": {+ "optional": true+ },+ "@vitest/browser-preview": {+ "optional": true+ },+ "@vitest/browser-webdriverio": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ }+ }+ },+ "../../node_modules/.pnpm/[email protected]/node_modules/zod": {+ "version": "3.25.76",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/@types/node": {+ "resolved": "../../node_modules/.pnpm/@[email protected]/node_modules/@types/node",+ "link": true+ },+ "node_modules/agent-browser": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/agent-browser/-/agent-browser-0.27.0.tgz",+ "integrity": "sha512-mmHzVsYFVA6nshNNGJzg83aVMgKpf4h98ytY3pvtJB1Cot0ZyA2bfnkbSngGD56Azkj+GlhVH6qx9DfKOVE0yg==",+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "bin": {+ "agent-browser": "bin/agent-browser.js"+ }+ },+ "node_modules/agentic-flow": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/agentic-flow",+ "link": true+ },+ "node_modules/typescript": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/typescript",+ "link": true+ },+ "node_modules/vitest": {+ "resolved": "../../node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]/node_modules/vitest",+ "link": true+ },+ "node_modules/zod": {+ "resolved": "../../node_modules/.pnpm/[email protected]/node_modules/zod",+ "link": true+ }+ }+}diff --git a/v3/@claude-flow/browser/package.json b/v3/@claude-flow/browser/package.jsonindex 86aeee98fe..09c6de6b8a 100644--- a/v3/@claude-flow/browser/package.json+++ b/v3/@claude-flow/browser/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/browser",- "version": "3.0.0-alpha.3",+ "version": "3.0.0-alpha.4","description": "Browser automation for AI agents - integrates agent-browser with claude-flow swarms","type": "module","main": "dist/index.js",@@ -22,7 +22,7 @@"postinstall": "node -e \"const{execSync}=require('child_process');try{execSync('agent-browser --version',{stdio:'ignore'});}catch{console.log('\\nπ¦ Installing agent-browser globally...');try{execSync('npm install -g agent-browser@latest',{stdio:'inherit'});console.log('β agent-browser installed successfully!');}catch(e){console.log('β οΈ Could not install agent-browser globally. Run manually:\\n npm install -g agent-browser@latest');}}\""},"dependencies": {- "agent-browser": "^0.6.0",+ "agent-browser": "^0.27.0","agentic-flow": "^2.0.3","zod": "^3.22.4"},diff --git a/v3/@claude-flow/browser/src/application/browser-service.ts b/v3/@claude-flow/browser/src/application/browser-service.tsindex 6efb7e3282..732f86cd0b 100644--- a/v3/@claude-flow/browser/src/application/browser-service.ts+++ b/v3/@claude-flow/browser/src/application/browser-service.ts@@ -6,6 +6,8 @@import { AgentBrowserAdapter } from '../infrastructure/agent-browser-adapter.js';import { createMemoryManager, type BrowserMemoryManager } from '../infrastructure/memory-integration.js';import { getSecurityScanner, type BrowserSecurityScanner, type ThreatScanResult } from '../infrastructure/security-integration.js';+import { sealTrajectory, type SealedTrajectory } from './signed-trajectory-service.js';+import type { WitnessKey } from '../infrastructure/witness-signer.js';import type {Snapshot,SnapshotOptions,@@ -42,6 +44,12 @@ export interface BrowserServiceConfig extends Partial<BrowserAgentConfig> {requireHttps?: boolean;blockedDomains?: string[];allowedDomains?: string[];+ /** ADR-122 Phase 1: sign every completed trajectory with Ed25519 witness. */+ signTrajectories?: boolean;+ /** Override the witness key (else resolved from RUFLO_BROWSER_WITNESS_KEY or generated). */+ witnessKey?: WitnessKey;+ /** Project ID embedded in signed envelopes (federation trust boundary). */+ projectId?: string;}export class BrowserService {@@ -116,16 +124,25 @@ export class BrowserService {}/**- * End trajectory and return for learning (also stores in memory)+ * End trajectory and return for learning (also stores in memory).+ *+ * When `signTrajectories: true` is configured, the completed trajectory is+ * also sealed into an Ed25519-signed envelope (ADR-122 Phase 1). The signed+ * envelope is attached to the returned object as `__sealed` so callers can+ * persist it to disk or distribute via federation.*/- async endTrajectory(success: boolean, verdict?: string): Promise<BrowserTrajectory | null> {+ async endTrajectory(success: boolean, verdict?: string): Promise<(BrowserTrajectory & { __sealed?: SealedTrajectory }) | null> {if (!this.currentTrajectory) return null;const trajectory = activeTrajectories.get(this.currentTrajectory);if (!trajectory) return null;const completed: BrowserTrajectory = {- ...trajectory,+ id: trajectory.id,+ sessionId: trajectory.sessionId,+ goal: trajectory.goal,+ steps: trajectory.steps,+ startedAt: trajectory.startedAt,completedAt: new Date().toISOString(),success,verdict,@@ -139,7 +156,17 @@ export class BrowserService {activeTrajectories.delete(this.currentTrajectory);this.currentTrajectory = undefined;- return completed;+ // ADR-122 Phase 1: optionally seal the trajectory.+ let sealed: SealedTrajectory | undefined;+ if (this.config.signTrajectories) {+ sealed = sealTrajectory({+ trajectory: completed,+ witnessKey: this.config.witnessKey,+ projectId: this.config.projectId,+ });+ }++ return sealed ? { ...completed, __sealed: sealed } : completed;}/**diff --git a/v3/@claude-flow/browser/src/application/signed-trajectory-service.ts b/v3/@claude-flow/browser/src/application/signed-trajectory-service.tsnew file mode 100644index 0000000000..cd8591bc70--- /dev/null+++ b/v3/@claude-flow/browser/src/application/signed-trajectory-service.ts@@ -0,0 +1,210 @@+/**+ * @claude-flow/browser - Signed Trajectory Service (ADR-122 Phase 1)+ *+ * High-level API for sealing a recorded BrowserTrajectory into a portable,+ * Ed25519-signed envelope and for verifying / replaying received envelopes.+ *+ * Phase 1 ships a JSON-on-disk container; Phase 1.5 will swap the on-disk+ * format for the binary RVF format from `@ruvector/[email protected]` once we have+ * a working dependency story for it.+ */++import { readFile, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { resolve as resolvePath } from 'node:path';+import {+ signTrajectory,+ verifyTrajectory,+ resolveWitnessKey,+ sha256Hex,+ type WitnessKey,+} from '../infrastructure/witness-signer.js';+import type { BrowserTrajectory, Snapshot } from '../domain/types.js';+import type {+ SignedTrajectoryEnvelope,+ VerificationResult,+ ReplayDelta,+ ReplayMutation,+} from '../domain/signed-trajectory.js';++export interface SealTrajectoryInput {+ trajectory: BrowserTrajectory;+ /** Project / installation ID. Falls back to env or 'unknown'. */+ projectId?: string;+ /** Optional final accessibility snapshot. */+ finalSnapshot?: Snapshot;+ /** Per-screenshot content. Keys are paths or step IDs; values are buffers. Hashes are computed. */+ screenshots?: Record<string, Buffer>;+ /** Override witness key (tests / advanced callers). */+ witnessKey?: WitnessKey;+ /** When sealed (test determinism). Defaults to now. */+ sealedAt?: string;+ /** Parent trajectory ID for replay deltas. */+ parentTrajectoryId?: string;+}++export interface SealedTrajectory {+ envelope: SignedTrajectoryEnvelope;+ publicKeyHex: string;+}++/** Seal a trajectory into a signed envelope. */+export function sealTrajectory(input: SealTrajectoryInput): SealedTrajectory {+ const key = input.witnessKey ?? resolveWitnessKey();+ const screenshotHashes: Record<string, string> = {};+ for (const [path, buf] of Object.entries(input.screenshots ?? {})) {+ screenshotHashes[path] = sha256Hex(buf);+ }++ const envelope = signTrajectory(+ {+ trajectoryId: input.trajectory.id,+ projectId: input.projectId ?? process.env.RUFLO_PROJECT_ID ?? 'unknown',+ trajectory: {+ id: input.trajectory.id,+ sessionId: input.trajectory.sessionId,+ goal: input.trajectory.goal,+ steps: input.trajectory.steps,+ startedAt: input.trajectory.startedAt,+ completedAt: input.trajectory.completedAt,+ success: input.trajectory.success,+ verdict: input.trajectory.verdict,+ },+ screenshotHashes,+ finalSnapshot: input.finalSnapshot,+ parentTrajectoryId: input.parentTrajectoryId,+ },+ key,+ { sealedAt: input.sealedAt },+ );++ return { envelope, publicKeyHex: key.publicKeyHex };+}++/** Write a signed envelope to disk. */+export async function writeSealedTrajectory(+ envelope: SignedTrajectoryEnvelope,+ path: string,+): Promise<void> {+ await writeFile(resolvePath(path), JSON.stringify(envelope, null, 2), 'utf8');+}++/** Read a signed envelope from disk. */+export async function readSealedTrajectory(path: string): Promise<SignedTrajectoryEnvelope> {+ if (!existsSync(path)) throw new Error('trajectory envelope not found: ' + path);+ const raw = await readFile(resolvePath(path), 'utf8');+ return JSON.parse(raw) as SignedTrajectoryEnvelope;+}++/** Verify a sealed envelope. Thin wrapper that allows trust-list filtering. */+export function verifySealedTrajectory(+ envelope: unknown,+ options: { trustedPublicKeys?: string[] } = {},+): VerificationResult {+ return verifyTrajectory(envelope, options);+}++/**+ * Compute the replay plan from a sealed envelope + mutations.+ *+ * Phase 1 deliberately returns a plan rather than executing β the executor+ * needs a live BrowserService and is wired in BrowserService.replayFromEnvelope.+ * This keeps the signing/replay logic browser-engine-independent so it can be+ * unit-tested without spawning Playwright.+ */+export function planReplay(+ envelope: SignedTrajectoryEnvelope,+ mutations: ReplayMutation = {},+): {+ steps: Array<{+ index: number;+ action: string;+ input: Record<string, unknown>;+ /** True iff the original recorded this step as successful. */+ parentSucceeded: boolean;+ }>;+ goal: string;+ parentTrajectoryId: string;+} {+ const parent = envelope.payload.trajectory;+ const skipSet = new Set(mutations.skipSteps ?? []);+ const overrides = mutations.replaceStepInput ?? {};++ // Phase 1: trajectory steps are typed as unknown[] (preserves cross-version compat);+ // pick out the bits we actually need for planning.+ const steps = (parent.steps as Array<Record<string, unknown>>)+ .map((step, index) => {+ if (skipSet.has(index)) return null;+ const baseInput = (step.input ?? {}) as Record<string, unknown>;+ const override = overrides[index] ?? {};+ return {+ index,+ action: String(step.action ?? 'unknown'),+ input: { ...baseInput, ...override },+ parentSucceeded: Boolean((step.result as Record<string, unknown> | undefined)?.success ?? true),+ };+ })+ .filter((s): s is NonNullable<typeof s> => s !== null);++ return {+ steps,+ goal: mutations.goal ?? parent.goal,+ parentTrajectoryId: parent.id,+ };+}++/**+ * Compute a delta between an original sealed trajectory and a fresh replay.+ *+ * Both must reference the same goal+parent. The delta tells you which steps+ * still produce the same outcome under replay and which have diverged β+ * the foundation of visual-regression / "did this site change?" CI gates.+ */+export function buildReplayDelta(+ envelope: SignedTrajectoryEnvelope,+ newTrajectory: BrowserTrajectory,+): ReplayDelta {+ const parentSteps = envelope.payload.trajectory.steps as Array<Record<string, unknown>>;+ const newSteps = newTrajectory.steps as unknown as Array<Record<string, unknown>>;++ const stepResults: ReplayDelta['stepResults'] = [];+ const len = Math.max(parentSteps.length, newSteps.length);+ for (let i = 0; i < len; i++) {+ const parent = parentSteps[i];+ const next = newSteps[i];+ const parentAction = String(parent?.action ?? 'missing');+ const replayAction = String(next?.action ?? 'missing');+ const parentSuccess = Boolean((parent?.result as Record<string, unknown> | undefined)?.success ?? true);+ const replaySuccess = Boolean((next?.result as Record<string, unknown> | undefined)?.success ?? true);+ const matched = parentAction === replayAction && parentSuccess === replaySuccess;+ stepResults.push({+ index: i,+ parentAction,+ replayAction,+ matched,+ note: matched ? undefined : describeDivergence(parent, next),+ });+ }++ return {+ parentTrajectoryId: envelope.payload.trajectory.id,+ newTrajectory,+ stepResults,+ allMatched: stepResults.every(s => s.matched),+ };+}++function describeDivergence(+ parent: Record<string, unknown> | undefined,+ next: Record<string, unknown> | undefined,+): string {+ if (!parent) return 'extra step in replay';+ if (!next) return 'missing step in replay';+ const parentAction = String(parent.action ?? 'unknown');+ const nextAction = String(next.action ?? 'unknown');+ if (parentAction !== nextAction) return `action drift: ${parentAction} β ${nextAction}`;+ const parentOk = Boolean((parent.result as Record<string, unknown> | undefined)?.success ?? true);+ const nextOk = Boolean((next.result as Record<string, unknown> | undefined)?.success ?? true);+ if (parentOk !== nextOk) return `outcome drift: parent=${parentOk}, replay=${nextOk}`;+ return 'unspecified divergence';+}diff --git a/v3/@claude-flow/browser/src/domain/signed-trajectory.ts b/v3/@claude-flow/browser/src/domain/signed-trajectory.tsnew file mode 100644index 0000000000..df4f02c4ee--- /dev/null+++ b/v3/@claude-flow/browser/src/domain/signed-trajectory.ts@@ -0,0 +1,98 @@+/**+ * @claude-flow/browser - Signed Trajectory Container (ADR-122 Phase 1)+ *+ * Combines RVF trajectory envelope + Ed25519 witness signature to produce a+ * portable, verifiable browser-session artifact. No SOTA web agent ships+ * cryptographic provenance for AI browsing β this is the beyond-SOTA wedge.+ */++import { z } from 'zod';+import type { BrowserTrajectory } from './types.js';++/** Container envelope version. Bump when shape changes incompatibly. */+export const SIGNED_TRAJECTORY_ENVELOPE_VERSION = '1.0.0';++/** Magic identifier so verifiers can refuse non-trajectory containers. */+export const SIGNED_TRAJECTORY_KIND = 'browser-trajectory';++export const SignedTrajectoryPayloadSchema = z.object({+ envelopeVersion: z.literal(SIGNED_TRAJECTORY_ENVELOPE_VERSION),+ kind: z.literal(SIGNED_TRAJECTORY_KIND),+ /** Stable trajectory ID (matches BrowserTrajectory.id). */+ trajectoryId: z.string().min(1),+ /** Project/installation identifier for federation trust boundary. */+ projectId: z.string().min(1),+ /** Ed25519 public key (hex) of the signer for verifier convenience. */+ publicKey: z.string().regex(/^[0-9a-f]{64}$/, 'public key must be 64 hex chars'),+ /** Trajectory itself β steps + verdict + timing. */+ trajectory: z.object({+ id: z.string(),+ sessionId: z.string(),+ goal: z.string(),+ steps: z.array(z.unknown()),+ startedAt: z.string(),+ completedAt: z.string().optional(),+ success: z.boolean().optional(),+ verdict: z.string().optional(),+ }),+ /** Content hashes of screenshots referenced by steps (path β sha256 hex). */+ screenshotHashes: z.record(z.string().regex(/^[0-9a-f]{64}$/)),+ /** Final snapshot at endTrajectory β deterministic enough to drive replay. */+ finalSnapshot: z.unknown().optional(),+ /** When this envelope was sealed. */+ sealedAt: z.string(),+ /** Causal parent β if this is a replay-delta, points to the source trajectory ID. */+ parentTrajectoryId: z.string().optional(),+});++export type SignedTrajectoryPayload = z.infer<typeof SignedTrajectoryPayloadSchema>;++export const SignedTrajectoryEnvelopeSchema = z.object({+ payload: SignedTrajectoryPayloadSchema,+ /** Ed25519 signature (hex) over the canonical-JSON-stringified payload. */+ signature: z.string().regex(/^[0-9a-f]{128}$/, 'signature must be 128 hex chars'),+ /** Algorithm tag for future-proofing. Today only ed25519. */+ algorithm: z.literal('ed25519'),+});++export type SignedTrajectoryEnvelope = z.infer<typeof SignedTrajectoryEnvelopeSchema>;++/** Result of verifying an envelope. */+export interface VerificationResult {+ valid: boolean;+ /** True iff signature checks out AND payload schema passes. */+ signatureValid: boolean;+ schemaValid: boolean;+ /** Public key the envelope was signed with (for trust-list checks). */+ publicKey?: string;+ /** Why verification failed. Populated only when valid === false. */+ reason?: string;+}++/** Options for replay-with-mutation. */+export interface ReplayMutation {+ /** Replace step inputs by index β e.g. swap a URL or a fill value. */+ replaceStepInput?: Record<number, Record<string, unknown>>;+ /** Skip step indexes entirely (e.g. for shorter replay scenarios). */+ skipSteps?: number[];+ /** Override the trajectory goal (informational only). */+ goal?: string;+}++/** Result returned by replay() β points back to the original signed envelope. */+export interface ReplayDelta {+ /** Trajectory that was replayed. */+ parentTrajectoryId: string;+ /** New trajectory produced by replay; can itself be signed. */+ newTrajectory: BrowserTrajectory;+ /** Per-step verdict β did the replay step succeed against the same target? */+ stepResults: Array<{+ index: number;+ parentAction: string;+ replayAction: string;+ matched: boolean;+ note?: string;+ }>;+ /** True iff every replayed step matched the original outcome. */+ allMatched: boolean;+}diff --git a/v3/@claude-flow/browser/src/index.ts b/v3/@claude-flow/browser/src/index.tsindex b54379157d..ae0e98bd4d 100644--- a/v3/@claude-flow/browser/src/index.ts+++ b/v3/@claude-flow/browser/src/index.ts@@ -110,6 +110,39 @@ export {type BrowserServiceConfig,} from './application/browser-service.js';+// Signed trajectory containers (ADR-122 Phase 1)+export {+ sealTrajectory,+ verifySealedTrajectory,+ writeSealedTrajectory,+ readSealedTrajectory,+ planReplay,+ buildReplayDelta,+ type SealTrajectoryInput,+ type SealedTrajectory,+} from './application/signed-trajectory-service.js';+export {+ generateWitnessKey,+ loadWitnessKey,+ resolveWitnessKey,+ signTrajectory,+ verifyTrajectory,+ canonicalJSON,+ sha256Hex,+ type WitnessKey,+} from './infrastructure/witness-signer.js';+export {+ SIGNED_TRAJECTORY_ENVELOPE_VERSION,+ SIGNED_TRAJECTORY_KIND,+ SignedTrajectoryEnvelopeSchema,+ SignedTrajectoryPayloadSchema,+ type SignedTrajectoryEnvelope,+ type SignedTrajectoryPayload,+ type VerificationResult,+ type ReplayDelta,+ type ReplayMutation,+} from './domain/signed-trajectory.js';+// MCP toolsexport { browserTools } from './mcp-tools/browser-tools.js';export type { MCPTool } from './mcp-tools/browser-tools.js';diff --git a/v3/@claude-flow/browser/src/infrastructure/witness-signer.ts b/v3/@claude-flow/browser/src/infrastructure/witness-signer.tsnew file mode 100644index 0000000000..13c5a35cd2--- /dev/null+++ b/v3/@claude-flow/browser/src/infrastructure/witness-signer.ts@@ -0,0 +1,186 @@+/**+ * @claude-flow/browser - Witness Signer (ADR-122 Phase 1)+ *+ * Ed25519 signing/verification for browser trajectory envelopes.+ * Uses node:crypto (no new deps) which supports Ed25519 natively on node 20+.+ *+ * In Phase 3+ this delegates to the project-level witness manifest key+ * (ADR-103) so trajectories carry the same root-of-trust as the fix manifest.+ * For Phase 1 we accept either an explicit key (tests, ephemeral) or a+ * project-keyed witness via the `RUFLO_BROWSER_WITNESS_KEY` env var.+ */++import { createPrivateKey, createPublicKey, sign, verify, generateKeyPairSync } from 'node:crypto';+import { createHash } from 'node:crypto';+import type { KeyObject } from 'node:crypto';+import {+ SIGNED_TRAJECTORY_ENVELOPE_VERSION,+ SIGNED_TRAJECTORY_KIND,+ SignedTrajectoryEnvelopeSchema,+ SignedTrajectoryPayloadSchema,+ type SignedTrajectoryEnvelope,+ type SignedTrajectoryPayload,+ type VerificationResult,+} from '../domain/signed-trajectory.js';++export interface WitnessKey {+ /** Ed25519 private key (KeyObject). */+ privateKey: KeyObject;+ /** Ed25519 public key (KeyObject). */+ publicKey: KeyObject;+ /** Public key as hex (32 bytes / 64 hex chars). */+ publicKeyHex: string;+}++/**+ * Canonicalize an object for deterministic signing.+ *+ * Recursively sorts keys so two structurally-equal payloads produce+ * byte-identical strings. Without this, a signature would depend on+ * JSON key insertion order β i.e. would not survive a round-trip+ * through any well-meaning JSON parser.+ */+export function canonicalJSON(value: unknown): string {+ if (value === undefined) return 'null'; // never reached at the top level β child branch handles it+ if (value === null || typeof value !== 'object') return JSON.stringify(value);+ if (Array.isArray(value)) return '[' + value.map(canonicalJSON).join(',') + ']';+ const obj = value as Record<string, unknown>;+ // Drop undefined keys so canonicalization matches what survives JSON.stringify round-trips.+ const keys = Object.keys(obj).filter(k => obj[k] !== undefined).sort();+ return '{' + keys.map(k => JSON.stringify(k) + ':' + canonicalJSON(obj[k])).join(',') + '}';+}++/** Generate a fresh Ed25519 keypair. Useful for tests and first-run setup. */+export function generateWitnessKey(): WitnessKey {+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');+ return {+ privateKey,+ publicKey,+ publicKeyHex: extractPublicKeyHex(publicKey),+ };+}++/** Load a witness key from PEM-encoded strings. */+export function loadWitnessKey(privateKeyPem: string): WitnessKey {+ const privateKey = createPrivateKey(privateKeyPem);+ const publicKey = createPublicKey(privateKey);+ return {+ privateKey,+ publicKey,+ publicKeyHex: extractPublicKeyHex(publicKey),+ };+}++/** Extract the raw 32-byte Ed25519 public key as hex. */+function extractPublicKeyHex(publicKey: KeyObject): string {+ // node's Ed25519 export gives a DER-wrapped key. The last 32 bytes are the+ // raw public key per RFC 8410.+ const der = publicKey.export({ format: 'der', type: 'spki' });+ return der.subarray(der.length - 32).toString('hex');+}++/** SHA-256 hex digest of a buffer or string. */+export function sha256Hex(input: Buffer | string): string {+ return createHash('sha256').update(input).digest('hex');+}++/** Sign a payload, producing a verifiable envelope. */+export function signTrajectory(+ payload: Omit<SignedTrajectoryPayload, 'publicKey' | 'envelopeVersion' | 'kind' | 'sealedAt'>,+ key: WitnessKey,+ options: { sealedAt?: string } = {},+): SignedTrajectoryEnvelope {+ const fullPayload: SignedTrajectoryPayload = {+ envelopeVersion: SIGNED_TRAJECTORY_ENVELOPE_VERSION,+ kind: SIGNED_TRAJECTORY_KIND,+ sealedAt: options.sealedAt ?? new Date().toISOString(),+ publicKey: key.publicKeyHex,+ ...payload,+ };++ // Schema-validate before signing so we never produce a signed-but-malformed envelope.+ const validated = SignedTrajectoryPayloadSchema.parse(fullPayload);+ const canonical = canonicalJSON(validated);+ const signatureBuf = sign(null, Buffer.from(canonical, 'utf8'), key.privateKey);++ return {+ payload: validated,+ signature: signatureBuf.toString('hex'),+ algorithm: 'ed25519',+ };+}++/**+ * Verify an envelope.+ *+ * Returns a structured result rather than throwing β callers (CLI, MCP+ * tools, federation peer ingest) often need to act on the reason.+ */+export function verifyTrajectory(+ envelope: unknown,+ options: { trustedPublicKeys?: string[] } = {},+): VerificationResult {+ // Step 1 β schema check+ const parsed = SignedTrajectoryEnvelopeSchema.safeParse(envelope);+ if (!parsed.success) {+ return {+ valid: false,+ signatureValid: false,+ schemaValid: false,+ reason: 'envelope schema validation failed: ' + parsed.error.issues.map(i => i.path.join('.') + ' ' + i.message).join('; '),+ };+ }++ const { payload, signature } = parsed.data;++ // Step 2 β trust check (if a trust list was supplied)+ if (options.trustedPublicKeys && !options.trustedPublicKeys.includes(payload.publicKey)) {+ return {+ valid: false,+ signatureValid: false,+ schemaValid: true,+ publicKey: payload.publicKey,+ reason: 'signer public key not in trusted list',+ };+ }++ // Step 3 β signature check+ try {+ // Reconstruct a SPKI-wrapped Ed25519 key from the bare 32-byte hex.+ // Ed25519 SPKI DER prefix per RFC 8410: 0x302a300506032b6570032100 (12 bytes), then the 32-byte key.+ const spkiPrefix = Buffer.from('302a300506032b6570032100', 'hex');+ const der = Buffer.concat([spkiPrefix, Buffer.from(payload.publicKey, 'hex')]);+ const publicKey = createPublicKey({ key: der, format: 'der', type: 'spki' });++ const canonical = canonicalJSON(payload);+ const signatureValid = verify(null, Buffer.from(canonical, 'utf8'), publicKey, Buffer.from(signature, 'hex'));++ return {+ valid: signatureValid,+ signatureValid,+ schemaValid: true,+ publicKey: payload.publicKey,+ reason: signatureValid ? undefined : 'signature verification failed (payload may be tampered)',+ };+ } catch (err) {+ return {+ valid: false,+ signatureValid: false,+ schemaValid: true,+ publicKey: payload.publicKey,+ reason: 'signature verification threw: ' + (err instanceof Error ? err.message : String(err)),+ };+ }+}++/**+ * Resolve a witness key from environment or generate an ephemeral one.+ *+ * Phase 1 ergonomics β production callers should pass a key explicitly or+ * point this at the project witness manifest key.+ */+export function resolveWitnessKey(): WitnessKey {+ const envKey = process.env.RUFLO_BROWSER_WITNESS_KEY;+ if (envKey) return loadWitnessKey(envKey);+ return generateWitnessKey();+}diff --git a/v3/@claude-flow/browser/tests/signed-trajectory.test.ts b/v3/@claude-flow/browser/tests/signed-trajectory.test.tsnew file mode 100644index 0000000000..d3776cae87--- /dev/null+++ b/v3/@claude-flow/browser/tests/signed-trajectory.test.ts@@ -0,0 +1,236 @@+/**+ * @claude-flow/browser - Signed Trajectory Tests (ADR-122 Phase 1)+ *+ * Acceptance criteria covered:+ * - Recorded trajectory round-trips through record β sign β distribute β verify+ * - Forging a step (modifying the trajectory JSON in the envelope) fails verification+ * - Tamper-evidence: changing one element ref breaks `verify`+ * - replay plan correctly applies mutations+ */++import { describe, it, expect } from 'vitest';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomBytes } from 'node:crypto';+import {+ sealTrajectory,+ verifySealedTrajectory,+ writeSealedTrajectory,+ readSealedTrajectory,+ planReplay,+ buildReplayDelta,+} from '../src/application/signed-trajectory-service.js';+import { generateWitnessKey, canonicalJSON, sha256Hex } from '../src/infrastructure/witness-signer.js';+import type { BrowserTrajectory } from '../src/domain/types.js';+import type { SignedTrajectoryEnvelope } from '../src/domain/signed-trajectory.js';++function buildTrajectory(overrides: Partial<BrowserTrajectory> = {}): BrowserTrajectory {+ return {+ id: 'traj-test-1',+ sessionId: 'sess-abc',+ goal: 'Login to example.com and read welcome banner',+ startedAt: '2026-05-18T20:00:00.000Z',+ completedAt: '2026-05-18T20:00:05.000Z',+ success: true,+ verdict: 'login succeeded',+ steps: [+ { action: 'open', input: { url: 'https://example.com/login' }, result: { success: true }, timestamp: '2026-05-18T20:00:00.500Z' },+ { action: 'fill', input: { target: '@e1', value: '[email protected]' }, result: { success: true }, timestamp: '2026-05-18T20:00:01.500Z' },+ { action: 'fill', input: { target: '@e2', value: 'hunter2' }, result: { success: true }, timestamp: '2026-05-18T20:00:02.500Z' },+ { action: 'click', input: { target: '@e3' }, result: { success: true }, timestamp: '2026-05-18T20:00:03.500Z' },+ ],+ ...overrides,+ };+}++describe('SignedTrajectoryService', () => {+ describe('canonicalJSON', () => {+ it('produces identical output for structurally-equal objects with different key order', () => {+ const a = { a: 1, b: { c: 2, d: 3 }, e: [1, 2, 3] };+ const b = { e: [1, 2, 3], b: { d: 3, c: 2 }, a: 1 };+ expect(canonicalJSON(a)).toBe(canonicalJSON(b));+ });++ it('preserves array order', () => {+ expect(canonicalJSON([3, 1, 2])).toBe('[3,1,2]');+ });+ });++ describe('seal + verify round-trip', () => {+ it('verifies a freshly sealed trajectory', () => {+ const trajectory = buildTrajectory();+ const key = generateWitnessKey();+ const { envelope } = sealTrajectory({ trajectory, witnessKey: key, projectId: 'test-project' });+ const result = verifySealedTrajectory(envelope);+ expect(result.valid).toBe(true);+ expect(result.signatureValid).toBe(true);+ expect(result.schemaValid).toBe(true);+ expect(result.publicKey).toBe(key.publicKeyHex);+ });++ it('round-trips through writeSealedTrajectory + readSealedTrajectory', async () => {+ const trajectory = buildTrajectory();+ const key = generateWitnessKey();+ const { envelope } = sealTrajectory({ trajectory, witnessKey: key });+ const path = join(tmpdir(), `cf-browser-test-${randomBytes(4).toString('hex')}.rvf.json`);+ await writeSealedTrajectory(envelope, path);+ const reloaded = await readSealedTrajectory(path);+ expect(verifySealedTrajectory(reloaded).valid).toBe(true);+ });++ it('includes sha256 hashes for screenshots', () => {+ const trajectory = buildTrajectory();+ const screenshot = Buffer.from('PNGfake-bytes-for-test', 'utf8');+ const { envelope } = sealTrajectory({+ trajectory,+ screenshots: { 'step-0.png': screenshot },+ });+ const expectedHash = sha256Hex(screenshot);+ expect(envelope.payload.screenshotHashes['step-0.png']).toBe(expectedHash);+ });+ });++ describe('tamper detection', () => {+ it('rejects a forged element ref in a trajectory step', () => {+ const trajectory = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory });++ // Tamper: change @e2's fill value (steal-the-password attack)+ const forged: SignedTrajectoryEnvelope = JSON.parse(JSON.stringify(envelope));+ const step2 = forged.payload.trajectory.steps[2] as Record<string, Record<string, unknown>>;+ step2.input!.value = 'stolen-password';++ const result = verifySealedTrajectory(forged);+ expect(result.valid).toBe(false);+ expect(result.signatureValid).toBe(false);+ expect(result.reason).toMatch(/signature verification failed/);+ });++ it('rejects a forged goal', () => {+ const trajectory = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory });+ const forged: SignedTrajectoryEnvelope = JSON.parse(JSON.stringify(envelope));+ forged.payload.trajectory.goal = 'malicious replacement goal';+ expect(verifySealedTrajectory(forged).valid).toBe(false);+ });++ it('rejects a forged screenshot hash', () => {+ const trajectory = buildTrajectory();+ const { envelope } = sealTrajectory({+ trajectory,+ screenshots: { 'step-0.png': Buffer.from('original') },+ });+ const forged: SignedTrajectoryEnvelope = JSON.parse(JSON.stringify(envelope));+ forged.payload.screenshotHashes['step-0.png'] = sha256Hex('replaced');+ expect(verifySealedTrajectory(forged).valid).toBe(false);+ });++ it('rejects schema-invalid envelopes', () => {+ const result = verifySealedTrajectory({ payload: 'not-an-object', signature: 'x', algorithm: 'ed25519' });+ expect(result.valid).toBe(false);+ expect(result.schemaValid).toBe(false);+ });+ });++ describe('trust list', () => {+ it('rejects envelopes signed by untrusted keys when a trust list is supplied', () => {+ const trajectory = buildTrajectory();+ const stranger = generateWitnessKey();+ const { envelope } = sealTrajectory({ trajectory, witnessKey: stranger });++ const result = verifySealedTrajectory(envelope, { trustedPublicKeys: ['00'.repeat(32)] });+ expect(result.valid).toBe(false);+ expect(result.reason).toMatch(/not in trusted list/);+ });++ it('accepts envelopes signed by trusted keys', () => {+ const trajectory = buildTrajectory();+ const friend = generateWitnessKey();+ const { envelope } = sealTrajectory({ trajectory, witnessKey: friend });+ const result = verifySealedTrajectory(envelope, { trustedPublicKeys: [friend.publicKeyHex] });+ expect(result.valid).toBe(true);+ });+ });++ describe('replay planning', () => {+ it('plans replay with no mutations as a straight copy', () => {+ const trajectory = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory });+ const plan = planReplay(envelope);+ expect(plan.steps).toHaveLength(4);+ expect(plan.goal).toBe(trajectory.goal);+ expect(plan.steps[0].action).toBe('open');+ });++ it('applies replaceStepInput mutations', () => {+ const trajectory = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory });+ const plan = planReplay(envelope, {+ replaceStepInput: { 1: { value: '[email protected]' } },+ });+ expect((plan.steps[1].input as Record<string, unknown>).value).toBe('[email protected]');+ // Untouched+ expect(plan.steps[0].action).toBe('open');+ });++ it('honours skipSteps', () => {+ const trajectory = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory });+ const plan = planReplay(envelope, { skipSteps: [2] });+ expect(plan.steps).toHaveLength(3);+ expect(plan.steps.find(s => s.index === 2)).toBeUndefined();+ });+ });++ describe('replay delta', () => {+ it('reports allMatched=true when replay reproduces every step outcome', () => {+ const original = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory: original });+ const replay = buildTrajectory({ id: 'replay-1' });+ const delta = buildReplayDelta(envelope, replay);+ expect(delta.allMatched).toBe(true);+ expect(delta.parentTrajectoryId).toBe(original.id);+ });++ it('reports outcome drift when a step that succeeded in the parent fails on replay', () => {+ const original = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory: original });+ const replay = buildTrajectory({ id: 'replay-2' });+ // Force a fail on step 3+ (replay.steps[3] as Record<string, unknown>).result = { success: false };+ const delta = buildReplayDelta(envelope, replay);+ expect(delta.allMatched).toBe(false);+ expect(delta.stepResults[3].matched).toBe(false);+ expect(delta.stepResults[3].note).toMatch(/outcome drift/);+ });++ it('reports action drift when steps diverge', () => {+ const original = buildTrajectory();+ const { envelope } = sealTrajectory({ trajectory: original });+ const replay = buildTrajectory({ id: 'replay-3' });+ (replay.steps[1] as Record<string, unknown>).action = 'type';+ const delta = buildReplayDelta(envelope, replay);+ expect(delta.allMatched).toBe(false);+ expect(delta.stepResults[1].note).toMatch(/action drift/);+ });+ });++ describe('determinism', () => {+ it('produces the same signature for the same payload + same key', () => {+ const trajectory = buildTrajectory();+ const key = generateWitnessKey();+ const sealedAt = '2026-05-18T20:00:00.000Z';+ const a = sealTrajectory({ trajectory, witnessKey: key, sealedAt });+ const b = sealTrajectory({ trajectory, witnessKey: key, sealedAt });+ expect(a.envelope.signature).toBe(b.envelope.signature);+ });++ it('produces a different signature when content changes', () => {+ const key = generateWitnessKey();+ const sealedAt = '2026-05-18T20:00:00.000Z';+ const a = sealTrajectory({ trajectory: buildTrajectory({ goal: 'A' }), witnessKey: key, sealedAt });+ const b = sealTrajectory({ trajectory: buildTrajectory({ goal: 'B' }), witnessKey: key, sealedAt });+ expect(a.envelope.signature).not.toBe(b.envelope.signature);+ });+ });+});diff --git a/v3/docs/adr/ADR-122-browser-beyond-sota.md b/v3/docs/adr/ADR-122-browser-beyond-sota.mdnew file mode 100644index 0000000000..0f406dd0a4--- /dev/null+++ b/v3/docs/adr/ADR-122-browser-beyond-sota.md@@ -0,0 +1,175 @@+# ADR-122 β `@claude-flow/browser` beyond-SOTA: signed trajectories, causal self-healing, federated MCTS++**Status**: Proposed (2026-05-18)+**Date**: 2026-05-18+**Authors**: claude (drafted with rUv)+**Related**: `@claude-flow/[email protected]`, [`[email protected]`](https://www.npmjs.com/package/agent-browser), `ruflo-browser` plugin (record/replay/auth-flow/cookie-vault), [`@ruvector/[email protected]`](https://www.npmjs.com/package/@ruvector/rvf), AgentDB causal graph (ADR-076 family), Ed25519 witness manifest (ADR-103), Federation v1 (ADR-097/104/105β110), AIDefence 2.3.0 (ADR-118)+**Supersedes**: nothing (additive)++## Context++There are **two browser systems** in this repo, drifting apart:++1. **`@claude-flow/[email protected]`** (v3 monorepo) β built on AugmentCode's `agent-browser` CLI, ships 59 MCP tools, element-ref snapshots (`@e1`, `@e2` β 93% context reduction), trajectory recording into ReasoningBank, URL/PII scanning, 9 workflow templates, basic multi-session swarm. **Locked to `agent-browser@^0.6.0` while upstream is at `0.27.0`** β a 21-minor-version drift covering the entire 2025βmid-2026 evolution of the CLI.+2. **`ruflo-browser` plugin** (`plugins/ruflo-browser/`) β more modern, 23 MCP tools, already composes RVF cognitive containers + AIDefence gates + cookie vault + replay-with-mutation. This is where the "beyond SOTA" primitives have been quietly accumulating.++Meanwhile the SOTA web-agent field has moved hard. Current WebVoyager numbers (Apr 2026):++| System | WebVoyager | Distinctive technique |+|---|---|---|+| **Surfer-H + Holo1** | **92.2%** | Policy/Localizer/Validator triad β separate VLM for visual UI element localization |+| Browser Use | 89.1% | Hybrid DOM+screenshot, implicit fallback |+| Gemini 2.5 CU | 88.9% | Pure visual grounding, screenshot loop |+| Claude Opus 4.6 (CU) | 88.0% | Pure pixel reasoning, no DOM |+| OpenAI Operator | 87.0% | RL-trained CoT-over-screenshots, user-confirm sensitive actions |+| Skyvern | 85.8% | Validator loop β vision-LLM verifies every action's effect |+| Stagehand v3 | n/a (DX leader) | `observe/act/extract` primitives, CDP-native, managed stealth |++The benchmark frontier is no longer about action accuracy β it's about **inspectability, provenance, and cross-session learning**, none of which any of the named systems ship. Pure-Playwright + LLM systems cannot bolt on signed replay or causal-graph recovery without architectural surgery.++This ADR converges the two ruflo browser systems and commits to three wedges that exploit ambient ruflo infrastructure (HNSW vector memory + AgentDB causal graphs + Ed25519 witness + federation peers + AIDefence) to do what SOTA structurally cannot.++## Gap analysis (what we don't have)++| Capability | Surfer-H | Browser Use | Stagehand v3 | Skyvern | Operator | `@claude-flow/browser` today | `ruflo-browser` today |+|---|---|---|---|---|---|---|---|+| Visual grounding (specialized VLM Localizer) | Y | partial | N | Y | Y | N | N |+| Self-healing selectors (queryable) | Y (silent) | partial | Y (silent) | Y (silent) | N | N | N |+| Parallel MCTS branch exploration | N | N | N | N | N | N | N |+| **Signed / verifiable replay artifact** | **N** | **N** | **N** | **N** | **N** | **N (RVF unused)** | **partial (RVF, no witness)** |+| **Causal-graph selector recovery** | **N** | **N** | **N** | **N** | **N** | **N** | **N** |+| **PII-gated cookie vault with attestation** | **N** | **N** | **N** | **N** | **N** | **N** | **partial (AIDefence yes, no witness)** |+| Cross-session trajectory learning (HNSW) | partial | N | N | partial | N | partial (ReasoningBank) | partial |+| Federated multi-peer session sharing | N | N | N | N | N | N | N |+| Cost-aware per-action model routing | N | N | N | N | N | N | N |+| OCR for screenshot text | Y | N | N | Y | Y | N | N |+| Action-graph / GOAP pre-planning | N | N | N | partial | partial | N | N |++The bolded rows are the wedges: every named SOTA system is "N", ruflo has the primitives in place to be "Y", and nothing else can ship these without rebuilding their core.++## Decision++Land beyond-SOTA in **six phases**, each shippable alone, each opt-in via configuration. Phases 0β2 are convergence (fix what's broken / merge what's split); phases 3β5 are the new wedges.++### Phase 0 β Upgrade `agent-browser` 0.6 β 0.27 and converge the two systems++The 21-minor drift on `agent-browser` is the highest-yield, lowest-risk fix. Land it first.++- Bump `@claude-flow/browser` dependency to `agent-browser@^0.27.0` in one PR.+- Audit the 59 MCP tools against `[email protected]` CLI surface; deprecate any that no longer have a CLI counterpart; surface any new CLI verbs (`record`, `replay`, etc.) as new MCP tools.+- Fold the more-mature `ruflo-browser` plugin primitives (record/replay/auth-flow/cookie-vault/screenshot-diff) into `@claude-flow/browser` as first-class application services. Keep the plugin as a thin re-export for backward compatibility, scheduled for removal in 4.0.++**Acceptance:**+- Single source of truth: `@claude-flow/browser` exports `record`, `replay`, `replayWithMutation`, `authFlow`, `cookieVault`, `screenshotDiff` as application-level operations.+- Plugin `plugins/ruflo-browser` re-exports from `@claude-flow/browser` only; no duplicated logic.+- Zero regression on existing 128 tests; new tests cover the merged surface area.+- `ruflo doctor` reports `agent-browser` version and warns when below 0.27.++**Non-goals (Phase 0):** removing the plugin entirely (keep through 4.0); changing the MCP tool names (back-compat).++### Phase 1 β Wedge 1: Signed, replayable trajectory containers (RVF + Ed25519 witness)++Combine the existing RVF cognitive container format (`@ruvector/[email protected]`) with the Ed25519 witness manifest (ADR-103) to produce a portable, signed `.rvf` browser-session bundle. No other web agent has cryptographic provenance for a recorded session.++- At `endTrajectory(success, verdict)`, write the trajectory steps + final snapshot + screenshot hashes into an RVF container, then sign the container with the project's witness key.+- Provide a verifier: `ruflo browser verify <session.rvf>` β confirms signature, integrity, and chain-of-custody back to the recording project.+- Provide `replayWithMutation(session.rvf, mutations)` β replay against the same or mutated URL, producing a new signed delta artifact suitable for visual-regression CI gates.++**Acceptance:**+- A recorded trajectory round-trips through `record β sign β distribute β verify β replay` with byte-exact step reproduction.+- Forging a step (modifying the trajectory JSON in the container) fails verification.+- CI integration: a session `.rvf` artifact can be checked into a repo and replayed by an unrelated checkout; the replay produces a signed delta against the original.+- Tamper-evidence: changing one element ref in the trajectory breaks `ruflo browser verify`.++**Non-goals (Phase 1):** distributed signing (use single project key); replay across browser-engine versions (require same Playwright major).++### Phase 2 β Wedge 2: Causal-graph-backed self-healing selectors++Every time a selector resolution fails (element-ref no longer present, click target moved, fill target's role changed), record a causal edge in AgentDB: `selector @eN at URL U broke because of DOM mutation M observed between timestamps T1..T2`. Future sessions on the same domain query the causal graph *before* attempting a known-brittle locator family.++- Hook into the existing `agent-browser-adapter` retry path. On retry, snapshot the DOM diff (Playwright `accessibility.snapshot()` before/after) and write a causal edge via `mcp__claude-flow__agentdb_causal-edge`.+- New MCP tool: `browser/explain-recovery` β given a current page + a failing selector, walk the causal graph and return the historical break events that share a structural ancestor.+- Heal proactively: the next session's snapshot is annotated with `_causalRiskScore` per element-ref, sourced from prior break events on this domain. Element-refs with high break-history are flagged in the MCP response.++**Acceptance:**+- After 10 sessions on a domain with N selector breaks, the 11th session's snapshot annotates the N break-prone element-refs with a non-zero `_causalRiskScore`.+- `agentdb_causal-explain` on a failed selector returns at least one prior break event with timestamp and DOM-diff payload.+- Cross-domain isolation: break events on `example.com` do not pollute risk scores on `other.com`.++**Non-goals (Phase 2):** structural deep-learning over the causal graph; just record + query. Learning comes in Phase 5.++### Phase 3 β Wedge 3: AIDefence-attested cookie vault++Every cookie write goes through AIDefence (`aidefence_has_pii` + `aidefence_is_safe`) before it lands in the vault. The vault entry is sealed in an RVF container and witness-signed. The signed attestation confirms: "this cookie handle was scanned by AIDefence version X at timestamp T and contained no PII / no detected threats."++- Replace the current cookie persistence in `ruflo-browser`'s `browser-cookies` MCP tool with the attested flow.+- The cookie handle exposes a `verifyAttestation()` method consumers MUST call before reuse; unverified handles refuse to attach to a new session.+- Federation peers (when ADR-097/111 is online) can request attested cookie handles from each other; the witness signature is the cross-installation trust boundary.++**Acceptance:**+- Cookie containing a value AIDefence flags as PII never persists; an audit event is written.+- A cookie handle whose witness signature is invalid refuses to attach to a session and emits a structured warning.+- A handle attested by Installation A and consumed by Installation B verifies successfully iff B trusts A's witness key.++**Non-goals (Phase 3):** rotating sealed-cookie encryption keys (future ADR); cross-engine cookie portability.++### Phase 4 β Wedge 4: Federated MCTS branch exploration++For exploratory browse-tasks (unfamiliar site, ambiguous goal), distribute parallel branch explorations across federation peers. Each peer explores one subtree, writes its trajectory vector to the shared HNSW index, and the queen node picks the highest-cosine-similarity branch to past successful ReasoningBank trajectories. Plan-MCTS / Agent Alpha style search, but the search is parallelizable across the installation mesh.++- New MCP tool: `browser/explore-mcts` β takes a goal + initial URL, returns the best trajectory by HNSW-similarity to past successes.+- Federation message type `browser_mcts_branch` carries an opaque branch ID, parent-trajectory pointer, and depth budget.+- Each peer runs the branch in an isolated browser session (RVF container per branch), reports the trajectory vector and a self-evaluated value back to the queen.++**Acceptance:**+- On a controlled benchmark task with N=5 federation peers, MCTS exploration produces a higher success rate than single-process exploration at equal wall-clock budget.+- A peer that returns a trajectory whose witness signature fails is excluded from the branch aggregation.+- Cost-tracker reports per-peer spend; the queen can early-terminate branches over budget.++**Non-goals (Phase 4):** running MCTS on every task β gate behind explicit `mcts: true` config; this is for hard tasks only.++### Phase 5 β Cost-aware per-action model routing + GOAP pre-planning++Compose with existing ruflo primitives β no new architecture:++- Wire `hooks_route` per browser action: simple DOM-present actions β Agent Booster (Tier 1, $0); visual grounding on unfamiliar pages β Haiku (Tier 2); plan-level reasoning + recovery β Sonnet/Opus (Tier 3). Cost-tracker already logs per-action spend.+- Wire `ruflo-goals` GOAP planner: before touching the browser, produce an action plan with preconditions/effects against AgentDB causal graphs. Dry-run validation surfaces likely failures (e.g. "this site requires login; you have no cookie attestation") before consuming a real browser session.++**Acceptance:**+- β₯30% of browser actions route through Agent Booster (Tier 1, $0) on a representative workload.+- GOAP dry-run catches at least one class of failure (missing cookie / missing auth state) before the live session starts on the test suite.+- Cost-tracker can produce a per-trajectory cost report broken down by tier.++**Non-goals (Phase 5):** retraining a model for routing; reuse the existing intelligence pipeline.++## Phase summary++| Phase | Wedge | Composed primitives | Ships as |+|---|---|---|---|+| 0 | Convergence + upgrade | `[email protected]`, fold plugin into package | alpha.4 |+| 1 | Signed trajectories | RVF + witness + replay-with-mutation | alpha.5 |+| 2 | Causal self-healing | AgentDB causal edges + adapter retry hook | alpha.6 |+| 3 | Attested cookie vault | AIDefence + RVF + witness | alpha.7 |+| 4 | Federated MCTS | Federation v1 + HNSW + ReasoningBank | alpha.8 |+| 5 | Cost-aware routing + GOAP | hooks_route + ruflo-goals + cost-tracker | alpha.9 |++## Open questions++- **Holo1 Localizer adoption.** Surfer-H's open-weight 7B Localizer model is the current grounding SOTA. Should we ship a `browser/localize` MCP tool backed by a self-hosted Holo1 via `ruvllm` routing? Defer to a Phase 6 follow-up ADR once Phases 0β2 land β Phase 0 alone closes most of the perceived gap.+- **Anti-bot stealth.** Stagehand outsources this to Browserbase's managed infrastructure. Self-hosting CDP-stealth has its own moral hazard (enables abuse). Defer; if/when a customer asks, scope a separate ADR.+- **Witness key rotation for cross-installation cookie attestation.** ADR-103 covers project-key rotation but not federation-fanout. Likely needs an ADR-122-companion before Phase 3 ships across federations.++## References++- Surfer-H + Holo1 (current WebVoyager SOTA, 92.2%): https://arxiv.org/abs/2506.02865+- Plan-MCTS for web navigation: https://arxiv.org/html/2602.14083+- Grounding Computer Use Agents on Human Demonstrations: https://arxiv.org/pdf/2511.07332+- Stagehand v3 (CDP-native): https://www.browserbase.com/changelog/stagehand-v3+- Browser Use (DOM+vision hybrid): https://github.com/browser-use/browser-use+- Skyvern (Validator loop): https://www.skyvern.com/blog/how-skyvern-reads-and-understands-the-web/+- OpenAI Operator / CUA: https://openai.com/index/computer-using-agent/+- An Illusion of Progress? Assessing Web Agents: https://arxiv.org/html/2504.01382v4+- ADR-103 (witness temporal history): `v3/docs/adr/ADR-103-witness-temporal-history.md`+- ADR-104 (federation wire transport): `v3/docs/adr/ADR-104-federation-wire-transport.md`+- ADR-118 (AIDefence 2.3.0): `v3/docs/adr/ADR-118-aidefence-2.3.0-upgrade.md`+- ADR-121 (embeddings ruvector upgrade): `v3/docs/adr/ADR-121-embeddings-ruvector-upgrade.md`