Skill: midnightstudioai/game-theory-strategist (version 1.0.1)

--- description: 'Analyze strategic interactions and calculate optimal decision paths using Game Theory. Trigger on: strategic planning, negotiation tactics, pricing wars, competitive analysis, conflict of interest, or any scenario where outcomes depend on multiple agents. Also trigger for Nash Equilibrium, dominant strategies, backward induction, Pareto optimality, mechanism design, Bayesian games, Prisoner''s Dilemma, salary negotiation, co-founder disputes, inheritance conflicts, career pivots, household coordination. If someone asks what should I do knowing my competitor will react or how do I negotiate or I have a conflict - use this skill. Produces dark-themed visual analysis: payoff matrix, Nash equilibrium, optimal strategy, action phases, strategic verdict.' name: game-theory-strategist compatibility: runtime: python3 dependencies: - numpy platform: claude.ai notes: Scripts require Python 3 + numpy. sendPrompt() and HTML artifact rendering are claude.ai-specific features. --- # Game Theory Strategist ## Philosophy This skill operates on the principle of **Strategic Interdependence**: an agent's utility is contingent upon the actions of others. We move beyond simple optimization to recursive modeling — asking not just what we should do, but what we should do *in response to what others do*, knowing they are thinking the same about us. The skill balances pure theoretical rationality with **Bounded Rationality** — recognizing that humans use heuristics, suffer cognitive biases, and satisfice rather than optimize. The output is always actionable, never just academic. --- ## Operational Workflow ### Step 1 — Game Identification & Classification Categorize the interaction: - **Players**: Identity and number of decision-makers - **Rules**: Sequential (Extensive Form) vs. Simultaneous (Normal Form) - **Payoffs**: Zero-sum vs. Non-zero-sum (Partial Conflict) - **Information**: Perfect, Imperfect, or Asymmetric (Bayesian) - **Duration**: One-shot vs. Repeated (Finite or Infinite) ### Step 2 — Modeling & Representation - **Simultaneous Games**: Construct a Payoff Matrix (utility values -10 to +10) - **Sequential Games**: Map decision tree with backward induction - **Repeated Games**: Identify shadow of the future and trigger strategies ### Step 3 — Solution Concepts Apply the relevant lens: - **Dominant Strategy Equilibrium**: Best move regardless of opponent - **Nash Equilibrium**: States where no player benefits by unilateral deviation (mark with ★) - **Subgame Perfect Equilibrium**: Backward induction for sequential games - **Pareto Optimality**: Is the equilibrium efficient for the group? If not, flag it ### Step 4 — Mechanism Design (when applicable) For coaching/negotiation scenarios, evaluate whether the current "rules of the game" can be redesigned: - **Individual Rationality (IR)**: All parties prefer participating over walking away - **Incentive Compatibility (IC)**: Truth-telling or desired behavior is the optimal strategy - Use `scripts/mechanism_designer.py` to check IR and IC conditions formally (requires Python 3 + numpy; if unavailable, apply IR/IC checks manually using the definitions above) ### Step 5 — Regret & Risk Evaluation (for career/life decisions) For uncertain life choices with multiple paths: - Apply Counterfactual Regret Minimization principles - Use `scripts/regret_calculator.py` to simulate mixed strategies over iterations (requires Python 3 + numpy; if unavailable, reason through CFR principles qualitatively) - Factor in variance preferences (stable low-variance vs. high-variance high-EV options) ### Step 6 — Behavioral Adjustment - Adjust theoretical optimum for opponent's cognitive biases (anchoring, loss aversion, fairness norms) - Identify nudge or signaling strategies - Account for Brinkmanship in high-stakes negotiations: leverage is created by credibly raising mutual risk ### Step 7 — Output Produce a **structured visual analysis** (HTML artifact). See Output Format section below. --- ## Commands - `/model_conflict [description]`: Maps a personal/professional dispute into a normal or extensive-form game to identify Nash Equilibria - `/minimize_regret [option A] [option B]`: Applies CFR principles to weigh long-term costs of divergent life choices - `/design_incentives [goal]`: Constructs an incentive-compatible framework for partners, employees, or family members --- ## Output Format Always produce a **dark-themed HTML artifact** with the following sections: 1. **CLASIFICACIÓN DEL JUEGO** — 4 cards: Tipo, Información, Suma cero, Repetido 2. **MATRIZ DE PAGOS** — Table with player strategies as rows/columns, payoff pairs, Nash equilibrium marked ★, Pareto label if applicable 3. **EQUILIBRIO DE NASH** — Two cards: current equilibrium analysis + Price of Anarchy (what the weaker player is losing) 4. **ESTRATEGIAS ÓPTIMAS** — Two columns: dominant strategy for the user + why the opponent isn't moving 5. **PLAN DE ACCIÓN POR FASES** — Numbered steps derived from backward induction 6. **VEREDICTO ESTRATÉGICO** — 2-3 sentence synthesis 7. **Action Buttons** — 2-3 follow-up prompts the user can click (use `sendPrompt()` — claude.ai only; omit buttons if rendering outside claude.ai) ### Visual Style - Background: `#0f0f0f`, cards: `#1a1a1a`, borders: `#2a2a2a` - Nash equilibrium cell: teal highlight `rgba(20, 184, 166, 0.15)`, border `#14b8a6` - Warning/bad equilibrium: red-orange `rgba(239, 68, 68, 0.1)` - Positive values: `#4ade80`, negative values: `#f87171`, neutral: `#94a3b8` - Font: IBM Plex Mono or JetBrains Mono for data; system sans-serif for prose - Pareto badge: pill label `#ef4444` background on matrix header when NOT Pareto-optimal --- ## Reference Files - `references/methodology.md` — Theoretical foundations (Von Neumann, Nash, Selten, Harsanyi, Schelling, Kahneman). Read when you need to justify solution concepts or explain theory to the user. - `evals/evals.json` — 5 benchmark scenarios with expected outputs. Use to verify skill quality. ## Scripts - `scripts/regret_calculator.py` — CFR simulation for life/career decisions with multiple uncertain paths - `scripts/mechanism_designer.py` — IR/IC checker for agreement and negotiation design

