Skip to main content

What is Branching Mode?

Branching mode implements forward simulation with counterfactual branching: the timeline proceeds forward from an origin, but at critical decision points, the simulation explores multiple divergent futures simultaneously. Think of Branching mode as “what if?” exploration: at key moments, the system generates 3-5 different outcomes and follows each branch to its conclusion.
Core concept: Branching mode explores the possibility space. At decision points, instead of choosing one path, it explores multiple paths in parallel.

When to Use Branching Mode

Use Branching mode when:
  • Exploring alternatives - What if we had chosen strategy B instead of A?
  • Counterfactual analysis - How would history change if X?
  • Strategic planning - Evaluate multiple approaches before committing
  • Risk assessment - Explore best-case, worst-case, and twist scenarios
  • Training data diversity - Generate varied outcomes from the same setup

Perfect for

  • Strategic decision analysis
  • Crisis response scenarios
  • “Choose your own adventure” narratives
  • Survival/resource allocation scenarios
  • Negotiation strategy comparison

Not ideal for

  • Single linear timeline (use Forward)
  • Working backward from outcome (use Portal)
  • Repeating cycles (use Cyclical)
  • Dramatic storytelling (use Directorial)

How Branching Mode Works

1

Define Origin & Scenario

Specify the starting state and scenario description:
{
  "scenario_description": "Research vessel Meridian crash-lands on Kepler-442b. Six crew must decide: fortify, explore, or repair beacon.",
  "temporal": {
    "mode": "branching",
    "origin_year": 2034,
    "backward_steps": 15,  // forward steps in branching
    "path_count": 5,  // branches to explore
    "enable_counterfactuals": true
  }
}
2

Generate Forward Steps

Timeline proceeds forward chronologically, generating plausible consequent states:
  • What happens next given current state?
  • Uses LLM + scenario anchoring to prevent drift
  • Accumulates world state across steps
3

Detect Branch Points

System detects decision/conflict moments:
  • Conflict keywords (“decide”, “choose”, “confront”)
  • Regular intervals (every N steps)
  • High-tension moments
At branch points, generates divergent outcomes instead of continuations.
4

Explore Branches

At each branch point, generate N divergent futures:
  • Positive outcome - Things go well
  • Negative outcome - Things go poorly
  • Neutral outcome - Mixed results
  • Twist outcome - Unexpected intervention
5

Score & Rank Branches

Each branch is scored for:
  • Plausibility - Could this realistically happen?
  • Coherence - Does it follow from prior events?
  • Diversity - How different is it from other branches?

Architecture

Branching mode is implemented in workflows/branching_strategy.py:
class BranchingStrategy:
    """
    Forward simulation strategy with counterfactual branching.
    
    Process:
    1. Generate origin state from initial scene
    2. Step forward, detecting decision/branch points
    3. At branch points, generate N divergent futures
    4. Score and rank branches using hybrid scoring
    5. Validate backward coherence (does path make causal sense?)
    6. Return all branches with rankings
    """
    
    def run(self) -> list[BranchingPath]:
        """
        Execute forward simulation with branching.
        
        Returns:
            List of BranchingPath objects (one per branch)
        """

Key Data Structures

@dataclass
class BranchingState:
    """A state at a specific point in the forward simulation"""
    year: int
    month: int
    description: str
    entities: list[Entity]
    world_state: dict[str, Any]
    plausibility_score: float = 0.0
    parent_state: Optional["BranchingState"] = None  # T-1
    children_states: list["BranchingState"] = field(default_factory=list)  # T+1
    branch_id: str = ""  # Identifies which branch this belongs to
    is_branch_point: bool = False
    outcome_type: str = ""  # positive, negative, neutral, twist

@dataclass
class BranchingPath:
    """Complete path from origin through one branch to endpoint"""
    path_id: str
    branch_name: str  # "Positive outcome", "Twist outcome", etc.
    states: list[BranchingState]  # Ordered origin → endpoint
    coherence_score: float
    branch_points: list[int]  # Indices where branches occurred
    explanation: str

Configuration

{
  "temporal": {
    "mode": "branching",
    "origin_year": 2034,
    "backward_steps": 15,  // actually forward steps
    "path_count": 5,  // number of branches
    "enable_counterfactuals": true,
    "candidate_antecedents_per_step": 3,
    "coherence_threshold": 0.7,
    "max_parallel_workers": 8,
    "fidelity_planning_mode": "hybrid",
    "token_budget": 200000.0
  }
}
ParameterTypeDefaultDescription
modestringrequiredMust be "branching"
origin_yearintrequiredStarting year
backward_stepsint15Forward steps to generate
path_countint5Number of branches to explore
enable_counterfactualsbooltrueEnable counterfactual branching
candidate_antecedents_per_stepint3Candidate futures per step
coherence_thresholdfloat0.7Minimum branch plausibility
max_parallel_workersint5Parallel LLM calls per step
dramatic_tensionfloat0.8Tension level for branch detection

