> ## Documentation Index
> Fetch the complete documentation index at: https://www.stratus.run/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Cascade Prediction

> Build agents that predict and handle chain reactions before they execute

Some actions don't just change one thing — they trigger waves. A button click recalculates prices, updates inventory, fires webhooks, and invalidates caches. A schema migration cascades through indexes, views, and downstream services. An agent that acts without predicting these chains makes costly mistakes.

Stratus was benchmarked on exactly this problem. In the **Cascade Reactor** level — where every click triggers three waves of ripple effects at 700ms intervals — the Stratus agent solved the board in ≤10 moves. The baseline didn't finish.

<CardGroup cols={3}>
  <Card title="Predict Before Acting" icon="eye" color="#22d3ee">
    The world model simulates cascade outcomes in embedding space before your LLM executes a single action.
  </Card>

  <Card title="Chain Reasoning" icon="diagram-project" color="#c084fc">
    Stratus tracks multi-step consequence chains — not just "what does this action do" but "what does that effect cause next."
  </Card>

  <Card title="Interference Avoidance" icon="shield-check" color="#34d399">
    Identifies when two planned actions would collide in a downstream state — and reorders before execution.
  </Card>
</CardGroup>

## The Pattern

Cascade-aware agents follow a loop: **predict → verify → execute**. Only commit to an action after the world model confirms the predicted outcome moves toward the goal.

```
Current State
    ↓
Stratus: encode state → predict next state for each candidate action
    ↓
Select action whose predicted outcome best matches goal state
    ↓
Execute → observe actual next state
    ↓
Verify predicted ≈ actual (if not, re-plan)
    ↓
Repeat
```

## Example: E-Commerce Checkout with Side Effects

A checkout flow that cascades: applying a coupon triggers price recalculation, eligibility checks, and a cart lock that expires in 30 seconds. An agent that doesn't predict this chain will race against state it created.

<CodeGroup>
  ```typescript TypeScript theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
    baseURL: 'https://api.stratus.run/v1',
    apiKey: process.env.STRATUS_API_KEY
  });

  interface AgentState {
    description: string;
    knownEffects?: string[];
  }

  async function predictAndAct(state: AgentState, goal: string) {
    const stateDescription = state.knownEffects?.length
      ? `${state.description}\nKnown side effects from last action: ${state.knownEffects.join(', ')}`
      : state.description;

    const response = await client.chat.completions.create({
      model: 'stratus-x1ac-base-gpt-4o',
      messages: [
        { role: 'system', content: `Current state: ${stateDescription}` },
        { role: 'user', content: goal }
      ]
    });

    const { action_sequence, confidence } = response.stratus;

    return {
      action: response.choices[0].message.content,
      predictedChain: action_sequence,
      confidence,
      shouldProceed: confidence > 0.8
    };
  }

  async function checkoutWithCascades() {
    // Step 1: Apply coupon — this triggers a cascade
    const couponStep = await predictAndAct(
      {
        description: 'Cart page. Items: Laptop $999, Case $49. Subtotal: $1048. Coupon field empty. Apply button visible.',
      },
      'Apply coupon code SAVE20'
    );

    console.log('Action:', couponStep.action);
    console.log('Predicted chain:', couponStep.predictedChain);
    // Predicted chain: ["type", "click", "wait", "verify-discount", "update-total"]

    if (!couponStep.shouldProceed) {
      console.warn('Low confidence on cascade step. Inspect state before proceeding.');
      return;
    }

    // Step 2: State now includes the effects from the coupon cascade
    const checkoutStep = await predictAndAct(
      {
        description: 'Cart page. Coupon SAVE20 applied. Discount: -$209.60. New total: $838.40. Cart locked for 28 seconds. Proceed to Checkout button active.',
        knownEffects: [
          'coupon discount applied',
          'cart locked with 28s timer',
          'inventory hold placed'
        ]
      },
      'Proceed to checkout before cart lock expires'
    );

    console.log('Action:', checkoutStep.action);
    console.log('Confidence:', checkoutStep.overall_confidence);
  }

  checkoutWithCascades();
  ```

  ```python Python theme={null}
  import os
  from openai import OpenAI

  client = OpenAI(
      base_url="https://api.stratus.run/v1",
      api_key=os.environ["STRATUS_API_KEY"]
  )

  def predict_and_act(state_description, goal, known_effects=None):
      if known_effects:
          state_description += f"\nKnown side effects from last action: {', '.join(known_effects)}"

      response = client.chat.completions.create(
          model="stratus-x1ac-base-gpt-4o",
          messages=[
              {"role": "system", "content": f"Current state: {state_description}"},
              {"role": "user", "content": goal}
          ]
      )

      meta = response.stratus
      return {
          "action": response.choices[0].message.content,
          "predicted_chain": meta.action_sequence,
          "confidence": meta.overall_confidence,
          "should_proceed": meta.overall_confidence > 0.8
      }

  # Step 1: Apply coupon — triggers a cascade
  result = predict_and_act(
      "Cart page. Items: Laptop $999, Case $49. Subtotal: $1048. Coupon field empty.",
      "Apply coupon code SAVE20"
  )
  print(f"Action: {result['action']}")
  print(f"Predicted chain: {' → '.join(result['predicted_chain'])}")
  # ['type', 'click', 'wait', 'verify-discount', 'update-total']

  # Step 2: Proceed with full cascade context
  result = predict_and_act(
      "Cart page. Coupon SAVE20 applied. Discount: -$209.60. New total: $838.40. Cart locked 28s.",
      "Proceed to checkout before cart lock expires",
      known_effects=["coupon applied", "cart locked with timer", "inventory hold placed"]
  )
  print(f"Confidence: {result['confidence']}")
  ```