path: evals/evals.json
content: [
  {
    "scenario_id": "EV-001",
    "title": "Salary Negotiation under Incomplete Information",
    "description": "User is negotiating a starting salary but does not know the company's true reservation price. The company knows the user's current salary. Assess using Bayesian game principles.",
    "expected_coaching_output": "Formulate a signaling strategy to reveal the user's 'type' (high-value) without exposing their reservation minimum. Produce a 2x2 matrix with user strategies (Anchor High / Reveal Current) vs company strategies (Meet / Lowball). Identify Nash Equilibrium. Recommend anchoring first with a credible high number backed by market data, framed as the user's outside option — not as a demand. Plan includes: research phase, anchor delivery script, silence tactic post-offer.",
    "expected_sections": ["CLASIFICACIÓN DEL JUEGO", "MATRIZ DE PAGOS", "EQUILIBRIO DE NASH", "ESTRATEGIAS ÓPTIMAS", "PLAN DE ACCIÓN POR FASES", "VEREDICTO ESTRATÉGICO"]
  },
  {
    "scenario_id": "EV-002",
    "title": "Family Inheritance Ultimatum",
    "description": "User is offered an unfair split of an inheritance by a sibling (80/20). If the user rejects, neither gets anything. Evaluate using Behavioral Game Theory.",
    "expected_coaching_output": "Identify Ultimatum Game dynamics. Classify as one-shot sequential game with asymmetric information about the sibling's minimum acceptable split. Acknowledge inequity aversion. Propose shifting from single-shot Ultimatum to iterated negotiation by introducing a third option (delay, mediation, legal escalation) that changes the payoff structure. Nash in current form: sibling proposes 80/20, user accepts reluctantly. After mechanism redesign: equilibrium shifts toward fairer split.",
    "expected_sections": ["CLASIFICACIÓN DEL JUEGO", "MATRIZ DE PAGOS", "EQUILIBRIO DE NASH", "ESTRATEGIAS ÓPTIMAS", "PLAN DE ACCIÓN POR FASES", "VEREDICTO ESTRATÉGICO"]
  },
  {
    "scenario_id": "EV-003",
    "title": "Career Pivot: Exploration vs. Exploitation",
    "description": "User is ten years into a stable but unfulfilling career and is considering a high-risk startup venture. Apply Regret Minimization and CFR.",
    "expected_coaching_output": "Apply CFR framework. Model as multi-period decision under uncertainty. Stable career: EV ~5, low variance (σ=1). Startup: EV ~6, high variance (σ=4). CFR over 1000 iterations typically converges to 60-70% startup weight when EV advantage is +1 and variance is 4x. Recommend mixed strategy: do not quit immediately — activate startup as side project first to generate real data and reduce variance before committing. Plan phases: validate while employed, set a 6-month decision gate, define exit criteria.",
    "expected_sections": ["CLASIFICACIÓN DEL JUEGO", "PLAN DE ACCIÓN POR FASES", "VEREDICTO ESTRATÉGICO"]
  },
  {
    "scenario_id": "EV-004",
    "title": "Co-founder Equity Dispute",
    "description": "Two co-founders are locked in a Prisoner's Dilemma over workload and equity. Both are currently shirking because they feel the other isn't working hard enough.",
    "expected_coaching_output": "Identify Prisoner's Dilemma: (Shirk, Shirk) is the Nash Equilibrium even though (Work, Work) is Pareto-superior. Use Mechanism Design to restructure. Implement: 4-year vesting with 1-year cliff, quarterly milestone reviews, transparent work-logging. This raises the cost of shirking and shifts Nash from (Defect, Defect) to (Cooperate, Cooperate). Use mechanism_designer.py: set lying_payoff below truthful_payoff for both agents.",
    "expected_sections": ["CLASIFICACIÓN DEL JUEGO", "MATRIZ DE PAGOS", "EQUILIBRIO DE NASH", "PLAN DE ACCIÓN POR FASES", "VEREDICTO ESTRATÉGICO"]
  },
  {
    "scenario_id": "EV-005",
    "title": "The Price of Anarchy in Household Management",
    "description": "A household of 4 adults is experiencing a Tragedy of the Commons regarding shared resources and cleaning.",
    "expected_coaching_output": "Calculate Price of Anarchy: current Nash (everyone free-rides) vs. Pareto optimum (coordinated effort). PoA is likely 3-4x in household chore games. Introduce a Coordination Mechanism: rotating weekly accountability roles, transparent completion tracking, or a small penalty-reward system (chore tax). Show that the mechanism reduces PoA toward 1.0 by making contribution the dominant strategy for each individual.",
    "expected_sections": ["CLASIFICACIÓN DEL JUEGO", "MATRIZ DE PAGOS", "EQUILIBRIO DE NASH", "PLAN DE ACCIÓN POR FASES", "VEREDICTO ESTRATÉGICO"]
  }
]


