# Weave Integration for Strategic Memory

**Document Version:** 1.0.0 **Game Mode:** The Veil War (Mode 1) **Design
Date:** December 2024 **Status:** Initial Design

---

## Overview

The Weave Integration for Strategic Memory transforms The Veil War from a purely
tactical experience into a narrative-rich strategic game where past actions have
lasting consequences. The system tracks alliances, betrayals, trust, and
dramatic events, generating emergent stories that influence future gameplay.

**Design Principles:**

1. **Memory Matters:** Past actions create lasting consequences that affect
   future options
2. **Trust is Currency:** Diplomatic relationships are mechanically meaningful
3. **Emergent Narrative:** Stories emerge from player interactions, not
   predetermined scripts
4. **Dramatic Beats:** The system identifies and highlights dramatic moments
5. **Redemption Possible:** Even betrayers can rebuild trust, but at significant
   cost

**Research Sources:**

- Diplomacy game's trust/betrayal mechanics
- Crusader Kings emergent dynasty narratives
- Left 4 Dead's Director system for procedural pacing
- Academic research on procedural narrative generation
- Game theory analysis of trust in iterated games

---

## 1. Treachery Thread System

_"The Weave remembers every broken oath. Trust, once shattered, leaves scars
that time alone cannot heal."_

The Treachery Thread system tracks alliances and betrayals, creating lasting
narrative consequences and mechanical effects.

### 1.1 Alliance Formation Tracking

**Alliance Types:**

| Alliance Type      | Strength | Duration         | Breaking Cost | Benefits                  |
| ------------------ | -------- | ---------------- | ------------- | ------------------------- |
| Non-Aggression     | 1        | 3 turns minimum  | Low           | Cannot attack each other  |
| Trade Pact         | 2        | 5 turns minimum  | Medium        | Resource exchange bonuses |
| Defensive Alliance | 3        | 8 turns minimum  | High          | Must aid if attacked      |
| Offensive Alliance | 4        | 10 turns minimum | Very High     | Joint war declaration     |
| Blood Oath         | 5        | Permanent        | Catastrophic  | Shared victory possible   |

```typescript
interface Alliance {
  id: AllianceId;
  type: AllianceType;
  participants: PlayerId[];

  // Formation
  formedTurn: number;
  proposer: PlayerId;
  accepter: PlayerId;

  // Terms
  terms: AllianceTerm[];
  minimumDuration: number;
  canBeExtended: boolean;

  // State
  status: 'active' | 'strained' | 'broken' | 'expired' | 'fulfilled';
  strainLevel: number; // 0-100, broken at 100
  honoredTurns: number;

  // Weave integration
  weaveThreadId: WeaveThreadId;
  publicKnowledge: boolean;
  secretClauses: SecretClause[];
}

interface AllianceTerm {
  termType: AllianceTermType;
  description: string;
  mechanicalEffect: MechanicalEffect;
  violationSeverity: number; // 1-5, how bad breaking this is
}

type AllianceTermType =
  | 'non_aggression'
  | 'military_access'
  | 'trade_rights'
  | 'defensive_commitment'
  | 'offensive_commitment'
  | 'tribute_payment'
  | 'territory_guarantee'
  | 'information_sharing'
  | 'joint_victory';

function formAlliance(
  proposal: AllianceProposal,
  gameState: GameState
): AllianceFormationResult {
  const { proposer, accepter, type, terms } = proposal;

  // Validate proposal
  const validation = validateAllianceProposal(proposal, gameState);
  if (!validation.valid) {
    return { success: false, reason: validation.reason };
  }

  // Check existing relationships
  const existingRelation = getRelationship(proposer, accepter, gameState);
  if (existingRelation.treacheryLevel > 50) {
    // High treachery makes alliances harder
    return {
      success: false,
      reason: `Trust too low (Treachery: ${existingRelation.treacheryLevel})`,
      trustRequirement: 50 - existingRelation.treacheryLevel,
    };
  }

  // Create alliance
  const alliance: Alliance = {
    id: generateAllianceId(),
    type,
    participants: [proposer, accepter],
    formedTurn: gameState.currentTurn,
    proposer,
    accepter,
    terms,
    minimumDuration: getAllianceMinDuration(type),
    canBeExtended: true,
    status: 'active',
    strainLevel: 0,
    honoredTurns: 0,
    weaveThreadId: null as any,
    publicKnowledge: type !== 'secret_pact',
    secretClauses: [],
  };

  // Create Weave thread
  const thread = createAllianceWeaveThread(alliance, gameState);
  alliance.weaveThreadId = thread.id;

  // Add to game state
  gameState.alliances.set(alliance.id, alliance);

  // Notify players
  broadcastAllianceFormation(alliance, gameState);

  return {
    success: true,
    alliance,
    weaveThread: thread,
    trustGained: calculateTrustGain(type),
  };
}

function getAllianceMinDuration(type: AllianceType): number {
  const durations: Record<AllianceType, number> = {
    non_aggression: 3,
    trade_pact: 5,
    defensive_alliance: 8,
    offensive_alliance: 10,
    blood_oath: Infinity,
  };
  return durations[type];
}
```

### 1.2 Betrayal Detection and Recording

**Betrayal Types:**

| Betrayal Type           | Severity         | Detection | Treachery Cost |
| ----------------------- | ---------------- | --------- | -------------- |
| Breaking Non-Aggression | Minor (1)        | Automatic | +20            |
| Trade Violation         | Minor (1)        | Moderate  | +15            |
| Refusing Aid            | Moderate (2)     | Automatic | +30            |
| Abandoning Ally         | Severe (3)       | Automatic | +50            |
| Stabbing Active Ally    | Critical (4)     | Automatic | +75            |
| Blood Oath Betrayal     | Catastrophic (5) | Automatic | +100           |

```typescript
interface Betrayal {
  id: BetrayalId;
  betrayer: PlayerId;
  victim: PlayerId;
  allianceId: AllianceId;

  // Classification
  type: BetrayalType;
  severity: number; // 1-5
  circumstances: string;

  // Detection
  turn: number;
  detectedImmediately: boolean;
  publicKnowledge: boolean;
  witnesses: PlayerId[];

  // Consequences
  treacheryCost: number;
  mechanicalPenalties: MechanicalPenalty[];
  weaveConsequences: WeaveConsequence[];

  // Resolution
  acknowledged: boolean;
  restitutionOffered: boolean;
  restitutionAccepted: boolean;
}

type BetrayalType =
  | 'pact_breaking' // Broke alliance before minimum duration
  | 'backstab' // Attacked ally
  | 'abandonment' // Failed to honor defensive commitment
  | 'sabotage' // Secret action against ally
  | 'information_leak' // Shared secrets with enemies
  | 'territory_seizure' // Took ally's territory
  | 'economic_exploitation' // Trade fraud
  | 'assassination_attempt'; // Targeted ally's commander

function detectBetrayal(
  action: PlayerAction,
  gameState: GameState
): BetrayalDetectionResult {
  const actor = action.player;

  // Check if action violates any alliance terms
  for (const alliance of getPlayerAlliances(actor, gameState)) {
    if (alliance.status !== 'active') continue;

    const violation = checkAllianceViolation(action, alliance, gameState);
    if (violation.isViolation) {
      const betrayal = recordBetrayal(
        {
          betrayer: actor,
          victim: getOtherAllianceParticipant(alliance, actor),
          allianceId: alliance.id,
          type: violation.betrayalType,
          severity: violation.severity,
          circumstances: violation.description,
          turn: gameState.currentTurn,
          detectedImmediately: violation.obviousBetyal,
          publicKnowledge: violation.obviousBetyal || alliance.publicKnowledge,
          witnesses: violation.witnesses,
        },
        gameState
      );

      return {
        detected: true,
        betrayal,
        allianceBroken: violation.breakAlliance,
      };
    }
  }

  return { detected: false };
}

function checkAllianceViolation(
  action: PlayerAction,
  alliance: Alliance,
  gameState: GameState
): ViolationCheck {
  const ally = getOtherAllianceParticipant(alliance, action.player);

  // Check for direct attacks
  if (action.type === 'attack' && action.target === ally) {
    return {
      isViolation: true,
      betrayalType: 'backstab',
      severity: alliance.type === 'blood_oath' ? 5 : 4,
      description: `Attacked allied player ${ally} while in ${alliance.type}`,
      obviousBetyal: true,
      witnesses: getAllPlayersExcept([action.player], gameState),
      breakAlliance: true,
    };
  }

  // Check for defensive commitment failures
  if (action.type === 'pass' || action.type === 'defend_self') {
    if (alliance.terms.some((t) => t.termType === 'defensive_commitment')) {
      const allyUnderAttack = isPlayerUnderAttack(ally, gameState);
      if (allyUnderAttack) {
        return {
          isViolation: true,
          betrayalType: 'abandonment',
          severity: 3,
          description: `Failed to honor defensive commitment while ${ally} was attacked`,
          obviousBetyal: true,
          witnesses: [ally],
          breakAlliance: false, // Strains but doesn't immediately break
        };
      }
    }
  }

  // Check for territory seizure
  if (action.type === 'capture_territory') {
    const territory = gameState.territories.get(action.territoryId)!;
    if (territory.material.controller === ally) {
      return {
        isViolation: true,
        betrayalType: 'territory_seizure',
        severity: 4,
        description: `Seized allied territory ${action.territoryId}`,
        obviousBetyal: true,
        witnesses: getAllPlayersExcept([action.player], gameState),
        breakAlliance: true,
      };
    }
  }

  // Check for early pact breaking
  if (action.type === 'break_alliance' && action.allianceId === alliance.id) {
    const turnsHonored = gameState.currentTurn - alliance.formedTurn;
    if (turnsHonored < alliance.minimumDuration) {
      return {
        isViolation: true,
        betrayalType: 'pact_breaking',
        severity: getSeverityForPactBreaking(alliance.type),
        description: `Broke ${alliance.type} after only ${turnsHonored} turns`,
        obviousBetyal: true,
        witnesses: [ally],
        breakAlliance: true,
      };
    }
  }

  return { isViolation: false };
}

function recordBetrayal(
  betrayalData: Partial<Betrayal>,
  gameState: GameState
): Betrayal {
  const betrayal: Betrayal = {
    id: generateBetrayalId(),
    ...betrayalData,
    treacheryCost: calculateTreacheryCost(
      betrayalData.type!,
      betrayalData.severity!
    ),
    mechanicalPenalties: generateMechanicalPenalties(betrayalData),
    weaveConsequences: [],
    acknowledged: false,
    restitutionOffered: false,
    restitutionAccepted: false,
  } as Betrayal;

  // Apply treachery to betrayer
  applyTreachery(
    betrayal.betrayer,
    betrayal.victim,
    betrayal.treacheryCost,
    gameState
  );

  // Create Weave consequences
  betrayal.weaveConsequences = generateBetrayalWeaveConsequences(
    betrayal,
    gameState
  );

  // Store betrayal
  gameState.betrayals.push(betrayal);

  // Update Weave
  recordBetrayalInWeave(betrayal, gameState.weave);

  return betrayal;
}
```

