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 6 + substrate reframing β€” Session Capsule + adapters + risk classes

ruv45f951143ea3
diff --git a/v3/@claude-flow/browser/src/application/session-capsule-service.ts b/v3/@claude-flow/browser/src/application/session-capsule-service.ts
new file mode 100644
index 0000000000..4566c9a81b
--- /dev/null
+++ b/v3/@claude-flow/browser/src/application/session-capsule-service.ts
@@ -0,0 +1,325 @@
+/**
+ * @claude-flow/browser - Session Capsule Service (ADR-122 Phase 6)
+ *
+ * Seal / verify / mount / refresh / revoke for Session Capsules.
+ * Builds on Phase 1's witness signer + Phase 3's AIDefence-gated scanning.
+ *
+ * The capsule itself is signed and policy-enforced. Mounting in a browser
+ * session is delegated to ruflo-browexec (Phase 6.5+) β€” this module is the
+ * **substrate** sessiond that owns lifecycle and policy.
+ */
+
+import { createPublicKey, sign, verify } from 'node:crypto';
+import { randomBytes } from 'node:crypto';
+import { canonicalJSON, resolveWitnessKey, sha256Hex, type WitnessKey } from '../infrastructure/witness-signer.js';
+import { getSecurityScanner, type BrowserSecurityScanner, type ThreatScanResult } from '../infrastructure/security-integration.js';
+import {
+ AUTONOMOUS_CLASSES,
+ CAPSULE_ENVELOPE_KIND,
+ CAPSULE_ENVELOPE_VERSION,
+ SessionCapsuleEnvelopeSchema,
+ SessionCapsulePayloadSchema,
+ type SessionCapsuleEnvelope,
+ type SessionCapsulePayload,
+ type ConsentProof,
+ type InlineState,
+ type ReusePolicy,
+ type BrowserProfile,
+ type OriginPolicy,
+ type CapsuleVerificationResult,
+ type RiskClass,
+ type RiskClassification,
+} from '../domain/session-capsule.js';
+
+export interface CreateCapsuleInput {
+ tenantId: string;
+ ownerId: string;
+ origins: OriginPolicy[];
+ browserProfile?: BrowserProfile;
+ inlineState?: InlineState;
+ reusePolicy?: Partial<ReusePolicy>;
+ consentStatement: string;
+ /** Capsule lifetime in ms. Default 24h. */
+ ttlMs?: number;
+ /** Override witness key. */
+ witnessKey?: WitnessKey;
+ /** Project / installation ID (federation trust boundary). */
+ projectId?: string;
+}
+
+export class SessionCapsuleService {
+ private readonly witnessKey: WitnessKey;
+ private readonly scanner: BrowserSecurityScanner;
+ private readonly capsules = new Map<string, SessionCapsuleEnvelope>();
+
+ constructor(options: { witnessKey?: WitnessKey; scanner?: BrowserSecurityScanner } = {}) {
+ this.witnessKey = options.witnessKey ?? resolveWitnessKey();
+ this.scanner = options.scanner ?? getSecurityScanner();
+ }
+
+ /** Seal a new Session Capsule. PII-scans inline state before sealing. */
+ async create(input: CreateCapsuleInput): Promise<
+ | { success: true; envelope: SessionCapsuleEnvelope; capsuleId: string }
+ | { success: false; reason: string; piiCount: number; threatCount: number }
+ > {
+ const key = input.witnessKey ?? this.witnessKey;
+ const projectId = input.projectId ?? process.env.RUFLO_PROJECT_ID ?? 'unknown';
+
+ // Inline state is scanned cookie-by-cookie + storage value by value
+ if (input.inlineState) {
+ const scan = scanInlineState(input.inlineState, this.scanner);
+ if (!isClean(scan)) {
+ return {
+ success: false,
+ reason: 'inline state contains PII or threats',
+ piiCount: scan.pii.length,
+ threatCount: scan.threats.length,
+ };
+ }
+ }
+
+ const capsuleId = 'cap-' + Date.now() + '-' + randomBytes(4).toString('hex');
+ const now = new Date();
+ const ttl = input.ttlMs ?? 24 * 60 * 60 * 1000;
+ const reusePolicy: ReusePolicy = {
+ allowedOrigins: input.reusePolicy?.allowedOrigins ?? input.origins.map(o => o.origin),
+ allowedTaskClasses: input.reusePolicy?.allowedTaskClasses ?? ['read-only', 'authenticated-read'],
+ maxReplays: input.reusePolicy?.maxReplays ?? 0,
+ requireFreshMfa: input.reusePolicy?.requireFreshMfa ?? false,
+ allowCrossDevice: input.reusePolicy?.allowCrossDevice ?? false,
+ allowCrossInstallation: input.reusePolicy?.allowCrossInstallation ?? false,
+ };
+
+ const consentProof = signConsent(input.consentStatement, key);
+
+ const initialChainHead = sha256Hex(canonicalJSON({ capsuleId, createdAt: now.toISOString(), tenantId: input.tenantId }));
+
+ const payload: SessionCapsulePayload = SessionCapsulePayloadSchema.parse({
+ envelopeVersion: CAPSULE_ENVELOPE_VERSION,
+ kind: CAPSULE_ENVELOPE_KIND,
+ capsuleId,
+ tenantId: input.tenantId,
+ ownerId: input.ownerId,
+ projectId,
+ publicKey: key.publicKeyHex,
+ origins: input.origins,
+ browserProfile: input.browserProfile ?? {},
+ inlineState: input.inlineState,
+ stateRef: undefined,
+ reusePolicy,
+ consentProof,
+ witnessChainHead: initialChainHead,
+ replays: 0,
+ createdAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + ttl).toISOString(),
+ });
+
+ const canonical = canonicalJSON(payload);
+ const signature = sign(null, Buffer.from(canonical, 'utf8'), key.privateKey).toString('hex');
+ const envelope: SessionCapsuleEnvelope = { payload, signature, algorithm: 'ed25519' };
+ this.capsules.set(capsuleId, envelope);
+ return { success: true, envelope, capsuleId };
+ }
+
+ /** Verify a capsule's signature, schema, expiry, and replay count. */
+ verify(envelope: unknown, options: { trustedPublicKeys?: string[]; now?: Date } = {}): CapsuleVerificationResult {
+ const parsed = SessionCapsuleEnvelopeSchema.safeParse(envelope);
+ if (!parsed.success) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: false,
+ withinPolicy: false,
+ reason: 'capsule schema validation failed: ' + parsed.error.issues.map(i => i.path.join('.') + ' ' + i.message).join('; '),
+ };
+ }
+
+ const { payload, signature } = parsed.data;
+
+ if (options.trustedPublicKeys && !options.trustedPublicKeys.includes(payload.publicKey)) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ withinPolicy: false,
+ publicKey: payload.publicKey,
+ reason: 'signer public key not in trusted list',
+ };
+ }
+
+ let signatureValid = false;
+ try {
+ 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);
+ signatureValid = verify(null, Buffer.from(canonical, 'utf8'), publicKey, Buffer.from(signature, 'hex'));
+ } catch (err) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ withinPolicy: false,
+ publicKey: payload.publicKey,
+ reason: 'signature verification threw: ' + (err instanceof Error ? err.message : String(err)),
+ };
+ }
+
+ if (!signatureValid) {
+ return {
+ valid: false,
+ signatureValid: false,
+ schemaValid: true,
+ withinPolicy: false,
+ publicKey: payload.publicKey,
+ reason: 'signature verification failed (capsule tampered)',
+ };
+ }
+
+ // Policy check: expiry + replay count
+ const now = options.now ?? new Date();
+ const expiresAt = new Date(payload.expiresAt);
+ if (now.getTime() >= expiresAt.getTime()) {
+ return {
+ valid: false,
+ signatureValid: true,
+ schemaValid: true,
+ withinPolicy: false,
+ publicKey: payload.publicKey,
+ reason: 'capsule expired at ' + payload.expiresAt,
+ };
+ }
+
+ if (payload.reusePolicy.maxReplays > 0 && payload.replays >= payload.reusePolicy.maxReplays) {
+ return {
+ valid: false,
+ signatureValid: true,
+ schemaValid: true,
+ withinPolicy: false,
+ publicKey: payload.publicKey,
+ reason: 'replay count ' + payload.replays + ' β‰₯ maxReplays ' + payload.reusePolicy.maxReplays,
+ };
+ }
+
+ return {
+ valid: true,
+ signatureValid: true,
+ schemaValid: true,
+ withinPolicy: true,
+ publicKey: payload.publicKey,
+ };
+ }
+
+ /** Mount a capsule β€” records a replay attempt and increments the chain head. */
+ async mount(capsuleId: string, options: { taskClass?: RiskClass; targetOrigin?: string } = {}): Promise<
+ | { success: true; envelope: SessionCapsuleEnvelope }
+ | { success: false; reason: string }
+ > {
+ const envelope = this.capsules.get(capsuleId);
+ if (!envelope) return { success: false, reason: 'capsule not found' };
+
+ const verification = this.verify(envelope);
+ if (!verification.valid) return { success: false, reason: verification.reason ?? 'verification failed' };
+
+ if (options.targetOrigin && !envelope.payload.reusePolicy.allowedOrigins.includes(options.targetOrigin)) {
+ return { success: false, reason: 'target origin ' + options.targetOrigin + ' not in allowedOrigins' };
+ }
+ if (options.taskClass && !envelope.payload.reusePolicy.allowedTaskClasses.includes(options.taskClass)) {
+ return { success: false, reason: 'task class ' + options.taskClass + ' not in allowedTaskClasses' };
+ }
+
+ // Bump replays + chain head + re-sign.
+ const newReplays = envelope.payload.replays + 1;
+ const newChainHead = sha256Hex(envelope.payload.witnessChainHead + ':' + new Date().toISOString());
+ const newPayload: SessionCapsulePayload = {
+ ...envelope.payload,
+ replays: newReplays,
+ witnessChainHead: newChainHead,
+ };
+ const canonical = canonicalJSON(newPayload);
+ const newSignature = sign(null, Buffer.from(canonical, 'utf8'), this.witnessKey.privateKey).toString('hex');
+ const updated: SessionCapsuleEnvelope = { payload: newPayload, signature: newSignature, algorithm: 'ed25519' };
+ this.capsules.set(capsuleId, updated);
+ return { success: true, envelope: updated };
+ }
+
+ /** Revoke a capsule β€” drops it from the registry. */
+ revoke(capsuleId: string): boolean {
+ return this.capsules.delete(capsuleId);
+ }
+
+ get(capsuleId: string): SessionCapsuleEnvelope | undefined {
+ return this.capsules.get(capsuleId);
+ }
+
+ list(): readonly SessionCapsuleEnvelope[] {
+ return [...this.capsules.values()];
+ }
+
+ /** Test helper. */
+ getWitnessKeyPublicHex(): string {
+ return this.witnessKey.publicKeyHex;
+ }
+}
+
+/** Risk-class classifier β€” maps a planned action to one of the 7 classes. */
+export class RiskClassifier {
+ classify(input: { action: string; target?: string; goal?: string }): RiskClassification {
+ const verb = input.action;
+ const haystack = `${input.action} ${input.target ?? ''} ${input.goal ?? ''}`.toLowerCase();
+
+ // Class 7 β€” destructive
+ if (/(delete|destroy|wipe|drop|truncate)/.test(haystack)) {
+ return { class: 'destructive', autonomousAllowed: false, rationale: 'destructive verb detected', requiredConsent: ['destructive-action'] };
+ }
+ // Class 5 β€” financial
+ if (/(pay|payment|charge|invoice|refund|transfer|wire|withdraw|deposit)/.test(haystack)) {
+ return { class: 'financial', autonomousAllowed: false, rationale: 'financial action detected', requiredConsent: ['financial-action'] };
+ }
+ // Class 6 β€” account mutation
+ if (/(change.*password|reset.*password|update.*email|change.*account|2fa|two.factor)/.test(haystack)) {
+ return { class: 'account-mutation', autonomousAllowed: false, rationale: 'account mutation detected', requiredConsent: ['account-mutation'] };
+ }
+ // Class 4 β€” external submission
+ if ((verb === 'click' && /submit|send|publish|post/.test(haystack)) || /submit form/.test(haystack)) {
+ return { class: 'external-submission', autonomousAllowed: false, rationale: 'external submission detected', requiredConsent: ['external-submission'] };
+ }
+ // Class 3 β€” draft write
+ if (verb === 'fill' || verb === 'type') {
+ return { class: 'draft-write', autonomousAllowed: true, rationale: 'form-fill counts as draft write' };
+ }
+ // Class 2 β€” authenticated read
+ if (/dashboard|account|profile|inbox|orders|invoices|admin/.test(haystack)) {
+ return { class: 'authenticated-read', autonomousAllowed: true, rationale: 'authenticated read surface' };
+ }
+ // Class 1 β€” read-only default
+ return { class: 'read-only', autonomousAllowed: true, rationale: 'no mutation indicators' };
+ }
+
+ /** True iff the planned action is allowed for autonomous execution. */
+ isAutonomous(classification: RiskClassification): boolean {
+ return AUTONOMOUS_CLASSES.has(classification.class);
+ }
+}
+
+function isClean(scan: ThreatScanResult): boolean {
+ return scan.pii.length === 0 && scan.threats.length === 0;
+}
+
+function scanInlineState(state: InlineState, scanner: BrowserSecurityScanner): ThreatScanResult {
+ // Join cookie values + storage entries into one string for a single scanContent call.
+ // Note: do NOT spread the result of .join() β€” that would split the string into individual chars
+ // and the SSN/credit-card regexes (which need contiguous digits) would never match.
+ const cookieValues = state.cookies.map(c => c.value).join(' ');
+ const localKv = Object.entries(state.localStorage).map(([k, v]) => `${k}=${v}`).join(' ');
+ const sessionKv = Object.entries(state.sessionStorage).map(([k, v]) => `${k}=${v}`).join(' ');
+ const allValues = [cookieValues, localKv, sessionKv].join(' ');
+ return scanner.scanContent(allValues, 'session-capsule');
+}
+
+function signConsent(statement: string, key: WitnessKey): ConsentProof {
+ const now = new Date().toISOString();
+ const canonical = canonicalJSON({ statement, signedAt: now, ownerPublicKey: key.publicKeyHex });
+ const sig = sign(null, Buffer.from(canonical, 'utf8'), key.privateKey).toString('hex');
+ return { statement, signedAt: now, signature: sig, ownerPublicKey: key.publicKeyHex };
+}
diff --git a/v3/@claude-flow/browser/src/domain/browser-adapter.ts b/v3/@claude-flow/browser/src/domain/browser-adapter.ts
new file mode 100644
index 0000000000..fc18a0bde0
--- /dev/null
+++ b/v3/@claude-flow/browser/src/domain/browser-adapter.ts
@@ -0,0 +1,62 @@
+/**
+ * @claude-flow/browser - Browser Execution Adapter (ADR-122 Phase 6)
+ *
+ * Single interface above the browser-tool wars. Concrete adapters:
+ * - agent-browser (existing AgentBrowserAdapter β€” already wraps a Playwright CLI)
+ * - Stagehand (future)
+ * - Browserbase (future)
+ * - Browser Use (future)
+ * - local Chrome profile via CDP (future)
+ * - remote browser pool (future)
+ * - Surfer-H + Holo1 visual adapter (future)
+ *
+ * Phase 6 ships the interface + the AgentBrowserExecutionAdapter that wraps
+ * the existing adapter. Adding additional adapters in later phases is a
+ * single-file change (implement the interface + register in a factory).
+ */
+
+import type { ActionResult, Snapshot } from './types.js';
+
+/** Backend identifier. */
+export type AdapterBackend = 'agent-browser' | 'stagehand' | 'browserbase' | 'browser-use' | 'local-chrome' | 'remote-pool' | 'surfer-h';
+
+/** Standardized observation shape across all adapters. */
+export interface Observation {
+ url: string;
+ title: string;
+ snapshot?: Snapshot;
+ /** Optional screenshot β€” base64 PNG. */
+ screenshot?: string;
+ /** Origin of the page. */
+ origin: string;
+ /** Backend that produced this observation. */
+ backend: AdapterBackend;
+ timestamp: string;
+}
+
+export interface BrowserExecutionAdapter {
+ /** Identifier β€” what backend this adapter wraps. */
+ readonly backend: AdapterBackend;
+ /** Open a URL. */
+ open(url: string, options?: { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' }): Promise<ActionResult>;
+ /** Get an accessibility snapshot with refs. */
+ snapshot(options?: { interactive?: boolean; compact?: boolean }): Promise<ActionResult<Snapshot>>;
+ /** Click. */
+ click(target: string): Promise<ActionResult>;
+ /** Fill a form field. */
+ fill(target: string, value: string): Promise<ActionResult>;
+ /** Type with key events. */
+ type(target: string, text: string): Promise<ActionResult>;
+ /** Take a screenshot. */
+ screenshot(): Promise<ActionResult<string>>;
+ /** Wait for selector / time / condition. */
+ wait(input: { selector?: string; timeout?: number; text?: string; url?: string }): Promise<ActionResult>;
+ /** Get URL / title / text. */
+ getUrl(): Promise<ActionResult<string>>;
+ getTitle(): Promise<ActionResult<string>>;
+ getText(target: string): Promise<ActionResult<string>>;
+ /** Close. */
+ close(): Promise<ActionResult>;
+ /** Produce a normalised observation for current state. */
+ observe(): Promise<Observation>;
+}
diff --git a/v3/@claude-flow/browser/src/domain/session-capsule.ts b/v3/@claude-flow/browser/src/domain/session-capsule.ts
new file mode 100644
index 0000000000..8946f9367a
--- /dev/null
+++ b/v3/@claude-flow/browser/src/domain/session-capsule.ts
@@ -0,0 +1,169 @@
+/**
+ * @claude-flow/browser - Session Capsule (ADR-122 Phase 6)
+ *
+ * The Session Capsule is the substrate primitive: a sealed bundle of browser
+ * state with explicit origin policy, consent proof, expiry, reuse policy, and
+ * a witness chain. NEVER treat cookies as raw reusable blobs β€” OWASP guidance
+ * is unambiguous that session identifiers are security-critical.
+ *
+ * Phase 6 extends Phase 3's CookieVaultService into the full capsule model:
+ * - multi-store state (cookies + localStorage + sessionStorage + indexeddb metadata)
+ * - origin-scoped reuse policy
+ * - consent proof (signed by capsule owner)
+ * - cross-device / cross-installation flags
+ * - witness chain head (rolls forward on every refresh/rotate)
+ */
+
+import { z } from 'zod';
+
+/** Reuse policy β€” what callers can do with this capsule. */
+export const ReusePolicySchema = z.object({
+ /** Origins where this capsule may be mounted. */
+ allowedOrigins: z.array(z.string()).default([]),
+ /** Task classes allowed to use this capsule (e.g. ['read-only', 'authenticated-read']). */
+ allowedTaskClasses: z.array(z.string()).default(['read-only', 'authenticated-read']),
+ /** Maximum number of replays before forced re-auth. 0 = unlimited within expiry. */
+ maxReplays: z.number().int().nonnegative().default(0),
+ /** Require a fresh MFA before each mount. */
+ requireFreshMfa: z.boolean().default(false),
+ /** Allow mounting on a different device than the one that captured. */
+ allowCrossDevice: z.boolean().default(false),
+ /** Allow mounting on a different ruflo installation. */
+ allowCrossInstallation: z.boolean().default(false),
+});
+export type ReusePolicy = z.infer<typeof ReusePolicySchema>;
+
+export const OriginPolicySchema = z.object({
+ origin: z.string().min(1),
+ /** Cookie-domain restriction for entries in this capsule. */
+ cookieDomain: z.string().optional(),
+ /** Whether secure flag is required on cookies bound to this origin. */
+ requireSecure: z.boolean().default(true),
+ /** Whether httpOnly is required. */
+ requireHttpOnly: z.boolean().default(false),
+});
+export type OriginPolicy = z.infer<typeof OriginPolicySchema>;
+
+/** Consent proof β€” owner signed approval for this capsule's reuse policy. */
+export const ConsentProofSchema = z.object({
+ /** Statement the owner consented to. */
+ statement: z.string().min(1),
+ /** When the consent was given. */
+ signedAt: z.string(),
+ /** Signature (hex) over canonicalized {statement, signedAt, ownerPublicKey}. */
+ signature: z.string().regex(/^[0-9a-f]{128}$/),
+ /** Owner's public key (hex). May equal the witness key or be separate. */
+ ownerPublicKey: z.string().regex(/^[0-9a-f]{64}$/),
+});
+export type ConsentProof = z.infer<typeof ConsentProofSchema>;
+
+/** Browser profile fingerprint β€” keeps capsule playback consistent. */
+export const BrowserProfileSchema = z.object({
+ userAgent: z.string().optional(),
+ acceptLanguage: z.string().optional(),
+ viewport: z.object({ width: z.number().int().positive(), height: z.number().int().positive() }).optional(),
+ timezone: z.string().optional(),
+ /** Capsule-scoped device identifier; not a global device fingerprint. */
+ capsuleDeviceId: z.string().optional(),
+});
+export type BrowserProfile = z.infer<typeof BrowserProfileSchema>;
+
+/** Encrypted state blob reference β€” for state stored elsewhere (S3, RVF, disk). */
+export const StateRefSchema = z.object({
+ /** Storage scheme (e.g. 'file', 'rvf', 's3'). */
+ scheme: z.string().min(1),
+ /** Opaque locator within the scheme. */
+ locator: z.string().min(1),
+ /** SHA-256 of the encrypted blob for integrity. */
+ hash: z.string().regex(/^[0-9a-f]{64}$/),
+ /** Encryption identifier (algorithm + key reference). */
+ encryption: z.string().min(1),
+});
+export type StateRef = z.infer<typeof StateRefSchema>;
+
+/** Cookie+storage state inlined when small enough to skip the StateRef indirection. */
+export const InlineStateSchema = z.object({
+ cookies: z.array(z.object({
+ name: z.string(),
+ value: z.string(),
+ domain: z.string().optional(),
+ path: z.string().optional(),
+ expires: z.number().optional(),
+ httpOnly: z.boolean().optional(),
+ secure: z.boolean().optional(),
+ sameSite: z.enum(['Strict', 'Lax', 'None']).optional(),
+ })),
+ localStorage: z.record(z.string()).default({}),
+ sessionStorage: z.record(z.string()).default({}),
+ /** Metadata only β€” IndexedDB *contents* never leave the origin. */
+ indexedDbMeta: z.array(z.object({ dbName: z.string(), version: z.number().int() })).default([]),
+});
+export type InlineState = z.infer<typeof InlineStateSchema>;
+
+export const CAPSULE_ENVELOPE_VERSION = '1.0.0';
+export const CAPSULE_ENVELOPE_KIND = 'session-capsule';
+
+export const SessionCapsulePayloadSchema = z.object({
+ envelopeVersion: z.literal(CAPSULE_ENVELOPE_VERSION),
+ kind: z.literal(CAPSULE_ENVELOPE_KIND),
+ capsuleId: z.string().min(1),
+ tenantId: z.string().min(1),
+ ownerId: z.string().min(1),
+ /** Federation trust boundary (matches signed-trajectory `projectId`). */
+ projectId: z.string().min(1),
+ /** Witness public key (hex). */
+ publicKey: z.string().regex(/^[0-9a-f]{64}$/),
+ origins: z.array(OriginPolicySchema),
+ browserProfile: BrowserProfileSchema,
+ /** Either inline OR a StateRef β€” never both. */
+ inlineState: InlineStateSchema.optional(),
+ stateRef: StateRefSchema.optional(),
+ reusePolicy: ReusePolicySchema,
+ consentProof: ConsentProofSchema,
+ /** Witness-chain head β€” rolls forward on every mutation (refresh/rotate). */
+ witnessChainHead: z.string().regex(/^[0-9a-f]{64}$/),
+ /** Replay counter β€” incremented on every successful mount. */
+ replays: z.number().int().nonnegative().default(0),
+ createdAt: z.string(),
+ expiresAt: z.string(),
+});
+export type SessionCapsulePayload = z.infer<typeof SessionCapsulePayloadSchema>;
+
+export const SessionCapsuleEnvelopeSchema = z.object({
+ payload: SessionCapsulePayloadSchema,
+ signature: z.string().regex(/^[0-9a-f]{128}$/),
+ algorithm: z.literal('ed25519'),
+});
+export type SessionCapsuleEnvelope = z.infer<typeof SessionCapsuleEnvelopeSchema>;
+
+/** Risk classes for autonomous action gating. */
+export const RiskClassSchema = z.enum([
+ 'read-only', // Class 1
+ 'authenticated-read', // Class 2
+ 'draft-write', // Class 3 β€” autonomous OK
+ 'external-submission', // Class 4 β€” human approval
+ 'financial', // Class 5 β€” human approval
+ 'account-mutation', // Class 6 β€” human approval
+ 'destructive', // Class 7 β€” human approval
+]);
+export type RiskClass = z.infer<typeof RiskClassSchema>;
+
+export const AUTONOMOUS_CLASSES: ReadonlySet<RiskClass> = new Set(['read-only', 'authenticated-read', 'draft-write']);
+
+export interface RiskClassification {
+ class: RiskClass;
+ autonomousAllowed: boolean;
+ rationale: string;
+ /** Required additional consent if autonomousAllowed = false. */
+ requiredConsent?: string[];
+}
+
+export interface CapsuleVerificationResult {
+ valid: boolean;
+ signatureValid: boolean;
+ schemaValid: boolean;
+ /** True iff capsule has not expired AND replay count is under maxReplays. */
+ withinPolicy: boolean;
+ reason?: string;
+ publicKey?: string;
+}
diff --git a/v3/@claude-flow/browser/src/index.ts b/v3/@claude-flow/browser/src/index.ts
index 2bc94c65a6..1455fdbcb8 100644
--- a/v3/@claude-flow/browser/src/index.ts
+++ b/v3/@claude-flow/browser/src/index.ts
@@ -166,6 +166,46 @@ export {
type RecoveryExplanation,
} from './domain/causal-recovery.js';
+// Session Capsule + Risk Classifier + Browser Execution Adapter (ADR-122 Phase 6 β€” substrate)
+export {
+ SessionCapsuleService,
+ RiskClassifier,
+ type CreateCapsuleInput,
+} from './application/session-capsule-service.js';
+export {
+ CAPSULE_ENVELOPE_VERSION,
+ CAPSULE_ENVELOPE_KIND,
+ SessionCapsuleEnvelopeSchema,
+ SessionCapsulePayloadSchema,
+ ReusePolicySchema,
+ OriginPolicySchema,
+ ConsentProofSchema,
+ BrowserProfileSchema,
+ StateRefSchema,
+ InlineStateSchema,
+ RiskClassSchema,
+ AUTONOMOUS_CLASSES,
+ type SessionCapsuleEnvelope,
+ type SessionCapsulePayload,
+ type ReusePolicy,
+ type OriginPolicy,
+ type ConsentProof,
+ type BrowserProfile,
+ type StateRef,
+ type InlineState,
+ type RiskClass,
+ type RiskClassification,
+ type CapsuleVerificationResult,
+} from './domain/session-capsule.js';
+export {
+ AgentBrowserExecutionAdapter,
+} from './infrastructure/agent-browser-execution-adapter.js';
+export type {
+ BrowserExecutionAdapter,
+ Observation,
+ AdapterBackend,
+} from './domain/browser-adapter.js';
+
// Cost-aware action routing + GOAP preflight (ADR-122 Phase 5)
export {
ActionRouter,
diff --git a/v3/@claude-flow/browser/src/infrastructure/agent-browser-execution-adapter.ts b/v3/@claude-flow/browser/src/infrastructure/agent-browser-execution-adapter.ts
new file mode 100644
index 0000000000..230e07d284
--- /dev/null
+++ b/v3/@claude-flow/browser/src/infrastructure/agent-browser-execution-adapter.ts
@@ -0,0 +1,87 @@
+/**
+ * @claude-flow/browser - Agent-Browser Execution Adapter (ADR-122 Phase 6)
+ *
+ * The first concrete BrowserExecutionAdapter β€” wraps the existing
+ * AgentBrowserAdapter so callers can program against the substrate interface
+ * without caring which backend they're talking to.
+ */
+
+import { AgentBrowserAdapter } from './agent-browser-adapter.js';
+import type { ActionResult, Snapshot } from '../domain/types.js';
+import type { BrowserExecutionAdapter, Observation, AdapterBackend } from '../domain/browser-adapter.js';
+
+export class AgentBrowserExecutionAdapter implements BrowserExecutionAdapter {
+ readonly backend: AdapterBackend = 'agent-browser';
+ private readonly adapter: AgentBrowserAdapter;
+
+ constructor(adapter?: AgentBrowserAdapter) {
+ this.adapter = adapter ?? new AgentBrowserAdapter();
+ }
+
+ open(url: string, options?: { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' }): Promise<ActionResult> {
+ return this.adapter.open({ url, waitUntil: options?.waitUntil });
+ }
+
+ snapshot(options?: { interactive?: boolean; compact?: boolean }): Promise<ActionResult<Snapshot>> {
+ return this.adapter.snapshot({ interactive: options?.interactive, compact: options?.compact });
+ }
+
+ click(target: string): Promise<ActionResult> {
+ return this.adapter.click({ target });
+ }
+
+ fill(target: string, value: string): Promise<ActionResult> {
+ return this.adapter.fill({ target, value });
+ }
+
+ type(target: string, text: string): Promise<ActionResult> {
+ return this.adapter.type({ target, text });
+ }
+
+ screenshot(): Promise<ActionResult<string>> {
+ return this.adapter.screenshot();
+ }
+
+ wait(input: { selector?: string; timeout?: number; text?: string; url?: string }): Promise<ActionResult> {
+ return this.adapter.wait(input);
+ }
+
+ getUrl(): Promise<ActionResult<string>> {
+ return this.adapter.getUrl();
+ }
+
+ getTitle(): Promise<ActionResult<string>> {
+ return this.adapter.getTitle();
+ }
+
+ getText(target: string): Promise<ActionResult<string>> {
+ return this.adapter.getText(target);
+ }
+
+ close(): Promise<ActionResult> {
+ return this.adapter.close();
+ }
+
+ async observe(): Promise<Observation> {
+ const [urlResult, titleResult, snapshotResult] = await Promise.all([
+ this.getUrl(),
+ this.getTitle(),
+ this.snapshot({ interactive: true, compact: true }),
+ ]);
+ const url = (urlResult.data as string) ?? '';
+ let origin = '';
+ try {
+ origin = url ? new URL(url).origin : '';
+ } catch {
+ origin = url;
+ }
+ return {
+ url,
+ title: (titleResult.data as string) ?? '',
+ snapshot: snapshotResult.data as Snapshot | undefined,
+ origin,
+ backend: this.backend,
+ timestamp: new Date().toISOString(),
+ };
+ }
+}
diff --git a/v3/@claude-flow/browser/tests/session-capsule.test.ts b/v3/@claude-flow/browser/tests/session-capsule.test.ts
new file mode 100644
index 0000000000..7b237eb158
--- /dev/null
+++ b/v3/@claude-flow/browser/tests/session-capsule.test.ts
@@ -0,0 +1,249 @@
+/**
+ * @claude-flow/browser - Session Capsule + Risk Classifier Tests (ADR-122 Phase 6)
+ *
+ * Acceptance criteria covered:
+ * - Capsule with PII in inline state is refused at creation
+ * - Clean capsule verifies, mounts, and increments replays
+ * - Capsule with maxReplays cap rejects further mounts past the limit
+ * - Expired capsule fails verification
+ * - Trust-list filter accepts/rejects by signer
+ * - Mount enforces allowedOrigins + allowedTaskClasses
+ * - Tampered capsule fails signature verification
+ * - RiskClassifier produces correct class for representative actions
+ */
+
+import { describe, it, expect } from 'vitest';
+import { SessionCapsuleService, RiskClassifier } from '../src/application/session-capsule-service.js';
+import { generateWitnessKey } from '../src/infrastructure/witness-signer.js';
+import type { SessionCapsuleEnvelope } from '../src/domain/session-capsule.js';
+
+const cleanState = {
+ cookies: [{ name: 'sid', value: 'opaque-token-xyz', domain: 'example.com' }],
+ localStorage: { theme: 'dark' },
+ sessionStorage: {},
+ indexedDbMeta: [],
+};
+
+const piiState = {
+ cookies: [{ name: 'sid', value: 'name=John Doe ssn=123-45-6789', domain: 'example.com' }],
+ localStorage: {},
+ sessionStorage: {},
+ indexedDbMeta: [],
+};
+
+describe('SessionCapsuleService', () => {
+ describe('create', () => {
+ it('seals a clean capsule with verifiable signature', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 'tenant-1',
+ ownerId: 'owner-a',
+ origins: [{ origin: 'https://example.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState,
+ consentStatement: 'I consent to reuse this session for authenticated reads of example.com',
+ });
+ expect(result.success).toBe(true);
+ if (!result.success) return;
+ expect(result.envelope.payload.capsuleId).toMatch(/^cap-/);
+ expect(result.envelope.payload.replays).toBe(0);
+ expect(result.envelope.payload.witnessChainHead).toMatch(/^[0-9a-f]{64}$/);
+ const verification = svc.verify(result.envelope);
+ expect(verification.valid).toBe(true);
+ expect(verification.withinPolicy).toBe(true);
+ });
+
+ it('refuses a capsule whose inline state contains PII', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 'tenant-1',
+ ownerId: 'owner-a',
+ origins: [{ origin: 'https://example.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: piiState,
+ consentStatement: 'test',
+ });
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.piiCount).toBeGreaterThan(0);
+ });
+
+ it('defaults reusePolicy.allowedTaskClasses to safe defaults', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 'tenant-1', ownerId: 'o', origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ });
+ if (!result.success) throw new Error('expected success');
+ expect(result.envelope.payload.reusePolicy.allowedTaskClasses).toContain('read-only');
+ expect(result.envelope.payload.reusePolicy.allowedTaskClasses).not.toContain('destructive');
+ });
+ });
+
+ describe('verify', () => {
+ it('rejects expired capsules', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok', ttlMs: 100,
+ });
+ if (!result.success) throw new Error('expected success');
+ const verification = svc.verify(result.envelope, { now: new Date(Date.now() + 60_000) });
+ expect(verification.valid).toBe(false);
+ expect(verification.reason).toMatch(/expired/);
+ });
+
+ it('rejects tampered capsules', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ });
+ if (!result.success) throw new Error('expected success');
+ const forged: SessionCapsuleEnvelope = JSON.parse(JSON.stringify(result.envelope));
+ forged.payload.reusePolicy.allowCrossInstallation = true; // escalate
+ const verification = svc.verify(forged);
+ expect(verification.valid).toBe(false);
+ expect(verification.signatureValid).toBe(false);
+ });
+
+ it('rejects untrusted signers via trust list', async () => {
+ const stranger = new SessionCapsuleService({ witnessKey: generateWitnessKey() });
+ const result = await stranger.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ });
+ if (!result.success) throw new Error('expected success');
+ const ourVault = new SessionCapsuleService();
+ const verification = ourVault.verify(result.envelope, { trustedPublicKeys: ['00'.repeat(32)] });
+ expect(verification.valid).toBe(false);
+ expect(verification.reason).toMatch(/not in trusted list/);
+ });
+ });
+
+ describe('mount', () => {
+ it('increments replays and rolls the chain head', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ });
+ if (!result.success) throw new Error('expected success');
+ const before = result.envelope.payload.witnessChainHead;
+ const mounted = await svc.mount(result.capsuleId);
+ expect(mounted.success).toBe(true);
+ if (!mounted.success) return;
+ expect(mounted.envelope.payload.replays).toBe(1);
+ expect(mounted.envelope.payload.witnessChainHead).not.toBe(before);
+ });
+
+ it('rejects mounts past maxReplays', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ reusePolicy: { maxReplays: 2 },
+ });
+ if (!result.success) throw new Error('expected success');
+ const m1 = await svc.mount(result.capsuleId);
+ expect(m1.success).toBe(true);
+ const m2 = await svc.mount(result.capsuleId);
+ expect(m2.success).toBe(true);
+ const m3 = await svc.mount(result.capsuleId);
+ expect(m3.success).toBe(false);
+ if (m3.success) return;
+ expect(m3.reason).toMatch(/maxReplays|replay count/);
+ });
+
+ it('rejects mount on origin not in allowedOrigins', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://example.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ reusePolicy: { allowedOrigins: ['https://example.com'] },
+ });
+ if (!result.success) throw new Error('expected success');
+ const mounted = await svc.mount(result.capsuleId, { targetOrigin: 'https://malicious.com' });
+ expect(mounted.success).toBe(false);
+ if (mounted.success) return;
+ expect(mounted.reason).toMatch(/origin/);
+ });
+
+ it('rejects mount with a task class not in allowedTaskClasses', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ reusePolicy: { allowedTaskClasses: ['read-only'] },
+ });
+ if (!result.success) throw new Error('expected success');
+ const mounted = await svc.mount(result.capsuleId, { taskClass: 'destructive' });
+ expect(mounted.success).toBe(false);
+ if (mounted.success) return;
+ expect(mounted.reason).toMatch(/task class/);
+ });
+ });
+
+ describe('revoke', () => {
+ it('drops the capsule from the registry', async () => {
+ const svc = new SessionCapsuleService();
+ const result = await svc.create({
+ tenantId: 't', ownerId: 'o',
+ origins: [{ origin: 'https://x.com', requireSecure: true, requireHttpOnly: false }],
+ inlineState: cleanState, consentStatement: 'ok',
+ });
+ if (!result.success) throw new Error('expected success');
+ expect(svc.revoke(result.capsuleId)).toBe(true);
+ expect(svc.get(result.capsuleId)).toBeUndefined();
+ const remount = await svc.mount(result.capsuleId);
+ expect(remount.success).toBe(false);
+ });
+ });
+});
+
+describe('RiskClassifier', () => {
+ const classifier = new RiskClassifier();
+
+ it('classifies destructive verbs as Class 7', () => {
+ expect(classifier.classify({ action: 'click', target: 'Delete account', goal: 'delete user' }).class).toBe('destructive');
+ });
+
+ it('classifies financial actions as Class 5', () => {
+ expect(classifier.classify({ action: 'click', target: 'Pay invoice', goal: 'submit payment' }).class).toBe('financial');
+ });
+
+ it('classifies account mutation as Class 6', () => {
+ expect(classifier.classify({ action: 'fill', target: 'New password', goal: 'change password' }).class).toBe('account-mutation');
+ });
+
+ it('classifies submit clicks as Class 4 external submission', () => {
+ expect(classifier.classify({ action: 'click', target: 'Submit form', goal: 'send' }).class).toBe('external-submission');
+ });
+
+ it('classifies fill/type as Class 3 draft write', () => {
+ expect(classifier.classify({ action: 'fill', target: '@e1', goal: 'enter email' }).class).toBe('draft-write');
+ });
+
+ it('classifies dashboard reads as Class 2', () => {
+ expect(classifier.classify({ action: 'open', target: '/dashboard', goal: 'view dashboard' }).class).toBe('authenticated-read');
+ });
+
+ it('defaults to Class 1 read-only', () => {
+ expect(classifier.classify({ action: 'snapshot' }).class).toBe('read-only');
+ });
+
+ it('blocks autonomous execution for Class 4+', () => {
+ expect(classifier.isAutonomous(classifier.classify({ action: 'click', target: 'Submit', goal: 'submit form' }))).toBe(false);
+ expect(classifier.isAutonomous(classifier.classify({ action: 'click', target: 'Pay', goal: 'pay invoice' }))).toBe(false);
+ });
+
+ it('allows autonomous execution for Class 1-3', () => {
+ expect(classifier.isAutonomous(classifier.classify({ action: 'snapshot' }))).toBe(true);
+ expect(classifier.isAutonomous(classifier.classify({ action: 'fill', target: '@e1' }))).toBe(true);
+ });
+});
diff --git a/v3/docs/adr/ADR-122-browser-beyond-sota.md b/v3/docs/adr/ADR-122-browser-beyond-sota.md
index 0f406dd0a4..17baaf59b4 100644
--- a/v3/docs/adr/ADR-122-browser-beyond-sota.md
+++ b/v3/docs/adr/ADR-122-browser-beyond-sota.md
@@ -1,11 +1,33 @@
-# ADR-122 β€” `@claude-flow/browser` beyond-SOTA: signed trajectories, causal self-healing, federated MCTS
+# ADR-122 β€” RuFlo Browser Substrate: signed trajectories, causal self-healing, federated MCTS, session capsules
-**Status**: Proposed (2026-05-18)
+**Status**: Proposed (2026-05-18) β€” revised 2026-05-18 to reframe as substrate
**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)
+**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), [Reflective MCTS for web agents (arXiv 2410.02052)](https://arxiv.org/abs/2410.02052), [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html), [Browserbase Stagehand](https://www.browserbase.com/blog/browser-automation-all-languages-with-stagehand/)
**Supersedes**: nothing (additive)
+## Core thesis (revised)
+
+**RuFlo is not a browser agent. RuFlo is the memory, policy, replay, and distributed-planning substrate underneath browser agents.**
+
+Stagehand, Browser Use, Surfer-H, Playwright, Chrome, Browserbase, local browsers, and cloud browser pools become **execution targets**. RuFlo owns: memory, auth state, planning, replay, scoring, policy, learning, and cross-installation coordination.
+
+The public stack today is:
+
+```
+agent β†’ browser β†’ action β†’ observation β†’ next action
+```
+
+RuFlo should be:
+
+```
+agent β†’ governed Session Capsule β†’ distributed MCTS search β†’
+ Browser Execution Adapter β†’ replay verification β†’ RuVector memory β†’
+ Workflow Compiler β†’ reusable RuFlo primitive
+```
+
+That is the architectural jump and the defensible SOTA claim.
+
## Context
There are **two browser systems** in this repo, drifting apart:
@@ -47,9 +69,92 @@ This ADR converges the two ruflo browser systems and commits to three wedges tha
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.
+## Architecture (substrate)
+
+### Layered system
+
+1. **Browser Execution Adapters** β€” Playwright, Stagehand, Browser Use, Browserbase, local Chrome profile, remote browser pool, future Surfer-H visual adapter. Single interface; RuFlo stays above the tool wars.
+2. **Session Capsule Layer** β€” sealed browser-state bundles with origin policy, consent proof, expiry, reuse policy, and witness chain. Cookies, localStorage, sessionStorage, IndexedDB metadata, browser fingerprint profile β€” never raw reusable blobs.
+3. **Distributed MCTS Layer** β€” risk/cost/auth-aware UCT search distributed across federation peers. Reflective MCTS extended to persist across runs and installations.
+4. **Cross-Installation Search Fabric** β€” Explorer / Verifier / Critic / Recorder / Learner / Coordinator node roles. CRDT or append-only event-log merge of search-tree deltas. **Search deltas shared by default; raw secrets never.**
+5. **RuVector Memory** β€” DOM/screenshot/task embeddings, site-flow graphs, selector-reliability vectors, MCTS node summaries. The recall path that gates the cost of a fresh exploration.
+6. **Workflow Compiler** β€” successful MCTS traces become deterministic workflows with selector fallback graphs, test harnesses, policy manifests, and ADR traces.
+7. **Policy & Risk Layer** β€” risk-class taxonomy gates autonomous action. Only read-only / authenticated-read / draft-write run autonomously by default.
+
+### Runtime services
+
+| Service | Responsibility |
+|---|---|
+| `ruflo-sessiond` | Capture / seal / refresh / rotate / revoke Session Capsules. Mount into browser context. Audit reuse. |
+| `ruflo-browexec` | Adapter dispatch. Launch browser via chosen adapter; apply capsule; execute action; emit trace event. |
+| `ruflo-mcts` | Distributed tree search engine. Select / expand / simulate / score / backprop / publish delta. |
+| `ruflo-replayd` | Replay successful runs; verify; generalize selectors; produce fallback paths; create workflow artifact. |
+| `ruflo-critic` | Policy + risk evaluation. Detects irreversible actions; scores auth/site risk; enforces consent; blocks unsafe transitions. |
+| `ruflo-memory` | RuVector-backed embeddings + similarity retrieval; failure clustering; reusable-path ranking. |
+
+### Risk classes (autonomous-action gate)
+
+| Class | Description | Autonomous? |
+|---|---|---|
+| 1 | Read-only | βœ… |
+| 2 | Authenticated read | βœ… |
+| 3 | Draft write | βœ… |
+| 4 | External submission | ❌ human approval |
+| 5 | Financial action | ❌ human approval |
+| 6 | Account mutation | ❌ human approval |
+| 7 | Destructive | ❌ human approval |
+
+### Session Capsule schema
+
+```rust
+pub struct SessionCapsule {
+ pub capsule_id: CapsuleId,
+ pub tenant_id: TenantId,
+ pub owner_id: OwnerId,
+ pub origins: Vec<OriginPolicy>,
+ pub browser_profile: BrowserProfile,
+ pub encrypted_state_ref: StateRef,
+ pub created_at: Timestamp,
+ pub expires_at: Timestamp,
+ pub reuse_policy: ReusePolicy,
+ pub consent_proof: ConsentProof,
+ pub witness_chain_head: Hash256,
+}
+pub struct ReusePolicy {
+ pub allowed_origins: Vec<String>,
+ pub allowed_tasks: Vec<TaskClass>,
+ pub max_replays: u32,
+ pub require_fresh_mfa: bool,
+ pub allow_cross_device: bool,
+ pub allow_cross_installation: bool,
+}
+```
+
+The Phase 3 attested cookie vault is the **subset** of this β€” extended in Phase 6 to full SessionCapsule with multi-store state, browser fingerprint, and ReusePolicy.
+
+### Production-aware UCT scoring
+
+```
+score = Q + C·√(ln(parent_visits) / child_visits) + R βˆ’ λ·risk βˆ’ ΞΌΒ·cost βˆ’ Ξ±Β·auth
+```
+
+Where `Q` = task value, `R` = replay bonus, `λ·risk` = irreversible-action penalty, `μ·cost` = token + browser-runtime cost, `α·auth` = session-fragility penalty. Phase 4's UCB1 implementation is extended in Phase 6 to use this production-aware formula.
+
+### SOTA scoring rubric
+
+| Dimension | Target |
+|---|---|
+| Completion rate | > 85% |
+| Replay success | > 90% on stable sites |
+| Auth reuse success | > 95% within allowed expiry |
+| Human intervention rate | < 10% (read-only tasks) |
+| Token reduction from memory | > 30% |
+| Unsafe action escape rate | 0% |
+| Trace completeness | 100% for privileged actions |
+
## 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.
+Land the substrate in **eight phases**, each shippable alone, each opt-in via configuration. Phases 0–2 are convergence; phases 3–5 are the original beyond-SOTA wedges; phases 6–7 are the substrate framing.
### Phase 0 β€” Upgrade `agent-browser` 0.6 β†’ 0.27 and converge the two systems
@@ -142,16 +247,38 @@ Compose with existing ruflo primitives β€” no new architecture:
**Non-goals (Phase 5):** retraining a model for routing; reuse the existing intelligence pipeline.
+### Phase 6 β€” Substrate primitives: Session Capsule + adapter abstraction + risk classes
+
+Extend Phase 3's cookie vault into the full **SessionCapsule** model (origins[], browser-profile, encrypted-state-ref, reuse-policy, consent-proof, witness-chain-head). Expose a single `BrowserExecutionAdapter` interface that wraps the existing AgentBrowserAdapter and adds shim adapters for Playwright/Stagehand/Browserbase/local Chrome. Add a `RiskClassifier` that maps planned actions to the 7-class risk taxonomy and gates autonomous execution.
+
+**Acceptance:**
+- Login-once / reuse-many round-trip works across two installations (same project key) with policy enforcement
+- `BrowserExecutionAdapter.execute()` dispatches to β‰₯2 backends (agent-browser + one of Playwright/Stagehand) with byte-identical observation shape
+- Risk-class-4-and-above actions block on `approval_required` events
+- `ConsentProof` is signed + verifiable; revoke flow invalidates downstream replays
+
+### Phase 7 β€” Workflow Compiler + production-aware UCT
+
+Compile winning MCTS traces (Phase 4) into deterministic YAML workflows with selector fallback graphs and policy manifests. Extend Phase 4's UCB1 to use the production-aware formula (Q + C·√(ln(N)/n) + R βˆ’ λ·risk βˆ’ ΞΌΒ·cost βˆ’ Ξ±Β·auth). Add the Recorder/Learner node roles for cross-installation workflow exchange.
+
+**Acceptance:**
+- A successful MCTS trace compiles to a YAML workflow with β‰₯1 selector fallback per step
+- Replaying the compiled workflow on a fresh installation succeeds end-to-end (without re-exploration)
+- Production-aware UCT scores correlate with measured replay-success on a held-out benchmark
+- β‰₯30% token reduction on a second run of a previously-solved task (rubric row 5)
+
## 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 |
+| 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 βœ… |
+| 6 | Session Capsule + adapters + risk classes | Capsule schema + BrowserExecutionAdapter + RiskClassifier | alpha.10 🚧 |
+| 7 | Workflow Compiler + production-aware UCT | YAML workflows + selector fallback graphs + UCT extension | alpha.11 ⏳ |
## Open questions