path: README.md
content: # game-theory-strategist

A skill for Claude that applies game theory frameworks to real decisions — negotiations, conflicts, career pivots, co-founder disputes, household coordination problems.

---

## What it does

When you describe a situation involving another person or genuine uncertainty, the skill:

1. Classifies the type of game (sequential vs simultaneous, symmetric vs asymmetric information, one-shot vs repeated)
2. Builds a payoff matrix with both players' utilities (-10 to +10 scale)
3. Identifies the Nash Equilibrium — the trap you're currently in
4. Flags if the equilibrium is Pareto-suboptimal (i.e., both of you could do better)
5. Derives a dominant strategy and an action plan via backward induction
6. Delivers a strategic verdict

Output is a dark-themed visual analysis rendered directly in Claude.ai.

---

## What it does NOT do

- The payoff matrices are **qualitative approximations**, not cardinal utility measurements. They are illustrative, not formally rigorous. A game theorist would not publish them.
- The CFR script (`scripts/regret_calculator.py`) is a **simplified regret matching simulation** over sampled utilities — not a full CFR implementation over an extensive-form game tree. It is useful for life/career decisions under uncertainty, not for poker or formal mechanism proofs.
- The IR/IC checker (`scripts/mechanism_designer.py`) assumes **linear, comparable utilities** across agents — a strong simplification that rarely holds in practice.
- The skill does **not compute mixed-strategy Nash Equilibria** mathematically. It identifies pure strategy Nash only.
- It does **not replace legal, financial, or professional advice**.