### 1.3 Treachery Cost Scaling for Future Alliances

The more betrayals a player commits, the harder and more expensive future
alliances become.

```typescript
interface TreacheryRecord {
  player: PlayerId;

  // Current treachery level
  treacheryLevel: number; // 0-100

  // History
  betrayalsCommitted: BetrayalId[];
  betrayalsSuffered: BetrayalId[];

  // Decay tracking
  lastBetrayalTurn: number;
  turnsOfGoodBehavior: number;

  // Faction knowledge
  knownByFactions: Map<PlayerId, TreacheryKnowledge>;
}

interface TreacheryKnowledge {
  knowsOf: BetrayalId[];
  perceivedTreachery: number; // May differ from actual
  trustModifier: number; // How this affects alliance formation
}

function calculateAllianceDifficulty(
  proposer: PlayerId,
  target: PlayerId,
  allianceType: AllianceType,
  gameState: GameState
): AllianceDifficulty {
  const proposerRecord = getTreacheryRecord(proposer, gameState);
  const targetRecord = getTreacheryRecord(target, gameState);

  // Base difficulty from alliance type
  let difficulty = getBaseAllianceDifficulty(allianceType);

  // Add proposer's treachery (known to target)
  const knownTreachery =
    targetRecord.knownByFactions.get(proposer)?.perceivedTreachery ?? 0;
  difficulty += knownTreachery * 0.5;

  // If proposer has betrayed THIS target before, massive penalty
  const priorBetrayals = proposerRecord.betrayalsCommitted.filter(
    (bId) => gameState.betrayals.find((b) => b.id === bId)?.victim === target
  );
  difficulty += priorBetrayals.length * 30;

  // Recent betrayals (any target) add extra difficulty
  const recentBetrayals = proposerRecord.betrayalsCommitted.filter((bId) => {
    const betrayal = gameState.betrayals.find((b) => b.id === bId)!;
    return gameState.currentTurn - betrayal.turn <= 10;
  });
  difficulty += recentBetrayals.length * 10;

  // Good behavior reduces difficulty
  if (proposerRecord.turnsOfGoodBehavior >= 5) {
    difficulty -= Math.min(20, proposerRecord.turnsOfGoodBehavior * 2);
  }

  return {
    baseDifficulty: getBaseAllianceDifficulty(allianceType),
    treacheryPenalty: knownTreachery * 0.5,
    priorBetrayalPenalty: priorBetrayals.length * 30,
    recentBetrayalPenalty: recentBetrayals.length * 10,
    goodBehaviorBonus: Math.min(20, proposerRecord.turnsOfGoodBehavior * 2),
    totalDifficulty: Math.max(0, difficulty),
    canAttempt: difficulty < 100,
    specialRequirements:
      difficulty >= 50
        ? [
            'Must offer significant concessions',
            'Requires third-party guarantor',
          ]
        : [],
  };
}

function getBaseAllianceDifficulty(type: AllianceType): number {
  const difficulties: Record<AllianceType, number> = {
    non_aggression: 10,
    trade_pact: 15,
    defensive_alliance: 25,
    offensive_alliance: 35,
    blood_oath: 50,
  };
  return difficulties[type];
}
```

### 1.4 Redemption Mechanics

Players can work to reduce their treachery level and rebuild trust.

```typescript
interface RedemptionPath {
  player: PlayerId;
  targetReduction: number;
  method: RedemptionMethod;

  // Progress
  started: number;
  progress: number; // 0-100
  turnsRequired: number;

  // Requirements
  requirements: RedemptionRequirement[];
  currentlyMeeting: boolean;
}

type RedemptionMethod =
  | 'time_and_honor' // Keep alliances, don't betray (slow)
  | 'restitution' // Pay compensation to victims
  | 'public_penance' // Declare betrayal, accept shame
  | 'heroic_deed' // Major positive Weave action
  | 'alliance_fulfilled' // Complete a difficult alliance successfully
  | 'victim_forgiveness'; // Victim explicitly forgives

const REDEMPTION_RATES: Record<RedemptionMethod, number> = {
  time_and_honor: 2, // -2 treachery per turn
  restitution: 5, // -5 per payment accepted
  public_penance: 10, // -10 once (but reputation hit)
  heroic_deed: 15, // -15 per deed
  alliance_fulfilled: 20, // -20 per successful alliance
  victim_forgiveness: 25, // -25 per forgiveness
};

function progressRedemption(
  player: PlayerId,
  gameState: GameState
): RedemptionProgressResult {
  const record = getTreacheryRecord(player, gameState);
  const activePaths = getActiveRedemptionPaths(player, gameState);
  const results: RedemptionProgressResult[] = [];

  for (const path of activePaths) {
    // Check if still meeting requirements
    const meetingRequirements = checkRedemptionRequirements(path, gameState);
    path.currentlyMeeting = meetingRequirements.all;

    if (!meetingRequirements.all) {
      // Path paused or reset
      results.push({
        path,
        progress: 'paused',
        reason: meetingRequirements.failedRequirement,
      });
      continue;
    }

    // Apply progress
    const reduction = REDEMPTION_RATES[path.method];
    record.treacheryLevel = Math.max(0, record.treacheryLevel - reduction);
    path.progress += 100 / path.turnsRequired;

    // Check for completion
    if (path.progress >= 100) {
      results.push({
        path,
        progress: 'complete',
        treacheryReduced: path.targetReduction,
      });

      // Record in Weave
      recordRedemptionInWeave(player, path, gameState.weave);
    } else {
      results.push({
        path,
        progress: 'ongoing',
        currentTreachery: record.treacheryLevel,
      });
    }
  }

  // Passive decay (very slow)
  if (record.turnsOfGoodBehavior >= 10) {
    record.treacheryLevel = Math.max(0, record.treacheryLevel - 1);
  }

  return { results, newTreacheryLevel: record.treacheryLevel };
}

function requestVictimForgiveness(
  betrayer: PlayerId,
  victim: PlayerId,
  betrayalId: BetrayalId,
  offering: ForgivenessOffering,
  gameState: GameState
): ForgivenessResult {
  const betrayal = gameState.betrayals.find((b) => b.id === betrayalId)!;

  // Verify this is the right betrayal
  if (betrayal.betrayer !== betrayer || betrayal.victim !== victim) {
    return { success: false, reason: 'Invalid betrayal reference' };
  }

  // Check if already forgiven
  if (betrayal.restitutionAccepted) {
    return { success: false, reason: 'Already forgiven' };
  }

  // Calculate forgiveness likelihood based on offering
  const offeringValue = calculateOfferingValue(offering, victim, gameState);
  const betrayalSeverity = betrayal.severity * 20; // 20-100

  // AI/automated decision (for NPC or suggestion to player)
  const forgivenessLikelihood = Math.min(
    100,
    (offeringValue / betrayalSeverity) * 100
  );

  // If victim is a player, this becomes a choice prompt
  // If AI-controlled, use likelihood
  if (isAIControlled(victim, gameState)) {
    const forgives = Math.random() * 100 < forgivenessLikelihood;

    if (forgives) {
      betrayal.restitutionAccepted = true;
      applyForgiveness(betrayer, victim, betrayal, gameState);

      return {
        success: true,
        forgiven: true,
        treacheryReduction: REDEMPTION_RATES.victim_forgiveness,
      };
    }

    return {
      success: true,
      forgiven: false,
      reason: 'Offering insufficient for the betrayal',
    };
  }

  // For player victims, create forgiveness prompt
  return {
    success: true,
    pendingPlayerDecision: true,
    forgivenessPrompt: createForgivenessPrompt(
      betrayer,
      victim,
      betrayal,
      offering
    ),
  };
}
```