Template Examples

Example 1: Castaway Colony (Full Mechanism Showcase)

From showcase/castaway_colony_branching.json:
{
  "scenario_description": "Research vessel Meridian crash-lands on Kepler-442b. Six crew survive with partial supplies, damaged ship, no contact with Earth for 14 months. On Day 7, Commander Tanaka must choose: Branch A (Fortify & Wait), Branch B (Explore & Adapt), or Branch C (Repair & Signal).",
  "temporal": {
    "mode": "branching",
    "backward_steps": 15,
    "path_count": 5,
    "enable_counterfactuals": true,
    "max_parallel_workers": 8,
    "fidelity_planning_mode": "hybrid",
    "token_budget": 200000.0
  },
  "metadata": {
    "mechanisms_featured": [
      "M1_heterogeneous_fidelity",
      "M2_progressive_training",
      "M3_exposure_events",
      "M12_counterfactual_branching",
      "M15_entity_prospection",
      "M16_animistic_entities"
    ],
    "branching_points": [
      {
        "timepoint": "tp_005",
        "day": 7,
        "trigger": "Commander must decide colony strategy",
        "branches": {
          "branch_a_fortify": {
            "label": "Fortify & Wait",
            "description": "Consolidate at crash site. Repair life support, ration supplies. Conservative but depletes reserves.",
            "risk_profile": "low_risk_low_reward"
          },
          "branch_b_explore": {
            "label": "Explore & Adapt",
            "description": "Send teams into biosphere. Discover food sources, map caves. Higher risk, builds knowledge.",
            "risk_profile": "high_risk_high_reward"
          },
          "branch_c_repair": {
            "label": "Repair & Signal",
            "description": "All resources to beacon repair. Fastest rescue if successful; catastrophic if fails.",
            "risk_profile": "binary_outcome"
          }
        }
      }
    ]
  }
}
Cost: $1.50 | Duration: ~20min | Entities: 10 | Branches: 3 major + variations Knowledge provenance examples:
  • “Who discovered the edible purple lichen?” → Dr. Okonkwo (xenobiologist)
  • “Who noticed fauna migration predicts storms?” → Vasquez (atmospheric scientist)
  • “Who found the cave system?” → Lt. Cole (security)

Example 2: VC Pitch Branching

From showcase/vc_pitch_branching.json:
{
  "scenario_description": "Pre-seed pitch with counterfactual branching. At critical moments (equity ask, runway questions, competitive landscape), explore what happens if founder takes aggressive vs. conservative approach.",
  "temporal": {
    "mode": "branching",
    "path_count": 4,
    "enable_counterfactuals": true
  },
  "metadata": {
    "mechanisms_featured": [
      "M11_dialog_synthesis",
      "M12_counterfactual_branching",
      "M13_relationship_evolution",
      "M15_entity_prospection"
    ]
  }
}
Cost: $0.10 | Duration: ~4min | Branches: 4 Branches explored:
  1. Aggressive equity ask (10% for $500K) → Investor pushback
  2. Conservative ask (15% for $500K) → Easy yes but dilution regret
  3. Strategic pivot → Redirects to warm intro pathway
  4. Early termination → Founder realizes poor fit, exits gracefully

Branch Detection Logic