---

## Files

```
game-theory-strategist/
├── SKILL.md                      — skill instructions for Claude
├── README.md                     — this file
├── scripts/
│   ├── regret_calculator.py      — CFR-inspired life decision simulator
│   └── mechanism_designer.py     — IR/IC checker for agreements
├── references/
│   └── methodology.md            — theoretical foundations (Nash, Schelling, Kahneman...)
└── evals/
    └── evals.json                — 5 benchmark scenarios with expected outputs
```

---

## Eval results (5/5 pass, avg 93/100)

| Scenario | Score |
|---|---|
| Salary negotiation under incomplete information | 92 |
| Family inheritance ultimatum game | 95 |
| Career pivot — CFR regret minimization | 88 |
| Co-founder Prisoner's Dilemma | 96 |
| Household Tragedy of the Commons | 94 |

The career pivot scenario scores lowest (88) because it is a decision against nature — no strategic opponent — so no payoff matrix applies. The skill handles it correctly via CFR but the transition is implicit, not explicit.

---

## Installation

Drop the `game-theory-strategist/` folder into your Claude skills directory and reload.

---

## Good test cases

- Freelancer chasing a $2,400 unpaid invoice from a client who can leave a public bad review
- Negotiating a rent increase with a landlord after 3 years of on-time payments

---

## Known limitations worth fixing

- Mixed-strategy Nash (requires linear programming — nashpy or similar)
- Formal PoA calculation (currently narrative only)
- Explicit warning in output when matrix utilities are qualitative estimates
- n-player games beyond 2x2

---

Built with Claude Sonnet 4. Part of the OpenClaw skill library.


path: references/methodology.md
content: # Technical Reference: Game Theory Methodologies

## Table of Contents
1. Mechanism Design & Incentive Alignment
2. Counterfactual Regret Minimization (CFR)
3. Behavioral Game Theory & Bounded Rationality
4. The Price of Anarchy (PoA)
5. Brinkmanship & Dynamic Crises
6. Key Theorists

---

## 1. Mechanism Design & Incentive Alignment

Mechanism design is the science of designing the rules of a game to achieve a specific outcome, even when participants are self-interested. In personal coaching, this translates to setting up boundaries, contracts, or relationship dynamics where individuals have an incentive to behave as intended.

- **Individual Rationality (IR):** Participating in the agreement is better than the outside option (BATNA). If IR fails, the agent will walk away.
- **Incentive Compatibility (IC):** Acting truthfully or cooperatively is the dominant strategy. If IC fails, the agent has a rational reason to defect or misrepresent.
- **Revelation Principle:** Any equilibrium outcome of an arbitrary mechanism can be replicated by an incentive-compatible direct mechanism. Implication: you can always redesign the game so truth-telling is optimal without loss of generality.
- **Vickrey-Clarke-Groves (VCG):** A class of mechanisms that achieve IC in multi-player settings by making each agent pay the social cost of their presence.

**Practical application:** When a relationship/agreement is failing, check IR and IC first. Most chronic conflicts are IC failures — one party has an incentive to shirk because defection is costless. Fix: add monitoring, vesting cliffs, performance milestones, or credible penalties.

---

## 2. Counterfactual Regret Minimization (CFR)

CFR is an iterative learning algorithm for finding Nash Equilibria in imperfect-information games. It works by repeatedly simulating play and adjusting strategy to minimize the regret of not having played differently.

**Regret** = (payoff of best action in hindsight) − (payoff of action actually taken)

CFR guarantees convergence to a Nash Equilibrium in two-player zero-sum games. In n-player or non-zero-sum games it finds correlated or coarse correlated equilibria.