---

## 2. Trust Node System

_"Pacts are the threads that bind factions together. Honor them, and they grow
strong. Break them, and they unravel catastrophically."_

The Trust Node system creates Weave nodes representing diplomatic relationships
that generate mechanical bonuses over time.

### 2.1 Pact Formation and Tracking

```typescript
interface TrustNode {
  id: TrustNodeId;
  weaveNodeId: WeaveNodeId;

  // Participants
  parties: PlayerId[];
  initiator: PlayerId;

  // Trust levels
  trustLevel: number; // 0-100
  maxTrustAchieved: number; // Highest ever reached
  trustHistory: TrustHistoryEntry[];

  // Pact details
  pactType: PactType;
  formedTurn: number;
  lastTestedTurn: number | null;

  // Bonuses
  currentBonuses: TrustBonus[];
  unlockedTiers: number; // 0-5

  // Invocation tracking
  aidInvocations: AidInvocation[];
  invocationsRemaining: number;
}

interface TrustHistoryEntry {
  turn: number;
  trustChange: number;
  reason: string;
  eventId: string | null;
}

type PactType =
  | 'mutual_defense'
  | 'shared_prosperity'
  | 'knowledge_exchange'
  | 'blood_bond'
  | 'eternal_alliance';

const TRUST_TIER_THRESHOLDS = [0, 20, 40, 60, 80, 100];
const TRUST_TIER_BONUSES: TrustTierBonus[][] = [
  // Tier 0 (0-19): Basic
  [{ type: 'no_betrayal_suspicion', value: 0 }],
  // Tier 1 (20-39): Cooperation
  [
    { type: 'trade_bonus', value: 10 },
    { type: 'shared_vision_radius', value: 2 },
  ],
  // Tier 2 (40-59): Partnership
  [
    { type: 'military_access', value: 1 },
    { type: 'shared_ley_line_bonus', value: 5 },
  ],
  // Tier 3 (60-79): Deep Trust
  [
    { type: 'emergency_aid_available', value: 1 },
    { type: 'joint_ritual_bonus', value: 10 },
  ],
  // Tier 4 (80-99): Unshakeable Bond
  [
    { type: 'combined_weave_score', value: 0.5 },
    { type: 'morale_bonus_adjacent', value: 15 },
  ],
  // Tier 5 (100): Perfect Trust
  [
    { type: 'shared_victory_eligible', value: 1 },
    { type: 'legendary_unit_access', value: 1 },
  ],
];

function createTrustNode(
  parties: PlayerId[],
  pactType: PactType,
  gameState: GameState
): TrustNode {
  // Calculate initial trust based on history
  const initialTrust = calculateInitialTrust(parties, gameState);

  const trustNode: TrustNode = {
    id: generateTrustNodeId(),
    weaveNodeId: null as any,
    parties,
    initiator: parties[0],
    trustLevel: initialTrust,
    maxTrustAchieved: initialTrust,
    trustHistory: [
      {
        turn: gameState.currentTurn,
        trustChange: initialTrust,
        reason: 'Pact formation',
        eventId: null,
      },
    ],
    pactType,
    formedTurn: gameState.currentTurn,
    lastTestedTurn: null,
    currentBonuses: [],
    unlockedTiers: getTierFromTrust(initialTrust),
    aidInvocations: [],
    invocationsRemaining:
      pactType === 'blood_bond'
        ? 3
        : pactType === 'eternal_alliance'
          ? Infinity
          : 1,
  };

  // Create Weave node
  const weaveNode = createTrustWeaveNode(trustNode, gameState);
  trustNode.weaveNodeId = weaveNode.id;

  // Apply initial bonuses
  trustNode.currentBonuses = calculateTrustBonuses(trustNode);

  // Store
  gameState.trustNodes.set(trustNode.id, trustNode);

  return trustNode;
}

function calculateInitialTrust(
  parties: PlayerId[],
  gameState: GameState
): number {
  let baseTrust = 20; // Starting point

  // Check for prior positive history
  const [p1, p2] = parties;
  const sharedHistory = getSharedHistory(p1, p2, gameState);

  // Prior successful alliances
  baseTrust += sharedHistory.successfulAlliances * 10;

  // Prior betrayals (by either party)
  baseTrust -= sharedHistory.betrayalsByP1 * 15;
  baseTrust -= sharedHistory.betrayalsByP2 * 15;

  // Joint victories
  baseTrust += sharedHistory.jointBattlesWon * 5;

  // Faction affinity
  const factionAffinity = getFactionAffinity(
    getPlayerFaction(p1, gameState),
    getPlayerFaction(p2, gameState)
  );
  baseTrust += factionAffinity * 5;

  return Math.max(0, Math.min(50, baseTrust)); // Cap initial at 50
}
```

### 2.2 Honor Accumulation Over Time

Trust grows through honored commitments and positive interactions.

```typescript
interface TrustGrowthEvent {
  type: TrustGrowthType;
  trustGain: number;
  description: string;
}

type TrustGrowthType =
  | 'turn_in_alliance' // +1 per turn
  | 'joint_combat_victory' // +3 per battle
  | 'aid_provided' // +5 when helping
  | 'shared_enemy_defeated' // +10 when jointly winning
  | 'pact_term_honored' // +2 per honored term
  | 'information_shared' // +2 per valuable intel
  | 'resource_gift' // +variable based on value
  | 'territory_returned' // +8 if returned contested territory
  | 'legendary_deed_witnessed'; // +5 if ally performed heroic deed

function updateTrustLevels(gameState: GameState): void {
  for (const trustNode of gameState.trustNodes.values()) {
    if (!isActiveNode(trustNode, gameState)) continue;

    const events: TrustGrowthEvent[] = [];

    // Base growth for maintained alliance
    events.push({
      type: 'turn_in_alliance',
      trustGain: 1,
      description: 'Alliance maintained',
    });

    // Check for joint combat this turn
    const jointCombats = getJointCombatsThisTurn(trustNode.parties, gameState);
    for (const combat of jointCombats) {
      if (combat.won) {
        events.push({
          type: 'joint_combat_victory',
          trustGain: 3,
          description: `Joint victory at ${combat.location}`,
        });
      }
    }

    // Check if aid was provided
    const aidEvents = getAidEventsThisTurn(trustNode.parties, gameState);
    for (const aid of aidEvents) {
      events.push({
        type: 'aid_provided',
        trustGain: 5,
        description: `${aid.helper} aided ${aid.receiver}`,
      });
    }

    // Check for shared enemy defeat
    const sharedEnemyDefeats = getSharedEnemyDefeats(
      trustNode.parties,
      gameState
    );
    for (const defeat of sharedEnemyDefeats) {
      events.push({
        type: 'shared_enemy_defeated',
        trustGain: 10,
        description: `Jointly defeated ${defeat.enemy}`,
      });
    }

    // Apply trust changes
    let totalChange = events.reduce((sum, e) => sum + e.trustGain, 0);

    // Cap growth per turn
    totalChange = Math.min(5, totalChange);

    // Apply
    trustNode.trustLevel = Math.min(100, trustNode.trustLevel + totalChange);
    trustNode.maxTrustAchieved = Math.max(
      trustNode.maxTrustAchieved,
      trustNode.trustLevel
    );

    // Record history
    trustNode.trustHistory.push({
      turn: gameState.currentTurn,
      trustChange: totalChange,
      reason: events.map((e) => e.description).join(', '),
      eventId: null,
    });

    // Check for tier unlock
    const newTier = getTierFromTrust(trustNode.trustLevel);
    if (newTier > trustNode.unlockedTiers) {
      trustNode.unlockedTiers = newTier;
      trustNode.currentBonuses = calculateTrustBonuses(trustNode);

      // Notify players
      notifyTrustTierUnlock(trustNode, newTier, gameState);
    }
  }
}

function getTierFromTrust(trust: number): number {
  for (let i = TRUST_TIER_THRESHOLDS.length - 1; i >= 0; i--) {
    if (trust >= TRUST_TIER_THRESHOLDS[i]) {
      return i;
    }
  }
  return 0;
}
```

### 2.3 Emergency Aid Invocation Mechanics

High-trust relationships unlock the ability to call for emergency aid.

