@agent-e/core 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/defaults.ts","../src/Observer.ts","../src/Diagnoser.ts","../src/types.ts","../src/principles/supply-chain.ts","../src/principles/incentives.ts","../src/principles/population.ts","../src/principles/currency-flow.ts","../src/principles/bootstrap.ts","../src/principles/feedback-loops.ts","../src/principles/regulator.ts","../src/principles/market-dynamics.ts","../src/principles/measurement.ts","../src/principles/statistical.ts","../src/principles/system-dynamics.ts","../src/principles/resource-mgmt.ts","../src/principles/player-experience.ts","../src/principles/open-economy.ts","../src/principles/liveops.ts","../src/principles/index.ts","../src/Simulator.ts","../src/Planner.ts","../src/Executor.ts","../src/DecisionLog.ts","../src/MetricStore.ts","../src/PersonaTracker.ts","../src/AgentE.ts"],"sourcesContent":["// @agent-e/core — main entry point\n\nexport { AgentE } from './AgentE.js';\nexport { Observer } from './Observer.js';\nexport { Diagnoser } from './Diagnoser.js';\nexport { Simulator } from './Simulator.js';\nexport { Planner } from './Planner.js';\nexport { Executor } from './Executor.js';\nexport { DecisionLog } from './DecisionLog.js';\nexport { MetricStore } from './MetricStore.js';\nexport { PersonaTracker } from './PersonaTracker.js';\nexport { DEFAULT_THRESHOLDS, PERSONA_HEALTHY_RANGES } from './defaults.js';\nexport { ALL_PRINCIPLES } from './principles/index.js';\nexport * from './principles/index.js';\nexport * from './types.js';\n","import type { Thresholds } from './types.js';\n\nexport const DEFAULT_THRESHOLDS: Thresholds = {\n // Statistical (P42-P43)\n meanMedianDivergenceMax: 0.30,\n simulationMinIterations: 100,\n\n // Population (P46)\n personaMonocultureMax: 0.40,\n personaMinClusters: 3,\n\n // Open Economy (P34, P47-P48)\n extractionRatioYellow: 0.50,\n extractionRatioRed: 0.65,\n smokeTestWarning: 0.30,\n smokeTestCritical: 0.10,\n currencyInsulationMax: 0.50,\n\n // Player Experience (P45, P50)\n timeBudgetRatio: 0.80,\n payPowerRatioMax: 2.0,\n payPowerRatioTarget: 1.5,\n\n // LiveOps (P51, P53)\n sharkToothPeakDecay: 0.95,\n sharkToothValleyDecay: 0.90,\n eventCompletionMin: 0.40,\n eventCompletionMax: 0.80,\n\n // System Dynamics (P39, P44)\n lagMultiplierMin: 3,\n lagMultiplierMax: 5,\n complexityBudgetMax: 20,\n\n // Resource (P40)\n replacementRateMultiplier: 2.0,\n\n // Regulator (P26-P27)\n maxAdjustmentPercent: 0.15,\n cooldownTicks: 15,\n\n // Currency (P13)\n arenaWinRate: 0.65,\n arenaHouseCut: 0.10,\n\n // Population balance (P9)\n roleSwitchFrictionMax: 0.05, // >5% of population switching in one period = herd\n\n // Pool limits (P15)\n poolCapPercent: 0.05, // no pool > 5% of total currency\n poolDecayRate: 0.02,\n\n // Profitability (P5)\n stampedeProfitRatio: 3.0, // one role's profit > 3× median → stampede risk\n\n // Satisfaction (P24)\n blockedAgentMaxFraction: 0.15,\n\n // Gini (P33)\n giniWarnThreshold: 0.45,\n giniRedThreshold: 0.60,\n\n // Churn (P9)\n churnWarnRate: 0.05,\n\n // Net flow (P12)\n netFlowWarnThreshold: 10,\n\n // V1.1 (P55-P60)\n arbitrageIndexWarning: 0.35,\n arbitrageIndexCritical: 0.55,\n contentDropCooldownTicks: 30,\n postDropArbitrageMax: 0.45,\n relativePriceConvergenceTarget: 0.85,\n priceDiscoveryWindowTicks: 20,\n giftTradeFilterRatio: 0.15,\n disposalTradeWeightDiscount: 0.5,\n};\n\nexport const PERSONA_HEALTHY_RANGES: Record<string, { min: number; max: number }> = {\n Gamer: { min: 0.20, max: 0.40 },\n Trader: { min: 0.05, max: 0.15 },\n Collector: { min: 0.05, max: 0.15 },\n Speculator: { min: 0.00, max: 0.10 },\n Earner: { min: 0.00, max: 0.15 },\n Builder: { min: 0.05, max: 0.15 },\n Social: { min: 0.10, max: 0.20 },\n Whale: { min: 0.00, max: 0.05 },\n Influencer: { min: 0.00, max: 0.05 },\n};\n","// Stage 1: Observer — translates raw EconomyState into EconomyMetrics\n\nimport type { EconomyState, EconomyMetrics, EconomicEvent } from './types.js';\nimport { emptyMetrics } from './types.js';\n\nexport class Observer {\n private previousMetrics: EconomyMetrics | null = null;\n private previousPrices: Record<string, number> = {};\n private customMetricFns: Record<string, (state: EconomyState) => number> = {};\n private anchorBaseline: { goldPerHour: number; itemsPerGold: number } | null = null;\n\n registerCustomMetric(name: string, fn: (state: EconomyState) => number): void {\n this.customMetricFns[name] = fn;\n }\n\n compute(state: EconomyState, recentEvents: EconomicEvent[]): EconomyMetrics {\n const tick = state.tick;\n const balances = Object.values(state.agentBalances);\n const roles = Object.values(state.agentRoles);\n const totalAgents = balances.length;\n\n // ── Event classification (single pass) ──\n let faucetVolume = 0;\n let sinkVolume = 0;\n const tradeEvents: EconomicEvent[] = [];\n const roleChangeEvents: EconomicEvent[] = [];\n let churnCount = 0;\n\n for (const e of recentEvents) {\n switch (e.type) {\n case 'mint':\n case 'spawn':\n faucetVolume += e.amount ?? 0;\n break;\n case 'burn':\n case 'consume':\n sinkVolume += e.amount ?? 0;\n break;\n case 'trade':\n tradeEvents.push(e);\n break;\n case 'churn':\n churnCount++;\n roleChangeEvents.push(e);\n break;\n case 'role_change':\n roleChangeEvents.push(e);\n break;\n }\n }\n\n // ── Currency ──\n const totalSupply = balances.reduce((s, b) => s + b, 0);\n const netFlow = faucetVolume - sinkVolume;\n const tapSinkRatio = sinkVolume > 0 ? faucetVolume / sinkVolume : faucetVolume > 0 ? Infinity : 1;\n\n const prevSupply = this.previousMetrics?.totalSupply ?? totalSupply;\n const inflationRate = prevSupply > 0 ? (totalSupply - prevSupply) / prevSupply : 0;\n\n const velocity = totalSupply > 0 ? tradeEvents.length / totalSupply : 0;\n\n // ── Wealth distribution ──\n const sortedBalances = [...balances].sort((a, b) => a - b);\n const meanBalance = totalAgents > 0 ? totalSupply / totalAgents : 0;\n const medianBalance = computeMedian(sortedBalances);\n const top10Idx = Math.floor(totalAgents * 0.9);\n const top10Sum = sortedBalances.slice(top10Idx).reduce((s, b) => s + b, 0);\n const top10PctShare = totalSupply > 0 ? top10Sum / totalSupply : 0;\n const giniCoefficient = computeGini(sortedBalances);\n const meanMedianDivergence =\n medianBalance > 0 ? Math.abs(meanBalance - medianBalance) / medianBalance : 0;\n\n // ── Population ──\n const populationByRole: Record<string, number> = {};\n const roleShares: Record<string, number> = {};\n for (const role of roles) {\n populationByRole[role] = (populationByRole[role] ?? 0) + 1;\n }\n for (const [role, count] of Object.entries(populationByRole)) {\n roleShares[role] = count / Math.max(1, totalAgents);\n }\n\n const churnByRole: Record<string, number> = {};\n for (const e of roleChangeEvents) {\n const role = e.role ?? 'unknown';\n churnByRole[role] = (churnByRole[role] ?? 0) + 1;\n }\n const churnRate = churnCount / Math.max(1, totalAgents);\n\n // ── Market ──\n const prices: Record<string, number> = { ...state.marketPrices };\n const priceVolatility: Record<string, number> = {};\n for (const [resource, price] of Object.entries(prices)) {\n const prev = this.previousPrices[resource] ?? price;\n priceVolatility[resource] = prev > 0 ? Math.abs(price - prev) / prev : 0;\n }\n this.previousPrices = { ...prices };\n\n // Compute price index (equal-weight basket)\n const priceValues = Object.values(prices);\n const priceIndex =\n priceValues.length > 0 ? priceValues.reduce((s, p) => s + p, 0) / priceValues.length : 0;\n\n // Supply from agent inventories\n const supplyByResource: Record<string, number> = {};\n for (const inv of Object.values(state.agentInventories)) {\n for (const [resource, qty] of Object.entries(inv)) {\n supplyByResource[resource] = (supplyByResource[resource] ?? 0) + qty;\n }\n }\n\n // Demand signals: approximate from recent trade events\n const demandSignals: Record<string, number> = {};\n for (const e of tradeEvents) {\n if (e.resource) {\n demandSignals[e.resource] = (demandSignals[e.resource] ?? 0) + (e.amount ?? 1);\n }\n }\n\n // Pinch points: resources where demand > 2× supply or supply > 3× demand\n const pinchPoints: Record<string, 'optimal' | 'oversupplied' | 'scarce'> = {};\n for (const resource of new Set([...Object.keys(supplyByResource), ...Object.keys(demandSignals)])) {\n const s = supplyByResource[resource] ?? 0;\n const d = demandSignals[resource] ?? 0;\n if (d > 2 && s / d < 0.5) {\n pinchPoints[resource] = 'scarce';\n } else if (s > 3 && d > 0 && s / d > 3) {\n pinchPoints[resource] = 'oversupplied';\n } else {\n pinchPoints[resource] = 'optimal';\n }\n }\n\n const productionIndex = recentEvents\n .filter(e => e.type === 'produce')\n .reduce((s, e) => s + (e.amount ?? 1), 0);\n\n const maxPossibleProduction = productionIndex + sinkVolume;\n const capacityUsage =\n maxPossibleProduction > 0 ? productionIndex / maxPossibleProduction : 0;\n\n // ── Satisfaction ──\n const satisfactions = Object.values(state.agentSatisfaction ?? {});\n const avgSatisfaction =\n satisfactions.length > 0\n ? satisfactions.reduce((s, v) => s + v, 0) / satisfactions.length\n : 80;\n\n const blockedAgentCount = satisfactions.filter(s => s < 20).length;\n const timeToValue = tick > 0 ? Math.max(0, 20 - tick * 0.1) : 20; // simple proxy\n\n // ── Pools ──\n const poolSizes: Record<string, number> = { ...(state.poolSizes ?? {}) };\n\n // ── Anchor ratio ──\n if (!this.anchorBaseline && tick === 1 && totalSupply > 0) {\n this.anchorBaseline = {\n goldPerHour: totalSupply / Math.max(1, totalAgents),\n itemsPerGold: priceIndex > 0 ? 1 / priceIndex : 0,\n };\n }\n let anchorRatioDrift = 0;\n if (this.anchorBaseline && totalAgents > 0) {\n const currentGoldPerHour = totalSupply / totalAgents;\n anchorRatioDrift =\n this.anchorBaseline.goldPerHour > 0\n ? (currentGoldPerHour - this.anchorBaseline.goldPerHour) /\n this.anchorBaseline.goldPerHour\n : 0;\n }\n\n // ── V1.1 Metrics ──\n\n // arbitrageIndex: average pairwise price divergence across all resources\n // For N resources with prices, compute all (N-1)*N/2 relative price ratios\n // and measure how far they deviate from 1.0 (perfect equilibrium)\n let arbitrageIndex = 0;\n const priceKeys = Object.keys(prices).filter(k => prices[k]! > 0);\n if (priceKeys.length >= 2) {\n let pairCount = 0;\n let totalDivergence = 0;\n for (let i = 0; i < priceKeys.length; i++) {\n for (let j = i + 1; j < priceKeys.length; j++) {\n const pA = prices[priceKeys[i]!]!;\n const pB = prices[priceKeys[j]!]!;\n let ratio = pA / pB;\n // Clamp ratio to prevent Math.log(0) or Math.log(Infinity)\n ratio = Math.max(0.001, Math.min(1000, ratio));\n // Divergence from 1.0: |ln(ratio)| gives symmetric measure\n totalDivergence += Math.abs(Math.log(ratio));\n pairCount++;\n }\n }\n arbitrageIndex = pairCount > 0 ? Math.min(1, totalDivergence / pairCount) : 0;\n }\n\n // contentDropAge: ticks since last 'produce' event with metadata.contentDrop === true\n // Falls back to 0 if no content drops tracked\n const contentDropEvents = recentEvents.filter(\n e => e.metadata?.['contentDrop'] === true\n );\n const contentDropAge = contentDropEvents.length > 0\n ? tick - Math.max(...contentDropEvents.map(e => e.timestamp))\n : (this.previousMetrics?.contentDropAge ?? 0) + 1;\n\n // giftTradeRatio: fraction of trades where price is 0 or significantly below market\n let giftTrades = 0;\n if (tradeEvents.length > 0) {\n for (const e of tradeEvents) {\n const marketPrice = prices[e.resource ?? ''] ?? 0;\n const tradePrice = e.price ?? 0;\n if (tradePrice === 0 || (marketPrice > 0 && tradePrice < marketPrice * 0.3)) {\n giftTrades++;\n }\n }\n }\n const giftTradeRatio = tradeEvents.length > 0 ? giftTrades / tradeEvents.length : 0;\n\n // disposalTradeRatio: fraction of trades classified as surplus liquidation\n // Heuristic: trade where seller has >3× average inventory of that resource\n let disposalTrades = 0;\n if (tradeEvents.length > 0) {\n for (const e of tradeEvents) {\n if (e.from && e.resource) {\n const sellerInv = state.agentInventories[e.from]?.[e.resource] ?? 0;\n const avgInv = (supplyByResource[e.resource] ?? 0) / Math.max(1, totalAgents);\n if (sellerInv > avgInv * 3) {\n disposalTrades++;\n }\n }\n }\n }\n const disposalTradeRatio = tradeEvents.length > 0 ? disposalTrades / tradeEvents.length : 0;\n\n // ── Custom metrics ──\n const custom: Record<string, number> = {};\n for (const [name, fn] of Object.entries(this.customMetricFns)) {\n try {\n custom[name] = fn(state);\n } catch {\n custom[name] = NaN;\n }\n }\n\n const metrics: EconomyMetrics = {\n tick,\n timestamp: Date.now(),\n totalSupply,\n netFlow,\n velocity,\n inflationRate,\n populationByRole,\n roleShares,\n totalAgents,\n churnRate,\n churnByRole,\n personaDistribution: {}, // populated by PersonaTracker\n giniCoefficient,\n medianBalance,\n meanBalance,\n top10PctShare,\n meanMedianDivergence,\n priceIndex,\n productionIndex,\n capacityUsage,\n prices,\n priceVolatility,\n supplyByResource,\n demandSignals,\n pinchPoints,\n avgSatisfaction,\n blockedAgentCount,\n timeToValue,\n faucetVolume,\n sinkVolume,\n tapSinkRatio,\n poolSizes,\n anchorRatioDrift,\n extractionRatio: NaN,\n newUserDependency: NaN,\n smokeTestRatio: NaN,\n currencyInsulation: NaN,\n sharkToothPeaks: this.previousMetrics?.sharkToothPeaks ?? [],\n sharkToothValleys: this.previousMetrics?.sharkToothValleys ?? [],\n eventCompletionRate: NaN,\n arbitrageIndex,\n contentDropAge,\n giftTradeRatio,\n disposalTradeRatio,\n custom,\n };\n\n this.previousMetrics = metrics;\n return metrics;\n }\n}\n\n// ── Math helpers ──────────────────────────────────────────────────────────────\n\nfunction computeMedian(sorted: number[]): number {\n if (sorted.length === 0) return 0;\n const mid = Math.floor(sorted.length / 2);\n return sorted.length % 2 === 0\n ? ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2\n : (sorted[mid] ?? 0);\n}\n\nfunction computeGini(sorted: number[]): number {\n const n = sorted.length;\n if (n === 0) return 0;\n const sum = sorted.reduce((a, b) => a + b, 0);\n if (sum === 0) return 0;\n let numerator = 0;\n for (let i = 0; i < n; i++) {\n numerator += (2 * (i + 1) - n - 1) * (sorted[i] ?? 0);\n }\n return Math.abs(numerator) / (n * sum);\n}\n","// Stage 2: Diagnoser — runs all principles, returns sorted violations\n\nimport type { Principle, EconomyMetrics, Thresholds, Diagnosis } from './types.js';\n\nexport class Diagnoser {\n private principles: Principle[] = [];\n\n constructor(principles: Principle[]) {\n this.principles = [...principles];\n }\n\n addPrinciple(principle: Principle): void {\n this.principles.push(principle);\n }\n\n removePrinciple(id: string): void {\n this.principles = this.principles.filter(p => p.id !== id);\n }\n\n /**\n * Run all principles against current metrics.\n * Returns violations sorted by severity (highest first).\n * Only one action is taken per cycle — the highest severity violation.\n */\n diagnose(metrics: EconomyMetrics, thresholds: Thresholds): Diagnosis[] {\n const diagnoses: Diagnosis[] = [];\n\n for (const principle of this.principles) {\n try {\n const result = principle.check(metrics, thresholds);\n if (result.violated) {\n diagnoses.push({\n principle,\n violation: result,\n tick: metrics.tick,\n });\n }\n } catch (err) {\n // Never let a buggy principle crash the engine\n console.warn(`[AgentE] Principle ${principle.id} threw an error:`, err);\n }\n }\n\n // Sort by severity DESC, then by confidence DESC as tiebreaker\n diagnoses.sort((a, b) => {\n const severityDiff = b.violation.severity - a.violation.severity;\n if (severityDiff !== 0) return severityDiff;\n return b.violation.confidence - a.violation.confidence;\n });\n\n return diagnoses;\n }\n\n getPrinciples(): Principle[] {\n return [...this.principles];\n }\n}\n","// ─────────────────────────────────────────────────────────────────────────────\n// AgentE Core Types\n// Every other file imports from here. Keep this file pure (no logic).\n// ─────────────────────────────────────────────────────────────────────────────\n\n// ── Events ───────────────────────────────────────────────────────────────────\n\nexport type EconomicEventType =\n | 'trade'\n | 'mint'\n | 'burn'\n | 'transfer'\n | 'produce'\n | 'consume'\n | 'role_change'\n | 'spawn'\n | 'churn';\n\nexport interface EconomicEvent {\n type: EconomicEventType;\n timestamp: number; // tick or unix ms — adapter decides\n actor: string; // agent/user/wallet ID\n role?: string; // actor's role in the economy\n resource?: string; // what resource is involved\n amount?: number; // quantity\n price?: number; // per-unit price\n from?: string; // source (for transfers)\n to?: string; // destination\n metadata?: Record<string, unknown>;\n}\n\n// ── Metrics ──────────────────────────────────────────────────────────────────\n\nexport type PinchPointStatus = 'optimal' | 'oversupplied' | 'scarce';\n\nexport interface EconomyMetrics {\n // ── Snapshot info ──\n tick: number;\n timestamp: number;\n\n // ── Currency health ──\n totalSupply: number;\n netFlow: number; // faucets minus sinks per period\n velocity: number; // transactions per period / total supply\n inflationRate: number; // % change in price index per period\n\n // ── Population health ──\n populationByRole: Record<string, number>;\n roleShares: Record<string, number>; // each role as fraction of total\n totalAgents: number;\n churnRate: number; // fraction lost per period\n churnByRole: Record<string, number>;\n personaDistribution: Record<string, number>;\n\n // ── Wealth distribution ──\n giniCoefficient: number; // 0 = perfect equality, 1 = one agent has everything\n medianBalance: number;\n meanBalance: number;\n top10PctShare: number; // fraction of wealth held by top 10%\n meanMedianDivergence: number; // (mean - median) / median\n\n // ── Market health ──\n priceIndex: number;\n productionIndex: number;\n capacityUsage: number;\n prices: Record<string, number>;\n priceVolatility: Record<string, number>;\n supplyByResource: Record<string, number>;\n demandSignals: Record<string, number>;\n pinchPoints: Record<string, PinchPointStatus>;\n\n // ── Satisfaction / Engagement ──\n avgSatisfaction: number;\n blockedAgentCount: number;\n timeToValue: number;\n\n // ── Flow tracking ──\n faucetVolume: number;\n sinkVolume: number;\n tapSinkRatio: number;\n poolSizes: Record<string, number>;\n anchorRatioDrift: number;\n\n // ── Open economy (optional, NaN if not tracked) ──\n extractionRatio: number;\n newUserDependency: number;\n smokeTestRatio: number;\n currencyInsulation: number;\n\n // ── LiveOps (optional, empty arrays if not tracked) ──\n sharkToothPeaks: number[];\n sharkToothValleys: number[];\n eventCompletionRate: number;\n\n // ── V1.1 Metrics (P55-P60) ──\n arbitrageIndex: number; // 0–1, aggregate arbitrage opportunity across all relative prices\n contentDropAge: number; // ticks since last content/item injection event\n giftTradeRatio: number; // fraction of recent trades classified as gifts/below-market\n disposalTradeRatio: number; // fraction of recent trades that are surplus liquidation, not production-for-sale\n\n // ── Custom metrics registered by developer ──\n custom: Record<string, number>;\n}\n\n// Sensible defaults for an EconomyMetrics snapshot when data is unavailable\nexport function emptyMetrics(tick = 0): EconomyMetrics {\n return {\n tick,\n timestamp: Date.now(),\n totalSupply: 0,\n netFlow: 0,\n velocity: 0,\n inflationRate: 0,\n populationByRole: {},\n roleShares: {},\n totalAgents: 0,\n churnRate: 0,\n churnByRole: {},\n personaDistribution: {},\n giniCoefficient: 0,\n medianBalance: 0,\n meanBalance: 0,\n top10PctShare: 0,\n meanMedianDivergence: 0,\n priceIndex: 0,\n productionIndex: 0,\n capacityUsage: 0,\n prices: {},\n priceVolatility: {},\n supplyByResource: {},\n demandSignals: {},\n pinchPoints: {},\n avgSatisfaction: 100,\n blockedAgentCount: 0,\n timeToValue: 0,\n faucetVolume: 0,\n sinkVolume: 0,\n tapSinkRatio: 1,\n poolSizes: {},\n anchorRatioDrift: 0,\n extractionRatio: NaN,\n newUserDependency: NaN,\n smokeTestRatio: NaN,\n currencyInsulation: NaN,\n sharkToothPeaks: [],\n sharkToothValleys: [],\n eventCompletionRate: NaN,\n arbitrageIndex: 0,\n contentDropAge: 0,\n giftTradeRatio: 0,\n disposalTradeRatio: 0,\n custom: {},\n };\n}\n\n// ── Principles ────────────────────────────────────────────────────────────────\n\nexport type PrincipleCategory =\n | 'supply_chain'\n | 'incentive'\n | 'population'\n | 'currency'\n | 'bootstrap'\n | 'feedback'\n | 'regulator'\n | 'market_dynamics'\n | 'measurement'\n | 'wealth_distribution'\n | 'resource'\n | 'system_design'\n | 'player_experience'\n | 'statistical'\n | 'system_dynamics'\n | 'open_economy'\n | 'liveops';\n\nexport interface PrincipleViolation {\n violated: true;\n severity: number; // 1–10\n evidence: Record<string, unknown>;\n suggestedAction: SuggestedAction;\n confidence: number; // 0–1\n estimatedLag?: number; // ticks before effect visible\n}\n\nexport interface PrincipleOk {\n violated: false;\n}\n\nexport type PrincipleResult = PrincipleViolation | PrincipleOk;\n\nexport interface Principle {\n id: string; // 'P1', 'P2', ... 'P54', or custom\n name: string;\n category: PrincipleCategory;\n description: string;\n check: (metrics: EconomyMetrics, thresholds: Thresholds) => PrincipleResult;\n}\n\n// ── Actions ──────────────────────────────────────────────────────────────────\n\nexport interface SuggestedAction {\n parameter: string;\n direction: 'increase' | 'decrease' | 'set';\n magnitude?: number; // fractional (0.15 = 15%)\n absoluteValue?: number;\n reasoning: string;\n}\n\nexport interface ActionPlan {\n id: string;\n diagnosis: Diagnosis;\n parameter: string;\n currentValue: number;\n targetValue: number;\n maxChangePercent: number;\n cooldownTicks: number;\n rollbackCondition: RollbackCondition;\n simulationResult: SimulationResult;\n estimatedLag: number;\n appliedAt?: number; // tick when applied\n}\n\nexport interface RollbackCondition {\n metric: keyof EconomyMetrics | string; // what to watch\n direction: 'above' | 'below';\n threshold: number;\n checkAfterTick: number; // don't check until this tick\n}\n\n// ── Diagnosis ────────────────────────────────────────────────────────────────\n\nexport interface Diagnosis {\n principle: Principle;\n violation: PrincipleViolation;\n tick: number;\n}\n\n// ── Simulation ───────────────────────────────────────────────────────────────\n\nexport interface SimulationOutcome {\n p10: EconomyMetrics;\n p50: EconomyMetrics;\n p90: EconomyMetrics;\n mean: EconomyMetrics;\n}\n\nexport interface SimulationResult {\n proposedAction: SuggestedAction;\n iterations: number;\n forwardTicks: number;\n outcomes: SimulationOutcome;\n netImprovement: boolean;\n noNewProblems: boolean;\n confidenceInterval: [number, number];\n estimatedEffectTick: number;\n overshootRisk: number; // 0–1\n}\n\n// ── Decision Log ─────────────────────────────────────────────────────────────\n\nexport type DecisionResult =\n | 'applied'\n | 'skipped_cooldown'\n | 'skipped_simulation_failed'\n | 'skipped_locked'\n | 'skipped_override'\n | 'rolled_back';\n\nexport interface DecisionEntry {\n id: string;\n tick: number;\n timestamp: number;\n diagnosis: Diagnosis;\n plan: ActionPlan;\n result: DecisionResult;\n reasoning: string;\n metricsSnapshot: EconomyMetrics;\n}\n\n// ── Adapter ──────────────────────────────────────────────────────────────────\n\nexport interface EconomyState {\n tick: number;\n roles: string[];\n resources: string[];\n currency: string;\n agentBalances: Record<string, number>;\n agentRoles: Record<string, string>;\n agentInventories: Record<string, Record<string, number>>;\n agentSatisfaction?: Record<string, number>;\n marketPrices: Record<string, number>;\n recentTransactions: EconomicEvent[];\n poolSizes?: Record<string, number>;\n customData?: Record<string, unknown>;\n}\n\nexport interface EconomyAdapter {\n /** Return current full state snapshot */\n getState(): EconomyState | Promise<EconomyState>;\n /** Apply a parameter change to the host system */\n setParam(key: string, value: number): void | Promise<void>;\n /** Optional: adapter pushes events as they happen */\n onEvent?: (handler: (event: EconomicEvent) => void) => void;\n}\n\n// ── Thresholds ────────────────────────────────────────────────────────────────\n\nexport interface Thresholds {\n // Statistical (P42-P43)\n meanMedianDivergenceMax: number;\n simulationMinIterations: number;\n\n // Population (P46)\n personaMonocultureMax: number;\n personaMinClusters: number;\n\n // Open Economy (P34, P47-P48)\n extractionRatioYellow: number;\n extractionRatioRed: number;\n smokeTestWarning: number;\n smokeTestCritical: number;\n currencyInsulationMax: number;\n\n // Player Experience (P45, P50)\n timeBudgetRatio: number;\n payPowerRatioMax: number;\n payPowerRatioTarget: number;\n\n // LiveOps (P51, P53)\n sharkToothPeakDecay: number;\n sharkToothValleyDecay: number;\n eventCompletionMin: number;\n eventCompletionMax: number;\n\n // System Dynamics (P39, P44)\n lagMultiplierMin: number;\n lagMultiplierMax: number;\n complexityBudgetMax: number;\n\n // Resource (P40)\n replacementRateMultiplier: number;\n\n // Regulator (P26-P27)\n maxAdjustmentPercent: number;\n cooldownTicks: number;\n\n // Currency (P13)\n arenaWinRate: number;\n arenaHouseCut: number;\n\n // Population balance (P9)\n roleSwitchFrictionMax: number;\n\n // Pool limits (P15)\n poolCapPercent: number;\n poolDecayRate: number;\n\n // Profitability (P5)\n stampedeProfitRatio: number; // if one role's profit > X× others → stampede risk\n\n // Satisfaction (P24)\n blockedAgentMaxFraction: number;\n\n // Gini (P33)\n giniWarnThreshold: number;\n giniRedThreshold: number;\n\n // Churn (P9)\n churnWarnRate: number;\n\n // Net flow (P12)\n netFlowWarnThreshold: number;\n\n // V1.1 Thresholds (P55-P60)\n arbitrageIndexWarning: number; // P55: yellow alert\n arbitrageIndexCritical: number; // P55: red alert\n contentDropCooldownTicks: number; // P56: ticks to wait after drop before measuring\n postDropArbitrageMax: number; // P56: max acceptable arbitrage during cooldown\n relativePriceConvergenceTarget: number; // P57: fraction of relative prices within ±20% of equilibrium\n priceDiscoveryWindowTicks: number; // P57: ticks to allow for distributed price discovery\n giftTradeFilterRatio: number; // P59: max gift-trade fraction before filtering kicks in\n disposalTradeWeightDiscount: number; // P60: multiplier applied to disposal-trade price signals (0–1)\n}\n\n// ── AgentE Config ─────────────────────────────────────────────────────────────\n\nexport type AgentEMode = 'autonomous' | 'advisor';\n\nexport interface AgentEConfig {\n adapter: EconomyAdapter | 'game' | 'defi' | 'marketplace';\n mode?: AgentEMode;\n\n // Economy structure hints (helps grace period + fighter-exempt logic)\n dominantRoles?: string[]; // roles exempt from population caps (e.g. ['Fighter'])\n idealDistribution?: Record<string, number>;\n\n // Timing\n gracePeriod?: number; // ticks before first intervention (default 50)\n checkInterval?: number; // ticks between checks (default 5)\n\n // Tuning\n maxAdjustmentPercent?: number;\n cooldownTicks?: number;\n\n // Thresholds overrides (partial — merged with defaults)\n thresholds?: Partial<Thresholds>;\n\n // Callbacks\n onDecision?: (entry: DecisionEntry) => void;\n onAlert?: (diagnosis: Diagnosis) => void;\n onRollback?: (plan: ActionPlan, reason: string) => void;\n}\n\n// ── Persona Types ─────────────────────────────────────────────────────────────\n\nexport type PersonaType =\n | 'Gamer'\n | 'Trader'\n | 'Collector'\n | 'Speculator'\n | 'Earner'\n | 'Builder'\n | 'Social'\n | 'Whale'\n | 'Influencer';\n\nexport interface PersonaProfile {\n type: PersonaType;\n share: number; // fraction of total\n healthyRangeMin: number;\n healthyRangeMax: number;\n}\n\n// ── Metric Query ──────────────────────────────────────────────────────────────\n\nexport type MetricResolution = 'fine' | 'medium' | 'coarse';\n\nexport interface MetricQuery {\n metric: keyof EconomyMetrics | string;\n from?: number; // tick\n to?: number; // tick\n resolution?: MetricResolution;\n}\n\nexport interface MetricQueryResult {\n metric: string;\n resolution: MetricResolution;\n points: Array<{ tick: number; value: number }>;\n}\n","// P1-P4: Supply Chain Principles\n// Source: V0.0-V0.4.6 development failures — ore piling at Forge, hand-off blockage\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P1_ProductionMatchesConsumption: Principle = {\n id: 'P1',\n name: 'Production Must Match Consumption',\n category: 'supply_chain',\n description:\n 'If producer rate < consumer rate, supply deficit kills the economy. ' +\n '105 ore rotting at Forge (V0.4.6) happened because this was out of balance.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, demandSignals, populationByRole } = metrics;\n\n // Look for resources with high demand signals but low / declining supply\n const violations: string[] = [];\n for (const resource of Object.keys(demandSignals)) {\n const demand = demandSignals[resource] ?? 0;\n const supply = supplyByResource[resource] ?? 0;\n // Deficit: demand exceeds supply by >50% with meaningful demand\n if (demand > 5 && supply / Math.max(1, demand) < 0.5) {\n violations.push(resource);\n }\n }\n\n // Also check: if producer roles are outnumbered relative to consumer roles\n const crafters = (populationByRole['Crafter'] ?? 0) + (populationByRole['Alchemist'] ?? 0);\n const consumers = (populationByRole['Fighter'] ?? 0);\n const productionDeficit = consumers > 0 && crafters / consumers < 0.1;\n\n if (violations.length > 0 || productionDeficit) {\n return {\n violated: true,\n severity: 7,\n evidence: { scarceResources: violations, crafters, consumers },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning: 'Lower crafting cost to incentivise more production.',\n },\n confidence: violations.length > 0 ? 0.85 : 0.6,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P2_ClosedLoopsNeedDirectHandoff: Principle = {\n id: 'P2',\n name: 'Closed Loops Need Direct Handoff',\n category: 'supply_chain',\n description:\n 'Raw materials listed on an open market create noise and liquidity problems. ' +\n 'Gatherers delivering ore directly to Crafters at the Forge is faster and cleaner.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, prices, velocity } = metrics;\n\n // Signal: raw materials (ore, wood) have high supply but low velocity\n // This suggests they are listed but not being bought\n const ore = supplyByResource['ore'] ?? 0;\n const wood = supplyByResource['wood'] ?? 0;\n const orePrice = prices['ore'] ?? 0;\n const woodPrice = prices['wood'] ?? 0;\n\n const oreBacklog = ore > 50 && orePrice > 0;\n const woodBacklog = wood > 50 && woodPrice > 0;\n const stagnant = velocity < 3;\n\n if ((oreBacklog || woodBacklog) && stagnant) {\n return {\n violated: true,\n severity: 5,\n evidence: { ore, wood, velocity },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n 'Raise AH fees to discourage raw material listings. ' +\n 'Direct hand-off at production zones is the correct channel.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P3_BootstrapCapitalCoversFirstTransaction: Principle = {\n id: 'P3',\n name: 'Bootstrap Capital Covers First Transaction',\n category: 'supply_chain',\n description:\n 'A new producer must be able to afford their first transaction without selling ' +\n 'anything first. Crafter starting with 15g but needing 30g to accept ore hand-off ' +\n 'blocks the entire supply chain from tick 1.',\n check(metrics, _thresholds): PrincipleResult {\n const { populationByRole, supplyByResource, prices } = metrics;\n\n // Proxy: if there are producers but supply of their output is zero or near-zero\n // despite producers existing, bootstrap likely failed\n const crafters = populationByRole['Crafter'] ?? 0;\n const alchemists = populationByRole['Alchemist'] ?? 0;\n const weapons = supplyByResource['weapons'] ?? 0;\n const potions = supplyByResource['potions'] ?? 0;\n\n const crafterBootstrapFail = crafters > 0 && weapons === 0 && (prices['ore'] ?? 0) > 0;\n const alchemistBootstrapFail = alchemists > 0 && potions === 0 && (prices['wood'] ?? 0) > 0;\n\n if (crafterBootstrapFail || alchemistBootstrapFail) {\n return {\n violated: true,\n severity: 8,\n evidence: { crafters, alchemists, weapons, potions },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.30,\n reasoning:\n 'Producers cannot complete first transaction. ' +\n 'Lower production cost to unblock bootstrap.',\n },\n confidence: 0.80,\n estimatedLag: 3,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P4_MaterialsFlowFasterThanCooldown: Principle = {\n id: 'P4',\n name: 'Materials Flow Faster Than Cooldown',\n category: 'supply_chain',\n description:\n 'Input delivery rate must exceed or match production cooldown rate. ' +\n 'If Crafters craft every 5 ticks but only receive ore every 10 ticks, ' +\n 'they starve regardless of supply levels.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, populationByRole, velocity } = metrics;\n\n const gatherers = populationByRole['Gatherer'] ?? 0;\n const crafters = populationByRole['Crafter'] ?? 0;\n const alchemists = populationByRole['Alchemist'] ?? 0;\n\n // Rough proxy: if ore supply is growing (gatherers > 0) but weapons aren't\n // being produced (weapons supply static), delivery is outpacing consumption\n // or consumption is bottlenecked by material shortage\n const producers = crafters + alchemists;\n const gathererToProcuderRatio = gatherers / Math.max(1, producers);\n\n // Too few gatherers: producers will starve\n if (producers > 0 && gathererToProcuderRatio < 0.5 && velocity < 5) {\n return {\n violated: true,\n severity: 5,\n evidence: { gatherers, crafters, alchemists, gathererToProcuderRatio },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'increase',\n magnitude: 0.15,\n reasoning: 'Too few gatherers relative to producers. Increase yield to compensate.',\n },\n confidence: 0.65,\n estimatedLag: 8,\n };\n }\n\n // Too many: materials pile up\n const ore = supplyByResource['ore'] ?? 0;\n const wood = supplyByResource['wood'] ?? 0;\n if (ore > 80 || wood > 80) {\n return {\n violated: true,\n severity: 4,\n evidence: { ore, wood, gatherers, producers },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'decrease',\n magnitude: 0.20,\n reasoning: 'Raw materials piling up. Gatherers outpacing producers.',\n },\n confidence: 0.80,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P60_SurplusDisposalAsymmetry: Principle = {\n id: 'P60',\n name: 'Surplus Disposal Asymmetry',\n category: 'supply_chain',\n description:\n 'Most trades liquidate unwanted surplus, not deliberate production. ' +\n 'Price signals from disposal trades are weaker demand indicators than ' +\n 'production-for-sale trades — weight them accordingly.',\n check(metrics, thresholds): PrincipleResult {\n const { disposalTradeRatio } = metrics;\n\n // If majority of trades are disposal, price signals are unreliable\n if (disposalTradeRatio > 0.60) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n disposalTradeRatio,\n discount: thresholds.disposalTradeWeightDiscount,\n },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${(disposalTradeRatio * 100).toFixed(0)}% of trades are surplus disposal. ` +\n 'Price signals unreliable as demand indicators. ' +\n 'Lower production costs to shift balance toward deliberate production-for-sale. ' +\n `ADVISORY: Weight disposal-trade prices at ${thresholds.disposalTradeWeightDiscount}× ` +\n 'in index calculations.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const SUPPLY_CHAIN_PRINCIPLES: Principle[] = [\n P1_ProductionMatchesConsumption,\n P2_ClosedLoopsNeedDirectHandoff,\n P3_BootstrapCapitalCoversFirstTransaction,\n P4_MaterialsFlowFasterThanCooldown,\n P60_SurplusDisposalAsymmetry,\n];\n","// P5-P8: Incentive Alignment Principles\n// Source: 97-Trader stampede (V0.4.6), regulator killing bootstrap (V0.4.4)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P5_ProfitabilityIsCompetitive: Principle = {\n id: 'P5',\n name: 'Profitability Is Competitive, Not Absolute',\n category: 'incentive',\n description:\n 'Any profitability formula that returns the same number regardless of how many ' +\n 'agents are already in that role will cause stampedes. ' +\n '97 Traders happened because profit = transactions × 10 with no competition denominator.',\n check(metrics, thresholds): PrincipleResult {\n const { roleShares, populationByRole } = metrics;\n\n // Look for roles with disproportionate share that shouldn't dominate\n // Heuristic: any non-primary role above 40% share is suspicious\n const highShareRoles: string[] = [];\n for (const [role, share] of Object.entries(roleShares)) {\n if (share > 0.45) highShareRoles.push(role); // >45% = stampede signal; Fighter at ~44% is healthy design\n }\n\n if (highShareRoles.length > 0) {\n const dominantRole = highShareRoles[0]!;\n return {\n violated: true,\n severity: 6,\n evidence: {\n dominantRole,\n share: roleShares[dominantRole],\n population: populationByRole[dominantRole],\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: thresholds.maxAdjustmentPercent,\n reasoning:\n `${dominantRole} share at ${((roleShares[dominantRole] ?? 0) * 100).toFixed(0)}%. ` +\n 'Likely stampede from non-competitive profitability formula. ' +\n 'Raise market friction to slow role accumulation.',\n },\n confidence: 0.75,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P6_CrowdingMultiplierOnAllRoles: Principle = {\n id: 'P6',\n name: 'Crowding Multiplier Applies to ALL Roles',\n category: 'incentive',\n description:\n 'Every role needs an inverse-population profitability scaling. ' +\n 'A role without crowding pressure is a stampede waiting to happen.',\n check(metrics, _thresholds): PrincipleResult {\n const { roleShares } = metrics;\n\n // Any role above 35% is likely lacking crowding pressure\n // (healthy max for any single role in a diverse economy)\n for (const [role, share] of Object.entries(roleShares)) {\n if (share > 0.35) {\n return {\n violated: true,\n severity: 5,\n evidence: { role, share },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${role} at ${(share * 100).toFixed(0)}% — no crowding pressure detected. ` +\n 'Apply role-specific cost increase to simulate saturation.',\n },\n confidence: 0.70,\n estimatedLag: 10,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P7_NonSpecialistsSubsidiseSpecialists: Principle = {\n id: 'P7',\n name: 'Non-Specialists Subsidise Specialists in Zero-Sum Games',\n category: 'incentive',\n description:\n 'In zero-sum pools (arena, staking), the math only works if non-specialists ' +\n 'overpay relative to specialists. If the pool is >70% specialists, ' +\n 'there is no one left to subsidise and the pot drains.',\n check(metrics, _thresholds): PrincipleResult {\n const { populationByRole, poolSizes } = metrics;\n\n // Check: if arena pot exists, are Fighters overwhelming it?\n const arenaPot = poolSizes['arena'] ?? poolSizes['arenaPot'] ?? 0;\n if (arenaPot <= 0) return { violated: false };\n\n const fighters = populationByRole['Fighter'] ?? 0;\n const total = metrics.totalAgents;\n const fighterShare = fighters / Math.max(1, total);\n\n if (fighterShare > 0.70 && arenaPot < 100) {\n return {\n violated: true,\n severity: 6,\n evidence: { fighterShare, arenaPot },\n suggestedAction: {\n parameter: 'arenaEntryFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n 'Arena pot draining — too many specialists, not enough subsidising non-specialists. ' +\n 'Lower entry fee to attract diverse participants.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P8_RegulatorCannotFightDesign: Principle = {\n id: 'P8',\n name: 'Regulator Cannot Fight the Design',\n category: 'incentive',\n description:\n 'If the economy is designed to have a majority role (e.g. 55% Fighters), ' +\n 'the regulator must know this and exempt that role from population suppression. ' +\n 'AgentE at tick 1 seeing 55% Fighters and slashing arena rewards is overreach.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is mostly enforced by configuration (dominantRoles).\n // Here we detect a possible signal: dominant role's satisfaction is dropping\n // while their share is also dropping — both together suggest regulator overreach.\n const { roleShares, avgSatisfaction } = metrics;\n\n // If average satisfaction is low (<45) and some role dominates,\n // it may be suppression causing satisfaction decay\n if (avgSatisfaction < 45) {\n const dominantRole = Object.entries(roleShares).sort((a, b) => b[1] - a[1])[0];\n if (dominantRole && dominantRole[1] > 0.30) {\n return {\n violated: true,\n severity: 4,\n evidence: { dominantRole: dominantRole[0], share: dominantRole[1], avgSatisfaction },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Low satisfaction with ${dominantRole[0]} dominant. ` +\n 'Regulator may be suppressing a structurally necessary role. ' +\n 'Ease pressure on dominant role rewards.',\n },\n confidence: 0.55,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const INCENTIVE_PRINCIPLES: Principle[] = [\n P5_ProfitabilityIsCompetitive,\n P6_CrowdingMultiplierOnAllRoles,\n P7_NonSpecialistsSubsidiseSpecialists,\n P8_RegulatorCannotFightDesign,\n];\n","// P9-P11, P46: Population Dynamics Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P9_RoleSwitchingNeedsFriction: Principle = {\n id: 'P9',\n name: 'Role Switching Needs Friction',\n category: 'population',\n description:\n 'If >5% of the population switches roles in a single evaluation period, ' +\n 'it is a herd movement, not rational rebalancing. Without friction ' +\n '(satisfaction cost, cooldown), one good tick causes mass migration.',\n check(metrics, thresholds): PrincipleResult {\n const { churnByRole, roleShares } = metrics;\n\n // Heuristic: any single role that gained >5% share this period\n // We approximate from churnByRole — high churn in one role + gain in another\n const totalChurn = Object.values(churnByRole).reduce((s, v) => s + v, 0);\n if (totalChurn > thresholds.roleSwitchFrictionMax) {\n return {\n violated: true,\n severity: 5,\n evidence: { totalChurnRate: totalChurn, churnByRole },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `Role switch rate ${(totalChurn * 100).toFixed(1)}% exceeds friction threshold. ` +\n 'Increase production costs to slow herd movement.',\n },\n confidence: 0.65,\n estimatedLag: 20,\n };\n }\n\n // Also: if a role went from <10% to >30% very quickly (large share jump)\n // we can't detect this without a previous snapshot, so we rely on churn proxy above.\n void roleShares; // suppresses unused warning\n\n return { violated: false };\n },\n};\n\nexport const P10_SpawnWeightingUsesInversePopulation: Principle = {\n id: 'P10',\n name: 'Spawn Weighting Uses Inverse Population',\n category: 'population',\n description:\n 'New agents should preferentially fill the least-populated roles. ' +\n 'Flat spawn probability causes initial imbalances to compound.',\n check(metrics, _thresholds): PrincipleResult {\n const { roleShares } = metrics;\n if (Object.keys(roleShares).length === 0) return { violated: false };\n\n const shares = Object.values(roleShares);\n const mean = shares.reduce((s, v) => s + v, 0) / shares.length;\n // High variance in role shares is a signal that spawn is not balancing\n const variance = shares.reduce((s, v) => s + (v - mean) ** 2, 0) / shares.length;\n const stdDev = Math.sqrt(variance);\n\n if (stdDev > 0.20) {\n const minRole = Object.entries(roleShares).sort((a, b) => a[1] - b[1])[0];\n return {\n violated: true,\n severity: 4,\n evidence: { roleShares, stdDev, leastPopulatedRole: minRole?.[0] },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `High role share variance (σ=${stdDev.toFixed(2)}). ` +\n 'Spawn weighting may not be filling under-populated roles. ' +\n 'Increasing yield makes under-populated producer roles more attractive.',\n },\n confidence: 0.60,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P11_TwoTierPressure: Principle = {\n id: 'P11',\n name: 'Two-Tier Pressure (Continuous + Hard)',\n category: 'population',\n description:\n 'Corrections only at thresholds create delayed response. ' +\n 'Continuous gentle pressure (1% per tick toward ideal) plus hard cuts ' +\n 'for extreme cases catches imbalances early.',\n check(metrics, _thresholds): PrincipleResult {\n const { roleShares } = metrics;\n\n // Detect if any role is trending away from ideal for many ticks without correction\n // Proxy: if a role is >40% (hard threshold territory) it means continuous pressure failed\n for (const [role, share] of Object.entries(roleShares)) {\n if (share > 0.45) {\n return {\n violated: true,\n severity: 6,\n evidence: { role, share },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `${role} at ${(share * 100).toFixed(0)}% — continuous pressure was insufficient. ` +\n 'Hard intervention needed alongside resumed continuous pressure.',\n },\n confidence: 0.80,\n estimatedLag: 10,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P46_PersonaDiversity: Principle = {\n id: 'P46',\n name: 'Persona Diversity',\n category: 'population',\n description:\n 'Any single behavioral persona above 40% = monoculture. ' +\n 'Need at least 3 distinct persona clusters each above 15%.',\n check(metrics, thresholds): PrincipleResult {\n const { personaDistribution } = metrics;\n if (Object.keys(personaDistribution).length === 0) return { violated: false };\n\n // Check for monoculture\n for (const [persona, share] of Object.entries(personaDistribution)) {\n if (share > thresholds.personaMonocultureMax) {\n return {\n violated: true,\n severity: 5,\n evidence: { dominantPersona: persona, share, personaDistribution },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${persona} persona at ${(share * 100).toFixed(0)}% — behavioral monoculture. ` +\n 'Diversify reward structures to attract other persona types.',\n },\n confidence: 0.70,\n estimatedLag: 30,\n };\n }\n }\n\n // Check for minimum cluster count\n const significantClusters = Object.values(personaDistribution).filter(s => s >= 0.15).length;\n if (significantClusters < thresholds.personaMinClusters) {\n return {\n violated: true,\n severity: 3,\n evidence: { significantClusters, required: thresholds.personaMinClusters },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.05,\n reasoning:\n `Only ${significantClusters} significant persona clusters (need ${thresholds.personaMinClusters}). ` +\n 'Lower trade barriers to attract non-dominant persona types.',\n },\n confidence: 0.55,\n estimatedLag: 40,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const POPULATION_PRINCIPLES: Principle[] = [\n P9_RoleSwitchingNeedsFriction,\n P10_SpawnWeightingUsesInversePopulation,\n P11_TwoTierPressure,\n P46_PersonaDiversity,\n];\n","// P12-P16, P32: Currency Flow Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P12_OnePrimaryFaucet: Principle = {\n id: 'P12',\n name: 'One Primary Faucet',\n category: 'currency',\n description:\n 'Multiple independent currency sources (gathering + crafting + quests) each ' +\n 'creating gold causes uncontrolled inflation. One clear primary faucet ' +\n 'makes the economy predictable and auditable.',\n check(metrics, thresholds): PrincipleResult {\n const { netFlow, faucetVolume, sinkVolume } = metrics;\n\n if (netFlow > thresholds.netFlowWarnThreshold) {\n return {\n violated: true,\n severity: 5,\n evidence: { netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Net flow +${netFlow.toFixed(1)} g/t. Inflationary. ` +\n 'Increase crafting cost (primary sink) to balance faucet output.',\n },\n confidence: 0.80,\n estimatedLag: 8,\n };\n }\n\n if (netFlow < -thresholds.netFlowWarnThreshold) {\n return {\n violated: true,\n severity: 4,\n evidence: { netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Net flow ${netFlow.toFixed(1)} g/t. Deflationary. ` +\n 'Decrease crafting cost to ease sink pressure.',\n },\n confidence: 0.80,\n estimatedLag: 8,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P13_PotsAreZeroSumAndSelfRegulate: Principle = {\n id: 'P13',\n name: 'Pots Self-Regulate with Correct Multiplier',\n category: 'currency',\n description:\n 'Arena pot math: winRate × multiplier > (1 - houseCut) drains the pot. ' +\n 'At 65% win rate, multiplier must be ≤ 1.38. We use 1.5 for slight surplus buffer.',\n check(metrics, thresholds): PrincipleResult {\n const { poolSizes } = metrics;\n const arenaPot = poolSizes['arena'] ?? poolSizes['arenaPot'] ?? 0;\n\n // Pot is draining if it's near zero despite fights happening\n const fighters = metrics.populationByRole['Fighter'] ?? 0;\n if (fighters > 5 && arenaPot < 50) {\n // Estimate if the multiplier math is sustainable\n const { arenaWinRate, arenaHouseCut } = thresholds;\n const maxSustainableMultiplier = (1 - arenaHouseCut) / arenaWinRate;\n\n return {\n violated: true,\n severity: 7,\n evidence: { arenaPot, fighters, maxSustainableMultiplier },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Arena pot at ${arenaPot.toFixed(0)}g with ${fighters} fighters. ` +\n `Sustainable multiplier ≤ ${maxSustainableMultiplier.toFixed(2)}. ` +\n 'Reduce reward multiplier to prevent pot drain.',\n },\n confidence: 0.85,\n estimatedLag: 3,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P14_TrackActualInjection: Principle = {\n id: 'P14',\n name: 'Track Actual Gold Injection, Not Value Creation',\n category: 'currency',\n description:\n 'Counting resource gathering as \"gold injected\" is a lie. ' +\n 'Gold only enters when Fighters spawn (100-150g each). ' +\n 'Fake metrics break every downstream decision.',\n check(metrics, _thresholds): PrincipleResult {\n const { faucetVolume, netFlow, totalSupply } = metrics;\n\n // If faucetVolume is suspiciously large relative to any real injection mechanism\n // (spawning), flag for audit. Proxy: if supply grows faster than expected.\n const supplyGrowthRate = Math.abs(netFlow) / Math.max(1, totalSupply);\n\n if (supplyGrowthRate > 0.10) {\n return {\n violated: true,\n severity: 4,\n evidence: { faucetVolume, netFlow, supplyGrowthRate },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Supply growing at ${(supplyGrowthRate * 100).toFixed(1)}%/tick. ` +\n 'Verify gold injection tracking. Resources should not create gold directly.',\n },\n confidence: 0.55,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P15_PoolsNeedCapAndDecay: Principle = {\n id: 'P15',\n name: 'Pools Need Cap + Decay',\n category: 'currency',\n description:\n 'Any pool (bank, reward pool) without a cap accumulates infinitely. ' +\n 'Bank pool at 42% of gold supply means 42% of the economy is frozen. ' +\n 'Cap at 5%, decay at 2%/tick.',\n check(metrics, thresholds): PrincipleResult {\n const { poolSizes, totalSupply } = metrics;\n const { poolCapPercent } = thresholds;\n\n for (const [pool, size] of Object.entries(poolSizes)) {\n if (pool === 'arena' || pool === 'arenaPot') continue; // pot has different rules\n const shareOfSupply = size / Math.max(1, totalSupply);\n if (shareOfSupply > poolCapPercent * 2) { // trigger at 2× cap\n return {\n violated: true,\n severity: 6,\n evidence: { pool, size, shareOfSupply, cap: poolCapPercent },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${pool} pool at ${(shareOfSupply * 100).toFixed(1)}% of supply ` +\n `(cap: ${(poolCapPercent * 100).toFixed(0)}%). Gold frozen. ` +\n 'Lower fees to encourage circulation over accumulation.',\n },\n confidence: 0.85,\n estimatedLag: 5,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P16_WithdrawalPenaltyScales: Principle = {\n id: 'P16',\n name: 'Withdrawal Penalty Scales with Lock Duration',\n category: 'currency',\n description:\n 'A 50-tick lock period with a penalty calculated as /100 means agents can ' +\n 'exit after 1 tick and keep 99% of accrued yield. ' +\n 'Penalty must scale linearly: (1 - ticksStaked/lockDuration) × yield.',\n check(metrics, _thresholds): PrincipleResult {\n const { poolSizes, totalSupply } = metrics;\n const bankPool = poolSizes['bank'] ?? poolSizes['bankPool'] ?? 0;\n\n // If bank pool is small but staked gold is large, early withdrawal penalty is weak\n // (people staking but pulling out early, depleting the pool)\n const stakedEstimate = totalSupply * 0.15; // rough: if 15% staked is healthy\n if (bankPool < 10 && stakedEstimate > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: { bankPool, estimatedStaked: stakedEstimate },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n 'Bank pool depleted while significant gold should be staked. ' +\n 'Early withdrawals may be draining yield pool. ' +\n 'Ensure withdrawal penalty scales with lock duration.',\n },\n confidence: 0.45,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P32_VelocityAboveSupply: Principle = {\n id: 'P32',\n name: 'Velocity > Supply for Liquidity',\n category: 'currency',\n description:\n 'Low transactions despite adequate supply means liquidity is trapped. ' +\n 'High supply with low velocity = stagnation, not abundance.',\n check(metrics, _thresholds): PrincipleResult {\n const { velocity, totalSupply, supplyByResource } = metrics;\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n\n // Stagnation: resources exist, gold exists, but nobody is trading\n if (velocity < 3 && totalSupply > 100 && totalResources > 20) {\n return {\n violated: true,\n severity: 4,\n evidence: { velocity, totalSupply, totalResources },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.20,\n reasoning:\n `Velocity ${velocity}/t with ${totalResources} resources in system. ` +\n 'Economy stagnant despite available supply. Lower trading friction.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P58_NoNaturalNumeraire: Principle = {\n id: 'P58',\n name: 'No Natural Numéraire',\n category: 'currency',\n description:\n 'No single commodity naturally stabilizes as currency in barter-heavy economies. ' +\n 'Multiple items rotate as de facto units of account, but none locks in. ' +\n 'If a numéraire is needed, design and enforce it — emergence alone will not produce one.',\n check(metrics, _thresholds): PrincipleResult {\n const { prices, velocity, totalSupply } = metrics;\n\n // Detect barter-dominant economy: high trade velocity but most resources\n // have prices close to each other (no clear numéraire emerging)\n const priceValues = Object.values(prices).filter(p => p > 0);\n if (priceValues.length < 3) return { violated: false };\n\n const mean = priceValues.reduce((s, p) => s + p, 0) / priceValues.length;\n const coeffOfVariation = mean > 0\n ? Math.sqrt(\n priceValues.reduce((s, p) => s + (p - mean) ** 2, 0) / priceValues.length\n ) / mean\n : 0;\n\n // Low CoV = all items priced similarly = no emergent numéraire\n // Combined with high velocity = active barter economy\n if (coeffOfVariation < 0.25 && velocity > 5 && totalSupply > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: {\n coeffOfVariation,\n velocity,\n numResources: priceValues.length,\n meanPrice: mean,\n },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Price coefficient of variation ${coeffOfVariation.toFixed(2)} with velocity ${velocity.toFixed(1)}. ` +\n 'All items priced similarly in an active economy — no natural numéraire emerging. ' +\n 'If a designated currency exists, increase its sink demand to differentiate it.',\n },\n confidence: 0.50,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const CURRENCY_FLOW_PRINCIPLES: Principle[] = [\n P12_OnePrimaryFaucet,\n P13_PotsAreZeroSumAndSelfRegulate,\n P14_TrackActualInjection,\n P15_PoolsNeedCapAndDecay,\n P16_WithdrawalPenaltyScales,\n P32_VelocityAboveSupply,\n P58_NoNaturalNumeraire,\n];\n","// P17-P19: Bootstrap Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P17_GracePeriodBeforeIntervention: Principle = {\n id: 'P17',\n name: 'Grace Period Before Intervention',\n category: 'bootstrap',\n description:\n 'Any intervention before tick 50 is premature. The economy needs time to ' +\n 'bootstrap with designed distributions. AgentE intervening at tick 1 against ' +\n '55% Fighters (designed) killed the economy instantly.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is enforced in the AgentE pipeline itself (gracePeriod config).\n // Here we flag if grace period appears to have ended too early by checking:\n // low satisfaction at very early ticks.\n if (metrics.tick < 30 && metrics.avgSatisfaction < 40) {\n return {\n violated: true,\n severity: 7,\n evidence: { tick: metrics.tick, avgSatisfaction: metrics.avgSatisfaction },\n suggestedAction: {\n parameter: 'arenaEntryFee',\n direction: 'decrease',\n magnitude: 0.20,\n reasoning:\n `Very low satisfaction at tick ${metrics.tick}. ` +\n 'Intervention may have fired during grace period. ' +\n 'Ease all costs to let economy bootstrap.',\n },\n confidence: 0.70,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P18_FirstProducerNeedsStartingInventory: Principle = {\n id: 'P18',\n name: 'First Producer Needs Starting Inventory + Capital',\n category: 'bootstrap',\n description:\n 'A Crafter with 0 weapons and 0 gold must sell nothing to get gold before ' +\n 'they can buy ore. This creates a chicken-and-egg freeze. ' +\n 'Starting inventory (2 weapons + 4 ore + 40g) breaks the deadlock.',\n check(metrics, _thresholds): PrincipleResult {\n if (metrics.tick > 20) return { violated: false }; // bootstrap window over\n\n const weapons = metrics.supplyByResource['weapons'] ?? 0;\n const potions = metrics.supplyByResource['potions'] ?? 0;\n const crafters = metrics.populationByRole['Crafter'] ?? 0;\n const alchemists = metrics.populationByRole['Alchemist'] ?? 0;\n\n // If producers exist but their products don't, bootstrap inventory wasn't provided\n if ((crafters > 0 && weapons === 0) || (alchemists > 0 && potions === 0)) {\n return {\n violated: true,\n severity: 8,\n evidence: { tick: metrics.tick, weapons, potions, crafters, alchemists },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.50,\n reasoning:\n 'Bootstrap failure: producers have no products on tick 1-20. ' +\n 'Drastically reduce production cost to allow immediate output.',\n },\n confidence: 0.90,\n estimatedLag: 2,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P19_StartingSupplyExceedsDemand: Principle = {\n id: 'P19',\n name: 'Starting Supply Exceeds Initial Demand',\n category: 'bootstrap',\n description:\n 'Launch with more consumables than you think you need. ' +\n 'Early scarcity creates an AH gridlock where everyone wants to buy ' +\n 'and nobody has anything to sell.',\n check(metrics, _thresholds): PrincipleResult {\n if (metrics.tick > 30) return { violated: false }; // only relevant early\n\n const fighters = metrics.populationByRole['Fighter'] ?? 0;\n const weapons = metrics.supplyByResource['weapons'] ?? 0;\n const potions = metrics.supplyByResource['potions'] ?? 0;\n\n // Each fighter needs a weapon. If weapons < 50% of fighters at start, cold-start likely\n if (fighters > 5 && weapons < fighters * 0.5) {\n return {\n violated: true,\n severity: 6,\n evidence: { fighters, weapons, potions, weaponsPerFighter: weapons / Math.max(1, fighters) },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `${fighters} fighters but only ${weapons} weapons. Cold-start scarcity. ` +\n 'Boost arena reward to attract fighters even without weapons.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const BOOTSTRAP_PRINCIPLES: Principle[] = [\n P17_GracePeriodBeforeIntervention,\n P18_FirstProducerNeedsStartingInventory,\n P19_StartingSupplyExceedsDemand,\n];\n","// P20-P24: Feedback Loop Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P20_DecayPreventsAccumulation: Principle = {\n id: 'P20',\n name: 'Decay Prevents Accumulation',\n category: 'feedback',\n description:\n 'Resources without decay create infinite hoarding. ' +\n 'A Gatherer who never sells has 500 ore rotting in their pocket ' +\n 'while Crafters starve. 2-10% decay per period forces circulation.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, velocity, totalAgents } = metrics;\n\n // High supply + low velocity = hoarding, not abundance\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n const resourcesPerAgent = totalResources / Math.max(1, totalAgents);\n\n if (resourcesPerAgent > 20 && velocity < 3) {\n return {\n violated: true,\n severity: 4,\n evidence: { totalResources, resourcesPerAgent, velocity },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${totalResources.toFixed(0)} resources with velocity ${velocity}/t. ` +\n 'Likely hoarding. Reduce yield to increase scarcity and force circulation.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P21_PriceFromGlobalSupply: Principle = {\n id: 'P21',\n name: 'Price Reflects Global Supply, Not Just AH Listings',\n category: 'feedback',\n description:\n 'If prices only update from Auction House activity, agents with hoarded ' +\n 'inventory see artificially high prices and keep gathering when they should stop.',\n check(metrics, _thresholds): PrincipleResult {\n const { priceVolatility, supplyByResource, prices } = metrics;\n\n // High price volatility with stable supply = price disconnected from fundamentals\n for (const resource of Object.keys(prices)) {\n const volatility = priceVolatility[resource] ?? 0;\n const supply = supplyByResource[resource] ?? 0;\n\n if (volatility > 0.30 && supply > 30) {\n return {\n violated: true,\n severity: 3,\n evidence: { resource, volatility, supply, price: prices[resource] },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `${resource} price volatile (${(volatility * 100).toFixed(0)}%) despite supply ${supply}. ` +\n 'Price may not reflect global inventory. Increase trading friction to stabilise.',\n },\n confidence: 0.55,\n estimatedLag: 10,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P22_MarketAwarenessPreventsSurplus: Principle = {\n id: 'P22',\n name: 'Market Awareness Prevents Overproduction',\n category: 'feedback',\n description:\n 'Producers who craft without checking market prices will create surpluses ' +\n 'that crash prices. Agents need to see prices before deciding to produce.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, prices, productionIndex } = metrics;\n\n // Signal: weapons supply very high, weapon price very low, but Crafters still producing\n const weapons = supplyByResource['weapons'] ?? 0;\n const weaponPrice = prices['weapons'] ?? 0;\n const healthyWeaponPrice = 30; // approximate floor\n\n if (weapons > 100 && weaponPrice < healthyWeaponPrice * 0.5 && productionIndex > 0) {\n return {\n violated: true,\n severity: 4,\n evidence: { weapons, weaponPrice, productionIndex },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${weapons} weapons with price ${weaponPrice.toFixed(0)}g but still producing. ` +\n 'Producers appear unaware of market. Raise production cost to slow output.',\n },\n confidence: 0.70,\n estimatedLag: 8,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P23_ProfitabilityFactorsFeasibility: Principle = {\n id: 'P23',\n name: 'Profitability Factors Execution Feasibility',\n category: 'feedback',\n description:\n 'An agent who calculates profit = weapon_price - ore_cost but has no gold ' +\n 'to buy ore is chasing phantom profit. ' +\n 'Feasibility (can I afford the inputs?) must be part of the profitability calc.',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, blockedAgentCount, totalAgents } = metrics;\n\n const blockedFraction = blockedAgentCount / Math.max(1, totalAgents);\n if (blockedFraction > 0.20 && avgSatisfaction < 60) {\n return {\n violated: true,\n severity: 5,\n evidence: { blockedFraction, blockedAgentCount, avgSatisfaction },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `${(blockedFraction * 100).toFixed(0)}% of agents blocked with low satisfaction. ` +\n 'Agents may have roles they cannot afford to execute. ' +\n 'Lower production costs to restore feasibility.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P24_BlockedAgentsDecayFaster: Principle = {\n id: 'P24',\n name: 'Blocked Agents Decay Faster',\n category: 'feedback',\n description:\n 'An agent who cannot perform their preferred activity loses satisfaction faster ' +\n 'and churns sooner. Blocked agents must be identified and unblocked, ' +\n 'or they become silent bottlenecks that skew churn data.',\n check(metrics, thresholds): PrincipleResult {\n const { blockedAgentCount, totalAgents, churnRate } = metrics;\n const blockedFraction = blockedAgentCount / Math.max(1, totalAgents);\n\n if (blockedFraction > thresholds.blockedAgentMaxFraction) {\n return {\n violated: true,\n severity: 5,\n evidence: { blockedFraction, blockedAgentCount, churnRate },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `${(blockedFraction * 100).toFixed(0)}% of agents blocked. ` +\n 'Blocked agents churn silently, skewing metrics. ' +\n 'Lower fees to unblock market participation.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const FEEDBACK_LOOP_PRINCIPLES: Principle[] = [\n P20_DecayPreventsAccumulation,\n P21_PriceFromGlobalSupply,\n P22_MarketAwarenessPreventsSurplus,\n P23_ProfitabilityFactorsFeasibility,\n P24_BlockedAgentsDecayFaster,\n];\n","// P25-P28, P38: Regulator Behavior Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P25_CorrectLeversForCorrectProblems: Principle = {\n id: 'P25',\n name: 'Target the Correct Lever',\n category: 'regulator',\n description:\n 'Adjusting sinks for supply-side inflation is wrong. ' +\n 'Inflation from too much gathering → reduce mining yield. ' +\n 'Inflation from pot payout → reduce reward multiplier. ' +\n 'Matching lever to cause prevents oscillation.',\n check(metrics, thresholds): PrincipleResult {\n const { netFlow, supplyByResource } = metrics;\n\n // Heuristic: if net flow is high AND raw material supply is very high,\n // gathering is the primary source — correct lever is miningYield, not fees\n const ore = supplyByResource['ore'] ?? 0;\n const wood = supplyByResource['wood'] ?? 0;\n const resourceFlood = ore + wood > 100;\n\n if (netFlow > thresholds.netFlowWarnThreshold && resourceFlood) {\n return {\n violated: true,\n severity: 4,\n evidence: { netFlow, ore, wood },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Inflation with raw material backlog (ore ${ore}, wood ${wood}). ` +\n 'Root cause is gathering. Correct lever: miningYield, not fees.',\n },\n confidence: 0.75,\n estimatedLag: 8,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P26_ContinuousPressureBeatsThresholdCuts: Principle = {\n id: 'P26',\n name: 'Continuous 1%/tick > One-Time 10% Cut',\n category: 'regulator',\n description:\n 'Large one-time adjustments cause overshoot and oscillation. ' +\n '1% per tick for 10 ticks reaches the same destination with far less disruption. ' +\n 'This principle is enforced by maxAdjustmentPercent in the Planner.',\n check(metrics, thresholds): PrincipleResult {\n // Detect oscillation: if a metric swings back and forth with high amplitude\n // Proxy: if net flow alternates sign significantly in recent history\n // (This would need history — for now we check the current state for oscillation signals)\n\n const { inflationRate } = metrics;\n // Rapid sign change in inflationRate with large magnitude suggests overcorrection\n if (Math.abs(inflationRate) > 0.20) {\n return {\n violated: true,\n severity: 4,\n evidence: { inflationRate },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: inflationRate > 0 ? 'increase' : 'decrease',\n magnitude: Math.min(thresholds.maxAdjustmentPercent, 0.05), // force smaller step\n reasoning:\n `Inflation rate ${(inflationRate * 100).toFixed(1)}% — possible oscillation. ` +\n 'Apply smaller correction to avoid overshoot.',\n },\n confidence: 0.60,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P27_AdjustmentsNeedCooldowns: Principle = {\n id: 'P27',\n name: 'Adjustments Need Cooldowns',\n category: 'regulator',\n description:\n 'Adjusting the same parameter twice in a window causes oscillation. ' +\n 'Minimum 15 ticks between same-parameter adjustments. ' +\n 'This is enforced in the Planner but checked here as a diagnostic.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is enforced structurally by the Planner.\n // As a diagnostic, we flag if churn rate is high AND satisfaction is volatile\n // (which correlates with oscillating economy from rapid adjustments)\n const { churnRate, avgSatisfaction } = metrics;\n\n if (churnRate > 0.08 && avgSatisfaction < 50) {\n return {\n violated: true,\n severity: 4,\n evidence: { churnRate, avgSatisfaction },\n suggestedAction: {\n parameter: 'arenaEntryFee',\n direction: 'decrease',\n magnitude: 0.05,\n reasoning:\n `High churn (${(churnRate * 100).toFixed(1)}%) with low satisfaction. ` +\n 'Possible oscillation from rapid adjustments. Apply small correction only.',\n },\n confidence: 0.50,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P28_StructuralDominanceIsNotPathological: Principle = {\n id: 'P28',\n name: 'Structural Dominance ≠ Pathological Monopoly',\n category: 'regulator',\n description:\n 'A designed Fighter majority (55%) should not trigger population suppression. ' +\n 'AgentE must distinguish between \"this role is dominant BY DESIGN\" (configured via ' +\n 'dominantRoles) and \"this role took over unexpectedly\".',\n check(metrics, _thresholds): PrincipleResult {\n // This is enforced by the dominantRoles config.\n // As a check: if the most dominant role has high satisfaction,\n // it's likely structural (they're thriving in their designed role), not pathological.\n const { roleShares, avgSatisfaction } = metrics;\n\n const dominant = Object.entries(roleShares).sort((a, b) => b[1] - a[1])[0];\n if (!dominant) return { violated: false };\n\n const [dominantRole, dominantShare] = dominant;\n // Healthy structural dominance: high share + high satisfaction\n if (dominantShare > 0.40 && avgSatisfaction > 70) {\n // Not a violation — this is healthy structural dominance\n return { violated: false };\n }\n\n // Pathological: high share + low satisfaction (agents trapped, not thriving)\n if (dominantShare > 0.40 && avgSatisfaction < 50) {\n return {\n violated: true,\n severity: 5,\n evidence: { dominantRole, dominantShare, avgSatisfaction },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${dominantRole} dominant (${(dominantShare * 100).toFixed(0)}%) with low satisfaction. ` +\n 'Pathological dominance — agents trapped, not thriving. ' +\n 'Ease costs to allow role switching.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P38_CommunicationPreventsRevolt: Principle = {\n id: 'P38',\n name: 'Communication Prevents Revolt',\n category: 'regulator',\n description:\n 'Every adjustment must be logged with reasoning. ' +\n 'An adjustment made without explanation to players causes revolt. ' +\n 'AgentE logs every decision — this principle checks that logging is active.',\n check(metrics, _thresholds): PrincipleResult {\n // This is structurally enforced by DecisionLog. As a diagnostic,\n // we check if churn spiked without any corresponding logged decision.\n // Since we can't access the log here, this is a light sanity check.\n const { churnRate } = metrics;\n if (churnRate > 0.10) {\n return {\n violated: true,\n severity: 3,\n evidence: { churnRate },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `High churn (${(churnRate * 100).toFixed(1)}%) — agents leaving. ` +\n 'Ensure all recent adjustments are logged with reasoning to diagnose cause.',\n },\n confidence: 0.50,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const REGULATOR_PRINCIPLES: Principle[] = [\n P25_CorrectLeversForCorrectProblems,\n P26_ContinuousPressureBeatsThresholdCuts,\n P27_AdjustmentsNeedCooldowns,\n P28_StructuralDominanceIsNotPathological,\n P38_CommunicationPreventsRevolt,\n];\n","// P29-P30: Market Dynamics Principles (from Machinations/Naavik research)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P29_PinchPoint: Principle = {\n id: 'P29',\n name: 'Pinch Point',\n category: 'market_dynamics',\n description:\n 'Every economy has a resource that constrains all downstream activity. ' +\n 'In AgentE v0: weapons are the pinch point (Fighters need them, Crafters make them). ' +\n 'If demand drops → oversupply. If frustration rises → undersupply.',\n check(metrics, _thresholds): PrincipleResult {\n const { pinchPoints, supplyByResource, demandSignals } = metrics;\n\n // Check each resource marked as a pinch point\n for (const [resource, status] of Object.entries(pinchPoints)) {\n if (status === 'scarce') {\n const supply = supplyByResource[resource] ?? 0;\n const demand = demandSignals[resource] ?? 0;\n return {\n violated: true,\n severity: 7,\n evidence: { resource, supply, demand, status },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `${resource} is a pinch point and currently SCARCE (supply ${supply}, demand ${demand}). ` +\n 'Reduce production cost to increase throughput.',\n },\n confidence: 0.80,\n estimatedLag: 5,\n };\n }\n\n if (status === 'oversupplied') {\n const supply = supplyByResource[resource] ?? 0;\n return {\n violated: true,\n severity: 4,\n evidence: { resource, supply, status },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${resource} is a pinch point and OVERSUPPLIED (supply ${supply}). ` +\n 'Raise production cost to reduce surplus.',\n },\n confidence: 0.70,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P30_MovingPinchPoint: Principle = {\n id: 'P30',\n name: 'Moving Pinch Point',\n category: 'market_dynamics',\n description:\n 'Player progression shifts the demand curve. A static pinch point that ' +\n 'works at level 1 will be cleared at level 10. The pinch point must move ' +\n 'with the player to maintain ongoing scarcity and engagement.',\n check(metrics, _thresholds): PrincipleResult {\n const { capacityUsage, supplyByResource, avgSatisfaction } = metrics;\n\n // Signal: very high capacity usage + high supply of all resources\n // = economy has \"outrun\" the pinch point (everything is easy to get)\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n const resourcesPerAgent = totalResources / Math.max(1, metrics.totalAgents);\n\n if (capacityUsage > 0.90 && resourcesPerAgent > 15 && avgSatisfaction > 75) {\n // High satisfaction + abundant resources = pinch point cleared, no challenge\n return {\n violated: true,\n severity: 3,\n evidence: { capacityUsage, resourcesPerAgent, avgSatisfaction },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n 'Economy operating at full capacity with abundant resources and high satisfaction. ' +\n 'Pinch point may have been cleared. Increase production cost to restore scarcity.',\n },\n confidence: 0.55,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P57_CombinatorialPriceSpace: Principle = {\n id: 'P57',\n name: 'Combinatorial Price Space',\n category: 'market_dynamics',\n description:\n 'N tradeable items generate (N−1)N/2 relative prices. With thousands of items ' +\n 'no single agent can track them all. Design for distributed self-organization, ' +\n 'not centralized pricing.',\n check(metrics, thresholds): PrincipleResult {\n const { prices, priceVolatility } = metrics;\n\n const priceKeys = Object.keys(prices);\n const n = priceKeys.length;\n const relativePriceCount = (n * (n - 1)) / 2;\n\n if (n < 2) return { violated: false };\n\n // Count how many relative prices have converged (low volatility on both sides)\n let convergedPairs = 0;\n for (let i = 0; i < priceKeys.length; i++) {\n for (let j = i + 1; j < priceKeys.length; j++) {\n const volA = priceVolatility[priceKeys[i]!] ?? 0;\n const volB = priceVolatility[priceKeys[j]!] ?? 0;\n // Both items stable = pair converged\n if (volA < 0.20 && volB < 0.20) {\n convergedPairs++;\n }\n }\n }\n\n const convergenceRate = convergedPairs / Math.max(1, relativePriceCount);\n\n if (convergenceRate < thresholds.relativePriceConvergenceTarget && n >= 4) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n totalItems: n,\n relativePriceCount,\n convergedPairs,\n convergenceRate,\n target: thresholds.relativePriceConvergenceTarget,\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Only ${(convergenceRate * 100).toFixed(0)}% of ${relativePriceCount} relative prices ` +\n `have converged (target: ${(thresholds.relativePriceConvergenceTarget * 100).toFixed(0)}%). ` +\n 'Price space too complex for distributed discovery. Lower friction to help.',\n },\n confidence: 0.55,\n estimatedLag: thresholds.priceDiscoveryWindowTicks,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const MARKET_DYNAMICS_PRINCIPLES: Principle[] = [\n P29_PinchPoint,\n P30_MovingPinchPoint,\n P57_CombinatorialPriceSpace,\n];\n","// P31, P41: Measurement Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P31_AnchorValueTracking: Principle = {\n id: 'P31',\n name: 'Anchor Value Tracking',\n category: 'measurement',\n description:\n '1 hour of play = X gold = Y items. If this ratio drifts, the economy ' +\n 'is inflating or deflating in ways that players feel before metrics catch it. ' +\n 'Track the ratio constantly.',\n check(metrics, _thresholds): PrincipleResult {\n const { anchorRatioDrift, inflationRate } = metrics;\n\n if (Math.abs(anchorRatioDrift) > 0.25) {\n return {\n violated: true,\n severity: 5,\n evidence: { anchorRatioDrift, inflationRate },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: anchorRatioDrift > 0 ? 'increase' : 'decrease',\n magnitude: 0.10,\n reasoning:\n `Anchor ratio has drifted ${(anchorRatioDrift * 100).toFixed(0)}% from baseline. ` +\n 'Time-to-value for players is changing. Adjust production costs to restore.',\n },\n confidence: 0.65,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P41_MultiResolutionMonitoring: Principle = {\n id: 'P41',\n name: 'Multi-Resolution Monitoring',\n category: 'measurement',\n description:\n 'Single-resolution monitoring misses crises that develop slowly (coarse only) ' +\n 'or explode suddenly (fine only). Monitor at fine (per-tick), medium ' +\n '(per-10-ticks), and coarse (per-100-ticks) simultaneously.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is enforced structurally by MetricStore.\n // As a diagnostic: if gini is climbing but satisfaction is still high,\n // a coarse-only monitor would miss the early warning.\n const { giniCoefficient, avgSatisfaction } = metrics;\n\n if (giniCoefficient > 0.50 && avgSatisfaction > 65) {\n // Gini rising but agents still happy — coarse monitor would not trigger.\n // Fine monitor catches it early.\n return {\n violated: true,\n severity: 4,\n evidence: { giniCoefficient, avgSatisfaction },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} rising despite okay satisfaction. ` +\n 'Early warning from fine-resolution monitoring. ' +\n 'Raise trading fees to slow wealth concentration before it hurts satisfaction.',\n },\n confidence: 0.70,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P55_ArbitrageThermometer: Principle = {\n id: 'P55',\n name: 'Arbitrage Thermometer',\n category: 'measurement',\n description:\n 'A virtual economy is never in true equilibrium — it oscillates around it. ' +\n 'The aggregate arbitrage window across relative prices is a live health metric: ' +\n 'rising arbitrage signals destabilization, falling signals recovery.',\n check(metrics, thresholds): PrincipleResult {\n const { arbitrageIndex } = metrics;\n\n if (arbitrageIndex > thresholds.arbitrageIndexCritical) {\n return {\n violated: true,\n severity: 7,\n evidence: {\n arbitrageIndex,\n warning: thresholds.arbitrageIndexWarning,\n critical: thresholds.arbitrageIndexCritical,\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Arbitrage index ${arbitrageIndex.toFixed(2)} exceeds critical threshold ` +\n `(${thresholds.arbitrageIndexCritical}). Relative prices are diverging — ` +\n 'economy destabilizing. Lower trading friction to accelerate price convergence.',\n },\n confidence: 0.75,\n estimatedLag: 8,\n };\n }\n\n if (arbitrageIndex > thresholds.arbitrageIndexWarning) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n arbitrageIndex,\n warning: thresholds.arbitrageIndexWarning,\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.08,\n reasoning:\n `Arbitrage index ${arbitrageIndex.toFixed(2)} above warning threshold ` +\n `(${thresholds.arbitrageIndexWarning}). Early sign of price divergence. ` +\n 'Gently reduce friction to support self-correction.',\n },\n confidence: 0.65,\n estimatedLag: 12,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P59_GiftEconomyNoise: Principle = {\n id: 'P59',\n name: 'Gift-Economy Noise',\n category: 'measurement',\n description:\n 'Non-market exchanges — gifts, charity trades, social signaling — contaminate ' +\n 'price signals. Filter gift-like and below-market transactions before computing ' +\n 'economic indicators.',\n check(metrics, thresholds): PrincipleResult {\n const { giftTradeRatio } = metrics;\n\n if (giftTradeRatio > thresholds.giftTradeFilterRatio) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n giftTradeRatio,\n threshold: thresholds.giftTradeFilterRatio,\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `${(giftTradeRatio * 100).toFixed(0)}% of trades are gift-like (price = 0 or <30% market). ` +\n `Exceeds filter threshold (${(thresholds.giftTradeFilterRatio * 100).toFixed(0)}%). ` +\n 'Price signals contaminated. Slightly raise trading fees to discourage zero-value listings. ' +\n 'ADVISORY: Consider filtering sub-market trades from price index computation.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const MEASUREMENT_PRINCIPLES: Principle[] = [\n P31_AnchorValueTracking,\n P41_MultiResolutionMonitoring,\n P55_ArbitrageThermometer,\n P59_GiftEconomyNoise,\n];\n","// P42-P43: Statistical Balancing Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P42_TheMedianPrinciple: Principle = {\n id: 'P42',\n name: 'The Median Principle',\n category: 'statistical',\n description:\n 'When (mean - median) / median > 0.3, mean is a lie. ' +\n 'A few whales with 10,000g raise the mean while most agents have 50g. ' +\n 'Always balance to median when divergence exceeds 30%.',\n check(metrics, thresholds): PrincipleResult {\n const { meanMedianDivergence, giniCoefficient } = metrics;\n\n if (meanMedianDivergence > thresholds.meanMedianDivergenceMax) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n meanMedianDivergence,\n giniCoefficient,\n meanBalance: metrics.meanBalance,\n medianBalance: metrics.medianBalance,\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Mean/median divergence ${(meanMedianDivergence * 100).toFixed(0)}% ` +\n `(threshold: ${(thresholds.meanMedianDivergenceMax * 100).toFixed(0)}%). ` +\n 'Economy has outliers skewing metrics. Use median for decisions. ' +\n 'Raise auction fees to redistribute wealth.',\n },\n confidence: 0.85,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P43_SimulationMinimum: Principle = {\n id: 'P43',\n name: 'Simulation Minimum (100 Iterations)',\n category: 'statistical',\n description:\n 'Fewer than 100 Monte Carlo iterations produces unreliable predictions. ' +\n 'The variance of a 10-iteration simulation is so high that you might as well ' +\n 'be guessing. This principle enforces the minimum in the Simulator.',\n check(metrics, thresholds): PrincipleResult {\n // This is enforced structurally by the Simulator (iterations >= 100).\n // As a diagnostic: if inflationRate is oscillating wildly, it may indicate\n // decisions were made on insufficient simulation data.\n const { inflationRate } = metrics;\n\n if (Math.abs(inflationRate) > 0.30) {\n return {\n violated: true,\n severity: 3,\n evidence: { inflationRate, minIterations: thresholds.simulationMinIterations },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: inflationRate > 0 ? 'increase' : 'decrease',\n magnitude: 0.05,\n reasoning:\n `Large inflation rate swing (${(inflationRate * 100).toFixed(0)}%). ` +\n `Ensure all decisions use ≥${thresholds.simulationMinIterations} simulation iterations. ` +\n 'Apply conservative correction.',\n },\n confidence: 0.50,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const STATISTICAL_PRINCIPLES: Principle[] = [\n P42_TheMedianPrinciple,\n P43_SimulationMinimum,\n];\n","// P39, P44: System Dynamics Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P39_TheLagPrinciple: Principle = {\n id: 'P39',\n name: 'The Lag Principle',\n category: 'system_dynamics',\n description:\n 'Total lag = 3-5× observation interval. If you observe every 5 ticks, ' +\n 'expect effects after 15-25 ticks. Adjusting again before lag expires = overshoot. ' +\n 'This is enforced by the Planner but diagnosed here.',\n check(metrics, thresholds): PrincipleResult {\n const { inflationRate, netFlow } = metrics;\n\n // Detect overshoot pattern: inflation flips direction rapidly\n // Proxy: net flow is in opposite direction to inflation rate\n const inflationPositive = inflationRate > 0.05;\n const netFlowNegative = netFlow < -5;\n const inflationNegative = inflationRate < -0.05;\n const netFlowPositive = netFlow > 5;\n\n const oscillating =\n (inflationPositive && netFlowNegative) || (inflationNegative && netFlowPositive);\n\n if (oscillating) {\n const lagMin = thresholds.lagMultiplierMin;\n const lagMax = thresholds.lagMultiplierMax;\n return {\n violated: true,\n severity: 5,\n evidence: { inflationRate, netFlow, lagRange: [lagMin, lagMax] },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'increase',\n magnitude: 0.03, // very small — oscillation means over-adjusting\n reasoning:\n 'Inflation and net flow moving in opposite directions — overshoot pattern. ' +\n `Wait for lag to resolve (${lagMin}-${lagMax}× observation interval). ` +\n 'Apply minimal correction only.',\n },\n confidence: 0.65,\n estimatedLag: thresholds.lagMultiplierMax * 5, // conservative\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P44_ComplexityBudget: Principle = {\n id: 'P44',\n name: 'Complexity Budget',\n category: 'system_dynamics',\n description:\n 'More than 20 active adjustable parameters → exponential debugging cost. ' +\n 'Each parameter that affects <5% of a core metric should be pruned. ' +\n 'AgentE tracks active parameters and flags when budget exceeded.',\n check(metrics, thresholds): PrincipleResult {\n // This is enforced by the Planner's parameter tracking.\n // As a diagnostic: if many custom metrics are registered with low correlation\n // to core metrics, complexity budget is likely exceeded.\n // Simple proxy: if there are many custom metrics with small values, flag.\n const customMetricCount = Object.keys(metrics.custom).length;\n\n if (customMetricCount > thresholds.complexityBudgetMax) {\n return {\n violated: true,\n severity: 3,\n evidence: { customMetricCount, budgetMax: thresholds.complexityBudgetMax },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.01,\n reasoning:\n `${customMetricCount} custom metrics tracked (budget: ${thresholds.complexityBudgetMax}). ` +\n 'Consider pruning low-impact parameters. ' +\n 'Applying minimal correction to avoid adding complexity.',\n },\n confidence: 0.40,\n estimatedLag: 0,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const SYSTEM_DYNAMICS_PRINCIPLES: Principle[] = [\n P39_TheLagPrinciple,\n P44_ComplexityBudget,\n];\n","// P35, P40, P49: Resource Management Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P35_DestructionCreatesValue: Principle = {\n id: 'P35',\n name: 'Destruction Creates Value',\n category: 'resource',\n description:\n 'If nothing is ever permanently lost, inflation is inevitable. ' +\n 'Weapon durability (breaks after 3 fights), potion consumption on use, ' +\n 'and ore costs for crafting are all destruction mechanisms. ' +\n 'Without them, supply grows without bound.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, sinkVolume, netFlow } = metrics;\n\n // High supply of consumables + low sink volume = destruction not working\n const weapons = supplyByResource['weapons'] ?? 0;\n const potions = supplyByResource['potions'] ?? 0;\n\n if ((weapons > 200 || potions > 200) && sinkVolume < 5 && netFlow > 0) {\n return {\n violated: true,\n severity: 6,\n evidence: { weapons, potions, sinkVolume, netFlow },\n suggestedAction: {\n parameter: 'arenaEntryFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${weapons} weapons + ${potions} potions with low destruction (sink ${sinkVolume}/t). ` +\n 'Consumables not being consumed. Lower arena entry to increase weapon/potion usage.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P40_ReplacementRate: Principle = {\n id: 'P40',\n name: 'Replacement Rate ≥ 2× Consumption',\n category: 'resource',\n description:\n 'Respawn/production rate must be at least 2× consumption rate for equilibrium. ' +\n 'At 1× you drift toward depletion. At 2× you have a buffer for demand spikes.',\n check(metrics, thresholds): PrincipleResult {\n const { productionIndex, sinkVolume } = metrics;\n\n if (sinkVolume > 0 && productionIndex > 0) { // skip if production not tracked (productionIndex=0)\n const replacementRatio = productionIndex / sinkVolume;\n if (replacementRatio < 1.0) {\n return {\n violated: true,\n severity: 6,\n evidence: { productionIndex, sinkVolume, replacementRatio },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Replacement rate ${replacementRatio.toFixed(2)} (need ≥${thresholds.replacementRateMultiplier}). ` +\n 'Production below consumption. Resources will deplete. Increase yield.',\n },\n confidence: 0.80,\n estimatedLag: 5,\n };\n } else if (replacementRatio > thresholds.replacementRateMultiplier * 3) {\n return {\n violated: true,\n severity: 3,\n evidence: { productionIndex, sinkVolume, replacementRatio },\n suggestedAction: {\n parameter: 'miningYield',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Replacement rate ${replacementRatio.toFixed(2)} — overproducing. ` +\n 'Production far exceeds consumption. Reduce yield to prevent glut.',\n },\n confidence: 0.70,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P49_IdleAssetTax: Principle = {\n id: 'P49',\n name: 'Idle Asset Tax',\n category: 'resource',\n description:\n 'Appreciating assets without holding cost → wealth concentration. ' +\n 'If hoarding an asset makes you richer just by holding it, everyone hoards. ' +\n 'Decay rates, storage costs, or expiry are \"idle asset taxes\" that force circulation.',\n check(metrics, _thresholds): PrincipleResult {\n const { giniCoefficient, top10PctShare, velocity } = metrics;\n\n // High Gini + low velocity + high top-10% share = idle asset hoarding\n if (giniCoefficient > 0.55 && top10PctShare > 0.60 && velocity < 5) {\n return {\n violated: true,\n severity: 5,\n evidence: { giniCoefficient, top10PctShare, velocity },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)}, top 10% hold ${(top10PctShare * 100).toFixed(0)}%, velocity ${velocity}. ` +\n 'Wealth concentrated in idle assets. Raise trading costs to simulate holding tax.',\n },\n confidence: 0.70,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const RESOURCE_MGMT_PRINCIPLES: Principle[] = [\n P35_DestructionCreatesValue,\n P40_ReplacementRate,\n P49_IdleAssetTax,\n];\n","// P33, P37, P45, P50: Player Experience Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P33_FairNotEqual: Principle = {\n id: 'P33',\n name: 'Fair ≠ Equal',\n category: 'player_experience',\n description:\n 'Gini = 0 is boring — everyone has the same and there is nothing to strive for. ' +\n 'Healthy inequality from skill/effort is fine. Inequality from money (pay-to-win) ' +\n 'is toxic. Target Gini 0.3-0.45: meaningful spread, not oligarchy.',\n check(metrics, thresholds): PrincipleResult {\n const { giniCoefficient } = metrics;\n\n if (giniCoefficient < 0.10) {\n return {\n violated: true,\n severity: 3,\n evidence: { giniCoefficient },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} — near-perfect equality. Economy lacks stakes. ` +\n 'Increase winner rewards to create meaningful spread.',\n },\n confidence: 0.60,\n estimatedLag: 20,\n };\n }\n\n if (giniCoefficient > thresholds.giniRedThreshold) {\n return {\n violated: true,\n severity: 7,\n evidence: { giniCoefficient },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} — oligarchy level. Toxic inequality. ` +\n 'Raise transaction fees to redistribute wealth from rich to pool.',\n },\n confidence: 0.85,\n estimatedLag: 10,\n };\n }\n\n if (giniCoefficient > thresholds.giniWarnThreshold) {\n return {\n violated: true,\n severity: 4,\n evidence: { giniCoefficient },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} — high inequality warning. ` +\n 'Gently raise fees to slow wealth concentration.',\n },\n confidence: 0.75,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P36_MechanicFrictionDetector: Principle = {\n id: 'P36',\n name: 'Mechanic Friction Detector',\n category: 'player_experience',\n description:\n 'Deterministic + probabilistic systems → expectation mismatch. ' +\n 'When crafting is guaranteed but combat is random, players feel betrayed by ' +\n 'the random side. Mix mechanics carefully or segregate them entirely.',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, churnRate, velocity } = metrics;\n\n // Proxy: High churn despite reasonable economic activity suggests\n // frustration with mechanic mismatch rather than economic problems\n // (Activity exists but players leave anyway = not economic, likely mechanic friction)\n if (churnRate > 0.10 && avgSatisfaction < 50 && velocity > 3) {\n return {\n violated: true,\n severity: 5,\n evidence: { churnRate, avgSatisfaction, velocity },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Churn ${(churnRate * 100).toFixed(1)}% with satisfaction ${avgSatisfaction.toFixed(0)} ` +\n 'despite active economy (velocity ' + velocity.toFixed(1) + '). ' +\n 'Suggests mechanic friction (deterministic vs random systems). ' +\n 'Increase rewards to compensate for perceived unfairness. ' +\n 'ADVISORY: Review if mixing guaranteed and probabilistic mechanics.',\n },\n confidence: 0.55,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P37_LatecommerProblem: Principle = {\n id: 'P37',\n name: 'Latecomer Problem',\n category: 'player_experience',\n description:\n 'A new participant must reach viability in reasonable time. ' +\n 'If all the good roles are saturated and prices are high, ' +\n 'new agents cannot contribute and churn immediately.',\n check(metrics, _thresholds): PrincipleResult {\n const { timeToValue, avgSatisfaction, churnRate } = metrics;\n\n // High churn + low satisfaction + slow time-to-value = latecomer problem\n if (churnRate > 0.08 && avgSatisfaction < 55 && timeToValue > 20) {\n return {\n violated: true,\n severity: 6,\n evidence: { timeToValue, avgSatisfaction, churnRate },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `New agents taking ${timeToValue} ticks to reach viability. ` +\n `Churn ${(churnRate * 100).toFixed(1)}%, satisfaction ${avgSatisfaction.toFixed(0)}. ` +\n 'Lower production costs to help new participants contribute faster.',\n },\n confidence: 0.70,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P45_TimeBudget: Principle = {\n id: 'P45',\n name: 'Time Budget',\n category: 'player_experience',\n description:\n 'required_time ≤ available_time × 0.8. If the economy requires more engagement ' +\n 'than participants can realistically give, it is a disguised paywall. ' +\n 'The 0.8 buffer accounts for real life.',\n check(metrics, thresholds): PrincipleResult {\n const { timeToValue, avgSatisfaction } = metrics;\n\n // If time to value is very high AND satisfaction is dropping,\n // the economy demands too much time\n const timePressure = timeToValue > 30;\n const dissatisfied = avgSatisfaction < 55;\n\n if (timePressure && dissatisfied) {\n return {\n violated: true,\n severity: 5,\n evidence: { timeToValue, avgSatisfaction, timeBudgetRatio: thresholds.timeBudgetRatio },\n suggestedAction: {\n parameter: 'arenaEntryFee',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Time-to-value ${timeToValue} ticks with ${avgSatisfaction.toFixed(0)} satisfaction. ` +\n 'Economy requires too much time investment. Lower barriers to participation.',\n },\n confidence: 0.65,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P50_PayPowerRatio: Principle = {\n id: 'P50',\n name: 'Pay-Power Ratio',\n category: 'player_experience',\n description:\n 'spender / non-spender power ratio > 2.0 = pay-to-win territory. ' +\n 'Target 1.5 (meaningful advantage without shutting out non-payers). ' +\n 'Above 2.0, non-paying participants start leaving.',\n check(metrics, thresholds): PrincipleResult {\n const { top10PctShare, giniCoefficient } = metrics;\n\n // Proxy for pay-power: if top 10% hold disproportionate wealth AND gini is high,\n // wealth advantage is likely translating to power advantage\n const wealthToTopFraction = top10PctShare;\n\n if (wealthToTopFraction > 0.70 && giniCoefficient > 0.55) {\n return {\n violated: true,\n severity: 6,\n evidence: {\n top10PctShare,\n giniCoefficient,\n threshold: thresholds.payPowerRatioMax,\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `Top 10% hold ${(top10PctShare * 100).toFixed(0)}% of wealth (Gini ${giniCoefficient.toFixed(2)}). ` +\n 'Wealth advantage may exceed pay-power ratio threshold. ' +\n 'Redistribute via higher trading fees.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const PLAYER_EXPERIENCE_PRINCIPLES: Principle[] = [\n P33_FairNotEqual,\n P36_MechanicFrictionDetector,\n P37_LatecommerProblem,\n P45_TimeBudget,\n P50_PayPowerRatio,\n];\n","// P34, P47-P48: Open Economy Principles (DeFi / blockchain contexts)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P34_ExtractionRatio: Principle = {\n id: 'P34',\n name: 'Extraction Ratio',\n category: 'open_economy',\n description:\n 'If >65% of participants are net extractors (taking value out without putting it in), ' +\n 'the economy needs external subsidy (new user influx) to survive. ' +\n 'Above 65%, any slowdown in new users collapses the economy.',\n check(metrics, thresholds): PrincipleResult {\n const { extractionRatio } = metrics;\n if (isNaN(extractionRatio)) return { violated: false }; // not tracked for this economy\n\n if (extractionRatio > thresholds.extractionRatioRed) {\n return {\n violated: true,\n severity: 8,\n evidence: { extractionRatio, threshold: thresholds.extractionRatioRed },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.25,\n reasoning:\n `Extraction ratio ${(extractionRatio * 100).toFixed(0)}% (critical: ${(thresholds.extractionRatioRed * 100).toFixed(0)}%). ` +\n 'Economy is extraction-heavy and subsidy-dependent. ' +\n 'Raise fees to increase the cost of extraction.',\n },\n confidence: 0.85,\n estimatedLag: 10,\n };\n }\n\n if (extractionRatio > thresholds.extractionRatioYellow) {\n return {\n violated: true,\n severity: 5,\n evidence: { extractionRatio, threshold: thresholds.extractionRatioYellow },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Extraction ratio ${(extractionRatio * 100).toFixed(0)}% (warning: ${(thresholds.extractionRatioYellow * 100).toFixed(0)}%). ` +\n 'Economy trending toward extraction-heavy. Apply early pressure.',\n },\n confidence: 0.75,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P47_SmokeTest: Principle = {\n id: 'P47',\n name: 'Smoke Test',\n category: 'open_economy',\n description:\n 'intrinsic_utility_value / total_market_value < 0.3 = economy is >70% speculation. ' +\n 'If utility value drops below 10%, a single bad week can collapse the entire market. ' +\n 'Real utility (weapons that help you fight, potions that heal) must anchor value.',\n check(metrics, thresholds): PrincipleResult {\n const { smokeTestRatio } = metrics;\n if (isNaN(smokeTestRatio)) return { violated: false };\n\n if (smokeTestRatio < thresholds.smokeTestCritical) {\n return {\n violated: true,\n severity: 9,\n evidence: { smokeTestRatio, threshold: thresholds.smokeTestCritical },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `Utility/market ratio ${(smokeTestRatio * 100).toFixed(0)}% (critical). ` +\n 'Economy is >90% speculative. Collapse risk is extreme. ' +\n 'Increase utility rewards to anchor real value.',\n },\n confidence: 0.90,\n estimatedLag: 20,\n };\n }\n\n if (smokeTestRatio < thresholds.smokeTestWarning) {\n return {\n violated: true,\n severity: 6,\n evidence: { smokeTestRatio, threshold: thresholds.smokeTestWarning },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Utility/market ratio ${(smokeTestRatio * 100).toFixed(0)}% (warning). ` +\n 'Economy is >70% speculative. Boost utility rewards to restore intrinsic value anchor.',\n },\n confidence: 0.75,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P48_CurrencyInsulation: Principle = {\n id: 'P48',\n name: 'Currency Insulation',\n category: 'open_economy',\n description:\n 'Gameplay economy correlation with external markets > 0.5 = insulation failure. ' +\n 'When your in-game gold price tracks ETH/USD, external market crashes destroy ' +\n 'in-game economies. Good design insulates the two.',\n check(metrics, thresholds): PrincipleResult {\n const { currencyInsulation } = metrics;\n if (isNaN(currencyInsulation)) return { violated: false };\n\n if (currencyInsulation > thresholds.currencyInsulationMax) {\n return {\n violated: true,\n severity: 6,\n evidence: { currencyInsulation, threshold: thresholds.currencyInsulationMax },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Currency correlation with external market: ${(currencyInsulation * 100).toFixed(0)}% ` +\n `(max: ${(thresholds.currencyInsulationMax * 100).toFixed(0)}%). ` +\n 'Economy is exposed to external market shocks. ' +\n 'Increase internal friction to reduce external correlation.',\n },\n confidence: 0.70,\n estimatedLag: 30,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const OPEN_ECONOMY_PRINCIPLES: Principle[] = [\n P34_ExtractionRatio,\n P47_SmokeTest,\n P48_CurrencyInsulation,\n];\n","// P51-P54: LiveOps Principles (from Naavik research)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P51_SharkTooth: Principle = {\n id: 'P51',\n name: 'Shark Tooth Pattern',\n category: 'liveops',\n description:\n 'Each event peak should be ≥95% of the previous peak. ' +\n 'If peaks are shrinking (shark tooth becoming flat), event fatigue is setting in. ' +\n 'If valleys are deepening, the off-event economy is failing to sustain engagement.',\n check(metrics, thresholds): PrincipleResult {\n const { sharkToothPeaks, sharkToothValleys } = metrics;\n if (sharkToothPeaks.length < 2) return { violated: false };\n\n const lastPeak = sharkToothPeaks[sharkToothPeaks.length - 1] ?? 0;\n const prevPeak = sharkToothPeaks[sharkToothPeaks.length - 2] ?? 0;\n\n if (prevPeak > 0 && lastPeak / prevPeak < thresholds.sharkToothPeakDecay) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n lastPeak,\n prevPeak,\n ratio: lastPeak / prevPeak,\n threshold: thresholds.sharkToothPeakDecay,\n },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Peak engagement dropped to ${(lastPeak / prevPeak * 100).toFixed(0)}% of previous peak ` +\n `(threshold: ${(thresholds.sharkToothPeakDecay * 100).toFixed(0)}%). Event fatigue detected. ` +\n 'Boost event rewards to restore peak engagement.',\n },\n confidence: 0.75,\n estimatedLag: 30,\n };\n }\n\n if (sharkToothValleys.length >= 2) {\n const lastValley = sharkToothValleys[sharkToothValleys.length - 1] ?? 0;\n const prevValley = sharkToothValleys[sharkToothValleys.length - 2] ?? 0;\n if (prevValley > 0 && lastValley / prevValley < thresholds.sharkToothValleyDecay) {\n return {\n violated: true,\n severity: 4,\n evidence: { lastValley, prevValley, ratio: lastValley / prevValley },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n 'Between-event engagement declining (deepening valleys). ' +\n 'Base economy not sustaining participants between events. ' +\n 'Lower production costs to improve off-event value.',\n },\n confidence: 0.65,\n estimatedLag: 20,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P52_EndowmentEffect: Principle = {\n id: 'P52',\n name: 'Endowment Effect',\n category: 'liveops',\n description:\n 'Players who never owned premium items do not value them. ' +\n 'Free trial events that let players experience premium items drive conversions ' +\n 'because ownership creates perceived value (endowment effect).',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, churnRate } = metrics;\n\n // Proxy: if event completion is high but satisfaction is still low,\n // events are not creating the endowment effect (players complete but don't value the rewards)\n const { eventCompletionRate } = metrics;\n if (isNaN(eventCompletionRate)) return { violated: false };\n\n if (eventCompletionRate > 0.90 && avgSatisfaction < 60) {\n return {\n violated: true,\n severity: 4,\n evidence: { eventCompletionRate, avgSatisfaction, churnRate },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `${(eventCompletionRate * 100).toFixed(0)}% event completion but satisfaction only ${avgSatisfaction.toFixed(0)}. ` +\n 'Events not creating perceived value. Increase reward quality/quantity.',\n },\n confidence: 0.60,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P53_EventCompletionRate: Principle = {\n id: 'P53',\n name: 'Event Completion Rate Sweet Spot',\n category: 'liveops',\n description:\n 'Free completion at 60-80% is the sweet spot. ' +\n '<40% = predatory design. >80% = no monetization pressure. ' +\n '100% free = zero reason to ever spend.',\n check(metrics, thresholds): PrincipleResult {\n const { eventCompletionRate } = metrics;\n if (isNaN(eventCompletionRate)) return { violated: false };\n\n if (eventCompletionRate < thresholds.eventCompletionMin) {\n return {\n violated: true,\n severity: 6,\n evidence: {\n eventCompletionRate,\n min: thresholds.eventCompletionMin,\n max: thresholds.eventCompletionMax,\n },\n suggestedAction: {\n parameter: 'craftingCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Event completion rate ${(eventCompletionRate * 100).toFixed(0)}% — predatory territory ` +\n `(min: ${(thresholds.eventCompletionMin * 100).toFixed(0)}%). ` +\n 'Too hard for free players. Lower barriers to participation.',\n },\n confidence: 0.80,\n estimatedLag: 10,\n };\n }\n\n if (eventCompletionRate > thresholds.eventCompletionMax) {\n return {\n violated: true,\n severity: 3,\n evidence: { eventCompletionRate, max: thresholds.eventCompletionMax },\n suggestedAction: {\n parameter: 'arenaEntryFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `Event completion rate ${(eventCompletionRate * 100).toFixed(0)}% — no monetization pressure ` +\n `(max: ${(thresholds.eventCompletionMax * 100).toFixed(0)}%). ` +\n 'Slightly raise costs to create meaningful premium differentiation.',\n },\n confidence: 0.55,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P54_LiveOpsCadence: Principle = {\n id: 'P54',\n name: 'LiveOps Cadence',\n category: 'liveops',\n description:\n '>50% of events that are re-wrapped existing content → staleness. ' +\n 'The cadence must include genuinely new content at regular intervals. ' +\n 'This is an advisory principle — AgentE can flag but cannot fix content.',\n check(metrics, _thresholds): PrincipleResult {\n // Proxy: declining engagement velocity over time = staleness\n const { velocity, avgSatisfaction } = metrics;\n\n if (velocity < 2 && avgSatisfaction < 55 && metrics.tick > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: { velocity, avgSatisfaction, tick: metrics.tick },\n suggestedAction: {\n parameter: 'arenaReward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n 'Low velocity and satisfaction after long runtime. ' +\n 'Possible content staleness. Increase rewards as bridge while ' +\n 'new content is developed (developer action required).',\n },\n confidence: 0.40,\n estimatedLag: 30,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P56_ContentDropShock: Principle = {\n id: 'P56',\n name: 'Content-Drop Shock',\n category: 'liveops',\n description:\n 'Every new-item injection shatters existing price equilibria — arbitrage spikes ' +\n 'as participants re-price. Build cooldown windows for price discovery before ' +\n 'measuring post-drop economic health.',\n check(metrics, thresholds): PrincipleResult {\n const { contentDropAge, arbitrageIndex } = metrics;\n\n // Only fires during the cooldown window after a content drop\n if (contentDropAge > 0 && contentDropAge <= thresholds.contentDropCooldownTicks) {\n if (arbitrageIndex > thresholds.postDropArbitrageMax) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n contentDropAge,\n arbitrageIndex,\n cooldownTicks: thresholds.contentDropCooldownTicks,\n postDropMax: thresholds.postDropArbitrageMax,\n },\n suggestedAction: {\n parameter: 'auctionFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Content drop ${contentDropAge} ticks ago — arbitrage at ${arbitrageIndex.toFixed(2)} ` +\n `exceeds post-drop max (${thresholds.postDropArbitrageMax}). ` +\n 'Price discovery struggling. Lower trading friction temporarily.',\n },\n confidence: 0.60,\n estimatedLag: 5,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const LIVEOPS_PRINCIPLES: Principle[] = [\n P51_SharkTooth,\n P52_EndowmentEffect,\n P53_EventCompletionRate,\n P54_LiveOpsCadence,\n P56_ContentDropShock,\n];\n","import { SUPPLY_CHAIN_PRINCIPLES } from './supply-chain.js';\nimport { INCENTIVE_PRINCIPLES } from './incentives.js';\nimport { POPULATION_PRINCIPLES } from './population.js';\nimport { CURRENCY_FLOW_PRINCIPLES } from './currency-flow.js';\nimport { BOOTSTRAP_PRINCIPLES } from './bootstrap.js';\nimport { FEEDBACK_LOOP_PRINCIPLES } from './feedback-loops.js';\nimport { REGULATOR_PRINCIPLES } from './regulator.js';\nimport { MARKET_DYNAMICS_PRINCIPLES } from './market-dynamics.js';\nimport { MEASUREMENT_PRINCIPLES } from './measurement.js';\nimport { STATISTICAL_PRINCIPLES } from './statistical.js';\nimport { SYSTEM_DYNAMICS_PRINCIPLES } from './system-dynamics.js';\nimport { RESOURCE_MGMT_PRINCIPLES } from './resource-mgmt.js';\nimport { PLAYER_EXPERIENCE_PRINCIPLES } from './player-experience.js';\nimport { OPEN_ECONOMY_PRINCIPLES } from './open-economy.js';\nimport { LIVEOPS_PRINCIPLES } from './liveops.js';\nimport type { Principle } from '../types.js';\n\nexport * from './supply-chain.js';\nexport * from './incentives.js';\nexport * from './population.js';\nexport * from './currency-flow.js';\nexport * from './bootstrap.js';\nexport * from './feedback-loops.js';\nexport * from './regulator.js';\nexport * from './market-dynamics.js';\nexport * from './measurement.js';\nexport * from './statistical.js';\nexport * from './system-dynamics.js';\nexport * from './resource-mgmt.js';\nexport * from './player-experience.js';\nexport * from './open-economy.js';\nexport * from './liveops.js';\n\n/** All 60 built-in principles in priority order (supply chain → liveops) */\nexport const ALL_PRINCIPLES: Principle[] = [\n ...SUPPLY_CHAIN_PRINCIPLES, // P1-P4, P60\n ...INCENTIVE_PRINCIPLES, // P5-P8\n ...POPULATION_PRINCIPLES, // P9-P11, P46\n ...CURRENCY_FLOW_PRINCIPLES, // P12-P16, P32, P58\n ...BOOTSTRAP_PRINCIPLES, // P17-P19\n ...FEEDBACK_LOOP_PRINCIPLES, // P20-P24\n ...REGULATOR_PRINCIPLES, // P25-P28, P38\n ...MARKET_DYNAMICS_PRINCIPLES, // P29-P30, P57\n ...MEASUREMENT_PRINCIPLES, // P31, P41, P55, P59\n ...STATISTICAL_PRINCIPLES, // P42-P43\n ...SYSTEM_DYNAMICS_PRINCIPLES, // P39, P44\n ...RESOURCE_MGMT_PRINCIPLES, // P35, P40, P49\n ...PLAYER_EXPERIENCE_PRINCIPLES, // P33, P36, P37, P45, P50\n ...OPEN_ECONOMY_PRINCIPLES, // P34, P47-P48\n ...LIVEOPS_PRINCIPLES, // P51-P54, P56\n];\n","// Stage 3: Simulator — forward Monte Carlo projection before any action is applied\n// The single biggest architectural addition in V1 (vs V0's intuition-based adjustments)\n\nimport type {\n EconomyMetrics,\n SuggestedAction,\n SimulationResult,\n SimulationOutcome,\n Thresholds,\n} from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { Diagnoser } from './Diagnoser.js';\nimport { ALL_PRINCIPLES } from './principles/index.js';\n\nexport class Simulator {\n private diagnoser = new Diagnoser(ALL_PRINCIPLES);\n private beforeViolationsCache = new Map<number, Set<string>>();\n\n /**\n * Simulate the effect of applying `action` to the current economy forward `forwardTicks`.\n * Runs `iterations` Monte Carlo trials and returns the outcome distribution.\n *\n * The inner model is intentionally lightweight — it models how key metrics evolve\n * under a parameter change using simplified dynamics. This is not a full agent simulation;\n * it is a fast inner model that catches obvious over/under-corrections.\n */\n simulate(\n action: SuggestedAction,\n currentMetrics: EconomyMetrics,\n thresholds: Thresholds,\n iterations: number = 100,\n forwardTicks: number = 20,\n ): SimulationResult {\n const actualIterations = Math.max(thresholds.simulationMinIterations, iterations);\n const outcomes: EconomyMetrics[] = [];\n\n for (let i = 0; i < actualIterations; i++) {\n const projected = this.runForward(currentMetrics, action, forwardTicks, thresholds);\n outcomes.push(projected);\n }\n\n // Sort outcomes by avgSatisfaction to compute percentiles\n const sorted = [...outcomes].sort((a, b) => a.avgSatisfaction - b.avgSatisfaction);\n const p10 = sorted[Math.floor(actualIterations * 0.10)] ?? emptyMetrics();\n const p50 = sorted[Math.floor(actualIterations * 0.50)] ?? emptyMetrics();\n const p90 = sorted[Math.floor(actualIterations * 0.90)] ?? emptyMetrics();\n const mean = this.averageMetrics(outcomes);\n\n // Validate: does p50 improve the diagnosed issue?\n const netImprovement = this.checkImprovement(currentMetrics, p50, action);\n\n // Validate: does the action create new principle violations not present before?\n // Cache beforeViolations per tick to avoid redundant diagnose() calls\n const tick = currentMetrics.tick;\n let beforeViolations = this.beforeViolationsCache.get(tick);\n if (!beforeViolations) {\n beforeViolations = new Set(\n this.diagnoser.diagnose(currentMetrics, thresholds).map(d => d.principle.id),\n );\n this.beforeViolationsCache.set(tick, beforeViolations);\n }\n const afterViolations = new Set(\n this.diagnoser.diagnose(p50, thresholds).map(d => d.principle.id),\n );\n const newViolations = [...afterViolations].filter(id => !beforeViolations.has(id));\n const noNewProblems = newViolations.length === 0;\n\n // Confidence interval on avgSatisfaction\n const satisfactions = outcomes.map(o => o.avgSatisfaction);\n const meanSat = satisfactions.reduce((s, v) => s + v, 0) / satisfactions.length;\n const stdDev = Math.sqrt(\n satisfactions.reduce((s, v) => s + (v - meanSat) ** 2, 0) / satisfactions.length,\n );\n const ci: [number, number] = [meanSat - 1.96 * stdDev, meanSat + 1.96 * stdDev];\n\n // Lag estimation: P39 — effect visible after 3-5× observation interval\n const estimatedEffectTick =\n currentMetrics.tick + thresholds.lagMultiplierMin * 5;\n\n // Overshoot risk: how often does p90 overshoot relative to p50?\n const overshootRisk = sorted\n .slice(Math.floor(actualIterations * 0.80))\n .filter(m => Math.abs(m.netFlow) > Math.abs(currentMetrics.netFlow) * 2).length\n / (actualIterations * 0.20);\n\n return {\n proposedAction: action,\n iterations: actualIterations,\n forwardTicks,\n outcomes: { p10, p50, p90, mean } as SimulationOutcome,\n netImprovement,\n noNewProblems,\n confidenceInterval: ci,\n estimatedEffectTick,\n overshootRisk: Math.min(1, overshootRisk),\n };\n }\n\n /**\n * Lightweight forward model: apply action then project key metrics forward.\n * Uses simplified dynamics — not a full agent replay.\n */\n private runForward(\n metrics: EconomyMetrics,\n action: SuggestedAction,\n ticks: number,\n _thresholds: Thresholds,\n ): EconomyMetrics {\n // Apply the action effect as a multiplier on the relevant metric\n const multiplier = this.actionMultiplier(action);\n\n // Add stochastic noise (Monte Carlo element)\n const noise = () => 1 + (Math.random() - 0.5) * 0.1;\n\n let supply = metrics.totalSupply;\n let satisfaction = metrics.avgSatisfaction;\n let gini = metrics.giniCoefficient;\n let velocity = metrics.velocity;\n let netFlow = metrics.netFlow;\n const churnRate = metrics.churnRate;\n\n for (let t = 0; t < ticks; t++) {\n // Apply action effect on net flow (most actions affect flow)\n const effectOnFlow = this.flowEffect(action, metrics) * multiplier * noise();\n netFlow = netFlow * 0.9 + effectOnFlow * 0.1; // smooth convergence\n\n // Supply drifts with net flow\n supply += netFlow * noise();\n supply = Math.max(0, supply);\n\n // Satisfaction improves when net flow is balanced and supply is stable\n const satDelta = netFlow > 0 && netFlow < 20 ? 0.5 : netFlow < 0 ? -1 : 0;\n satisfaction = Math.min(100, Math.max(0, satisfaction + satDelta * noise()));\n\n // Gini slowly reverts (market pressure)\n gini = gini * 0.99 + 0.35 * 0.01 * noise(); // drift toward 0.35\n\n // Velocity follows supply (more money = more trading)\n velocity = (supply / Math.max(1, metrics.totalAgents)) * 0.01 * noise();\n\n // Agent churn reduces population over time\n const agentLoss = metrics.totalAgents * churnRate * noise();\n void agentLoss; // tracked but not used in simplified model\n }\n\n const projected: EconomyMetrics = {\n ...metrics,\n tick: metrics.tick + ticks,\n totalSupply: supply,\n netFlow,\n velocity,\n giniCoefficient: Math.max(0, Math.min(1, gini)),\n avgSatisfaction: satisfaction,\n inflationRate: metrics.totalSupply > 0 ? (supply - metrics.totalSupply) / metrics.totalSupply : 0,\n };\n\n return projected;\n }\n\n private actionMultiplier(action: SuggestedAction): number {\n const base = action.magnitude ?? 0.10;\n return action.direction === 'increase' ? 1 + base : 1 - base;\n }\n\n private flowEffect(action: SuggestedAction, metrics: EconomyMetrics): number {\n // Rough model: which parameters affect net flow, and in which direction?\n const { parameter, direction } = action;\n const sign = direction === 'increase' ? -1 : 1; // increase cost = reduce flow\n\n if (parameter === 'craftingCost' || parameter === 'alchemyCost') {\n return sign * metrics.netFlow * 0.2;\n }\n if (parameter === 'auctionFee') {\n return sign * metrics.velocity * 10 * 0.1;\n }\n if (parameter === 'arenaEntryFee') {\n return sign * (metrics.populationByRole['Fighter'] ?? 0) * 0.5;\n }\n if (parameter === 'arenaReward') {\n return -sign * (metrics.populationByRole['Fighter'] ?? 0) * 0.3;\n }\n if (parameter === 'miningYield' || parameter === 'lumberYield') {\n return sign * metrics.faucetVolume * 0.15;\n }\n return sign * metrics.netFlow * 0.1;\n }\n\n private checkImprovement(\n before: EconomyMetrics,\n after: EconomyMetrics,\n action: SuggestedAction,\n ): boolean {\n // Net improvement: key metrics should be trending better\n const satisfactionImproved = after.avgSatisfaction >= before.avgSatisfaction - 2;\n const flowMoreBalanced = Math.abs(after.netFlow) <= Math.abs(before.netFlow) * 1.2;\n const notWorseGini = after.giniCoefficient <= before.giniCoefficient + 0.05;\n void action; // could be used for targeted checks\n return satisfactionImproved && flowMoreBalanced && notWorseGini;\n }\n\n private averageMetrics(outcomes: EconomyMetrics[]): EconomyMetrics {\n if (outcomes.length === 0) return emptyMetrics();\n const base = { ...outcomes[0]! };\n const avg = (key: keyof EconomyMetrics) => {\n const vals = outcomes.map(o => o[key] as number).filter(v => typeof v === 'number' && !isNaN(v));\n return vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n };\n return {\n ...base,\n totalSupply: avg('totalSupply'),\n netFlow: avg('netFlow'),\n velocity: avg('velocity'),\n giniCoefficient: avg('giniCoefficient'),\n avgSatisfaction: avg('avgSatisfaction'),\n inflationRate: avg('inflationRate'),\n };\n }\n}\n","// Stage 4: Planner — converts validated diagnosis into a concrete, constrained action plan\n\nimport type {\n Diagnosis,\n ActionPlan,\n Thresholds,\n EconomyMetrics,\n SimulationResult,\n} from './types.js';\n\ninterface ParameterConstraint {\n min: number;\n max: number;\n}\n\nexport class Planner {\n private lockedParams = new Set<string>();\n private constraints = new Map<string, ParameterConstraint>();\n private cooldowns = new Map<string, number>(); // param → last-applied-tick\n private activePlanCount = 0;\n\n lock(param: string): void {\n this.lockedParams.add(param);\n }\n\n unlock(param: string): void {\n this.lockedParams.delete(param);\n }\n\n constrain(param: string, constraint: ParameterConstraint): void {\n this.constraints.set(param, constraint);\n }\n\n /**\n * Convert a diagnosis into an ActionPlan.\n * Returns null if:\n * - parameter is locked\n * - parameter is still in cooldown\n * - simulation result failed\n * - complexity budget exceeded\n */\n plan(\n diagnosis: Diagnosis,\n metrics: EconomyMetrics,\n simulationResult: SimulationResult,\n currentParams: Record<string, number>,\n thresholds: Thresholds,\n ): ActionPlan | null {\n const action = diagnosis.violation.suggestedAction;\n const param = action.parameter;\n\n // Hard checks\n if (this.lockedParams.has(param)) return null;\n if (this.isOnCooldown(param, metrics.tick, thresholds.cooldownTicks)) return null;\n if (!simulationResult.netImprovement) return null;\n if (!simulationResult.noNewProblems) return null;\n\n // Complexity budget (P44)\n if (this.activePlanCount >= thresholds.complexityBudgetMax) return null;\n\n // Compute target value\n const currentValue = currentParams[param] ?? 1.0;\n const magnitude = Math.min(action.magnitude ?? 0.10, thresholds.maxAdjustmentPercent);\n let targetValue: number;\n\n if (action.direction === 'set' && action.absoluteValue !== undefined) {\n targetValue = action.absoluteValue;\n } else if (action.direction === 'increase') {\n targetValue = currentValue * (1 + magnitude);\n } else {\n targetValue = currentValue * (1 - magnitude);\n }\n\n // Apply constraints\n const constraint = this.constraints.get(param);\n if (constraint) {\n targetValue = Math.max(constraint.min, Math.min(constraint.max, targetValue));\n }\n\n // Don't plan if target === current (nothing to do)\n if (Math.abs(targetValue - currentValue) < 0.001) return null;\n\n const estimatedLag =\n diagnosis.violation.estimatedLag ?? simulationResult.estimatedEffectTick - metrics.tick;\n\n const plan: ActionPlan = {\n id: `plan_${metrics.tick}_${param}`,\n diagnosis,\n parameter: param,\n currentValue,\n targetValue,\n maxChangePercent: thresholds.maxAdjustmentPercent,\n cooldownTicks: thresholds.cooldownTicks,\n rollbackCondition: {\n metric: 'avgSatisfaction',\n direction: 'below',\n threshold: Math.max(20, metrics.avgSatisfaction - 10), // rollback if sat drops >10 pts\n checkAfterTick: metrics.tick + estimatedLag + 3,\n },\n simulationResult,\n estimatedLag,\n };\n\n return plan;\n }\n\n recordApplied(plan: ActionPlan, tick: number): void {\n this.cooldowns.set(plan.parameter, tick);\n this.activePlanCount++;\n }\n\n recordRolledBack(_plan: ActionPlan): void {\n this.activePlanCount = Math.max(0, this.activePlanCount - 1);\n }\n\n isOnCooldown(param: string, currentTick: number, cooldownTicks: number): boolean {\n const lastApplied = this.cooldowns.get(param);\n if (lastApplied === undefined) return false;\n return currentTick - lastApplied < cooldownTicks;\n }\n\n /** Reset all cooldowns (useful for testing) */\n resetCooldowns(): void {\n this.cooldowns.clear();\n }\n}\n","// Stage 5: Executor — applies actions to the host system and monitors rollback conditions\n\nimport type { ActionPlan, EconomyMetrics, EconomyAdapter } from './types.js';\n\nexport type ExecutionResult = 'applied' | 'rolled_back' | 'rollback_skipped';\n\ninterface ActivePlan {\n plan: ActionPlan;\n originalValue: number;\n}\n\nexport class Executor {\n private activePlans: ActivePlan[] = [];\n\n async apply(\n plan: ActionPlan,\n adapter: EconomyAdapter,\n currentParams: Record<string, number>,\n ): Promise<void> {\n const originalValue = currentParams[plan.parameter] ?? plan.currentValue;\n await adapter.setParam(plan.parameter, plan.targetValue);\n plan.appliedAt = plan.diagnosis.tick;\n\n this.activePlans.push({ plan, originalValue });\n }\n\n /**\n * Check all active plans for rollback conditions.\n * Called every tick after metrics are computed.\n * Returns list of plans that were rolled back.\n */\n async checkRollbacks(\n metrics: EconomyMetrics,\n adapter: EconomyAdapter,\n ): Promise<ActionPlan[]> {\n const rolledBack: ActionPlan[] = [];\n const remaining: ActivePlan[] = [];\n\n for (const active of this.activePlans) {\n const { plan, originalValue } = active;\n const rc = plan.rollbackCondition;\n\n // Not ready to check yet\n if (metrics.tick < rc.checkAfterTick) {\n remaining.push(active);\n continue;\n }\n\n // Check rollback condition\n const metricValue = this.getMetricValue(metrics, rc.metric);\n const shouldRollback =\n rc.direction === 'below'\n ? metricValue < rc.threshold\n : metricValue > rc.threshold;\n\n if (shouldRollback) {\n // Undo the adjustment\n await adapter.setParam(plan.parameter, originalValue);\n rolledBack.push(plan);\n // Don't push to remaining — remove from tracking\n } else {\n // Plan has passed its check window — consider it settled\n const settledTick = rc.checkAfterTick + 10;\n if (metrics.tick > settledTick) {\n // Plan is settled, stop tracking\n } else {\n remaining.push(active);\n }\n }\n }\n\n this.activePlans = remaining;\n return rolledBack;\n }\n\n private getMetricValue(metrics: EconomyMetrics, metricPath: string): number {\n // Support dotted paths like 'poolSizes.arena' or 'custom.myMetric'\n const parts = metricPath.split('.');\n let value: unknown = metrics;\n for (const part of parts) {\n if (value !== null && typeof value === 'object') {\n value = (value as Record<string, unknown>)[part];\n } else {\n return NaN;\n }\n }\n return typeof value === 'number' ? value : NaN;\n }\n\n getActivePlans(): ActionPlan[] {\n return this.activePlans.map(a => a.plan);\n }\n}\n","// Full-transparency decision logging\n// Every decision AgentE makes is logged with diagnosis, plan, simulation proof, and outcome\n\nimport type { DecisionEntry, DecisionResult, Diagnosis, ActionPlan, EconomyMetrics } from './types.js';\n\nexport class DecisionLog {\n private entries: DecisionEntry[] = [];\n private maxEntries: number;\n\n constructor(maxEntries = 1000) {\n this.maxEntries = maxEntries;\n }\n\n record(\n diagnosis: Diagnosis,\n plan: ActionPlan,\n result: DecisionResult,\n metrics: EconomyMetrics,\n ): DecisionEntry {\n const entry: DecisionEntry = {\n id: `decision_${metrics.tick}_${plan.parameter}`,\n tick: metrics.tick,\n timestamp: Date.now(),\n diagnosis,\n plan,\n result,\n reasoning: this.buildReasoning(diagnosis, plan, result),\n metricsSnapshot: metrics,\n };\n\n this.entries.unshift(entry); // newest first\n if (this.entries.length > this.maxEntries) {\n this.entries.pop();\n }\n\n return entry;\n }\n\n recordSkip(\n diagnosis: Diagnosis,\n result: DecisionResult,\n metrics: EconomyMetrics,\n reason: string,\n ): void {\n const entry: DecisionEntry = {\n id: `skip_${metrics.tick}_${diagnosis.principle.id}`,\n tick: metrics.tick,\n timestamp: Date.now(),\n diagnosis,\n plan: this.stubPlan(diagnosis, metrics),\n result,\n reasoning: reason,\n metricsSnapshot: metrics,\n };\n this.entries.unshift(entry);\n if (this.entries.length > this.maxEntries) this.entries.pop();\n }\n\n query(filter?: {\n since?: number;\n until?: number;\n issue?: string;\n parameter?: string;\n result?: DecisionResult;\n }): DecisionEntry[] {\n return this.entries.filter(e => {\n if (filter?.since !== undefined && e.tick < filter.since) return false;\n if (filter?.until !== undefined && e.tick > filter.until) return false;\n if (filter?.issue && e.diagnosis.principle.id !== filter.issue) return false;\n if (filter?.parameter && e.plan.parameter !== filter.parameter) return false;\n if (filter?.result && e.result !== filter.result) return false;\n return true;\n });\n }\n\n latest(n = 30): DecisionEntry[] {\n return this.entries.slice(0, n);\n }\n\n export(format: 'json' | 'text' = 'json'): string {\n if (format === 'text') {\n return this.entries\n .map(e => `[Tick ${e.tick}] ${e.result.toUpperCase()} — ${e.reasoning}`)\n .join('\\n');\n }\n return JSON.stringify(this.entries, null, 2);\n }\n\n private buildReasoning(\n diagnosis: Diagnosis,\n plan: ActionPlan,\n result: DecisionResult,\n ): string {\n const sim = plan.simulationResult;\n const simSummary =\n `Simulation (${sim.iterations} iterations, ${sim.forwardTicks} ticks forward): ` +\n `p50 satisfaction ${sim.outcomes.p50.avgSatisfaction.toFixed(0)}, ` +\n `net improvement ${sim.netImprovement}, ` +\n `no new problems ${sim.noNewProblems}, ` +\n `overshoot risk ${(sim.overshootRisk * 100).toFixed(0)}%.`;\n\n const actionSummary =\n `[${diagnosis.principle.id}] ${diagnosis.principle.name}: ` +\n `${plan.parameter} ${plan.currentValue.toFixed(3)} → ${plan.targetValue.toFixed(3)}. ` +\n `Severity ${diagnosis.violation.severity}/10, confidence ${(diagnosis.violation.confidence * 100).toFixed(0)}%.`;\n\n if (result === 'applied') {\n return `${actionSummary} ${simSummary} Expected effect in ${plan.estimatedLag} ticks.`;\n }\n\n return `${actionSummary} Skipped (${result}). ${simSummary}`;\n }\n\n private stubPlan(diagnosis: Diagnosis, metrics: EconomyMetrics): ActionPlan {\n const action = diagnosis.violation.suggestedAction;\n return {\n id: `stub_${metrics.tick}`,\n diagnosis,\n parameter: action.parameter,\n currentValue: 1,\n targetValue: 1,\n maxChangePercent: 0,\n cooldownTicks: 0,\n rollbackCondition: {\n metric: 'avgSatisfaction',\n direction: 'below',\n threshold: 0,\n checkAfterTick: 0,\n },\n simulationResult: {\n proposedAction: action,\n iterations: 0,\n forwardTicks: 0,\n outcomes: {\n p10: metrics,\n p50: metrics,\n p90: metrics,\n mean: metrics,\n },\n netImprovement: false,\n noNewProblems: true,\n confidenceInterval: [0, 0],\n estimatedEffectTick: 0,\n overshootRisk: 0,\n },\n estimatedLag: 0,\n };\n }\n}\n","// Multi-resolution metric time-series storage (P41)\n// Three resolutions: fine (every tick), medium (every 10 ticks), coarse (every 100 ticks)\n\nimport type { EconomyMetrics, MetricResolution, MetricQuery, MetricQueryResult } from './types.js';\nimport { emptyMetrics } from './types.js';\n\nclass RingBuffer<T> {\n private buf: T[];\n private head = 0;\n private count = 0;\n\n constructor(private readonly capacity: number) {\n this.buf = new Array(capacity);\n }\n\n push(item: T): void {\n this.buf[this.head] = item;\n this.head = (this.head + 1) % this.capacity;\n if (this.count < this.capacity) this.count++;\n }\n\n /** All items in chronological order (oldest first) */\n toArray(): T[] {\n if (this.count === 0) return [];\n const result: T[] = [];\n const start = this.count < this.capacity ? 0 : this.head;\n for (let i = 0; i < this.count; i++) {\n result.push(this.buf[(start + i) % this.capacity]!);\n }\n return result;\n }\n\n last(): T | undefined {\n if (this.count === 0) return undefined;\n const idx = (this.head - 1 + this.capacity) % this.capacity;\n return this.buf[idx];\n }\n\n get length(): number {\n return this.count;\n }\n}\n\nexport class MetricStore {\n /** Fine: last 200 ticks, one entry per tick */\n private fine = new RingBuffer<EconomyMetrics>(200);\n /** Medium: last 200 windows of 10 ticks */\n private medium = new RingBuffer<EconomyMetrics>(200);\n /** Coarse: last 200 epochs of 100 ticks */\n private coarse = new RingBuffer<EconomyMetrics>(200);\n\n private ticksSinceLastMedium = 0;\n private ticksSinceLastCoarse = 0;\n private mediumAccumulator: EconomyMetrics[] = [];\n private coarseAccumulator: EconomyMetrics[] = [];\n\n record(metrics: EconomyMetrics): void {\n this.fine.push(metrics);\n\n this.mediumAccumulator.push(metrics);\n this.ticksSinceLastMedium++;\n if (this.ticksSinceLastMedium >= 10) {\n this.medium.push(this.aggregate(this.mediumAccumulator));\n this.mediumAccumulator = [];\n this.ticksSinceLastMedium = 0;\n }\n\n this.coarseAccumulator.push(metrics);\n this.ticksSinceLastCoarse++;\n if (this.ticksSinceLastCoarse >= 100) {\n this.coarse.push(this.aggregate(this.coarseAccumulator));\n this.coarseAccumulator = [];\n this.ticksSinceLastCoarse = 0;\n }\n }\n\n latest(resolution: MetricResolution = 'fine'): EconomyMetrics {\n const buf = this.bufferFor(resolution);\n return buf.last() ?? emptyMetrics();\n }\n\n query(q: MetricQuery): MetricQueryResult {\n const resolution: MetricResolution = q.resolution ?? 'fine';\n const buf = this.bufferFor(resolution);\n const all = buf.toArray();\n\n const filtered = all.filter(m => {\n if (q.from !== undefined && m.tick < q.from) return false;\n if (q.to !== undefined && m.tick > q.to) return false;\n return true;\n });\n\n const metricKey = q.metric as keyof EconomyMetrics;\n const points = filtered.map(m => ({\n tick: m.tick,\n value: typeof m[metricKey] === 'number' ? (m[metricKey] as number) : NaN,\n }));\n\n return { metric: q.metric, resolution, points };\n }\n\n /** Check if fine and coarse resolution metrics diverge significantly */\n divergenceDetected(): boolean {\n const f = this.fine.last();\n const c = this.coarse.last();\n if (!f || !c) return false;\n const fineSat = f.avgSatisfaction;\n const coarseSat = c.avgSatisfaction;\n return Math.abs(fineSat - coarseSat) > 20;\n }\n\n private bufferFor(resolution: MetricResolution): RingBuffer<EconomyMetrics> {\n if (resolution === 'medium') return this.medium;\n if (resolution === 'coarse') return this.coarse;\n return this.fine;\n }\n\n private aggregate(snapshots: EconomyMetrics[]): EconomyMetrics {\n if (snapshots.length === 0) return emptyMetrics();\n const last = snapshots[snapshots.length - 1]!;\n // Average numeric scalars, take last for maps/arrays\n const avg = (key: keyof EconomyMetrics): number => {\n const vals = snapshots.map(s => s[key] as number).filter(v => !isNaN(v));\n return vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n };\n\n return {\n ...last,\n totalSupply: avg('totalSupply'),\n netFlow: avg('netFlow'),\n velocity: avg('velocity'),\n inflationRate: avg('inflationRate'),\n giniCoefficient: avg('giniCoefficient'),\n medianBalance: avg('medianBalance'),\n meanBalance: avg('meanBalance'),\n top10PctShare: avg('top10PctShare'),\n meanMedianDivergence: avg('meanMedianDivergence'),\n avgSatisfaction: avg('avgSatisfaction'),\n churnRate: avg('churnRate'),\n blockedAgentCount: avg('blockedAgentCount'),\n faucetVolume: avg('faucetVolume'),\n sinkVolume: avg('sinkVolume'),\n tapSinkRatio: avg('tapSinkRatio'),\n productionIndex: avg('productionIndex'),\n capacityUsage: avg('capacityUsage'),\n anchorRatioDrift: avg('anchorRatioDrift'),\n };\n }\n}\n","// Behavioral persona classification (P46)\n// Classifies agents into 9 behavioral archetypes based on observable signals\n\nimport type { EconomyState, PersonaType } from './types.js';\n\ninterface AgentSignals {\n transactionCount: number;\n netExtraction: number; // gold out - gold in\n uniqueItemsHeld: number;\n holdingDuration: number; // ticks holding items\n spendAmount: number;\n sessionActivity: number; // actions per tick\n socialInteractions: number;\n}\n\nexport class PersonaTracker {\n private agentHistory = new Map<string, AgentSignals[]>();\n\n /** Ingest a state snapshot and update agent signal history */\n update(state: EconomyState): void {\n for (const agentId of Object.keys(state.agentBalances)) {\n const history = this.agentHistory.get(agentId) ?? [];\n const inv = state.agentInventories[agentId] ?? {};\n const uniqueItems = Object.values(inv).filter(q => q > 0).length;\n\n history.push({\n transactionCount: 0, // would be computed from events in full impl\n netExtraction: 0, // gold out vs in\n uniqueItemsHeld: uniqueItems,\n holdingDuration: 1,\n spendAmount: 0,\n sessionActivity: 1,\n socialInteractions: 0,\n });\n\n // Keep last 50 ticks of history\n if (history.length > 50) history.shift();\n this.agentHistory.set(agentId, history);\n }\n }\n\n /** Classify all agents and return persona distribution */\n getDistribution(): Record<string, number> {\n const counts: Record<PersonaType, number> = {\n Gamer: 0, Trader: 0, Collector: 0, Speculator: 0, Earner: 0,\n Builder: 0, Social: 0, Whale: 0, Influencer: 0,\n };\n let total = 0;\n\n for (const [, history] of this.agentHistory) {\n const persona = this.classify(history);\n counts[persona]++;\n total++;\n }\n\n if (total === 0) return {};\n\n const distribution: Record<string, number> = {};\n for (const [persona, count] of Object.entries(counts)) {\n distribution[persona] = count / total;\n }\n return distribution;\n }\n\n private classify(history: AgentSignals[]): PersonaType {\n if (history.length === 0) return 'Gamer';\n\n const avg = (key: keyof AgentSignals): number => {\n const vals = history.map(h => h[key]);\n return vals.reduce((s, v) => s + v, 0) / vals.length;\n };\n\n const txRate = avg('transactionCount');\n const extraction = avg('netExtraction');\n const uniqueItems = avg('uniqueItemsHeld');\n const spend = avg('spendAmount');\n\n // Simple rule-based classification (replace with ML in production)\n if (spend > 1000) return 'Whale';\n if (txRate > 10) return 'Trader';\n if (uniqueItems > 5 && extraction < 0) return 'Collector'; // buys and holds\n if (extraction > 100) return 'Earner';\n if (extraction > 50) return 'Speculator';\n return 'Gamer'; // default: plays for engagement, not profit\n }\n}\n","// AgentE — the main class\n// Observer → Diagnose → Simulate → Plan → Execute\n\nimport type {\n AgentEConfig,\n AgentEMode,\n EconomyAdapter,\n EconomyState,\n EconomicEvent,\n Principle,\n DecisionEntry,\n ActionPlan,\n Thresholds,\n MetricQuery,\n MetricQueryResult,\n} from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { DEFAULT_THRESHOLDS } from './defaults.js';\nimport { Observer } from './Observer.js';\nimport { Diagnoser } from './Diagnoser.js';\nimport { Simulator } from './Simulator.js';\nimport { Planner } from './Planner.js';\nimport { Executor } from './Executor.js';\nimport { DecisionLog } from './DecisionLog.js';\nimport { MetricStore } from './MetricStore.js';\nimport { PersonaTracker } from './PersonaTracker.js';\nimport { ALL_PRINCIPLES } from './principles/index.js';\n\ntype EventName = 'decision' | 'alert' | 'rollback' | 'beforeAction' | 'afterAction';\n\nexport class AgentE {\n // ── Config ──\n private readonly config: Required<\n Omit<AgentEConfig, 'adapter' | 'thresholds' | 'onDecision' | 'onAlert' | 'onRollback'>\n >;\n private readonly thresholds: Thresholds;\n private adapter!: EconomyAdapter;\n private mode: AgentEMode;\n\n // ── Pipeline ──\n private observer = new Observer();\n private diagnoser: Diagnoser;\n private simulator = new Simulator();\n private planner = new Planner();\n private executor = new Executor();\n\n // ── State ──\n readonly log = new DecisionLog();\n readonly store = new MetricStore();\n private personaTracker = new PersonaTracker();\n private params: Record<string, number> = {};\n private eventBuffer: EconomicEvent[] = [];\n private isRunning = false;\n private isPaused = false;\n private currentTick = 0;\n\n // ── Event handlers ──\n private handlers = new Map<EventName, Array<(...args: unknown[]) => unknown>>();\n\n constructor(config: AgentEConfig) {\n this.mode = config.mode ?? 'autonomous';\n\n this.config = {\n mode: this.mode,\n dominantRoles: config.dominantRoles ?? [],\n idealDistribution: config.idealDistribution ?? {},\n gracePeriod: config.gracePeriod ?? 50,\n checkInterval: config.checkInterval ?? 5,\n maxAdjustmentPercent: config.maxAdjustmentPercent ?? 0.15,\n cooldownTicks: config.cooldownTicks ?? 15,\n };\n\n this.thresholds = {\n ...DEFAULT_THRESHOLDS,\n ...(config.thresholds ?? {}),\n maxAdjustmentPercent: config.maxAdjustmentPercent ?? DEFAULT_THRESHOLDS.maxAdjustmentPercent,\n cooldownTicks: config.cooldownTicks ?? DEFAULT_THRESHOLDS.cooldownTicks,\n };\n\n this.diagnoser = new Diagnoser(ALL_PRINCIPLES);\n\n // Wire up config callbacks\n if (config.onDecision) this.on('decision', config.onDecision as never);\n if (config.onAlert) this.on('alert', config.onAlert as never);\n if (config.onRollback) this.on('rollback', config.onRollback as never);\n\n // Lock dominant roles from population suppression by locking arena reward adjustments\n // (structural protection — dominant roles' key param won't be suppressed)\n if (config.dominantRoles && config.dominantRoles.length > 0) {\n // Mark dominant roles as protected (used in Diagnoser context)\n // This is a lightweight approach — in production, principles query this list.\n }\n }\n\n // ── Connection ──────────────────────────────────────────────────────────────\n\n connect(adapter: EconomyAdapter): this {\n this.adapter = adapter;\n\n // Wire up event stream if adapter supports it\n if (adapter.onEvent) {\n adapter.onEvent(event => this.eventBuffer.push(event));\n }\n\n return this;\n }\n\n start(): this {\n if (!this.adapter) throw new Error('[AgentE] Call .connect(adapter) before .start()');\n this.isRunning = true;\n this.isPaused = false;\n return this;\n }\n\n pause(): void {\n this.isPaused = true;\n }\n\n resume(): void {\n this.isPaused = false;\n }\n\n stop(): void {\n this.isRunning = false;\n this.isPaused = false;\n }\n\n // ── Main cycle (call once per tick from your game loop) ────────────────────\n\n async tick(state?: EconomyState): Promise<void> {\n if (!this.isRunning || this.isPaused) return;\n\n // Fetch state if not provided (polling mode)\n const currentState = state ?? (await Promise.resolve(this.adapter.getState()));\n this.currentTick = currentState.tick;\n\n // Drain event buffer\n const events = [...this.eventBuffer];\n this.eventBuffer = [];\n\n // Stage 1: Observe\n const metrics = this.observer.compute(currentState, events);\n this.store.record(metrics);\n this.personaTracker.update(currentState);\n metrics.personaDistribution = this.personaTracker.getDistribution();\n\n // Check rollbacks on active plans\n const rolledBack = await this.executor.checkRollbacks(metrics, this.adapter);\n for (const plan of rolledBack) {\n this.planner.recordRolledBack(plan);\n this.emit('rollback', plan, 'rollback condition triggered');\n }\n\n // Grace period — no interventions\n if (metrics.tick < this.config.gracePeriod) return;\n\n // Only run the full pipeline every checkInterval ticks\n if (metrics.tick % this.config.checkInterval !== 0) return;\n\n // Stage 2: Diagnose\n const diagnoses = this.diagnoser.diagnose(metrics, this.thresholds);\n\n // Alert on all violations (regardless of whether we act)\n for (const diagnosis of diagnoses) {\n this.emit('alert', diagnosis);\n }\n\n // Only act on the top-priority issue (prevents oscillation from multi-action)\n const topDiagnosis = diagnoses[0];\n if (!topDiagnosis) return;\n\n // Stage 3: Simulate\n const simulationResult = this.simulator.simulate(\n topDiagnosis.violation.suggestedAction,\n metrics,\n this.thresholds,\n 100, // always >= minimum (P43)\n 20,\n );\n\n // Stage 4: Plan\n const plan = this.planner.plan(\n topDiagnosis,\n metrics,\n simulationResult,\n this.params,\n this.thresholds,\n );\n\n if (!plan) {\n // Log the skip\n let reason = 'skipped_cooldown';\n if (!simulationResult.netImprovement) reason = 'skipped_simulation_failed';\n this.log.recordSkip(topDiagnosis, reason as never, metrics, `Skipped: ${reason}`);\n return;\n }\n\n // Advisor mode: emit recommendation, don't apply\n if (this.mode === 'advisor') {\n const entry = this.log.record(topDiagnosis, plan, 'skipped_override', metrics);\n this.emit('decision', entry);\n return;\n }\n\n // beforeAction hook — veto if handler returns false\n const vetoed = this.emit('beforeAction', plan);\n if (vetoed === false) {\n this.log.recordSkip(topDiagnosis, 'skipped_override', metrics, 'vetoed by beforeAction hook');\n return;\n }\n\n // Stage 5: Execute\n await this.executor.apply(plan, this.adapter, this.params);\n this.params[plan.parameter] = plan.targetValue;\n this.planner.recordApplied(plan, metrics.tick);\n\n const entry = this.log.record(topDiagnosis, plan, 'applied', metrics);\n this.emit('decision', entry);\n this.emit('afterAction', entry);\n }\n\n /** Apply a plan manually (for advisor mode) */\n async apply(plan: ActionPlan): Promise<void> {\n await this.executor.apply(plan, this.adapter, this.params);\n this.params[plan.parameter] = plan.targetValue;\n this.planner.recordApplied(plan, this.currentTick);\n }\n\n // ── Developer API ───────────────────────────────────────────────────────────\n\n lock(param: string): void {\n this.planner.lock(param);\n }\n\n unlock(param: string): void {\n this.planner.unlock(param);\n }\n\n constrain(param: string, bounds: { min: number; max: number }): void {\n this.planner.constrain(param, bounds);\n }\n\n addPrinciple(principle: Principle): void {\n this.diagnoser.addPrinciple(principle);\n }\n\n removePrinciple(id: string): void {\n this.diagnoser.removePrinciple(id);\n }\n\n registerCustomMetric(name: string, fn: (state: EconomyState) => number): void {\n this.observer.registerCustomMetric(name, fn);\n }\n\n getDecisions(filter?: Parameters<DecisionLog['query']>[0]): DecisionEntry[] {\n return this.log.query(filter);\n }\n\n getPrinciples(): Principle[] {\n return this.diagnoser.getPrinciples();\n }\n\n getActivePlans(): ActionPlan[] {\n return this.executor.getActivePlans();\n }\n\n /** Access to the metric time-series store */\n readonly metrics = {\n query: (q: MetricQuery): MetricQueryResult => this.store.query(q),\n latest: (resolution?: 'fine' | 'medium' | 'coarse') => this.store.latest(resolution),\n };\n\n // ── Events ──────────────────────────────────────────────────────────────────\n\n on(event: EventName, handler: (...args: unknown[]) => unknown): this {\n const list = this.handlers.get(event) ?? [];\n list.push(handler);\n this.handlers.set(event, list);\n return this;\n }\n\n off(event: EventName, handler: (...args: unknown[]) => unknown): this {\n const list = this.handlers.get(event) ?? [];\n this.handlers.set(event, list.filter(h => h !== handler));\n return this;\n }\n\n private emit(event: EventName, ...args: unknown[]): unknown {\n const list = this.handlers.get(event) ?? [];\n let result: unknown;\n for (const handler of list) {\n result = handler(...args);\n if (result === false) return false; // veto\n }\n return result;\n }\n\n // ── Diagnostics ─────────────────────────────────────────────────────────────\n\n diagnoseNow(): ReturnType<Diagnoser['diagnose']> {\n const metrics = this.store.latest();\n return this.diagnoser.diagnose(metrics, this.thresholds);\n }\n\n getHealth(): number {\n const m = this.store.latest();\n if (m.tick === 0) return 100;\n let health = 100;\n if (m.avgSatisfaction < 65) health -= 15;\n if (m.avgSatisfaction < 50) health -= 10;\n if (m.giniCoefficient > 0.45) health -= 15;\n if (m.giniCoefficient > 0.60) health -= 10;\n if (Math.abs(m.netFlow) > 10) health -= 15;\n if (Math.abs(m.netFlow) > 20) health -= 10;\n if (m.churnRate > 0.05) health -= 15;\n return Math.max(0, Math.min(100, health));\n }\n\n // ── Ingest events directly (event-driven mode) ───────────────────────────\n\n ingest(event: EconomicEvent): void {\n this.eventBuffer.push(event);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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WAAU;AACxC,QAAI,EAAE,YAAY,KAAM,WAAU;AAClC,WAAO,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,MAAM,CAAC;AAAA,EAC1C;AAAA;AAAA,EAIA,OAAO,OAA4B;AACjC,SAAK,YAAY,KAAK,KAAK;AAAA,EAC7B;AACF;","names":["plan","entry"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/defaults.ts","../src/Observer.ts","../src/Diagnoser.ts","../src/types.ts","../src/principles/supply-chain.ts","../src/principles/incentives.ts","../src/principles/population.ts","../src/principles/currency-flow.ts","../src/principles/bootstrap.ts","../src/principles/feedback-loops.ts","../src/principles/regulator.ts","../src/principles/market-dynamics.ts","../src/principles/measurement.ts","../src/principles/statistical.ts","../src/principles/system-dynamics.ts","../src/principles/resource-mgmt.ts","../src/principles/player-experience.ts","../src/principles/open-economy.ts","../src/principles/liveops.ts","../src/principles/index.ts","../src/Simulator.ts","../src/Planner.ts","../src/Executor.ts","../src/DecisionLog.ts","../src/MetricStore.ts","../src/PersonaTracker.ts","../src/AgentE.ts"],"sourcesContent":["// @agent-e/core — main entry point\n\nexport { AgentE } from './AgentE.js';\nexport { Observer } from './Observer.js';\nexport { Diagnoser } from './Diagnoser.js';\nexport { Simulator } from './Simulator.js';\nexport { Planner } from './Planner.js';\nexport { Executor } from './Executor.js';\nexport { DecisionLog } from './DecisionLog.js';\nexport { MetricStore } from './MetricStore.js';\nexport { PersonaTracker } from './PersonaTracker.js';\nexport { DEFAULT_THRESHOLDS, PERSONA_HEALTHY_RANGES } from './defaults.js';\nexport { ALL_PRINCIPLES } from './principles/index.js';\nexport * from './principles/index.js';\nexport * from './types.js';\n","import type { Thresholds, TickConfig } from './types.js';\n\nexport const DEFAULT_THRESHOLDS: Thresholds = {\n // Statistical (P42-P43)\n meanMedianDivergenceMax: 0.30,\n simulationMinIterations: 100,\n\n // Population (P46)\n personaMonocultureMax: 0.40,\n personaMinClusters: 3,\n\n // Open Economy (P34, P47-P48)\n extractionRatioYellow: 0.50,\n extractionRatioRed: 0.65,\n smokeTestWarning: 0.30,\n smokeTestCritical: 0.10,\n currencyInsulationMax: 0.50,\n\n // Player Experience (P45, P50)\n timeBudgetRatio: 0.80,\n payPowerRatioMax: 2.0,\n payPowerRatioTarget: 1.5,\n\n // LiveOps (P51, P53)\n sharkToothPeakDecay: 0.95,\n sharkToothValleyDecay: 0.90,\n eventCompletionMin: 0.40,\n eventCompletionMax: 0.80,\n\n // System Dynamics (P39, P44)\n lagMultiplierMin: 3,\n lagMultiplierMax: 5,\n complexityBudgetMax: 20,\n\n // Resource (P40)\n replacementRateMultiplier: 2.0,\n\n // Regulator (P26-P27)\n maxAdjustmentPercent: 0.15,\n cooldownTicks: 15,\n\n // Currency (P13)\n poolWinRate: 0.65,\n poolHouseCut: 0.10,\n\n // Population balance (P9)\n roleSwitchFrictionMax: 0.05, // >5% of population switching in one period = herd\n\n // Pool limits (P15)\n poolCapPercent: 0.05, // no pool > 5% of total currency\n poolDecayRate: 0.02,\n\n // Profitability (P5)\n stampedeProfitRatio: 3.0, // one role's profit > 3× median → stampede risk\n\n // Satisfaction (P24)\n blockedAgentMaxFraction: 0.15,\n\n // Gini (P33)\n giniWarnThreshold: 0.45,\n giniRedThreshold: 0.60,\n\n // Churn (P9)\n churnWarnRate: 0.05,\n\n // Net flow (P12)\n netFlowWarnThreshold: 10,\n\n // V1.1 (P55-P60)\n arbitrageIndexWarning: 0.35,\n arbitrageIndexCritical: 0.55,\n contentDropCooldownTicks: 30,\n postDropArbitrageMax: 0.45,\n relativePriceConvergenceTarget: 0.85,\n priceDiscoveryWindowTicks: 20,\n giftTradeFilterRatio: 0.15,\n disposalTradeWeightDiscount: 0.5,\n};\n\nexport const PERSONA_HEALTHY_RANGES: Record<string, { min: number; max: number }> = {\n Active: { min: 0.20, max: 0.40 },\n Trader: { min: 0.05, max: 0.15 },\n Collector: { min: 0.05, max: 0.15 },\n Speculator: { min: 0.00, max: 0.10 },\n Earner: { min: 0.00, max: 0.15 },\n Builder: { min: 0.05, max: 0.15 },\n Social: { min: 0.10, max: 0.20 },\n Whale: { min: 0.00, max: 0.05 },\n Influencer: { min: 0.00, max: 0.05 },\n};\n\nexport const DEFAULT_TICK_CONFIG: TickConfig = {\n duration: 1,\n unit: 'tick',\n mediumWindow: 10,\n coarseWindow: 100,\n};\n","// Stage 1: Observer — translates raw EconomyState into EconomyMetrics\n\nimport type { EconomyState, EconomyMetrics, EconomicEvent, TickConfig } from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { DEFAULT_TICK_CONFIG } from './defaults.js';\n\nexport class Observer {\n private previousMetrics: EconomyMetrics | null = null;\n private previousPrices: Record<string, number> = {};\n private customMetricFns: Record<string, (state: EconomyState) => number> = {};\n private anchorBaseline: { currencyPerPeriod: number; itemsPerCurrency: number } | null = null;\n private tickConfig: TickConfig;\n\n constructor(tickConfig?: Partial<TickConfig>) {\n this.tickConfig = { ...DEFAULT_TICK_CONFIG, ...tickConfig };\n }\n\n registerCustomMetric(name: string, fn: (state: EconomyState) => number): void {\n this.customMetricFns[name] = fn;\n }\n\n compute(state: EconomyState, recentEvents: EconomicEvent[]): EconomyMetrics {\n const tick = state.tick;\n const balances = Object.values(state.agentBalances);\n const roles = Object.values(state.agentRoles);\n const totalAgents = balances.length;\n\n // ── Event classification (single pass) ──\n let faucetVolume = 0;\n let sinkVolume = 0;\n const tradeEvents: EconomicEvent[] = [];\n const roleChangeEvents: EconomicEvent[] = [];\n let churnCount = 0;\n\n for (const e of recentEvents) {\n switch (e.type) {\n case 'mint':\n case 'spawn':\n faucetVolume += e.amount ?? 0;\n break;\n case 'burn':\n case 'consume':\n sinkVolume += e.amount ?? 0;\n break;\n case 'trade':\n tradeEvents.push(e);\n break;\n case 'churn':\n churnCount++;\n roleChangeEvents.push(e);\n break;\n case 'role_change':\n roleChangeEvents.push(e);\n break;\n }\n }\n\n // ── Currency ──\n const totalSupply = balances.reduce((s, b) => s + b, 0);\n const netFlow = faucetVolume - sinkVolume;\n const tapSinkRatio = sinkVolume > 0 ? faucetVolume / sinkVolume : faucetVolume > 0 ? Infinity : 1;\n\n const prevSupply = this.previousMetrics?.totalSupply ?? totalSupply;\n const inflationRate = prevSupply > 0 ? (totalSupply - prevSupply) / prevSupply : 0;\n\n const velocity = totalSupply > 0 ? tradeEvents.length / totalSupply : 0;\n\n // ── Wealth distribution ──\n const sortedBalances = [...balances].sort((a, b) => a - b);\n const meanBalance = totalAgents > 0 ? totalSupply / totalAgents : 0;\n const medianBalance = computeMedian(sortedBalances);\n const top10Idx = Math.floor(totalAgents * 0.9);\n const top10Sum = sortedBalances.slice(top10Idx).reduce((s, b) => s + b, 0);\n const top10PctShare = totalSupply > 0 ? top10Sum / totalSupply : 0;\n const giniCoefficient = computeGini(sortedBalances);\n const meanMedianDivergence =\n medianBalance > 0 ? Math.abs(meanBalance - medianBalance) / medianBalance : 0;\n\n // ── Population ──\n const populationByRole: Record<string, number> = {};\n const roleShares: Record<string, number> = {};\n for (const role of roles) {\n populationByRole[role] = (populationByRole[role] ?? 0) + 1;\n }\n for (const [role, count] of Object.entries(populationByRole)) {\n roleShares[role] = count / Math.max(1, totalAgents);\n }\n\n const churnByRole: Record<string, number> = {};\n for (const e of roleChangeEvents) {\n const role = e.role ?? 'unknown';\n churnByRole[role] = (churnByRole[role] ?? 0) + 1;\n }\n const churnRate = churnCount / Math.max(1, totalAgents);\n\n // ── Market ──\n const prices: Record<string, number> = { ...state.marketPrices };\n const priceVolatility: Record<string, number> = {};\n for (const [resource, price] of Object.entries(prices)) {\n const prev = this.previousPrices[resource] ?? price;\n priceVolatility[resource] = prev > 0 ? Math.abs(price - prev) / prev : 0;\n }\n this.previousPrices = { ...prices };\n\n // Compute price index (equal-weight basket)\n const priceValues = Object.values(prices);\n const priceIndex =\n priceValues.length > 0 ? priceValues.reduce((s, p) => s + p, 0) / priceValues.length : 0;\n\n // Supply from agent inventories\n const supplyByResource: Record<string, number> = {};\n for (const inv of Object.values(state.agentInventories)) {\n for (const [resource, qty] of Object.entries(inv)) {\n supplyByResource[resource] = (supplyByResource[resource] ?? 0) + qty;\n }\n }\n\n // Demand signals: approximate from recent trade events\n const demandSignals: Record<string, number> = {};\n for (const e of tradeEvents) {\n if (e.resource) {\n demandSignals[e.resource] = (demandSignals[e.resource] ?? 0) + (e.amount ?? 1);\n }\n }\n\n // Pinch points: resources where demand > 2× supply or supply > 3× demand\n const pinchPoints: Record<string, 'optimal' | 'oversupplied' | 'scarce'> = {};\n for (const resource of new Set([...Object.keys(supplyByResource), ...Object.keys(demandSignals)])) {\n const s = supplyByResource[resource] ?? 0;\n const d = demandSignals[resource] ?? 0;\n if (d > 2 && s / d < 0.5) {\n pinchPoints[resource] = 'scarce';\n } else if (s > 3 && d > 0 && s / d > 3) {\n pinchPoints[resource] = 'oversupplied';\n } else {\n pinchPoints[resource] = 'optimal';\n }\n }\n\n const productionIndex = recentEvents\n .filter(e => e.type === 'produce')\n .reduce((s, e) => s + (e.amount ?? 1), 0);\n\n const maxPossibleProduction = productionIndex + sinkVolume;\n const capacityUsage =\n maxPossibleProduction > 0 ? productionIndex / maxPossibleProduction : 0;\n\n // ── Satisfaction ──\n const satisfactions = Object.values(state.agentSatisfaction ?? {});\n const avgSatisfaction =\n satisfactions.length > 0\n ? satisfactions.reduce((s, v) => s + v, 0) / satisfactions.length\n : 80;\n\n const blockedAgentCount = satisfactions.filter(s => s < 20).length;\n // Time-to-value: ratio of blocked agents to total. Lower = healthier.\n const timeToValue = totalAgents > 0 ? blockedAgentCount / totalAgents * 100 : 0;\n\n // ── Pools ──\n const poolSizes: Record<string, number> = { ...(state.poolSizes ?? {}) };\n\n // ── Anchor ratio ──\n if (!this.anchorBaseline && tick === 1 && totalSupply > 0) {\n this.anchorBaseline = {\n currencyPerPeriod: totalSupply / Math.max(1, totalAgents),\n itemsPerCurrency: priceIndex > 0 ? 1 / priceIndex : 0,\n };\n }\n let anchorRatioDrift = 0;\n if (this.anchorBaseline && totalAgents > 0) {\n const currentCurrencyPerPeriod = totalSupply / totalAgents;\n anchorRatioDrift =\n this.anchorBaseline.currencyPerPeriod > 0\n ? (currentCurrencyPerPeriod - this.anchorBaseline.currencyPerPeriod) /\n this.anchorBaseline.currencyPerPeriod\n : 0;\n }\n\n // ── V1.1 Metrics ──\n\n // arbitrageIndex: average pairwise price divergence across all resources\n // For N resources with prices, compute all (N-1)*N/2 relative price ratios\n // and measure how far they deviate from 1.0 (perfect equilibrium)\n let arbitrageIndex = 0;\n const priceKeys = Object.keys(prices).filter(k => prices[k]! > 0);\n if (priceKeys.length >= 2) {\n let pairCount = 0;\n let totalDivergence = 0;\n for (let i = 0; i < priceKeys.length; i++) {\n for (let j = i + 1; j < priceKeys.length; j++) {\n const pA = prices[priceKeys[i]!]!;\n const pB = prices[priceKeys[j]!]!;\n let ratio = pA / pB;\n // Clamp ratio to prevent Math.log(0) or Math.log(Infinity)\n ratio = Math.max(0.001, Math.min(1000, ratio));\n // Divergence from 1.0: |ln(ratio)| gives symmetric measure\n totalDivergence += Math.abs(Math.log(ratio));\n pairCount++;\n }\n }\n arbitrageIndex = pairCount > 0 ? Math.min(1, totalDivergence / pairCount) : 0;\n }\n\n // contentDropAge: ticks since last 'produce' event with metadata.contentDrop === true\n // Falls back to 0 if no content drops tracked\n const contentDropEvents = recentEvents.filter(\n e => e.metadata?.['contentDrop'] === true\n );\n const contentDropAge = contentDropEvents.length > 0\n ? tick - Math.max(...contentDropEvents.map(e => e.timestamp))\n : (this.previousMetrics?.contentDropAge ?? 0) + 1;\n\n // giftTradeRatio: fraction of trades where price is 0 or significantly below market\n let giftTrades = 0;\n if (tradeEvents.length > 0) {\n for (const e of tradeEvents) {\n const marketPrice = prices[e.resource ?? ''] ?? 0;\n const tradePrice = e.price ?? 0;\n if (tradePrice === 0 || (marketPrice > 0 && tradePrice < marketPrice * 0.3)) {\n giftTrades++;\n }\n }\n }\n const giftTradeRatio = tradeEvents.length > 0 ? giftTrades / tradeEvents.length : 0;\n\n // disposalTradeRatio: fraction of trades classified as surplus liquidation\n // Heuristic: trade where seller has >3× average inventory of that resource\n let disposalTrades = 0;\n if (tradeEvents.length > 0) {\n for (const e of tradeEvents) {\n if (e.from && e.resource) {\n const sellerInv = state.agentInventories[e.from]?.[e.resource] ?? 0;\n const avgInv = (supplyByResource[e.resource] ?? 0) / Math.max(1, totalAgents);\n if (sellerInv > avgInv * 3) {\n disposalTrades++;\n }\n }\n }\n }\n const disposalTradeRatio = tradeEvents.length > 0 ? disposalTrades / tradeEvents.length : 0;\n\n // ── Custom metrics ──\n const custom: Record<string, number> = {};\n for (const [name, fn] of Object.entries(this.customMetricFns)) {\n try {\n custom[name] = fn(state);\n } catch {\n custom[name] = NaN;\n }\n }\n\n const metrics: EconomyMetrics = {\n tick,\n timestamp: Date.now(),\n totalSupply,\n netFlow,\n velocity,\n inflationRate,\n populationByRole,\n roleShares,\n totalAgents,\n churnRate,\n churnByRole,\n personaDistribution: {}, // populated by PersonaTracker\n giniCoefficient,\n medianBalance,\n meanBalance,\n top10PctShare,\n meanMedianDivergence,\n priceIndex,\n productionIndex,\n capacityUsage,\n prices,\n priceVolatility,\n supplyByResource,\n demandSignals,\n pinchPoints,\n avgSatisfaction,\n blockedAgentCount,\n timeToValue,\n faucetVolume,\n sinkVolume,\n tapSinkRatio,\n poolSizes,\n anchorRatioDrift,\n extractionRatio: NaN,\n newUserDependency: NaN,\n smokeTestRatio: NaN,\n currencyInsulation: NaN,\n sharkToothPeaks: this.previousMetrics?.sharkToothPeaks ?? [],\n sharkToothValleys: this.previousMetrics?.sharkToothValleys ?? [],\n eventCompletionRate: NaN,\n arbitrageIndex,\n contentDropAge,\n giftTradeRatio,\n disposalTradeRatio,\n custom,\n };\n\n this.previousMetrics = metrics;\n return metrics;\n }\n}\n\n// ── Math helpers ──────────────────────────────────────────────────────────────\n\nfunction computeMedian(sorted: number[]): number {\n if (sorted.length === 0) return 0;\n const mid = Math.floor(sorted.length / 2);\n return sorted.length % 2 === 0\n ? ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2\n : (sorted[mid] ?? 0);\n}\n\nfunction computeGini(sorted: number[]): number {\n const n = sorted.length;\n if (n === 0) return 0;\n const sum = sorted.reduce((a, b) => a + b, 0);\n if (sum === 0) return 0;\n let numerator = 0;\n for (let i = 0; i < n; i++) {\n numerator += (2 * (i + 1) - n - 1) * (sorted[i] ?? 0);\n }\n return Math.abs(numerator) / (n * sum);\n}\n","// Stage 2: Diagnoser — runs all principles, returns sorted violations\n\nimport type { Principle, EconomyMetrics, Thresholds, Diagnosis } from './types.js';\n\nexport class Diagnoser {\n private principles: Principle[] = [];\n\n constructor(principles: Principle[]) {\n this.principles = [...principles];\n }\n\n addPrinciple(principle: Principle): void {\n this.principles.push(principle);\n }\n\n removePrinciple(id: string): void {\n this.principles = this.principles.filter(p => p.id !== id);\n }\n\n /**\n * Run all principles against current metrics.\n * Returns violations sorted by severity (highest first).\n * Only one action is taken per cycle — the highest severity violation.\n */\n diagnose(metrics: EconomyMetrics, thresholds: Thresholds): Diagnosis[] {\n const diagnoses: Diagnosis[] = [];\n\n for (const principle of this.principles) {\n try {\n const result = principle.check(metrics, thresholds);\n if (result.violated) {\n diagnoses.push({\n principle,\n violation: result,\n tick: metrics.tick,\n });\n }\n } catch (err) {\n // Never let a buggy principle crash the engine\n console.warn(`[AgentE] Principle ${principle.id} threw an error:`, err);\n }\n }\n\n // Sort by severity DESC, then by confidence DESC as tiebreaker\n diagnoses.sort((a, b) => {\n const severityDiff = b.violation.severity - a.violation.severity;\n if (severityDiff !== 0) return severityDiff;\n return b.violation.confidence - a.violation.confidence;\n });\n\n return diagnoses;\n }\n\n getPrinciples(): Principle[] {\n return [...this.principles];\n }\n}\n","// ─────────────────────────────────────────────────────────────────────────────\n// AgentE Core Types\n// Every other file imports from here. Keep this file pure (no logic).\n// ─────────────────────────────────────────────────────────────────────────────\n\n// ── Events ───────────────────────────────────────────────────────────────────\n\nexport type EconomicEventType =\n | 'trade'\n | 'mint'\n | 'burn'\n | 'transfer'\n | 'produce'\n | 'consume'\n | 'role_change'\n | 'spawn'\n | 'churn';\n\nexport interface EconomicEvent {\n type: EconomicEventType;\n timestamp: number; // tick or unix ms — adapter decides\n actor: string; // agent/user/wallet ID\n role?: string; // actor's role in the economy\n resource?: string; // what resource is involved\n amount?: number; // quantity\n price?: number; // per-unit price\n from?: string; // source (for transfers)\n to?: string; // destination\n metadata?: Record<string, unknown>;\n}\n\n// ── Metrics ──────────────────────────────────────────────────────────────────\n\nexport type PinchPointStatus = 'optimal' | 'oversupplied' | 'scarce';\n\nexport interface EconomyMetrics {\n // ── Snapshot info ──\n tick: number;\n timestamp: number;\n\n // ── Currency health ──\n totalSupply: number;\n netFlow: number; // faucets minus sinks per period\n velocity: number; // transactions per period / total supply\n inflationRate: number; // % change in price index per period\n\n // ── Population health ──\n populationByRole: Record<string, number>;\n roleShares: Record<string, number>; // each role as fraction of total\n totalAgents: number;\n churnRate: number; // fraction lost per period\n churnByRole: Record<string, number>;\n personaDistribution: Record<string, number>;\n\n // ── Wealth distribution ──\n giniCoefficient: number; // 0 = perfect equality, 1 = one agent has everything\n medianBalance: number;\n meanBalance: number;\n top10PctShare: number; // fraction of wealth held by top 10%\n meanMedianDivergence: number; // (mean - median) / median\n\n // ── Market health ──\n priceIndex: number;\n productionIndex: number;\n capacityUsage: number;\n prices: Record<string, number>;\n priceVolatility: Record<string, number>;\n supplyByResource: Record<string, number>;\n demandSignals: Record<string, number>;\n pinchPoints: Record<string, PinchPointStatus>;\n\n // ── Satisfaction / Engagement ──\n avgSatisfaction: number;\n blockedAgentCount: number;\n timeToValue: number;\n\n // ── Flow tracking ──\n faucetVolume: number;\n sinkVolume: number;\n tapSinkRatio: number;\n poolSizes: Record<string, number>;\n anchorRatioDrift: number;\n\n // ── Open economy (optional, NaN if not tracked) ──\n extractionRatio: number;\n newUserDependency: number;\n smokeTestRatio: number;\n currencyInsulation: number;\n\n // ── LiveOps (optional, empty arrays if not tracked) ──\n sharkToothPeaks: number[];\n sharkToothValleys: number[];\n eventCompletionRate: number;\n\n // ── V1.1 Metrics (P55-P60) ──\n arbitrageIndex: number; // 0–1, aggregate arbitrage opportunity across all relative prices\n contentDropAge: number; // ticks since last content/item injection event\n giftTradeRatio: number; // fraction of recent trades classified as gifts/below-market\n disposalTradeRatio: number; // fraction of recent trades that are surplus liquidation, not production-for-sale\n\n // ── Custom metrics registered by developer ──\n custom: Record<string, number>;\n}\n\n// Sensible defaults for an EconomyMetrics snapshot when data is unavailable\nexport function emptyMetrics(tick = 0): EconomyMetrics {\n return {\n tick,\n timestamp: Date.now(),\n totalSupply: 0,\n netFlow: 0,\n velocity: 0,\n inflationRate: 0,\n populationByRole: {},\n roleShares: {},\n totalAgents: 0,\n churnRate: 0,\n churnByRole: {},\n personaDistribution: {},\n giniCoefficient: 0,\n medianBalance: 0,\n meanBalance: 0,\n top10PctShare: 0,\n meanMedianDivergence: 0,\n priceIndex: 0,\n productionIndex: 0,\n capacityUsage: 0,\n prices: {},\n priceVolatility: {},\n supplyByResource: {},\n demandSignals: {},\n pinchPoints: {},\n avgSatisfaction: 100,\n blockedAgentCount: 0,\n timeToValue: 0,\n faucetVolume: 0,\n sinkVolume: 0,\n tapSinkRatio: 1,\n poolSizes: {},\n anchorRatioDrift: 0,\n extractionRatio: NaN,\n newUserDependency: NaN,\n smokeTestRatio: NaN,\n currencyInsulation: NaN,\n sharkToothPeaks: [],\n sharkToothValleys: [],\n eventCompletionRate: NaN,\n arbitrageIndex: 0,\n contentDropAge: 0,\n giftTradeRatio: 0,\n disposalTradeRatio: 0,\n custom: {},\n };\n}\n\n// ── Principles ────────────────────────────────────────────────────────────────\n\nexport type PrincipleCategory =\n | 'supply_chain'\n | 'incentive'\n | 'population'\n | 'currency'\n | 'bootstrap'\n | 'feedback'\n | 'regulator'\n | 'market_dynamics'\n | 'measurement'\n | 'wealth_distribution'\n | 'resource'\n | 'system_design'\n | 'player_experience'\n | 'statistical'\n | 'system_dynamics'\n | 'open_economy'\n | 'liveops';\n\nexport interface PrincipleViolation {\n violated: true;\n severity: number; // 1–10\n evidence: Record<string, unknown>;\n suggestedAction: SuggestedAction;\n confidence: number; // 0–1\n estimatedLag?: number; // ticks before effect visible\n}\n\nexport interface PrincipleOk {\n violated: false;\n}\n\nexport type PrincipleResult = PrincipleViolation | PrincipleOk;\n\nexport interface Principle {\n id: string; // 'P1', 'P2', ... 'P54', or custom\n name: string;\n category: PrincipleCategory;\n description: string;\n check: (metrics: EconomyMetrics, thresholds: Thresholds) => PrincipleResult;\n}\n\n// ── Actions ──────────────────────────────────────────────────────────────────\n\nexport interface SuggestedAction {\n parameter: string;\n direction: 'increase' | 'decrease' | 'set';\n magnitude?: number; // fractional (0.15 = 15%)\n absoluteValue?: number;\n reasoning: string;\n}\n\nexport interface ActionPlan {\n id: string;\n diagnosis: Diagnosis;\n parameter: string;\n currentValue: number;\n targetValue: number;\n maxChangePercent: number;\n cooldownTicks: number;\n rollbackCondition: RollbackCondition;\n simulationResult: SimulationResult;\n estimatedLag: number;\n appliedAt?: number; // tick when applied\n}\n\nexport interface RollbackCondition {\n metric: keyof EconomyMetrics | string; // what to watch\n direction: 'above' | 'below';\n threshold: number;\n checkAfterTick: number; // don't check until this tick\n}\n\n// ── Diagnosis ────────────────────────────────────────────────────────────────\n\nexport interface Diagnosis {\n principle: Principle;\n violation: PrincipleViolation;\n tick: number;\n}\n\n// ── Simulation ───────────────────────────────────────────────────────────────\n\nexport interface SimulationOutcome {\n p10: EconomyMetrics;\n p50: EconomyMetrics;\n p90: EconomyMetrics;\n mean: EconomyMetrics;\n}\n\nexport interface SimulationResult {\n proposedAction: SuggestedAction;\n iterations: number;\n forwardTicks: number;\n outcomes: SimulationOutcome;\n netImprovement: boolean;\n noNewProblems: boolean;\n confidenceInterval: [number, number];\n estimatedEffectTick: number;\n overshootRisk: number; // 0–1\n}\n\n// ── Decision Log ─────────────────────────────────────────────────────────────\n\nexport type DecisionResult =\n | 'applied'\n | 'skipped_cooldown'\n | 'skipped_simulation_failed'\n | 'skipped_locked'\n | 'skipped_override'\n | 'rolled_back';\n\nexport interface DecisionEntry {\n id: string;\n tick: number;\n timestamp: number;\n diagnosis: Diagnosis;\n plan: ActionPlan;\n result: DecisionResult;\n reasoning: string;\n metricsSnapshot: EconomyMetrics;\n}\n\n// ── Adapter ──────────────────────────────────────────────────────────────────\n\nexport interface EconomyState {\n tick: number;\n roles: string[];\n resources: string[];\n currency: string;\n agentBalances: Record<string, number>;\n agentRoles: Record<string, string>;\n agentInventories: Record<string, Record<string, number>>;\n agentSatisfaction?: Record<string, number>;\n marketPrices: Record<string, number>;\n recentTransactions: EconomicEvent[];\n poolSizes?: Record<string, number>;\n customData?: Record<string, unknown>;\n}\n\nexport interface EconomyAdapter {\n /** Return current full state snapshot */\n getState(): EconomyState | Promise<EconomyState>;\n /** Apply a parameter change to the host system */\n setParam(key: string, value: number): void | Promise<void>;\n /** Optional: adapter pushes events as they happen */\n onEvent?: (handler: (event: EconomicEvent) => void) => void;\n}\n\n// ── Thresholds ────────────────────────────────────────────────────────────────\n\nexport interface Thresholds {\n // Statistical (P42-P43)\n meanMedianDivergenceMax: number;\n simulationMinIterations: number;\n\n // Population (P46)\n personaMonocultureMax: number;\n personaMinClusters: number;\n\n // Open Economy (P34, P47-P48)\n extractionRatioYellow: number;\n extractionRatioRed: number;\n smokeTestWarning: number;\n smokeTestCritical: number;\n currencyInsulationMax: number;\n\n // Player Experience (P45, P50)\n timeBudgetRatio: number;\n payPowerRatioMax: number;\n payPowerRatioTarget: number;\n\n // LiveOps (P51, P53)\n sharkToothPeakDecay: number;\n sharkToothValleyDecay: number;\n eventCompletionMin: number;\n eventCompletionMax: number;\n\n // System Dynamics (P39, P44)\n lagMultiplierMin: number;\n lagMultiplierMax: number;\n complexityBudgetMax: number;\n\n // Resource (P40)\n replacementRateMultiplier: number;\n\n // Regulator (P26-P27)\n maxAdjustmentPercent: number;\n cooldownTicks: number;\n\n // Currency (P13)\n poolWinRate: number; // generic: win rate for competitive pools\n poolHouseCut: number; // generic: house cut for competitive pools\n\n // Population balance (P9)\n roleSwitchFrictionMax: number;\n\n // Pool limits (P15)\n poolCapPercent: number;\n poolDecayRate: number;\n\n // Profitability (P5)\n stampedeProfitRatio: number; // if one role's profit > X× others → stampede risk\n\n // Satisfaction (P24)\n blockedAgentMaxFraction: number;\n\n // Gini (P33)\n giniWarnThreshold: number;\n giniRedThreshold: number;\n\n // Churn (P9)\n churnWarnRate: number;\n\n // Net flow (P12)\n netFlowWarnThreshold: number;\n\n // V1.1 Thresholds (P55-P60)\n arbitrageIndexWarning: number; // P55: yellow alert\n arbitrageIndexCritical: number; // P55: red alert\n contentDropCooldownTicks: number; // P56: ticks to wait after drop before measuring\n postDropArbitrageMax: number; // P56: max acceptable arbitrage during cooldown\n relativePriceConvergenceTarget: number; // P57: fraction of relative prices within ±20% of equilibrium\n priceDiscoveryWindowTicks: number; // P57: ticks to allow for distributed price discovery\n giftTradeFilterRatio: number; // P59: max gift-trade fraction before filtering kicks in\n disposalTradeWeightDiscount: number; // P60: multiplier applied to disposal-trade price signals (0–1)\n}\n\n// ── Tick Configuration ───────────────────────────────────────────────────────\n\nexport interface TickConfig {\n /** How many real-world units one tick represents. Default: 1 */\n duration: number;\n /** The unit of time. Default: 'tick' (abstract). Examples: 'second', 'minute', 'block', 'frame' */\n unit: string;\n /** Medium-resolution metric window in ticks. Default: 10 */\n mediumWindow?: number;\n /** Coarse-resolution metric window in ticks. Default: 100 */\n coarseWindow?: number;\n}\n\n// ── AgentE Config ─────────────────────────────────────────────────────────────\n\nexport type AgentEMode = 'autonomous' | 'advisor';\n\nexport interface AgentEConfig {\n adapter: EconomyAdapter;\n mode?: AgentEMode;\n\n // Economy structure hints\n dominantRoles?: string[]; // roles exempt from population caps\n idealDistribution?: Record<string, number>;\n\n // Tick configuration\n tickConfig?: Partial<TickConfig>;\n\n // Timing\n gracePeriod?: number; // ticks before first intervention (default 50)\n checkInterval?: number; // ticks between checks (default 5)\n\n // Tuning\n maxAdjustmentPercent?: number;\n cooldownTicks?: number;\n\n // Thresholds overrides (partial — merged with defaults)\n thresholds?: Partial<Thresholds>;\n\n // Callbacks\n onDecision?: (entry: DecisionEntry) => void;\n onAlert?: (diagnosis: Diagnosis) => void;\n onRollback?: (plan: ActionPlan, reason: string) => void;\n}\n\n// ── Persona Types ─────────────────────────────────────────────────────────────\n\nexport type PersonaType =\n | 'Active'\n | 'Trader'\n | 'Collector'\n | 'Speculator'\n | 'Earner'\n | 'Builder'\n | 'Social'\n | 'Whale'\n | 'Influencer';\n\nexport interface PersonaProfile {\n type: PersonaType;\n share: number; // fraction of total\n healthyRangeMin: number;\n healthyRangeMax: number;\n}\n\n// ── Metric Query ──────────────────────────────────────────────────────────────\n\nexport type MetricResolution = 'fine' | 'medium' | 'coarse';\n\nexport interface MetricQuery {\n metric: keyof EconomyMetrics | string;\n from?: number; // tick\n to?: number; // tick\n resolution?: MetricResolution;\n}\n\nexport interface MetricQueryResult {\n metric: string;\n resolution: MetricResolution;\n points: Array<{ tick: number; value: number }>;\n}\n","// P1-P4: Supply Chain Principles\n// Source: V0.0-V0.4.6 development failures — ore piling at Forge, hand-off blockage\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P1_ProductionMatchesConsumption: Principle = {\n id: 'P1',\n name: 'Production Must Match Consumption',\n category: 'supply_chain',\n description:\n 'If producer rate < consumer rate, supply deficit kills the economy. ' +\n 'Raw materials piling at production locations happened because this was out of balance.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, demandSignals, populationByRole } = metrics;\n\n // Look for resources with high demand signals but low / declining supply\n const violations: string[] = [];\n for (const resource of Object.keys(demandSignals)) {\n const demand = demandSignals[resource] ?? 0;\n const supply = supplyByResource[resource] ?? 0;\n // Deficit: demand exceeds supply by >50% with meaningful demand\n if (demand > 5 && supply / Math.max(1, demand) < 0.5) {\n violations.push(resource);\n }\n }\n\n // Also check: population imbalance between roles (producers vs consumers)\n const roleEntries = Object.entries(populationByRole).sort((a, b) => b[1] - a[1]);\n const totalPop = metrics.totalAgents;\n const dominantRole = roleEntries[0];\n const dominantCount = dominantRole?.[1] ?? 0;\n const dominantShare = totalPop > 0 ? dominantCount / totalPop : 0;\n\n // If dominant role > 40% but their key resources are scarce, production can't keep up\n const populationImbalance = dominantShare > 0.4 && violations.length > 0;\n\n if (violations.length > 0 || populationImbalance) {\n return {\n violated: true,\n severity: 7,\n evidence: { scarceResources: violations, dominantRole: dominantRole?.[0], dominantShare },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning: 'Lower production cost to incentivise more production.',\n },\n confidence: violations.length > 0 ? 0.85 : 0.6,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P2_ClosedLoopsNeedDirectHandoff: Principle = {\n id: 'P2',\n name: 'Closed Loops Need Direct Handoff',\n category: 'supply_chain',\n description:\n 'Raw materials listed on an open market create noise and liquidity problems. ' +\n 'Gatherers delivering raw materials directly to producers at production zones is faster and cleaner.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, prices, velocity, totalAgents } = metrics;\n\n // Signal: raw materials have high supply but low velocity\n // This suggests they are listed but not being bought\n const avgSupplyPerAgent = totalAgents > 0\n ? Object.values(supplyByResource).reduce((s, v) => s + v, 0) / totalAgents\n : 0;\n\n // Check for ANY resource with excessive supply relative to average\n const backlogResources: string[] = [];\n for (const [resource, supply] of Object.entries(supplyByResource)) {\n const price = prices[resource] ?? 0;\n if (supply > avgSupplyPerAgent * 0.5 && price > 0) {\n backlogResources.push(resource);\n }\n }\n\n const stagnant = velocity < 3;\n\n if (backlogResources.length > 0 && stagnant) {\n return {\n violated: true,\n severity: 5,\n evidence: { backlogResources, velocity },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n 'Raise market fees to discourage raw material listings. ' +\n 'Direct hand-off at production zones is the correct channel.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P3_BootstrapCapitalCoversFirstTransaction: Principle = {\n id: 'P3',\n name: 'Bootstrap Capital Covers First Transaction',\n category: 'supply_chain',\n description:\n 'A new producer must be able to afford their first transaction without selling ' +\n 'anything first. Producer starting with low currency but needing more to accept raw material hand-off ' +\n 'blocks the entire supply chain from tick 1.',\n check(metrics, _thresholds): PrincipleResult {\n const { populationByRole, supplyByResource, prices, totalAgents } = metrics;\n\n // Proxy: if there are agents but supply of ANY produced resource is zero\n // despite positive prices for inputs, bootstrap likely failed\n const totalProducers = Object.values(populationByRole).reduce((s, v) => s + v, 0);\n\n if (totalProducers > 0) {\n // Check for any resource with zero supply but positive input prices\n for (const [resource, supply] of Object.entries(supplyByResource)) {\n if (supply === 0) {\n // Check if there are any priced inputs (suggesting materials available but not being produced)\n const anyInputPriced = Object.values(prices).some(p => p > 0);\n if (anyInputPriced) {\n return {\n violated: true,\n severity: 8,\n evidence: { resource, totalProducers, supply },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.30,\n reasoning:\n 'Producers cannot complete first transaction. ' +\n 'Lower production cost to unblock bootstrap.',\n },\n confidence: 0.80,\n estimatedLag: 3,\n };\n }\n }\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P4_MaterialsFlowFasterThanCooldown: Principle = {\n id: 'P4',\n name: 'Materials Flow Faster Than Cooldown',\n category: 'supply_chain',\n description:\n 'Input delivery rate must exceed or match production cooldown rate. ' +\n 'If producers craft every 5 ticks but only receive raw materials every 10 ticks, ' +\n 'they starve regardless of supply levels.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, populationByRole, velocity, totalAgents } = metrics;\n\n // Check total raw material supply vs total population\n const totalSupply = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n const avgSupplyPerAgent = totalAgents > 0 ? totalSupply / totalAgents : 0;\n\n // Check population ratio across all roles\n const roleEntries = Object.entries(populationByRole);\n const totalRoles = roleEntries.length;\n\n // If there's significant population imbalance and low velocity, may indicate flow issues\n if (totalRoles >= 2 && velocity < 5 && avgSupplyPerAgent < 0.5) {\n return {\n violated: true,\n severity: 5,\n evidence: { avgSupplyPerAgent, velocity, totalRoles },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'increase',\n magnitude: 0.15,\n reasoning: 'Low supply per agent with stagnant velocity. Increase yield to compensate.',\n },\n confidence: 0.65,\n estimatedLag: 8,\n };\n }\n\n // Too much supply piling up: materials accumulating faster than being consumed\n if (avgSupplyPerAgent > 2) {\n return {\n violated: true,\n severity: 4,\n evidence: { avgSupplyPerAgent, totalSupply, totalAgents },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'decrease',\n magnitude: 0.20,\n reasoning: 'Raw materials piling up. Extractors outpacing producers.',\n },\n confidence: 0.80,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P60_SurplusDisposalAsymmetry: Principle = {\n id: 'P60',\n name: 'Surplus Disposal Asymmetry',\n category: 'supply_chain',\n description:\n 'Most trades liquidate unwanted surplus, not deliberate production. ' +\n 'Price signals from disposal trades are weaker demand indicators than ' +\n 'production-for-sale trades — weight them accordingly.',\n check(metrics, thresholds): PrincipleResult {\n const { disposalTradeRatio } = metrics;\n\n // If majority of trades are disposal, price signals are unreliable\n if (disposalTradeRatio > 0.60) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n disposalTradeRatio,\n discount: thresholds.disposalTradeWeightDiscount,\n },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${(disposalTradeRatio * 100).toFixed(0)}% of trades are surplus disposal. ` +\n 'Price signals unreliable as demand indicators. ' +\n 'Lower production costs to shift balance toward deliberate production-for-sale. ' +\n `ADVISORY: Weight disposal-trade prices at ${thresholds.disposalTradeWeightDiscount}× ` +\n 'in index calculations.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const SUPPLY_CHAIN_PRINCIPLES: Principle[] = [\n P1_ProductionMatchesConsumption,\n P2_ClosedLoopsNeedDirectHandoff,\n P3_BootstrapCapitalCoversFirstTransaction,\n P4_MaterialsFlowFasterThanCooldown,\n P60_SurplusDisposalAsymmetry,\n];\n","// P5-P8: Incentive Alignment Principles\n// Source: 97-Trader stampede (V0.4.6), regulator killing bootstrap (V0.4.4)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P5_ProfitabilityIsCompetitive: Principle = {\n id: 'P5',\n name: 'Profitability Is Competitive, Not Absolute',\n category: 'incentive',\n description:\n 'Any profitability formula that returns the same number regardless of how many ' +\n 'agents are already in that role will cause stampedes. ' +\n '97 intermediaries happened because profit = transactions × 10 with no competition denominator.',\n check(metrics, thresholds): PrincipleResult {\n const { roleShares, populationByRole } = metrics;\n\n // Look for roles with disproportionate share that shouldn't dominate\n // Heuristic: any non-primary role above 40% share is suspicious\n const highShareRoles: string[] = [];\n for (const [role, share] of Object.entries(roleShares)) {\n if (share > 0.45) highShareRoles.push(role); // >45% = stampede signal; dominant role at ~44% is healthy design\n }\n\n if (highShareRoles.length > 0) {\n const dominantRole = highShareRoles[0]!;\n return {\n violated: true,\n severity: 6,\n evidence: {\n dominantRole,\n share: roleShares[dominantRole],\n population: populationByRole[dominantRole],\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: thresholds.maxAdjustmentPercent,\n reasoning:\n `${dominantRole} share at ${((roleShares[dominantRole] ?? 0) * 100).toFixed(0)}%. ` +\n 'Likely stampede from non-competitive profitability formula. ' +\n 'Raise market friction to slow role accumulation.',\n },\n confidence: 0.75,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P6_CrowdingMultiplierOnAllRoles: Principle = {\n id: 'P6',\n name: 'Crowding Multiplier Applies to ALL Roles',\n category: 'incentive',\n description:\n 'Every role needs an inverse-population profitability scaling. ' +\n 'A role without crowding pressure is a stampede waiting to happen.',\n check(metrics, _thresholds): PrincipleResult {\n const { roleShares } = metrics;\n\n // Any role above 35% is likely lacking crowding pressure\n // (healthy max for any single role in a diverse economy)\n for (const [role, share] of Object.entries(roleShares)) {\n if (share > 0.35) {\n return {\n violated: true,\n severity: 5,\n evidence: { role, share },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${role} at ${(share * 100).toFixed(0)}% — no crowding pressure detected. ` +\n 'Apply role-specific cost increase to simulate saturation.',\n },\n confidence: 0.70,\n estimatedLag: 10,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P7_NonSpecialistsSubsidiseSpecialists: Principle = {\n id: 'P7',\n name: 'Non-Specialists Subsidise Specialists in Zero-Sum Games',\n category: 'incentive',\n description:\n 'In zero-sum pools (competitive pool, staking), the math only works if non-specialists ' +\n 'overpay relative to specialists. If the pool is >70% specialists, ' +\n 'there is no one left to subsidise and the pot drains.',\n check(metrics, _thresholds): PrincipleResult {\n const { poolSizes } = metrics;\n\n // Check ALL pools: if any pool is growing while participant count is stagnant/declining\n for (const [poolName, poolSize] of Object.entries(poolSizes)) {\n if (poolSize <= 0) continue;\n\n // Get the dominant role (likely the specialist for this pool)\n const roleEntries = Object.entries(metrics.populationByRole);\n if (roleEntries.length === 0) continue;\n\n const [dominantRole, dominantPop] = roleEntries.reduce((max, entry) =>\n entry[1] > max[1] ? entry : max\n );\n\n const total = metrics.totalAgents;\n const dominantShare = dominantPop / Math.max(1, total);\n\n // If dominant role exceeds 70% and pool is small, pool is draining\n if (dominantShare > 0.70 && poolSize < 100) {\n return {\n violated: true,\n severity: 6,\n evidence: { poolName, poolSize, dominantRole, dominantShare },\n suggestedAction: {\n parameter: 'entryFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Pool \"${poolName}\" draining (${poolSize}) — ${dominantRole} at ${(dominantShare * 100).toFixed(0)}%. ` +\n 'Too many specialists, not enough subsidising non-specialists. ' +\n 'Lower entry fee to attract diverse participants.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P8_RegulatorCannotFightDesign: Principle = {\n id: 'P8',\n name: 'Regulator Cannot Fight the Design',\n category: 'incentive',\n description:\n 'If the economy is designed to have a majority role (e.g. dominant role exceeds 55%), ' +\n 'the regulator must know this and exempt that role from population suppression. ' +\n 'AgentE at tick 1 seeing dominant role exceeds 55% and slashing competitive pool rewards is overreach.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is mostly enforced by configuration (dominantRoles).\n // Here we detect a possible signal: dominant role's satisfaction is dropping\n // while their share is also dropping — both together suggest regulator overreach.\n const { roleShares, avgSatisfaction } = metrics;\n\n // If average satisfaction is low (<45) and some role dominates,\n // it may be suppression causing satisfaction decay\n if (avgSatisfaction < 45) {\n const dominantRole = Object.entries(roleShares).sort((a, b) => b[1] - a[1])[0];\n if (dominantRole && dominantRole[1] > 0.30) {\n return {\n violated: true,\n severity: 4,\n evidence: { dominantRole: dominantRole[0], share: dominantRole[1], avgSatisfaction },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Low satisfaction with ${dominantRole[0]} dominant. ` +\n 'Regulator may be suppressing a structurally necessary role. ' +\n 'Ease pressure on dominant role rewards.',\n },\n confidence: 0.55,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const INCENTIVE_PRINCIPLES: Principle[] = [\n P5_ProfitabilityIsCompetitive,\n P6_CrowdingMultiplierOnAllRoles,\n P7_NonSpecialistsSubsidiseSpecialists,\n P8_RegulatorCannotFightDesign,\n];\n","// P9-P11, P46: Population Dynamics Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P9_RoleSwitchingNeedsFriction: Principle = {\n id: 'P9',\n name: 'Role Switching Needs Friction',\n category: 'population',\n description:\n 'If >5% of the population switches roles in a single evaluation period, ' +\n 'it is a herd movement, not rational rebalancing. Without friction ' +\n '(satisfaction cost, cooldown), one good tick causes mass migration.',\n check(metrics, thresholds): PrincipleResult {\n const { churnByRole, roleShares } = metrics;\n\n // Heuristic: any single role that gained >5% share this period\n // We approximate from churnByRole — high churn in one role + gain in another\n const totalChurn = Object.values(churnByRole).reduce((s, v) => s + v, 0);\n if (totalChurn > thresholds.roleSwitchFrictionMax) {\n return {\n violated: true,\n severity: 5,\n evidence: { totalChurnRate: totalChurn, churnByRole },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `Role switch rate ${(totalChurn * 100).toFixed(1)}% exceeds friction threshold. ` +\n 'Increase production costs to slow herd movement.',\n },\n confidence: 0.65,\n estimatedLag: 20,\n };\n }\n\n // Also: if a role went from <10% to >30% very quickly (large share jump)\n // we can't detect this without a previous snapshot, so we rely on churn proxy above.\n void roleShares; // suppresses unused warning\n\n return { violated: false };\n },\n};\n\nexport const P10_SpawnWeightingUsesInversePopulation: Principle = {\n id: 'P10',\n name: 'Spawn Weighting Uses Inverse Population',\n category: 'population',\n description:\n 'New agents should preferentially fill the least-populated roles. ' +\n 'Flat entry probability causes initial imbalances to compound.',\n check(metrics, _thresholds): PrincipleResult {\n const { roleShares } = metrics;\n if (Object.keys(roleShares).length === 0) return { violated: false };\n\n const shares = Object.values(roleShares);\n const mean = shares.reduce((s, v) => s + v, 0) / shares.length;\n // High variance in role shares is a signal that spawn is not balancing\n const variance = shares.reduce((s, v) => s + (v - mean) ** 2, 0) / shares.length;\n const stdDev = Math.sqrt(variance);\n\n if (stdDev > 0.20) {\n const minRole = Object.entries(roleShares).sort((a, b) => a[1] - b[1])[0];\n return {\n violated: true,\n severity: 4,\n evidence: { roleShares, stdDev, leastPopulatedRole: minRole?.[0] },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `High role share variance (σ=${stdDev.toFixed(2)}). ` +\n 'Entry weighting may not be filling under-populated roles. ' +\n 'Increasing yield makes under-populated producer roles more attractive.',\n },\n confidence: 0.60,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P11_TwoTierPressure: Principle = {\n id: 'P11',\n name: 'Two-Tier Pressure (Continuous + Hard)',\n category: 'population',\n description:\n 'Corrections only at thresholds create delayed response. ' +\n 'Continuous gentle pressure (1% per tick toward ideal) plus hard cuts ' +\n 'for extreme cases catches imbalances early.',\n check(metrics, _thresholds): PrincipleResult {\n const { roleShares } = metrics;\n\n // Detect if any role is trending away from ideal for many ticks without correction\n // Proxy: if a role is >40% (hard threshold territory) it means continuous pressure failed\n for (const [role, share] of Object.entries(roleShares)) {\n if (share > 0.45) {\n return {\n violated: true,\n severity: 6,\n evidence: { role, share },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `${role} at ${(share * 100).toFixed(0)}% — continuous pressure was insufficient. ` +\n 'Hard intervention needed alongside resumed continuous pressure.',\n },\n confidence: 0.80,\n estimatedLag: 10,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P46_PersonaDiversity: Principle = {\n id: 'P46',\n name: 'Persona Diversity',\n category: 'population',\n description:\n 'Any single behavioral persona above 40% = monoculture. ' +\n 'Need at least 3 distinct persona clusters each above 15%.',\n check(metrics, thresholds): PrincipleResult {\n const { personaDistribution } = metrics;\n if (Object.keys(personaDistribution).length === 0) return { violated: false };\n\n // Check for monoculture\n for (const [persona, share] of Object.entries(personaDistribution)) {\n if (share > thresholds.personaMonocultureMax) {\n return {\n violated: true,\n severity: 5,\n evidence: { dominantPersona: persona, share, personaDistribution },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${persona} persona at ${(share * 100).toFixed(0)}% — behavioral monoculture. ` +\n 'Diversify reward structures to attract other persona types.',\n },\n confidence: 0.70,\n estimatedLag: 30,\n };\n }\n }\n\n // Check for minimum cluster count\n const significantClusters = Object.values(personaDistribution).filter(s => s >= 0.15).length;\n if (significantClusters < thresholds.personaMinClusters) {\n return {\n violated: true,\n severity: 3,\n evidence: { significantClusters, required: thresholds.personaMinClusters },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.05,\n reasoning:\n `Only ${significantClusters} significant persona clusters (need ${thresholds.personaMinClusters}). ` +\n 'Lower trade barriers to attract non-dominant persona types.',\n },\n confidence: 0.55,\n estimatedLag: 40,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const POPULATION_PRINCIPLES: Principle[] = [\n P9_RoleSwitchingNeedsFriction,\n P10_SpawnWeightingUsesInversePopulation,\n P11_TwoTierPressure,\n P46_PersonaDiversity,\n];\n","// P12-P16, P32: Currency Flow Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P12_OnePrimaryFaucet: Principle = {\n id: 'P12',\n name: 'One Primary Faucet',\n category: 'currency',\n description:\n 'Multiple independent currency sources (gathering + crafting + quests) each ' +\n 'creating gold causes uncontrolled inflation. One clear primary faucet ' +\n 'makes the economy predictable and auditable.',\n check(metrics, thresholds): PrincipleResult {\n const { netFlow, faucetVolume, sinkVolume } = metrics;\n\n if (netFlow > thresholds.netFlowWarnThreshold) {\n return {\n violated: true,\n severity: 5,\n evidence: { netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Net flow +${netFlow.toFixed(1)} g/t. Inflationary. ` +\n 'Increase crafting cost (primary sink) to balance faucet output.',\n },\n confidence: 0.80,\n estimatedLag: 8,\n };\n }\n\n if (netFlow < -thresholds.netFlowWarnThreshold) {\n return {\n violated: true,\n severity: 4,\n evidence: { netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Net flow ${netFlow.toFixed(1)} g/t. Deflationary. ` +\n 'Decrease crafting cost to ease sink pressure.',\n },\n confidence: 0.80,\n estimatedLag: 8,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P13_PotsAreZeroSumAndSelfRegulate: Principle = {\n id: 'P13',\n name: 'Pots Self-Regulate with Correct Multiplier',\n category: 'currency',\n description:\n 'Competitive pot math: winRate × multiplier > (1 - houseCut) drains the pot. ' +\n 'At 65% win rate, multiplier must be ≤ 1.38. We use 1.5 for slight surplus buffer.',\n check(metrics, thresholds): PrincipleResult {\n const { poolSizes, populationByRole } = metrics;\n const totalAgents = metrics.totalAgents;\n\n // Check all pools - find the largest population (likely participants in competitive pools)\n const roleEntries = Object.entries(populationByRole).sort((a, b) => b[1] - a[1]);\n const dominantRole = roleEntries[0]?.[0];\n const dominantCount = roleEntries[0]?.[1] ?? 0;\n\n // For each pool, check if it's draining despite activity\n for (const [poolName, poolSize] of Object.entries(poolSizes)) {\n if (dominantCount > 5 && poolSize < 50) {\n // Estimate if the multiplier math is sustainable\n const { poolWinRate, poolHouseCut } = thresholds;\n const maxSustainableMultiplier = (1 - poolHouseCut) / poolWinRate;\n\n return {\n violated: true,\n severity: 7,\n evidence: { pool: poolName, poolSize, participants: dominantCount, maxSustainableMultiplier },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `${poolName} pool at ${poolSize.toFixed(0)} currency with ${dominantCount} active participants. ` +\n `Sustainable multiplier ≤ ${maxSustainableMultiplier.toFixed(2)}. ` +\n 'Reduce reward multiplier to prevent pool drain.',\n },\n confidence: 0.85,\n estimatedLag: 3,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P14_TrackActualInjection: Principle = {\n id: 'P14',\n name: 'Track Actual Currency Injection, Not Value Creation',\n category: 'currency',\n description:\n 'Counting resource gathering as \"currency injected\" is misleading. ' +\n 'Currency enters through faucet mechanisms (spawning, rewards). ' +\n 'Fake metrics break every downstream decision.',\n check(metrics, _thresholds): PrincipleResult {\n const { faucetVolume, netFlow, totalSupply } = metrics;\n\n // If faucetVolume is suspiciously large relative to any real injection mechanism\n // (spawning), flag for audit. Proxy: if supply grows faster than expected.\n const supplyGrowthRate = Math.abs(netFlow) / Math.max(1, totalSupply);\n\n if (supplyGrowthRate > 0.10) {\n return {\n violated: true,\n severity: 4,\n evidence: { faucetVolume, netFlow, supplyGrowthRate },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Supply growing at ${(supplyGrowthRate * 100).toFixed(1)}%/tick. ` +\n 'Verify gold injection tracking. Resources should not create gold directly.',\n },\n confidence: 0.55,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P15_PoolsNeedCapAndDecay: Principle = {\n id: 'P15',\n name: 'Pools Need Cap + Decay',\n category: 'currency',\n description:\n 'Any pool (bank, reward pool) without a cap accumulates infinitely. ' +\n 'Bank pool at 42% of gold supply means 42% of the economy is frozen. ' +\n 'Cap at 5%, decay at 2%/tick.',\n check(metrics, thresholds): PrincipleResult {\n const { poolSizes, totalSupply } = metrics;\n const { poolCapPercent } = thresholds;\n\n for (const [pool, size] of Object.entries(poolSizes)) {\n const shareOfSupply = size / Math.max(1, totalSupply);\n if (shareOfSupply > poolCapPercent * 2) { // trigger at 2× cap\n return {\n violated: true,\n severity: 6,\n evidence: { pool, size, shareOfSupply, cap: poolCapPercent },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${pool} pool at ${(shareOfSupply * 100).toFixed(1)}% of supply ` +\n `(cap: ${(poolCapPercent * 100).toFixed(0)}%). Gold frozen. ` +\n 'Lower fees to encourage circulation over accumulation.',\n },\n confidence: 0.85,\n estimatedLag: 5,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P16_WithdrawalPenaltyScales: Principle = {\n id: 'P16',\n name: 'Withdrawal Penalty Scales with Lock Duration',\n category: 'currency',\n description:\n 'A 50-tick lock period with a penalty calculated as /100 means agents can ' +\n 'exit after 1 tick and keep 99% of accrued yield. ' +\n 'Penalty must scale linearly: (1 - ticksStaked/lockDuration) × yield.',\n check(metrics, _thresholds): PrincipleResult {\n const { poolSizes, totalSupply } = metrics;\n\n // Check all pools - if any pool is small but locked capital is large, withdrawal penalty is weak\n const stakedEstimate = totalSupply * 0.15; // rough: if 15% staked is healthy\n\n for (const [poolName, poolSize] of Object.entries(poolSizes)) {\n if (poolSize < 10 && stakedEstimate > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: { pool: poolName, poolSize, estimatedStaked: stakedEstimate },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `${poolName} pool depleted while significant currency should be locked. ` +\n 'Early withdrawals may be draining the pool. ' +\n 'Ensure withdrawal penalty scales with lock duration.',\n },\n confidence: 0.45,\n estimatedLag: 10,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P32_VelocityAboveSupply: Principle = {\n id: 'P32',\n name: 'Velocity > Supply for Liquidity',\n category: 'currency',\n description:\n 'Low transactions despite adequate supply means liquidity is trapped. ' +\n 'High supply with low velocity = stagnation, not abundance.',\n check(metrics, _thresholds): PrincipleResult {\n const { velocity, totalSupply, supplyByResource } = metrics;\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n\n // Stagnation: resources exist, gold exists, but nobody is trading\n if (velocity < 3 && totalSupply > 100 && totalResources > 20) {\n return {\n violated: true,\n severity: 4,\n evidence: { velocity, totalSupply, totalResources },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.20,\n reasoning:\n `Velocity ${velocity}/t with ${totalResources} resources in system. ` +\n 'Economy stagnant despite available supply. Lower trading friction.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P58_NoNaturalNumeraire: Principle = {\n id: 'P58',\n name: 'No Natural Numéraire',\n category: 'currency',\n description:\n 'No single commodity naturally stabilizes as currency in barter-heavy economies. ' +\n 'Multiple items rotate as de facto units of account, but none locks in. ' +\n 'If a numéraire is needed, design and enforce it — emergence alone will not produce one.',\n check(metrics, _thresholds): PrincipleResult {\n const { prices, velocity, totalSupply } = metrics;\n\n // Detect barter-dominant economy: high trade velocity but most resources\n // have prices close to each other (no clear numéraire emerging)\n const priceValues = Object.values(prices).filter(p => p > 0);\n if (priceValues.length < 3) return { violated: false };\n\n const mean = priceValues.reduce((s, p) => s + p, 0) / priceValues.length;\n const coeffOfVariation = mean > 0\n ? Math.sqrt(\n priceValues.reduce((s, p) => s + (p - mean) ** 2, 0) / priceValues.length\n ) / mean\n : 0;\n\n // Low CoV = all items priced similarly = no emergent numéraire\n // Combined with high velocity = active barter economy\n if (coeffOfVariation < 0.25 && velocity > 5 && totalSupply > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: {\n coeffOfVariation,\n velocity,\n numResources: priceValues.length,\n meanPrice: mean,\n },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Price coefficient of variation ${coeffOfVariation.toFixed(2)} with velocity ${velocity.toFixed(1)}. ` +\n 'All items priced similarly in an active economy — no natural numéraire emerging. ' +\n 'If a designated currency exists, increase its sink demand to differentiate it.',\n },\n confidence: 0.50,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const CURRENCY_FLOW_PRINCIPLES: Principle[] = [\n P12_OnePrimaryFaucet,\n P13_PotsAreZeroSumAndSelfRegulate,\n P14_TrackActualInjection,\n P15_PoolsNeedCapAndDecay,\n P16_WithdrawalPenaltyScales,\n P32_VelocityAboveSupply,\n P58_NoNaturalNumeraire,\n];\n","// P17-P19: Bootstrap Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P17_GracePeriodBeforeIntervention: Principle = {\n id: 'P17',\n name: 'Grace Period Before Intervention',\n category: 'bootstrap',\n description:\n 'Any intervention before tick 50 is premature. The economy needs time to ' +\n 'bootstrap with designed distributions. AgentE intervening at tick 1 against ' +\n 'dominant role exceeds 55% (designed) killed the economy instantly.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is enforced in the AgentE pipeline itself (gracePeriod config).\n // Here we flag if grace period appears to have ended too early by checking:\n // low satisfaction at very early ticks.\n if (metrics.tick < 30 && metrics.avgSatisfaction < 40) {\n return {\n violated: true,\n severity: 7,\n evidence: { tick: metrics.tick, avgSatisfaction: metrics.avgSatisfaction },\n suggestedAction: {\n parameter: 'entryFee',\n direction: 'decrease',\n magnitude: 0.20,\n reasoning:\n `Very low satisfaction at tick ${metrics.tick}. ` +\n 'Intervention may have fired during grace period. ' +\n 'Ease all costs to let economy bootstrap.',\n },\n confidence: 0.70,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P18_FirstProducerNeedsStartingInventory: Principle = {\n id: 'P18',\n name: 'First Producer Needs Starting Inventory + Capital',\n category: 'bootstrap',\n description:\n 'A producer with 0 resources and 0 currency must sell nothing to get currency before ' +\n 'they can buy raw materials. This creates a chicken-and-egg freeze. ' +\n 'Starting inventory (2 goods + 4 raw materials + 40 currency) breaks the deadlock.',\n check(metrics, _thresholds): PrincipleResult {\n if (metrics.tick > 20) return { violated: false }; // bootstrap window over\n\n // Check all resources: if ANY resource has zero supply while its producers exist\n for (const [resource, supply] of Object.entries(metrics.supplyByResource)) {\n if (supply === 0) {\n // Find roles that produce this resource (heuristic: check if role population exists)\n for (const [role, population] of Object.entries(metrics.populationByRole)) {\n if (population > 0) {\n // Bootstrap failure detected\n return {\n violated: true,\n severity: 8,\n evidence: { tick: metrics.tick, resource, supply, role, population },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.50,\n reasoning:\n `Bootstrap failure: ${role} exists but ${resource} supply is 0 on tick 1-20. ` +\n 'Drastically reduce production cost to allow immediate output.',\n },\n confidence: 0.90,\n estimatedLag: 2,\n };\n }\n }\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P19_StartingSupplyExceedsDemand: Principle = {\n id: 'P19',\n name: 'Starting Supply Exceeds Initial Demand',\n category: 'bootstrap',\n description:\n 'Launch with more consumables than you think you need. ' +\n 'Early scarcity creates a market gridlock where everyone wants to buy ' +\n 'and nobody has anything to sell.',\n check(metrics, _thresholds): PrincipleResult {\n if (metrics.tick > 30) return { violated: false }; // only relevant early\n\n // Find the most-populated role\n const roleEntries = Object.entries(metrics.populationByRole);\n if (roleEntries.length === 0) return { violated: false };\n\n const [mostPopulatedRole, population] = roleEntries.reduce((max, entry) =>\n entry[1] > max[1] ? entry : max\n );\n\n if (population < 5) return { violated: false }; // not enough agents to matter\n\n // Check if this role has zero access to ANY resource they would consume\n // (Heuristic: check all resources - if total supply across all resources < 50% of population)\n const totalResourceSupply = Object.values(metrics.supplyByResource).reduce((sum, s) => sum + s, 0);\n const resourcesPerAgent = totalResourceSupply / Math.max(1, population);\n\n if (resourcesPerAgent < 0.5) {\n return {\n violated: true,\n severity: 6,\n evidence: {\n mostPopulatedRole,\n population,\n totalResourceSupply,\n resourcesPerAgent\n },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `${mostPopulatedRole} (${population} agents) has insufficient resources (${resourcesPerAgent.toFixed(2)} per agent). ` +\n 'Cold-start scarcity. Boost competitive pool reward to attract participation despite scarcity.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const BOOTSTRAP_PRINCIPLES: Principle[] = [\n P17_GracePeriodBeforeIntervention,\n P18_FirstProducerNeedsStartingInventory,\n P19_StartingSupplyExceedsDemand,\n];\n","// P20-P24: Feedback Loop Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P20_DecayPreventsAccumulation: Principle = {\n id: 'P20',\n name: 'Decay Prevents Accumulation',\n category: 'feedback',\n description:\n 'Resources without decay create infinite hoarding. ' +\n 'A gatherer who never sells has 500 raw materials rotting in their pocket ' +\n 'while producers starve. 2-10% decay per period forces circulation.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, velocity, totalAgents } = metrics;\n\n // High supply + low velocity = hoarding, not abundance\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n const resourcesPerAgent = totalResources / Math.max(1, totalAgents);\n\n if (resourcesPerAgent > 20 && velocity < 3) {\n return {\n violated: true,\n severity: 4,\n evidence: { totalResources, resourcesPerAgent, velocity },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${totalResources.toFixed(0)} resources with velocity ${velocity}/t. ` +\n 'Likely hoarding. Reduce yield to increase scarcity and force circulation.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P21_PriceFromGlobalSupply: Principle = {\n id: 'P21',\n name: 'Price Reflects Global Supply, Not Just AH Listings',\n category: 'feedback',\n description:\n 'If prices only update from market activity, agents with hoarded ' +\n 'inventory see artificially high prices and keep gathering when they should stop.',\n check(metrics, _thresholds): PrincipleResult {\n const { priceVolatility, supplyByResource, prices } = metrics;\n\n // High price volatility with stable supply = price disconnected from fundamentals\n for (const resource of Object.keys(prices)) {\n const volatility = priceVolatility[resource] ?? 0;\n const supply = supplyByResource[resource] ?? 0;\n\n if (volatility > 0.30 && supply > 30) {\n return {\n violated: true,\n severity: 3,\n evidence: { resource, volatility, supply, price: prices[resource] },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `${resource} price volatile (${(volatility * 100).toFixed(0)}%) despite supply ${supply}. ` +\n 'Price may not reflect global inventory. Increase trading friction to stabilise.',\n },\n confidence: 0.55,\n estimatedLag: 10,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P22_MarketAwarenessPreventsSurplus: Principle = {\n id: 'P22',\n name: 'Market Awareness Prevents Overproduction',\n category: 'feedback',\n description:\n 'Producers who craft without checking market prices will create surpluses ' +\n 'that crash prices. Agents need to see prices before deciding to produce.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, prices, productionIndex } = metrics;\n\n // Calculate median price across all resources\n const priceValues = Object.values(prices).filter(p => p > 0);\n if (priceValues.length === 0) return { violated: false };\n\n const sortedPrices = [...priceValues].sort((a, b) => a - b);\n const medianPrice = sortedPrices[Math.floor(sortedPrices.length / 2)] ?? 0;\n\n // Check each resource: if price deviates >3× from median while supply is falling\n for (const [resource, price] of Object.entries(prices)) {\n if (price <= 0) continue;\n\n const supply = supplyByResource[resource] ?? 0;\n const priceDeviation = price / Math.max(1, medianPrice);\n\n // Price crash: price < 1/3 median, high supply, still producing\n if (priceDeviation < 0.33 && supply > 100 && productionIndex > 0) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n resource,\n price,\n medianPrice,\n priceDeviation,\n supply,\n productionIndex\n },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${resource} price ${price.toFixed(0)} is ${(priceDeviation * 100).toFixed(0)}% of median (${medianPrice.toFixed(0)}). ` +\n `Supply ${supply} units but still producing. ` +\n 'Producers appear unaware of market. Raise production cost to slow output.',\n },\n confidence: 0.70,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P23_ProfitabilityFactorsFeasibility: Principle = {\n id: 'P23',\n name: 'Profitability Factors Execution Feasibility',\n category: 'feedback',\n description:\n 'An agent who calculates profit = goods_price - materials_cost but has no currency ' +\n 'to buy raw materials is chasing phantom profit. ' +\n 'Feasibility (can I afford the inputs?) must be part of the profitability calc.',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, blockedAgentCount, totalAgents } = metrics;\n\n const blockedFraction = blockedAgentCount / Math.max(1, totalAgents);\n if (blockedFraction > 0.20 && avgSatisfaction < 60) {\n return {\n violated: true,\n severity: 5,\n evidence: { blockedFraction, blockedAgentCount, avgSatisfaction },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `${(blockedFraction * 100).toFixed(0)}% of agents blocked with low satisfaction. ` +\n 'Agents may have roles they cannot afford to execute. ' +\n 'Lower production costs to restore feasibility.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P24_BlockedAgentsDecayFaster: Principle = {\n id: 'P24',\n name: 'Blocked Agents Decay Faster',\n category: 'feedback',\n description:\n 'An agent who cannot perform their preferred activity loses satisfaction faster ' +\n 'and churns sooner. Blocked agents must be identified and unblocked, ' +\n 'or they become silent bottlenecks that skew churn data.',\n check(metrics, thresholds): PrincipleResult {\n const { blockedAgentCount, totalAgents, churnRate } = metrics;\n const blockedFraction = blockedAgentCount / Math.max(1, totalAgents);\n\n if (blockedFraction > thresholds.blockedAgentMaxFraction) {\n return {\n violated: true,\n severity: 5,\n evidence: { blockedFraction, blockedAgentCount, churnRate },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `${(blockedFraction * 100).toFixed(0)}% of agents blocked. ` +\n 'Blocked agents churn silently, skewing metrics. ' +\n 'Lower fees to unblock market participation.',\n },\n confidence: 0.75,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const FEEDBACK_LOOP_PRINCIPLES: Principle[] = [\n P20_DecayPreventsAccumulation,\n P21_PriceFromGlobalSupply,\n P22_MarketAwarenessPreventsSurplus,\n P23_ProfitabilityFactorsFeasibility,\n P24_BlockedAgentsDecayFaster,\n];\n","// P25-P28, P38: Regulator Behavior Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P25_CorrectLeversForCorrectProblems: Principle = {\n id: 'P25',\n name: 'Target the Correct Lever',\n category: 'regulator',\n description:\n 'Adjusting sinks for supply-side inflation is wrong. ' +\n 'Inflation from too much gathering → reduce yield rate. ' +\n 'Inflation from pot payout → reduce reward multiplier. ' +\n 'Matching lever to cause prevents oscillation.',\n check(metrics, thresholds): PrincipleResult {\n const { netFlow, supplyByResource } = metrics;\n\n // Check ALL resources: if any single resource's supply exceeds 3× the average\n const resourceEntries = Object.entries(supplyByResource);\n if (resourceEntries.length === 0) return { violated: false };\n\n const totalSupply = resourceEntries.reduce((sum, [_, s]) => sum + s, 0);\n const avgSupply = totalSupply / resourceEntries.length;\n\n for (const [resource, supply] of resourceEntries) {\n if (supply > avgSupply * 3 && netFlow > thresholds.netFlowWarnThreshold) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n resource,\n supply,\n avgSupply,\n ratio: supply / Math.max(1, avgSupply),\n netFlow\n },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Inflation with ${resource} backlog (${supply} units, ${(supply / Math.max(1, avgSupply)).toFixed(1)}× average). ` +\n 'Root cause is gathering. Correct lever: yieldRate, not fees.',\n },\n confidence: 0.75,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P26_ContinuousPressureBeatsThresholdCuts: Principle = {\n id: 'P26',\n name: 'Continuous 1%/tick > One-Time 10% Cut',\n category: 'regulator',\n description:\n 'Large one-time adjustments cause overshoot and oscillation. ' +\n '1% per tick for 10 ticks reaches the same destination with far less disruption. ' +\n 'This principle is enforced by maxAdjustmentPercent in the Planner.',\n check(metrics, thresholds): PrincipleResult {\n // Detect oscillation: if a metric swings back and forth with high amplitude\n // Proxy: if net flow alternates sign significantly in recent history\n // (This would need history — for now we check the current state for oscillation signals)\n\n const { inflationRate } = metrics;\n // Rapid sign change in inflationRate with large magnitude suggests overcorrection\n if (Math.abs(inflationRate) > 0.20) {\n return {\n violated: true,\n severity: 4,\n evidence: { inflationRate },\n suggestedAction: {\n parameter: 'productionCost',\n direction: inflationRate > 0 ? 'increase' : 'decrease',\n magnitude: Math.min(thresholds.maxAdjustmentPercent, 0.05), // force smaller step\n reasoning:\n `Inflation rate ${(inflationRate * 100).toFixed(1)}% — possible oscillation. ` +\n 'Apply smaller correction to avoid overshoot.',\n },\n confidence: 0.60,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P27_AdjustmentsNeedCooldowns: Principle = {\n id: 'P27',\n name: 'Adjustments Need Cooldowns',\n category: 'regulator',\n description:\n 'Adjusting the same parameter twice in a window causes oscillation. ' +\n 'Minimum 15 ticks between same-parameter adjustments. ' +\n 'This is enforced in the Planner but checked here as a diagnostic.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is enforced structurally by the Planner.\n // As a diagnostic, we flag if churn rate is high AND satisfaction is volatile\n // (which correlates with oscillating economy from rapid adjustments)\n const { churnRate, avgSatisfaction } = metrics;\n\n if (churnRate > 0.08 && avgSatisfaction < 50) {\n return {\n violated: true,\n severity: 4,\n evidence: { churnRate, avgSatisfaction },\n suggestedAction: {\n parameter: 'entryFee',\n direction: 'decrease',\n magnitude: 0.05,\n reasoning:\n `High churn (${(churnRate * 100).toFixed(1)}%) with low satisfaction. ` +\n 'Possible oscillation from rapid adjustments. Apply small correction only.',\n },\n confidence: 0.50,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P28_StructuralDominanceIsNotPathological: Principle = {\n id: 'P28',\n name: 'Structural Dominance ≠ Pathological Monopoly',\n category: 'regulator',\n description:\n 'A designed dominant role (majority exceeds 55%) should not trigger population suppression. ' +\n 'AgentE must distinguish between \"this role is dominant BY DESIGN\" (configured via ' +\n 'dominantRoles) and \"this role took over unexpectedly\".',\n check(metrics, _thresholds): PrincipleResult {\n // This is enforced by the dominantRoles config.\n // As a check: if the most dominant role has high satisfaction,\n // it's likely structural (they're thriving in their designed role), not pathological.\n const { roleShares, avgSatisfaction } = metrics;\n\n const dominant = Object.entries(roleShares).sort((a, b) => b[1] - a[1])[0];\n if (!dominant) return { violated: false };\n\n const [dominantRole, dominantShare] = dominant;\n // Healthy structural dominance: high share + high satisfaction\n if (dominantShare > 0.40 && avgSatisfaction > 70) {\n // Not a violation — this is healthy structural dominance\n return { violated: false };\n }\n\n // Pathological: high share + low satisfaction (agents trapped, not thriving)\n if (dominantShare > 0.40 && avgSatisfaction < 50) {\n return {\n violated: true,\n severity: 5,\n evidence: { dominantRole, dominantShare, avgSatisfaction },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${dominantRole} dominant (${(dominantShare * 100).toFixed(0)}%) with low satisfaction. ` +\n 'Pathological dominance — agents trapped, not thriving. ' +\n 'Ease costs to allow role switching.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P38_CommunicationPreventsRevolt: Principle = {\n id: 'P38',\n name: 'Communication Prevents Revolt',\n category: 'regulator',\n description:\n 'Every adjustment must be logged with reasoning. ' +\n 'An adjustment made without explanation to players causes revolt. ' +\n 'AgentE logs every decision — this principle checks that logging is active.',\n check(metrics, _thresholds): PrincipleResult {\n // This is structurally enforced by DecisionLog. As a diagnostic,\n // we check if churn spiked without any corresponding logged decision.\n // Since we can't access the log here, this is a light sanity check.\n const { churnRate } = metrics;\n if (churnRate > 0.10) {\n return {\n violated: true,\n severity: 3,\n evidence: { churnRate },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `High churn (${(churnRate * 100).toFixed(1)}%) — agents leaving. ` +\n 'Ensure all recent adjustments are logged with reasoning to diagnose cause.',\n },\n confidence: 0.50,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const REGULATOR_PRINCIPLES: Principle[] = [\n P25_CorrectLeversForCorrectProblems,\n P26_ContinuousPressureBeatsThresholdCuts,\n P27_AdjustmentsNeedCooldowns,\n P28_StructuralDominanceIsNotPathological,\n P38_CommunicationPreventsRevolt,\n];\n","// P29-P30: Market Dynamics Principles (from Machinations/Naavik research)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P29_PinchPoint: Principle = {\n id: 'P29',\n name: 'Pinch Point',\n category: 'market_dynamics',\n description:\n 'Every economy has a resource that constrains all downstream activity. ' +\n 'Identify which resource is the pinch point (consumers need them, producers make them). ' +\n 'If demand drops → oversupply. If frustration rises → undersupply.',\n check(metrics, _thresholds): PrincipleResult {\n const { pinchPoints, supplyByResource, demandSignals } = metrics;\n\n // Check each resource marked as a pinch point\n for (const [resource, status] of Object.entries(pinchPoints)) {\n if (status === 'scarce') {\n const supply = supplyByResource[resource] ?? 0;\n const demand = demandSignals[resource] ?? 0;\n return {\n violated: true,\n severity: 7,\n evidence: { resource, supply, demand, status },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `${resource} is a pinch point and currently SCARCE (supply ${supply}, demand ${demand}). ` +\n 'Reduce production cost to increase throughput.',\n },\n confidence: 0.80,\n estimatedLag: 5,\n };\n }\n\n if (status === 'oversupplied') {\n const supply = supplyByResource[resource] ?? 0;\n return {\n violated: true,\n severity: 4,\n evidence: { resource, supply, status },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `${resource} is a pinch point and OVERSUPPLIED (supply ${supply}). ` +\n 'Raise production cost to reduce surplus.',\n },\n confidence: 0.70,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P30_MovingPinchPoint: Principle = {\n id: 'P30',\n name: 'Moving Pinch Point',\n category: 'market_dynamics',\n description:\n 'Agent progression shifts the demand curve. A static pinch point that ' +\n 'works early will be cleared later. The pinch point must move ' +\n 'with agent progression to maintain ongoing scarcity and engagement.',\n check(metrics, _thresholds): PrincipleResult {\n const { capacityUsage, supplyByResource, avgSatisfaction } = metrics;\n\n // Signal: very high capacity usage + high supply of all resources\n // = economy has \"outrun\" the pinch point (everything is easy to get)\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n const resourcesPerAgent = totalResources / Math.max(1, metrics.totalAgents);\n\n if (capacityUsage > 0.90 && resourcesPerAgent > 15 && avgSatisfaction > 75) {\n // High satisfaction + abundant resources = pinch point cleared, no challenge\n return {\n violated: true,\n severity: 3,\n evidence: { capacityUsage, resourcesPerAgent, avgSatisfaction },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n 'Economy operating at full capacity with abundant resources and high satisfaction. ' +\n 'Pinch point may have been cleared. Increase production cost to restore scarcity.',\n },\n confidence: 0.55,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P57_CombinatorialPriceSpace: Principle = {\n id: 'P57',\n name: 'Combinatorial Price Space',\n category: 'market_dynamics',\n description:\n 'N tradeable items generate (N−1)N/2 relative prices. With thousands of items ' +\n 'no single agent can track them all. Design for distributed self-organization, ' +\n 'not centralized pricing.',\n check(metrics, thresholds): PrincipleResult {\n const { prices, priceVolatility } = metrics;\n\n const priceKeys = Object.keys(prices);\n const n = priceKeys.length;\n const relativePriceCount = (n * (n - 1)) / 2;\n\n if (n < 2) return { violated: false };\n\n // Count how many relative prices have converged (low volatility on both sides)\n let convergedPairs = 0;\n for (let i = 0; i < priceKeys.length; i++) {\n for (let j = i + 1; j < priceKeys.length; j++) {\n const volA = priceVolatility[priceKeys[i]!] ?? 0;\n const volB = priceVolatility[priceKeys[j]!] ?? 0;\n // Both items stable = pair converged\n if (volA < 0.20 && volB < 0.20) {\n convergedPairs++;\n }\n }\n }\n\n const convergenceRate = convergedPairs / Math.max(1, relativePriceCount);\n\n if (convergenceRate < thresholds.relativePriceConvergenceTarget && n >= 4) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n totalItems: n,\n relativePriceCount,\n convergedPairs,\n convergenceRate,\n target: thresholds.relativePriceConvergenceTarget,\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Only ${(convergenceRate * 100).toFixed(0)}% of ${relativePriceCount} relative prices ` +\n `have converged (target: ${(thresholds.relativePriceConvergenceTarget * 100).toFixed(0)}%). ` +\n 'Price space too complex for distributed discovery. Lower friction to help.',\n },\n confidence: 0.55,\n estimatedLag: thresholds.priceDiscoveryWindowTicks,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const MARKET_DYNAMICS_PRINCIPLES: Principle[] = [\n P29_PinchPoint,\n P30_MovingPinchPoint,\n P57_CombinatorialPriceSpace,\n];\n","// P31, P41: Measurement Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P31_AnchorValueTracking: Principle = {\n id: 'P31',\n name: 'Anchor Value Tracking',\n category: 'measurement',\n description:\n '1 period of activity = X currency = Y resources. If this ratio drifts, the economy ' +\n 'is inflating or deflating in ways that participants feel before metrics catch it. ' +\n 'Track the ratio constantly.',\n check(metrics, _thresholds): PrincipleResult {\n const { anchorRatioDrift, inflationRate } = metrics;\n\n if (Math.abs(anchorRatioDrift) > 0.25) {\n return {\n violated: true,\n severity: 5,\n evidence: { anchorRatioDrift, inflationRate },\n suggestedAction: {\n parameter: 'productionCost',\n direction: anchorRatioDrift > 0 ? 'increase' : 'decrease',\n magnitude: 0.10,\n reasoning:\n `Anchor ratio has drifted ${(anchorRatioDrift * 100).toFixed(0)}% from baseline. ` +\n 'Time-to-value for participants is changing. Adjust production costs to restore.',\n },\n confidence: 0.65,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P41_MultiResolutionMonitoring: Principle = {\n id: 'P41',\n name: 'Multi-Resolution Monitoring',\n category: 'measurement',\n description:\n 'Single-resolution monitoring misses crises that develop slowly (coarse only) ' +\n 'or explode suddenly (fine only). Monitor at fine (per-tick), medium ' +\n '(per-10-ticks), and coarse (per-100-ticks) simultaneously.',\n check(metrics, _thresholds): PrincipleResult {\n // This principle is enforced structurally by MetricStore.\n // As a diagnostic: if gini is climbing but satisfaction is still high,\n // a coarse-only monitor would miss the early warning.\n const { giniCoefficient, avgSatisfaction } = metrics;\n\n if (giniCoefficient > 0.50 && avgSatisfaction > 65) {\n // Gini rising but agents still happy — coarse monitor would not trigger.\n // Fine monitor catches it early.\n return {\n violated: true,\n severity: 4,\n evidence: { giniCoefficient, avgSatisfaction },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} rising despite okay satisfaction. ` +\n 'Early warning from fine-resolution monitoring. ' +\n 'Raise trading fees to slow wealth concentration before it hurts satisfaction.',\n },\n confidence: 0.70,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P55_ArbitrageThermometer: Principle = {\n id: 'P55',\n name: 'Arbitrage Thermometer',\n category: 'measurement',\n description:\n 'A virtual economy is never in true equilibrium — it oscillates around it. ' +\n 'The aggregate arbitrage window across relative prices is a live health metric: ' +\n 'rising arbitrage signals destabilization, falling signals recovery.',\n check(metrics, thresholds): PrincipleResult {\n const { arbitrageIndex } = metrics;\n\n if (arbitrageIndex > thresholds.arbitrageIndexCritical) {\n return {\n violated: true,\n severity: 7,\n evidence: {\n arbitrageIndex,\n warning: thresholds.arbitrageIndexWarning,\n critical: thresholds.arbitrageIndexCritical,\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Arbitrage index ${arbitrageIndex.toFixed(2)} exceeds critical threshold ` +\n `(${thresholds.arbitrageIndexCritical}). Relative prices are diverging — ` +\n 'economy destabilizing. Lower trading friction to accelerate price convergence.',\n },\n confidence: 0.75,\n estimatedLag: 8,\n };\n }\n\n if (arbitrageIndex > thresholds.arbitrageIndexWarning) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n arbitrageIndex,\n warning: thresholds.arbitrageIndexWarning,\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.08,\n reasoning:\n `Arbitrage index ${arbitrageIndex.toFixed(2)} above warning threshold ` +\n `(${thresholds.arbitrageIndexWarning}). Early sign of price divergence. ` +\n 'Gently reduce friction to support self-correction.',\n },\n confidence: 0.65,\n estimatedLag: 12,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P59_GiftEconomyNoise: Principle = {\n id: 'P59',\n name: 'Gift-Economy Noise',\n category: 'measurement',\n description:\n 'Non-market exchanges — gifts, charity trades, social signaling — contaminate ' +\n 'price signals. Filter gift-like and below-market transactions before computing ' +\n 'economic indicators.',\n check(metrics, thresholds): PrincipleResult {\n const { giftTradeRatio } = metrics;\n\n if (giftTradeRatio > thresholds.giftTradeFilterRatio) {\n return {\n violated: true,\n severity: 4,\n evidence: {\n giftTradeRatio,\n threshold: thresholds.giftTradeFilterRatio,\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `${(giftTradeRatio * 100).toFixed(0)}% of trades are gift-like (price = 0 or <30% market). ` +\n `Exceeds filter threshold (${(thresholds.giftTradeFilterRatio * 100).toFixed(0)}%). ` +\n 'Price signals contaminated. Slightly raise trading fees to discourage zero-value listings. ' +\n 'ADVISORY: Consider filtering sub-market trades from price index computation.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const MEASUREMENT_PRINCIPLES: Principle[] = [\n P31_AnchorValueTracking,\n P41_MultiResolutionMonitoring,\n P55_ArbitrageThermometer,\n P59_GiftEconomyNoise,\n];\n","// P42-P43: Statistical Balancing Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P42_TheMedianPrinciple: Principle = {\n id: 'P42',\n name: 'The Median Principle',\n category: 'statistical',\n description:\n 'When (mean - median) / median > 0.3, mean is a lie. ' +\n 'A few high-balance agents raise the mean while most agents have low balances. ' +\n 'Always balance to median when divergence exceeds 30%.',\n check(metrics, thresholds): PrincipleResult {\n const { meanMedianDivergence, giniCoefficient } = metrics;\n\n if (meanMedianDivergence > thresholds.meanMedianDivergenceMax) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n meanMedianDivergence,\n giniCoefficient,\n meanBalance: metrics.meanBalance,\n medianBalance: metrics.medianBalance,\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Mean/median divergence ${(meanMedianDivergence * 100).toFixed(0)}% ` +\n `(threshold: ${(thresholds.meanMedianDivergenceMax * 100).toFixed(0)}%). ` +\n 'Economy has outliers skewing metrics. Use median for decisions. ' +\n 'Raise auction fees to redistribute wealth.',\n },\n confidence: 0.85,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P43_SimulationMinimum: Principle = {\n id: 'P43',\n name: 'Simulation Minimum (100 Iterations)',\n category: 'statistical',\n description:\n 'Fewer than 100 Monte Carlo iterations produces unreliable predictions. ' +\n 'The variance of a 10-iteration simulation is so high that you might as well ' +\n 'be guessing. This principle enforces the minimum in the Simulator.',\n check(metrics, thresholds): PrincipleResult {\n // This is enforced structurally by the Simulator (iterations >= 100).\n // As a diagnostic: if inflationRate is oscillating wildly, it may indicate\n // decisions were made on insufficient simulation data.\n const { inflationRate } = metrics;\n\n if (Math.abs(inflationRate) > 0.30) {\n return {\n violated: true,\n severity: 3,\n evidence: { inflationRate, minIterations: thresholds.simulationMinIterations },\n suggestedAction: {\n parameter: 'productionCost',\n direction: inflationRate > 0 ? 'increase' : 'decrease',\n magnitude: 0.05,\n reasoning:\n `Large inflation rate swing (${(inflationRate * 100).toFixed(0)}%). ` +\n `Ensure all decisions use ≥${thresholds.simulationMinIterations} simulation iterations. ` +\n 'Apply conservative correction.',\n },\n confidence: 0.50,\n estimatedLag: 5,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const STATISTICAL_PRINCIPLES: Principle[] = [\n P42_TheMedianPrinciple,\n P43_SimulationMinimum,\n];\n","// P39, P44: System Dynamics Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P39_TheLagPrinciple: Principle = {\n id: 'P39',\n name: 'The Lag Principle',\n category: 'system_dynamics',\n description:\n 'Total lag = 3-5× observation interval. If you observe every 5 ticks, ' +\n 'expect effects after 15-25 ticks. Adjusting again before lag expires = overshoot. ' +\n 'This is enforced by the Planner but diagnosed here.',\n check(metrics, thresholds): PrincipleResult {\n const { inflationRate, netFlow } = metrics;\n\n // Detect overshoot pattern: inflation flips direction rapidly\n // Proxy: net flow is in opposite direction to inflation rate\n const inflationPositive = inflationRate > 0.05;\n const netFlowNegative = netFlow < -5;\n const inflationNegative = inflationRate < -0.05;\n const netFlowPositive = netFlow > 5;\n\n const oscillating =\n (inflationPositive && netFlowNegative) || (inflationNegative && netFlowPositive);\n\n if (oscillating) {\n const lagMin = thresholds.lagMultiplierMin;\n const lagMax = thresholds.lagMultiplierMax;\n return {\n violated: true,\n severity: 5,\n evidence: { inflationRate, netFlow, lagRange: [lagMin, lagMax] },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'increase',\n magnitude: 0.03, // very small — oscillation means over-adjusting\n reasoning:\n 'Inflation and net flow moving in opposite directions — overshoot pattern. ' +\n `Wait for lag to resolve (${lagMin}-${lagMax}× observation interval). ` +\n 'Apply minimal correction only.',\n },\n confidence: 0.65,\n estimatedLag: thresholds.lagMultiplierMax * 5, // conservative\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P44_ComplexityBudget: Principle = {\n id: 'P44',\n name: 'Complexity Budget',\n category: 'system_dynamics',\n description:\n 'More than 20 active adjustable parameters → exponential debugging cost. ' +\n 'Each parameter that affects <5% of a core metric should be pruned. ' +\n 'AgentE tracks active parameters and flags when budget exceeded.',\n check(metrics, thresholds): PrincipleResult {\n // This is enforced by the Planner's parameter tracking.\n // As a diagnostic: if many custom metrics are registered with low correlation\n // to core metrics, complexity budget is likely exceeded.\n // Simple proxy: if there are many custom metrics with small values, flag.\n const customMetricCount = Object.keys(metrics.custom).length;\n\n if (customMetricCount > thresholds.complexityBudgetMax) {\n return {\n violated: true,\n severity: 3,\n evidence: { customMetricCount, budgetMax: thresholds.complexityBudgetMax },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.01,\n reasoning:\n `${customMetricCount} custom metrics tracked (budget: ${thresholds.complexityBudgetMax}). ` +\n 'Consider pruning low-impact parameters. ' +\n 'Applying minimal correction to avoid adding complexity.',\n },\n confidence: 0.40,\n estimatedLag: 0,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const SYSTEM_DYNAMICS_PRINCIPLES: Principle[] = [\n P39_TheLagPrinciple,\n P44_ComplexityBudget,\n];\n","// P35, P40, P49: Resource Management Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P35_DestructionCreatesValue: Principle = {\n id: 'P35',\n name: 'Destruction Creates Value',\n category: 'resource',\n description:\n 'If nothing is ever permanently lost, inflation is inevitable. ' +\n 'Resource durability and consumption mechanisms create destruction. ' +\n 'Without them, supply grows without bound.',\n check(metrics, _thresholds): PrincipleResult {\n const { supplyByResource, sinkVolume, netFlow } = metrics;\n\n // Check ALL resources: if any resource has high supply + low destruction\n for (const [resource, supply] of Object.entries(supplyByResource)) {\n if (supply > 200 && sinkVolume < 5 && netFlow > 0) {\n return {\n violated: true,\n severity: 6,\n evidence: { resource, supply, sinkVolume, netFlow },\n suggestedAction: {\n parameter: 'entryFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `${resource} supply at ${supply} units with low destruction (sink ${sinkVolume}/t). ` +\n 'Resources not being consumed. Lower competitive pool entry to increase resource usage.',\n },\n confidence: 0.70,\n estimatedLag: 5,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P40_ReplacementRate: Principle = {\n id: 'P40',\n name: 'Replacement Rate ≥ 2× Consumption',\n category: 'resource',\n description:\n 'Respawn/production rate must be at least 2× consumption rate for equilibrium. ' +\n 'At 1× you drift toward depletion. At 2× you have a buffer for demand spikes.',\n check(metrics, thresholds): PrincipleResult {\n const { productionIndex, sinkVolume } = metrics;\n\n if (sinkVolume > 0 && productionIndex > 0) { // skip if production not tracked (productionIndex=0)\n const replacementRatio = productionIndex / sinkVolume;\n if (replacementRatio < 1.0) {\n return {\n violated: true,\n severity: 6,\n evidence: { productionIndex, sinkVolume, replacementRatio },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Replacement rate ${replacementRatio.toFixed(2)} (need ≥${thresholds.replacementRateMultiplier}). ` +\n 'Production below consumption. Resources will deplete. Increase yield.',\n },\n confidence: 0.80,\n estimatedLag: 5,\n };\n } else if (replacementRatio > thresholds.replacementRateMultiplier * 3) {\n return {\n violated: true,\n severity: 3,\n evidence: { productionIndex, sinkVolume, replacementRatio },\n suggestedAction: {\n parameter: 'yieldRate',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Replacement rate ${replacementRatio.toFixed(2)} — overproducing. ` +\n 'Production far exceeds consumption. Reduce yield to prevent glut.',\n },\n confidence: 0.70,\n estimatedLag: 8,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P49_IdleAssetTax: Principle = {\n id: 'P49',\n name: 'Idle Asset Tax',\n category: 'resource',\n description:\n 'Appreciating assets without holding cost → wealth concentration. ' +\n 'If hoarding an asset makes you richer just by holding it, everyone hoards. ' +\n 'Decay rates, storage costs, or expiry are \"idle asset taxes\" that force circulation.',\n check(metrics, _thresholds): PrincipleResult {\n const { giniCoefficient, top10PctShare, velocity } = metrics;\n\n // High Gini + low velocity + high top-10% share = idle asset hoarding\n if (giniCoefficient > 0.55 && top10PctShare > 0.60 && velocity < 5) {\n return {\n violated: true,\n severity: 5,\n evidence: { giniCoefficient, top10PctShare, velocity },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)}, top 10% hold ${(top10PctShare * 100).toFixed(0)}%, velocity ${velocity}. ` +\n 'Wealth concentrated in idle assets. Raise trading costs to simulate holding tax.',\n },\n confidence: 0.70,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const RESOURCE_MGMT_PRINCIPLES: Principle[] = [\n P35_DestructionCreatesValue,\n P40_ReplacementRate,\n P49_IdleAssetTax,\n];\n","// P33, P37, P45, P50: Player Experience Principles\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P33_FairNotEqual: Principle = {\n id: 'P33',\n name: 'Fair ≠ Equal',\n category: 'player_experience',\n description:\n 'Gini = 0 is boring — everyone has the same and there is nothing to strive for. ' +\n 'Healthy inequality from skill/effort is fine. Inequality from money (pay-to-win) ' +\n 'is toxic. Target Gini 0.3-0.45: meaningful spread, not oligarchy.',\n check(metrics, thresholds): PrincipleResult {\n const { giniCoefficient } = metrics;\n\n if (giniCoefficient < 0.10) {\n return {\n violated: true,\n severity: 3,\n evidence: { giniCoefficient },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} — near-perfect equality. Economy lacks stakes. ` +\n 'Increase winner rewards to create meaningful spread.',\n },\n confidence: 0.60,\n estimatedLag: 20,\n };\n }\n\n if (giniCoefficient > thresholds.giniRedThreshold) {\n return {\n violated: true,\n severity: 7,\n evidence: { giniCoefficient },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} — oligarchy level. Toxic inequality. ` +\n 'Raise transaction fees to redistribute wealth from rich to pool.',\n },\n confidence: 0.85,\n estimatedLag: 10,\n };\n }\n\n if (giniCoefficient > thresholds.giniWarnThreshold) {\n return {\n violated: true,\n severity: 4,\n evidence: { giniCoefficient },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Gini ${giniCoefficient.toFixed(2)} — high inequality warning. ` +\n 'Gently raise fees to slow wealth concentration.',\n },\n confidence: 0.75,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P36_MechanicFrictionDetector: Principle = {\n id: 'P36',\n name: 'Mechanic Friction Detector',\n category: 'player_experience',\n description:\n 'Deterministic + probabilistic systems → expectation mismatch. ' +\n 'When crafting is guaranteed but combat is random, players feel betrayed by ' +\n 'the random side. Mix mechanics carefully or segregate them entirely.',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, churnRate, velocity } = metrics;\n\n // Proxy: High churn despite reasonable economic activity suggests\n // frustration with mechanic mismatch rather than economic problems\n // (Activity exists but players leave anyway = not economic, likely mechanic friction)\n if (churnRate > 0.10 && avgSatisfaction < 50 && velocity > 3) {\n return {\n violated: true,\n severity: 5,\n evidence: { churnRate, avgSatisfaction, velocity },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `Churn ${(churnRate * 100).toFixed(1)}% with satisfaction ${avgSatisfaction.toFixed(0)} ` +\n 'despite active economy (velocity ' + velocity.toFixed(1) + '). ' +\n 'Suggests mechanic friction (deterministic vs random systems). ' +\n 'Increase rewards to compensate for perceived unfairness. ' +\n 'ADVISORY: Review if mixing guaranteed and probabilistic mechanics.',\n },\n confidence: 0.55,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P37_LatecommerProblem: Principle = {\n id: 'P37',\n name: 'Latecomer Problem',\n category: 'player_experience',\n description:\n 'A new participant must reach viability in reasonable time. ' +\n 'If all the good roles are saturated and prices are high, ' +\n 'new agents cannot contribute and churn immediately.',\n check(metrics, _thresholds): PrincipleResult {\n const { timeToValue, avgSatisfaction, churnRate } = metrics;\n\n // High churn + low satisfaction + slow time-to-value = latecomer problem\n if (churnRate > 0.08 && avgSatisfaction < 55 && timeToValue > 20) {\n return {\n violated: true,\n severity: 6,\n evidence: { timeToValue, avgSatisfaction, churnRate },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `New agents taking ${timeToValue} ticks to reach viability. ` +\n `Churn ${(churnRate * 100).toFixed(1)}%, satisfaction ${avgSatisfaction.toFixed(0)}. ` +\n 'Lower production costs to help new participants contribute faster.',\n },\n confidence: 0.70,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P45_TimeBudget: Principle = {\n id: 'P45',\n name: 'Time Budget',\n category: 'player_experience',\n description:\n 'required_time ≤ available_time × 0.8. If the economy requires more engagement ' +\n 'than participants can realistically give, it is a disguised paywall. ' +\n 'The 0.8 buffer accounts for real life.',\n check(metrics, thresholds): PrincipleResult {\n const { timeToValue, avgSatisfaction } = metrics;\n\n // If time to value is very high AND satisfaction is dropping,\n // the economy demands too much time\n const timePressure = timeToValue > 30;\n const dissatisfied = avgSatisfaction < 55;\n\n if (timePressure && dissatisfied) {\n return {\n violated: true,\n severity: 5,\n evidence: { timeToValue, avgSatisfaction, timeBudgetRatio: thresholds.timeBudgetRatio },\n suggestedAction: {\n parameter: 'entryFee',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Time-to-value ${timeToValue} ticks with ${avgSatisfaction.toFixed(0)} satisfaction. ` +\n 'Economy requires too much time investment. Lower barriers to participation.',\n },\n confidence: 0.65,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P50_PayPowerRatio: Principle = {\n id: 'P50',\n name: 'Pay-Power Ratio',\n category: 'player_experience',\n description:\n 'spender / non-spender power ratio > 2.0 = pay-to-win territory. ' +\n 'Target 1.5 (meaningful advantage without shutting out non-payers). ' +\n 'Above 2.0, non-paying participants start leaving.',\n check(metrics, thresholds): PrincipleResult {\n const { top10PctShare, giniCoefficient } = metrics;\n\n // Proxy for pay-power: if top 10% hold disproportionate wealth AND gini is high,\n // wealth advantage is likely translating to power advantage\n const wealthToTopFraction = top10PctShare;\n\n if (wealthToTopFraction > 0.70 && giniCoefficient > 0.55) {\n return {\n violated: true,\n severity: 6,\n evidence: {\n top10PctShare,\n giniCoefficient,\n threshold: thresholds.payPowerRatioMax,\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `Top 10% hold ${(top10PctShare * 100).toFixed(0)}% of wealth (Gini ${giniCoefficient.toFixed(2)}). ` +\n 'Wealth advantage may exceed pay-power ratio threshold. ' +\n 'Redistribute via higher trading fees.',\n },\n confidence: 0.65,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const PLAYER_EXPERIENCE_PRINCIPLES: Principle[] = [\n P33_FairNotEqual,\n P36_MechanicFrictionDetector,\n P37_LatecommerProblem,\n P45_TimeBudget,\n P50_PayPowerRatio,\n];\n","// P34, P47-P48: Open Economy Principles (DeFi / blockchain contexts)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P34_ExtractionRatio: Principle = {\n id: 'P34',\n name: 'Extraction Ratio',\n category: 'open_economy',\n description:\n 'If >65% of participants are net extractors (taking value out without putting it in), ' +\n 'the economy needs external subsidy (new user influx) to survive. ' +\n 'Above 65%, any slowdown in new users collapses the economy.',\n check(metrics, thresholds): PrincipleResult {\n const { extractionRatio } = metrics;\n if (isNaN(extractionRatio)) return { violated: false }; // not tracked for this economy\n\n if (extractionRatio > thresholds.extractionRatioRed) {\n return {\n violated: true,\n severity: 8,\n evidence: { extractionRatio, threshold: thresholds.extractionRatioRed },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.25,\n reasoning:\n `Extraction ratio ${(extractionRatio * 100).toFixed(0)}% (critical: ${(thresholds.extractionRatioRed * 100).toFixed(0)}%). ` +\n 'Economy is extraction-heavy and subsidy-dependent. ' +\n 'Raise fees to increase the cost of extraction.',\n },\n confidence: 0.85,\n estimatedLag: 10,\n };\n }\n\n if (extractionRatio > thresholds.extractionRatioYellow) {\n return {\n violated: true,\n severity: 5,\n evidence: { extractionRatio, threshold: thresholds.extractionRatioYellow },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Extraction ratio ${(extractionRatio * 100).toFixed(0)}% (warning: ${(thresholds.extractionRatioYellow * 100).toFixed(0)}%). ` +\n 'Economy trending toward extraction-heavy. Apply early pressure.',\n },\n confidence: 0.75,\n estimatedLag: 15,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P47_SmokeTest: Principle = {\n id: 'P47',\n name: 'Smoke Test',\n category: 'open_economy',\n description:\n 'intrinsic_utility_value / total_market_value < 0.3 = economy is >70% speculation. ' +\n 'If utility value drops below 10%, a single bad week can collapse the entire market. ' +\n 'Real utility (resources in the economy serve distinct utility functions) must anchor value.',\n check(metrics, thresholds): PrincipleResult {\n const { smokeTestRatio } = metrics;\n if (isNaN(smokeTestRatio)) return { violated: false };\n\n if (smokeTestRatio < thresholds.smokeTestCritical) {\n return {\n violated: true,\n severity: 9,\n evidence: { smokeTestRatio, threshold: thresholds.smokeTestCritical },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.20,\n reasoning:\n `Utility/market ratio ${(smokeTestRatio * 100).toFixed(0)}% (critical). ` +\n 'Economy is >90% speculative. Collapse risk is extreme. ' +\n 'Increase utility rewards to anchor real value.',\n },\n confidence: 0.90,\n estimatedLag: 20,\n };\n }\n\n if (smokeTestRatio < thresholds.smokeTestWarning) {\n return {\n violated: true,\n severity: 6,\n evidence: { smokeTestRatio, threshold: thresholds.smokeTestWarning },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Utility/market ratio ${(smokeTestRatio * 100).toFixed(0)}% (warning). ` +\n 'Economy is >70% speculative. Boost utility rewards to restore intrinsic value anchor.',\n },\n confidence: 0.75,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P48_CurrencyInsulation: Principle = {\n id: 'P48',\n name: 'Currency Insulation',\n category: 'open_economy',\n description:\n 'Gameplay economy correlation with external markets > 0.5 = insulation failure. ' +\n 'When your native currency price correlates with external asset, external market crashes destroy ' +\n 'internal economies. Good design insulates the two.',\n check(metrics, thresholds): PrincipleResult {\n const { currencyInsulation } = metrics;\n if (isNaN(currencyInsulation)) return { violated: false };\n\n if (currencyInsulation > thresholds.currencyInsulationMax) {\n return {\n violated: true,\n severity: 6,\n evidence: { currencyInsulation, threshold: thresholds.currencyInsulationMax },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Currency correlation with external market: ${(currencyInsulation * 100).toFixed(0)}% ` +\n `(max: ${(thresholds.currencyInsulationMax * 100).toFixed(0)}%). ` +\n 'Economy is exposed to external market shocks. ' +\n 'Increase internal friction to reduce external correlation.',\n },\n confidence: 0.70,\n estimatedLag: 30,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const OPEN_ECONOMY_PRINCIPLES: Principle[] = [\n P34_ExtractionRatio,\n P47_SmokeTest,\n P48_CurrencyInsulation,\n];\n","// P51-P54: LiveOps Principles (from Naavik research)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P51_SharkTooth: Principle = {\n id: 'P51',\n name: 'Shark Tooth Pattern',\n category: 'liveops',\n description:\n 'Each event peak should be ≥95% of the previous peak. ' +\n 'If peaks are shrinking (shark tooth becoming flat), event fatigue is setting in. ' +\n 'If valleys are deepening, the off-event economy is failing to sustain engagement.',\n check(metrics, thresholds): PrincipleResult {\n const { sharkToothPeaks, sharkToothValleys } = metrics;\n if (sharkToothPeaks.length < 2) return { violated: false };\n\n const lastPeak = sharkToothPeaks[sharkToothPeaks.length - 1] ?? 0;\n const prevPeak = sharkToothPeaks[sharkToothPeaks.length - 2] ?? 0;\n\n if (prevPeak > 0 && lastPeak / prevPeak < thresholds.sharkToothPeakDecay) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n lastPeak,\n prevPeak,\n ratio: lastPeak / prevPeak,\n threshold: thresholds.sharkToothPeakDecay,\n },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n `Peak engagement dropped to ${(lastPeak / prevPeak * 100).toFixed(0)}% of previous peak ` +\n `(threshold: ${(thresholds.sharkToothPeakDecay * 100).toFixed(0)}%). Event fatigue detected. ` +\n 'Boost event rewards to restore peak engagement.',\n },\n confidence: 0.75,\n estimatedLag: 30,\n };\n }\n\n if (sharkToothValleys.length >= 2) {\n const lastValley = sharkToothValleys[sharkToothValleys.length - 1] ?? 0;\n const prevValley = sharkToothValleys[sharkToothValleys.length - 2] ?? 0;\n if (prevValley > 0 && lastValley / prevValley < thresholds.sharkToothValleyDecay) {\n return {\n violated: true,\n severity: 4,\n evidence: { lastValley, prevValley, ratio: lastValley / prevValley },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n 'Between-event engagement declining (deepening valleys). ' +\n 'Base economy not sustaining participants between events. ' +\n 'Lower production costs to improve off-event value.',\n },\n confidence: 0.65,\n estimatedLag: 20,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const P52_EndowmentEffect: Principle = {\n id: 'P52',\n name: 'Endowment Effect',\n category: 'liveops',\n description:\n 'Participants who never owned premium items do not value them. ' +\n 'Free trial events that let participants experience premium items drive conversions ' +\n 'because ownership creates perceived value (endowment effect).',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, churnRate } = metrics;\n\n // Proxy: if event completion is high but satisfaction is still low,\n // events are not creating the endowment effect (participants complete but don't value the rewards)\n const { eventCompletionRate } = metrics;\n if (isNaN(eventCompletionRate)) return { violated: false };\n\n if (eventCompletionRate > 0.90 && avgSatisfaction < 60) {\n return {\n violated: true,\n severity: 4,\n evidence: { eventCompletionRate, avgSatisfaction, churnRate },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `${(eventCompletionRate * 100).toFixed(0)}% event completion but satisfaction only ${avgSatisfaction.toFixed(0)}. ` +\n 'Events not creating perceived value. Increase reward quality/quantity.',\n },\n confidence: 0.60,\n estimatedLag: 20,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P53_EventCompletionRate: Principle = {\n id: 'P53',\n name: 'Event Completion Rate Sweet Spot',\n category: 'liveops',\n description:\n 'Free completion at 60-80% is the sweet spot. ' +\n '<40% = predatory design. >80% = no monetization pressure. ' +\n '100% free = zero reason to ever spend.',\n check(metrics, thresholds): PrincipleResult {\n const { eventCompletionRate } = metrics;\n if (isNaN(eventCompletionRate)) return { violated: false };\n\n if (eventCompletionRate < thresholds.eventCompletionMin) {\n return {\n violated: true,\n severity: 6,\n evidence: {\n eventCompletionRate,\n min: thresholds.eventCompletionMin,\n max: thresholds.eventCompletionMax,\n },\n suggestedAction: {\n parameter: 'productionCost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Event completion rate ${(eventCompletionRate * 100).toFixed(0)}% — predatory territory ` +\n `(min: ${(thresholds.eventCompletionMin * 100).toFixed(0)}%). ` +\n 'Too hard for free participants. Lower barriers to participation.',\n },\n confidence: 0.80,\n estimatedLag: 10,\n };\n }\n\n if (eventCompletionRate > thresholds.eventCompletionMax) {\n return {\n violated: true,\n severity: 3,\n evidence: { eventCompletionRate, max: thresholds.eventCompletionMax },\n suggestedAction: {\n parameter: 'entryFee',\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `Event completion rate ${(eventCompletionRate * 100).toFixed(0)}% — no monetization pressure ` +\n `(max: ${(thresholds.eventCompletionMax * 100).toFixed(0)}%). ` +\n 'Slightly raise costs to create meaningful premium differentiation.',\n },\n confidence: 0.55,\n estimatedLag: 10,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P54_LiveOpsCadence: Principle = {\n id: 'P54',\n name: 'LiveOps Cadence',\n category: 'liveops',\n description:\n '>50% of events that are re-wrapped existing content → staleness. ' +\n 'The cadence must include genuinely new content at regular intervals. ' +\n 'This is an advisory principle — AgentE can flag but cannot fix content.',\n check(metrics, _thresholds): PrincipleResult {\n // Proxy: declining engagement velocity over time = staleness\n const { velocity, avgSatisfaction } = metrics;\n\n if (velocity < 2 && avgSatisfaction < 55 && metrics.tick > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: { velocity, avgSatisfaction, tick: metrics.tick },\n suggestedAction: {\n parameter: 'rewardRate',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n 'Low velocity and satisfaction after long runtime. ' +\n 'Possible content staleness. Increase rewards as bridge while ' +\n 'new content is developed (developer action required).',\n },\n confidence: 0.40,\n estimatedLag: 30,\n };\n }\n\n return { violated: false };\n },\n};\n\nexport const P56_ContentDropShock: Principle = {\n id: 'P56',\n name: 'Content-Drop Shock',\n category: 'liveops',\n description:\n 'Every new-item injection shatters existing price equilibria — arbitrage spikes ' +\n 'as participants re-price. Build cooldown windows for price discovery before ' +\n 'measuring post-drop economic health.',\n check(metrics, thresholds): PrincipleResult {\n const { contentDropAge, arbitrageIndex } = metrics;\n\n // Only fires during the cooldown window after a content drop\n if (contentDropAge > 0 && contentDropAge <= thresholds.contentDropCooldownTicks) {\n if (arbitrageIndex > thresholds.postDropArbitrageMax) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n contentDropAge,\n arbitrageIndex,\n cooldownTicks: thresholds.contentDropCooldownTicks,\n postDropMax: thresholds.postDropArbitrageMax,\n },\n suggestedAction: {\n parameter: 'transactionFee',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Content drop ${contentDropAge} ticks ago — arbitrage at ${arbitrageIndex.toFixed(2)} ` +\n `exceeds post-drop max (${thresholds.postDropArbitrageMax}). ` +\n 'Price discovery struggling. Lower trading friction temporarily.',\n },\n confidence: 0.60,\n estimatedLag: 5,\n };\n }\n }\n\n return { violated: false };\n },\n};\n\nexport const LIVEOPS_PRINCIPLES: Principle[] = [\n P51_SharkTooth,\n P52_EndowmentEffect,\n P53_EventCompletionRate,\n P54_LiveOpsCadence,\n P56_ContentDropShock,\n];\n","import { SUPPLY_CHAIN_PRINCIPLES } from './supply-chain.js';\nimport { INCENTIVE_PRINCIPLES } from './incentives.js';\nimport { POPULATION_PRINCIPLES } from './population.js';\nimport { CURRENCY_FLOW_PRINCIPLES } from './currency-flow.js';\nimport { BOOTSTRAP_PRINCIPLES } from './bootstrap.js';\nimport { FEEDBACK_LOOP_PRINCIPLES } from './feedback-loops.js';\nimport { REGULATOR_PRINCIPLES } from './regulator.js';\nimport { MARKET_DYNAMICS_PRINCIPLES } from './market-dynamics.js';\nimport { MEASUREMENT_PRINCIPLES } from './measurement.js';\nimport { STATISTICAL_PRINCIPLES } from './statistical.js';\nimport { SYSTEM_DYNAMICS_PRINCIPLES } from './system-dynamics.js';\nimport { RESOURCE_MGMT_PRINCIPLES } from './resource-mgmt.js';\nimport { PLAYER_EXPERIENCE_PRINCIPLES } from './player-experience.js';\nimport { OPEN_ECONOMY_PRINCIPLES } from './open-economy.js';\nimport { LIVEOPS_PRINCIPLES } from './liveops.js';\nimport type { Principle } from '../types.js';\n\nexport * from './supply-chain.js';\nexport * from './incentives.js';\nexport * from './population.js';\nexport * from './currency-flow.js';\nexport * from './bootstrap.js';\nexport * from './feedback-loops.js';\nexport * from './regulator.js';\nexport * from './market-dynamics.js';\nexport * from './measurement.js';\nexport * from './statistical.js';\nexport * from './system-dynamics.js';\nexport * from './resource-mgmt.js';\nexport * from './player-experience.js';\nexport * from './open-economy.js';\nexport * from './liveops.js';\n\n/** All 60 built-in principles in priority order (supply chain → liveops) */\nexport const ALL_PRINCIPLES: Principle[] = [\n ...SUPPLY_CHAIN_PRINCIPLES, // P1-P4, P60\n ...INCENTIVE_PRINCIPLES, // P5-P8\n ...POPULATION_PRINCIPLES, // P9-P11, P46\n ...CURRENCY_FLOW_PRINCIPLES, // P12-P16, P32, P58\n ...BOOTSTRAP_PRINCIPLES, // P17-P19\n ...FEEDBACK_LOOP_PRINCIPLES, // P20-P24\n ...REGULATOR_PRINCIPLES, // P25-P28, P38\n ...MARKET_DYNAMICS_PRINCIPLES, // P29-P30, P57\n ...MEASUREMENT_PRINCIPLES, // P31, P41, P55, P59\n ...STATISTICAL_PRINCIPLES, // P42-P43\n ...SYSTEM_DYNAMICS_PRINCIPLES, // P39, P44\n ...RESOURCE_MGMT_PRINCIPLES, // P35, P40, P49\n ...PLAYER_EXPERIENCE_PRINCIPLES, // P33, P36, P37, P45, P50\n ...OPEN_ECONOMY_PRINCIPLES, // P34, P47-P48\n ...LIVEOPS_PRINCIPLES, // P51-P54, P56\n];\n","// Stage 3: Simulator — forward Monte Carlo projection before any action is applied\n// The single biggest architectural addition in V1 (vs V0's intuition-based adjustments)\n\nimport type {\n EconomyMetrics,\n SuggestedAction,\n SimulationResult,\n SimulationOutcome,\n Thresholds,\n} from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { Diagnoser } from './Diagnoser.js';\nimport { ALL_PRINCIPLES } from './principles/index.js';\n\nexport class Simulator {\n private diagnoser = new Diagnoser(ALL_PRINCIPLES);\n // Cache beforeViolations for the *current* tick only (one entry max).\n // Using a Map here is intentional but the cache must be bounded — we only\n // care about the tick that is currently being evaluated, so we evict any\n // entries whose key differs from the incoming tick.\n private beforeViolationsCache = new Map<number, Set<string>>();\n\n /**\n * Simulate the effect of applying `action` to the current economy forward `forwardTicks`.\n * Runs `iterations` Monte Carlo trials and returns the outcome distribution.\n *\n * The inner model is intentionally lightweight — it models how key metrics evolve\n * under a parameter change using simplified dynamics. This is not a full agent simulation;\n * it is a fast inner model that catches obvious over/under-corrections.\n */\n simulate(\n action: SuggestedAction,\n currentMetrics: EconomyMetrics,\n thresholds: Thresholds,\n iterations: number = 100,\n forwardTicks: number = 20,\n ): SimulationResult {\n const actualIterations = Math.max(thresholds.simulationMinIterations, iterations);\n const outcomes: EconomyMetrics[] = [];\n\n for (let i = 0; i < actualIterations; i++) {\n const projected = this.runForward(currentMetrics, action, forwardTicks, thresholds);\n outcomes.push(projected);\n }\n\n // Sort outcomes by avgSatisfaction to compute percentiles\n const sorted = [...outcomes].sort((a, b) => a.avgSatisfaction - b.avgSatisfaction);\n const p10 = sorted[Math.floor(actualIterations * 0.10)] ?? emptyMetrics();\n const p50 = sorted[Math.floor(actualIterations * 0.50)] ?? emptyMetrics();\n const p90 = sorted[Math.floor(actualIterations * 0.90)] ?? emptyMetrics();\n const mean = this.averageMetrics(outcomes);\n\n // Validate: does p50 improve the diagnosed issue?\n const netImprovement = this.checkImprovement(currentMetrics, p50, action);\n\n // Validate: does the action create new principle violations not present before?\n // Cache beforeViolations per tick to avoid redundant diagnose() calls when\n // evaluating multiple candidate actions at the same tick.\n // IMPORTANT: evict stale entries so the cache stays bounded to 1 entry.\n const tick = currentMetrics.tick;\n if (this.beforeViolationsCache.size > 0 && !this.beforeViolationsCache.has(tick)) {\n this.beforeViolationsCache.clear();\n }\n let beforeViolations = this.beforeViolationsCache.get(tick);\n if (!beforeViolations) {\n beforeViolations = new Set(\n this.diagnoser.diagnose(currentMetrics, thresholds).map(d => d.principle.id),\n );\n this.beforeViolationsCache.set(tick, beforeViolations);\n }\n const afterViolations = new Set(\n this.diagnoser.diagnose(p50, thresholds).map(d => d.principle.id),\n );\n const newViolations = [...afterViolations].filter(id => !beforeViolations.has(id));\n const noNewProblems = newViolations.length === 0;\n\n // Confidence interval on avgSatisfaction\n const satisfactions = outcomes.map(o => o.avgSatisfaction);\n const meanSat = satisfactions.reduce((s, v) => s + v, 0) / satisfactions.length;\n const stdDev = Math.sqrt(\n satisfactions.reduce((s, v) => s + (v - meanSat) ** 2, 0) / satisfactions.length,\n );\n const ci: [number, number] = [meanSat - 1.96 * stdDev, meanSat + 1.96 * stdDev];\n\n // Lag estimation: P39 — effect visible after 3-5× observation interval\n const estimatedEffectTick =\n currentMetrics.tick + thresholds.lagMultiplierMin * 5;\n\n // Overshoot risk: how often does p90 overshoot relative to p50?\n const overshootRisk = sorted\n .slice(Math.floor(actualIterations * 0.80))\n .filter(m => Math.abs(m.netFlow) > Math.abs(currentMetrics.netFlow) * 2).length\n / (actualIterations * 0.20);\n\n return {\n proposedAction: action,\n iterations: actualIterations,\n forwardTicks,\n outcomes: { p10, p50, p90, mean } as SimulationOutcome,\n netImprovement,\n noNewProblems,\n confidenceInterval: ci,\n estimatedEffectTick,\n overshootRisk: Math.min(1, overshootRisk),\n };\n }\n\n /**\n * Lightweight forward model: apply action then project key metrics forward.\n * Uses simplified dynamics — not a full agent replay.\n */\n private runForward(\n metrics: EconomyMetrics,\n action: SuggestedAction,\n ticks: number,\n _thresholds: Thresholds,\n ): EconomyMetrics {\n // Apply the action effect as a multiplier on the relevant metric\n const multiplier = this.actionMultiplier(action);\n\n // Add stochastic noise (Monte Carlo element)\n const noise = () => 1 + (Math.random() - 0.5) * 0.1;\n\n let supply = metrics.totalSupply;\n let satisfaction = metrics.avgSatisfaction;\n let gini = metrics.giniCoefficient;\n let velocity = metrics.velocity;\n let netFlow = metrics.netFlow;\n const churnRate = metrics.churnRate;\n\n for (let t = 0; t < ticks; t++) {\n // Apply action effect on net flow (most actions affect flow)\n const effectOnFlow = this.flowEffect(action, metrics) * multiplier * noise();\n netFlow = netFlow * 0.9 + effectOnFlow * 0.1; // smooth convergence\n\n // Supply drifts with net flow\n supply += netFlow * noise();\n supply = Math.max(0, supply);\n\n // Satisfaction improves when net flow is balanced and supply is stable\n const satDelta = netFlow > 0 && netFlow < 20 ? 0.5 : netFlow < 0 ? -1 : 0;\n satisfaction = Math.min(100, Math.max(0, satisfaction + satDelta * noise()));\n\n // Gini slowly reverts (market pressure)\n gini = gini * 0.99 + 0.35 * 0.01 * noise(); // drift toward 0.35\n\n // Velocity follows supply (more money = more trading)\n velocity = (supply / Math.max(1, metrics.totalAgents)) * 0.01 * noise();\n\n // Agent churn reduces population over time\n const agentLoss = metrics.totalAgents * churnRate * noise();\n void agentLoss; // tracked but not used in simplified model\n }\n\n const projected: EconomyMetrics = {\n ...metrics,\n tick: metrics.tick + ticks,\n totalSupply: supply,\n netFlow,\n velocity,\n giniCoefficient: Math.max(0, Math.min(1, gini)),\n avgSatisfaction: satisfaction,\n inflationRate: metrics.totalSupply > 0 ? (supply - metrics.totalSupply) / metrics.totalSupply : 0,\n };\n\n return projected;\n }\n\n private actionMultiplier(action: SuggestedAction): number {\n const base = action.magnitude ?? 0.10;\n return action.direction === 'increase' ? 1 + base : 1 - base;\n }\n\n private flowEffect(action: SuggestedAction, metrics: EconomyMetrics): number {\n // Rough model: which parameters affect net flow, and in which direction?\n const { parameter, direction } = action;\n const sign = direction === 'increase' ? -1 : 1; // increase cost = reduce flow\n\n // Get dominant role population (highest count)\n const roleEntries = Object.entries(metrics.populationByRole).sort((a, b) => b[1] - a[1]);\n const dominantRoleCount = roleEntries[0]?.[1] ?? 0;\n\n if (parameter === 'productionCost') {\n return sign * metrics.netFlow * 0.2;\n }\n if (parameter === 'transactionFee') {\n return sign * metrics.velocity * 10 * 0.1;\n }\n if (parameter === 'entryFee') {\n return sign * dominantRoleCount * 0.5;\n }\n if (parameter === 'rewardRate') {\n return -sign * dominantRoleCount * 0.3;\n }\n if (parameter === 'yieldRate') {\n return sign * metrics.faucetVolume * 0.15;\n }\n return sign * metrics.netFlow * 0.1;\n }\n\n private checkImprovement(\n before: EconomyMetrics,\n after: EconomyMetrics,\n action: SuggestedAction,\n ): boolean {\n // Net improvement: key metrics should be trending better\n const satisfactionImproved = after.avgSatisfaction >= before.avgSatisfaction - 2;\n const flowMoreBalanced = Math.abs(after.netFlow) <= Math.abs(before.netFlow) * 1.2;\n const notWorseGini = after.giniCoefficient <= before.giniCoefficient + 0.05;\n void action; // could be used for targeted checks\n return satisfactionImproved && flowMoreBalanced && notWorseGini;\n }\n\n private averageMetrics(outcomes: EconomyMetrics[]): EconomyMetrics {\n if (outcomes.length === 0) return emptyMetrics();\n const base = { ...outcomes[0]! };\n const avg = (key: keyof EconomyMetrics) => {\n const vals = outcomes.map(o => o[key] as number).filter(v => typeof v === 'number' && !isNaN(v));\n return vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n };\n return {\n ...base,\n totalSupply: avg('totalSupply'),\n netFlow: avg('netFlow'),\n velocity: avg('velocity'),\n giniCoefficient: avg('giniCoefficient'),\n avgSatisfaction: avg('avgSatisfaction'),\n inflationRate: avg('inflationRate'),\n };\n }\n}\n","// Stage 4: Planner — converts validated diagnosis into a concrete, constrained action plan\n\nimport type {\n Diagnosis,\n ActionPlan,\n Thresholds,\n EconomyMetrics,\n SimulationResult,\n} from './types.js';\n\ninterface ParameterConstraint {\n min: number;\n max: number;\n}\n\nexport class Planner {\n private lockedParams = new Set<string>();\n private constraints = new Map<string, ParameterConstraint>();\n private cooldowns = new Map<string, number>(); // param → last-applied-tick\n private activePlanCount = 0;\n\n lock(param: string): void {\n this.lockedParams.add(param);\n }\n\n unlock(param: string): void {\n this.lockedParams.delete(param);\n }\n\n constrain(param: string, constraint: ParameterConstraint): void {\n this.constraints.set(param, constraint);\n }\n\n /**\n * Convert a diagnosis into an ActionPlan.\n * Returns null if:\n * - parameter is locked\n * - parameter is still in cooldown\n * - simulation result failed\n * - complexity budget exceeded\n */\n plan(\n diagnosis: Diagnosis,\n metrics: EconomyMetrics,\n simulationResult: SimulationResult,\n currentParams: Record<string, number>,\n thresholds: Thresholds,\n ): ActionPlan | null {\n const action = diagnosis.violation.suggestedAction;\n const param = action.parameter;\n\n // Hard checks\n if (this.lockedParams.has(param)) return null;\n if (this.isOnCooldown(param, metrics.tick, thresholds.cooldownTicks)) return null;\n if (!simulationResult.netImprovement) return null;\n if (!simulationResult.noNewProblems) return null;\n\n // Complexity budget (P44)\n if (this.activePlanCount >= thresholds.complexityBudgetMax) return null;\n\n // Compute target value\n const currentValue = currentParams[param] ?? 1.0;\n const magnitude = Math.min(action.magnitude ?? 0.10, thresholds.maxAdjustmentPercent);\n let targetValue: number;\n\n if (action.direction === 'set' && action.absoluteValue !== undefined) {\n targetValue = action.absoluteValue;\n } else if (action.direction === 'increase') {\n targetValue = currentValue * (1 + magnitude);\n } else {\n targetValue = currentValue * (1 - magnitude);\n }\n\n // Apply constraints\n const constraint = this.constraints.get(param);\n if (constraint) {\n targetValue = Math.max(constraint.min, Math.min(constraint.max, targetValue));\n }\n\n // Don't plan if target === current (nothing to do)\n if (Math.abs(targetValue - currentValue) < 0.001) return null;\n\n const estimatedLag =\n diagnosis.violation.estimatedLag ?? simulationResult.estimatedEffectTick - metrics.tick;\n\n const plan: ActionPlan = {\n id: `plan_${metrics.tick}_${param}`,\n diagnosis,\n parameter: param,\n currentValue,\n targetValue,\n maxChangePercent: thresholds.maxAdjustmentPercent,\n cooldownTicks: thresholds.cooldownTicks,\n rollbackCondition: {\n metric: 'avgSatisfaction',\n direction: 'below',\n threshold: Math.max(20, metrics.avgSatisfaction - 10), // rollback if sat drops >10 pts\n checkAfterTick: metrics.tick + estimatedLag + 3,\n },\n simulationResult,\n estimatedLag,\n };\n\n return plan;\n }\n\n recordApplied(plan: ActionPlan, tick: number): void {\n this.cooldowns.set(plan.parameter, tick);\n this.activePlanCount++;\n }\n\n recordRolledBack(_plan: ActionPlan): void {\n this.activePlanCount = Math.max(0, this.activePlanCount - 1);\n }\n\n isOnCooldown(param: string, currentTick: number, cooldownTicks: number): boolean {\n const lastApplied = this.cooldowns.get(param);\n if (lastApplied === undefined) return false;\n return currentTick - lastApplied < cooldownTicks;\n }\n\n /** Reset all cooldowns (useful for testing) */\n resetCooldowns(): void {\n this.cooldowns.clear();\n }\n}\n","// Stage 5: Executor — applies actions to the host system and monitors rollback conditions\n\nimport type { ActionPlan, EconomyMetrics, EconomyAdapter } from './types.js';\n\nexport type ExecutionResult = 'applied' | 'rolled_back' | 'rollback_skipped';\n\ninterface ActivePlan {\n plan: ActionPlan;\n originalValue: number;\n}\n\nexport class Executor {\n private activePlans: ActivePlan[] = [];\n\n async apply(\n plan: ActionPlan,\n adapter: EconomyAdapter,\n currentParams: Record<string, number>,\n ): Promise<void> {\n const originalValue = currentParams[plan.parameter] ?? plan.currentValue;\n await adapter.setParam(plan.parameter, plan.targetValue);\n plan.appliedAt = plan.diagnosis.tick;\n\n this.activePlans.push({ plan, originalValue });\n }\n\n /**\n * Check all active plans for rollback conditions.\n * Called every tick after metrics are computed.\n * Returns list of plans that were rolled back.\n */\n async checkRollbacks(\n metrics: EconomyMetrics,\n adapter: EconomyAdapter,\n ): Promise<ActionPlan[]> {\n const rolledBack: ActionPlan[] = [];\n const remaining: ActivePlan[] = [];\n\n for (const active of this.activePlans) {\n const { plan, originalValue } = active;\n const rc = plan.rollbackCondition;\n\n // Not ready to check yet\n if (metrics.tick < rc.checkAfterTick) {\n remaining.push(active);\n continue;\n }\n\n // Check rollback condition\n const metricValue = this.getMetricValue(metrics, rc.metric);\n const shouldRollback =\n rc.direction === 'below'\n ? metricValue < rc.threshold\n : metricValue > rc.threshold;\n\n if (shouldRollback) {\n // Undo the adjustment\n await adapter.setParam(plan.parameter, originalValue);\n rolledBack.push(plan);\n // Don't push to remaining — remove from tracking\n } else {\n // Plan has passed its check window — consider it settled\n const settledTick = rc.checkAfterTick + 10;\n if (metrics.tick > settledTick) {\n // Plan is settled, stop tracking\n } else {\n remaining.push(active);\n }\n }\n }\n\n this.activePlans = remaining;\n return rolledBack;\n }\n\n private getMetricValue(metrics: EconomyMetrics, metricPath: string): number {\n // Support dotted paths like 'poolSizes.arena' or 'custom.myMetric'\n const parts = metricPath.split('.');\n let value: unknown = metrics;\n for (const part of parts) {\n if (value !== null && typeof value === 'object') {\n value = (value as Record<string, unknown>)[part];\n } else {\n return NaN;\n }\n }\n return typeof value === 'number' ? value : NaN;\n }\n\n getActivePlans(): ActionPlan[] {\n return this.activePlans.map(a => a.plan);\n }\n}\n","// Full-transparency decision logging\n// Every decision AgentE makes is logged with diagnosis, plan, simulation proof, and outcome\n\nimport type { DecisionEntry, DecisionResult, Diagnosis, ActionPlan, EconomyMetrics } from './types.js';\n\nexport class DecisionLog {\n private entries: DecisionEntry[] = [];\n private maxEntries: number;\n\n constructor(maxEntries = 1000) {\n this.maxEntries = maxEntries;\n }\n\n record(\n diagnosis: Diagnosis,\n plan: ActionPlan,\n result: DecisionResult,\n metrics: EconomyMetrics,\n ): DecisionEntry {\n const entry: DecisionEntry = {\n id: `decision_${metrics.tick}_${plan.parameter}`,\n tick: metrics.tick,\n timestamp: Date.now(),\n diagnosis,\n plan,\n result,\n reasoning: this.buildReasoning(diagnosis, plan, result),\n metricsSnapshot: metrics,\n };\n\n this.entries.unshift(entry); // newest first\n if (this.entries.length > this.maxEntries) {\n this.entries.pop();\n }\n\n return entry;\n }\n\n recordSkip(\n diagnosis: Diagnosis,\n result: DecisionResult,\n metrics: EconomyMetrics,\n reason: string,\n ): void {\n const entry: DecisionEntry = {\n id: `skip_${metrics.tick}_${diagnosis.principle.id}`,\n tick: metrics.tick,\n timestamp: Date.now(),\n diagnosis,\n plan: this.stubPlan(diagnosis, metrics),\n result,\n reasoning: reason,\n metricsSnapshot: metrics,\n };\n this.entries.unshift(entry);\n if (this.entries.length > this.maxEntries) this.entries.pop();\n }\n\n query(filter?: {\n since?: number;\n until?: number;\n issue?: string;\n parameter?: string;\n result?: DecisionResult;\n }): DecisionEntry[] {\n return this.entries.filter(e => {\n if (filter?.since !== undefined && e.tick < filter.since) return false;\n if (filter?.until !== undefined && e.tick > filter.until) return false;\n if (filter?.issue && e.diagnosis.principle.id !== filter.issue) return false;\n if (filter?.parameter && e.plan.parameter !== filter.parameter) return false;\n if (filter?.result && e.result !== filter.result) return false;\n return true;\n });\n }\n\n latest(n = 30): DecisionEntry[] {\n return this.entries.slice(0, n);\n }\n\n export(format: 'json' | 'text' = 'json'): string {\n if (format === 'text') {\n return this.entries\n .map(e => `[Tick ${e.tick}] ${e.result.toUpperCase()} — ${e.reasoning}`)\n .join('\\n');\n }\n return JSON.stringify(this.entries, null, 2);\n }\n\n private buildReasoning(\n diagnosis: Diagnosis,\n plan: ActionPlan,\n result: DecisionResult,\n ): string {\n const sim = plan.simulationResult;\n const simSummary =\n `Simulation (${sim.iterations} iterations, ${sim.forwardTicks} ticks forward): ` +\n `p50 satisfaction ${sim.outcomes.p50.avgSatisfaction.toFixed(0)}, ` +\n `net improvement ${sim.netImprovement}, ` +\n `no new problems ${sim.noNewProblems}, ` +\n `overshoot risk ${(sim.overshootRisk * 100).toFixed(0)}%.`;\n\n const actionSummary =\n `[${diagnosis.principle.id}] ${diagnosis.principle.name}: ` +\n `${plan.parameter} ${plan.currentValue.toFixed(3)} → ${plan.targetValue.toFixed(3)}. ` +\n `Severity ${diagnosis.violation.severity}/10, confidence ${(diagnosis.violation.confidence * 100).toFixed(0)}%.`;\n\n if (result === 'applied') {\n return `${actionSummary} ${simSummary} Expected effect in ${plan.estimatedLag} ticks.`;\n }\n\n return `${actionSummary} Skipped (${result}). ${simSummary}`;\n }\n\n private stubPlan(diagnosis: Diagnosis, metrics: EconomyMetrics): ActionPlan {\n const action = diagnosis.violation.suggestedAction;\n return {\n id: `stub_${metrics.tick}`,\n diagnosis,\n parameter: action.parameter,\n currentValue: 1,\n targetValue: 1,\n maxChangePercent: 0,\n cooldownTicks: 0,\n rollbackCondition: {\n metric: 'avgSatisfaction',\n direction: 'below',\n threshold: 0,\n checkAfterTick: 0,\n },\n simulationResult: {\n proposedAction: action,\n iterations: 0,\n forwardTicks: 0,\n outcomes: {\n p10: metrics,\n p50: metrics,\n p90: metrics,\n mean: metrics,\n },\n netImprovement: false,\n noNewProblems: true,\n confidenceInterval: [0, 0],\n estimatedEffectTick: 0,\n overshootRisk: 0,\n },\n estimatedLag: 0,\n };\n }\n}\n","// Multi-resolution metric time-series storage (P41)\n// Three resolutions: fine (every tick), medium (configurable window), coarse (configurable epoch)\n\nimport type { EconomyMetrics, MetricResolution, MetricQuery, MetricQueryResult, TickConfig } from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { DEFAULT_TICK_CONFIG } from './defaults.js';\n\nclass RingBuffer<T> {\n private buf: T[];\n private head = 0;\n private count = 0;\n\n constructor(private readonly capacity: number) {\n this.buf = new Array(capacity);\n }\n\n push(item: T): void {\n this.buf[this.head] = item;\n this.head = (this.head + 1) % this.capacity;\n if (this.count < this.capacity) this.count++;\n }\n\n /** All items in chronological order (oldest first) */\n toArray(): T[] {\n if (this.count === 0) return [];\n const result: T[] = [];\n const start = this.count < this.capacity ? 0 : this.head;\n for (let i = 0; i < this.count; i++) {\n result.push(this.buf[(start + i) % this.capacity]!);\n }\n return result;\n }\n\n last(): T | undefined {\n if (this.count === 0) return undefined;\n const idx = (this.head - 1 + this.capacity) % this.capacity;\n return this.buf[idx];\n }\n\n get length(): number {\n return this.count;\n }\n}\n\nexport class MetricStore {\n /** Fine: last 200 ticks, one entry per tick */\n private fine = new RingBuffer<EconomyMetrics>(200);\n /** Medium: last 200 windows */\n private medium = new RingBuffer<EconomyMetrics>(200);\n /** Coarse: last 200 epochs */\n private coarse = new RingBuffer<EconomyMetrics>(200);\n\n private mediumWindow: number;\n private coarseWindow: number;\n private ticksSinceLastMedium = 0;\n private ticksSinceLastCoarse = 0;\n private mediumAccumulator: EconomyMetrics[] = [];\n private coarseAccumulator: EconomyMetrics[] = [];\n\n constructor(tickConfig?: Partial<TickConfig>) {\n const config = { ...DEFAULT_TICK_CONFIG, ...tickConfig };\n this.mediumWindow = config.mediumWindow!;\n this.coarseWindow = config.coarseWindow!;\n }\n\n record(metrics: EconomyMetrics): void {\n this.fine.push(metrics);\n\n this.mediumAccumulator.push(metrics);\n this.ticksSinceLastMedium++;\n if (this.ticksSinceLastMedium >= this.mediumWindow) {\n this.medium.push(this.aggregate(this.mediumAccumulator));\n this.mediumAccumulator = [];\n this.ticksSinceLastMedium = 0;\n }\n\n this.coarseAccumulator.push(metrics);\n this.ticksSinceLastCoarse++;\n if (this.ticksSinceLastCoarse >= this.coarseWindow) {\n this.coarse.push(this.aggregate(this.coarseAccumulator));\n this.coarseAccumulator = [];\n this.ticksSinceLastCoarse = 0;\n }\n }\n\n latest(resolution: MetricResolution = 'fine'): EconomyMetrics {\n const buf = this.bufferFor(resolution);\n return buf.last() ?? emptyMetrics();\n }\n\n query(q: MetricQuery): MetricQueryResult {\n const resolution: MetricResolution = q.resolution ?? 'fine';\n const buf = this.bufferFor(resolution);\n const all = buf.toArray();\n\n const filtered = all.filter(m => {\n if (q.from !== undefined && m.tick < q.from) return false;\n if (q.to !== undefined && m.tick > q.to) return false;\n return true;\n });\n\n const metricKey = q.metric as keyof EconomyMetrics;\n const points = filtered.map(m => ({\n tick: m.tick,\n value: typeof m[metricKey] === 'number' ? (m[metricKey] as number) : NaN,\n }));\n\n return { metric: q.metric, resolution, points };\n }\n\n /** Check if fine and coarse resolution metrics diverge significantly */\n divergenceDetected(): boolean {\n const f = this.fine.last();\n const c = this.coarse.last();\n if (!f || !c) return false;\n const fineSat = f.avgSatisfaction;\n const coarseSat = c.avgSatisfaction;\n return Math.abs(fineSat - coarseSat) > 20;\n }\n\n private bufferFor(resolution: MetricResolution): RingBuffer<EconomyMetrics> {\n if (resolution === 'medium') return this.medium;\n if (resolution === 'coarse') return this.coarse;\n return this.fine;\n }\n\n private aggregate(snapshots: EconomyMetrics[]): EconomyMetrics {\n if (snapshots.length === 0) return emptyMetrics();\n const last = snapshots[snapshots.length - 1]!;\n // Average numeric scalars, take last for maps/arrays\n const avg = (key: keyof EconomyMetrics): number => {\n const vals = snapshots.map(s => s[key] as number).filter(v => !isNaN(v));\n return vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n };\n\n return {\n ...last,\n totalSupply: avg('totalSupply'),\n netFlow: avg('netFlow'),\n velocity: avg('velocity'),\n inflationRate: avg('inflationRate'),\n giniCoefficient: avg('giniCoefficient'),\n medianBalance: avg('medianBalance'),\n meanBalance: avg('meanBalance'),\n top10PctShare: avg('top10PctShare'),\n meanMedianDivergence: avg('meanMedianDivergence'),\n avgSatisfaction: avg('avgSatisfaction'),\n churnRate: avg('churnRate'),\n blockedAgentCount: avg('blockedAgentCount'),\n faucetVolume: avg('faucetVolume'),\n sinkVolume: avg('sinkVolume'),\n tapSinkRatio: avg('tapSinkRatio'),\n productionIndex: avg('productionIndex'),\n capacityUsage: avg('capacityUsage'),\n anchorRatioDrift: avg('anchorRatioDrift'),\n };\n }\n}\n","// Behavioral persona classification (P46)\n// Classifies agents into 9 behavioral archetypes based on observable signals\n\nimport type { EconomyState, PersonaType } from './types.js';\n\ninterface AgentSignals {\n transactionCount: number;\n netExtraction: number; // gold out - gold in\n uniqueItemsHeld: number;\n holdingDuration: number; // ticks holding items\n spendAmount: number;\n sessionActivity: number; // actions per tick\n socialInteractions: number;\n}\n\nexport class PersonaTracker {\n private agentHistory = new Map<string, AgentSignals[]>();\n\n /** Ingest a state snapshot and update agent signal history */\n update(state: EconomyState): void {\n for (const agentId of Object.keys(state.agentBalances)) {\n const history = this.agentHistory.get(agentId) ?? [];\n const inv = state.agentInventories[agentId] ?? {};\n const uniqueItems = Object.values(inv).filter(q => q > 0).length;\n\n history.push({\n transactionCount: 0, // would be computed from events in full impl\n netExtraction: 0, // gold out vs in\n uniqueItemsHeld: uniqueItems,\n holdingDuration: 1,\n spendAmount: 0,\n sessionActivity: 1,\n socialInteractions: 0,\n });\n\n // Keep last 50 ticks of history\n if (history.length > 50) history.shift();\n this.agentHistory.set(agentId, history);\n }\n }\n\n /** Classify all agents and return persona distribution */\n getDistribution(): Record<string, number> {\n const counts: Record<PersonaType, number> = {\n Active: 0, Trader: 0, Collector: 0, Speculator: 0, Earner: 0,\n Builder: 0, Social: 0, Whale: 0, Influencer: 0,\n };\n let total = 0;\n\n for (const [, history] of this.agentHistory) {\n const persona = this.classify(history);\n counts[persona]++;\n total++;\n }\n\n if (total === 0) return {};\n\n const distribution: Record<string, number> = {};\n for (const [persona, count] of Object.entries(counts)) {\n distribution[persona] = count / total;\n }\n return distribution;\n }\n\n private classify(history: AgentSignals[]): PersonaType {\n if (history.length === 0) return 'Active';\n\n const avg = (key: keyof AgentSignals): number => {\n const vals = history.map(h => h[key]);\n return vals.reduce((s, v) => s + v, 0) / vals.length;\n };\n\n const txRate = avg('transactionCount');\n const extraction = avg('netExtraction');\n const uniqueItems = avg('uniqueItemsHeld');\n const spend = avg('spendAmount');\n\n // Simple rule-based classification (replace with ML in production)\n if (spend > 1000) return 'Whale';\n if (txRate > 10) return 'Trader';\n if (uniqueItems > 5 && extraction < 0) return 'Collector'; // buys and holds\n if (extraction > 100) return 'Earner';\n if (extraction > 50) return 'Speculator';\n return 'Active'; // default: plays for engagement, not profit\n }\n}\n","// AgentE — the main class\n// Observer → Diagnose → Simulate → Plan → Execute\n\nimport type {\n AgentEConfig,\n AgentEMode,\n EconomyAdapter,\n EconomyState,\n EconomicEvent,\n Principle,\n DecisionEntry,\n ActionPlan,\n Thresholds,\n MetricQuery,\n MetricQueryResult,\n} from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { DEFAULT_THRESHOLDS, DEFAULT_TICK_CONFIG } from './defaults.js';\nimport { Observer } from './Observer.js';\nimport { Diagnoser } from './Diagnoser.js';\nimport { Simulator } from './Simulator.js';\nimport { Planner } from './Planner.js';\nimport { Executor } from './Executor.js';\nimport { DecisionLog } from './DecisionLog.js';\nimport { MetricStore } from './MetricStore.js';\nimport { PersonaTracker } from './PersonaTracker.js';\nimport { ALL_PRINCIPLES } from './principles/index.js';\n\ntype EventName = 'decision' | 'alert' | 'rollback' | 'beforeAction' | 'afterAction';\n\nexport class AgentE {\n // ── Config ──\n private readonly config: Required<\n Omit<AgentEConfig, 'adapter' | 'thresholds' | 'onDecision' | 'onAlert' | 'onRollback'>\n >;\n private readonly thresholds: Thresholds;\n private adapter!: EconomyAdapter;\n private mode: AgentEMode;\n\n // ── Pipeline ──\n private observer!: Observer;\n private diagnoser: Diagnoser;\n private simulator = new Simulator();\n private planner = new Planner();\n private executor = new Executor();\n\n // ── State ──\n readonly log = new DecisionLog();\n readonly store!: MetricStore;\n private personaTracker = new PersonaTracker();\n private params: Record<string, number> = {};\n private eventBuffer: EconomicEvent[] = [];\n private isRunning = false;\n private isPaused = false;\n private currentTick = 0;\n\n // ── Event handlers ──\n private handlers = new Map<EventName, Array<(...args: unknown[]) => unknown>>();\n\n constructor(config: AgentEConfig) {\n this.mode = config.mode ?? 'autonomous';\n\n this.config = {\n mode: this.mode,\n dominantRoles: config.dominantRoles ?? [],\n idealDistribution: config.idealDistribution ?? {},\n tickConfig: config.tickConfig ?? { duration: 1, unit: 'tick' },\n gracePeriod: config.gracePeriod ?? 50,\n checkInterval: config.checkInterval ?? 5,\n maxAdjustmentPercent: config.maxAdjustmentPercent ?? 0.15,\n cooldownTicks: config.cooldownTicks ?? 15,\n };\n\n this.thresholds = {\n ...DEFAULT_THRESHOLDS,\n ...(config.thresholds ?? {}),\n maxAdjustmentPercent: config.maxAdjustmentPercent ?? DEFAULT_THRESHOLDS.maxAdjustmentPercent,\n cooldownTicks: config.cooldownTicks ?? DEFAULT_THRESHOLDS.cooldownTicks,\n };\n\n // Resolve TickConfig and pass to Observer and MetricStore\n const tickConfig = { ...DEFAULT_TICK_CONFIG, ...config.tickConfig };\n this.observer = new Observer(tickConfig);\n this.store = new MetricStore(tickConfig);\n\n this.diagnoser = new Diagnoser(ALL_PRINCIPLES);\n\n // Wire up config callbacks\n if (config.onDecision) this.on('decision', config.onDecision as never);\n if (config.onAlert) this.on('alert', config.onAlert as never);\n if (config.onRollback) this.on('rollback', config.onRollback as never);\n\n // Lock dominant roles from population suppression by locking arena reward adjustments\n // (structural protection — dominant roles' key param won't be suppressed)\n if (config.dominantRoles && config.dominantRoles.length > 0) {\n // Mark dominant roles as protected (used in Diagnoser context)\n // This is a lightweight approach — in production, principles query this list.\n }\n }\n\n // ── Connection ──────────────────────────────────────────────────────────────\n\n connect(adapter: EconomyAdapter): this {\n this.adapter = adapter;\n\n // Wire up event stream if adapter supports it\n if (adapter.onEvent) {\n adapter.onEvent(event => this.eventBuffer.push(event));\n }\n\n return this;\n }\n\n start(): this {\n if (!this.adapter) throw new Error('[AgentE] Call .connect(adapter) before .start()');\n this.isRunning = true;\n this.isPaused = false;\n return this;\n }\n\n pause(): void {\n this.isPaused = true;\n }\n\n resume(): void {\n this.isPaused = false;\n }\n\n stop(): void {\n this.isRunning = false;\n this.isPaused = false;\n }\n\n // ── Main cycle (call once per tick from your economy loop) ─────────────────\n\n async tick(state?: EconomyState): Promise<void> {\n if (!this.isRunning || this.isPaused) return;\n\n // Fetch state if not provided (polling mode)\n const currentState = state ?? (await Promise.resolve(this.adapter.getState()));\n this.currentTick = currentState.tick;\n\n // Drain event buffer\n const events = [...this.eventBuffer];\n this.eventBuffer = [];\n\n // Stage 1: Observe\n const metrics = this.observer.compute(currentState, events);\n this.store.record(metrics);\n this.personaTracker.update(currentState);\n metrics.personaDistribution = this.personaTracker.getDistribution();\n\n // Check rollbacks on active plans\n const rolledBack = await this.executor.checkRollbacks(metrics, this.adapter);\n for (const plan of rolledBack) {\n this.planner.recordRolledBack(plan);\n this.emit('rollback', plan, 'rollback condition triggered');\n }\n\n // Grace period — no interventions\n if (metrics.tick < this.config.gracePeriod) return;\n\n // Only run the full pipeline every checkInterval ticks\n if (metrics.tick % this.config.checkInterval !== 0) return;\n\n // Stage 2: Diagnose\n const diagnoses = this.diagnoser.diagnose(metrics, this.thresholds);\n\n // Alert on all violations (regardless of whether we act)\n for (const diagnosis of diagnoses) {\n this.emit('alert', diagnosis);\n }\n\n // Only act on the top-priority issue (prevents oscillation from multi-action)\n const topDiagnosis = diagnoses[0];\n if (!topDiagnosis) return;\n\n // Stage 3: Simulate\n const simulationResult = this.simulator.simulate(\n topDiagnosis.violation.suggestedAction,\n metrics,\n this.thresholds,\n 100, // always >= minimum (P43)\n 20,\n );\n\n // Stage 4: Plan\n const plan = this.planner.plan(\n topDiagnosis,\n metrics,\n simulationResult,\n this.params,\n this.thresholds,\n );\n\n if (!plan) {\n // Log the skip\n let reason = 'skipped_cooldown';\n if (!simulationResult.netImprovement) reason = 'skipped_simulation_failed';\n this.log.recordSkip(topDiagnosis, reason as never, metrics, `Skipped: ${reason}`);\n return;\n }\n\n // Advisor mode: emit recommendation, don't apply\n if (this.mode === 'advisor') {\n const entry = this.log.record(topDiagnosis, plan, 'skipped_override', metrics);\n this.emit('decision', entry);\n return;\n }\n\n // beforeAction hook — veto if handler returns false\n const vetoed = this.emit('beforeAction', plan);\n if (vetoed === false) {\n this.log.recordSkip(topDiagnosis, 'skipped_override', metrics, 'vetoed by beforeAction hook');\n return;\n }\n\n // Stage 5: Execute\n await this.executor.apply(plan, this.adapter, this.params);\n this.params[plan.parameter] = plan.targetValue;\n this.planner.recordApplied(plan, metrics.tick);\n\n const entry = this.log.record(topDiagnosis, plan, 'applied', metrics);\n this.emit('decision', entry);\n this.emit('afterAction', entry);\n }\n\n /** Apply a plan manually (for advisor mode) */\n async apply(plan: ActionPlan): Promise<void> {\n await this.executor.apply(plan, this.adapter, this.params);\n this.params[plan.parameter] = plan.targetValue;\n this.planner.recordApplied(plan, this.currentTick);\n }\n\n // ── Developer API ───────────────────────────────────────────────────────────\n\n lock(param: string): void {\n this.planner.lock(param);\n }\n\n unlock(param: string): void {\n this.planner.unlock(param);\n }\n\n constrain(param: string, bounds: { min: number; max: number }): void {\n this.planner.constrain(param, bounds);\n }\n\n addPrinciple(principle: Principle): void {\n this.diagnoser.addPrinciple(principle);\n }\n\n removePrinciple(id: string): void {\n this.diagnoser.removePrinciple(id);\n }\n\n registerCustomMetric(name: string, fn: (state: EconomyState) => number): void {\n this.observer.registerCustomMetric(name, fn);\n }\n\n getDecisions(filter?: Parameters<DecisionLog['query']>[0]): DecisionEntry[] {\n return this.log.query(filter);\n }\n\n getPrinciples(): Principle[] {\n return this.diagnoser.getPrinciples();\n }\n\n getActivePlans(): ActionPlan[] {\n return this.executor.getActivePlans();\n }\n\n /** Access to the metric time-series store */\n readonly metrics = {\n query: (q: MetricQuery): MetricQueryResult => this.store.query(q),\n latest: (resolution?: 'fine' | 'medium' | 'coarse') => this.store.latest(resolution),\n };\n\n // ── Events ──────────────────────────────────────────────────────────────────\n\n on(event: EventName, handler: (...args: unknown[]) => unknown): this {\n const list = this.handlers.get(event) ?? [];\n list.push(handler);\n this.handlers.set(event, list);\n return this;\n }\n\n off(event: EventName, handler: (...args: unknown[]) => unknown): this {\n const list = this.handlers.get(event) ?? [];\n this.handlers.set(event, list.filter(h => h !== handler));\n return this;\n }\n\n private emit(event: EventName, ...args: unknown[]): unknown {\n const list = this.handlers.get(event) ?? [];\n let result: unknown;\n for (const handler of list) {\n result = handler(...args);\n if (result === false) return false; // veto\n }\n return result;\n }\n\n // ── Diagnostics ─────────────────────────────────────────────────────────────\n\n diagnoseNow(): ReturnType<Diagnoser['diagnose']> {\n const metrics = this.store.latest();\n return this.diagnoser.diagnose(metrics, this.thresholds);\n }\n\n getHealth(): number {\n const m = this.store.latest();\n if (m.tick === 0) return 100;\n let health = 100;\n if (m.avgSatisfaction < 65) health -= 15;\n if (m.avgSatisfaction < 50) health -= 10;\n if (m.giniCoefficient > 0.45) health -= 15;\n if (m.giniCoefficient > 0.60) health -= 10;\n if (Math.abs(m.netFlow) > 10) health -= 15;\n if (Math.abs(m.netFlow) > 20) health -= 10;\n if (m.churnRate > 0.05) health -= 15;\n return Math.max(0, Math.min(100, health));\n }\n\n // ── Ingest events directly (event-driven mode) ───────────────────────────\n\n ingest(event: EconomicEvent): void {\n this.eventBuffer.push(event);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,qBAAiC;AAAA;AAAA,EAE5C,yBAAyB;AAAA,EACzB,yBAAyB;AAAA;AAAA,EAGzB,uBAAuB;AAAA,EACvB,oBAAoB;AAAA;AAAA,EAGpB,uBAAuB;AAAA,EACvB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,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