**Application to life decisions:**
- Model the decision as a repeated game against an uncertain "environment"
- Each iteration = a simulated life period with random utility draws
- After N iterations, the average strategy weights are the optimal hedge
- High-variance options (Start Business) can dominate in expected value but lose in regret-minimized mixed strategy when variance is high

**See:** `scripts/regret_calculator.py` for implementation.

---

## 3. Behavioral Game Theory & Bounded Rationality

Classical game theory assumes perfect rationality and common knowledge of rationality. Behavioral GT relaxes this:

- **Bounded Rationality (Simon, 1955):** Agents have limited information, limited computation, and limited time. They satisfice (find "good enough" solutions) rather than optimize.
- **Level-k Thinking:** Level-0 plays randomly; Level-1 best-responds to Level-0; Level-2 best-responds to Level-1. Most humans play Level-1 or Level-2.
- **Inequity Aversion (Fehr-Schmidt):** People reject unfair offers even at personal cost (Ultimatum Game). Rational by social norm enforcement, irrational by classical theory.
- **Loss Aversion (Kahneman-Tversky):** Losses loom ~2x larger than equivalent gains. Exploit this in negotiations by framing your offer as preventing a loss, not delivering a gain.
- **Anchoring:** First number stated in a negotiation disproportionately influences the final outcome. Go first with a high anchor when you have information advantages.
- **Nudges & Boosts (Thaler, Sunstein):** Nudges preserve autonomy while steering choices via defaults and framing. Boosts improve decision competence directly. Both are valid coaching tools.

---

## 4. The Price of Anarchy (PoA)

The Price of Anarchy measures how much social welfare degrades when agents act selfishly versus cooperating optimally.

PoA = (Social cost of worst Nash Equilibrium) / (Social cost of optimal centralized solution)

- PoA = 1.0: Selfish behavior is socially optimal (rare)
- PoA = 2.0: Selfishness causes 2x the social cost of cooperation
- Braess's Paradox: Adding capacity to a network can *increase* total congestion — the social optimum requires coordinated restraint

**Application:** In household, team, or co-founder settings, identify the current Nash and compare it to the Pareto frontier. The gap is the PoA. Coaching intervention = design a coordination mechanism that closes this gap.

---

## 5. Brinkmanship & Dynamic Crises

Derived from Schelling's analysis of the Cuban Missile Crisis and nuclear deterrence.

- **Brinkmanship:** A "competition in risk-taking." Leverage is created not by making a direct threat but by taking steps that credibly raise the probability of mutual disaster.
- **The Threat That Leaves Something to Chance:** Pure threats are often not credible. A threat that involves genuine shared risk is more believable — and therefore more effective.
- **Commitment Devices:** Burn bridges (publicly, irreversibly) to make threats credible. Odysseus tied to the mast; Cortés burning his ships.
- **Focal Points (Schelling Points):** In coordination games without communication, people gravitate toward salient, "natural" solutions. Useful when designing agreements — make the fair/efficient solution the obvious Schelling point.

**Application to negotiation:** Don't just threaten to leave. Actually activate the alternative (get the competing offer, file the paperwork, post the listing). This transforms the threat from cheap talk to credible commitment and shifts the Nash Equilibrium.

---

## 6. Key Theorists

| Theorist | Contribution |
|---|---|
| John von Neumann | Minimax theorem, normal/extensive form games |
| John Nash | Nash Equilibrium, bargaining solution |
| Reinhard Selten | Subgame Perfect Equilibrium, trembling-hand perfection |
| John Harsanyi | Bayesian games, incomplete information |
| Thomas Schelling | Focal points, brinkmanship, commitment devices |
| Roger Myerson | Mechanism design, revelation principle |
| William Vickrey | Incentive-compatible auctions |
| Daniel Kahneman | Prospect theory, cognitive biases in decisions |
| Herbert Simon | Bounded rationality, satisficing |
| Ariel Rubinstein | Bargaining theory, alternating-offers model |