```typescript
interface AidInvocation {
  id: AidInvocationId;
  invoker: PlayerId;
  respondent: PlayerId;
  trustNodeId: TrustNodeId;

  // Request
  aidType: AidType;
  urgency: 'low' | 'medium' | 'high' | 'desperate';
  requestedResources: ResourceRequest[];
  requestedAction: ActionRequest | null;

  // Response
  status: 'pending' | 'accepted' | 'refused' | 'partial' | 'expired';
  response: AidResponse | null;
  responseDeadline: number;

  // Consequences
  trustImpact: number;
  weaveConsequence: WeaveConsequence | null;
}

type AidType =
  | 'military_intervention' // Send troops
  | 'resource_emergency' // Send resources
  | 'intelligence' // Share critical info
  | 'diplomatic_support' // Back in negotiations
  | 'ritual_assistance'; // Help with ritual

interface AidResponse {
  accepted: boolean;
  providedResources: ResourceProvision[];
  providedActions: ActionProvision[];
  conditions: AidCondition[];
  explanation: string;
}

function invokeEmergencyAid(
  invoker: PlayerId,
  trustNodeId: TrustNodeId,
  aidType: AidType,
  details: AidDetails,
  gameState: GameState
): AidInvocationResult {
  const trustNode = gameState.trustNodes.get(trustNodeId)!;

  // Verify invocation is valid
  if (!trustNode.parties.includes(invoker)) {
    return { success: false, reason: 'Not a party to this pact' };
  }

  if (trustNode.invocationsRemaining <= 0) {
    return { success: false, reason: 'No invocations remaining' };
  }

  if (trustNode.trustLevel < 60) {
    return {
      success: false,
      reason: 'Trust level below 60 (required for aid invocation)',
    };
  }

  const respondent = trustNode.parties.find((p) => p !== invoker)!;

  // Create invocation
  const invocation: AidInvocation = {
    id: generateAidInvocationId(),
    invoker,
    respondent,
    trustNodeId,
    aidType,
    urgency: details.urgency,
    requestedResources: details.resources ?? [],
    requestedAction: details.action ?? null,
    status: 'pending',
    response: null,
    responseDeadline: gameState.currentTurn + 2, // 2 turns to respond
    trustImpact: 0,
    weaveConsequence: null,
  };

  // Use an invocation
  trustNode.invocationsRemaining--;
  trustNode.aidInvocations.push(invocation);

  // If respondent is AI, resolve immediately
  if (isAIControlled(respondent, gameState)) {
    const aiResponse = generateAIAidResponse(invocation, trustNode, gameState);
    resolveAidInvocation(invocation, aiResponse, gameState);
  }

  return {
    success: true,
    invocation,
    invocationsRemaining: trustNode.invocationsRemaining,
  };
}

function resolveAidInvocation(
  invocation: AidInvocation,
  response: AidResponse,
  gameState: GameState
): AidResolutionResult {
  invocation.response = response;
  const trustNode = gameState.trustNodes.get(invocation.trustNodeId)!;

  if (response.accepted) {
    invocation.status = 'accepted';

    // Provide resources
    for (const provision of response.providedResources) {
      transferResource(
        invocation.respondent,
        invocation.invoker,
        provision.type,
        provision.amount,
        gameState
      );
    }

    // Execute actions
    for (const actionProvision of response.providedActions) {
      executeAidAction(invocation.respondent, actionProvision, gameState);
    }

    // Trust boost
    invocation.trustImpact = 10;
    trustNode.trustLevel = Math.min(100, trustNode.trustLevel + 10);

    // Weave entry
    invocation.weaveConsequence = recordAidHonoredInWeave(
      invocation,
      gameState
    );

    return {
      success: true,
      resourcesTransferred: response.providedResources,
      actionsExecuted: response.providedActions,
      trustGained: 10,
    };
  } else {
    invocation.status = 'refused';

    // Trust damage
    invocation.trustImpact = -20;
    trustNode.trustLevel = Math.max(0, trustNode.trustLevel - 20);

    // This may trigger betrayal detection
    if (invocation.urgency === 'desperate') {
      detectBetrayal(
        {
          type: 'refuse_aid',
          player: invocation.respondent,
          target: invocation.invoker,
          context: invocation,
        } as any,
        gameState
      );
    }

    // Weave entry
    invocation.weaveConsequence = recordAidRefusedInWeave(
      invocation,
      gameState
    );

    return {
      success: false,
      reason: response.explanation,
      trustLost: 20,
    };
  }
}
```

### 2.4 Trust Decay and Maintenance

Trust naturally decays if not maintained through active cooperation.

```typescript
interface TrustDecayConfig {
  // Passive decay
  decayPerTurnWithoutContact: number; // -1
  decayPerTurnWithDistantContact: number; // -0.5

  // Active decay triggers
  decayPerRefusedTrade: number; // -2
  decayPerMissedOpportunity: number; // -1
  decayPerHostileNeighborAction: number; // -3

  // Decay protection
  bloodBondDecayImmunity: boolean;
  minimumTrustBeforeDecay: number; // 20
}

const DEFAULT_DECAY_CONFIG: TrustDecayConfig = {
  decayPerTurnWithoutContact: 1,
  decayPerTurnWithDistantContact: 0.5,
  decayPerRefusedTrade: 2,
  decayPerMissedOpportunity: 1,
  decayPerHostileNeighborAction: 3,
  bloodBondDecayImmunity: true,
  minimumTrustBeforeDecay: 20,
};

function applyTrustDecay(gameState: GameState): void {
  const config = gameState.trustDecayConfig ?? DEFAULT_DECAY_CONFIG;

  for (const trustNode of gameState.trustNodes.values()) {
    if (!isActiveNode(trustNode, gameState)) continue;

    // Blood bonds don't decay
    if (trustNode.pactType === 'blood_bond' && config.bloodBondDecayImmunity) {
      continue;
    }

    // Don't decay below minimum
    if (trustNode.trustLevel <= config.minimumTrustBeforeDecay) {
      continue;
    }

    let totalDecay = 0;

    // Check for contact this turn
    const hadContact = checkForPositiveContact(trustNode.parties, gameState);
    if (!hadContact) {
      totalDecay += config.decayPerTurnWithoutContact;
    }

    // Check for refused trades
    const refusedTrades = countRefusedTrades(trustNode.parties, gameState);
    totalDecay += refusedTrades * config.decayPerRefusedTrade;

    // Check for hostile actions near ally
    const hostileActions = countHostileActionsNearAlly(
      trustNode.parties,
      gameState
    );
    totalDecay += hostileActions * config.decayPerHostileNeighborAction;

    // Apply decay
    if (totalDecay > 0) {
      trustNode.trustLevel = Math.max(
        config.minimumTrustBeforeDecay,
        trustNode.trustLevel - totalDecay
      );

      // Record
      trustNode.trustHistory.push({
        turn: gameState.currentTurn,
        trustChange: -totalDecay,
        reason: 'Trust decay from inactivity/negative events',
        eventId: null,
      });

      // Check for tier loss
      const currentTier = getTierFromTrust(trustNode.trustLevel);
      if (currentTier < trustNode.unlockedTiers) {
        // Don't immediately lose tier, but warn
        notifyTrustDecayWarning(trustNode, currentTier, gameState);
      }
    }
  }
}

function checkForPositiveContact(
  parties: PlayerId[],
  gameState: GameState
): boolean {
  const [p1, p2] = parties;
  const thisTurn = gameState.currentTurn;

  // Check for trades
  if (hadTradeThisTurn(p1, p2, gameState)) return true;

  // Check for shared combat
  if (hadJointCombatThisTurn(p1, p2, gameState)) return true;

  // Check for resource sharing
  if (hadResourceTransferThisTurn(p1, p2, gameState)) return true;

  // Check for diplomatic messages
  if (hadDiplomaticExchangeThisTurn(p1, p2, gameState)) return true;

  return false;
}
```

---

## 3. Weave Consequence System

_"Every action echoes through the Weave. In time, those echoes
return—transformed, amplified, and often... unexpected."_

The Weave Consequence system catalogues past actions and triggers narrative
consequences when conditions align.

### 3.1 Past Action Cataloging