Branching mode detects branch points using:
def _is_branch_point(self, state: BranchingState, step: int) -> bool:
    """
    Detect if this state is a decision/branch point.
    
    Branch points occur at:
    - Conflict moments (negotiations, confrontations)
    - Decision keywords ("decide", "choose", "fork")
    - Key milestones (every N steps)
    """
    # Branch at regular intervals
    branch_interval = max(1, self.forward_steps // self.branch_count)
    if step > 0 and step % branch_interval == 0:
        return True
    
    # Check for decision/conflict keywords
    conflict_keywords = [
        "decide", "choice", "confront", "negotiate",
        "choose", "fork", "branch", "option", "alternative"
    ]
    if any(kw in state.description.lower() for kw in conflict_keywords):
        return True
    
    return False

Consequent Generation

At branch points, the system generates divergent outcomes:
def _generate_consequents(
    self,
    current_state: BranchingState,
    target_year: int,
    target_month: int,
    is_branch_point: bool = False
) -> list[BranchingState]:
    """
    Generate N plausible NEXT states.
    
    At branch points: Generate VERY DIFFERENT outcomes:
    - One where things go well for protagonist
    - One where things go poorly
    - One with unexpected twist or intervention
    
    Otherwise: Generate continuations with slight variations.
    """
Prompt diversity instruction (branch points):
Generate 3 VERY DIFFERENT outcomes:
- One where things go well for the protagonist
- One where things go poorly
- One with an unexpected twist or intervention
- Vary the outcomes significantly - these are alternate timelines

Scenario Anchoring

Branching mode uses accumulated world state to prevent drift:
class BranchingStrategy:
    def __init__(self, ...):
        # Accumulated world state carries forward across steps
        self.accumulated_world_state = {
            "discoveries": [],
            "resource_states": {},
            "entity_knowledge": {},
            "key_events_history": [],
            "monitoring": {
                "steps_completed": 0,
                "scenario_drift_warnings": 0
            }
        }
Scenario anchor in prompt:
SCENARIO ANCHOR — do NOT drift from this premise:
{scenario_description[:800]}
All events MUST remain grounded in this scenario.
This ensures branches don’t drift into unrelated narratives.

Parallel Processing

Branching mode supports parallel LLM calls for efficiency:
# Multiple states at the same step level are independent
# Process them concurrently
with ThreadPoolExecutor(max_workers=max_workers) as executor:
    futures = [
        executor.submit(process_single_state, state)
        for state in current_states
    ]
    for future in as_completed(futures):
        results = future.result()
        next_states.extend(results)
Set max_parallel_workers: 8 in config to enable.

Best Practices

The scenario description anchors all branches. Include:
  • Setup: Who, what, where, when
  • Key entities: Name and role
  • Decision point: What choice must be made
  • Constraints: Resources, time limits, stakes
Good example:
“Meridian crashes on Kepler-442b. 6 crew, 14 days of food, damaged beacon. Day 7: Commander must choose survival strategy.”
For structured scenarios, explicitly define branches in metadata:
{
  "metadata": {
    "branching_points": [
      {
        "timepoint": "tp_005",
        "trigger": "Commander decision",
        "branches": {
          "fortify": {"label": "Fortify & Wait"},
          "explore": {"label": "Explore & Adapt"},
          "repair": {"label": "Repair & Signal"}
        }
      }
    ]
  }
}
Define entities upfront to keep narrative grounded:
{
  "metadata": {
    "entity_roster": {
      "cmdr_tanaka": {
        "role": "Mission commander",
        "initial_knowledge": ["crash_cause_partial"]
      }
    }
  }
}
{
  "temporal": {
    "max_parallel_workers": 8
  }
}
Branching mode can parallelize state processing within each step.
For resource-constrained scenarios, define quantitative tracking:
{
  "metadata": {
    "quantitative_tracking": {
      "o2_reserves": {"unit": "hours", "initial": 336},
      "food_rations": {"unit": "kg", "initial": 180},
      "hull_integrity": {"unit": "percentage", "initial": 62}
    }
  }
}

Cost Estimates

Quick

0.100.10 - 0.203-4 entities8-10 steps3-5 branches4-6 min

Standard

0.400.40 - 0.806-8 entities12-15 steps5-7 branches10-15 min

Comprehensive

1.001.00 - 2.008-10 entities15-20 steps8-10 branches20-30 min
Branching mode is more expensive than Forward because it explores multiple parallel timelines.

Running Branching Mode

# Run a branching template
./run.sh run castaway_colony_branching

# Run VC pitch branching
./run.sh run vc_pitch_branching

# Quick mode (fewer steps)
./run.sh run castaway_colony_branching --quick

Output Structure

Branching mode returns one path per branch:
[
  {
    "path_id": "branch_path_a8f9",
    "branch_name": "Positive outcome",
    "coherence_score": 0.82,
    "states": [...],
    "branch_points": [5, 11],
    "explanation": "Path following positive outcomes where crew makes optimal decisions"
  },
  {
    "path_id": "branch_path_b2c4",
    "branch_name": "Negative outcome",
    "coherence_score": 0.78,
    "states": [...],
    "branch_points": [5, 11],
    "explanation": "Path where resource depletion and injuries accumulate"
  }
]
Branching mode commonly pairs with:
  • M3 (Exposure Events) - Track knowledge flow across branches
  • M7 (Causal Chains) - Validate causality within each branch
  • M11 (Dialog Synthesis) - Generate conversations at decision points
  • M12 (Counterfactual Branching) - Core mechanism
  • M15 (Entity Prospection) - Characters model future outcomes

Next Steps

Build docs developers (and LLMs) love