π 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 3 + Phase 4 β attested cookie vault + federated MCTS
ruvdfb7747b326c
diff --git a/v3/@claude-flow/browser/src/application/cookie-vault-service.ts b/v3/@claude-flow/browser/src/application/cookie-vault-service.tsnew file mode 100644index 0000000000..736ef5c3bc--- /dev/null+++ b/v3/@claude-flow/browser/src/application/cookie-vault-service.ts@@ -0,0 +1,283 @@+/**+ * @claude-flow/browser - Cookie Vault Service (ADR-122 Phase 3)+ *+ * Attested cookie vault: every write is gated by AIDefence PII scanning, then+ * sealed with an Ed25519 witness signature. Consumers MUST call+ * verifyAttestation() before attaching a sealed handle to a live session.+ *+ * Phase 3 implementation is in-memory with optional JSON-on-disk persistence;+ * Phase 3.5 swaps storage for an RVF cognitive container (`@ruvector/rvf`).+ * The public surface does not 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 {+ signTrajectory as _unused, // kept for backwards-compat with witness-signer import path+ verifyTrajectory as _unused2,+} from '../infrastructure/witness-signer.js';+import {+ generateWitnessKey,+ loadWitnessKey,+ resolveWitnessKey,+ sha256Hex,+ canonicalJSON,+ type WitnessKey,+} from '../infrastructure/witness-signer.js';+import { createPublicKey, sign, verify } from 'node:crypto';+import {+ BrowserSecurityScanner,+ getSecurityScanner,+ type ThreatScanResult,+} from '../infrastructure/security-integration.js';+import {+ VAULT_ENVELOPE_KIND,+ VAULT_ENVELOPE_VERSION,+ VaultEntryEnvelopeSchema,+ VaultEntryPayloadSchema,+ type CookieValue,+ type ScanAttestation,+ type VaultEntryEnvelope,+ type VaultEntryPayload,+ type VaultRefusal,+ type VaultVerificationResult,+} from '../domain/cookie-vault.js';++/** Where the attestation data came from. Default scanner is the bundled BrowserSecurityScanner. */+export interface CookieVaultScannerInfo {+ name: string;+ version: string;+}++export interface CookieVaultServiceOptions {+ /** Witness key to sign with. Default resolves from env or generates ephemeral. */+ witnessKey?: WitnessKey;+ /** Override the scanner. Default uses the package's BrowserSecurityScanner. */+ scanner?: BrowserSecurityScanner;+ /** Identity for the embedded scanner attestation (default: [email protected]). */+ scannerInfo?: CookieVaultScannerInfo;+ /** Project ID (federation trust boundary). */+ projectId?: string;+ /** Persist refusals + entries to this path (JSON). */+ persistPath?: string;+}++interface VaultState {+ entries: VaultEntryEnvelope[];+ refusals: VaultRefusal[];+}++export class CookieVaultService {+ private readonly witnessKey: WitnessKey;+ private readonly scanner: BrowserSecurityScanner;+ private readonly scannerInfo: CookieVaultScannerInfo;+ private readonly projectId: string;+ private readonly persistPath?: string;+ private state: VaultState = { entries: [], refusals: [] };++ constructor(options: CookieVaultServiceOptions = {}) {+ this.witnessKey = options.witnessKey ?? resolveWitnessKey();+ this.scanner = options.scanner ?? getSecurityScanner();+ this.scannerInfo = options.scannerInfo ?? { name: 'aidefence-bundled', version: '2.3.0' };+ this.projectId = options.projectId ?? process.env.RUFLO_PROJECT_ID ?? 'unknown';+ this.persistPath = options.persistPath;+ }++ /**+ * Store a cookie in the vault. The value is scanned by AIDefence before+ * persistence; failures are recorded as audit refusals and the entry is+ * NOT persisted.+ *+ * Returns the sealed envelope on success or a structured failure result.+ */+ async store(input: {+ cookie: CookieValue;+ origin?: string;+ /** Override the witness key for this single store call (federation rotation). */+ witnessKey?: WitnessKey;+ }): Promise<+ | { success: true; envelope: VaultEntryEnvelope; handleId: string }+ | { success: false; refusal: VaultRefusal }+ > {+ const key = input.witnessKey ?? this.witnessKey;+ const scanResult = this.scanner.scanContent(input.cookie.value, 'cookie:' + input.cookie.name);++ if (!isClean(scanResult)) {+ const refusal: VaultRefusal = {+ attemptedAt: new Date().toISOString(),+ origin: input.origin ?? input.cookie.domain,+ cookieName: input.cookie.name,+ reason: 'AIDefence detected ' + scanResult.pii.length + ' PII + ' + scanResult.threats.length + ' threats',+ piiCount: scanResult.pii.length,+ threatCount: scanResult.threats.length,+ };+ this.state.refusals.push(refusal);+ await this.maybePersist();+ return { success: false, refusal };+ }++ const handleId = 'vh-' + Date.now() + '-' + randomBytes(3).toString('hex');+ const attestation: ScanAttestation = {+ scannerName: this.scannerInfo.name,+ scannerVersion: this.scannerInfo.version,+ scannedAt: new Date().toISOString(),+ clean: true,+ piiCount: 0,+ threatCount: 0,+ contentHash: sha256Hex(input.cookie.value),+ };++ const payload: VaultEntryPayload = VaultEntryPayloadSchema.parse({+ envelopeVersion: VAULT_ENVELOPE_VERSION,+ kind: VAULT_ENVELOPE_KIND,+ handleId,+ projectId: this.projectId,+ publicKey: key.publicKeyHex,+ cookie: input.cookie,+ attestation,+ sealedAt: new Date().toISOString(),+ origin: input.origin ?? input.cookie.domain,+ });++ const canonical = canonicalJSON(payload);+ const signature = sign(null, Buffer.from(canonical, 'utf8'), key.privateKey).toString('hex');++ const envelope: VaultEntryEnvelope = { payload, signature, algorithm: 'ed25519' };+ this.state.entries.push(envelope);+ await this.maybePersist();+ return { success: true, envelope, handleId };+ }++ /**+ * Verify a sealed envelope. Federation peers MUST call this before reusing+ * a foreign cookie handle. Optional `trustedPublicKeys` filters by signer.+ */+ verifyAttestation(envelope: unknown, options: { trustedPublicKeys?: string[] } = {}): VaultVerificationResult {+ const parsed = VaultEntryEnvelopeSchema.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;++ if (options.trustedPublicKeys && !options.trustedPublicKeys.includes(payload.publicKey)) {+ return {+ valid: false,+ signatureValid: false,+ schemaValid: true,+ publicKey: payload.publicKey,+ attestation: payload.attestation,+ reason: 'signer public key not in trusted list',+ };+ }++ // Attestation sanity: refuse anything claiming `clean: false` (the scanner+ // should never have produced a sealed envelope at all in that state).+ if (!payload.attestation.clean) {+ return {+ valid: false,+ signatureValid: false,+ schemaValid: true,+ publicKey: payload.publicKey,+ attestation: payload.attestation,+ reason: 'attestation declares unclean β entries with clean=false must never be sealed',+ };+ }++ // Content hash must still match the cookie value β protects against+ // someone replacing payload.cookie.value but forgetting to update the hash.+ const expectedHash = sha256Hex(payload.cookie.value);+ if (expectedHash !== payload.attestation.contentHash) {+ return {+ valid: false,+ signatureValid: false,+ schemaValid: true,+ publicKey: payload.publicKey,+ attestation: payload.attestation,+ reason: 'cookie value hash mismatch β cookie was tampered after attestation',+ };+ }++ 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);+ const signatureValid = verify(null, Buffer.from(canonical, 'utf8'), publicKey, Buffer.from(signature, 'hex'));+ return {+ valid: signatureValid,+ signatureValid,+ schemaValid: true,+ publicKey: payload.publicKey,+ attestation: payload.attestation,+ reason: signatureValid ? undefined : 'signature verification failed (envelope tampered)',+ };+ } catch (err) {+ return {+ valid: false,+ signatureValid: false,+ schemaValid: true,+ publicKey: payload.publicKey,+ attestation: payload.attestation,+ reason: 'signature verification threw: ' + (err instanceof Error ? err.message : String(err)),+ };+ }+ }++ /** Look up a vault entry by handle ID; returns undefined when not found. */+ getByHandle(handleId: string): VaultEntryEnvelope | undefined {+ return this.state.entries.find(e => e.payload.handleId === handleId);+ }++ /** All sealed entries (read-only copy). */+ listEntries(): readonly VaultEntryEnvelope[] {+ return [...this.state.entries];+ }++ /** All audit refusals (read-only copy). */+ listRefusals(): readonly VaultRefusal[] {+ return [...this.state.refusals];+ }++ /** Replace internal state from a persisted snapshot. */+ async load(): Promise<void> {+ if (!this.persistPath || !existsSync(this.persistPath)) return;+ try {+ const raw = await readFile(this.persistPath, 'utf8');+ this.state = JSON.parse(raw) as VaultState;+ } catch {+ // Corrupt vault file β start fresh rather than crashing.+ }+ }++ /** Persist to disk if persistPath was configured. */+ private async maybePersist(): Promise<void> {+ if (!this.persistPath) return;+ await mkdir(dirname(this.persistPath), { recursive: true });+ await writeFile(this.persistPath, JSON.stringify(this.state, null, 2), 'utf8');+ }++ /** Test helper: clear all state in memory. */+ clear(): void {+ this.state = { entries: [], refusals: [] };+ }++ /** Test helper: introspect the active witness key. */+ getWitnessKeyPublicHex(): string {+ return this.witnessKey.publicKeyHex;+ }+}++function isClean(result: ThreatScanResult): boolean {+ return result.threats.length === 0 && result.pii.length === 0;+}++// Re-exports β convenience for callers / tests.+export { generateWitnessKey, loadWitnessKey };diff --git a/v3/@claude-flow/browser/src/application/mcts-explorer.ts b/v3/@claude-flow/browser/src/application/mcts-explorer.tsnew file mode 100644index 0000000000..092f63874a--- /dev/null+++ b/v3/@claude-flow/browser/src/application/mcts-explorer.ts@@ -0,0 +1,320 @@+/**+ * @claude-flow/browser - MCTS Explorer (ADR-122 Phase 4)+ *+ * Coordinates branch expansion + UCB1 selection across one or more peers.+ * Every completed branch must produce a trajectory that passes Phase 1+ * verification (`verifySealedTrajectory`) β peers returning unverifiable+ * trajectories are blacklisted for the remainder of the run.+ *+ * Phase 4 ships the explorer; the federation transport (ADR-097/104) plugs+ * in via the PeerAdapter interface. A LocalPeerAdapter for in-process+ * exploration is included so the explorer is usable without a federation.+ */++import { randomBytes } from 'node:crypto';+import { verifySealedTrajectory } from './signed-trajectory-service.js';+import {+ McTsBranchSchema,+ type McTsBranch,+ type MctsRunResult,+ type PeerAdapter,+ type UcbParams,+ type ValueScorer,+} from '../domain/mcts-branch.js';++export interface MctsExplorerOptions {+ /** Peers to distribute exploration across. Must include at least one. */+ peers: PeerAdapter[];+ /** Value scorer. */+ scorer: ValueScorer;+ /** Maximum depth of the search tree. */+ maxDepth?: number;+ /** Maximum total branches per run. */+ maxBranches?: number;+ /** Per-peer budget cap (USD) β exceeded peers are excluded for rest of run. */+ defaultPeerBudgetUsd?: number;+ /** UCB1 parameters. */+ ucb?: UcbParams;+ /** Trusted public keys for trajectory verification. Empty = accept any valid signature. */+ trustedPublicKeys?: string[];+}++/** Initial action spec to seed the root branch. */+export interface RootAction {+ action: string;+ input: Record<string, unknown>;+}++/** Expansion hook: given a parent branch + its trajectory, return candidate next actions. */+export type ExpansionPolicy = (+ parent: McTsBranch,+ trajectoryEnvelope: unknown,+) => Promise<RootAction[]>;++export class MctsExplorer {+ private readonly peers: PeerAdapter[];+ private readonly scorer: ValueScorer;+ private readonly maxDepth: number;+ private readonly maxBranches: number;+ private readonly defaultPeerBudgetUsd: number;+ private readonly ucb: UcbParams;+ private readonly trustedPublicKeys: string[];++ private branches: Map<string, McTsBranch> = new Map();+ private peerSpend: Map<string, number> = new Map();+ private peerBlacklist: Set<string> = new Set();+ private peerSignatureBlacklist: Set<string> = new Set();++ constructor(options: MctsExplorerOptions) {+ if (options.peers.length === 0) throw new Error('MctsExplorer requires at least one peer');+ this.peers = options.peers;+ this.scorer = options.scorer;+ this.maxDepth = options.maxDepth ?? 5;+ this.maxBranches = options.maxBranches ?? 32;+ this.defaultPeerBudgetUsd = options.defaultPeerBudgetUsd ?? 1.0;+ this.ucb = options.ucb ?? { c: Math.SQRT2 };+ this.trustedPublicKeys = options.trustedPublicKeys ?? [];+ }++ /** Explore from a seed root action. Returns the winning branch's ID + aggregate stats. */+ async explore(input: {+ rootAction: RootAction;+ goal: string;+ expansionPolicy: ExpansionPolicy;+ }): Promise<MctsRunResult> {+ const runId = 'run-' + Date.now() + '-' + randomBytes(3).toString('hex');+ const rootId = 'br-root-' + randomBytes(3).toString('hex');+ const rootPeer = this.pickPeer();+ if (!rootPeer) throw new Error('no eligible peers for exploration');++ const root: McTsBranch = McTsBranchSchema.parse({+ id: rootId,+ runId,+ parentId: null,+ peerId: rootPeer.id,+ action: input.rootAction.action,+ input: input.rootAction.input,+ depth: 0,+ visits: 0,+ totalValue: 0,+ status: 'pending',+ costUsd: 0,+ createdAt: new Date().toISOString(),+ });+ this.branches.set(rootId, root);++ // Execute and expand iteratively. Counter is # of EXECUTIONS (not # of+ // branches in tree) β maxBranches reflects "how many we will actually run."+ let executed = 0;+ while (executed < this.maxBranches) {+ const next = this.selectByUcb1(runId);+ if (!next) break;++ const peer = this.peers.find(p => p.id === next.peerId && !this.peerBlacklist.has(p.id));+ if (!peer) {+ next.status = 'rejected-budget';+ next.completedAt = new Date().toISOString();+ this.branches.set(next.id, next);+ continue;+ }++ // Budget check β count BEFORE-this-call spend+ const currentSpend = this.peerSpend.get(peer.id) ?? 0;+ const cap = peer.budgetUsd ?? this.defaultPeerBudgetUsd;+ if (currentSpend >= cap) {+ next.status = 'rejected-budget';+ next.completedAt = new Date().toISOString();+ this.branches.set(next.id, next);+ this.peerBlacklist.add(peer.id);+ continue;+ }++ // Execute the branch+ next.status = 'in-progress';+ this.branches.set(next.id, next);++ let execution: Awaited<ReturnType<PeerAdapter['execute']>>;+ try {+ execution = await peer.execute(next);+ } catch (err) {+ next.status = 'failed';+ next.completedAt = new Date().toISOString();+ this.branches.set(next.id, next);+ continue;+ }++ this.peerSpend.set(peer.id, currentSpend + execution.costUsd);+ next.costUsd = execution.costUsd;+ executed++;++ // Mark peer blacklisted post-call if THIS call put us at/over budget β guards+ // against further attempts on this peer.+ if (currentSpend + execution.costUsd >= cap) {+ this.peerBlacklist.add(peer.id);+ }++ // Verify the trajectory β peers returning invalid signatures get blacklisted+ const verification = verifySealedTrajectory(execution.trajectoryEnvelope, {+ trustedPublicKeys: this.trustedPublicKeys.length > 0 ? this.trustedPublicKeys : undefined,+ });+ if (!verification.valid) {+ next.status = 'rejected-bad-signature';+ next.completedAt = new Date().toISOString();+ this.branches.set(next.id, next);+ this.peerSignatureBlacklist.add(peer.id);+ this.peerBlacklist.add(peer.id);+ continue;+ }++ // Score it+ const score = await this.scorer.score(execution.trajectoryEnvelope, input.goal);+ next.totalValue += score;+ next.visits += 1;+ next.status = 'completed';+ next.trajectoryId = extractTrajectoryId(execution.trajectoryEnvelope);+ next.completedAt = new Date().toISOString();+ this.branches.set(next.id, next);++ // Backprop: increment parent visits + propagate score+ this.backprop(next.id, score);++ // Expand: ask policy for next candidate actions+ if (next.depth < this.maxDepth) {+ const candidates = await input.expansionPolicy(next, execution.trajectoryEnvelope);+ for (const candidate of candidates) {+ if (this.branches.size >= this.maxBranches) break;+ const childId = 'br-' + randomBytes(3).toString('hex');+ const childPeer = this.pickPeer();+ if (!childPeer) break;+ this.branches.set(+ childId,+ McTsBranchSchema.parse({+ id: childId,+ runId,+ parentId: next.id,+ peerId: childPeer.id,+ action: candidate.action,+ input: candidate.input,+ depth: next.depth + 1,+ visits: 0,+ totalValue: 0,+ status: 'pending',+ costUsd: 0,+ createdAt: new Date().toISOString(),+ }),+ );+ }+ }+ }++ // Finalize any leftover pending branches β typically the tree was expanded+ // beyond the execution budget. Mark each according to peer-blacklist status.+ for (const branch of this.listBranches(runId)) {+ if (branch.status !== 'pending') continue;+ if (this.peerBlacklist.has(branch.peerId)) {+ branch.status = 'rejected-budget';+ } else {+ branch.status = 'terminated';+ }+ branch.completedAt = new Date().toISOString();+ this.branches.set(branch.id, branch);+ }++ return this.summarizeRun(runId);+ }++ /** Direct branch lookup. */+ getBranch(id: string): McTsBranch | undefined {+ return this.branches.get(id);+ }++ listBranches(runId: string): McTsBranch[] {+ return [...this.branches.values()].filter(b => b.runId === runId);+ }++ /** UCB1 selection over pending branches. */+ private selectByUcb1(runId: string): McTsBranch | null {+ const pending = this.listBranches(runId).filter(b => b.status === 'pending');+ if (pending.length === 0) return null;++ const totalVisits = Math.max(+ 1,+ this.listBranches(runId).reduce((acc, b) => acc + b.visits, 0),+ );+ let best: McTsBranch | null = null;+ let bestScore = -Infinity;+ for (const b of pending) {+ const score = ucb1(b, totalVisits, this.ucb.c);+ if (score > bestScore) {+ bestScore = score;+ best = b;+ }+ }+ return best;+ }++ /** Propagate score back up the parent chain (no decay for now). */+ private backprop(branchId: string, score: number): void {+ let cursor = this.branches.get(branchId);+ while (cursor?.parentId) {+ const parent = this.branches.get(cursor.parentId);+ if (!parent) break;+ parent.visits += 1;+ parent.totalValue += score;+ this.branches.set(parent.id, parent);+ cursor = parent;+ }+ }++ /** Round-robin peer picker skipping blacklisted peers. */+ private pickPeer(): PeerAdapter | null {+ const eligible = this.peers.filter(p => !this.peerBlacklist.has(p.id));+ if (eligible.length === 0) return null;+ // Pick the peer with the lowest cumulative spend (load balance).+ eligible.sort((a, b) => (this.peerSpend.get(a.id) ?? 0) - (this.peerSpend.get(b.id) ?? 0));+ return eligible[0];+ }++ private summarizeRun(runId: string): MctsRunResult {+ const branches = this.listBranches(runId);+ const completed = branches.filter(b => b.status === 'completed');+ let best: McTsBranch | undefined;+ let bestAvg = -Infinity;+ for (const b of completed) {+ const avg = b.visits > 0 ? b.totalValue / b.visits : 0;+ if (avg > bestAvg) {+ bestAvg = avg;+ best = b;+ }+ }+ const branchesByPeer: Record<string, number> = {};+ for (const b of branches) branchesByPeer[b.peerId] = (branchesByPeer[b.peerId] ?? 0) + 1;+ const totalCostUsd = [...this.peerSpend.values()].reduce((acc, n) => acc + n, 0);++ return {+ runId,+ bestBranchId: best?.id ?? '',+ totalBranches: branches.length,+ branchesByPeer,+ totalCostUsd,+ rejectedSignatures: branches.filter(b => b.status === 'rejected-bad-signature').map(b => b.id),+ rejectedBudget: branches.filter(b => b.status === 'rejected-budget').map(b => b.id),+ };+ }+}++/** UCB1: exploitation + sqrt(c * ln(N) / n_i). For unvisited nodes return Infinity. */+export function ucb1(branch: McTsBranch, totalVisits: number, c: number): number {+ if (branch.visits === 0) return Number.POSITIVE_INFINITY;+ const exploitation = branch.totalValue / branch.visits;+ const exploration = c * Math.sqrt(Math.log(totalVisits) / branch.visits);+ return exploitation + exploration;+}++function extractTrajectoryId(envelope: unknown): string | undefined {+ if (envelope && typeof envelope === 'object' && 'payload' in envelope) {+ const payload = (envelope as { payload?: { trajectoryId?: string } }).payload;+ return payload?.trajectoryId;+ }+ return undefined;+}diff --git a/v3/@claude-flow/browser/src/domain/cookie-vault.ts b/v3/@claude-flow/browser/src/domain/cookie-vault.tsnew file mode 100644index 0000000000..1ef53b2765--- /dev/null+++ b/v3/@claude-flow/browser/src/domain/cookie-vault.ts@@ -0,0 +1,94 @@+/**+ * @claude-flow/browser - Cookie Vault Types (ADR-122 Phase 3)+ *+ * Every cookie write goes through AIDefence PII scanning before persistence.+ * Vault entries are sealed with the same Ed25519 witness used for trajectories+ * (ADR-122 Phase 1) so peers can cryptographically attest that:+ * "this cookie handle was scanned by SCANNER@VERSION at TIMESTAMP and+ * contained no detected PII / no threats."+ *+ * No SOTA web agent (Surfer-H, Browser Use, Stagehand, Operator, Skyvern)+ * ships per-cookie attestation. Cross-installation cookie sharing is a known+ * open problem; the witness signature is the trust boundary.+ */++import { z } from 'zod';++export const CookieValueSchema = z.object({+ name: z.string().min(1),+ 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(),+});+export type CookieValue = z.infer<typeof CookieValueSchema>;++/** Scanner verdict β references what was scanned + by which AIDefence version. */+export const ScanAttestationSchema = z.object({+ scannerName: z.string().min(1),+ scannerVersion: z.string().min(1),+ scannedAt: z.string(),+ /** True iff the scan found neither PII nor threats. */+ clean: z.boolean(),+ /** Number of PII matches the scanner found (must be 0 for `clean`). */+ piiCount: z.number().int().nonnegative(),+ /** Number of threats the scanner found (must be 0 for `clean`). */+ threatCount: z.number().int().nonnegative(),+ /** Hash of the scanned cookie value (sha256 hex) β for replay verification. */+ contentHash: z.string().regex(/^[0-9a-f]{64}$/),+});+export type ScanAttestation = z.infer<typeof ScanAttestationSchema>;++export const VAULT_ENVELOPE_VERSION = '1.0.0';+export const VAULT_ENVELOPE_KIND = 'cookie-vault-entry';++export const VaultEntryPayloadSchema = z.object({+ envelopeVersion: z.literal(VAULT_ENVELOPE_VERSION),+ kind: z.literal(VAULT_ENVELOPE_KIND),+ /** Vault handle ID β opaque, used by consumers to attach the cookie to a session. */+ handleId: z.string().min(1),+ /** Project / installation ID embedded for federation trust boundary. */+ projectId: z.string().min(1),+ /** Ed25519 public key of the signer (hex). */+ publicKey: z.string().regex(/^[0-9a-f]{64}$/),+ /** Cookie payload. Value is verbatim β attestation says it was scanned clean. */+ cookie: CookieValueSchema,+ /** AIDefence (or compatible) scan verdict. */+ attestation: ScanAttestationSchema,+ /** When the vault entry was sealed. */+ sealedAt: z.string(),+ /** Origin the cookie is bound to (e.g. https://example.com). Inferred from cookie.domain when absent. */+ origin: z.string().optional(),+});+export type VaultEntryPayload = z.infer<typeof VaultEntryPayloadSchema>;++export const VaultEntryEnvelopeSchema = z.object({+ payload: VaultEntryPayloadSchema,+ signature: z.string().regex(/^[0-9a-f]{128}$/),+ algorithm: z.literal('ed25519'),+});+export type VaultEntryEnvelope = z.infer<typeof VaultEntryEnvelopeSchema>;++export interface VaultVerificationResult {+ valid: boolean;+ signatureValid: boolean;+ schemaValid: boolean;+ /** Scanner attestation embedded in the envelope (populated even on failure for diagnostics). */+ attestation?: ScanAttestation;+ publicKey?: string;+ reason?: string;+}++/** Audit record written when a write is refused due to PII/threat. */+export const VaultRefusalSchema = z.object({+ attemptedAt: z.string(),+ origin: z.string().optional(),+ cookieName: z.string(),+ reason: z.string(),+ piiCount: z.number().int().nonnegative(),+ threatCount: z.number().int().nonnegative(),+});+export type VaultRefusal = z.infer<typeof VaultRefusalSchema>;diff --git a/v3/@claude-flow/browser/src/domain/mcts-branch.ts b/v3/@claude-flow/browser/src/domain/mcts-branch.tsnew file mode 100644index 0000000000..bcc0bcf665--- /dev/null+++ b/v3/@claude-flow/browser/src/domain/mcts-branch.ts@@ -0,0 +1,101 @@+/**+ * @claude-flow/browser - MCTS Branch Types (ADR-122 Phase 4)+ *+ * Plan-MCTS / Agent Alpha style search where each branch explores a different+ * subtree of the action space. The novel wedge: branches can be distributed+ * across federation peers and the queen selects winners by HNSW cosine+ * similarity to past successful ReasoningBank trajectories.+ *+ * No SOTA web agent today distributes MCTS exploration across multiple+ * installations β every system is single-process. Federation primitives+ * (ADR-097/104) make this structurally available to ruflo only.+ */++import { z } from 'zod';++export const BranchStatusSchema = z.enum([+ 'pending',+ 'in-progress',+ 'completed',+ 'failed',+ 'rejected-bad-signature',+ 'rejected-budget',+ 'terminated',+]);+export type BranchStatus = z.infer<typeof BranchStatusSchema>;++export const McTsBranchSchema = z.object({+ /** Branch ID β unique within an exploration run. */+ id: z.string().min(1),+ /** Run ID β groups branches belonging to one MCTS exploration. */+ runId: z.string().min(1),+ /** Parent branch ID (root has parent = null). */+ parentId: z.string().nullable(),+ /** Peer assigned to explore this branch (local or federation). */+ peerId: z.string().min(1),+ /** Action this branch represents (open/click/fill/...). */+ action: z.string().min(1),+ /** Inputs for that action. */+ input: z.record(z.unknown()),+ /** Depth in the tree (root = 0). */+ depth: z.number().int().nonnegative(),+ /** Number of times this branch has been selected by UCB1. */+ visits: z.number().int().nonnegative(),+ /** Accumulated value (sum of trajectory similarity scores). */+ totalValue: z.number().nonnegative(),+ /** Status of this branch. */+ status: BranchStatusSchema,+ /** ID of the signed trajectory this branch produced (when completed). */+ trajectoryId: z.string().optional(),+ /** Cost (USD) reported back by the peer for this branch. */+ costUsd: z.number().nonnegative().default(0),+ /** When the branch was created. */+ createdAt: z.string(),+ /** When the branch completed (or failed). */+ completedAt: z.string().optional(),+});+export type McTsBranch = z.infer<typeof McTsBranchSchema>;++/** Result of an exploration run β best branch + aggregate stats. */+export interface MctsRunResult {+ runId: string;+ /** ID of the winning branch (best score). */+ bestBranchId: string;+ /** Total branches explored across all peers. */+ totalBranches: number;+ /** Branches per peer. */+ branchesByPeer: Record<string, number>;+ /** Total USD spend across all peers. */+ totalCostUsd: number;+ /** Branches rejected for signature failure (per-peer blacklist signal). */+ rejectedSignatures: string[];+ /** Branches rejected because their peer exceeded budget. */+ rejectedBudget: string[];+}++/** UCB1 selection criteria parameters. */+export interface UcbParams {+ /** Exploration constant. Higher = wider exploration. Default 1.41 (sqrt(2)). */+ c: number;+}++/** Federation peer adapter β abstract over local vs remote execution. */+export interface PeerAdapter {+ id: string;+ /** Hint to the queen: per-call budget cap in USD. */+ budgetUsd: number;+ /** Execute a single branch action and return a signed trajectory envelope. */+ execute(branch: McTsBranch): Promise<{+ trajectoryEnvelope: unknown;+ /** True iff trajectory's signature verified locally on the peer's side. */+ selfVerified: boolean;+ /** Cost actually incurred. */+ costUsd: number;+ }>;+}++/** Value function β scores a completed trajectory against past successes. */+export interface ValueScorer {+ /** Return a score in [0,1]. Higher = closer to known successful trajectories. */+ score(trajectoryEnvelope: unknown, goal: string): Promise<number>;+}diff --git a/v3/@claude-flow/browser/src/index.ts b/v3/@claude-flow/browser/src/index.tsindex 310297c81d..91ff33ca06 100644--- a/v3/@claude-flow/browser/src/index.ts+++ b/v3/@claude-flow/browser/src/index.ts@@ -166,6 +166,47 @@ export {type RecoveryExplanation,} from './domain/causal-recovery.js';+// Federated MCTS branch exploration (ADR-122 Phase 4)+export {+ MctsExplorer,+ ucb1,+ type MctsExplorerOptions,+ type RootAction,+ type ExpansionPolicy,+} from './application/mcts-explorer.js';+export {+ McTsBranchSchema,+ BranchStatusSchema,+ type McTsBranch,+ type BranchStatus,+ type MctsRunResult,+ type PeerAdapter,+ type UcbParams,+ type ValueScorer,+} from './domain/mcts-branch.js';++// AIDefence-attested cookie vault (ADR-122 Phase 3)+export {+ CookieVaultService,+ type CookieVaultServiceOptions,+ type CookieVaultScannerInfo,+} from './application/cookie-vault-service.js';+export {+ VAULT_ENVELOPE_VERSION,+ VAULT_ENVELOPE_KIND,+ VaultEntryEnvelopeSchema,+ VaultEntryPayloadSchema,+ CookieValueSchema,+ ScanAttestationSchema,+ VaultRefusalSchema,+ type CookieValue,+ type ScanAttestation,+ type VaultEntryEnvelope,+ type VaultEntryPayload,+ type VaultVerificationResult,+ type VaultRefusal,+} from './domain/cookie-vault.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/tests/cookie-vault.test.ts b/v3/@claude-flow/browser/tests/cookie-vault.test.tsnew file mode 100644index 0000000000..6387da7807--- /dev/null+++ b/v3/@claude-flow/browser/tests/cookie-vault.test.ts@@ -0,0 +1,190 @@+/**+ * @claude-flow/browser - Cookie Vault Tests (ADR-122 Phase 3)+ *+ * Acceptance criteria covered:+ * - Cookie containing PII (AIDefence-flagged) never persists; audit event written+ * - Sealed envelope verifyAttestation() round-trips for clean cookies+ * - Tampered envelope (replaced cookie value) fails verification+ * - Trust-list filtering accepts/rejects by signer public key+ * - clean=false attestations are refused (defense in depth)+ * - Handle lookup works after sealing+ */++import { describe, it, expect, beforeEach } from 'vitest';+import {+ CookieVaultService,+} from '../src/application/cookie-vault-service.js';+import { generateWitnessKey, sha256Hex } from '../src/infrastructure/witness-signer.js';+import type { VaultEntryEnvelope, CookieValue } from '../src/domain/cookie-vault.js';++const CLEAN_COOKIE: CookieValue = {+ name: 'sid',+ value: 'opaque-session-token-XK29q8vN1uYJ',+ domain: 'example.com',+ path: '/',+ httpOnly: true,+ secure: true,+ sameSite: 'Lax',+};++const PII_COOKIE: CookieValue = {+ name: 'user-info',+ value: 'name=John Doe [email protected] ssn=123-45-6789',+ domain: 'example.com',+};++describe('CookieVaultService', () => {+ let vault: CookieVaultService;++ beforeEach(() => {+ vault = new CookieVaultService({ projectId: 'test-project' });+ });++ describe('clean cookie store', () => {+ it('seals a clean cookie into a verifiable envelope', async () => {+ const result = await vault.store({ cookie: CLEAN_COOKIE, origin: 'https://example.com' });+ expect(result.success).toBe(true);+ if (!result.success) return; // narrow+ expect(result.handleId).toMatch(/^vh-/);+ expect(result.envelope.payload.cookie.value).toBe(CLEAN_COOKIE.value);+ expect(result.envelope.payload.attestation.clean).toBe(true);+ expect(result.envelope.payload.attestation.contentHash).toBe(sha256Hex(CLEAN_COOKIE.value));+ });++ it('verifyAttestation succeeds for a freshly sealed clean cookie', async () => {+ const result = await vault.store({ cookie: CLEAN_COOKIE });+ expect(result.success).toBe(true);+ if (!result.success) return;+ const verification = vault.verifyAttestation(result.envelope);+ expect(verification.valid).toBe(true);+ expect(verification.signatureValid).toBe(true);+ expect(verification.attestation?.clean).toBe(true);+ });++ it('round-trips through getByHandle()', async () => {+ const result = await vault.store({ cookie: CLEAN_COOKIE });+ if (!result.success) throw new Error('expected success');+ const retrieved = vault.getByHandle(result.handleId);+ expect(retrieved).toBeDefined();+ expect(retrieved?.payload.cookie.name).toBe(CLEAN_COOKIE.name);+ });+ });++ describe('PII refusal', () => {+ it('refuses a cookie containing PII and writes a refusal audit', async () => {+ const result = await vault.store({ cookie: PII_COOKIE });+ expect(result.success).toBe(false);+ if (result.success) return;+ expect(result.refusal.cookieName).toBe('user-info');+ expect(result.refusal.piiCount).toBeGreaterThan(0);+ // Audit record visible to consumers+ expect(vault.listRefusals()).toHaveLength(1);+ });++ it('does NOT persist a PII cookie to the entries list', async () => {+ await vault.store({ cookie: PII_COOKIE });+ expect(vault.listEntries()).toHaveLength(0);+ });++ it('records the attempted cookie name + reason in the refusal', async () => {+ const result = await vault.store({ cookie: PII_COOKIE });+ if (result.success) return;+ expect(result.refusal.reason).toMatch(/PII/);+ });+ });++ describe('tamper detection', () => {+ it('rejects an envelope where the cookie value was replaced after sealing', async () => {+ const result = await vault.store({ cookie: CLEAN_COOKIE });+ if (!result.success) throw new Error('expected success');++ // Attacker swaps the value but forgets to update the hash+ const forged: VaultEntryEnvelope = JSON.parse(JSON.stringify(result.envelope));+ forged.payload.cookie.value = 'stolen-session-token-xxxxx';++ const verification = vault.verifyAttestation(forged);+ expect(verification.valid).toBe(false);+ expect(verification.reason).toMatch(/(hash mismatch|tampered|signature verification failed)/i);+ });++ it('rejects an envelope where the hash was updated but signature was not', async () => {+ const result = await vault.store({ cookie: CLEAN_COOKIE });+ if (!result.success) throw new Error('expected success');++ // Attacker updates both value and hash but can't re-sign+ const forged: VaultEntryEnvelope = JSON.parse(JSON.stringify(result.envelope));+ forged.payload.cookie.value = 'stolen';+ forged.payload.attestation.contentHash = sha256Hex('stolen');++ const verification = vault.verifyAttestation(forged);+ expect(verification.valid).toBe(false);+ expect(verification.reason).toMatch(/signature verification failed/i);+ });++ it('rejects schema-invalid envelopes', () => {+ const verification = vault.verifyAttestation({ payload: 'wrong', signature: 'x', algorithm: 'ed25519' });+ expect(verification.valid).toBe(false);+ expect(verification.schemaValid).toBe(false);+ });++ it('refuses attestation with clean=false even when signature is valid (defense in depth)', async () => {+ // Hand-craft an envelope with clean=false by signing it with a fresh key.+ // The vault would never produce this, but a hostile peer might.+ const key = generateWitnessKey();+ const adverseVault = new CookieVaultService({ witnessKey: key });++ // Seal a clean cookie first to learn the canonical shape...+ const ok = await adverseVault.store({ cookie: CLEAN_COOKIE });+ if (!ok.success) throw new Error('expected clean store to succeed');+ const original = ok.envelope;++ // Flip clean=false and resign with the same key.+ const { sign } = await import('node:crypto');+ const { canonicalJSON } = await import('../src/infrastructure/witness-signer.js');+ const tampered: VaultEntryEnvelope = JSON.parse(JSON.stringify(original));+ tampered.payload.attestation.clean = false;+ const canonical = canonicalJSON(tampered.payload);+ tampered.signature = sign(null, Buffer.from(canonical, 'utf8'), key.privateKey).toString('hex');++ const verification = adverseVault.verifyAttestation(tampered);+ expect(verification.valid).toBe(false);+ expect(verification.reason).toMatch(/clean=false/);+ });+ });++ describe('trust list', () => {+ it('rejects envelopes from untrusted signers', async () => {+ const stranger = new CookieVaultService({ witnessKey: generateWitnessKey() });+ const ok = await stranger.store({ cookie: CLEAN_COOKIE });+ if (!ok.success) throw new Error('expected success');+ const verification = vault.verifyAttestation(ok.envelope, { trustedPublicKeys: ['00'.repeat(32)] });+ expect(verification.valid).toBe(false);+ expect(verification.reason).toMatch(/not in trusted list/);+ });++ it('accepts envelopes from trusted signers', async () => {+ const friend = new CookieVaultService({ witnessKey: generateWitnessKey() });+ const ok = await friend.store({ cookie: CLEAN_COOKIE });+ if (!ok.success) throw new Error('expected success');+ const verification = vault.verifyAttestation(ok.envelope, {+ trustedPublicKeys: [friend.getWitnessKeyPublicHex()],+ });+ expect(verification.valid).toBe(true);+ });+ });++ describe('audit record', () => {+ it('refusal includes pii + threat counts', async () => {+ const result = await vault.store({ cookie: PII_COOKIE });+ if (result.success) return;+ expect(result.refusal.piiCount).toBeGreaterThan(0);+ expect(result.refusal.threatCount).toBeGreaterThanOrEqual(0);+ });++ it('refusal records origin when provided', async () => {+ const result = await vault.store({ cookie: PII_COOKIE, origin: 'https://example.com' });+ if (result.success) return;+ expect(result.refusal.origin).toBe('https://example.com');+ });+ });+});diff --git a/v3/@claude-flow/browser/tests/mcts-explorer.test.ts b/v3/@claude-flow/browser/tests/mcts-explorer.test.tsnew file mode 100644index 0000000000..eda123373b--- /dev/null+++ b/v3/@claude-flow/browser/tests/mcts-explorer.test.ts@@ -0,0 +1,261 @@+/**+ * @claude-flow/browser - MCTS Explorer Tests (ADR-122 Phase 4)+ *+ * Acceptance criteria covered:+ * - UCB1 picks unvisited branches with priority (Infinity score)+ * - Round-robin / least-spend peer load balancing+ * - Peers returning invalid trajectory signatures are blacklisted for the run+ * - Peers exceeding budget are excluded from further work+ * - Expansion policy generates children; tree respects maxDepth + maxBranches+ * - Final winner is the highest-average-score completed branch+ */++import { describe, it, expect } from 'vitest';+import { MctsExplorer, ucb1 } from '../src/application/mcts-explorer.js';+import { sealTrajectory } from '../src/application/signed-trajectory-service.js';+import { generateWitnessKey } from '../src/infrastructure/witness-signer.js';+import type { PeerAdapter, McTsBranch, ValueScorer } from '../src/domain/mcts-branch.js';+import type { BrowserTrajectory } from '../src/domain/types.js';++const sharedKey = generateWitnessKey();++function makeTrajectory(score: number): BrowserTrajectory {+ return {+ id: 'traj-' + Math.random().toString(36).slice(2, 8) + '-' + score,+ sessionId: 'mcts-sess',+ goal: 'Test exploration',+ startedAt: new Date().toISOString(),+ completedAt: new Date().toISOString(),+ success: true,+ verdict: 'ok',+ steps: [{ action: 'open', input: { url: 'https://example.com' }, result: { success: true }, timestamp: new Date().toISOString() }],+ };+}++function makeScoringPeer(id: string, scoreOf: (b: McTsBranch) => number, costUsd = 0.01, budgetUsd = 1.0): PeerAdapter {+ return {+ id,+ budgetUsd,+ async execute(branch) {+ const trajectory = makeTrajectory(scoreOf(branch));+ const sealed = sealTrajectory({ trajectory, witnessKey: sharedKey });+ return { trajectoryEnvelope: sealed.envelope, selfVerified: true, costUsd };+ },+ };+}++function makeFaultyPeer(id: string): PeerAdapter {+ return {+ id,+ budgetUsd: 1.0,+ async execute() {+ // Return a syntactically-shaped but-unsigned envelope (signature invalid).+ return {+ trajectoryEnvelope: { payload: { foo: 'bar' }, signature: 'aa'.repeat(64), algorithm: 'ed25519' },+ selfVerified: false,+ costUsd: 0.01,+ };+ },+ };+}++function makeScorer(scoreOf: (envelope: unknown) => number): ValueScorer {+ return {+ async score(envelope) {+ return scoreOf(envelope);+ },+ };+}++describe('MctsExplorer', () => {+ describe('UCB1', () => {+ it('returns Infinity for unvisited branches', () => {+ const branch = {+ id: 'b', runId: 'r', parentId: null, peerId: 'p', action: 'open',+ input: {}, depth: 0, visits: 0, totalValue: 0, status: 'pending' as const,+ costUsd: 0, createdAt: 't',+ };+ expect(ucb1(branch, 10, Math.SQRT2)).toBe(Infinity);+ });++ it('exploits high-value branches with low visits', () => {+ const branch = {+ id: 'b', runId: 'r', parentId: null, peerId: 'p', action: 'open',+ input: {}, depth: 0, visits: 1, totalValue: 0.9, status: 'completed' as const,+ costUsd: 0, createdAt: 't',+ };+ const score = ucb1(branch, 10, Math.SQRT2);+ expect(score).toBeGreaterThan(0.9);+ });+ });++ describe('basic exploration', () => {+ it('completes the root branch and produces a winner', async () => {+ const peer = makeScoringPeer('local', () => 0.8);+ const explorer = new MctsExplorer({+ peers: [peer],+ scorer: makeScorer(() => 0.8),+ maxBranches: 1,+ maxDepth: 0,+ });+ const result = await explorer.explore({+ rootAction: { action: 'open', input: { url: 'https://example.com' } },+ goal: 'Find welcome page',+ expansionPolicy: async () => [],+ });+ expect(result.totalBranches).toBe(1);+ expect(result.bestBranchId).not.toBe('');+ const winner = explorer.getBranch(result.bestBranchId);+ expect(winner?.status).toBe('completed');+ });++ it('expands the tree via the expansion policy', async () => {+ const peer = makeScoringPeer('local', () => 0.5);+ const explorer = new MctsExplorer({+ peers: [peer],+ scorer: makeScorer(() => 0.5),+ maxBranches: 6,+ maxDepth: 2,+ });+ const result = await explorer.explore({+ rootAction: { action: 'open', input: { url: 'https://example.com' } },+ goal: 'Explore',+ expansionPolicy: async (parent) =>+ parent.depth < 2+ ? [+ { action: 'click', input: { target: '@e1' } },+ { action: 'click', input: { target: '@e2' } },+ ]+ : [],+ });+ // Root + 2 children + possibly grandchildren (capped at maxBranches)+ expect(result.totalBranches).toBeGreaterThanOrEqual(3);+ expect(result.totalBranches).toBeLessThanOrEqual(6);+ });+ });++ describe('signature verification + peer blacklisting', () => {+ it('rejects branches with invalid signatures and blacklists the peer', async () => {+ const good = makeScoringPeer('good', () => 0.8);+ const bad = makeFaultyPeer('bad');+ const explorer = new MctsExplorer({+ peers: [good, bad],+ scorer: makeScorer(() => 0.8),+ maxBranches: 8,+ maxDepth: 2,+ });+ const result = await explorer.explore({+ rootAction: { action: 'open', input: { url: 'https://example.com' } },+ goal: 'Test',+ expansionPolicy: async (parent) =>+ parent.depth < 2 ? [{ action: 'click', input: { target: '@e1' } }] : [],+ });+ // At least one branch went through the bad peer (round-robin sees them+ // first by lowest-spend) β that branch should be rejected.+ if (result.rejectedSignatures.length > 0) {+ const rejected = explorer.getBranch(result.rejectedSignatures[0]);+ expect(rejected?.status).toBe('rejected-bad-signature');+ }+ // Eventually all branches end up on good peer once bad is blacklisted.+ const goodBranches = (result.branchesByPeer.good ?? 0);+ expect(goodBranches).toBeGreaterThan(0);+ });+ });++ describe('budget cap', () => {+ it('rejects branches when a peer exceeds budget', async () => {+ const peer = makeScoringPeer('local', () => 0.5, /* costUsd */ 0.4, /* budgetUsd */ 1.0);+ const explorer = new MctsExplorer({+ peers: [peer],+ scorer: makeScorer(() => 0.5),+ maxBranches: 5,+ maxDepth: 3,+ });+ const result = await explorer.explore({+ rootAction: { action: 'open', input: { url: 'https://example.com' } },+ goal: 'Budget test',+ expansionPolicy: async (parent) =>+ parent.depth < 3+ ? [+ { action: 'click', input: { target: '@e1' } },+ { action: 'click', input: { target: '@e2' } },+ ]+ : [],+ });+ // After 3 successful branches at $0.40 each, the 4th should hit the budget cap.+ expect(result.rejectedBudget.length).toBeGreaterThan(0);+ expect(result.totalCostUsd).toBeGreaterThanOrEqual(1.0); // tipped over the cap by the last successful branch+ });+ });++ describe('multi-peer load balance', () => {+ it('distributes branches across peers using least-spend selection', async () => {+ const peerA = makeScoringPeer('peerA', () => 0.6);+ const peerB = makeScoringPeer('peerB', () => 0.7);+ const explorer = new MctsExplorer({+ peers: [peerA, peerB],+ scorer: makeScorer(() => 0.6),+ maxBranches: 5,+ maxDepth: 1,+ });+ const result = await explorer.explore({+ rootAction: { action: 'open', input: { url: 'https://example.com' } },+ goal: 'Distribution test',+ expansionPolicy: async (parent) =>+ parent.depth < 1+ ? [+ { action: 'click', input: { target: '@e1' } },+ { action: 'click', input: { target: '@e2' } },+ { action: 'click', input: { target: '@e3' } },+ ]+ : [],+ });+ expect(Object.keys(result.branchesByPeer).length).toBeGreaterThanOrEqual(2);+ });+ });++ describe('winner selection', () => {+ it('picks the branch with the highest average score', async () => {+ // The scorer reads the trajectory id; we encode the desired score in the action.+ const scoreByAction: Record<string, number> = { open: 0.3, 'click-A': 0.9, 'click-B': 0.4 };+ const peer: PeerAdapter = {+ id: 'tiered',+ budgetUsd: 5.0,+ async execute(branch) {+ const trajectory = makeTrajectory(scoreByAction[branch.action] ?? 0.1);+ // Encode score into goal so scorer can read it back+ trajectory.goal = String(scoreByAction[branch.action] ?? 0.1);+ const sealed = sealTrajectory({ trajectory, witnessKey: sharedKey });+ return { trajectoryEnvelope: sealed.envelope, selfVerified: true, costUsd: 0.01 };+ },+ };+ const scorer: ValueScorer = {+ async score(envelope) {+ const goal = (envelope as { payload: { trajectory: { goal: string } } }).payload.trajectory.goal;+ return parseFloat(goal);+ },+ };+ const explorer = new MctsExplorer({+ peers: [peer],+ scorer,+ maxBranches: 4,+ maxDepth: 1,+ });+ const result = await explorer.explore({+ rootAction: { action: 'open', input: {} },+ goal: 'Find best click',+ expansionPolicy: async (parent) =>+ parent.depth < 1+ ? [+ { action: 'click-A', input: {} },+ { action: 'click-B', input: {} },+ ]+ : [],+ });+ const winner = explorer.getBranch(result.bestBranchId);+ // click-A scores 0.9 (highest leaf); root scores 0.3 (but receives all child propagations,+ // averaging out). Winner should be the click-A leaf.+ expect(winner?.action).toBe('click-A');+ });+ });+});