```typescript
interface CataloguedAction {
  id: ActionId;
  actor: PlayerId;
  actionType: ActionType;
  turn: number;

  // Context
  targets: (PlayerId | TerritoryId | UnitId)[];
  resources: ResourceInvolvement[];
  narrativeWeight: number;

  // Classification
  moralAlignment: 'heroic' | 'neutral' | 'villainous';
  consequenceType: ConsequenceCategory[];
  witnessedBy: PlayerId[];

  // Potential consequences
  potentialConsequences: PotentialConsequence[];
  triggeredConsequences: TriggeredConsequence[];

  // Weave integration
  weaveNodeId: WeaveNodeId | null;
  relatedThreads: WeaveThreadId[];
}

type ConsequenceCategory =
  | 'karma' // What goes around comes around
  | 'reputation' // Others remember
  | 'obligation' // Created a debt
  | 'rivalry' // Made an enemy
  | 'legacy' // Long-term effects
  | 'destiny'; // Prophetic implications

interface PotentialConsequence {
  id: PotentialConsequenceId;
  category: ConsequenceCategory;
  description: string;

  // Trigger conditions
  triggerConditions: TriggerCondition[];
  minimumTurnsUntilTrigger: number;
  maximumTurnsUntilExpiry: number;

  // Effects when triggered
  effects: ConsequenceEffect[];
  narrativeDescription: string;

  // Probability
  baseProbability: number; // 0-100
  probabilityModifiers: ProbabilityModifier[];
}

function catalogueAction(
  action: PlayerAction,
  result: ActionResult,
  gameState: GameState
): CataloguedAction {
  const catalogued: CataloguedAction = {
    id: generateActionId(),
    actor: action.player,
    actionType: action.type,
    turn: gameState.currentTurn,
    targets: extractTargets(action),
    resources: extractResources(action, result),
    narrativeWeight: calculateNarrativeWeight(action, result),
    moralAlignment: classifyMoralAlignment(action, result, gameState),
    consequenceType: identifyConsequenceCategories(action, result),
    witnessedBy: identifyWitnesses(action, gameState),
    potentialConsequences: [],
    triggeredConsequences: [],
    weaveNodeId: null,
    relatedThreads: [],
  };

  // Generate potential consequences
  catalogued.potentialConsequences = generatePotentialConsequences(
    catalogued,
    gameState
  );

  // Create Weave node if significant
  if (catalogued.narrativeWeight >= 3) {
    const weaveNode = createActionWeaveNode(catalogued, gameState);
    catalogued.weaveNodeId = weaveNode.id;
  }

  // Store
  gameState.actionCatalogue.set(catalogued.id, catalogued);

  return catalogued;
}

function generatePotentialConsequences(
  action: CataloguedAction,
  gameState: GameState
): PotentialConsequence[] {
  const consequences: PotentialConsequence[] = [];

  // Karma consequences
  if (action.moralAlignment === 'villainous') {
    consequences.push({
      id: generateConsequenceId(),
      category: 'karma',
      description: 'Dark deeds invite dark returns',
      triggerConditions: [
        { type: 'actor_vulnerable', actor: action.actor },
        { type: 'random_chance', probability: 30 },
      ],
      minimumTurnsUntilTrigger: 5,
      maximumTurnsUntilExpiry: 20,
      effects: [
        { type: 'unexpected_enemy', source: 'karma' },
        { type: 'resource_loss', amount: 'moderate' },
      ],
      narrativeDescription: 'The shadows of past misdeeds materialize...',
      baseProbability: 40,
      probabilityModifiers: [],
    });
  }

  // Reputation consequences
  if (action.witnessedBy.length >= 3) {
    consequences.push({
      id: generateConsequenceId(),
      category: 'reputation',
      description: 'Word spreads of your deeds',
      triggerConditions: [
        { type: 'diplomatic_interaction', actor: action.actor },
      ],
      minimumTurnsUntilTrigger: 2,
      maximumTurnsUntilExpiry: 15,
      effects: [
        {
          type: 'diplomacy_modifier',
          modifier: action.moralAlignment === 'heroic' ? 10 : -10,
        },
      ],
      narrativeDescription:
        action.moralAlignment === 'heroic'
          ? 'Your noble reputation precedes you...'
          : 'Whispers of your ruthlessness spread...',
      baseProbability: 70,
      probabilityModifiers: [],
    });
  }

  // Rivalry consequences
  for (const target of action.targets) {
    if (typeof target === 'string' && isPlayerId(target)) {
      const hostility = calculateHostilityLevel(action, target);
      if (hostility >= 50) {
        consequences.push({
          id: generateConsequenceId(),
          category: 'rivalry',
          description: `${target} remembers your actions`,
          triggerConditions: [
            { type: 'target_gains_power', target },
            { type: 'opportunity_for_revenge', target },
          ],
          minimumTurnsUntilTrigger: 3,
          maximumTurnsUntilExpiry: 30,
          effects: [
            { type: 'rival_action', actor: target, against: action.actor },
          ],
          narrativeDescription: 'An old grudge resurfaces...',
          baseProbability: 50 + (hostility - 50),
          probabilityModifiers: [],
        });
      }
    }
  }

  return consequences;
}
```

### 3.2 Consequence Trigger Conditions

```typescript
interface TriggerCondition {
  type: TriggerConditionType;
  parameters: Record<string, any>;
}

type TriggerConditionType =
  | 'turn_elapsed' // X turns have passed
  | 'actor_vulnerable' // Original actor is weak
  | 'target_gains_power' // Target has grown strong
  | 'opportunity_for_revenge' // Specific revenge opportunity
  | 'diplomatic_interaction' // Any diplomacy attempt
  | 'random_chance' // Probability check
  | 'weave_alignment' // Weave state matches
  | 'territory_contested' // Specific territory in conflict
  | 'resource_threshold' // Resource level triggers
  | 'alliance_state'; // Alliance forms or breaks

function checkConsequenceTriggers(
  gameState: GameState
): TriggeredConsequence[] {
  const triggered: TriggeredConsequence[] = [];

  for (const action of gameState.actionCatalogue.values()) {
    for (const potential of action.potentialConsequences) {
      // Check if already triggered
      if (
        action.triggeredConsequences.some((t) => t.potentialId === potential.id)
      ) {
        continue;
      }

      // Check expiry
      const turnsElapsed = gameState.currentTurn - action.turn;
      if (turnsElapsed > potential.maximumTurnsUntilExpiry) {
        continue;
      }

      // Check minimum delay
      if (turnsElapsed < potential.minimumTurnsUntilTrigger) {
        continue;
      }

      // Check all trigger conditions
      const conditionsMet = potential.triggerConditions.every((condition) =>
        evaluateTriggerCondition(condition, action, gameState)
      );

      if (!conditionsMet) continue;

      // Roll for probability
      const probability = calculateFinalProbability(potential);
      if (Math.random() * 100 >= probability) continue;

      // Trigger the consequence!
      const triggeredConsequence = triggerConsequence(
        action,
        potential,
        gameState
      );
      triggered.push(triggeredConsequence);
      action.triggeredConsequences.push(triggeredConsequence);
    }
  }

  return triggered;
}

function evaluateTriggerCondition(
  condition: TriggerCondition,
  action: CataloguedAction,
  gameState: GameState
): boolean {
  switch (condition.type) {
    case 'turn_elapsed':
      return gameState.currentTurn - action.turn >= condition.parameters.turns;

    case 'actor_vulnerable':
      const actor = gameState.players.get(action.actor)!;
      const vulnerabilityScore = calculateVulnerability(actor, gameState);
      return vulnerabilityScore >= (condition.parameters.threshold ?? 50);

    case 'target_gains_power':
      const target = condition.parameters.target;
      const targetPower = calculatePlayerPower(target, gameState);
      const originalPower = getPlayerPowerAtTurn(
        target,
        action.turn,
        gameState
      );
      return targetPower > originalPower * 1.5; // 50% power gain

    case 'opportunity_for_revenge':
      return checkRevengeOpportunity(
        condition.parameters.target,
        action.actor,
        gameState
      );

    case 'diplomatic_interaction':
      return hadDiplomaticInteractionThisTurn(action.actor, gameState);

    case 'random_chance':
      return true; // Handled separately in probability

    case 'weave_alignment':
      return checkWeaveAlignment(
        condition.parameters.requiredState,
        gameState.weave
      );

    case 'territory_contested':
      const territory = gameState.territories.get(
        condition.parameters.territory
      );
      return territory ? isContested(territory) : false;

    case 'resource_threshold':
      const player = gameState.players.get(action.actor)!;
      const resource = player.resources.get(condition.parameters.resource) ?? 0;
      return condition.parameters.above
        ? resource > condition.parameters.threshold
        : resource < condition.parameters.threshold;

    case 'alliance_state':
      return checkAllianceState(
        action.actor,
        condition.parameters.expectedState,
        gameState
      );

    default:
      return false;
  }
}
```

### 3.3 AI/GM Consequence Generation

The system can generate narrative consequences automatically or suggest them to
the GM.

