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 7 β€” Workflow Compiler + production-aware UCT

ruv350bcf060652
diff --git a/v3/@claude-flow/browser/src/application/production-uct.ts b/v3/@claude-flow/browser/src/application/production-uct.ts
new file mode 100644
index 0000000000..6741007c9d
--- /dev/null
+++ b/v3/@claude-flow/browser/src/application/production-uct.ts
@@ -0,0 +1,54 @@
+/**
+ * @claude-flow/browser - Production-Aware UCT (ADR-122 Phase 7)
+ *
+ * Extends Phase 4's plain UCB1 with the substrate's production-aware formula:
+ *
+ * score = Q + C·√(ln(parent_visits) / child_visits)
+ * + Ξ»_R Β· replayability
+ * βˆ’ Ξ»_risk Β· risk
+ * βˆ’ ΞΌ_cost Β· cost_usd
+ * βˆ’ Ξ±_auth Β· auth_fragility
+ *
+ * Q = mean trajectory value (success / similarity)
+ * R = replayability bonus (encourages reusable winning paths)
+ * Ξ»_R = replay weight
+ *
+ * The penalties keep MCTS from chasing high-Q paths that are expensive,
+ * irreversible, or auth-fragile in production.
+ */
+
+import type { ProductionUctSignals, ProductionUctWeights } from '../domain/workflow.js';
+import { DEFAULT_PRODUCTION_UCT_WEIGHTS } from '../domain/workflow.js';
+
+export interface ProductionUctInput {
+ /** Visits for the candidate branch. */
+ visits: number;
+ /** Total visits across all siblings (for the ln(N) term). */
+ parentVisits: number;
+ signals: ProductionUctSignals;
+}
+
+/** Compute the production-aware UCT score. Unvisited branches return +Infinity. */
+export function productionUct(
+ input: ProductionUctInput,
+ weights: ProductionUctWeights = DEFAULT_PRODUCTION_UCT_WEIGHTS,
+): number {
+ if (input.visits === 0) return Number.POSITIVE_INFINITY;
+ const exploitation = input.signals.qValue;
+ const exploration = weights.c * Math.sqrt(Math.log(Math.max(1, input.parentVisits)) / input.visits);
+ const replayBonus = weights.replayBonus * input.signals.replayability;
+ const riskPenalty = weights.riskPenalty * input.signals.risk;
+ const costPenalty = weights.costPenalty * input.signals.costUsd;
+ const authPenalty = weights.authPenalty * input.signals.authFragility;
+ return exploitation + exploration + replayBonus - riskPenalty - costPenalty - authPenalty;
+}
+
+/**
+ * Compose two scoring sources β€” useful when a branch carries both a raw
+ * scorer value (HNSW similarity, Phase 4) and observed signals (cost, auth).
+ */
+export function blendQ(scorerValue: number, replaySuccessRate?: number): number {
+ if (replaySuccessRate === undefined) return scorerValue;
+ // Linear blend so both sources matter β€” replay carries 30% weight by default.
+ return 0.7 * scorerValue + 0.3 * replaySuccessRate;
+}
diff --git a/v3/@claude-flow/browser/src/application/workflow-compiler.ts b/v3/@claude-flow/browser/src/application/workflow-compiler.ts
new file mode 100644
index 0000000000..9bfaf23d0e
--- /dev/null
+++ b/v3/@claude-flow/browser/src/application/workflow-compiler.ts
@@ -0,0 +1,227 @@
+/**
+ * @claude-flow/browser - Workflow Compiler (ADR-122 Phase 7)
+ *
+ * Compile a winning MCTS branch (Phase 4) plus its parent chain into a
+ * deterministic CompiledWorkflow:
+ * - Each step gets a primary selector + ordered fallback chain (`@eN` β‡’
+ * role+name β‡’ testid β‡’ CSS) derived from observed snapshot metadata.
+ * - Policy manifest filled from the source MCTS goal + Phase 6
+ * RiskClassifier.
+ * - YAML serialisation for human inspection / VCS check-in.
+ *
+ * The compiler is BROWSER-INDEPENDENT: it operates on trajectory step records
+ * (the Phase 1 envelope's `payload.trajectory.steps`), so the same machinery
+ * works for traces from any Phase 6 BrowserExecutionAdapter.
+ */
+
+import {
+ type CompiledWorkflow,
+ type WorkflowStep,
+ type SelectorSpec,
+ WORKFLOW_VERSION,
+ CompiledWorkflowSchema,
+} from '../domain/workflow.js';
+import { RiskClassifier } from './session-capsule-service.js';
+import type { McTsBranch } from '../domain/mcts-branch.js';
+import type { SignedTrajectoryEnvelope } from '../domain/signed-trajectory.js';
+import type { Snapshot } from '../domain/types.js';
+
+/** Input for compile() β€” a single winning trace. */
+export interface CompileInput {
+ /** Slug identifier for the workflow. */
+ id: string;
+ goal: string;
+ trajectoryEnvelope: SignedTrajectoryEnvelope;
+ /** Optional MCTS provenance for the ADR trace fields. */
+ source?: { runId?: string; branchId?: string; branch?: McTsBranch };
+ /** Per-workflow replay defaults. */
+ defaults?: { maxRetries?: number; timeoutMs?: number };
+ /** Override classifier (tests). */
+ classifier?: RiskClassifier;
+ /** Override `compiledAt` (tests). */
+ compiledAt?: string;
+}
+
+interface RawStep {
+ action: string;
+ input: Record<string, unknown>;
+ snapshot?: Snapshot;
+ result?: { success?: boolean };
+}
+
+export class WorkflowCompiler {
+ constructor(private readonly classifier: RiskClassifier = new RiskClassifier()) {}
+
+ compile(input: CompileInput): CompiledWorkflow {
+ const classifier = input.classifier ?? this.classifier;
+ const rawSteps = (input.trajectoryEnvelope.payload.trajectory.steps as RawStep[]) ?? [];
+
+ const steps: WorkflowStep[] = [];
+ const origins = new Set<string>();
+ let highestRisk: ReturnType<RiskClassifier['classify']> = classifier.classify({ action: 'noop' });
+
+ for (const raw of rawSteps) {
+ const target = (raw.input as { url?: string; target?: string }).url
+ ?? (raw.input as { target?: string }).target;
+ const value = (raw.input as { value?: string; text?: string }).value
+ ?? (raw.input as { text?: string }).text;
+
+ // Collect origin from `open` steps for the requirements manifest.
+ if (raw.action === 'open' && typeof target === 'string') {
+ try {
+ origins.add(new URL(target).origin);
+ } catch { /* ignore non-URL targets */ }
+ }
+
+ const classification = classifier.classify({
+ action: raw.action,
+ target: typeof target === 'string' ? target : undefined,
+ goal: input.goal,
+ });
+ if (riskRank(classification.class) > riskRank(highestRisk.class)) {
+ highestRisk = classification;
+ }
+
+ const primary: SelectorSpec | string | undefined =
+ raw.action === 'open' && typeof target === 'string'
+ ? target
+ : target && typeof target === 'string'
+ ? primarySelectorSpec(target)
+ : undefined;
+
+ const fallback = buildFallbackChain(target, raw.snapshot);
+
+ steps.push({
+ action: raw.action,
+ target: primary,
+ fallback,
+ value,
+ });
+ }
+
+ const compiled: CompiledWorkflow = CompiledWorkflowSchema.parse({
+ workflow: input.id,
+ version: WORKFLOW_VERSION,
+ goal: input.goal,
+ sourceMctsRunId: input.source?.runId,
+ sourceBranchId: input.source?.branchId,
+ requirements: {
+ sessionCapsule: highestRisk.class !== 'read-only',
+ origins: [...origins],
+ taskClass: highestRisk.class,
+ },
+ steps,
+ guards: {
+ irreversibleAction: ['financial', 'account-mutation', 'destructive'].includes(highestRisk.class),
+ requiresUserConfirmation: !highestRisk.autonomousAllowed,
+ },
+ replay: {
+ maxRetries: input.defaults?.maxRetries ?? 2,
+ timeoutMs: input.defaults?.timeoutMs ?? 30_000,
+ },
+ compiledAt: input.compiledAt ?? new Date().toISOString(),
+ });
+
+ return compiled;
+ }
+
+ /** Render a compiled workflow as YAML (deterministic, no dynamic deps). */
+ toYaml(workflow: CompiledWorkflow): string {
+ const lines: string[] = [];
+ lines.push(`workflow: ${workflow.workflow}`);
+ lines.push(`version: ${workflow.version}`);
+ lines.push(`goal: ${quoteYaml(workflow.goal)}`);
+ if (workflow.sourceMctsRunId) lines.push(`sourceMctsRunId: ${workflow.sourceMctsRunId}`);
+ if (workflow.sourceBranchId) lines.push(`sourceBranchId: ${workflow.sourceBranchId}`);
+ lines.push(`compiledAt: ${workflow.compiledAt}`);
+ lines.push(`requirements:`);
+ lines.push(` sessionCapsule: ${workflow.requirements.sessionCapsule}`);
+ lines.push(` taskClass: ${workflow.requirements.taskClass}`);
+ lines.push(` origins:`);
+ for (const o of workflow.requirements.origins) lines.push(` - ${o}`);
+ lines.push(`guards:`);
+ lines.push(` irreversibleAction: ${workflow.guards.irreversibleAction}`);
+ lines.push(` requiresUserConfirmation: ${workflow.guards.requiresUserConfirmation}`);
+ lines.push(`replay:`);
+ lines.push(` maxRetries: ${workflow.replay.maxRetries}`);
+ lines.push(` timeoutMs: ${workflow.replay.timeoutMs}`);
+ lines.push(`steps:`);
+ for (const step of workflow.steps) {
+ lines.push(` - action: ${step.action}`);
+ if (typeof step.target === 'string') {
+ lines.push(` target: ${quoteYaml(step.target)}`);
+ } else if (step.target) {
+ lines.push(` target:`);
+ lines.push(` strategy: ${step.target.strategy}`);
+ lines.push(` value: ${quoteYaml(step.target.value)}`);
+ if (step.target.name) lines.push(` name: ${quoteYaml(step.target.name)}`);
+ }
+ if (step.value !== undefined) lines.push(` value: ${quoteYaml(step.value)}`);
+ if (step.fallback.length > 0) {
+ lines.push(` fallback:`);
+ for (const fb of step.fallback) {
+ lines.push(` - strategy: ${fb.strategy}`);
+ lines.push(` value: ${quoteYaml(fb.value)}`);
+ if (fb.name) lines.push(` name: ${quoteYaml(fb.name)}`);
+ }
+ }
+ }
+ return lines.join('\n') + '\n';
+ }
+}
+
+/** Convert a `@eN` ref into a SelectorSpec for the primary slot. */
+function primarySelectorSpec(target: string): SelectorSpec {
+ if (/^@e\d+$/.test(target)) return { strategy: 'ref', value: target };
+ if (target.startsWith('text=')) return { strategy: 'text', value: target.slice(5) };
+ if (target.startsWith('role=')) return { strategy: 'role', value: target.slice(5) };
+ if (target.startsWith('testid=')) return { strategy: 'testid', value: target.slice(7) };
+ return { strategy: 'css', value: target };
+}
+
+/** Build the ordered fallback chain β€” testid > role+name > text > css > ref. */
+function buildFallbackChain(target: string | undefined, snapshot?: Snapshot): SelectorSpec[] {
+ if (!target || typeof target !== 'string') return [];
+ const node = snapshot && /^@e\d+$/.test(target) ? snapshot.refs?.[target] : undefined;
+ const out: SelectorSpec[] = [];
+
+ // Most stable strategies first
+ if (node) {
+ if (node.role && node.name) out.push({ strategy: 'role', value: node.role, name: node.name });
+ if (node.name) out.push({ strategy: 'text', value: node.name });
+ }
+ if (/^@e\d+$/.test(target)) {
+ // ref already primary β€” no extra fallback needed
+ } else {
+ // Non-ref targets get the ref form as last-ditch (when re-snapshotted)
+ out.push({ strategy: 'ref', value: target });
+ }
+
+ // Deduplicate (strategy, value) pairs
+ const seen = new Set<string>();
+ return out.filter(spec => {
+ const key = `${spec.strategy}::${spec.value}::${spec.name ?? ''}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+}
+
+function riskRank(c: string): number {
+ switch (c) {
+ case 'destructive': return 7;
+ case 'account-mutation': return 6;
+ case 'financial': return 5;
+ case 'external-submission': return 4;
+ case 'draft-write': return 3;
+ case 'authenticated-read': return 2;
+ case 'read-only': return 1;
+ default: return 0;
+ }
+}
+
+function quoteYaml(value: string): string {
+ // Minimal YAML quoting β€” wrap in double quotes when value contains special chars.
+ if (/^[A-Za-z0-9_./:-]+$/.test(value)) return value;
+ return JSON.stringify(value);
+}
diff --git a/v3/@claude-flow/browser/src/domain/workflow.ts b/v3/@claude-flow/browser/src/domain/workflow.ts
new file mode 100644
index 0000000000..7613a5ff81
--- /dev/null
+++ b/v3/@claude-flow/browser/src/domain/workflow.ts
@@ -0,0 +1,131 @@
+/**
+ * @claude-flow/browser - Workflow Types (ADR-122 Phase 7)
+ *
+ * Successful MCTS traces (Phase 4) compile into deterministic Workflow
+ * artifacts. A Workflow is the runnable, replayable, distributable
+ * primitive β€” the output of the substrate.
+ *
+ * Workflows ship with:
+ * - per-step selector fallback graph (degrade gracefully)
+ * - policy manifest (which capsules, which task class)
+ * - replay guards (max-retries, timeouts, irreversible-action flags)
+ * - ADR trace (which winning MCTS run produced this)
+ */
+
+import { z } from 'zod';
+
+export const SelectorStrategySchema = z.enum([
+ 'ref', // @e1 style β€” fastest, brittle
+ 'css', // standard CSS β€” medium stability
+ 'role', // ARIA role β€” stable across reflows
+ 'text', // visible text β€” language-sensitive
+ 'label', // form label β€” stable for forms
+ 'placeholder', // input placeholder
+ 'testid', // data-testid β€” gold standard
+]);
+export type SelectorStrategy = z.infer<typeof SelectorStrategySchema>;
+
+export const SelectorSpecSchema = z.object({
+ strategy: SelectorStrategySchema,
+ value: z.string().min(1),
+ /** Optional `--name` for role-based locators. */
+ name: z.string().optional(),
+});
+export type SelectorSpec = z.infer<typeof SelectorSpecSchema>;
+
+/** A step in a compiled workflow β€” primary locator + ordered fallbacks. */
+export const WorkflowStepSchema = z.object({
+ /** Action verb (open / click / fill / type / wait / screenshot / extract / ...). */
+ action: z.string().min(1),
+ /** For non-target verbs (open) this is the URL; for selector verbs it's the primary locator. */
+ target: z.union([z.string(), SelectorSpecSchema]).optional(),
+ /** Ordered fallback selectors β€” tried in sequence if primary fails. */
+ fallback: z.array(SelectorSpecSchema).default([]),
+ /** Value for fill/type actions. */
+ value: z.string().optional(),
+ /** Per-step max-retries; defaults to workflow-level. */
+ maxRetries: z.number().int().nonnegative().optional(),
+ /** Optional human-readable comment. */
+ comment: z.string().optional(),
+});
+export type WorkflowStep = z.infer<typeof WorkflowStepSchema>;
+
+export const WorkflowRequirementsSchema = z.object({
+ /** Whether this workflow requires a Session Capsule mount before running. */
+ sessionCapsule: z.boolean().default(false),
+ /** Allowed origins this workflow may touch. */
+ origins: z.array(z.string()).default([]),
+ /** Risk class β€” gates autonomous execution. */
+ taskClass: z.string().default('read-only'),
+});
+export type WorkflowRequirements = z.infer<typeof WorkflowRequirementsSchema>;
+
+export const WorkflowGuardsSchema = z.object({
+ /** This workflow contains irreversible actions (financial/destructive). */
+ irreversibleAction: z.boolean().default(false),
+ /** Require human confirmation before live execution. */
+ requiresUserConfirmation: z.boolean().default(false),
+});
+export type WorkflowGuards = z.infer<typeof WorkflowGuardsSchema>;
+
+export const WorkflowReplaySchema = z.object({
+ maxRetries: z.number().int().nonnegative().default(2),
+ timeoutMs: z.number().int().positive().default(30_000),
+});
+export type WorkflowReplay = z.infer<typeof WorkflowReplaySchema>;
+
+export const WORKFLOW_VERSION = 1;
+
+export const CompiledWorkflowSchema = z.object({
+ /** Slug-shaped identifier. */
+ workflow: z.string().min(1).regex(/^[a-z0-9_-]+$/),
+ version: z.number().int().positive(),
+ /** Original goal that produced this workflow. */
+ goal: z.string().min(1),
+ /** Source MCTS run ID. */
+ sourceMctsRunId: z.string().optional(),
+ /** Source winning branch ID. */
+ sourceBranchId: z.string().optional(),
+ requirements: WorkflowRequirementsSchema,
+ steps: z.array(WorkflowStepSchema),
+ guards: WorkflowGuardsSchema,
+ replay: WorkflowReplaySchema,
+ /** When compiled (ISO timestamp). */
+ compiledAt: z.string(),
+});
+export type CompiledWorkflow = z.infer<typeof CompiledWorkflowSchema>;
+
+/** Cost / risk / auth signals consumed by production-aware UCT. */
+export interface ProductionUctSignals {
+ /** Q β€” accumulated task value from past visits. */
+ qValue: number;
+ /** Replayability score in [0,1]. Higher = more reusable. */
+ replayability: number;
+ /** Risk score in [0,1]. Higher = more irreversible. */
+ risk: number;
+ /** Cumulative token + browser-runtime cost in USD. */
+ costUsd: number;
+ /** Auth fragility in [0,1]. Higher = more likely to need re-auth. */
+ authFragility: number;
+}
+
+export interface ProductionUctWeights {
+ /** Exploration constant `C`. Default sqrt(2). */
+ c: number;
+ /** Replayability bonus weight. */
+ replayBonus: number;
+ /** Risk penalty weight. */
+ riskPenalty: number;
+ /** Cost penalty weight (USD β†’ score units). */
+ costPenalty: number;
+ /** Auth fragility penalty weight. */
+ authPenalty: number;
+}
+
+export const DEFAULT_PRODUCTION_UCT_WEIGHTS: ProductionUctWeights = {
+ c: Math.SQRT2,
+ replayBonus: 0.3,
+ riskPenalty: 0.4,
+ costPenalty: 2.0, // strong penalty per dollar
+ authPenalty: 0.25,
+};
diff --git a/v3/@claude-flow/browser/src/index.ts b/v3/@claude-flow/browser/src/index.ts
index 1455fdbcb8..03127cac3a 100644
--- a/v3/@claude-flow/browser/src/index.ts
+++ b/v3/@claude-flow/browser/src/index.ts
@@ -166,6 +166,37 @@ export {
type RecoveryExplanation,
} from './domain/causal-recovery.js';
+// Workflow Compiler + Production-Aware UCT (ADR-122 Phase 7)
+export {
+ WorkflowCompiler,
+ type CompileInput,
+} from './application/workflow-compiler.js';
+export {
+ productionUct,
+ blendQ,
+ type ProductionUctInput,
+} from './application/production-uct.js';
+export {
+ WORKFLOW_VERSION,
+ CompiledWorkflowSchema,
+ WorkflowStepSchema as CompiledWorkflowStepSchema,
+ WorkflowRequirementsSchema as CompiledWorkflowRequirementsSchema,
+ WorkflowGuardsSchema as CompiledWorkflowGuardsSchema,
+ WorkflowReplaySchema as CompiledWorkflowReplaySchema,
+ SelectorStrategySchema,
+ SelectorSpecSchema,
+ DEFAULT_PRODUCTION_UCT_WEIGHTS,
+ type CompiledWorkflow,
+ type WorkflowStep as CompiledWorkflowStep,
+ type WorkflowRequirements as CompiledWorkflowRequirements,
+ type WorkflowGuards as CompiledWorkflowGuards,
+ type WorkflowReplay as CompiledWorkflowReplay,
+ type SelectorSpec,
+ type SelectorStrategy,
+ type ProductionUctSignals,
+ type ProductionUctWeights,
+} from './domain/workflow.js';
+
// Session Capsule + Risk Classifier + Browser Execution Adapter (ADR-122 Phase 6 β€” substrate)
export {
SessionCapsuleService,
diff --git a/v3/@claude-flow/browser/tests/workflow-compiler.test.ts b/v3/@claude-flow/browser/tests/workflow-compiler.test.ts
new file mode 100644
index 0000000000..b251b2a4b7
--- /dev/null
+++ b/v3/@claude-flow/browser/tests/workflow-compiler.test.ts
@@ -0,0 +1,201 @@
+/**
+ * @claude-flow/browser - Workflow Compiler + Production-Aware UCT Tests (ADR-122 Phase 7)
+ *
+ * Acceptance criteria covered:
+ * - Compile a successful trajectory β†’ CompiledWorkflow with selector fallback per step
+ * - Detect highest-risk action in trajectory; gate requirements + guards accordingly
+ * - Origins extracted from `open` steps populate requirements.origins
+ * - YAML serialisation is deterministic + parseable
+ * - Production-aware UCT formula respects penalties (low Q + high risk < high Q + low risk)
+ * - Unvisited branches still return Infinity (parity with Phase 4 UCB1)
+ * - Cost penalty dominates exploitation when cost is high
+ */
+
+import { describe, it, expect } from 'vitest';
+import { WorkflowCompiler } from '../src/application/workflow-compiler.js';
+import { productionUct, blendQ } from '../src/application/production-uct.js';
+import { sealTrajectory } from '../src/application/signed-trajectory-service.js';
+import { generateWitnessKey } from '../src/infrastructure/witness-signer.js';
+import type { BrowserTrajectory, Snapshot } from '../src/domain/types.js';
+import { DEFAULT_PRODUCTION_UCT_WEIGHTS } from '../src/domain/workflow.js';
+
+const sharedKey = generateWitnessKey();
+
+function buildLoginTrajectory(): BrowserTrajectory {
+ const snapshot: Snapshot = {
+ tree: { role: 'main', children: [] },
+ refs: {
+ '@e1': { role: 'textbox', name: 'Email' },
+ '@e2': { role: 'textbox', name: 'Password' },
+ '@e3': { role: 'button', name: 'Sign in' },
+ },
+ url: 'https://example.com/login',
+ title: 'Login',
+ timestamp: '2026-05-18T20:00:00Z',
+ };
+ return {
+ id: 'wf-traj-1',
+ sessionId: 's',
+ goal: 'Sign in to example.com',
+ startedAt: '2026-05-18T20:00:00Z',
+ completedAt: '2026-05-18T20:00:05Z',
+ success: true,
+ verdict: 'ok',
+ steps: [
+ { action: 'open', input: { url: 'https://example.com/login' }, result: { success: true }, timestamp: '2026-05-18T20:00:00Z' },
+ { action: 'snapshot', input: {}, result: { success: true }, snapshot, timestamp: '2026-05-18T20:00:01Z' },
+ { action: 'fill', input: { target: '@e1', value: '[email protected]' }, result: { success: true }, snapshot, timestamp: '2026-05-18T20:00:02Z' },
+ { action: 'fill', input: { target: '@e2', value: 'hunter2' }, result: { success: true }, snapshot, timestamp: '2026-05-18T20:00:03Z' },
+ { action: 'click', input: { target: '@e3' }, result: { success: true }, snapshot, timestamp: '2026-05-18T20:00:04Z' },
+ ],
+ };
+}
+
+describe('WorkflowCompiler', () => {
+ it('compiles a successful trajectory into a typed workflow', () => {
+ const compiler = new WorkflowCompiler();
+ const { envelope } = sealTrajectory({ trajectory: buildLoginTrajectory(), witnessKey: sharedKey });
+ const wf = compiler.compile({
+ id: 'example-login',
+ goal: 'Sign in to example.com',
+ trajectoryEnvelope: envelope,
+ });
+ expect(wf.workflow).toBe('example-login');
+ expect(wf.steps).toHaveLength(5);
+ expect(wf.requirements.origins).toContain('https://example.com');
+ });
+
+ it('detects draft-write as the highest risk in a login trajectory', () => {
+ const compiler = new WorkflowCompiler();
+ const { envelope } = sealTrajectory({ trajectory: buildLoginTrajectory(), witnessKey: sharedKey });
+ const wf = compiler.compile({
+ id: 'login-flow', goal: 'login flow', trajectoryEnvelope: envelope,
+ });
+ expect(wf.requirements.taskClass).toBe('draft-write');
+ expect(wf.guards.requiresUserConfirmation).toBe(false);
+ expect(wf.guards.irreversibleAction).toBe(false);
+ expect(wf.requirements.sessionCapsule).toBe(true);
+ });
+
+ it('escalates guards when trajectory contains a payment action', () => {
+ const compiler = new WorkflowCompiler();
+ const traj = buildLoginTrajectory();
+ traj.steps.push({
+ action: 'click',
+ input: { target: '@e9' },
+ result: { success: true },
+ timestamp: '2026-05-18T20:01:00Z',
+ });
+ traj.goal = 'Pay invoice';
+ const { envelope } = sealTrajectory({ trajectory: traj, witnessKey: sharedKey });
+ const wf = compiler.compile({ id: 'pay-invoice', goal: traj.goal, trajectoryEnvelope: envelope });
+ expect(wf.requirements.taskClass).toBe('financial');
+ expect(wf.guards.irreversibleAction).toBe(true);
+ expect(wf.guards.requiresUserConfirmation).toBe(true);
+ });
+
+ it('produces selector fallback chain from snapshot metadata', () => {
+ const compiler = new WorkflowCompiler();
+ const { envelope } = sealTrajectory({ trajectory: buildLoginTrajectory(), witnessKey: sharedKey });
+ const wf = compiler.compile({ id: 'login', goal: 'login', trajectoryEnvelope: envelope });
+
+ const clickStep = wf.steps.find(s => s.action === 'click')!;
+ // Primary is @e3 ref; fallback should include role:button name:Sign in
+ expect(clickStep.target).toMatchObject({ strategy: 'ref', value: '@e3' });
+ expect(clickStep.fallback.some(f => f.strategy === 'role' && f.value === 'button' && f.name === 'Sign in')).toBe(true);
+ expect(clickStep.fallback.some(f => f.strategy === 'text' && f.value === 'Sign in')).toBe(true);
+ });
+
+ it('renders deterministic YAML', () => {
+ const compiler = new WorkflowCompiler();
+ const { envelope } = sealTrajectory({ trajectory: buildLoginTrajectory(), witnessKey: sharedKey });
+ const wf = compiler.compile({
+ id: 'login', goal: 'login', trajectoryEnvelope: envelope, compiledAt: '2026-05-18T21:00:00Z',
+ });
+ const yaml = compiler.toYaml(wf);
+ expect(yaml).toContain('workflow: login');
+ expect(yaml).toContain('version: 1');
+ expect(yaml).toContain('compiledAt: 2026-05-18T21:00:00Z');
+ expect(yaml).toContain(' - action: click');
+ expect(yaml).toContain(' target:');
+ expect(yaml).toContain(' strategy: ref');
+ expect(yaml).toContain(' fallback:');
+ expect(yaml).toContain(' - strategy: role');
+ });
+});
+
+describe('productionUct', () => {
+ const visited = (visits: number, parentVisits: number) => ({ visits, parentVisits });
+
+ it('returns Infinity for unvisited branches', () => {
+ const score = productionUct({
+ ...visited(0, 10),
+ signals: { qValue: 0, replayability: 0, risk: 0, costUsd: 0, authFragility: 0 },
+ });
+ expect(score).toBe(Infinity);
+ });
+
+ it('prefers high-Q low-risk branches over high-Q high-risk', () => {
+ const safe = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.8, replayability: 0.5, risk: 0.0, costUsd: 0.01, authFragility: 0.1 },
+ });
+ const risky = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.8, replayability: 0.5, risk: 0.9, costUsd: 0.01, authFragility: 0.1 },
+ });
+ expect(safe).toBeGreaterThan(risky);
+ });
+
+ it('penalizes high cost', () => {
+ const cheap = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.6, replayability: 0.3, risk: 0.1, costUsd: 0.01, authFragility: 0.1 },
+ });
+ const expensive = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.6, replayability: 0.3, risk: 0.1, costUsd: 0.5, authFragility: 0.1 },
+ });
+ expect(cheap).toBeGreaterThan(expensive);
+ expect(cheap - expensive).toBeCloseTo(
+ DEFAULT_PRODUCTION_UCT_WEIGHTS.costPenalty * (0.5 - 0.01),
+ 4,
+ );
+ });
+
+ it('rewards high replayability', () => {
+ const replayable = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.5, replayability: 1.0, risk: 0.1, costUsd: 0.01, authFragility: 0.1 },
+ });
+ const oneShot = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.5, replayability: 0.0, risk: 0.1, costUsd: 0.01, authFragility: 0.1 },
+ });
+ expect(replayable).toBeGreaterThan(oneShot);
+ });
+
+ it('honours custom weights', () => {
+ const weights = { ...DEFAULT_PRODUCTION_UCT_WEIGHTS, riskPenalty: 0 };
+ const risky = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.5, replayability: 0.5, risk: 1.0, costUsd: 0.01, authFragility: 0.0 },
+ }, weights);
+ const safe = productionUct({
+ ...visited(5, 20),
+ signals: { qValue: 0.5, replayability: 0.5, risk: 0.0, costUsd: 0.01, authFragility: 0.0 },
+ }, weights);
+ // With riskPenalty=0 the two should now tie
+ expect(risky).toBeCloseTo(safe, 6);
+ });
+});
+
+describe('blendQ', () => {
+ it('returns raw scorer value when replaySuccessRate is undefined', () => {
+ expect(blendQ(0.7)).toBe(0.7);
+ });
+
+ it('linearly blends scorer + replay-success', () => {
+ expect(blendQ(0.8, 0.6)).toBeCloseTo(0.7 * 0.8 + 0.3 * 0.6, 6);
+ });
+});