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

feat(browser): #2041 ADR-122 Phase 1 MCP + Phase 2 causal recovery

ruv8d10e1aa8c61
diff --git a/v3/@claude-flow/browser/src/application/causal-recovery-service.ts b/v3/@claude-flow/browser/src/application/causal-recovery-service.ts
new file mode 100644
index 0000000000..a40883a241
--- /dev/null
+++ b/v3/@claude-flow/browser/src/application/causal-recovery-service.ts
@@ -0,0 +1,148 @@
+/**
+ * @claude-flow/browser - Causal Recovery Service (ADR-122 Phase 2)
+ *
+ * Coordinates the in-process break store + snapshot annotation so the
+ * BrowserService can:
+ * 1. Record selector breaks as they happen (via reportBreak)
+ * 2. Annotate a fresh snapshot with `_causalRiskScore` per element-ref
+ * 3. Explain a current failure (priorBreaks + suggested alternative locators)
+ *
+ * Phase 2 ships an in-process implementation. Phase 2.5 substitutes the
+ * store backend with the AgentDB causal-edge MCP bridge β€” caller-facing
+ * API does not change.
+ */
+
+import {
+ InMemoryBreakStore,
+ JsonFileBreakStore,
+ classifyBreak,
+ parseUrl,
+ type IBreakStore,
+} from '../infrastructure/causal-recovery-store.js';
+import type {
+ SelectorBreakEvent,
+ CausalRiskAnnotation,
+ RecoveryExplanation,
+} from '../domain/causal-recovery.js';
+import type { Snapshot, SnapshotNode, ActionResult } from '../domain/types.js';
+
+export interface CausalRecoveryServiceOptions {
+ /** Existing store to use (else creates an in-memory one). */
+ store?: IBreakStore;
+ /** Path on disk for persistence; ignored when `store` is supplied. */
+ persistPath?: string;
+}
+
+/**
+ * Snapshot annotated with causal risk scores.
+ *
+ * Returned by `annotateSnapshot`. The wire shape is identical to a regular
+ * Snapshot plus a `_causal` field for per-ref risk metadata.
+ */
+export interface AnnotatedSnapshot extends Snapshot {
+ _causal: Record<string, CausalRiskAnnotation>;
+}
+
+export class CausalRecoveryService {
+ private readonly store: IBreakStore;
+
+ constructor(options: CausalRecoveryServiceOptions = {}) {
+ if (options.store) {
+ this.store = options.store;
+ } else if (options.persistPath) {
+ this.store = new JsonFileBreakStore(options.persistPath);
+ } else {
+ this.store = new InMemoryBreakStore();
+ }
+ }
+
+ /**
+ * Record a selector break observed during a browser action.
+ *
+ * Typically wired into the adapter's retry path so every retried failure
+ * produces an edge in the causal graph.
+ */
+ async reportBreak(input: {
+ url: string;
+ selector: string;
+ action: string;
+ actionResult: ActionResult;
+ lastKnownRole?: string;
+ lastKnownName?: string;
+ sessionId?: string;
+ }): Promise<SelectorBreakEvent> {
+ const { origin, path } = parseUrl(input.url);
+ return this.store.recordBreak({
+ origin,
+ path,
+ selector: input.selector,
+ action: input.action,
+ kind: classifyBreak(input.actionResult.error),
+ reason: input.actionResult.error,
+ lastKnownRole: input.lastKnownRole,
+ lastKnownName: input.lastKnownName,
+ sessionId: input.sessionId,
+ });
+ }
+
+ /** Per-(origin, selector) risk lookup β€” single point. */
+ getRisk(url: string, selector: string): Promise<CausalRiskAnnotation> {
+ const { origin } = parseUrl(url);
+ return this.store.getRisk(origin, selector);
+ }
+
+ /** Recovery explanation β€” prior breaks + suggested alternatives. */
+ explain(url: string, failingSelector: string, options: { lastKnownRole?: string; lastKnownName?: string } = {}): Promise<RecoveryExplanation> {
+ const { origin } = parseUrl(url);
+ return this.store.explainRecovery(origin, failingSelector, options);
+ }
+
+ listBreaks(url: string): Promise<SelectorBreakEvent[]> {
+ const { origin } = parseUrl(url);
+ return this.store.listBreaks(origin);
+ }
+
+ /**
+ * Annotate a snapshot with `_causalRiskScore` per element-ref.
+ *
+ * Returns a copy of the snapshot with a top-level `_causal` map. Existing
+ * snapshot fields are preserved byte-for-byte so downstream consumers can
+ * ignore the annotation if they don't care.
+ */
+ async annotateSnapshot(snapshot: Snapshot, url: string): Promise<AnnotatedSnapshot> {
+ const refs = Object.keys(snapshot.refs ?? {});
+ const annotations: Record<string, CausalRiskAnnotation> = {};
+ for (const ref of refs) {
+ annotations[ref] = await this.getRisk(url, ref);
+ }
+ return { ...snapshot, _causal: annotations };
+ }
+
+ /**
+ * Decorate a snapshot tree in-place with `_causalRiskScore` markers on each
+ * node that has a ref. Useful when callers want a single object to inspect
+ * rather than a separate `_causal` map.
+ */
+ async decorateTree(snapshot: Snapshot, url: string): Promise<Snapshot> {
+ const annotated = await this.annotateSnapshot(snapshot, url);
+ walk(annotated.tree, annotated._causal);
+ return annotated;
+ }
+
+ /** Direct store access for tests / advanced consumers. */
+ getStore(): IBreakStore {
+ return this.store;
+ }
+}
+
+function walk(node: SnapshotNode | undefined, annotations: Record<string, CausalRiskAnnotation>): void {
+ if (!node) return;
+ if (node.ref && annotations[node.ref]) {
+ const ann = annotations[node.ref];
+ (node as SnapshotNode & { _causalRiskScore?: number; _causalBreakCount?: number }).
+ _causalRiskScore = ann.riskScore;
+ (node as SnapshotNode & { _causalRiskScore?: number; _causalBreakCount?: number }).
+ _causalBreakCount = ann.breakCount;
+ }
+ for (const child of node.children ?? []) walk(child, annotations);
+}
diff --git a/v3/@claude-flow/browser/src/domain/causal-recovery.ts b/v3/@claude-flow/browser/src/domain/causal-recovery.ts
new file mode 100644
index 0000000000..e3fc4ae88f
--- /dev/null
+++ b/v3/@claude-flow/browser/src/domain/causal-recovery.ts
@@ -0,0 +1,94 @@
+/**
+ * @claude-flow/browser - Causal Recovery Types (ADR-122 Phase 2)
+ *
+ * When a selector fails to resolve (element-ref vanished, fill target moved,
+ * click target changed role), we don't just retry β€” we record a causal edge
+ * in AgentDB: "selector X at URL Y broke because DOM mutation M observed
+ * between T1..T2." Future sessions query the graph BEFORE attempting a
+ * known-brittle locator family.
+ *
+ * No SOTA web agent (Surfer-H, Browser Use, Stagehand, Operator, Skyvern)
+ * surfaces WHY a selector broke β€” they retry silently. This is the wedge.
+ */
+
+import { z } from 'zod';
+
+/** Why a selector resolution failed β€” taxonomy for causal-edge labels. */
+export const SelectorBreakKindSchema = z.enum([
+ 'element-not-found',
+ 'element-not-visible',
+ 'element-not-enabled',
+ 'element-detached',
+ 'ref-stale',
+ 'timeout',
+ 'navigation-during-action',
+ 'unknown',
+]);
+export type SelectorBreakKind = z.infer<typeof SelectorBreakKindSchema>;
+
+export const SelectorBreakEventSchema = z.object({
+ /** Globally-unique event ID. */
+ id: z.string().min(1),
+ /** Domain origin (e.g. `https://example.com`) β€” used as causal-graph isolation key. */
+ origin: z.string().min(1),
+ /** Path component of the URL where the break occurred. */
+ path: z.string(),
+ /** The failing selector β€” either an element-ref (`@e3`) or CSS / text= / role=. */
+ selector: z.string().min(1),
+ /** Action that triggered the failure (click/fill/wait/...). */
+ action: z.string().min(1),
+ /** What kind of break this is. */
+ kind: SelectorBreakKindSchema,
+ /** When the break was first observed. */
+ timestamp: z.string(),
+ /** Human-readable reason from the adapter, if any. */
+ reason: z.string().optional(),
+ /** Element-ref's ROLE and NAME at last successful resolution, if known β€” used for fuzzy match. */
+ lastKnownRole: z.string().optional(),
+ lastKnownName: z.string().optional(),
+ /** Session ID where the break was observed (for cross-trajectory queries). */
+ sessionId: z.string().optional(),
+});
+export type SelectorBreakEvent = z.infer<typeof SelectorBreakEventSchema>;
+
+/**
+ * Risk annotation surfaced on snapshot element-refs based on prior break history.
+ *
+ * A ref with a non-zero `riskScore` should be treated as a known-brittle locator
+ * β€” callers may prefer to switch strategies (`find role=button --name "Submit"`
+ * instead of `@e3`) BEFORE attempting the action.
+ */
+export const CausalRiskAnnotationSchema = z.object({
+ /** The element-ref or selector being annotated. */
+ selector: z.string(),
+ /** [0, 1] β€” fraction of prior attempts on this origin+selector that broke. */
+ riskScore: z.number().min(0).max(1),
+ /** Count of break events behind this score. */
+ breakCount: z.number().int().nonnegative(),
+ /** Most recent break event ID, if any. */
+ lastBreakId: z.string().optional(),
+ /** Most recent break kind, for callers that want to choose recovery strategy. */
+ lastBreakKind: SelectorBreakKindSchema.optional(),
+});
+export type CausalRiskAnnotation = z.infer<typeof CausalRiskAnnotationSchema>;
+
+/**
+ * Result returned by the recovery-explainer when a selector fails.
+ *
+ * Unlike SOTA "auto-heal silently and hope" recovery, this surfaces the
+ * CAUSAL CHAIN: prior break events, their structural ancestor, and
+ * suggested alternative locator strategies.
+ */
+export interface RecoveryExplanation {
+ origin: string;
+ failingSelector: string;
+ /** Prior break events for the same origin + selector family. */
+ priorBreaks: SelectorBreakEvent[];
+ /** Suggested alternative locator strategies, in priority order. */
+ suggestions: Array<{
+ strategy: 'find-role' | 'find-text' | 'find-testid' | 'find-label' | 'find-placeholder';
+ value: string;
+ confidence: number;
+ rationale: string;
+ }>;
+}
diff --git a/v3/@claude-flow/browser/src/index.ts b/v3/@claude-flow/browser/src/index.ts
index ae0e98bd4d..310297c81d 100644
--- a/v3/@claude-flow/browser/src/index.ts
+++ b/v3/@claude-flow/browser/src/index.ts
@@ -143,6 +143,29 @@ export {
type ReplayMutation,
} from './domain/signed-trajectory.js';
+// Causal-graph self-healing selectors (ADR-122 Phase 2)
+export {
+ CausalRecoveryService,
+ type CausalRecoveryServiceOptions,
+ type AnnotatedSnapshot,
+} from './application/causal-recovery-service.js';
+export {
+ InMemoryBreakStore,
+ JsonFileBreakStore,
+ classifyBreak,
+ parseUrl,
+ type IBreakStore,
+} from './infrastructure/causal-recovery-store.js';
+export {
+ SelectorBreakEventSchema,
+ SelectorBreakKindSchema,
+ CausalRiskAnnotationSchema,
+ type SelectorBreakEvent,
+ type SelectorBreakKind,
+ type CausalRiskAnnotation,
+ type RecoveryExplanation,
+} from './domain/causal-recovery.js';
+
// MCP tools
export { 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/causal-recovery-store.ts b/v3/@claude-flow/browser/src/infrastructure/causal-recovery-store.ts
new file mode 100644
index 0000000000..0ca71301ff
--- /dev/null
+++ b/v3/@claude-flow/browser/src/infrastructure/causal-recovery-store.ts
@@ -0,0 +1,223 @@
+/**
+ * @claude-flow/browser - Causal Recovery Store (ADR-122 Phase 2)
+ *
+ * In-process store for selector-break events with origin-scoped risk scoring.
+ *
+ * Phase 2 ships an in-memory + JSON-persistence implementation so the
+ * recovery loop works without external dependencies. Phase 2.5 swaps the
+ * backend for AgentDB causal-edge MCP tools (`mcp__claude-flow__agentdb_causal-edge`)
+ * once we have the bridge wired.
+ *
+ * The IBreakStore interface keeps the swap a one-file change.
+ */
+
+import { existsSync } from 'node:fs';
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { dirname } from 'node:path';
+import { randomBytes } from 'node:crypto';
+import {
+ SelectorBreakEventSchema,
+ type SelectorBreakEvent,
+ type CausalRiskAnnotation,
+ type RecoveryExplanation,
+ type SelectorBreakKind,
+} from '../domain/causal-recovery.js';
+
+export interface IBreakStore {
+ recordBreak(event: Omit<SelectorBreakEvent, 'id' | 'timestamp'> & Partial<Pick<SelectorBreakEvent, 'id' | 'timestamp'>>): Promise<SelectorBreakEvent>;
+ /** Get all break events for an origin. */
+ listBreaks(origin: string): Promise<SelectorBreakEvent[]>;
+ /** Risk score for a (origin, selector) pair, computed from break-history. */
+ getRisk(origin: string, selector: string): Promise<CausalRiskAnnotation>;
+ /** Explain a current failure using prior break events + suggest alternative locators. */
+ explainRecovery(origin: string, failingSelector: string, options?: { lastKnownRole?: string; lastKnownName?: string }): Promise<RecoveryExplanation>;
+ /** Clear store (tests). */
+ clear(): Promise<void>;
+}
+
+interface StoreState {
+ /** All recorded breaks. */
+ breaks: SelectorBreakEvent[];
+ /** Per-origin attempt counts (for risk denominator). */
+ attempts: Record<string, Record<string, number>>;
+}
+
+export class InMemoryBreakStore implements IBreakStore {
+ protected state: StoreState = { breaks: [], attempts: {} };
+
+ async recordBreak(input: Omit<SelectorBreakEvent, 'id' | 'timestamp'> & Partial<Pick<SelectorBreakEvent, 'id' | 'timestamp'>>): Promise<SelectorBreakEvent> {
+ const event = SelectorBreakEventSchema.parse({
+ id: input.id ?? `brk-${Date.now()}-${randomBytes(3).toString('hex')}`,
+ timestamp: input.timestamp ?? new Date().toISOString(),
+ origin: input.origin,
+ path: input.path,
+ selector: input.selector,
+ action: input.action,
+ kind: input.kind,
+ reason: input.reason,
+ lastKnownRole: input.lastKnownRole,
+ lastKnownName: input.lastKnownName,
+ sessionId: input.sessionId,
+ });
+ this.state.breaks.push(event);
+ return event;
+ }
+
+ /** Record an attempt (success or failure) β€” denominator for risk scoring. */
+ recordAttempt(origin: string, selector: string): void {
+ const perOrigin = this.state.attempts[origin] ?? (this.state.attempts[origin] = {});
+ perOrigin[selector] = (perOrigin[selector] ?? 0) + 1;
+ }
+
+ async listBreaks(origin: string): Promise<SelectorBreakEvent[]> {
+ return this.state.breaks.filter(b => b.origin === origin);
+ }
+
+ async getRisk(origin: string, selector: string): Promise<CausalRiskAnnotation> {
+ const breaks = this.state.breaks.filter(b => b.origin === origin && b.selector === selector);
+ const attempts = this.state.attempts[origin]?.[selector] ?? Math.max(breaks.length, 1);
+ const riskScore = Math.min(1, breaks.length / attempts);
+ const lastBreak = breaks[breaks.length - 1];
+ return {
+ selector,
+ riskScore,
+ breakCount: breaks.length,
+ lastBreakId: lastBreak?.id,
+ lastBreakKind: lastBreak?.kind,
+ };
+ }
+
+ async explainRecovery(
+ origin: string,
+ failingSelector: string,
+ options: { lastKnownRole?: string; lastKnownName?: string } = {},
+ ): Promise<RecoveryExplanation> {
+ // Prior breaks on the same origin+selector family. We consider "family"
+ // generously: a selector @e3 today might be @e4 tomorrow but they share
+ // role/name from prior snapshots β€” match those too if provided.
+ const exact = this.state.breaks.filter(b => b.origin === origin && b.selector === failingSelector);
+ const familyByRole = options.lastKnownRole
+ ? this.state.breaks.filter(b => b.origin === origin && b.lastKnownRole === options.lastKnownRole)
+ : [];
+ const familyByName = options.lastKnownName
+ ? this.state.breaks.filter(b => b.origin === origin && b.lastKnownName === options.lastKnownName)
+ : [];
+ const priorBreaks = dedupeBreaks([...exact, ...familyByRole, ...familyByName]);
+
+ const suggestions: RecoveryExplanation['suggestions'] = [];
+ if (options.lastKnownRole && options.lastKnownName) {
+ suggestions.push({
+ strategy: 'find-role',
+ value: `${options.lastKnownRole} --name "${options.lastKnownName}"`,
+ confidence: 0.85,
+ rationale: 'Last successful resolution had a stable role+name pair. Role-based locators survive structural reflows.',
+ });
+ } else if (options.lastKnownName) {
+ suggestions.push({
+ strategy: 'find-text',
+ value: options.lastKnownName,
+ confidence: 0.65,
+ rationale: 'Last known accessible name; text-based locators are reasonably stable for visible elements.',
+ });
+ }
+ // Generic fallback ordering, by SOTA stability heuristics.
+ suggestions.push({
+ strategy: 'find-testid',
+ value: '(use page-specific testid if known)',
+ confidence: 0.95,
+ rationale: 'data-testid is the most resilient locator strategy β€” survives styling and layout changes.',
+ });
+
+ return {
+ origin,
+ failingSelector,
+ priorBreaks,
+ suggestions,
+ };
+ }
+
+ async clear(): Promise<void> {
+ this.state = { breaks: [], attempts: {} };
+ }
+
+ /** Direct accessor for the in-memory state (tests / persistence). */
+ snapshot(): StoreState {
+ return this.state;
+ }
+
+ /** Restore state from a previous snapshot. */
+ restore(state: StoreState): void {
+ this.state = state;
+ }
+}
+
+function dedupeBreaks(events: SelectorBreakEvent[]): SelectorBreakEvent[] {
+ const seen = new Set<string>();
+ const out: SelectorBreakEvent[] = [];
+ for (const e of events) {
+ if (seen.has(e.id)) continue;
+ seen.add(e.id);
+ out.push(e);
+ }
+ return out.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
+}
+
+/** JSON-on-disk persistence wrapper. */
+export class JsonFileBreakStore extends InMemoryBreakStore {
+ constructor(private readonly path: string) {
+ super();
+ }
+
+ async load(): Promise<void> {
+ if (!existsSync(this.path)) return;
+ try {
+ const raw = await readFile(this.path, 'utf8');
+ this.restore(JSON.parse(raw) as StoreState);
+ } catch {
+ // Corrupt file β€” start fresh rather than crashing the agent.
+ }
+ }
+
+ async save(): Promise<void> {
+ await mkdir(dirname(this.path), { recursive: true });
+ await writeFile(this.path, JSON.stringify(this.snapshot(), null, 2), 'utf8');
+ }
+
+ async recordBreak(input: Parameters<InMemoryBreakStore['recordBreak']>[0]): Promise<SelectorBreakEvent> {
+ const event = await super.recordBreak(input);
+ await this.save();
+ return event;
+ }
+}
+
+/**
+ * Helper: classify an adapter ActionResult error into a SelectorBreakKind.
+ *
+ * Maps agent-browser / Playwright stderr patterns to our taxonomy. Returns
+ * `unknown` rather than throwing so callers always get something to record.
+ */
+export function classifyBreak(reason: string | undefined): SelectorBreakKind {
+ if (!reason) return 'unknown';
+ const r = reason.toLowerCase();
+ // Check navigation FIRST: "frame detached during navigation" is fundamentally a
+ // navigation event, not a stale-element event β€” without this order swap, the
+ // generic `detached` branch wins and mis-classifies.
+ if (r.includes('navigation') || r.includes('frame detached')) return 'navigation-during-action';
+ if (r.includes('not found') || r.includes('no element')) return 'element-not-found';
+ if (r.includes('not visible') || r.includes('hidden')) return 'element-not-visible';
+ if (r.includes('not enabled') || r.includes('disabled')) return 'element-not-enabled';
+ if (r.includes('detached') || r.includes('stale element')) return 'element-detached';
+ if (r.includes('stale ref') || (r.includes('@e') && r.includes('expired'))) return 'ref-stale';
+ if (r.includes('timeout') || r.includes('timed out')) return 'timeout';
+ return 'unknown';
+}
+
+/** Parse a URL into origin + path for causal-graph isolation. */
+export function parseUrl(url: string): { origin: string; path: string } {
+ try {
+ const u = new URL(url);
+ return { origin: u.origin, path: u.pathname + u.search };
+ } catch {
+ return { origin: url, path: '/' };
+ }
+}
diff --git a/v3/@claude-flow/browser/src/mcp-tools/browser-tools.ts b/v3/@claude-flow/browser/src/mcp-tools/browser-tools.ts
index 55baf95c0e..0120dc1de3 100644
--- a/v3/@claude-flow/browser/src/mcp-tools/browser-tools.ts
+++ b/v3/@claude-flow/browser/src/mcp-tools/browser-tools.ts
@@ -1237,6 +1237,8 @@ const findTools: MCPTool[] = [
// Export All Tools
// ============================================================================
+import { signedTrajectoryTools } from './signed-trajectory-tools.js';
+
export const browserTools: MCPTool[] = [
...navigationTools,
...snapshotTools,
@@ -1251,6 +1253,7 @@ export const browserTools: MCPTool[] = [
...settingsTools,
...debugTools,
...findTools,
+ ...signedTrajectoryTools, // ADR-122 Phase 1
];
export default browserTools;
diff --git a/v3/@claude-flow/browser/src/mcp-tools/signed-trajectory-tools.ts b/v3/@claude-flow/browser/src/mcp-tools/signed-trajectory-tools.ts
new file mode 100644
index 0000000000..c54db797bf
--- /dev/null
+++ b/v3/@claude-flow/browser/src/mcp-tools/signed-trajectory-tools.ts
@@ -0,0 +1,213 @@
+/**
+ * @claude-flow/browser - Signed Trajectory MCP Tools (ADR-122 Phase 1)
+ *
+ * Exposes seal/verify/plan-replay/build-delta over MCP so agents can produce
+ * and consume signed browser-session artifacts as portable, verifiable units.
+ */
+
+import {
+ sealTrajectory,
+ verifySealedTrajectory,
+ writeSealedTrajectory,
+ readSealedTrajectory,
+ planReplay,
+ buildReplayDelta,
+} from '../application/signed-trajectory-service.js';
+import { generateWitnessKey, loadWitnessKey } from '../infrastructure/witness-signer.js';
+import type { BrowserTrajectory } from '../domain/types.js';
+import type {
+ SignedTrajectoryEnvelope,
+ ReplayMutation,
+} from '../domain/signed-trajectory.js';
+import type { MCPTool } from './browser-tools.js';
+
+function decodeScreenshots(input: unknown): Record<string, Buffer> | undefined {
+ if (!input || typeof input !== 'object') return undefined;
+ const out: Record<string, Buffer> = {};
+ for (const [k, v] of Object.entries(input as Record<string, unknown>)) {
+ if (typeof v !== 'string') continue;
+ // Permit either base64 or raw text β€” base64 first, fall back to utf-8 bytes.
+ try {
+ out[k] = Buffer.from(v, 'base64');
+ // Sanity check: if decode produced empty buffer for non-empty input, fall back.
+ if (out[k].length === 0 && v.length > 0) out[k] = Buffer.from(v, 'utf8');
+ } catch {
+ out[k] = Buffer.from(v, 'utf8');
+ }
+ }
+ return out;
+}
+
+export const signedTrajectoryTools: MCPTool[] = [
+ {
+ name: 'browser/sign-trajectory',
+ description:
+ 'Seal a BrowserTrajectory into an Ed25519-signed envelope (ADR-122 Phase 1). Returns the envelope JSON. Optional `outputPath` writes to disk. Forging any field of the returned envelope breaks verification.',
+ category: 'browser-trajectory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ trajectory: { type: 'object', description: 'BrowserTrajectory to seal' },
+ projectId: { type: 'string', description: 'Project / installation ID embedded in the envelope (federation trust boundary)' },
+ screenshots: {
+ type: 'object',
+ description: 'Map of step-id β†’ base64 screenshot bytes. SHA-256 hashes are sealed into the envelope.',
+ additionalProperties: { type: 'string' },
+ },
+ outputPath: { type: 'string', description: 'If set, write the signed envelope to this path' },
+ privateKeyPem: { type: 'string', description: 'Optional Ed25519 PEM private key (else env RUFLO_BROWSER_WITNESS_KEY or ephemeral)' },
+ parentTrajectoryId: { type: 'string', description: 'If this is a replay-delta, the parent trajectory ID' },
+ },
+ required: ['trajectory'],
+ },
+ handler: async (input) => {
+ const trajectory = input.trajectory as BrowserTrajectory;
+ const witnessKey = input.privateKeyPem ? loadWitnessKey(input.privateKeyPem as string) : undefined;
+ const sealed = sealTrajectory({
+ trajectory,
+ projectId: input.projectId as string | undefined,
+ screenshots: decodeScreenshots(input.screenshots),
+ witnessKey,
+ parentTrajectoryId: input.parentTrajectoryId as string | undefined,
+ });
+ if (input.outputPath) {
+ await writeSealedTrajectory(sealed.envelope, input.outputPath as string);
+ }
+ return {
+ success: true,
+ envelope: sealed.envelope,
+ publicKey: sealed.publicKeyHex,
+ outputPath: input.outputPath ?? null,
+ };
+ },
+ },
+ {
+ name: 'browser/verify-trajectory',
+ description:
+ 'Verify a signed trajectory envelope. Either pass the envelope inline or a path. Returns valid/reason/publicKey. Optional `trustedPublicKeys` restricts accepted signers (federation trust boundary).',
+ category: 'browser-trajectory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ envelope: { type: 'object', description: 'Signed envelope to verify' },
+ path: { type: 'string', description: 'Path to a signed envelope on disk (alternative to envelope)' },
+ trustedPublicKeys: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'List of Ed25519 public-key hex strings allowed as signers',
+ },
+ },
+ },
+ handler: async (input) => {
+ let envelope: unknown = input.envelope;
+ if (!envelope && input.path) {
+ envelope = await readSealedTrajectory(input.path as string);
+ }
+ if (!envelope) {
+ return { success: false, error: 'must provide either envelope or path' };
+ }
+ const result = verifySealedTrajectory(envelope, {
+ trustedPublicKeys: input.trustedPublicKeys as string[] | undefined,
+ });
+ return { success: true, ...result };
+ },
+ },
+ {
+ name: 'browser/plan-replay',
+ description:
+ 'Plan a replay from a signed envelope with optional mutations (replaceStepInput / skipSteps / goal override). Does not execute the browser β€” produces an inspectable step plan for dry-run or downstream execution.',
+ category: 'browser-trajectory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ envelope: { type: 'object', description: 'Signed envelope to plan from' },
+ path: { type: 'string', description: 'Path to signed envelope on disk (alternative to envelope)' },
+ mutations: {
+ type: 'object',
+ description: 'Replay mutations',
+ properties: {
+ replaceStepInput: {
+ type: 'object',
+ description: 'Map of step-index β†’ replacement-input fields',
+ additionalProperties: { type: 'object' },
+ },
+ skipSteps: {
+ type: 'array',
+ items: { type: 'number' },
+ description: 'Step indexes to skip',
+ },
+ goal: { type: 'string', description: 'Override the trajectory goal (informational)' },
+ },
+ },
+ requireValid: { type: 'boolean', description: 'Refuse to plan if signature is invalid (default: true)' },
+ },
+ },
+ handler: async (input) => {
+ let envelope: SignedTrajectoryEnvelope | undefined;
+ if (input.envelope) envelope = input.envelope as SignedTrajectoryEnvelope;
+ else if (input.path) envelope = await readSealedTrajectory(input.path as string);
+ if (!envelope) return { success: false, error: 'must provide either envelope or path' };
+
+ const requireValid = input.requireValid !== false;
+ if (requireValid) {
+ const verification = verifySealedTrajectory(envelope);
+ if (!verification.valid) {
+ return {
+ success: false,
+ error: 'cannot plan replay from invalid envelope: ' + verification.reason,
+ verification,
+ };
+ }
+ }
+
+ const plan = planReplay(envelope, (input.mutations ?? {}) as ReplayMutation);
+ return { success: true, plan };
+ },
+ },
+ {
+ name: 'browser/build-replay-delta',
+ description:
+ 'Compute the delta between an original signed trajectory and a fresh replay trajectory. Detects action drift, outcome drift, and missing/extra steps β€” foundation for visual-regression CI gates.',
+ category: 'browser-trajectory',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ envelope: { type: 'object', description: 'Original signed envelope' },
+ path: { type: 'string', description: 'Path to original signed envelope (alternative to envelope)' },
+ newTrajectory: { type: 'object', description: 'Fresh trajectory produced by replay' },
+ },
+ required: ['newTrajectory'],
+ },
+ handler: async (input) => {
+ let envelope: SignedTrajectoryEnvelope | undefined;
+ if (input.envelope) envelope = input.envelope as SignedTrajectoryEnvelope;
+ else if (input.path) envelope = await readSealedTrajectory(input.path as string);
+ if (!envelope) return { success: false, error: 'must provide either envelope or path' };
+
+ const delta = buildReplayDelta(envelope, input.newTrajectory as BrowserTrajectory);
+ return { success: true, delta };
+ },
+ },
+ {
+ name: 'browser/generate-witness-key',
+ description:
+ 'Generate a fresh Ed25519 witness keypair for signing trajectories. Returns publicKeyHex + PEM-encoded private key. Store the private key securely (e.g. RUFLO_BROWSER_WITNESS_KEY env var).',
+ category: 'browser-trajectory',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async () => {
+ const key = generateWitnessKey();
+ const privateKeyPem = key.privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();
+ const publicKeyPem = key.publicKey.export({ format: 'pem', type: 'spki' }).toString();
+ return {
+ success: true,
+ publicKeyHex: key.publicKeyHex,
+ privateKeyPem,
+ publicKeyPem,
+ envVarHint: 'set RUFLO_BROWSER_WITNESS_KEY to the privateKeyPem value',
+ };
+ },
+ },
+];
diff --git a/v3/@claude-flow/browser/tests/causal-recovery.test.ts b/v3/@claude-flow/browser/tests/causal-recovery.test.ts
new file mode 100644
index 0000000000..3999c388aa
--- /dev/null
+++ b/v3/@claude-flow/browser/tests/causal-recovery.test.ts
@@ -0,0 +1,237 @@
+/**
+ * @claude-flow/browser - Causal Recovery Tests (ADR-122 Phase 2)
+ *
+ * Acceptance criteria covered:
+ * - After N selector breaks on a domain, snapshot annotates the broken refs
+ * with non-zero `_causalRiskScore`
+ * - Cross-origin isolation: breaks on example.com don't pollute other.com
+ * - explain() returns prior break events + alternative locator suggestions
+ * - classifyBreak maps Playwright-style errors to our taxonomy
+ * - parseUrl normalises into (origin, path) for graph isolation
+ */
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { CausalRecoveryService } from '../src/application/causal-recovery-service.js';
+import { InMemoryBreakStore, classifyBreak, parseUrl } from '../src/infrastructure/causal-recovery-store.js';
+import type { Snapshot } from '../src/domain/types.js';
+
+describe('CausalRecoveryService', () => {
+ let service: CausalRecoveryService;
+ let store: InMemoryBreakStore;
+
+ beforeEach(() => {
+ store = new InMemoryBreakStore();
+ service = new CausalRecoveryService({ store });
+ });
+
+ describe('classifyBreak', () => {
+ it('maps not-found errors', () => {
+ expect(classifyBreak('Element not found: @e3')).toBe('element-not-found');
+ });
+ it('maps visibility errors', () => {
+ expect(classifyBreak('Element is not visible')).toBe('element-not-visible');
+ });
+ it('maps timeout errors', () => {
+ expect(classifyBreak('action timed out after 5000ms')).toBe('timeout');
+ });
+ it('maps detached errors', () => {
+ expect(classifyBreak('stale element reference: element is detached')).toBe('element-detached');
+ });
+ it('maps navigation errors', () => {
+ expect(classifyBreak('frame detached during navigation')).toBe('navigation-during-action');
+ });
+ it('defaults to unknown', () => {
+ expect(classifyBreak('something weird happened')).toBe('unknown');
+ expect(classifyBreak(undefined)).toBe('unknown');
+ });
+ });
+
+ describe('parseUrl', () => {
+ it('extracts origin + path', () => {
+ const { origin, path } = parseUrl('https://example.com/login?next=/dash');
+ expect(origin).toBe('https://example.com');
+ expect(path).toBe('/login?next=/dash');
+ });
+ it('handles invalid URLs gracefully', () => {
+ const { origin, path } = parseUrl('not-a-url');
+ expect(origin).toBe('not-a-url');
+ expect(path).toBe('/');
+ });
+ });
+
+ describe('reportBreak', () => {
+ it('records a break event with classified kind', async () => {
+ const event = await service.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'Element not found: @e3' },
+ sessionId: 's1',
+ });
+ expect(event.origin).toBe('https://example.com');
+ expect(event.path).toBe('/login');
+ expect(event.kind).toBe('element-not-found');
+ expect(event.selector).toBe('@e3');
+ expect(event.sessionId).toBe('s1');
+ });
+
+ it('preserves lastKnownRole/Name for future fuzzy matching', async () => {
+ const event = await service.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'timeout' },
+ lastKnownRole: 'button',
+ lastKnownName: 'Submit',
+ });
+ expect(event.lastKnownRole).toBe('button');
+ expect(event.lastKnownName).toBe('Submit');
+ });
+ });
+
+ describe('risk scoring + snapshot annotation', () => {
+ it('returns zero risk for never-seen selectors', async () => {
+ const risk = await service.getRisk('https://example.com', '@e1');
+ expect(risk.riskScore).toBe(0);
+ expect(risk.breakCount).toBe(0);
+ });
+
+ it('accumulates risk with repeated breaks', async () => {
+ for (let i = 0; i < 3; i++) {
+ await service.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ });
+ }
+ const risk = await service.getRisk('https://example.com', '@e3');
+ expect(risk.breakCount).toBe(3);
+ expect(risk.riskScore).toBeGreaterThan(0);
+ expect(risk.lastBreakKind).toBe('element-not-found');
+ });
+
+ it('annotates a snapshot with _causalRiskScore on broken refs', async () => {
+ // Record one break on @e3
+ await service.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ });
+
+ const snapshot: Snapshot = {
+ tree: { role: 'main', children: [{ role: 'button', ref: '@e3', name: 'Submit' }] },
+ refs: { '@e1': { role: 'textbox' }, '@e2': { role: 'textbox' }, '@e3': { role: 'button' } },
+ url: 'https://example.com/login',
+ title: 'Login',
+ timestamp: '2026-05-18T20:00:00Z',
+ };
+ const annotated = await service.annotateSnapshot(snapshot, 'https://example.com/login');
+ expect(annotated._causal['@e3'].breakCount).toBe(1);
+ expect(annotated._causal['@e3'].riskScore).toBeGreaterThan(0);
+ // Un-broken refs should be zero
+ expect(annotated._causal['@e1'].riskScore).toBe(0);
+ expect(annotated._causal['@e2'].riskScore).toBe(0);
+ });
+
+ it('decorates the snapshot tree in-place with risk markers', async () => {
+ await service.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ });
+ const snapshot: Snapshot = {
+ tree: { role: 'main', children: [{ role: 'button', ref: '@e3', name: 'Submit' }] },
+ refs: { '@e3': { role: 'button' } },
+ url: 'https://example.com/login',
+ title: 'Login',
+ timestamp: '2026-05-18T20:00:00Z',
+ };
+ const annotated = await service.decorateTree(snapshot, 'https://example.com/login');
+ const btn = annotated.tree.children![0] as Record<string, unknown>;
+ expect(btn._causalRiskScore).toBeGreaterThan(0);
+ expect(btn._causalBreakCount).toBe(1);
+ });
+ });
+
+ describe('cross-origin isolation', () => {
+ it('breaks on example.com do not pollute other.com risk', async () => {
+ // 5 breaks on example.com
+ for (let i = 0; i < 5; i++) {
+ await service.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ });
+ }
+ const other = await service.getRisk('https://other.com', '@e3');
+ expect(other.breakCount).toBe(0);
+ expect(other.riskScore).toBe(0);
+
+ const same = await service.getRisk('https://example.com', '@e3');
+ expect(same.breakCount).toBe(5);
+ });
+ });
+
+ describe('explain()', () => {
+ it('returns prior breaks + suggested locator strategies', async () => {
+ // Record several breaks with role+name metadata
+ for (let i = 0; i < 2; i++) {
+ await service.reportBreak({
+ url: 'https://example.com/login',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ lastKnownRole: 'button',
+ lastKnownName: 'Submit',
+ });
+ }
+ const explanation = await service.explain('https://example.com/login', '@e3', {
+ lastKnownRole: 'button',
+ lastKnownName: 'Submit',
+ });
+ expect(explanation.priorBreaks.length).toBeGreaterThanOrEqual(2);
+ // Should suggest role-based locator first (highest stability)
+ const roleSuggestion = explanation.suggestions.find(s => s.strategy === 'find-role');
+ expect(roleSuggestion).toBeDefined();
+ expect(roleSuggestion!.value).toContain('button');
+ expect(roleSuggestion!.value).toContain('Submit');
+ // testid is always suggested as the gold standard
+ const testidSuggestion = explanation.suggestions.find(s => s.strategy === 'find-testid');
+ expect(testidSuggestion).toBeDefined();
+ });
+
+ it('does not include unrelated origin breaks in explanation', async () => {
+ await service.reportBreak({
+ url: 'https://other.com/foo',
+ selector: '@e3',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ });
+ const explanation = await service.explain('https://example.com', '@e3');
+ expect(explanation.priorBreaks).toHaveLength(0);
+ });
+ });
+
+ describe('listBreaks', () => {
+ it('returns all breaks for an origin', async () => {
+ await service.reportBreak({
+ url: 'https://example.com/a',
+ selector: '@e1',
+ action: 'click',
+ actionResult: { success: false, error: 'not found' },
+ });
+ await service.reportBreak({
+ url: 'https://example.com/b',
+ selector: '@e2',
+ action: 'fill',
+ actionResult: { success: false, error: 'not found' },
+ });
+ const breaks = await service.listBreaks('https://example.com');
+ expect(breaks).toHaveLength(2);
+ });
+ });
+});