```typescript
interface ConsequenceGenerator {
  generateConsequenceNarrative(
    consequence: TriggeredConsequence,
    gameState: GameState
  ): ConsequenceNarrative;

  suggestConsequenceEffects(
    action: CataloguedAction,
    category: ConsequenceCategory,
    gameState: GameState
  ): ConsequenceEffect[];

  generateDramaticReveal(
    consequence: TriggeredConsequence,
    gameState: GameState
  ): DramaticReveal;
}

interface ConsequenceNarrative {
  title: string;
  shortDescription: string;
  fullNarrative: string;
  dramaticMoment: string;
  weaveThreadTitle: string;
}

const NARRATIVE_TEMPLATES: Record<ConsequenceCategory, NarrativeTemplate[]> = {
  karma: [
    {
      title: "${actor}'s Past Returns",
      short: 'The consequences of ${action} catch up with ${actor}.',
      full: "What was done in shadow cannot remain hidden forever. ${actor}'s ${action} has echoed through the Weave, and now that echo returns—transformed, amplified, demanding balance.",
      dramatic:
        'The veil parts, and ${actor} sees the face of their own making.',
    },
  ],
  reputation: [
    {
      title: "The Weight of ${actor}'s Name",
      short: 'Word of ${action} spreads across the realm.',
      full: "Stories travel faster than armies. The tale of ${actor}'s ${action} has reached distant courts, and now ${actor}'s very name carries the weight of that deed—for good or ill.",
      dramatic:
        '\"Ah,\" says the stranger, \"so you are ${actor}. I have heard... stories.\"',
    },
  ],
  rivalry: [
    {
      title: "${target}'s Long Memory",
      short: '${target} has not forgotten ${action}.',
      full: 'Time may dull many things, but not the edge of vengeance. ${target} has bided their time, gathered strength, and now moves against ${actor} with the patience of stone and the fury of flame.',
      dramatic:
        '${target}\'s eyes meet ${actor}\'s across the battlefield. \"You thought I had forgotten?\"',
    },
  ],
  obligation: [
    {
      title: 'The Debt Comes Due',
      short: "${actor}'s past generosity creates an unexpected ally.",
      full: "Seeds planted in kindness bear fruit in strange seasons. ${beneficiary} remembers ${actor}'s ${action}, and now returns with aid unlooked-for—the Weave repaying debts its keepers have forgotten.",
      dramatic:
        'From the shadows steps a figure ${actor} barely remembers. \"You helped me once. Now I return the favor.\"',
    },
  ],
  legacy: [
    {
      title: "Echoes of ${actor}'s Choice",
      short: 'The long-term effects of ${action} become apparent.',
      full: "Some actions reshape the world in ways their authors never intended. ${actor}'s ${action}, performed ${turns} turns ago, has rippled outward through the Weave, and now those ripples have become waves.",
      dramatic: 'The land itself seems to remember what ${actor} did here.',
    },
  ],
  destiny: [
    {
      title: 'The Prophecy Stirs',
      short: "${actor}'s ${action} aligns with ancient prophecy.",
      full: "The seers spoke of this moment, though they did not know its shape. ${actor}'s ${action} has fulfilled a fragment of the great prophecy, and the Weave itself trembles with recognition.",
      dramatic:
        'The Oracle\'s eyes widen. \"It is as was foretold. ${actor} has become... inevitable.\"',
    },
  ],
};

function generateConsequenceNarrative(
  consequence: TriggeredConsequence,
  gameState: GameState
): ConsequenceNarrative {
  const action = gameState.actionCatalogue.get(consequence.sourceActionId)!;
  const templates = NARRATIVE_TEMPLATES[consequence.category];
  const template = templates[Math.floor(Math.random() * templates.length)];

  // Replace placeholders
  const context = {
    actor: getPlayerName(action.actor, gameState),
    action: describeAction(action),
    target: action.targets[0]
      ? describeTarget(action.targets[0], gameState)
      : 'the realm',
    turns: gameState.currentTurn - action.turn,
    beneficiary: consequence.effects[0]?.beneficiary
      ? getPlayerName(consequence.effects[0].beneficiary, gameState)
      : 'an unexpected ally',
  };

  return {
    title: fillTemplate(template.title, context),
    shortDescription: fillTemplate(template.short, context),
    fullNarrative: fillTemplate(template.full, context),
    dramaticMoment: fillTemplate(template.dramatic, context),
    weaveThreadTitle: fillTemplate(template.title, context),
  };
}
```

### 3.4 Player Notification of Emerging Consequences

```typescript
interface ConsequenceWarning {
  id: WarningId;
  player: PlayerId;
  warningLevel: 'distant' | 'approaching' | 'imminent';

  // Source
  relatedAction: ActionId | null;
  category: ConsequenceCategory;

  // Warning content
  crypticHint: string;
  clearer Hint: string;  // Revealed if player has high Clarity/Void

  // Timing
  estimatedTurnsUntilTrigger: number | null;
  canBeAverted: boolean;
  avertionHint: string | null;
}

function generateConsequenceWarnings(
  player: PlayerId,
  gameState: GameState
): ConsequenceWarning[] {
  const warnings: ConsequenceWarning[] = [];
  const playerClarity = getPlayerResonance(player, 'clarity', gameState);
  const playerVoid = getPlayerResonance(player, 'void', gameState);

  // Check all catalogued actions for this player
  for (const action of gameState.actionCatalogue.values()) {
    if (action.actor !== player) continue;

    for (const potential of action.potentialConsequences) {
      // Skip already triggered
      if (action.triggeredConsequences.some(t => t.potentialId === potential.id)) {
        continue;
      }

      const turnsElapsed = gameState.currentTurn - action.turn;
      const turnsUntilExpiry = potential.maximumTurnsUntilExpiry - turnsElapsed;

      // Calculate how close to triggering
      const conditionProgress = calculateConditionProgress(
        potential.triggerConditions,
        action,
        gameState
      );

      // Determine warning level
      let warningLevel: 'distant' | 'approaching' | 'imminent';
      if (conditionProgress >= 80) {
        warningLevel = 'imminent';
      } else if (conditionProgress >= 50) {
        warningLevel = 'approaching';
      } else if (conditionProgress >= 30) {
        warningLevel = 'distant';
      } else {
        continue;  // Too distant to warn
      }

      // Generate warning
      const warning: ConsequenceWarning = {
        id: generateWarningId(),
        player,
        warningLevel,
        relatedAction: action.id,
        category: potential.category,
        crypticHint: generateCrypticHint(potential),
        clearerHint: playerClarity >= 7 || playerVoid >= 6
          ? generateClearerHint(potential, action)
          : null,
        estimatedTurnsUntilTrigger: warningLevel === 'imminent'
          ? Math.floor(Math.random() * 3) + 1
          : null,
        canBeAverted: checkIfAvertable(potential, gameState),
        avertionHint: checkIfAvertable(potential, gameState)
          ? generateAvertionHint(potential)
          : null
      };

      warnings.push(warning);
    }
  }

  return warnings;
}

function generateCrypticHint(potential: PotentialConsequence): string {
  const hints: Record<ConsequenceCategory, string[]> = {
    karma: [
      'The scales shift in darkness...',
      'What was given shall be taken...',
      'Balance approaches on silent feet...'
    ],
    reputation: [
      'Whispers carry further than shouts...',
      'Your name echoes in distant halls...',
      'The world has not forgotten...'
    ],
    rivalry: [
      'Old eyes watch from the shadows...',
      'A grudge grows in fertile ground...',
      'Patience is a hunter\'s virtue...'
    ],
    obligation: [
      'Seeds long planted begin to sprout...',
      'The wheel of debt turns slowly...',
      'What was owed shall be repaid...'
    ],
    legacy: [
      'The ripples spread ever outward...',
      'Time transforms all actions...',
      'The future remembers the past...'
    ],
    destiny: [
      'The threads tighten...',
      'Prophecy stirs in its sleep...',
      'The pattern reveals itself...'
    ]
  };

  const categoryHints = hints[potential.category];
  return categoryHints[Math.floor(Math.random() * categoryHints.length)];
}
```

---

## 4. Narrative Event Generation from Weave State

_"The Weave is not passive. It watches, it waits, and when the moment is right,
it speaks."_

The narrative event generation system analyzes Weave state to identify dramatic
moments and generate story beats.

### 4.1 Tension Point Detection