</CodeGroup>

## Encoding Known Side Effects

The key to reliable cascade handling is **forward-feeding observed effects** into the next state description. Stratus uses this to build an accurate embedding of "where we are now, including what just changed."

```typescript theme={null}
// After executing an action, capture what changed
const observedEffects = [
  'dropdown expanded with 5 options',
  'form validation re-triggered',
  'price updated from $99 to $89'
];

// Feed into next state description
const nextState = `
  Product page. Price updated to $89 (was $99).
  Size selector open with options: XS, S, M, L, XL.
  Add to Cart button grayed out until size selected.
  Form validation active — required field indicator visible on Size.
  Known effects from last action: ${observedEffects.join(', ')}
`;
```

## Using the Rollout API for Deep Chains

For cascades with many steps, use `/v1/rollout` to simulate the full chain before executing anything.

```typescript theme={null}
const plan = await fetch('https://api.stratus.run/v1/rollout', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.STRATUS_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    goal: 'Apply coupon and complete checkout',
    initial_state: 'Cart page with 3 items, coupon field visible',
    max_steps: 8
  })
}).then(r => r.json());

console.log('Full predicted chain:', plan.predictions.map(p => p.action.action_name));
console.log('Outcome:', plan.summary.outcome);       // 'success' or 'failure'
console.log('Confidence:', plan.summary.overall_confidence); // 0-1
```

<Note>
  `/v1/rollout` doesn't require an LLM provider key — it runs entirely on the Stratus world model. Use it for planning validation before committing to execution.
</Note>

## When to Use Cascade Prediction

<CardGroup cols={2}>
  <Card title="Use It" icon="check" color="#34d399">
    * Multi-step checkout flows
    * Form submissions with validation cascades
    * Database operations with constraint propagation
    * Workflow automation with dependent steps
    * UI interactions that trigger loading states
  </Card>

  <Card title="Skip It" icon="x" color="#818cf8">
    * Single-step actions with no side effects
    * Read-only operations (search, display)
    * Simple classification or extraction tasks
    * Stateless API calls
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={3}>
  <Card title="Temporal Sequencing" icon="clock" color="#fbbf24" href="/docs/tutorials/temporal-sequencing">
    When action order matters — avoiding interference between concurrent operations.
  </Card>

  <Card title="Rollout API" icon="crystal-ball" color="#c084fc" href="/docs/api-reference/rollout">
    Simulate full action chains before committing to execution.
  </Card>

  <Card title="Web Navigation" icon="globe" color="#22d3ee" href="/docs/tutorials/web-navigation">
    Full step-by-step navigation tutorial with state quality guidance.
  </Card>
</CardGroup>