path: scripts/mechanism_designer.py
content: class PersonalMechanismDesigner:
    """
    Evaluates whether a proposed agreement or life arrangement meets the
    criteria for Individual Rationality (IR) and Incentive Compatibility (IC).

    IR:  Participating >= Outside option (agent won't walk away)
    IC:  Acting truthfully >= Acting deceptively (agent has no reason to lie/defect)

    Usage:
        designer = PersonalMechanismDesigner(["Partner A", "Partner B"])
        designer.set_utility("Partner A", truthful_payoff=10, lying_payoff=12, outside_option=2)
        designer.set_utility("Partner B", truthful_payoff=10, lying_payoff=8,  outside_option=2)
        for line in designer.evaluate_mechanism():
            print(line)
    """

    def __init__(self, agents):
        self.agents = agents
        self.utilities = {}

    def set_utility(self, agent, truthful_payoff, lying_payoff, outside_option):
        """
        truthful_payoff  : utility when the agent cooperates/is honest
        lying_payoff     : utility when the agent defects/misrepresents
        outside_option   : utility of not participating at all (BATNA)
        """
        if agent not in self.agents:
            raise ValueError(f"Agent '{agent}' not in agent list: {self.agents}")
        self.utilities[agent] = {
            "truthful": truthful_payoff,
            "lying":    lying_payoff,
            "outside":  outside_option
        }

    def check_individual_rationality(self):
        """IR: participating is better than walking away."""
        return {
            agent: payoffs["truthful"] >= payoffs["outside"]
            for agent, payoffs in self.utilities.items()
        }

    def check_incentive_compatibility(self):
        """IC: truth-telling is better than defecting."""
        return {
            agent: payoffs["truthful"] >= payoffs["lying"]
            for agent, payoffs in self.utilities.items()
        }

    def evaluate_mechanism(self):
        """Returns a list of assessment strings for each agent."""
        ir = self.check_individual_rationality()
        ic = self.check_incentive_compatibility()
        report = []
        for agent in self.agents:
            if agent not in self.utilities:
                report.append(f"MISSING DATA: No utilities set for {agent}.")
                continue
            p = self.utilities[agent]
            failures = []
            if not ir[agent]:
                delta = p["outside"] - p["truthful"]
                failures.append(
                    f"FAILED IR: {agent} will likely walk away "
                    f"(outside option {p['outside']} > participation {p['truthful']}, gap: {delta:+.1f})"
                )
            if not ic[agent]:
                delta = p["lying"] - p["truthful"]
                failures.append(
                    f"FAILED IC: {agent} has incentive to defect/lie "
                    f"(defection payoff {p['lying']} > honest payoff {p['truthful']}, gap: {delta:+.1f})"
                )
            if not failures:
                report.append(
                    f"SUCCESS: {agent}'s incentives are aligned "
                    f"(participation: {p['truthful']}, outside: {p['outside']}, honesty surplus: {p['truthful'] - p['lying']:+.1f})"
                )
            else:
                report.extend(failures)
        return report

    def suggest_fix(self):
        """Suggests adjustments to restore IR and IC for failing agents."""
        ir = self.check_individual_rationality()
        ic = self.check_incentive_compatibility()
        suggestions = []
        for agent in self.agents:
            if agent not in self.utilities:
                continue
            p = self.utilities[agent]
            if not ir[agent]:
                gap = p["outside"] - p["truthful"]
                suggestions.append(
                    f"{agent}: Increase participation payoff by at least {gap:.1f} "
                    f"(e.g., add sweeteners, reduce obligations, or lower the outside option via timing/urgency)."
                )
            if not ic[agent]:
                gap = p["lying"] - p["truthful"]
                suggestions.append(
                    f"{agent}: Reduce defection payoff by at least {gap:.1f} "
                    f"(e.g., add monitoring, penalties for dishonesty, vesting cliffs, or performance milestones)."
                )
        return suggestions if suggestions else ["No fixes needed — mechanism is IR and IC for all agents."]