```typescript
interface TensionPoint {
  id: TensionPointId;
  type: TensionType;
  intensity: number; // 1-10

  // Participants
  primaryActors: PlayerId[];
  secondaryActors: PlayerId[];
  affectedTerritories: TerritoryId[];

  // Weave elements
  relatedThreads: WeaveThreadId[];
  relatedNodes: WeaveNodeId[];

  // Timing
  buildupTurns: number;
  peakExpectedTurn: number | null;

  // Potential outcomes
  possibleResolutions: Resolution[];
  mostLikelyResolution: Resolution;

  // Narrative hooks
  dramaticQuestions: string[];
  foreshadowingElements: string[];
}

type TensionType =
  | 'military_standoff' // Armies facing off
  | 'betrayal_brewing' // Alliance about to break
  | 'revenge_imminent' // Revenge about to be taken
  | 'prophecy_convergence' // Multiple prophecies aligning
  | 'power_vacuum' // Major player eliminated
  | 'resource_crisis' // Scarcity driving conflict
  | 'ritual_race' // Multiple rituals competing
  | 'dominion_contest' // Close victory race
  | 'legacy_clash'; // Legendary units in proximity

function detectTensionPoints(gameState: GameState): TensionPoint[] {
  const tensions: TensionPoint[] = [];

  // Military standoffs
  tensions.push(...detectMilitaryStandoffs(gameState));

  // Brewing betrayals
  tensions.push(...detectBrewingBetrayals(gameState));

  // Imminent revenge
  tensions.push(...detectImminentRevenge(gameState));

  // Prophecy convergence
  tensions.push(...detectProphecyConvergence(gameState));

  // Power vacuums
  tensions.push(...detectPowerVacuums(gameState));

  // Close victory races
  tensions.push(...detectVictoryRaces(gameState));

  // Sort by intensity
  tensions.sort((a, b) => b.intensity - a.intensity);

  return tensions;
}

function detectMilitaryStandoffs(gameState: GameState): TensionPoint[] {
  const standoffs: TensionPoint[] = [];

  // Find territories with significant opposing forces nearby
  for (const [territoryId, territory] of gameState.territories) {
    const adjacentEnemies = getAdjacentEnemyForces(territoryId, gameState);

    if (adjacentEnemies.length === 0) continue;

    const defenderStrength = calculateTerritoryStrength(territory, gameState);

    for (const enemy of adjacentEnemies) {
      const attackerStrength = enemy.strength;
      const ratio = attackerStrength / defenderStrength;

      // Tension is highest when forces are evenly matched
      let intensity = 0;
      if (ratio >= 0.8 && ratio <= 1.2) {
        intensity = 8; // Very evenly matched
      } else if (ratio >= 0.5 && ratio <= 2.0) {
        intensity = 5; // Moderately matched
      } else {
        continue; // Clear advantage, less tension
      }

      // Boost intensity for strategic territories
      if (territory.type === 'nexus') intensity += 2;
      if (territory.fullDominion) intensity += 1;

      standoffs.push({
        id: generateTensionId(),
        type: 'military_standoff',
        intensity: Math.min(10, intensity),
        primaryActors: [territory.material.controller!, enemy.player],
        secondaryActors: [],
        affectedTerritories: [territoryId],
        relatedThreads: getRelatedWarThreads(
          [territory.material.controller!, enemy.player],
          gameState
        ),
        relatedNodes: [],
        buildupTurns: 0,
        peakExpectedTurn: gameState.currentTurn + 2,
        possibleResolutions: [
          { type: 'battle', likelihood: 70 },
          { type: 'negotiation', likelihood: 20 },
          { type: 'standoff_continues', likelihood: 10 },
        ],
        mostLikelyResolution: { type: 'battle', likelihood: 70 },
        dramaticQuestions: [
          `Will ${getPlayerName(territory.material.controller!, gameState)} hold against ${getPlayerName(enemy.player, gameState)}?`,
          `Who will strike first?`,
        ],
        foreshadowingElements: [],
      });
    }
  }

  return standoffs;
}

function detectBrewingBetrayals(gameState: GameState): TensionPoint[] {
  const betrayals: TensionPoint[] = [];

  for (const alliance of gameState.alliances.values()) {
    if (alliance.status !== 'active') continue;

    // Check strain level
    if (alliance.strainLevel >= 50) {
      const [p1, p2] = alliance.participants;

      // Check for signs of impending betrayal
      const p1Buildup = checkBetrayalBuildup(p1, p2, gameState);
      const p2Buildup = checkBetrayalBuildup(p2, p1, gameState);

      const intensity = Math.max(p1Buildup.score, p2Buildup.score);
      if (intensity < 3) continue;

      const likelyBetrayer = p1Buildup.score > p2Buildup.score ? p1 : p2;
      const likelyVictim = likelyBetrayer === p1 ? p2 : p1;

      betrayals.push({
        id: generateTensionId(),
        type: 'betrayal_brewing',
        intensity,
        primaryActors: [likelyBetrayer, likelyVictim],
        secondaryActors: [],
        affectedTerritories: [],
        relatedThreads: [alliance.weaveThreadId],
        relatedNodes: [],
        buildupTurns: Math.floor(alliance.strainLevel / 10),
        peakExpectedTurn: gameState.currentTurn + 3,
        possibleResolutions: [
          { type: 'betrayal', likelihood: intensity * 8 },
          { type: 'reconciliation', likelihood: 100 - intensity * 8 },
        ],
        mostLikelyResolution:
          intensity >= 7
            ? { type: 'betrayal', likelihood: intensity * 8 }
            : { type: 'reconciliation', likelihood: 100 - intensity * 8 },
        dramaticQuestions: [
          `Will the alliance between ${getPlayerName(p1, gameState)} and ${getPlayerName(p2, gameState)} survive?`,
          `Who will break first?`,
        ],
        foreshadowingElements: [
          `${getPlayerName(likelyBetrayer, gameState)}'s forces have been repositioning...`,
          `Trade caravans between the allies have grown sparse...`,
        ],
      });
    }
  }

  return betrayals;
}
```

### 4.2 Dramatic Moment Generation

```typescript
interface DramaticMoment {
  id: MomentId;
  type: DramaticMomentType;
  significance: 'minor' | 'moderate' | 'major' | 'climactic';

  // Participants
  spotlight: PlayerId[];
  supporting: PlayerId[];

  // Context
  trigger: TensionPoint | TriggeredConsequence | GameEvent;
  location: TerritoryId | null;

  // Narrative
  title: string;
  openingNarration: string;
  dramaticBeat: string;
  closingNarration: string;

  // Mechanical integration
  pauseForPlayer: boolean;
  choiceRequired: boolean;
  choices: DramaticChoice[];

  // Weave integration
  weaveImpact: number;
  threadsCreated: WeaveThread[];
  threadsResolved: WeaveThread[];
}

type DramaticMomentType =
  | 'confrontation' // Face-to-face encounter
  | 'revelation' // Truth revealed
  | 'sacrifice' // Heroic or tragic sacrifice
  | 'betrayal' // Alliance broken
  | 'triumph' // Great victory
  | 'fall' // Mighty brought low
  | 'prophecy_fulfillment'
  | 'redemption'
  | 'last_stand';

function generateDramaticMoment(
  trigger: TensionPoint | TriggeredConsequence,
  gameState: GameState
): DramaticMoment {
  const momentType = determineMomentType(trigger);
  const significance = determineSignificance(trigger);

  const moment: DramaticMoment = {
    id: generateMomentId(),
    type: momentType,
    significance,
    spotlight: trigger.primaryActors ?? [trigger.sourceActionId],
    supporting: trigger.secondaryActors ?? [],
    trigger,
    location: trigger.affectedTerritories?.[0] ?? null,
    title: generateMomentTitle(momentType, trigger, gameState),
    openingNarration: generateOpeningNarration(momentType, trigger, gameState),
    dramaticBeat: generateDramaticBeat(momentType, trigger, gameState),
    closingNarration: generateClosingNarration(momentType, trigger, gameState),
    pauseForPlayer: significance === 'climactic',
    choiceRequired: shouldOfferChoice(momentType),
    choices: generateDramaticChoices(momentType, trigger, gameState),
    weaveImpact: calculateWeaveImpact(significance),
    threadsCreated: [],
    threadsResolved: [],
  };

  // Generate Weave threads from moment
  if (significance === 'major' || significance === 'climactic') {
    moment.threadsCreated = createThreadsFromMoment(moment, gameState);
  }

  // Check for threads resolved by this moment
  moment.threadsResolved = findResolvedThreads(moment, gameState);

  return moment;
}

function generateMomentTitle(
  type: DramaticMomentType,
  trigger: any,
  gameState: GameState
): string {
  const templates: Record<
    DramaticMomentType,
    (t: any, g: GameState) => string
  > = {
    confrontation: (t, g) =>
      `The ${getPlayerName(t.primaryActors[0], g)} and ${getPlayerName(t.primaryActors[1], g)} Meet`,
    revelation: (t, g) =>
      `The Truth of ${t.relatedThreads[0] ? getThreadTitle(t.relatedThreads[0], g) : 'the Past'}`,
    sacrifice: (t, g) => `${getPlayerName(t.primaryActors[0], g)}'s Sacrifice`,
    betrayal: (t, g) =>
      `The Betrayal at ${t.affectedTerritories[0] ? getTerritoryName(t.affectedTerritories[0], g) : 'Dawn'}`,
    triumph: (t, g) => `The Triumph of ${getPlayerName(t.primaryActors[0], g)}`,
    fall: (t, g) => `The Fall of ${getPlayerName(t.primaryActors[0], g)}`,
    prophecy_fulfillment: (t, g) => `The Prophecy Fulfilled`,
    redemption: (t, g) =>
      `${getPlayerName(t.primaryActors[0], g)}'s Redemption`,
    last_stand: (t, g) =>
      `The Last Stand at ${getTerritoryName(t.affectedTerritories[0], g)}`,
  };

  return templates[type](trigger, gameState);
}

function generateDramaticBeat(
  type: DramaticMomentType,
  trigger: any,
  gameState: GameState
): string {
  // The core dramatic moment - the specific beat that defines the scene
  const beats: Record<DramaticMomentType, string[]> = {
    confrontation: [
      'Their eyes meet across the field. In this moment, words are unnecessary.',
      'The air itself seems to hold its breath as the two powers face each other.',
      '"So," one says, breaking the silence, "it has come to this."',
    ],
    revelation: [
      'The veil parts, and the truth stands naked before all who would see.',
      'What was hidden is now revealed. The Weave shudders with the weight of knowing.',
      'In the silence that follows, a new understanding crystallizes.',
    ],
    sacrifice: [
      'In the final moment, the choice is clear. Some things are worth more than survival.',
      'The light flares once, brilliant and brief, and then... peace.',
      '"For them," come the last words. "Always for them."',
    ],
    betrayal: [
      'The blade finds its mark—not in flesh, but in trust.',
      'The smile never wavers, even as the truth becomes undeniable.',
      '"Did you truly believe...?" The question hangs unanswered.',
    ],
    triumph: [
      'The banner rises over the field, and the roar of victory shakes the heavens.',
      'This moment will be remembered. This moment changes everything.',
      'They came to conquer. They have succeeded beyond measure.',
    ],
    fall: [
      'The mighty topple not with a crash, but with the quiet finality of exhaustion.',
      'Once, they seemed unassailable. Now, the truth is written in ash.',
      'The crown falls, rolling away into darkness.',
    ],
    prophecy_fulfillment: [
      'The words spoken in ages past echo now in living action.',
      'Destiny arrives not with fanfare, but with the quiet click of a lock opening.',
      'What the seers foresaw has come to pass. The wheel turns.',
    ],
    redemption: [
      'From the depths of darkness, a hand reaches toward the light.',
      'The past is not erased, but its chains... its chains are broken.',
      '"I was lost. But I am found."',
    ],
    last_stand: [
      'They know they cannot win. They fight anyway.',
      'Every step back is a story. Every breath is a prayer.',
      'When they speak of this day, they will speak of those who would not yield.',
    ],
  };

  const options = beats[type];
  return options[Math.floor(Math.random() * options.length)];
}
```

### 4.3 Story Beat Suggestions for GM

```typescript
interface StoryBeatSuggestion {
  id: SuggestionId;
  type: 'scene' | 'transition' | 'revelation' | 'complication' | 'climax';
  priority: 'low' | 'medium' | 'high' | 'urgent';