if __name__ == "__main__":
    # Example: Co-founder equity dispute
    print("=== Co-founder Mechanism Analysis ===")
    designer = PersonalMechanismDesigner(["Founder A", "Founder B"])
    designer.set_utility("Founder A", truthful_payoff=10, lying_payoff=13, outside_option=4)
    designer.set_utility("Founder B", truthful_payoff=10, lying_payoff=7,  outside_option=6)

    print("\nAssessment:")
    for line in designer.evaluate_mechanism():
        print(" ", line)

    print("\nRecommended fixes:")
    for line in designer.suggest_fix():
        print(" ", line)

    print()

    # Example: Marriage chore division
    print("=== Household Chore Mechanism ===")
    designer2 = PersonalMechanismDesigner(["Partner A", "Partner B"])
    designer2.set_utility("Partner A", truthful_payoff=10, lying_payoff=12, outside_option=2)
    designer2.set_utility("Partner B", truthful_payoff=10, lying_payoff=8,  outside_option=2)

    print("\nAssessment:")
    for line in designer2.evaluate_mechanism():
        print(" ", line)


path: scripts/regret_calculator.py
content: import numpy as np

class CounterfactualRegretMinimizer:
    """
    Models a simplified personal decision problem using CFR principles
    to find the optimal mixed strategy over simulated time.

    Usage:
        actions = ["Stay in Job", "Start Business"]
        cfr = CounterfactualRegretMinimizer(actions)
        for _ in range(1000):
            utilities = [np.random.normal(5, 1), np.random.normal(6, 4)]
            cfr.update(utilities)
        print(cfr.get_average_strategy())
        print(cfr.regret_report())
    """

    def __init__(self, actions):
        self.actions = actions
        self.num_actions = len(actions)
        self.regret_sum = np.zeros(self.num_actions)
        self.strategy_sum = np.zeros(self.num_actions)
        self.iteration = 0

    def get_strategy(self):
        """Calculates current strategy via regret matching."""
        strategy = np.maximum(self.regret_sum, 0)
        normalizing_sum = np.sum(strategy)
        if normalizing_sum > 0:
            strategy = strategy / normalizing_sum
        else:
            strategy = np.ones(self.num_actions) / self.num_actions
        return strategy

    def update(self, utilities):
        """
        Updates counterfactual regret based on realized utilities.
        utilities: array of payoffs if each action had been taken.
        """
        utilities = np.array(utilities, dtype=float)
        strategy = self.get_strategy()
        self.strategy_sum += strategy
        expected_utility = np.dot(strategy, utilities)
        for a in range(self.num_actions):
            self.regret_sum[a] += utilities[a] - expected_utility
        self.iteration += 1

    def get_average_strategy(self):
        """Returns the converged optimal strategy distribution."""
        normalizing_sum = np.sum(self.strategy_sum)
        if normalizing_sum > 0:
            return self.strategy_sum / normalizing_sum
        else:
            return np.ones(self.num_actions) / self.num_actions

    def regret_report(self):
        """Returns a human-readable regret summary per action."""
        avg = self.get_average_strategy()
        report = {}
        for i, action in enumerate(self.actions):
            report[action] = {
                "optimal_weight": round(float(avg[i]), 3),
                "cumulative_regret": round(float(self.regret_sum[i]), 2),
                "recommendation": "Primary path" if avg[i] == max(avg) else "Hedge / fallback"
            }
        return report


if __name__ == "__main__":
    # Example: Weighing "Stay in Job" vs "Start Business" over 1000 simulations
    actions = ["Stay in Job", "Start Business"]
    cfr = CounterfactualRegretMinimizer(actions)

    for _ in range(1000):
        u_stay   = np.random.normal(5, 1)   # Stable, low variance
        u_start  = np.random.normal(6, 4)   # Higher EV, high variance
        cfr.update([u_stay, u_start])

    print("=== CFR Life Strategy Analysis ===")
    print(f"Iterations: {cfr.iteration}")
    print()
    for action, data in cfr.regret_report().items():
        print(f"  {action}:")
        print(f"    Optimal weight   : {data['optimal_weight']:.1%}")
        print(f"    Cumulative regret: {data['cumulative_regret']}")
        print(f"    Verdict          : {data['recommendation']}")


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal:  | SkillSpector: suspicious (CRITICAL)