  // Context
  basedOn: TensionPoint[] | DramaticMoment[] | WeaveThread[];
  involves: PlayerId[];

  // Suggestion content
  title: string;
  description: string;
  suggestedTiming:
    | 'immediately'
    | 'this_turn'
    | 'next_few_turns'
    | 'when_appropriate';

  // Implementation options
  options: BeatOption[];

  // Weave guidance
  recommendedWeaveActions: WeaveAction[];
  threadsToAdvance: WeaveThreadId[];

  // GM notes
  gmNotes: string;
  playerHooks: Map<PlayerId, string>;
}

function generateStoryBeatSuggestions(
  gameState: GameState
): StoryBeatSuggestion[] {
  const suggestions: StoryBeatSuggestion[] = [];

  // Get current tension points
  const tensions = detectTensionPoints(gameState);

  // Get pending consequences
  const pendingConsequences = getPendingConsequences(gameState);

  // Get active Weave threads
  const activeThreads = gameState.weave.getActiveThreads();

  // Generate suggestions based on high-intensity tensions
  for (const tension of tensions.filter((t) => t.intensity >= 7)) {
    suggestions.push(generateTensionBeatSuggestion(tension, gameState));
  }

  // Generate suggestions for imminent consequences
  for (const consequence of pendingConsequences.filter(
    (c) => c.turnsUntilTrigger <= 2
  )) {
    suggestions.push(generateConsequenceBeatSuggestion(consequence, gameState));
  }

  // Generate suggestions for thread advancement
  for (const thread of activeThreads.filter(
    (t) =>
      t.importance === 'major' && t.lastProgressTurn < gameState.currentTurn - 3
  )) {
    suggestions.push(generateThreadAdvancementSuggestion(thread, gameState));
  }

  // Sort by priority
  const priorityOrder = { urgent: 0, high: 1, medium: 2, low: 3 };
  suggestions.sort(
    (a, b) => priorityOrder[a.priority] - priorityOrder[b.priority]
  );

  return suggestions;
}

function generateTensionBeatSuggestion(
  tension: TensionPoint,
  gameState: GameState
): StoryBeatSuggestion {
  const isClimactic = tension.intensity >= 9;

  return {
    id: generateSuggestionId(),
    type: isClimactic ? 'climax' : 'scene',
    priority:
      tension.intensity >= 9
        ? 'urgent'
        : tension.intensity >= 7
          ? 'high'
          : 'medium',
    basedOn: [tension],
    involves: [...tension.primaryActors, ...tension.secondaryActors],
    title: `${tension.type.replace('_', ' ').toUpperCase()}: ${tension.dramaticQuestions[0]}`,
    description: generateTensionDescription(tension, gameState),
    suggestedTiming: tension.intensity >= 9 ? 'immediately' : 'this_turn',
    options: generateTensionOptions(tension, gameState),
    recommendedWeaveActions: [
      { type: 'strengthen_thread', thread: tension.relatedThreads[0] },
      { type: 'create_connection', nodes: tension.relatedNodes },
    ],
    threadsToAdvance: tension.relatedThreads,
    gmNotes: generateGMNotes(tension, gameState),
    playerHooks: generatePlayerHooks(tension, gameState),
  };
}

function generateGMNotes(tension: TensionPoint, gameState: GameState): string {
  const notes: string[] = [];

  // Build-up context
  notes.push(
    `This tension has been building for ${tension.buildupTurns} turns.`
  );

  // Player motivations
  for (const actor of tension.primaryActors) {
    const motivation = analyzePlayerMotivation(actor, tension, gameState);
    notes.push(
      `${getPlayerName(actor, gameState)} is likely motivated by: ${motivation}`
    );
  }

  // Possible complications
  notes.push('Potential complications:');
  for (const thread of tension.relatedThreads) {
    const threadData = gameState.weave.getThread(thread);
    if (threadData.status === 'active') {
      notes.push(`- Thread "${threadData.title}" could influence this scene`);
    }
  }

  // Suggestion for dramatic pacing
  if (tension.intensity >= 8) {
    notes.push(
      'PACING NOTE: This is a high-intensity moment. Consider slowing down narration and giving players space to react.'
    );
  }

  return notes.join('\n\n');
}

function generatePlayerHooks(
  tension: TensionPoint,
  gameState: GameState
): Map<PlayerId, string> {
  const hooks = new Map<PlayerId, string>();

  for (const player of [...tension.primaryActors, ...tension.secondaryActors]) {
    const playerHistory = getPlayerRelevantHistory(player, tension, gameState);
    const prophecies = getPlayerProphecyHints(player, tension, gameState);
    const personalStakes = getPlayerStakes(player, tension, gameState);

    let hook = '';

    if (playerHistory.length > 0) {
      hook += `Your past actions echo here: ${playerHistory[0]}. `;
    }

    if (prophecies.length > 0) {
      hook += `Something about this moment resonates with your prophecy... `;
    }

    if (personalStakes.length > 0) {
      hook += `What's at stake for you: ${personalStakes.join(', ')}`;
    }

    hooks.set(player, hook);
  }

  return hooks;
}
```

---

## 5. Complete Weave Strategic Memory API

```typescript
interface WeaveStrategicMemoryAPI {
  // Alliance and Treachery
  formAlliance(proposal: AllianceProposal): AllianceFormationResult;
  breakAlliance(
    allianceId: AllianceId,
    initiator: PlayerId
  ): AllianceBreakResult;
  detectBetrayal(action: PlayerAction): BetrayalDetectionResult;
  getTreacheryLevel(player: PlayerId): number;
  getRedemptionPaths(player: PlayerId): RedemptionPath[];

  // Trust Nodes
  createTrustNode(parties: PlayerId[], type: PactType): TrustNode;
  getTrustLevel(p1: PlayerId, p2: PlayerId): number;
  invokeEmergencyAid(invocation: AidInvocation): AidInvocationResult;
  getTrustBonuses(trustNodeId: TrustNodeId): TrustBonus[];

  // Consequences
  catalogueAction(action: PlayerAction, result: ActionResult): CataloguedAction;
  getPotentialConsequences(player: PlayerId): PotentialConsequence[];
  checkConsequenceTriggers(): TriggeredConsequence[];
  getConsequenceWarnings(player: PlayerId): ConsequenceWarning[];

  // Narrative Generation
  detectTensionPoints(): TensionPoint[];
  generateDramaticMoment(trigger: any): DramaticMoment;
  getStoryBeatSuggestions(): StoryBeatSuggestion[];

  // Weave Queries
  getPlayerWeaveHistory(player: PlayerId): WeaveHistorySummary;
  getRelationshipHistory(p1: PlayerId, p2: PlayerId): RelationshipHistory;
  getTerritoryNarrativeHistory(
    territory: TerritoryId
  ): TerritoryNarrativeHistory;
}
```

---

## Appendix A: Trust and Treachery Quick Reference

| Action                       | Trust Impact | Treachery Impact | Notes           |
| ---------------------------- | ------------ | ---------------- | --------------- |
| Form alliance                | +20 trust    | -                | Both parties    |
| Maintain alliance (per turn) | +1 trust     | -                | Passive         |
| Joint victory                | +3 trust     | -                | Per battle      |
| Aid provided                 | +5 trust     | -                | When requested  |
| Break alliance early         | -            | +20-50 treachery | Depends on type |
| Backstab ally                | -            | +75 treachery    | Major violation |
| Refuse aid                   | -20 trust    | +30 treachery    | If aid invoked  |
| Redemption (time)            | -            | -2/turn          | After 5 turns   |
| Victim forgiveness           | -            | -25              | If accepted     |

---

## Appendix B: Implementation Checklist

- [ ] Implement Alliance tracking system
- [ ] Build Betrayal detection module
- [ ] Create Treachery record system
- [ ] Implement Redemption path mechanics
- [ ] Build Trust Node system
- [ ] Create Emergency Aid invocation
- [ ] Implement Trust decay
- [ ] Build Action catalogue
- [ ] Create Consequence trigger system
- [ ] Implement Consequence generation
- [ ] Build Warning notification system
- [ ] Create Tension point detector
- [ ] Implement Dramatic moment generator
- [ ] Build GM suggestion system
- [ ] Add comprehensive tests

---

_Document created as part of The Veil War (Mode 1) game design for Veilborn
Chronicles._
