@agent-e/core 1.6.2 → 1.6.4

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../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/participant-experience.ts","../src/principles/open-economy.ts","../src/principles/operations.ts","../src/principles/index.ts","../src/Simulator.ts","../src/Planner.ts","../src/Executor.ts","../src/DecisionLog.ts","../src/MetricStore.ts","../src/PersonaTracker.ts","../src/ParameterRegistry.ts","../src/AgentE.ts","../src/utils.ts","../src/StateValidator.ts"],"sourcesContent":["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 // Participant Experience (P45, P50)\n timeBudgetRatio: 0.80,\n payPowerRatioMax: 2.0,\n payPowerRatioTarget: 1.5,\n\n // Operations (P51, P53)\n cyclicalPeakDecay: 0.95,\n cyclicalValleyDecay: 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 poolOperatorShare: 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 HighValue: { 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 previousPricesByCurrency: Record<string, Record<string, number>> = {};\n private customMetricFns: Record<string, (state: EconomyState) => number> = {};\n private anchorBaselineByCurrency: Record<string, { currencyPerPeriod: number; itemsPerCurrency: number }> = {};\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 if (!state.currencies || state.currencies.length === 0) {\n console.warn('[AgentE] Warning: state.currencies is empty. Metrics will be zeroed.');\n }\n if (!state.agentBalances || Object.keys(state.agentBalances).length === 0) {\n console.warn('[AgentE] Warning: state.agentBalances is empty.');\n }\n\n const tick = state.tick;\n const roles = Object.values(state.agentRoles);\n const totalAgents = Object.keys(state.agentBalances).length;\n\n // ── Event classification (single pass, per-currency) ──\n let productionAmount = 0;\n const faucetVolumeByCurrency: Record<string, number> = {};\n const sinkVolumeByCurrency: Record<string, number> = {};\n const tradeEvents: EconomicEvent[] = [];\n const roleChangeEvents: EconomicEvent[] = [];\n let churnCount = 0;\n const defaultCurrency = state.currencies[0] ?? 'default';\n\n for (const e of recentEvents) {\n const curr = e.currency ?? defaultCurrency;\n switch (e.type) {\n case 'mint':\n case 'enter':\n faucetVolumeByCurrency[curr] = (faucetVolumeByCurrency[curr] ?? 0) + (e.amount ?? 0);\n break;\n case 'burn':\n case 'consume':\n sinkVolumeByCurrency[curr] = (sinkVolumeByCurrency[curr] ?? 0) + (e.amount ?? 0);\n break;\n case 'produce':\n productionAmount += e.amount ?? 1;\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 // ── Per-system & per-source/sink tracking ──\n const flowBySystem: Record<string, number> = {};\n const activityBySystem: Record<string, number> = {};\n const actorsBySystem: Record<string, Set<string>> = {};\n const flowBySource: Record<string, number> = {};\n const flowBySink: Record<string, number> = {};\n\n for (const e of recentEvents) {\n if (e.system) {\n activityBySystem[e.system] = (activityBySystem[e.system] ?? 0) + 1;\n if (!actorsBySystem[e.system]) actorsBySystem[e.system] = new Set();\n actorsBySystem[e.system]!.add(e.actor);\n\n const amt = e.amount ?? 0;\n if (e.type === 'mint') {\n flowBySystem[e.system] = (flowBySystem[e.system] ?? 0) + amt;\n } else if (e.type === 'burn' || e.type === 'consume') {\n flowBySystem[e.system] = (flowBySystem[e.system] ?? 0) - amt;\n }\n }\n if (e.sourceOrSink) {\n const amt = e.amount ?? 0;\n if (e.type === 'mint') {\n flowBySource[e.sourceOrSink] = (flowBySource[e.sourceOrSink] ?? 0) + amt;\n } else if (e.type === 'burn' || e.type === 'consume') {\n flowBySink[e.sourceOrSink] = (flowBySink[e.sourceOrSink] ?? 0) + amt;\n }\n }\n }\n\n const participantsBySystem: Record<string, number> = {};\n for (const [sys, actors] of Object.entries(actorsBySystem)) {\n participantsBySystem[sys] = actors.size;\n }\n\n const totalSourceFlow = Object.values(flowBySource).reduce((s, v) => s + v, 0);\n const sourceShare: Record<string, number> = {};\n for (const [src, vol] of Object.entries(flowBySource)) {\n sourceShare[src] = totalSourceFlow > 0 ? vol / totalSourceFlow : 0;\n }\n\n const totalSinkFlow = Object.values(flowBySink).reduce((s, v) => s + v, 0);\n const sinkShare: Record<string, number> = {};\n for (const [snk, vol] of Object.entries(flowBySink)) {\n sinkShare[snk] = totalSinkFlow > 0 ? vol / totalSinkFlow : 0;\n }\n\n const currencies = state.currencies;\n\n // ── Per-currency supply ──\n const totalSupplyByCurrency: Record<string, number> = {};\n const balancesByCurrency: Record<string, number[]> = {};\n\n for (const [_agentId, balances] of Object.entries(state.agentBalances)) {\n for (const [curr, bal] of Object.entries(balances)) {\n totalSupplyByCurrency[curr] = (totalSupplyByCurrency[curr] ?? 0) + bal;\n if (!balancesByCurrency[curr]) balancesByCurrency[curr] = [];\n balancesByCurrency[curr]!.push(bal);\n }\n }\n\n // ── Per-currency flow ──\n const netFlowByCurrency: Record<string, number> = {};\n const tapSinkRatioByCurrency: Record<string, number> = {};\n const inflationRateByCurrency: Record<string, number> = {};\n const velocityByCurrency: Record<string, number> = {};\n\n for (const curr of currencies) {\n const faucet = faucetVolumeByCurrency[curr] ?? 0;\n const sink = sinkVolumeByCurrency[curr] ?? 0;\n netFlowByCurrency[curr] = faucet - sink;\n tapSinkRatioByCurrency[curr] = sink > 0 ? Math.min(faucet / sink, 100) : faucet > 0 ? 100 : 1;\n\n const prevSupply = this.previousMetrics?.totalSupplyByCurrency?.[curr] ?? totalSupplyByCurrency[curr] ?? 0;\n const currSupply = totalSupplyByCurrency[curr] ?? 0;\n inflationRateByCurrency[curr] = prevSupply > 0 ? (currSupply - prevSupply) / prevSupply : 0;\n\n // Velocity: trades involving this currency / supply\n const currTrades = tradeEvents.filter(e => (e.currency ?? defaultCurrency) === curr);\n velocityByCurrency[curr] = currSupply > 0 ? currTrades.length / currSupply : 0;\n }\n\n // ── Per-currency wealth distribution ──\n const giniCoefficientByCurrency: Record<string, number> = {};\n const medianBalanceByCurrency: Record<string, number> = {};\n const meanBalanceByCurrency: Record<string, number> = {};\n const top10PctShareByCurrency: Record<string, number> = {};\n const meanMedianDivergenceByCurrency: Record<string, number> = {};\n\n for (const curr of currencies) {\n const bals = balancesByCurrency[curr] ?? [];\n const sorted = [...bals].sort((a, b) => a - b);\n const supply = totalSupplyByCurrency[curr] ?? 0;\n const count = sorted.length;\n\n const median = computeMedian(sorted);\n const mean = count > 0 ? supply / count : 0;\n const top10Idx = Math.floor(count * 0.9);\n const top10Sum = sorted.slice(top10Idx).reduce((s, b) => s + b, 0);\n\n giniCoefficientByCurrency[curr] = computeGini(sorted);\n medianBalanceByCurrency[curr] = median;\n meanBalanceByCurrency[curr] = mean;\n top10PctShareByCurrency[curr] = supply > 0 ? top10Sum / supply : 0;\n meanMedianDivergenceByCurrency[curr] = median > 0 ? Math.abs(mean - median) / median : 0;\n }\n\n // ── Aggregates (sum/avg across all currencies) ──\n const avgOf = (rec: Record<string, number>): number => {\n const vals = Object.values(rec);\n return vals.length > 0 ? vals.reduce((s, v) => s + v, 0) / vals.length : 0;\n };\n\n const totalSupply = Object.values(totalSupplyByCurrency).reduce((s, v) => s + v, 0);\n const faucetVolume = Object.values(faucetVolumeByCurrency).reduce((s, v) => s + v, 0);\n const sinkVolume = Object.values(sinkVolumeByCurrency).reduce((s, v) => s + v, 0);\n const netFlow = faucetVolume - sinkVolume;\n const tapSinkRatio = sinkVolume > 0 ? Math.min(faucetVolume / sinkVolume, 100) : faucetVolume > 0 ? 100 : 1;\n const velocity = totalSupply > 0 ? tradeEvents.length / totalSupply : 0;\n const prevTotalSupply = this.previousMetrics?.totalSupply ?? totalSupply;\n const inflationRate = prevTotalSupply > 0 ? (totalSupply - prevTotalSupply) / prevTotalSupply : 0;\n\n // Aggregate wealth: average across currencies\n const giniCoefficient = avgOf(giniCoefficientByCurrency);\n const medianBalance = avgOf(medianBalanceByCurrency);\n const meanBalance = totalAgents > 0 ? totalSupply / totalAgents : 0;\n const top10PctShare = avgOf(top10PctShareByCurrency);\n const meanMedianDivergence = avgOf(meanMedianDivergenceByCurrency);\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 // ── Per-currency prices ──\n const pricesByCurrency: Record<string, Record<string, number>> = {};\n const priceVolatilityByCurrency: Record<string, Record<string, number>> = {};\n const priceIndexByCurrency: Record<string, number> = {};\n\n for (const [curr, resourcePrices] of Object.entries(state.marketPrices)) {\n pricesByCurrency[curr] = { ...resourcePrices };\n const pricePrev = this.previousPricesByCurrency?.[curr] ?? {};\n const volMap: Record<string, number> = {};\n for (const [resource, price] of Object.entries(resourcePrices)) {\n const prev = pricePrev[resource] ?? price;\n volMap[resource] = prev > 0 ? Math.abs(price - prev) / prev : 0;\n }\n priceVolatilityByCurrency[curr] = volMap;\n\n const pVals = Object.values(resourcePrices);\n priceIndexByCurrency[curr] = pVals.length > 0 ? pVals.reduce((s, p) => s + p, 0) / pVals.length : 0;\n }\n this.previousPricesByCurrency = Object.fromEntries(\n Object.entries(pricesByCurrency).map(([c, p]) => [c, { ...p }])\n );\n\n // Aggregate prices: use first currency as default\n const prices = pricesByCurrency[defaultCurrency] ?? {};\n const priceVolatility = priceVolatilityByCurrency[defaultCurrency] ?? {};\n const priceIndex = priceIndexByCurrency[defaultCurrency] ?? 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 > 0 && d > 2 && s / d < 0.5) {\n pinchPoints[resource] = 'scarce';\n } else if (d > 0 && s > 3 && s / d > 3) {\n pinchPoints[resource] = 'oversupplied';\n } else {\n pinchPoints[resource] = 'optimal';\n }\n }\n\n const productionIndex = productionAmount;\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 = totalAgents > 0 ? blockedAgentCount / totalAgents * 100 : 0;\n\n // ── Per-currency pools ──\n const poolSizesByCurrency: Record<string, Record<string, number>> = {};\n const poolSizesAggregate: Record<string, number> = {};\n\n if (state.poolSizes) {\n for (const [pool, currencyAmounts] of Object.entries(state.poolSizes)) {\n poolSizesByCurrency[pool] = { ...currencyAmounts };\n poolSizesAggregate[pool] = Object.values(currencyAmounts).reduce((s, v) => s + v, 0);\n }\n }\n\n // ── Per-currency anchor baseline ──\n const anchorRatioDriftByCurrency: Record<string, number> = {};\n if (tick === 1) {\n for (const curr of currencies) {\n const supply = totalSupplyByCurrency[curr] ?? 0;\n if (supply > 0) {\n this.anchorBaselineByCurrency[curr] = {\n currencyPerPeriod: supply / Math.max(1, totalAgents),\n itemsPerCurrency: (priceIndexByCurrency[curr] ?? 0) > 0 ? 1 / priceIndexByCurrency[curr]! : 0,\n };\n }\n }\n }\n for (const curr of currencies) {\n const baseline = this.anchorBaselineByCurrency[curr];\n if (baseline && totalAgents > 0) {\n const currentCPP = (totalSupplyByCurrency[curr] ?? 0) / totalAgents;\n anchorRatioDriftByCurrency[curr] = baseline.currencyPerPeriod > 0\n ? (currentCPP - baseline.currencyPerPeriod) / baseline.currencyPerPeriod\n : 0;\n } else {\n anchorRatioDriftByCurrency[curr] = 0;\n }\n }\n const anchorRatioDrift = avgOf(anchorRatioDriftByCurrency);\n\n // ── V1.1 Metrics ──\n\n // ── Per-currency arbitrage index ──\n // O(n) arbitrage index: standard deviation of log prices\n const arbitrageIndexByCurrency: Record<string, number> = {};\n for (const curr of currencies) {\n const cPrices = pricesByCurrency[curr] ?? {};\n const logPrices = Object.values(cPrices).filter(p => p > 0).map(p => Math.log(p));\n if (logPrices.length >= 2) {\n const mean = logPrices.reduce((s, v) => s + v, 0) / logPrices.length;\n const variance = logPrices.reduce((s, v) => s + (v - mean) ** 2, 0) / logPrices.length;\n arbitrageIndexByCurrency[curr] = Math.min(1, Math.sqrt(variance));\n } else {\n arbitrageIndexByCurrency[curr] = 0;\n }\n }\n const arbitrageIndex = avgOf(arbitrageIndexByCurrency);\n\n // contentDropAge: ticks since last 'produce' event with metadata.contentDrop === true\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 // ── Per-currency gift/disposal trade ratios ──\n const giftTradeRatioByCurrency: Record<string, number> = {};\n const disposalTradeRatioByCurrency: Record<string, number> = {};\n for (const curr of currencies) {\n const currTrades = tradeEvents.filter(e => (e.currency ?? defaultCurrency) === curr);\n const cPrices = pricesByCurrency[curr] ?? {};\n let gifts = 0;\n let disposals = 0;\n for (const e of currTrades) {\n const marketPrice = cPrices[e.resource ?? ''] ?? 0;\n const tradePrice = e.price ?? 0;\n if (tradePrice === 0 || (marketPrice > 0 && tradePrice < marketPrice * 0.3)) gifts++;\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) disposals++;\n }\n }\n giftTradeRatioByCurrency[curr] = currTrades.length > 0 ? gifts / currTrades.length : 0;\n disposalTradeRatioByCurrency[curr] = currTrades.length > 0 ? disposals / currTrades.length : 0;\n }\n const giftTradeRatio = avgOf(giftTradeRatioByCurrency);\n const disposalTradeRatio = avgOf(disposalTradeRatioByCurrency);\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 (err) {\n console.warn(`[AgentE] Custom metric '${name}' threw an error:`, err);\n custom[name] = 0;\n }\n }\n\n const metrics: EconomyMetrics = {\n tick,\n timestamp: Date.now(),\n currencies,\n\n // Per-currency\n totalSupplyByCurrency,\n netFlowByCurrency,\n velocityByCurrency,\n inflationRateByCurrency,\n faucetVolumeByCurrency,\n sinkVolumeByCurrency,\n tapSinkRatioByCurrency,\n anchorRatioDriftByCurrency,\n giniCoefficientByCurrency,\n medianBalanceByCurrency,\n meanBalanceByCurrency,\n top10PctShareByCurrency,\n meanMedianDivergenceByCurrency,\n priceIndexByCurrency,\n pricesByCurrency,\n priceVolatilityByCurrency,\n poolSizesByCurrency,\n extractionRatioByCurrency: {},\n newUserDependencyByCurrency: {},\n currencyInsulationByCurrency: {},\n arbitrageIndexByCurrency,\n giftTradeRatioByCurrency,\n disposalTradeRatioByCurrency,\n\n // Aggregates\n totalSupply,\n netFlow,\n velocity,\n inflationRate,\n faucetVolume,\n sinkVolume,\n tapSinkRatio,\n anchorRatioDrift,\n giniCoefficient,\n medianBalance,\n meanBalance,\n top10PctShare,\n meanMedianDivergence,\n priceIndex,\n prices,\n priceVolatility,\n poolSizes: poolSizesAggregate,\n extractionRatio: 0,\n newUserDependency: 0,\n smokeTestRatio: 0,\n currencyInsulation: 0,\n arbitrageIndex,\n giftTradeRatio,\n disposalTradeRatio,\n\n // Unchanged\n populationByRole,\n roleShares,\n totalAgents,\n churnRate,\n churnByRole,\n personaDistribution: {}, // populated by PersonaTracker\n productionIndex,\n capacityUsage,\n supplyByResource,\n demandSignals,\n pinchPoints,\n avgSatisfaction,\n blockedAgentCount,\n timeToValue,\n cyclicalPeaks: this.previousMetrics?.cyclicalPeaks ?? [],\n cyclicalValleys: this.previousMetrics?.cyclicalValleys ?? [],\n eventCompletionRate: 0,\n contentDropAge,\n systems: state.systems ?? [],\n sources: state.sources ?? [],\n sinks: state.sinks ?? [],\n flowBySystem,\n activityBySystem,\n participantsBySystem,\n flowBySource,\n flowBySink,\n sourceShare,\n sinkShare,\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.min(1, 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 | 'enter'\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 currency?: string; // which currency this event affects (defaults to first in currencies[])\n amount?: number; // quantity\n price?: number; // per-unit price (in the event's currency)\n from?: string; // source (for transfers)\n to?: string; // destination\n system?: string; // which subsystem generated this event\n sourceOrSink?: string; // named source/sink for flow attribution\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 currencies: string[]; // all tracked currencies this tick\n\n // ── Currency health (per-currency) ──\n totalSupplyByCurrency: Record<string, number>; // currency → total supply\n netFlowByCurrency: Record<string, number>; // currency → faucets minus sinks\n velocityByCurrency: Record<string, number>; // currency → transactions / supply\n inflationRateByCurrency: Record<string, number>; // currency → % change per period\n faucetVolumeByCurrency: Record<string, number>; // currency → inflow volume\n sinkVolumeByCurrency: Record<string, number>; // currency → outflow volume\n tapSinkRatioByCurrency: Record<string, number>; // currency → faucet / sink ratio\n anchorRatioDriftByCurrency: Record<string, number>;// currency → anchor drift\n\n // ── Currency health (aggregate convenience — sum/avg of all currencies) ──\n totalSupply: number;\n netFlow: number;\n velocity: number;\n inflationRate: number;\n faucetVolume: number;\n sinkVolume: number;\n tapSinkRatio: number;\n anchorRatioDrift: number;\n\n // ── Wealth distribution (per-currency) ──\n giniCoefficientByCurrency: Record<string, number>;\n medianBalanceByCurrency: Record<string, number>;\n meanBalanceByCurrency: Record<string, number>;\n top10PctShareByCurrency: Record<string, number>;\n meanMedianDivergenceByCurrency: Record<string, number>;\n\n // ── Wealth distribution (aggregate convenience) ──\n giniCoefficient: number;\n medianBalance: number;\n meanBalance: number;\n top10PctShare: number;\n meanMedianDivergence: number;\n\n // ── Population health (unchanged — not currency-specific) ──\n populationByRole: Record<string, number>;\n roleShares: Record<string, number>;\n totalAgents: number;\n churnRate: number;\n churnByRole: Record<string, number>;\n personaDistribution: Record<string, number>;\n\n // ── Market health (per-currency prices) ──\n priceIndexByCurrency: Record<string, number>; // currency → equal-weight price basket\n pricesByCurrency: Record<string, Record<string, number>>; // currency → resource → price\n priceVolatilityByCurrency: Record<string, Record<string, number>>; // currency → resource → volatility\n\n // ── Market health (aggregate convenience) ──\n priceIndex: number;\n prices: Record<string, number>; // first currency's prices (backward compat)\n priceVolatility: Record<string, number>; // first currency's volatility\n\n // ── Market health (unchanged — resource-keyed, not currency-specific) ──\n productionIndex: number;\n capacityUsage: number;\n supplyByResource: Record<string, number>;\n demandSignals: Record<string, number>;\n pinchPoints: Record<string, PinchPointStatus>;\n\n // ── Satisfaction / Engagement (unchanged) ──\n avgSatisfaction: number;\n blockedAgentCount: number;\n timeToValue: number;\n\n // ── Pools (per-currency) ──\n poolSizesByCurrency: Record<string, Record<string, number>>; // pool → currency → amount\n poolSizes: Record<string, number>; // aggregate: pool → sum of all currencies\n\n // ── Open economy (per-currency) ──\n extractionRatioByCurrency: Record<string, number>;\n newUserDependencyByCurrency: Record<string, number>;\n currencyInsulationByCurrency: Record<string, number>;\n\n // ── Open economy (aggregate convenience) ──\n extractionRatio: number;\n newUserDependency: number;\n smokeTestRatio: number;\n currencyInsulation: number;\n\n // ── Operations (unchanged) ──\n cyclicalPeaks: number[];\n cyclicalValleys: number[];\n eventCompletionRate: number;\n\n // ── V1.1 Metrics (per-currency where applicable) ──\n arbitrageIndexByCurrency: Record<string, number>; // per-currency cross-resource arbitrage\n arbitrageIndex: number; // aggregate\n contentDropAge: number; // unchanged (not currency-specific)\n giftTradeRatioByCurrency: Record<string, number>;\n giftTradeRatio: number;\n disposalTradeRatioByCurrency: Record<string, number>;\n disposalTradeRatio: number;\n\n // ── Topology (from EconomyState) ──\n systems: string[]; // registered systems\n sources: string[]; // registered source names\n sinks: string[]; // registered sink names\n\n // ── Multi-system metrics ──\n flowBySystem: Record<string, number>; // system → net flow\n activityBySystem: Record<string, number>; // system → event count\n participantsBySystem: Record<string, number>; // system → unique actor count\n flowBySource: Record<string, number>; // source → inflow volume\n flowBySink: Record<string, number>; // sink → outflow volume\n sourceShare: Record<string, number>; // source → fraction of total inflow\n sinkShare: Record<string, number>; // sink → fraction of total outflow\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 currencies: [],\n\n // Per-currency\n totalSupplyByCurrency: {},\n netFlowByCurrency: {},\n velocityByCurrency: {},\n inflationRateByCurrency: {},\n faucetVolumeByCurrency: {},\n sinkVolumeByCurrency: {},\n tapSinkRatioByCurrency: {},\n anchorRatioDriftByCurrency: {},\n giniCoefficientByCurrency: {},\n medianBalanceByCurrency: {},\n meanBalanceByCurrency: {},\n top10PctShareByCurrency: {},\n meanMedianDivergenceByCurrency: {},\n priceIndexByCurrency: {},\n pricesByCurrency: {},\n priceVolatilityByCurrency: {},\n poolSizesByCurrency: {},\n extractionRatioByCurrency: {},\n newUserDependencyByCurrency: {},\n currencyInsulationByCurrency: {},\n arbitrageIndexByCurrency: {},\n giftTradeRatioByCurrency: {},\n disposalTradeRatioByCurrency: {},\n\n // Aggregates\n totalSupply: 0,\n netFlow: 0,\n velocity: 0,\n inflationRate: 0,\n faucetVolume: 0,\n sinkVolume: 0,\n tapSinkRatio: 1,\n anchorRatioDrift: 0,\n giniCoefficient: 0,\n medianBalance: 0,\n meanBalance: 0,\n top10PctShare: 0,\n meanMedianDivergence: 0,\n priceIndex: 0,\n prices: {},\n priceVolatility: {},\n poolSizes: {},\n extractionRatio: 0,\n newUserDependency: 0,\n smokeTestRatio: 0,\n currencyInsulation: 0,\n arbitrageIndex: 0,\n giftTradeRatio: 0,\n disposalTradeRatio: 0,\n\n // Unchanged\n populationByRole: {},\n roleShares: {},\n totalAgents: 0,\n churnRate: 0,\n churnByRole: {},\n personaDistribution: {},\n productionIndex: 0,\n capacityUsage: 0,\n supplyByResource: {},\n demandSignals: {},\n pinchPoints: {},\n avgSatisfaction: 100,\n blockedAgentCount: 0,\n timeToValue: 0,\n cyclicalPeaks: [],\n cyclicalValleys: [],\n eventCompletionRate: 0,\n contentDropAge: 0,\n systems: [],\n sources: [],\n sinks: [],\n flowBySystem: {},\n activityBySystem: {},\n participantsBySystem: {},\n flowBySource: {},\n flowBySink: {},\n sourceShare: {},\n sinkShare: {},\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 | 'participant_experience'\n | 'statistical'\n | 'system_dynamics'\n | 'open_economy'\n | 'operations';\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 parameterType: import('./ParameterRegistry.js').ParameterType;\n direction: 'increase' | 'decrease' | 'set';\n magnitude?: number; // fractional (0.15 = 15%)\n absoluteValue?: number;\n scope?: Partial<import('./ParameterRegistry.js').ParameterScope>;\n resolvedParameter?: string; // filled by Planner after registry resolution\n reasoning: string;\n}\n\nexport interface ActionPlan {\n id: string;\n diagnosis: Diagnosis;\n parameter: string;\n scope?: import('./ParameterRegistry.js').ParameterScope;\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 | 'rejected';\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 currencies: string[]; // e.g. ['gold', 'gems', 'stakingToken']\n agentBalances: Record<string, Record<string, number>>; // agentId → { currencyName → balance }\n agentRoles: Record<string, string>;\n agentInventories: Record<string, Record<string, number>>;\n agentSatisfaction?: Record<string, number>;\n marketPrices: Record<string, Record<string, number>>; // currencyName → { resource → price }\n recentTransactions: EconomicEvent[];\n poolSizes?: Record<string, Record<string, number>>; // poolName → { currencyName → amount }\n systems?: string[]; // e.g. ['marketplace', 'staking', 'production']\n sources?: string[]; // named faucet sources\n sinks?: string[]; // named sink channels\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, scope?: import('./ParameterRegistry.js').ParameterScope): 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 // Participant Experience (P45, P50)\n timeBudgetRatio: number;\n payPowerRatioMax: number;\n payPowerRatioTarget: number;\n\n // Operations (P51, P53)\n cyclicalPeakDecay: number;\n cyclicalValleyDecay: 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 pools (competitive, liquidity, staking, etc.)\n poolOperatorShare: number; // generic: operator's share of pool proceeds\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\n// ── Simulation Config ─────────────────────────────────────────────────────────\n\nexport interface SimulationConfig {\n sinkMultiplier?: number; // default 0.20\n faucetMultiplier?: number; // default 0.15\n frictionMultiplier?: number; // default 0.10\n frictionVelocityScale?: number; // default 10\n redistributionMultiplier?: number; // default 0.30\n neutralMultiplier?: number; // default 0.05\n minIterations?: number; // default 100\n maxProjectionTicks?: number; // default 20\n}\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 // Parameter registry\n parameters?: import('./ParameterRegistry.js').RegisteredParameter[];\n /** Run registry.validate() on startup and log warnings/errors (default: true) */\n validateRegistry?: boolean;\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 // Simulation tuning\n simulation?: SimulationConfig;\n\n // Executor settlement window (ticks before plan auto-settles; default: 200)\n settlementWindowTicks?: 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 | 'Whale'\n | 'ActiveTrader'\n | 'Accumulator'\n | 'Spender'\n | 'NewEntrant'\n | 'AtRisk'\n | 'Dormant'\n | 'PowerUser'\n | 'Passive'\n | string; // extensible — adapters can add domain-specific labels\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: Supply-chain failure patterns — resource accumulation at bottlenecks, 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 parameterType: 'cost',\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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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 parameterType: 'cost',\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 produce 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 parameterType: 'yield',\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 parameterType: 'yield',\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 parameterType: 'cost',\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: Incentive failure patterns — population stampedes, regulator suppressing bootstrap\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P5_ProfitabilityIsRelative: Principle = {\n id: 'P5',\n name: 'Profitability Is Relative, 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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'cost',\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 (staking, prize pools, etc.), 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 parameterType: 'fee', scope: { tags: ['entry'] },\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 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 parameterType: 'reward',\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_ProfitabilityIsRelative,\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, minimum interval), 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 parameterType: 'cost',\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_EntryWeightingUsesInversePopulation: Principle = {\n id: 'P10',\n name: 'Entry Weighting Uses Inverse Population',\n category: 'population',\n description:\n 'New entrants 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 entry 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 parameterType: 'yield',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'reward',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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_EntryWeightingUsesInversePopulation,\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 + production + activities) each ' +\n 'creating currency causes uncontrolled inflation. One clear primary faucet ' +\n 'makes the economy predictable and auditable.',\n check(metrics, thresholds): PrincipleResult {\n for (const curr of metrics.currencies) {\n const netFlow = metrics.netFlowByCurrency[curr] ?? 0;\n const faucetVolume = metrics.faucetVolumeByCurrency[curr] ?? 0;\n const sinkVolume = metrics.sinkVolumeByCurrency[curr] ?? 0;\n\n if (netFlow > thresholds.netFlowWarnThreshold) {\n return {\n violated: true,\n severity: 5,\n evidence: { currency: curr, netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'increase',\n scope: { currency: curr },\n magnitude: 0.15,\n reasoning:\n `[${curr}] Net flow +${netFlow.toFixed(1)}/tick. Inflationary. ` +\n 'Increase production 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: { currency: curr, netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'decrease',\n scope: { currency: curr },\n magnitude: 0.15,\n reasoning:\n `[${curr}] Net flow ${netFlow.toFixed(1)}/tick. Deflationary. ` +\n 'Decrease production cost to ease sink pressure.',\n },\n confidence: 0.80,\n estimatedLag: 8,\n };\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 'Pool math: winRate × multiplier > (1 - operatorShare) 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 { populationByRole } = metrics;\n\n const roleEntries = Object.entries(populationByRole).sort((a, b) => b[1] - a[1]);\n const dominantCount = roleEntries[0]?.[1] ?? 0;\n\n for (const [poolName, currencyAmounts] of Object.entries(metrics.poolSizesByCurrency)) {\n for (const curr of metrics.currencies) {\n const poolSize = currencyAmounts[curr] ?? 0;\n\n if (dominantCount > 5 && poolSize < 50) {\n const { poolWinRate, poolOperatorShare } = thresholds;\n const maxSustainableMultiplier = (1 - poolOperatorShare) / poolWinRate;\n\n return {\n violated: true,\n severity: 7,\n evidence: { currency: curr, pool: poolName, poolSize, participants: dominantCount, maxSustainableMultiplier },\n suggestedAction: {\n parameterType: 'reward',\n direction: 'decrease',\n scope: { currency: curr },\n magnitude: 0.15,\n reasoning:\n `[${curr}] ${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\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 extraction as \"currency injected\" is misleading. ' +\n 'Currency enters through faucet mechanisms (entering, rewards). ' +\n 'Fake metrics break every downstream decision.',\n check(metrics, _thresholds): PrincipleResult {\n for (const curr of metrics.currencies) {\n const faucetVolume = metrics.faucetVolumeByCurrency[curr] ?? 0;\n const netFlow = metrics.netFlowByCurrency[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n\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: { currency: curr, faucetVolume, netFlow, supplyGrowthRate },\n suggestedAction: {\n parameterType: 'yield',\n direction: 'decrease',\n scope: { currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] Supply growing at ${(supplyGrowthRate * 100).toFixed(1)}%/tick. ` +\n 'Verify currency injection tracking. Resources should not create currency directly.',\n },\n confidence: 0.55,\n estimatedLag: 5,\n };\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 'A pool at 42% of total supply means 42% of the economy is frozen. ' +\n 'Cap at 5%, decay at 2%/tick.',\n check(metrics, thresholds): PrincipleResult {\n const { poolCapPercent } = thresholds;\n\n for (const [pool, currencyAmounts] of Object.entries(metrics.poolSizesByCurrency)) {\n for (const curr of metrics.currencies) {\n const size = currencyAmounts[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n const shareOfSupply = size / Math.max(1, totalSupply);\n\n if (shareOfSupply > poolCapPercent * 2) {\n return {\n violated: true,\n severity: 6,\n evidence: { currency: curr, pool, size, shareOfSupply, cap: poolCapPercent },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'decrease',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] ${pool} pool at ${(shareOfSupply * 100).toFixed(1)}% of supply ` +\n `(cap: ${(poolCapPercent * 100).toFixed(0)}%). Currency frozen. ` +\n 'Lower fees to encourage circulation over accumulation.',\n },\n confidence: 0.85,\n estimatedLag: 5,\n };\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 for (const [poolName, currencyAmounts] of Object.entries(metrics.poolSizesByCurrency)) {\n for (const curr of metrics.currencies) {\n const poolSize = currencyAmounts[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n const stakedEstimate = totalSupply * 0.15;\n\n if (poolSize < 10 && stakedEstimate > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: { currency: curr, pool: poolName, poolSize, estimatedStaked: stakedEstimate },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.05,\n reasoning:\n `[${curr}] ${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\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 { supplyByResource } = metrics;\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n\n for (const curr of metrics.currencies) {\n const velocity = metrics.velocityByCurrency[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n\n if (velocity < 3 && totalSupply > 100 && totalResources > 20) {\n return {\n violated: true,\n severity: 4,\n evidence: { currency: curr, velocity, totalSupply, totalResources },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'decrease',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.20,\n reasoning:\n `[${curr}] 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\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 for (const curr of metrics.currencies) {\n const currPrices = metrics.pricesByCurrency[curr] ?? {};\n const velocity = metrics.velocityByCurrency[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n\n const priceValues = Object.values(currPrices).filter(p => p > 0);\n if (priceValues.length < 3) continue;\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 if (coeffOfVariation < 0.25 && velocity > 5 && totalSupply > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: {\n currency: curr,\n coeffOfVariation,\n velocity,\n numResources: priceValues.length,\n meanPrice: mean,\n },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'increase',\n scope: { currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] 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\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 parameterType: 'fee', scope: { tags: ['entry'] },\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 agents exist\n const hasAgents = metrics.totalAgents > 0;\n for (const [resource, supply] of Object.entries(metrics.supplyByResource)) {\n if (supply === 0 && hasAgents) {\n return {\n violated: true,\n severity: 8,\n evidence: { tick: metrics.tick, resource, supply, totalAgents: metrics.totalAgents },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'decrease',\n magnitude: 0.50,\n reasoning:\n `Bootstrap failure: ${resource} supply is 0 at tick ${metrics.tick} with ${metrics.totalAgents} agents. ` +\n 'Drastically reduce production cost to allow immediate output.',\n },\n confidence: 0.90,\n estimatedLag: 2,\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 parameterType: 'reward',\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 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 parameterType: 'yield',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 produce 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 parameterType: 'cost',\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'yield',\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['entry'] },\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 parameterType: 'cost',\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 participants 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 parameterType: 'reward',\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_BottleneckDetection: Principle = {\n id: 'P29',\n name: 'Bottleneck Detection',\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 parameterType: 'cost',\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 parameterType: 'cost',\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_DynamicBottleneckRotation: Principle = {\n id: 'P30',\n name: 'Dynamic Bottleneck Rotation',\n category: 'market_dynamics',\n description:\n 'Participant progression shifts the demand curve. A static pinch point that ' +\n 'works early will be cleared later. The pinch point must move ' +\n 'with participant 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 parameterType: 'cost',\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 participant 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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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_BottleneckDetection,\n P30_DynamicBottleneckRotation,\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 for (const curr of metrics.currencies) {\n const meanMedianDivergence = metrics.meanMedianDivergenceByCurrency[curr] ?? 0;\n const giniCoefficient = metrics.giniCoefficientByCurrency[curr] ?? 0;\n const meanBalance = metrics.meanBalanceByCurrency[curr] ?? 0;\n const medianBalance = metrics.medianBalanceByCurrency[curr] ?? 0;\n\n if (meanMedianDivergence > thresholds.meanMedianDivergenceMax) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n currency: curr,\n meanMedianDivergence,\n giniCoefficient,\n meanBalance,\n medianBalance,\n },\n suggestedAction: {\n parameterType: 'fee',\n scope: { tags: ['transaction'], currency: curr },\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `[${curr}] 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 transaction fees to redistribute wealth.',\n },\n confidence: 0.85,\n estimatedLag: 15,\n };\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 parameterType: 'cost',\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['entry'] },\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 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 'Replacement/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 parameterType: 'yield',\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 parameterType: 'yield',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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: Participant 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: 'participant_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 for (const curr of metrics.currencies) {\n const giniCoefficient = metrics.giniCoefficientByCurrency[curr] ?? 0;\n\n if (giniCoefficient < 0.10) {\n return {\n violated: true,\n severity: 3,\n evidence: { currency: curr, giniCoefficient },\n suggestedAction: {\n parameterType: 'reward',\n direction: 'increase',\n scope: { currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] 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: { currency: curr, giniCoefficient },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.20,\n reasoning:\n `[${curr}] 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: { currency: curr, giniCoefficient },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] 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\n return { violated: false };\n },\n};\n\nexport const P36_MechanicFrictionDetector: Principle = {\n id: 'P36',\n name: 'Mechanism Friction Detector',\n category: 'participant_experience',\n description:\n 'Deterministic + probabilistic systems → expectation mismatch. ' +\n 'When production is guaranteed but competition is random, participants feel betrayed by ' +\n 'the random side. Mix mechanisms 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 mechanism mismatch rather than economic problems\n // (Activity exists but participants leave anyway = not economic, likely mechanism 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 parameterType: 'reward',\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 mechanism friction (deterministic vs random systems). ' +\n 'Increase rewards to compensate for perceived unfairness. ' +\n 'ADVISORY: Review if mixing guaranteed and probabilistic mechanisms.',\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: 'Late Entrant Problem',\n category: 'participant_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 = late entrant 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 parameterType: 'cost',\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: 'participant_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 parameterType: 'fee',\n direction: 'decrease',\n scope: { tags: ['entry'] },\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: 'participant_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 parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'] },\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 PARTICIPANT_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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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 parameterType: 'reward',\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 parameterType: 'reward',\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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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, P56: Operations Principles (from Naavik research)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P51_CyclicalEngagement: Principle = {\n id: 'P51',\n name: 'Cyclical Engagement Pattern',\n category: 'operations',\n description:\n 'Each activity peak should be >=95% of the previous peak. ' +\n 'If peaks are shrinking (cyclical engagement becoming flat), activity fatigue is setting in. ' +\n 'If valleys are deepening, the off-activity economy is failing to sustain engagement.',\n check(metrics, thresholds): PrincipleResult {\n const { cyclicalPeaks, cyclicalValleys } = metrics;\n if (cyclicalPeaks.length < 2) return { violated: false };\n\n const lastPeak = cyclicalPeaks[cyclicalPeaks.length - 1] ?? 0;\n const prevPeak = cyclicalPeaks[cyclicalPeaks.length - 2] ?? 0;\n\n if (prevPeak > 0 && lastPeak / prevPeak < thresholds.cyclicalPeakDecay) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n lastPeak,\n prevPeak,\n ratio: lastPeak / prevPeak,\n threshold: thresholds.cyclicalPeakDecay,\n },\n suggestedAction: {\n parameterType: 'reward',\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.cyclicalPeakDecay * 100).toFixed(0)}%). Activity fatigue detected. ` +\n 'Boost activity rewards to restore peak engagement.',\n },\n confidence: 0.75,\n estimatedLag: 30,\n };\n }\n\n if (cyclicalValleys.length >= 2) {\n const lastValley = cyclicalValleys[cyclicalValleys.length - 1] ?? 0;\n const prevValley = cyclicalValleys[cyclicalValleys.length - 2] ?? 0;\n if (prevValley > 0 && lastValley / prevValley < thresholds.cyclicalValleyDecay) {\n return {\n violated: true,\n severity: 4,\n evidence: { lastValley, prevValley, ratio: lastValley / prevValley },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n 'Between-activity engagement declining (deepening valleys). ' +\n 'Base economy not sustaining participants between activities. ' +\n 'Lower production costs to improve off-activity 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: 'operations',\n description:\n 'Participants who never owned premium assets do not value them. ' +\n 'Free trial activities that let participants experience premium assets drive conversions ' +\n 'because ownership creates perceived value (endowment effect).',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, churnRate } = metrics;\n\n // Proxy: if activity completion is high but satisfaction is still low,\n // activities 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 parameterType: 'reward',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `${(eventCompletionRate * 100).toFixed(0)}% activity completion but satisfaction only ${avgSatisfaction.toFixed(0)}. ` +\n 'Activities 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: 'Activity Completion Rate Sweet Spot',\n category: 'operations',\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 parameterType: 'cost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Activity 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 parameterType: 'fee', scope: { tags: ['entry'] },\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `Activity 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_OperationalCadence: Principle = {\n id: 'P54',\n name: 'Operational Cadence',\n category: 'operations',\n description:\n '>50% of activities that are re-wrapped existing supply → stagnation. ' +\n 'The cadence must include genuinely new supply at regular intervals. ' +\n 'This is an advisory principle — AgentE can flag but cannot fix supply.',\n check(metrics, _thresholds): PrincipleResult {\n // Proxy: declining engagement velocity over time = stagnation\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 parameterType: 'reward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n 'Low velocity and satisfaction after long runtime. ' +\n 'Possible supply stagnation. Increase rewards as bridge while ' +\n 'new supply 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_SupplyShockAbsorption: Principle = {\n id: 'P56',\n name: 'Supply Shock Absorption',\n category: 'operations',\n description:\n 'Every new-item injection shatters existing price equilibria — arbitrage spikes ' +\n 'as participants re-price. Build stabilization windows for price discovery before ' +\n 'measuring post-injection economic health.',\n check(metrics, thresholds): PrincipleResult {\n const { contentDropAge, arbitrageIndex } = metrics;\n\n // Only fires during the stabilization window after a supply injection\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 parameterType: 'fee', scope: { tags: ['transaction'] },\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Supply injection ${contentDropAge} ticks ago — arbitrage at ${arbitrageIndex.toFixed(2)} ` +\n `exceeds post-injection 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 OPERATIONS_PRINCIPLES: Principle[] = [\n P51_CyclicalEngagement,\n P52_EndowmentEffect,\n P53_EventCompletionRate,\n P54_OperationalCadence,\n P56_SupplyShockAbsorption,\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 { PARTICIPANT_EXPERIENCE_PRINCIPLES } from './participant-experience.js';\nimport { OPEN_ECONOMY_PRINCIPLES } from './open-economy.js';\nimport { OPERATIONS_PRINCIPLES } from './operations.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 './participant-experience.js';\nexport * from './open-economy.js';\nexport * from './operations.js';\n\n/** All 60 built-in principles in priority order (supply chain → operations) */\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 ...PARTICIPANT_EXPERIENCE_PRINCIPLES, // P33, P36, P37, P45, P50\n ...OPEN_ECONOMY_PRINCIPLES, // P34, P47-P48\n ...OPERATIONS_PRINCIPLES, // P51-P54, P56\n];\n","// Stage 3: Simulator — forward Monte Carlo projection before any action is applied\n// Monte Carlo forward projection — simulates before any action is applied\n\nimport type {\n EconomyMetrics,\n SuggestedAction,\n SimulationResult,\n SimulationOutcome,\n SimulationConfig,\n Thresholds,\n} from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { Diagnoser } from './Diagnoser.js';\nimport { ALL_PRINCIPLES } from './principles/index.js';\nimport type { ParameterRegistry, FlowImpact } from './ParameterRegistry.js';\n\nconst DEFAULT_SIM_CONFIG: Required<SimulationConfig> = {\n sinkMultiplier: 0.20,\n faucetMultiplier: 0.15,\n frictionMultiplier: 0.10,\n frictionVelocityScale: 10,\n redistributionMultiplier: 0.30,\n neutralMultiplier: 0.05,\n minIterations: 100,\n maxProjectionTicks: 20,\n};\n\nexport class Simulator {\n private diagnoser = new Diagnoser(ALL_PRINCIPLES);\n private registry: ParameterRegistry | undefined;\n private simConfig: Required<SimulationConfig>;\n\n constructor(registry?: ParameterRegistry, simConfig?: SimulationConfig) {\n this.registry = registry;\n this.simConfig = { ...DEFAULT_SIM_CONFIG, ...simConfig };\n }\n // Cache beforeViolations for the *current* tick only.\n private cachedViolationsTick: number = -1;\n private cachedViolations: Set<string> = new Set();\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 if (this.cachedViolationsTick !== tick) {\n this.cachedViolations = new Set(\n this.diagnoser.diagnose(currentMetrics, thresholds).map(d => d.principle.id),\n );\n this.cachedViolationsTick = tick;\n }\n const beforeViolations = this.cachedViolations;\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 const multiplier = this.actionMultiplier(action);\n const noise = () => 1 + (Math.random() - 0.5) * 0.1;\n const currencies = metrics.currencies;\n const targetCurrency = action.scope?.currency; // may be undefined (= all)\n\n // Per-currency state\n const supplies: Record<string, number> = { ...metrics.totalSupplyByCurrency };\n const netFlows: Record<string, number> = { ...metrics.netFlowByCurrency };\n const ginis: Record<string, number> = { ...metrics.giniCoefficientByCurrency };\n const velocities: Record<string, number> = { ...metrics.velocityByCurrency };\n let satisfaction = metrics.avgSatisfaction;\n\n for (let t = 0; t < ticks; t++) {\n for (const curr of currencies) {\n // Only apply action effect to the targeted currency (or all if unscoped)\n const isTarget = !targetCurrency || targetCurrency === curr;\n const effectOnFlow = isTarget\n ? this.flowEffect(action, metrics, curr) * multiplier * noise()\n : 0;\n\n netFlows[curr] = (netFlows[curr] ?? 0) * 0.9 + effectOnFlow * 0.1;\n supplies[curr] = Math.max(0, (supplies[curr] ?? 0) + (netFlows[curr] ?? 0) * noise());\n ginis[curr] = (ginis[curr] ?? 0) * 0.99 + 0.35 * 0.01 * noise();\n velocities[curr] = ((supplies[curr] ?? 0) / Math.max(1, metrics.totalAgents)) * 0.01 * noise();\n }\n\n const avgNetFlow = currencies.length > 0\n ? Object.values(netFlows).reduce((s, v) => s + v, 0) / currencies.length\n : 0;\n const satDelta = avgNetFlow > 0 && avgNetFlow < 20 ? 0.5 : avgNetFlow < 0 ? -1 : 0;\n satisfaction = Math.min(100, Math.max(0, satisfaction + satDelta * noise()));\n }\n\n // Build projected metrics\n const totalSupply = Object.values(supplies).reduce((s, v) => s + v, 0);\n const projected: EconomyMetrics = {\n ...metrics,\n tick: metrics.tick + ticks,\n currencies,\n totalSupplyByCurrency: supplies,\n netFlowByCurrency: netFlows,\n velocityByCurrency: velocities,\n giniCoefficientByCurrency: ginis,\n totalSupply,\n netFlow: Object.values(netFlows).reduce((s, v) => s + v, 0),\n velocity: totalSupply > 0 && currencies.length > 0\n ? Object.values(velocities).reduce((s, v) => s + v, 0) / currencies.length\n : 0,\n giniCoefficient: currencies.length > 0\n ? Object.values(ginis).reduce((s, v) => s + v, 0) / currencies.length\n : 0,\n avgSatisfaction: satisfaction,\n inflationRate: metrics.totalSupply > 0 ? (totalSupply - 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, currency: string): number {\n const { direction } = action;\n const sign = direction === 'increase' ? -1 : 1;\n\n const roleEntries = Object.entries(metrics.populationByRole).sort((a, b) => b[1] - a[1]);\n const dominantRoleCount = roleEntries[0]?.[1] ?? 0;\n\n // Resolve flow impact directly from registry by type+scope (independent of Planner)\n let impact: FlowImpact | undefined;\n if (this.registry) {\n const resolved = this.registry.resolve(action.parameterType, action.scope);\n if (resolved) {\n impact = resolved.flowImpact;\n }\n }\n if (!impact) {\n impact = this.inferFlowImpact(action.parameterType);\n }\n\n const cfg = this.simConfig;\n switch (impact) {\n case 'sink':\n return sign * (metrics.netFlowByCurrency[currency] ?? 0) * cfg.sinkMultiplier;\n case 'faucet':\n return -sign * dominantRoleCount * cfg.redistributionMultiplier;\n case 'neutral':\n return sign * dominantRoleCount * cfg.neutralMultiplier;\n case 'mixed':\n return sign * (metrics.faucetVolumeByCurrency[currency] ?? 0) * cfg.faucetMultiplier;\n case 'friction':\n return sign * (metrics.netFlowByCurrency[currency] ?? 0) * cfg.frictionMultiplier;\n case 'redistribution':\n return sign * dominantRoleCount * cfg.neutralMultiplier;\n default:\n return sign * (metrics.netFlowByCurrency[currency] ?? 0) * cfg.frictionMultiplier;\n }\n }\n\n /** Infer flow impact from parameter type when registry is unavailable */\n private inferFlowImpact(parameterType: string): FlowImpact {\n switch (parameterType) {\n case 'cost':\n case 'fee':\n case 'penalty':\n return 'sink';\n case 'reward':\n return 'faucet';\n case 'yield':\n return 'mixed';\n case 'cap':\n case 'multiplier':\n return 'neutral';\n default:\n return 'mixed';\n }\n }\n\n private checkImprovement(\n before: EconomyMetrics,\n after: EconomyMetrics,\n _action: SuggestedAction,\n ): boolean {\n const satisfactionImproved = after.avgSatisfaction >= before.avgSatisfaction - 2;\n\n // Check net flow improvement across all currencies\n const flowMoreBalanced = before.currencies.every(curr => {\n const afterFlow = Math.abs(after.netFlowByCurrency[curr] ?? 0);\n const beforeFlow = Math.abs(before.netFlowByCurrency[curr] ?? 0);\n return afterFlow <= beforeFlow * 1.2 || afterFlow < 1;\n });\n\n const notWorseGini = before.currencies.every(curr => {\n const afterGini = after.giniCoefficientByCurrency[curr] ?? 0;\n const beforeGini = before.giniCoefficientByCurrency[curr] ?? 0;\n return afterGini <= beforeGini + 0.05;\n });\n\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\n const avg = (key: keyof EconomyMetrics): number => {\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\n const avgRecord = (key: keyof EconomyMetrics): Record<string, number> => {\n const allKeys = new Set<string>();\n for (const o of outcomes) {\n const rec = o[key];\n if (rec && typeof rec === 'object' && !Array.isArray(rec)) {\n Object.keys(rec as Record<string, unknown>).forEach(k => allKeys.add(k));\n }\n }\n const result: Record<string, number> = {};\n for (const k of allKeys) {\n const vals = outcomes\n .map(o => (o[key] as Record<string, number>)?.[k])\n .filter((v): v is number => typeof v === 'number' && !isNaN(v));\n result[k] = vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n }\n return result;\n };\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 totalSupplyByCurrency: avgRecord('totalSupplyByCurrency'),\n netFlowByCurrency: avgRecord('netFlowByCurrency'),\n velocityByCurrency: avgRecord('velocityByCurrency'),\n giniCoefficientByCurrency: avgRecord('giniCoefficientByCurrency'),\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';\nimport type { ParameterRegistry, ParameterScope } from './ParameterRegistry.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 typeCooldowns = new Map<string, number>(); // type+scope key → 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 * - no matching parameter in registry\n */\n plan(\n diagnosis: Diagnosis,\n metrics: EconomyMetrics,\n simulationResult: SimulationResult,\n currentParams: Record<string, number>,\n thresholds: Thresholds,\n registry?: ParameterRegistry,\n ): ActionPlan | null {\n const action = diagnosis.violation.suggestedAction;\n\n // Type-level cooldown: prevent re-planning the same parameterType+scope before registry resolution\n const typeKey = this.typeCooldownKey(action.parameterType, action.scope);\n if (this.isTypeCooldown(typeKey, metrics.tick, thresholds.cooldownTicks)) return null;\n\n // Resolve parameterType + scope to a concrete key via registry\n let param: string;\n let resolvedBaseline: number | undefined;\n let scope: ParameterScope | undefined;\n\n if (registry) {\n const resolved = registry.resolve(action.parameterType, action.scope);\n if (!resolved) return null; // no matching parameter registered\n param = resolved.key;\n resolvedBaseline = resolved.currentValue;\n scope = resolved.scope as ParameterScope | undefined;\n action.resolvedParameter = param;\n } else {\n // Fallback: use parameterType as param name directly\n param = action.resolvedParameter ?? action.parameterType;\n scope = action.scope as ParameterScope | undefined;\n }\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 // Prefer registry's currentValue, then currentParams, then absoluteValue, then 1.0\n const currentValue = resolvedBaseline ?? currentParams[param] ?? action.absoluteValue ?? 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 ...(scope !== undefined ? { scope } : {}),\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),\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 // Also record type-level cooldown from the diagnosis action\n const action = plan.diagnosis.violation.suggestedAction;\n const typeKey = this.typeCooldownKey(action.parameterType, action.scope);\n this.typeCooldowns.set(typeKey, tick);\n this.activePlanCount++;\n }\n\n recordRolledBack(_plan: ActionPlan): void {\n this.activePlanCount = Math.max(0, this.activePlanCount - 1);\n }\n\n recordSettled(_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 this.typeCooldowns.clear();\n }\n\n /** V1.5.2: Reset active plan count (e.g., on system restart) */\n resetActivePlans(): void {\n this.activePlanCount = 0;\n }\n\n /** V1.5.2: Current active plan count (for diagnostics) */\n getActivePlanCount(): number {\n return this.activePlanCount;\n }\n\n private typeCooldownKey(type: string, scope?: Partial<ParameterScope>): string {\n const parts = [type];\n if (scope?.system) parts.push(`sys:${scope.system}`);\n if (scope?.currency) parts.push(`cur:${scope.currency}`);\n if (scope?.tags?.length) parts.push(`tags:${scope.tags.sort().join(',')}`);\n return parts.join('|');\n }\n\n private isTypeCooldown(typeKey: string, currentTick: number, cooldownTicks: number): boolean {\n const lastApplied = this.typeCooldowns.get(typeKey);\n if (lastApplied === undefined) return false;\n return currentTick - lastApplied < cooldownTicks;\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 private maxActiveTicks: number;\n\n constructor(settlementWindowTicks = 200) {\n this.maxActiveTicks = settlementWindowTicks;\n }\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, plan.scope);\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 * Returns { rolledBack, settled } — plans that were undone and plans that passed their window.\n */\n async checkRollbacks(\n metrics: EconomyMetrics,\n adapter: EconomyAdapter,\n ): Promise<{ rolledBack: ActionPlan[]; settled: ActionPlan[] }> {\n const rolledBack: ActionPlan[] = [];\n const settled: 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 // Hard TTL: evict plans that have been active for too long\n if (plan.appliedAt !== undefined && metrics.tick - plan.appliedAt > this.maxActiveTicks) {\n settled.push(plan);\n continue;\n }\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\n // Fail-safe: if metric is unresolvable, trigger rollback\n if (Number.isNaN(metricValue)) {\n console.warn(\n `[AgentE] Rollback check: metric path '${rc.metric}' resolved to NaN for plan '${plan.id}'. Triggering rollback as fail-safe.`\n );\n await adapter.setParam(plan.parameter, originalValue, plan.scope);\n rolledBack.push(plan);\n continue;\n }\n\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, plan.scope);\n rolledBack.push(plan);\n } else {\n // Plan has passed its check window — consider it settled\n const settledTick = rc.checkAfterTick + 10;\n if (metrics.tick > settledTick) {\n settled.push(plan);\n } else {\n remaining.push(active);\n }\n }\n }\n\n this.activePlans = remaining;\n return { rolledBack, settled };\n }\n\n private getMetricValue(metrics: EconomyMetrics, metricPath: string): number {\n // Support dotted paths like 'poolSizes.primary' 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.push(entry); // oldest first, newest at end\n if (this.entries.length > this.maxEntries * 1.5) {\n this.entries = this.entries.slice(-this.maxEntries);\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.push(entry);\n if (this.entries.length > this.maxEntries * 1.5) {\n this.entries = this.entries.slice(-this.maxEntries);\n }\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 getById(id: string): DecisionEntry | undefined {\n return this.entries.find(e => e.id === id);\n }\n\n updateResult(id: string, newResult: DecisionResult, reasoning?: string): boolean {\n const entry = this.entries.find(e => e.id === id);\n if (!entry) return false;\n entry.result = newResult;\n if (reasoning !== undefined) entry.reasoning = reasoning;\n return true;\n }\n\n latest(n = 30): DecisionEntry[] {\n return this.entries.slice(-n).reverse();\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.resolvedParameter ?? action.parameterType,\n ...(action.scope !== undefined ? { scope: action.scope } : {}),\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\nfunction getNestedValue(obj: Record<string, unknown>, path: string): number {\n const parts = path.split('.');\n let val: unknown = obj;\n for (const part of parts) {\n if (val !== null && typeof val === 'object') {\n val = (val as Record<string, unknown>)[part];\n } else {\n return NaN;\n }\n }\n return typeof val === 'number' ? val : NaN;\n}\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 points = filtered.map(m => ({\n tick: m.tick,\n value: getNestedValue(m as unknown as Record<string, unknown>, q.metric as string),\n }));\n\n return { metric: q.metric as string, resolution, points };\n }\n\n /** Summarized recent history for dashboard charts */\n recentHistory(count = 100): Array<{\n tick: number;\n health: number;\n giniCoefficient: number;\n totalSupply: number;\n netFlow: number;\n velocity: number;\n inflationRate: number;\n avgSatisfaction: number;\n churnRate: number;\n totalAgents: number;\n priceIndex: number;\n }> {\n const all = this.fine.toArray();\n const slice = all.slice(-count);\n return slice.map(m => {\n // Compute health inline (same formula as AgentE.getHealth())\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 health = Math.max(0, Math.min(100, health));\n\n return {\n tick: m.tick,\n health,\n giniCoefficient: m.giniCoefficient,\n totalSupply: m.totalSupply,\n netFlow: m.netFlow,\n velocity: m.velocity,\n inflationRate: m.inflationRate,\n avgSatisfaction: m.avgSatisfaction,\n churnRate: m.churnRate,\n totalAgents: m.totalAgents,\n priceIndex: m.priceIndex,\n };\n });\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 const avgRecord = (key: keyof EconomyMetrics): Record<string, number> => {\n const allKeys = new Set<string>();\n for (const s of snapshots) {\n const rec = s[key];\n if (rec && typeof rec === 'object' && !Array.isArray(rec)) {\n Object.keys(rec as Record<string, unknown>).forEach(k => allKeys.add(k));\n }\n }\n const result: Record<string, number> = {};\n for (const k of allKeys) {\n const vals = snapshots\n .map(s => (s[key] as Record<string, number>)?.[k])\n .filter((v): v is number => typeof v === 'number' && !isNaN(v));\n result[k] = vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n }\n return result;\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 // Per-currency averages\n totalSupplyByCurrency: avgRecord('totalSupplyByCurrency'),\n netFlowByCurrency: avgRecord('netFlowByCurrency'),\n velocityByCurrency: avgRecord('velocityByCurrency'),\n inflationRateByCurrency: avgRecord('inflationRateByCurrency'),\n faucetVolumeByCurrency: avgRecord('faucetVolumeByCurrency'),\n sinkVolumeByCurrency: avgRecord('sinkVolumeByCurrency'),\n tapSinkRatioByCurrency: avgRecord('tapSinkRatioByCurrency'),\n anchorRatioDriftByCurrency: avgRecord('anchorRatioDriftByCurrency'),\n giniCoefficientByCurrency: avgRecord('giniCoefficientByCurrency'),\n medianBalanceByCurrency: avgRecord('medianBalanceByCurrency'),\n meanBalanceByCurrency: avgRecord('meanBalanceByCurrency'),\n top10PctShareByCurrency: avgRecord('top10PctShareByCurrency'),\n meanMedianDivergenceByCurrency: avgRecord('meanMedianDivergenceByCurrency'),\n };\n }\n}\n","// Behavioral persona auto-classification\n// Classifies agents into 9 universal archetypes from observable signals\n// All thresholds are RELATIVE (percentile-based) — no magic numbers\n\nimport type {\n EconomyState,\n EconomicEvent,\n PersonaType,\n} from './types.js';\n\n// ── Configuration ──\n\nexport interface PersonaConfig {\n /** Top X% by holdings = Whale. Default: 0.05 (5%) */\n whalePercentile: number;\n\n /** Top X% by tx frequency = Active Trader. Default: 0.20 (20%) */\n activeTraderPercentile: number;\n\n /** Ticks to consider an agent \"new.\" Default: 10 */\n newEntrantWindow: number;\n\n /** Ticks with zero activity = Dormant. Default: 20 */\n dormantWindow: number;\n\n /** Activity drop threshold for At-Risk. Default: 0.5 (50% drop) */\n atRiskDropThreshold: number;\n\n /** Min distinct systems for Power User. Default: 3 */\n powerUserMinSystems: number;\n\n /** Rolling history window size (ticks). Default: 50 */\n historyWindow: number;\n}\n\nconst DEFAULT_PERSONA_CONFIG: PersonaConfig = {\n whalePercentile: 0.05,\n activeTraderPercentile: 0.20,\n newEntrantWindow: 10,\n dormantWindow: 20,\n atRiskDropThreshold: 0.5,\n powerUserMinSystems: 3,\n historyWindow: 50,\n};\n\n// ── Per-agent rolling signals ──\n\ninterface AgentSnapshot {\n totalHoldings: number;\n txCount: number;\n txVolume: number;\n systems: Set<string>;\n}\n\ninterface AgentRecord {\n firstSeen: number;\n lastActive: number;\n snapshots: AgentSnapshot[];\n previousTxRate: number; // tx frequency in prior window (for At-Risk detection)\n}\n\n// ── Classifier ──\n\nexport class PersonaTracker {\n private agents = new Map<string, AgentRecord>();\n private config: PersonaConfig;\n\n constructor(config?: Partial<PersonaConfig>) {\n this.config = { ...DEFAULT_PERSONA_CONFIG, ...config };\n }\n\n /**\n * Ingest a state snapshot + events and update per-agent signals.\n * Call this once per tick BEFORE getDistribution().\n */\n update(state: EconomyState, events?: EconomicEvent[]): void {\n const tick = state.tick;\n const txByAgent = new Map<string, { count: number; volume: number; systems: Set<string> }>();\n\n // Tally events per agent\n if (events) {\n for (const e of events) {\n const agents = [e.actor];\n if (e.from) agents.push(e.from);\n if (e.to) agents.push(e.to);\n\n for (const id of agents) {\n if (!id) continue;\n const entry = txByAgent.get(id) ?? { count: 0, volume: 0, systems: new Set() };\n entry.count++;\n entry.volume += e.amount ?? 0;\n if (e.system) entry.systems.add(e.system);\n txByAgent.set(id, entry);\n }\n }\n }\n\n // Update each agent's record\n for (const [agentId, balances] of Object.entries(state.agentBalances)) {\n const totalHoldings = Object.values(balances).reduce((s, v) => s + v, 0);\n const tx = txByAgent.get(agentId);\n\n const record = this.agents.get(agentId) ?? {\n firstSeen: tick,\n lastActive: tick,\n snapshots: [],\n previousTxRate: 0,\n };\n\n const snapshot: AgentSnapshot = {\n totalHoldings,\n txCount: tx?.count ?? 0,\n txVolume: tx?.volume ?? 0,\n systems: tx?.systems ?? new Set(),\n };\n\n record.snapshots.push(snapshot);\n\n // Trim to history window\n if (record.snapshots.length > this.config.historyWindow) {\n // Before trimming, save the old tx rate for At-Risk comparison\n const oldHalf = record.snapshots.slice(0, Math.floor(record.snapshots.length / 2));\n record.previousTxRate = oldHalf.reduce((s, sn) => s + sn.txCount, 0) / Math.max(1, oldHalf.length);\n record.snapshots = record.snapshots.slice(-this.config.historyWindow);\n }\n\n if ((tx?.count ?? 0) > 0) {\n record.lastActive = tick;\n }\n\n this.agents.set(agentId, record);\n }\n\n // Prune agents gone from state for >2× dormant window\n const pruneThreshold = this.config.dormantWindow * 2;\n if (tick % this.config.dormantWindow === 0) {\n for (const [id, rec] of this.agents) {\n if (tick - rec.lastActive > pruneThreshold && !(id in state.agentBalances)) {\n this.agents.delete(id);\n }\n }\n }\n }\n\n /**\n * Classify all tracked agents and return the population distribution.\n * Returns { Whale: 0.05, ActiveTrader: 0.18, Passive: 0.42, ... }\n */\n getDistribution(): Record<string, number> {\n const agentIds = [...this.agents.keys()];\n const total = agentIds.length;\n if (total === 0) return {};\n\n // ── Compute population-wide statistics ──\n\n // Holdings for percentile calculation\n const holdings = agentIds.map(id => {\n const rec = this.agents.get(id)!;\n const latest = rec.snapshots[rec.snapshots.length - 1];\n return latest?.totalHoldings ?? 0;\n }).sort((a, b) => a - b);\n\n const whaleThreshold = percentile(holdings, 1 - this.config.whalePercentile);\n\n // Tx frequency for percentile calculation\n const txRatesUnsorted = agentIds.map(id => {\n const rec = this.agents.get(id)!;\n return rec.snapshots.reduce((s, sn) => s + sn.txCount, 0) / Math.max(1, rec.snapshots.length);\n });\n const txRates = [...txRatesUnsorted].sort((a, b) => a - b);\n\n const activeTraderThreshold = percentile(txRates, 1 - this.config.activeTraderPercentile);\n const medianTxRate = percentile(txRates, 0.5);\n\n // ── Classify each agent ──\n\n const counts: Record<string, number> = {};\n const currentTick = Math.max(...agentIds.map(id => this.agents.get(id)!.lastActive), 0);\n\n for (let i = 0; i < agentIds.length; i++) {\n const id = agentIds[i]!;\n const rec = this.agents.get(id)!;\n const snaps = rec.snapshots;\n if (snaps.length === 0) continue;\n\n const latestHoldings = snaps[snaps.length - 1]!.totalHoldings;\n const agentTxRate = txRatesUnsorted[i]!;\n const ticksSinceFirst = currentTick - rec.firstSeen;\n const ticksSinceActive = currentTick - rec.lastActive;\n\n // Balance delta: compare first half vs second half of history\n const halfIdx = Math.floor(snaps.length / 2);\n const earlyAvg = snaps.slice(0, Math.max(1, halfIdx))\n .reduce((s, sn) => s + sn.totalHoldings, 0) / Math.max(1, halfIdx);\n const lateAvg = snaps.slice(halfIdx)\n .reduce((s, sn) => s + sn.totalHoldings, 0) / Math.max(1, snaps.length - halfIdx);\n const balanceDelta = lateAvg - earlyAvg;\n\n // System diversity\n const allSystems = new Set<string>();\n for (const sn of snaps) {\n for (const sys of sn.systems) allSystems.add(sys);\n }\n\n // Current window tx rate (for At-Risk comparison)\n const recentSnaps = snaps.slice(-Math.min(10, snaps.length));\n const recentTxRate = recentSnaps.reduce((s, sn) => s + sn.txCount, 0) / Math.max(1, recentSnaps.length);\n\n // ── Priority-ordered classification ──\n let persona: PersonaType;\n\n if (ticksSinceFirst <= this.config.newEntrantWindow) {\n persona = 'NewEntrant';\n } else if (latestHoldings > 0 && ticksSinceActive > this.config.dormantWindow) {\n persona = 'Dormant';\n } else if (rec.previousTxRate > 0 && recentTxRate < rec.previousTxRate * (1 - this.config.atRiskDropThreshold)) {\n persona = 'AtRisk';\n } else if (latestHoldings >= whaleThreshold && whaleThreshold > 0) {\n persona = 'Whale';\n } else if (allSystems.size >= this.config.powerUserMinSystems) {\n persona = 'PowerUser';\n } else if (agentTxRate >= activeTraderThreshold && activeTraderThreshold > 0) {\n persona = 'ActiveTrader';\n } else if (balanceDelta > 0 && agentTxRate < medianTxRate) {\n persona = 'Accumulator';\n } else if (balanceDelta < 0 && agentTxRate >= medianTxRate) {\n persona = 'Spender';\n } else {\n persona = 'Passive';\n }\n\n counts[persona] = (counts[persona] ?? 0) + 1;\n }\n\n // Convert to fractions\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\n// ── Helpers ──\n\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0;\n const idx = Math.ceil(p * sorted.length) - 1;\n return sorted[Math.max(0, Math.min(idx, sorted.length - 1))]!;\n}\n","// ParameterRegistry — type-based parameter resolution for universal economies\n// Replaces hardcoded parameter strings with a registry that resolves by type + scope.\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** High-level parameter categories (what it IS, not what it's called) */\nexport type ParameterType =\n | 'cost' // production cost, minting cost, operating cost\n | 'fee' // transaction fee, entry fee, withdrawal fee\n | 'reward' // reward rate, payout multiplier\n | 'yield' // yield rate, harvest rate, emission rate\n | 'rate' // generic rate (fallback)\n | 'cap' // supply cap, pool cap\n | 'penalty' // withdrawal penalty, decay rate\n | 'multiplier' // crowding multiplier, bonus multiplier\n | string; // extensible — any custom type\n\n/** How a parameter change affects net currency flow */\nexport type FlowImpact =\n | 'sink' // increasing this parameter drains currency (costs, fees, penalties)\n | 'faucet' // increasing this parameter injects currency (rewards, yields)\n | 'neutral' // no direct flow effect (caps, multipliers)\n | 'mixed' // depends on context\n | 'friction' // slows flow without removing currency (cooldowns, lock periods)\n | 'redistribution'; // moves currency between participants without net change\n\n/** Scope narrows which concrete parameter a type resolves to */\nexport interface ParameterScope {\n system?: string; // e.g. 'marketplace', 'staking', 'production'\n currency?: string; // e.g. 'gold', 'gems', 'ETH'\n tags?: string[]; // e.g. ['entry'], ['transaction'], ['withdrawal']\n}\n\n/** A registered parameter in the economy */\nexport interface RegisteredParameter {\n /** Concrete key used by the adapter (e.g. 'craftingCost', 'stakingYield') */\n key: string;\n /** What type of parameter this is */\n type: ParameterType;\n /** How changing this affects net flow */\n flowImpact: FlowImpact;\n /** Scope constraints — narrows resolution */\n scope?: Partial<ParameterScope>;\n /** Current value (updated after each apply) */\n currentValue?: number;\n /** Human-readable description */\n description?: string;\n /** Priority tiebreaker — higher wins when specificity scores are equal */\n priority?: number;\n /** Human-readable label for UIs and logs */\n label?: string;\n}\n\n/** Result of registry.validate() */\nexport interface RegistryValidationResult {\n valid: boolean;\n warnings: string[];\n errors: string[];\n}\n\n// ── Registry ────────────────────────────────────────────────────────────────\n\nexport class ParameterRegistry {\n private parameters = new Map<string, RegisteredParameter>();\n\n /** Register a parameter. Overwrites if key already exists. */\n register(param: RegisteredParameter): void {\n this.parameters.set(param.key, { ...param });\n }\n\n /** Register multiple parameters at once. */\n registerAll(params: RegisteredParameter[]): void {\n for (const p of params) this.register(p);\n }\n\n /**\n * Resolve a parameterType + scope to a concrete RegisteredParameter.\n * Returns the best match, or undefined if no match.\n *\n * Matching rules:\n * 1. Filter candidates by type\n * 2. Score each by scope specificity (system +10, currency +5, tags +3 each)\n * 3. Mismatched scope fields disqualify (score = -Infinity)\n * 4. Ties broken by `priority` (higher wins), then registration order\n * 5. All disqualified → undefined\n */\n resolve(type: ParameterType, scope?: Partial<ParameterScope>): RegisteredParameter | undefined {\n const candidates = this.findByType(type);\n if (candidates.length === 0) return undefined;\n if (candidates.length === 1) return candidates[0];\n\n let bestScore = -Infinity;\n let bestPriority = -Infinity;\n let best: RegisteredParameter | undefined;\n\n for (const candidate of candidates) {\n const score = this.scopeSpecificity(candidate.scope, scope);\n const prio = candidate.priority ?? 0;\n\n if (score > bestScore || (score === bestScore && prio > bestPriority)) {\n bestScore = score;\n bestPriority = prio;\n best = candidate;\n }\n }\n\n // If the best score is still -Infinity, all candidates were disqualified\n if (bestScore === -Infinity) return undefined;\n\n return best;\n }\n\n /** Find all parameters of a given type. */\n findByType(type: ParameterType): RegisteredParameter[] {\n const results: RegisteredParameter[] = [];\n for (const param of this.parameters.values()) {\n if (param.type === type) results.push(param);\n }\n return results;\n }\n\n /** Find all parameters belonging to a given system. */\n findBySystem(system: string): RegisteredParameter[] {\n const results: RegisteredParameter[] = [];\n for (const param of this.parameters.values()) {\n if (param.scope?.system === system) results.push(param);\n }\n return results;\n }\n\n /** Get a parameter by its concrete key. */\n get(key: string): RegisteredParameter | undefined {\n return this.parameters.get(key);\n }\n\n /** Get the flow impact of a parameter by its concrete key. */\n getFlowImpact(key: string): FlowImpact | undefined {\n return this.parameters.get(key)?.flowImpact;\n }\n\n /** Update the current value of a registered parameter. */\n updateValue(key: string, value: number): void {\n const param = this.parameters.get(key);\n if (param) {\n param.currentValue = value;\n }\n }\n\n /** Get all registered parameters. */\n getAll(): RegisteredParameter[] {\n return [...this.parameters.values()];\n }\n\n /** Number of registered parameters. */\n get size(): number {\n return this.parameters.size;\n }\n\n /**\n * Validate the registry for common misconfigurations.\n * Returns warnings (non-fatal) and errors (likely broken).\n */\n validate(): RegistryValidationResult {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n // Check for duplicate keys (impossible via Map, but verify types with same scope)\n const typeMap = new Map<string, RegisteredParameter[]>();\n for (const param of this.parameters.values()) {\n const list = typeMap.get(param.type) ?? [];\n list.push(param);\n typeMap.set(param.type, list);\n }\n\n // Warn: types with multiple entries but no scope differentiation\n for (const [type, params] of typeMap) {\n if (params.length > 1) {\n const unscopedCount = params.filter(p => !p.scope).length;\n if (unscopedCount > 1) {\n errors.push(\n `Type '${type}' has ${unscopedCount} unscoped parameters — resolve() cannot distinguish them`,\n );\n }\n }\n }\n\n // Warn: parameters without flowImpact\n for (const param of this.parameters.values()) {\n if (!param.flowImpact) {\n warnings.push(`Parameter '${param.key}' has no flowImpact — Simulator will use inference`);\n }\n }\n\n return {\n valid: errors.length === 0,\n warnings,\n errors,\n };\n }\n\n // ── Private ─────────────────────────────────────────────────────────────\n\n private scopeSpecificity(\n paramScope?: Partial<ParameterScope>,\n queryScope?: Partial<ParameterScope>,\n ): number {\n // No query scope → any param matches with base score\n if (!queryScope) return 0;\n // No param scope → generic match (lowest priority)\n if (!paramScope) return 0;\n\n let score = 0;\n\n // System match\n if (queryScope.system && paramScope.system) {\n if (queryScope.system === paramScope.system) score += 10;\n else return -Infinity; // system mismatch = disqualify\n }\n\n // Currency match\n if (queryScope.currency && paramScope.currency) {\n if (queryScope.currency === paramScope.currency) score += 5;\n else return -Infinity; // currency mismatch = disqualify\n }\n\n // Tag overlap\n if (queryScope.tags && queryScope.tags.length > 0 && paramScope.tags && paramScope.tags.length > 0) {\n const overlap = queryScope.tags.filter(t => paramScope.tags!.includes(t)).length;\n if (overlap > 0) {\n score += overlap * 3;\n } else {\n return -Infinity; // no tag overlap when both specify tags = disqualify\n }\n }\n\n return score;\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 EconomyMetrics,\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';\nimport { ParameterRegistry } from './ParameterRegistry.js';\nimport type { RegisteredParameter } from './ParameterRegistry.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: Simulator;\n private planner = new Planner();\n private executor!: Executor;\n private registry = new ParameterRegistry();\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 validateRegistry: config.validateRegistry ?? true,\n simulation: config.simulation ?? {},\n settlementWindowTicks: config.settlementWindowTicks ?? 200,\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 parameters: config.parameters ?? [],\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 // Register parameters if provided\n if (config.parameters) {\n this.registry.registerAll(config.parameters);\n }\n\n // Validate registry on startup (default: true)\n if (config.validateRegistry !== false && this.registry.size > 0) {\n const validation = this.registry.validate();\n for (const w of validation.warnings) console.warn(`[AgentE] Registry warning: ${w}`);\n for (const e of validation.errors) console.error(`[AgentE] Registry error: ${e}`);\n }\n\n this.executor = new Executor(config.settlementWindowTicks);\n this.simulator = new Simulator(this.registry, config.simulation);\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 reward parameter 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 (atomic swap — no window for lost events)\n const events = this.eventBuffer;\n this.eventBuffer = [];\n\n // Stage 1: Observe\n let metrics: EconomyMetrics;\n try {\n metrics = this.observer.compute(currentState, events);\n } catch (err) {\n console.error(`[AgentE] Observer.compute() failed at tick ${currentState.tick}:`, err);\n return; // skip this tick, don't crash the loop\n }\n this.store.record(metrics);\n this.personaTracker.update(currentState, events);\n metrics.personaDistribution = this.personaTracker.getDistribution();\n\n // Check rollbacks on active plans\n const { rolledBack, settled } = 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 for (const plan of settled) {\n this.planner.recordSettled(plan);\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 this.registry,\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.registry.updateValue(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.registry.updateValue(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 setMode(mode: AgentEMode): void {\n this.mode = mode;\n }\n\n getMode(): AgentEMode {\n return this.mode;\n }\n\n removePrinciple(id: string): void {\n this.diagnoser.removePrinciple(id);\n }\n\n registerParameter(param: RegisteredParameter): void {\n this.registry.register(param);\n }\n\n getRegistry(): ParameterRegistry {\n return this.registry;\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 if (!list.includes(handler)) {\n list.push(handler);\n }\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 try {\n result = handler(...args);\n if (result === false) return false; // veto\n } catch (err) {\n console.error(`[AgentE] Handler error on '${event}':`, err);\n }\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","// Utility functions for economy analysis\n\nimport type { EconomyMetrics } from './types.js';\n\n/**\n * Find the system with the worst metric value.\n * Works with flat Record<string, number> maps like flowBySystem.\n *\n * @param metrics - Current economy metrics snapshot\n * @param check - Function that returns a numeric \"badness\" score per system (higher = worse)\n * @param tolerancePercent - Only flag if the worst system exceeds the average by this % (default 0)\n * @returns The system name and its score, or undefined if no systems or none exceeds tolerance\n */\nexport function findWorstSystem(\n metrics: EconomyMetrics,\n check: (systemName: string, metrics: EconomyMetrics) => number,\n tolerancePercent: number = 0,\n): { system: string; score: number } | undefined {\n const systems = metrics.systems;\n if (systems.length === 0) return undefined;\n\n let worstSystem: string | undefined;\n let worstScore = -Infinity;\n let totalScore = 0;\n\n for (const sys of systems) {\n const score = check(sys, metrics);\n totalScore += score;\n if (score > worstScore) {\n worstScore = score;\n worstSystem = sys;\n }\n }\n\n if (!worstSystem) return undefined;\n\n // Tolerance check: only flag if worst exceeds average by tolerancePercent\n if (tolerancePercent > 0 && systems.length > 1) {\n const avg = totalScore / systems.length;\n if (avg === 0) return { system: worstSystem, score: worstScore };\n const excessPercent = ((worstScore - avg) / Math.abs(avg)) * 100;\n if (excessPercent < tolerancePercent) return undefined;\n }\n\n return { system: worstSystem, score: worstScore };\n}\n","// StateValidator — validates incoming EconomyState shape at runtime\n\nexport interface ValidationError {\n path: string;\n expected: string;\n received: string;\n message: string;\n}\n\nexport interface ValidationWarning {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n warnings: ValidationWarning[];\n}\n\nexport function validateEconomyState(state: unknown): ValidationResult {\n const errors: ValidationError[] = [];\n const warnings: ValidationWarning[] = [];\n\n if (state === null || state === undefined || typeof state !== 'object') {\n errors.push({\n path: '',\n expected: 'object',\n received: state === null ? 'null' : typeof state,\n message: 'State must be a non-null object',\n });\n return { valid: false, errors, warnings };\n }\n\n const s = state as Record<string, unknown>;\n\n // ── tick ──\n if (!isNonNegativeInteger(s['tick'])) {\n errors.push({\n path: 'tick',\n expected: 'non-negative integer',\n received: describeValue(s['tick']),\n message: 'tick must be a non-negative integer',\n });\n }\n\n // ── roles ──\n if (!isNonEmptyStringArray(s['roles'])) {\n errors.push({\n path: 'roles',\n expected: 'non-empty string[]',\n received: describeValue(s['roles']),\n message: 'roles must be a non-empty array of strings',\n });\n }\n const roles = new Set(Array.isArray(s['roles']) ? (s['roles'] as unknown[]).filter(r => typeof r === 'string') as string[] : []);\n\n // ── resources ──\n if (!isStringArray(s['resources'])) {\n errors.push({\n path: 'resources',\n expected: 'string[]',\n received: describeValue(s['resources']),\n message: 'resources must be an array of strings (can be empty)',\n });\n }\n const resources = new Set(Array.isArray(s['resources']) ? (s['resources'] as unknown[]).filter(r => typeof r === 'string') as string[] : []);\n\n // ── currencies ──\n if (!isNonEmptyStringArray(s['currencies'])) {\n errors.push({\n path: 'currencies',\n expected: 'non-empty string[]',\n received: describeValue(s['currencies']),\n message: 'currencies must be a non-empty array of strings',\n });\n }\n const currencies = new Set(\n Array.isArray(s['currencies'])\n ? (s['currencies'] as unknown[]).filter(r => typeof r === 'string') as string[]\n : [],\n );\n\n // ── agentBalances ── Record<string, Record<string, number>>\n if (isRecord(s['agentBalances'])) {\n const balances = s['agentBalances'] as Record<string, unknown>;\n for (const [agentId, currencyMap] of Object.entries(balances)) {\n if (!isRecord(currencyMap)) {\n errors.push({\n path: `agentBalances.${agentId}`,\n expected: 'Record<string, number>',\n received: describeValue(currencyMap),\n message: `agentBalances.${agentId} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [currency, value] of Object.entries(currencyMap as Record<string, unknown>)) {\n if (typeof value !== 'number' || value < 0) {\n errors.push({\n path: `agentBalances.${agentId}.${currency}`,\n expected: 'number >= 0',\n received: describeValue(value),\n message: `agentBalances.${agentId}.${currency} must be a non-negative number`,\n });\n }\n if (currencies.size > 0 && !currencies.has(currency)) {\n errors.push({\n path: `agentBalances.${agentId}.${currency}`,\n expected: `one of [${[...currencies].join(', ')}]`,\n received: currency,\n message: `agentBalances currency key \"${currency}\" is not in currencies`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'agentBalances',\n expected: 'Record<string, Record<string, number>>',\n received: describeValue(s['agentBalances']),\n message: 'agentBalances must be a nested Record<string, Record<string, number>>',\n });\n }\n\n // ── agentRoles ── Record<string, string>\n if (isRecord(s['agentRoles'])) {\n const agentRoles = s['agentRoles'] as Record<string, unknown>;\n for (const [agentId, role] of Object.entries(agentRoles)) {\n if (typeof role !== 'string') {\n errors.push({\n path: `agentRoles.${agentId}`,\n expected: 'string',\n received: describeValue(role),\n message: `agentRoles.${agentId} must be a string`,\n });\n } else if (roles.size > 0 && !roles.has(role)) {\n errors.push({\n path: `agentRoles.${agentId}`,\n expected: `one of [${[...roles].join(', ')}]`,\n received: role,\n message: `agentRoles value \"${role}\" is not in roles`,\n });\n }\n }\n } else {\n errors.push({\n path: 'agentRoles',\n expected: 'Record<string, string>',\n received: describeValue(s['agentRoles']),\n message: 'agentRoles must be a Record<string, string>',\n });\n }\n\n // ── agentInventories ── Record<string, Record<string, number>>\n if (isRecord(s['agentInventories'])) {\n const inventories = s['agentInventories'] as Record<string, unknown>;\n for (const [agentId, inv] of Object.entries(inventories)) {\n if (!isRecord(inv)) {\n errors.push({\n path: `agentInventories.${agentId}`,\n expected: 'Record<string, number>',\n received: describeValue(inv),\n message: `agentInventories.${agentId} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [resource, qty] of Object.entries(inv as Record<string, unknown>)) {\n if (typeof qty !== 'number' || qty < 0) {\n errors.push({\n path: `agentInventories.${agentId}.${resource}`,\n expected: 'number >= 0',\n received: describeValue(qty),\n message: `agentInventories.${agentId}.${resource} must be a non-negative number`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'agentInventories',\n expected: 'Record<string, Record<string, number>>',\n received: describeValue(s['agentInventories']),\n message: 'agentInventories must be a Record<string, Record<string, number>>',\n });\n }\n\n // ── marketPrices ── Record<string, Record<string, number>>\n if (isRecord(s['marketPrices'])) {\n const marketPrices = s['marketPrices'] as Record<string, unknown>;\n for (const [currency, resourcePrices] of Object.entries(marketPrices)) {\n if (currencies.size > 0 && !currencies.has(currency)) {\n errors.push({\n path: `marketPrices.${currency}`,\n expected: `one of [${[...currencies].join(', ')}]`,\n received: currency,\n message: `marketPrices outer key \"${currency}\" is not in currencies`,\n });\n }\n if (!isRecord(resourcePrices)) {\n errors.push({\n path: `marketPrices.${currency}`,\n expected: 'Record<string, number>',\n received: describeValue(resourcePrices),\n message: `marketPrices.${currency} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [resource, price] of Object.entries(resourcePrices as Record<string, unknown>)) {\n if (typeof price !== 'number' || price < 0) {\n errors.push({\n path: `marketPrices.${currency}.${resource}`,\n expected: 'number >= 0',\n received: describeValue(price),\n message: `marketPrices.${currency}.${resource} must be a non-negative number`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'marketPrices',\n expected: 'Record<string, Record<string, number>>',\n received: describeValue(s['marketPrices']),\n message: 'marketPrices must be a nested Record<string, Record<string, number>>',\n });\n }\n\n // ── recentTransactions ── array\n if (!Array.isArray(s['recentTransactions'])) {\n errors.push({\n path: 'recentTransactions',\n expected: 'array',\n received: describeValue(s['recentTransactions']),\n message: 'recentTransactions must be an array',\n });\n }\n\n // ── Optional: agentSatisfaction ──\n if (s['agentSatisfaction'] !== undefined) {\n if (isRecord(s['agentSatisfaction'])) {\n const satisfaction = s['agentSatisfaction'] as Record<string, unknown>;\n for (const [agentId, value] of Object.entries(satisfaction)) {\n if (typeof value !== 'number' || value < 0 || value > 100) {\n errors.push({\n path: `agentSatisfaction.${agentId}`,\n expected: 'number 0-100',\n received: describeValue(value),\n message: `agentSatisfaction.${agentId} must be a number between 0 and 100`,\n });\n }\n }\n } else {\n errors.push({\n path: 'agentSatisfaction',\n expected: 'Record<string, number> | undefined',\n received: describeValue(s['agentSatisfaction']),\n message: 'agentSatisfaction must be a Record<string, number> if provided',\n });\n }\n }\n\n // ── Optional: poolSizes ── Record<string, Record<string, number>>\n if (s['poolSizes'] !== undefined) {\n if (isRecord(s['poolSizes'])) {\n const pools = s['poolSizes'] as Record<string, unknown>;\n for (const [currency, poolMap] of Object.entries(pools)) {\n if (!isRecord(poolMap)) {\n errors.push({\n path: `poolSizes.${currency}`,\n expected: 'Record<string, number>',\n received: describeValue(poolMap),\n message: `poolSizes.${currency} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [poolName, size] of Object.entries(poolMap as Record<string, unknown>)) {\n if (typeof size !== 'number' || size < 0) {\n errors.push({\n path: `poolSizes.${currency}.${poolName}`,\n expected: 'number >= 0',\n received: describeValue(size),\n message: `poolSizes.${currency}.${poolName} must be a non-negative number`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'poolSizes',\n expected: 'Record<string, Record<string, number>> | undefined',\n received: describeValue(s['poolSizes']),\n message: 'poolSizes must be a nested Record if provided',\n });\n }\n }\n\n // ── Warnings ──\n\n // Currency declared but no agent holds it\n if (currencies.size > 0 && isRecord(s['agentBalances'])) {\n const heldCurrencies = new Set<string>();\n const balances = s['agentBalances'] as Record<string, Record<string, unknown>>;\n for (const currencyMap of Object.values(balances)) {\n if (isRecord(currencyMap)) {\n for (const key of Object.keys(currencyMap as Record<string, unknown>)) {\n heldCurrencies.add(key);\n }\n }\n }\n for (const currency of currencies) {\n if (!heldCurrencies.has(currency)) {\n warnings.push({\n path: `currencies`,\n message: `Currency \"${currency}\" is declared but no agent holds it`,\n });\n }\n }\n }\n\n // Agent with balance but no role\n if (isRecord(s['agentBalances']) && isRecord(s['agentRoles'])) {\n const agentRoles = s['agentRoles'] as Record<string, unknown>;\n const agentBalances = s['agentBalances'] as Record<string, unknown>;\n for (const agentId of Object.keys(agentBalances)) {\n if (!(agentId in agentRoles)) {\n warnings.push({\n path: `agentBalances.${agentId}`,\n message: `Agent \"${agentId}\" has balances but no role assigned`,\n });\n }\n }\n }\n\n // Empty resources with non-empty inventories\n if (resources.size === 0 && isRecord(s['agentInventories'])) {\n const inventories = s['agentInventories'] as Record<string, unknown>;\n let hasItems = false;\n for (const inv of Object.values(inventories)) {\n if (isRecord(inv) && Object.keys(inv as Record<string, unknown>).length > 0) {\n hasItems = true;\n break;\n }\n }\n if (hasItems) {\n warnings.push({\n path: 'resources',\n message: 'resources is empty but agents have non-empty inventories',\n });\n }\n }\n\n // Events referencing unknown currencies\n if (Array.isArray(s['recentTransactions']) && currencies.size > 0) {\n for (const event of s['recentTransactions'] as unknown[]) {\n if (isRecord(event)) {\n const e = event as Record<string, unknown>;\n if (typeof e['metadata'] === 'object' && e['metadata'] !== null) {\n const meta = e['metadata'] as Record<string, unknown>;\n if (typeof meta['currency'] === 'string' && !currencies.has(meta['currency'])) {\n warnings.push({\n path: 'recentTransactions',\n message: `Event references unknown currency \"${meta['currency']}\"`,\n });\n }\n }\n }\n }\n }\n\n return { valid: errors.length === 0, errors, warnings };\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction isRecord(value: unknown): boolean {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isStringArray(value: unknown): boolean {\n return Array.isArray(value) && value.every((v: unknown) => typeof v === 'string');\n}\n\nfunction isNonEmptyStringArray(value: unknown): boolean {\n return isStringArray(value) && (value as unknown[]).length > 0;\n}\n\nfunction isNonNegativeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0;\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return `array(${value.length})`;\n return typeof value;\n}\n"],"mappings":";AAEO,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,EAClB,mBAAmB;AAAA,EACnB,uBAAuB;AAAA;AAAA,EAGvB,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,qBAAqB;AAAA;AAAA,EAGrB,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,oBAAoB;AAAA;AAAA,EAGpB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,qBAAqB;AAAA;AAAA,EAGrB,2BAA2B;AAAA;AAAA,EAG3B,sBAAsB;AAAA,EACtB,eAAe;AAAA;AAAA,EAGf,aAAa;AAAA,EACb,mBAAmB;AAAA;AAAA,EAGnB,uBAAuB;AAAA;AAAA;AAAA,EAGvB,gBAAgB;AAAA;AAAA,EAChB,eAAe;AAAA;AAAA,EAGf,qBAAqB;AAAA;AAAA;AAAA,EAGrB,yBAAyB;AAAA;AAAA,EAGzB,mBAAmB;AAAA,EACnB,kBAAkB;AAAA;AAAA,EAGlB,eAAe;AAAA;AAAA,EAGf,sBAAsB;AAAA;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AChB;","names":["plan","entry"]}
1
+ {"version":3,"sources":["../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/participant-experience.ts","../src/principles/open-economy.ts","../src/principles/operations.ts","../src/principles/index.ts","../src/Simulator.ts","../src/Planner.ts","../src/Executor.ts","../src/DecisionLog.ts","../src/MetricStore.ts","../src/PersonaTracker.ts","../src/ParameterRegistry.ts","../src/AgentE.ts","../src/utils.ts","../src/StateValidator.ts"],"sourcesContent":["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 // Participant Experience (P45, P50)\n timeBudgetRatio: 0.80,\n payPowerRatioMax: 2.0,\n payPowerRatioTarget: 1.5,\n\n // Operations (P51, P53)\n cyclicalPeakDecay: 0.95,\n cyclicalValleyDecay: 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 poolOperatorShare: 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 HighValue: { 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 { DEFAULT_TICK_CONFIG } from './defaults.js';\n\nexport class Observer {\n private previousMetrics: EconomyMetrics | null = null;\n private previousPricesByCurrency: Record<string, Record<string, number>> = {};\n private customMetricFns: Record<string, (state: EconomyState) => number> = {};\n private anchorBaselineByCurrency: Record<string, { currencyPerPeriod: number; itemsPerCurrency: number }> = {};\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 if (!state.currencies || state.currencies.length === 0) {\n console.warn('[AgentE] Warning: state.currencies is empty. Metrics will be zeroed.');\n }\n if (!state.agentBalances || Object.keys(state.agentBalances).length === 0) {\n console.warn('[AgentE] Warning: state.agentBalances is empty.');\n }\n\n const tick = state.tick;\n const roles = Object.values(state.agentRoles);\n const totalAgents = Object.keys(state.agentBalances).length;\n\n // ── Event classification (single pass, per-currency) ──\n let productionAmount = 0;\n const faucetVolumeByCurrency: Record<string, number> = {};\n const sinkVolumeByCurrency: Record<string, number> = {};\n const tradeEvents: EconomicEvent[] = [];\n const roleChangeEvents: EconomicEvent[] = [];\n let churnCount = 0;\n const defaultCurrency = state.currencies[0] ?? 'default';\n\n for (const e of recentEvents) {\n const curr = e.currency ?? defaultCurrency;\n switch (e.type) {\n case 'mint':\n case 'enter':\n faucetVolumeByCurrency[curr] = (faucetVolumeByCurrency[curr] ?? 0) + (e.amount ?? 0);\n break;\n case 'burn':\n case 'consume':\n sinkVolumeByCurrency[curr] = (sinkVolumeByCurrency[curr] ?? 0) + (e.amount ?? 0);\n break;\n case 'produce':\n productionAmount += e.amount ?? 1;\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 // ── Per-system & per-source/sink tracking ──\n const flowBySystem: Record<string, number> = {};\n const activityBySystem: Record<string, number> = {};\n const actorsBySystem: Record<string, Set<string>> = {};\n const flowBySource: Record<string, number> = {};\n const flowBySink: Record<string, number> = {};\n\n for (const e of recentEvents) {\n if (e.system) {\n activityBySystem[e.system] = (activityBySystem[e.system] ?? 0) + 1;\n if (!actorsBySystem[e.system]) actorsBySystem[e.system] = new Set();\n actorsBySystem[e.system]!.add(e.actor);\n\n const amt = e.amount ?? 0;\n if (e.type === 'mint') {\n flowBySystem[e.system] = (flowBySystem[e.system] ?? 0) + amt;\n } else if (e.type === 'burn' || e.type === 'consume') {\n flowBySystem[e.system] = (flowBySystem[e.system] ?? 0) - amt;\n }\n }\n if (e.sourceOrSink) {\n const amt = e.amount ?? 0;\n if (e.type === 'mint') {\n flowBySource[e.sourceOrSink] = (flowBySource[e.sourceOrSink] ?? 0) + amt;\n } else if (e.type === 'burn' || e.type === 'consume') {\n flowBySink[e.sourceOrSink] = (flowBySink[e.sourceOrSink] ?? 0) + amt;\n }\n }\n }\n\n const participantsBySystem: Record<string, number> = {};\n for (const [sys, actors] of Object.entries(actorsBySystem)) {\n participantsBySystem[sys] = actors.size;\n }\n\n const totalSourceFlow = Object.values(flowBySource).reduce((s, v) => s + v, 0);\n const sourceShare: Record<string, number> = {};\n for (const [src, vol] of Object.entries(flowBySource)) {\n sourceShare[src] = totalSourceFlow > 0 ? vol / totalSourceFlow : 0;\n }\n\n const totalSinkFlow = Object.values(flowBySink).reduce((s, v) => s + v, 0);\n const sinkShare: Record<string, number> = {};\n for (const [snk, vol] of Object.entries(flowBySink)) {\n sinkShare[snk] = totalSinkFlow > 0 ? vol / totalSinkFlow : 0;\n }\n\n const currencies = state.currencies;\n\n // ── Per-currency supply ──\n const totalSupplyByCurrency: Record<string, number> = {};\n const balancesByCurrency: Record<string, number[]> = {};\n\n for (const [_agentId, balances] of Object.entries(state.agentBalances)) {\n for (const [curr, bal] of Object.entries(balances)) {\n totalSupplyByCurrency[curr] = (totalSupplyByCurrency[curr] ?? 0) + bal;\n if (!balancesByCurrency[curr]) balancesByCurrency[curr] = [];\n balancesByCurrency[curr]!.push(bal);\n }\n }\n\n // ── Per-currency flow ──\n const netFlowByCurrency: Record<string, number> = {};\n const tapSinkRatioByCurrency: Record<string, number> = {};\n const inflationRateByCurrency: Record<string, number> = {};\n const velocityByCurrency: Record<string, number> = {};\n\n for (const curr of currencies) {\n const faucet = faucetVolumeByCurrency[curr] ?? 0;\n const sink = sinkVolumeByCurrency[curr] ?? 0;\n netFlowByCurrency[curr] = faucet - sink;\n tapSinkRatioByCurrency[curr] = sink > 0 ? Math.min(faucet / sink, 100) : faucet > 0 ? 100 : 1;\n\n const prevSupply = this.previousMetrics?.totalSupplyByCurrency?.[curr] ?? totalSupplyByCurrency[curr] ?? 0;\n const currSupply = totalSupplyByCurrency[curr] ?? 0;\n inflationRateByCurrency[curr] = prevSupply > 0 ? (currSupply - prevSupply) / prevSupply : 0;\n\n // Velocity: trades involving this currency / supply\n const currTrades = tradeEvents.filter(e => (e.currency ?? defaultCurrency) === curr);\n velocityByCurrency[curr] = currSupply > 0 ? currTrades.length / currSupply : 0;\n }\n\n // ── Per-currency wealth distribution ──\n const giniCoefficientByCurrency: Record<string, number> = {};\n const medianBalanceByCurrency: Record<string, number> = {};\n const meanBalanceByCurrency: Record<string, number> = {};\n const top10PctShareByCurrency: Record<string, number> = {};\n const meanMedianDivergenceByCurrency: Record<string, number> = {};\n\n for (const curr of currencies) {\n const bals = balancesByCurrency[curr] ?? [];\n const sorted = [...bals].sort((a, b) => a - b);\n const supply = totalSupplyByCurrency[curr] ?? 0;\n const count = sorted.length;\n\n const median = computeMedian(sorted);\n const mean = count > 0 ? supply / count : 0;\n const top10Idx = Math.floor(count * 0.9);\n const top10Sum = sorted.slice(top10Idx).reduce((s, b) => s + b, 0);\n\n giniCoefficientByCurrency[curr] = computeGini(sorted);\n medianBalanceByCurrency[curr] = median;\n meanBalanceByCurrency[curr] = mean;\n top10PctShareByCurrency[curr] = supply > 0 ? top10Sum / supply : 0;\n meanMedianDivergenceByCurrency[curr] = median > 0 ? Math.abs(mean - median) / median : 0;\n }\n\n // ── Aggregates (sum/avg across all currencies) ──\n const avgOf = (rec: Record<string, number>): number => {\n const vals = Object.values(rec);\n return vals.length > 0 ? vals.reduce((s, v) => s + v, 0) / vals.length : 0;\n };\n\n const totalSupply = Object.values(totalSupplyByCurrency).reduce((s, v) => s + v, 0);\n const faucetVolume = Object.values(faucetVolumeByCurrency).reduce((s, v) => s + v, 0);\n const sinkVolume = Object.values(sinkVolumeByCurrency).reduce((s, v) => s + v, 0);\n const netFlow = faucetVolume - sinkVolume;\n const tapSinkRatio = sinkVolume > 0 ? Math.min(faucetVolume / sinkVolume, 100) : faucetVolume > 0 ? 100 : 1;\n const velocity = totalSupply > 0 ? tradeEvents.length / totalSupply : 0;\n const prevTotalSupply = this.previousMetrics?.totalSupply ?? totalSupply;\n const inflationRate = prevTotalSupply > 0 ? (totalSupply - prevTotalSupply) / prevTotalSupply : 0;\n\n // Aggregate wealth: average across currencies\n const giniCoefficient = avgOf(giniCoefficientByCurrency);\n const medianBalance = avgOf(medianBalanceByCurrency);\n const meanBalance = totalAgents > 0 ? totalSupply / totalAgents : 0;\n const top10PctShare = avgOf(top10PctShareByCurrency);\n const meanMedianDivergence = avgOf(meanMedianDivergenceByCurrency);\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 // ── Per-currency prices ──\n const pricesByCurrency: Record<string, Record<string, number>> = {};\n const priceVolatilityByCurrency: Record<string, Record<string, number>> = {};\n const priceIndexByCurrency: Record<string, number> = {};\n\n for (const [curr, resourcePrices] of Object.entries(state.marketPrices)) {\n pricesByCurrency[curr] = { ...resourcePrices };\n const pricePrev = this.previousPricesByCurrency?.[curr] ?? {};\n const volMap: Record<string, number> = {};\n for (const [resource, price] of Object.entries(resourcePrices)) {\n const prev = pricePrev[resource] ?? price;\n volMap[resource] = prev > 0 ? Math.abs(price - prev) / prev : 0;\n }\n priceVolatilityByCurrency[curr] = volMap;\n\n const pVals = Object.values(resourcePrices);\n priceIndexByCurrency[curr] = pVals.length > 0 ? pVals.reduce((s, p) => s + p, 0) / pVals.length : 0;\n }\n this.previousPricesByCurrency = Object.fromEntries(\n Object.entries(pricesByCurrency).map(([c, p]) => [c, { ...p }])\n );\n\n // Aggregate prices: use first currency as default\n const prices = pricesByCurrency[defaultCurrency] ?? {};\n const priceVolatility = priceVolatilityByCurrency[defaultCurrency] ?? {};\n const priceIndex = priceIndexByCurrency[defaultCurrency] ?? 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 > 0 && d > 2 && s / d < 0.5) {\n pinchPoints[resource] = 'scarce';\n } else if (d > 0 && s > 3 && s / d > 3) {\n pinchPoints[resource] = 'oversupplied';\n } else {\n pinchPoints[resource] = 'optimal';\n }\n }\n\n const productionIndex = productionAmount;\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 = totalAgents > 0 ? blockedAgentCount / totalAgents * 100 : 0;\n\n // ── Per-currency pools ──\n const poolSizesByCurrency: Record<string, Record<string, number>> = {};\n const poolSizesAggregate: Record<string, number> = {};\n\n if (state.poolSizes) {\n for (const [pool, currencyAmounts] of Object.entries(state.poolSizes)) {\n poolSizesByCurrency[pool] = { ...currencyAmounts };\n poolSizesAggregate[pool] = Object.values(currencyAmounts).reduce((s, v) => s + v, 0);\n }\n }\n\n // ── Per-currency anchor baseline ──\n const anchorRatioDriftByCurrency: Record<string, number> = {};\n if (tick === 1) {\n for (const curr of currencies) {\n const supply = totalSupplyByCurrency[curr] ?? 0;\n if (supply > 0) {\n this.anchorBaselineByCurrency[curr] = {\n currencyPerPeriod: supply / Math.max(1, totalAgents),\n itemsPerCurrency: (priceIndexByCurrency[curr] ?? 0) > 0 ? 1 / priceIndexByCurrency[curr]! : 0,\n };\n }\n }\n }\n for (const curr of currencies) {\n const baseline = this.anchorBaselineByCurrency[curr];\n if (baseline && totalAgents > 0) {\n const currentCPP = (totalSupplyByCurrency[curr] ?? 0) / totalAgents;\n anchorRatioDriftByCurrency[curr] = baseline.currencyPerPeriod > 0\n ? (currentCPP - baseline.currencyPerPeriod) / baseline.currencyPerPeriod\n : 0;\n } else {\n anchorRatioDriftByCurrency[curr] = 0;\n }\n }\n const anchorRatioDrift = avgOf(anchorRatioDriftByCurrency);\n\n // ── V1.1 Metrics ──\n\n // ── Per-currency arbitrage index ──\n // O(n) arbitrage index: standard deviation of log prices\n const arbitrageIndexByCurrency: Record<string, number> = {};\n for (const curr of currencies) {\n const cPrices = pricesByCurrency[curr] ?? {};\n const logPrices = Object.values(cPrices).filter(p => p > 0).map(p => Math.log(p));\n if (logPrices.length >= 2) {\n const mean = logPrices.reduce((s, v) => s + v, 0) / logPrices.length;\n const variance = logPrices.reduce((s, v) => s + (v - mean) ** 2, 0) / logPrices.length;\n arbitrageIndexByCurrency[curr] = Math.min(1, Math.sqrt(variance));\n } else {\n arbitrageIndexByCurrency[curr] = 0;\n }\n }\n const arbitrageIndex = avgOf(arbitrageIndexByCurrency);\n\n // contentDropAge: ticks since last 'produce' event with metadata.contentDrop === true\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 // ── Per-currency gift/disposal trade ratios ──\n const giftTradeRatioByCurrency: Record<string, number> = {};\n const disposalTradeRatioByCurrency: Record<string, number> = {};\n for (const curr of currencies) {\n const currTrades = tradeEvents.filter(e => (e.currency ?? defaultCurrency) === curr);\n const cPrices = pricesByCurrency[curr] ?? {};\n let gifts = 0;\n let disposals = 0;\n for (const e of currTrades) {\n const marketPrice = cPrices[e.resource ?? ''] ?? 0;\n const tradePrice = e.price ?? 0;\n if (tradePrice === 0 || (marketPrice > 0 && tradePrice < marketPrice * 0.3)) gifts++;\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) disposals++;\n }\n }\n giftTradeRatioByCurrency[curr] = currTrades.length > 0 ? gifts / currTrades.length : 0;\n disposalTradeRatioByCurrency[curr] = currTrades.length > 0 ? disposals / currTrades.length : 0;\n }\n const giftTradeRatio = avgOf(giftTradeRatioByCurrency);\n const disposalTradeRatio = avgOf(disposalTradeRatioByCurrency);\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 (err) {\n console.warn(`[AgentE] Custom metric '${name}' threw an error:`, err);\n custom[name] = 0;\n }\n }\n\n const metrics: EconomyMetrics = {\n tick,\n timestamp: Date.now(),\n currencies,\n\n // Per-currency\n totalSupplyByCurrency,\n netFlowByCurrency,\n velocityByCurrency,\n inflationRateByCurrency,\n faucetVolumeByCurrency,\n sinkVolumeByCurrency,\n tapSinkRatioByCurrency,\n anchorRatioDriftByCurrency,\n giniCoefficientByCurrency,\n medianBalanceByCurrency,\n meanBalanceByCurrency,\n top10PctShareByCurrency,\n meanMedianDivergenceByCurrency,\n priceIndexByCurrency,\n pricesByCurrency,\n priceVolatilityByCurrency,\n poolSizesByCurrency,\n extractionRatioByCurrency: {},\n newUserDependencyByCurrency: {},\n currencyInsulationByCurrency: {},\n arbitrageIndexByCurrency,\n giftTradeRatioByCurrency,\n disposalTradeRatioByCurrency,\n\n // Aggregates\n totalSupply,\n netFlow,\n velocity,\n inflationRate,\n faucetVolume,\n sinkVolume,\n tapSinkRatio,\n anchorRatioDrift,\n giniCoefficient,\n medianBalance,\n meanBalance,\n top10PctShare,\n meanMedianDivergence,\n priceIndex,\n prices,\n priceVolatility,\n poolSizes: poolSizesAggregate,\n extractionRatio: 0,\n newUserDependency: 0,\n smokeTestRatio: 0,\n currencyInsulation: 0,\n arbitrageIndex,\n giftTradeRatio,\n disposalTradeRatio,\n\n // Unchanged\n populationByRole,\n roleShares,\n totalAgents,\n churnRate,\n churnByRole,\n personaDistribution: {}, // populated by PersonaTracker\n productionIndex,\n capacityUsage,\n supplyByResource,\n demandSignals,\n pinchPoints,\n avgSatisfaction,\n blockedAgentCount,\n timeToValue,\n cyclicalPeaks: this.previousMetrics?.cyclicalPeaks ?? [],\n cyclicalValleys: this.previousMetrics?.cyclicalValleys ?? [],\n eventCompletionRate: 0,\n contentDropAge,\n systems: state.systems ?? [],\n sources: state.sources ?? [],\n sinks: state.sinks ?? [],\n flowBySystem,\n activityBySystem,\n participantsBySystem,\n flowBySource,\n flowBySink,\n sourceShare,\n sinkShare,\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.min(1, 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 | 'enter'\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 currency?: string; // which currency this event affects (defaults to first in currencies[])\n amount?: number; // quantity\n price?: number; // per-unit price (in the event's currency)\n from?: string; // source (for transfers)\n to?: string; // destination\n system?: string; // which subsystem generated this event\n sourceOrSink?: string; // named source/sink for flow attribution\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 currencies: string[]; // all tracked currencies this tick\n\n // ── Currency health (per-currency) ──\n totalSupplyByCurrency: Record<string, number>; // currency → total supply\n netFlowByCurrency: Record<string, number>; // currency → faucets minus sinks\n velocityByCurrency: Record<string, number>; // currency → transactions / supply\n inflationRateByCurrency: Record<string, number>; // currency → % change per period\n faucetVolumeByCurrency: Record<string, number>; // currency → inflow volume\n sinkVolumeByCurrency: Record<string, number>; // currency → outflow volume\n tapSinkRatioByCurrency: Record<string, number>; // currency → faucet / sink ratio\n anchorRatioDriftByCurrency: Record<string, number>;// currency → anchor drift\n\n // ── Currency health (aggregate convenience — sum/avg of all currencies) ──\n totalSupply: number;\n netFlow: number;\n velocity: number;\n inflationRate: number;\n faucetVolume: number;\n sinkVolume: number;\n tapSinkRatio: number;\n anchorRatioDrift: number;\n\n // ── Wealth distribution (per-currency) ──\n giniCoefficientByCurrency: Record<string, number>;\n medianBalanceByCurrency: Record<string, number>;\n meanBalanceByCurrency: Record<string, number>;\n top10PctShareByCurrency: Record<string, number>;\n meanMedianDivergenceByCurrency: Record<string, number>;\n\n // ── Wealth distribution (aggregate convenience) ──\n giniCoefficient: number;\n medianBalance: number;\n meanBalance: number;\n top10PctShare: number;\n meanMedianDivergence: number;\n\n // ── Population health (unchanged — not currency-specific) ──\n populationByRole: Record<string, number>;\n roleShares: Record<string, number>;\n totalAgents: number;\n churnRate: number;\n churnByRole: Record<string, number>;\n personaDistribution: Record<string, number>;\n\n // ── Market health (per-currency prices) ──\n priceIndexByCurrency: Record<string, number>; // currency → equal-weight price basket\n pricesByCurrency: Record<string, Record<string, number>>; // currency → resource → price\n priceVolatilityByCurrency: Record<string, Record<string, number>>; // currency → resource → volatility\n\n // ── Market health (aggregate convenience) ──\n priceIndex: number;\n prices: Record<string, number>; // first currency's prices (backward compat)\n priceVolatility: Record<string, number>; // first currency's volatility\n\n // ── Market health (unchanged — resource-keyed, not currency-specific) ──\n productionIndex: number;\n capacityUsage: number;\n supplyByResource: Record<string, number>;\n demandSignals: Record<string, number>;\n pinchPoints: Record<string, PinchPointStatus>;\n\n // ── Satisfaction / Engagement (unchanged) ──\n avgSatisfaction: number;\n blockedAgentCount: number;\n timeToValue: number;\n\n // ── Pools (per-currency) ──\n poolSizesByCurrency: Record<string, Record<string, number>>; // pool → currency → amount\n poolSizes: Record<string, number>; // aggregate: pool → sum of all currencies\n\n // ── Open economy (per-currency) ──\n extractionRatioByCurrency: Record<string, number>;\n newUserDependencyByCurrency: Record<string, number>;\n currencyInsulationByCurrency: Record<string, number>;\n\n // ── Open economy (aggregate convenience) ──\n extractionRatio: number;\n newUserDependency: number;\n smokeTestRatio: number;\n currencyInsulation: number;\n\n // ── Operations (unchanged) ──\n cyclicalPeaks: number[];\n cyclicalValleys: number[];\n eventCompletionRate: number;\n\n // ── V1.1 Metrics (per-currency where applicable) ──\n arbitrageIndexByCurrency: Record<string, number>; // per-currency cross-resource arbitrage\n arbitrageIndex: number; // aggregate\n contentDropAge: number; // unchanged (not currency-specific)\n giftTradeRatioByCurrency: Record<string, number>;\n giftTradeRatio: number;\n disposalTradeRatioByCurrency: Record<string, number>;\n disposalTradeRatio: number;\n\n // ── Topology (from EconomyState) ──\n systems: string[]; // registered systems\n sources: string[]; // registered source names\n sinks: string[]; // registered sink names\n\n // ── Multi-system metrics ──\n flowBySystem: Record<string, number>; // system → net flow\n activityBySystem: Record<string, number>; // system → event count\n participantsBySystem: Record<string, number>; // system → unique actor count\n flowBySource: Record<string, number>; // source → inflow volume\n flowBySink: Record<string, number>; // sink → outflow volume\n sourceShare: Record<string, number>; // source → fraction of total inflow\n sinkShare: Record<string, number>; // sink → fraction of total outflow\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 currencies: [],\n\n // Per-currency\n totalSupplyByCurrency: {},\n netFlowByCurrency: {},\n velocityByCurrency: {},\n inflationRateByCurrency: {},\n faucetVolumeByCurrency: {},\n sinkVolumeByCurrency: {},\n tapSinkRatioByCurrency: {},\n anchorRatioDriftByCurrency: {},\n giniCoefficientByCurrency: {},\n medianBalanceByCurrency: {},\n meanBalanceByCurrency: {},\n top10PctShareByCurrency: {},\n meanMedianDivergenceByCurrency: {},\n priceIndexByCurrency: {},\n pricesByCurrency: {},\n priceVolatilityByCurrency: {},\n poolSizesByCurrency: {},\n extractionRatioByCurrency: {},\n newUserDependencyByCurrency: {},\n currencyInsulationByCurrency: {},\n arbitrageIndexByCurrency: {},\n giftTradeRatioByCurrency: {},\n disposalTradeRatioByCurrency: {},\n\n // Aggregates\n totalSupply: 0,\n netFlow: 0,\n velocity: 0,\n inflationRate: 0,\n faucetVolume: 0,\n sinkVolume: 0,\n tapSinkRatio: 1,\n anchorRatioDrift: 0,\n giniCoefficient: 0,\n medianBalance: 0,\n meanBalance: 0,\n top10PctShare: 0,\n meanMedianDivergence: 0,\n priceIndex: 0,\n prices: {},\n priceVolatility: {},\n poolSizes: {},\n extractionRatio: 0,\n newUserDependency: 0,\n smokeTestRatio: 0,\n currencyInsulation: 0,\n arbitrageIndex: 0,\n giftTradeRatio: 0,\n disposalTradeRatio: 0,\n\n // Unchanged\n populationByRole: {},\n roleShares: {},\n totalAgents: 0,\n churnRate: 0,\n churnByRole: {},\n personaDistribution: {},\n productionIndex: 0,\n capacityUsage: 0,\n supplyByResource: {},\n demandSignals: {},\n pinchPoints: {},\n avgSatisfaction: 100,\n blockedAgentCount: 0,\n timeToValue: 0,\n cyclicalPeaks: [],\n cyclicalValleys: [],\n eventCompletionRate: 0,\n contentDropAge: 0,\n systems: [],\n sources: [],\n sinks: [],\n flowBySystem: {},\n activityBySystem: {},\n participantsBySystem: {},\n flowBySource: {},\n flowBySink: {},\n sourceShare: {},\n sinkShare: {},\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 | 'participant_experience'\n | 'statistical'\n | 'system_dynamics'\n | 'open_economy'\n | 'operations';\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 parameterType: import('./ParameterRegistry.js').ParameterType;\n direction: 'increase' | 'decrease' | 'set';\n magnitude?: number; // fractional (0.15 = 15%)\n absoluteValue?: number;\n scope?: Partial<import('./ParameterRegistry.js').ParameterScope>;\n resolvedParameter?: string; // filled by Planner after registry resolution\n reasoning: string;\n}\n\nexport interface ActionPlan {\n id: string;\n diagnosis: Diagnosis;\n parameter: string;\n scope?: import('./ParameterRegistry.js').ParameterScope;\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 | 'rejected';\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 currencies: string[]; // e.g. ['gold', 'gems', 'stakingToken']\n agentBalances: Record<string, Record<string, number>>; // agentId → { currencyName → balance }\n agentRoles: Record<string, string>;\n agentInventories: Record<string, Record<string, number>>;\n agentSatisfaction?: Record<string, number>;\n marketPrices: Record<string, Record<string, number>>; // currencyName → { resource → price }\n recentTransactions: EconomicEvent[];\n poolSizes?: Record<string, Record<string, number>>; // poolName → { currencyName → amount }\n systems?: string[]; // e.g. ['marketplace', 'staking', 'production']\n sources?: string[]; // named faucet sources\n sinks?: string[]; // named sink channels\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, scope?: import('./ParameterRegistry.js').ParameterScope): 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 // Participant Experience (P45, P50)\n timeBudgetRatio: number;\n payPowerRatioMax: number;\n payPowerRatioTarget: number;\n\n // Operations (P51, P53)\n cyclicalPeakDecay: number;\n cyclicalValleyDecay: 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 pools (competitive, liquidity, staking, etc.)\n poolOperatorShare: number; // generic: operator's share of pool proceeds\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\n// ── Simulation Config ─────────────────────────────────────────────────────────\n\nexport interface SimulationConfig {\n sinkMultiplier?: number; // default 0.20\n faucetMultiplier?: number; // default 0.15\n frictionMultiplier?: number; // default 0.10\n frictionVelocityScale?: number; // default 10\n redistributionMultiplier?: number; // default 0.30\n neutralMultiplier?: number; // default 0.05\n minIterations?: number; // default 100\n maxProjectionTicks?: number; // default 20\n}\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 // Parameter registry\n parameters?: import('./ParameterRegistry.js').RegisteredParameter[];\n /** Run registry.validate() on startup and log warnings/errors (default: true) */\n validateRegistry?: boolean;\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 // Simulation tuning\n simulation?: SimulationConfig;\n\n // Executor settlement window (ticks before plan auto-settles; default: 200)\n settlementWindowTicks?: 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 | 'Whale'\n | 'ActiveTrader'\n | 'Accumulator'\n | 'Spender'\n | 'NewEntrant'\n | 'AtRisk'\n | 'Dormant'\n | 'PowerUser'\n | 'Passive'\n | string; // extensible — adapters can add domain-specific labels\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: Supply-chain failure patterns — resource accumulation at bottlenecks, 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 parameterType: 'cost',\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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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 } = 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 parameterType: 'cost',\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 produce 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 parameterType: 'yield',\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 parameterType: 'yield',\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 parameterType: 'cost',\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: Incentive failure patterns — population stampedes, regulator suppressing bootstrap\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P5_ProfitabilityIsRelative: Principle = {\n id: 'P5',\n name: 'Profitability Is Relative, 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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'cost',\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 (staking, prize pools, etc.), 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 parameterType: 'fee', scope: { tags: ['entry'] },\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 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 parameterType: 'reward',\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_ProfitabilityIsRelative,\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, minimum interval), 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 parameterType: 'cost',\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_EntryWeightingUsesInversePopulation: Principle = {\n id: 'P10',\n name: 'Entry Weighting Uses Inverse Population',\n category: 'population',\n description:\n 'New entrants 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 entry 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 parameterType: 'yield',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'reward',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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_EntryWeightingUsesInversePopulation,\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 + production + activities) each ' +\n 'creating currency causes uncontrolled inflation. One clear primary faucet ' +\n 'makes the economy predictable and auditable.',\n check(metrics, thresholds): PrincipleResult {\n for (const curr of metrics.currencies) {\n const netFlow = metrics.netFlowByCurrency[curr] ?? 0;\n const faucetVolume = metrics.faucetVolumeByCurrency[curr] ?? 0;\n const sinkVolume = metrics.sinkVolumeByCurrency[curr] ?? 0;\n\n if (netFlow > thresholds.netFlowWarnThreshold) {\n return {\n violated: true,\n severity: 5,\n evidence: { currency: curr, netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'increase',\n scope: { currency: curr },\n magnitude: 0.15,\n reasoning:\n `[${curr}] Net flow +${netFlow.toFixed(1)}/tick. Inflationary. ` +\n 'Increase production 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: { currency: curr, netFlow, faucetVolume, sinkVolume },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'decrease',\n scope: { currency: curr },\n magnitude: 0.15,\n reasoning:\n `[${curr}] Net flow ${netFlow.toFixed(1)}/tick. Deflationary. ` +\n 'Decrease production cost to ease sink pressure.',\n },\n confidence: 0.80,\n estimatedLag: 8,\n };\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 'Pool math: winRate × multiplier > (1 - operatorShare) 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 { populationByRole } = metrics;\n\n const roleEntries = Object.entries(populationByRole).sort((a, b) => b[1] - a[1]);\n const dominantCount = roleEntries[0]?.[1] ?? 0;\n\n for (const [poolName, currencyAmounts] of Object.entries(metrics.poolSizesByCurrency)) {\n for (const curr of metrics.currencies) {\n const poolSize = currencyAmounts[curr] ?? 0;\n\n if (dominantCount > 5 && poolSize < 50) {\n const { poolWinRate, poolOperatorShare } = thresholds;\n const maxSustainableMultiplier = (1 - poolOperatorShare) / poolWinRate;\n\n return {\n violated: true,\n severity: 7,\n evidence: { currency: curr, pool: poolName, poolSize, participants: dominantCount, maxSustainableMultiplier },\n suggestedAction: {\n parameterType: 'reward',\n direction: 'decrease',\n scope: { currency: curr },\n magnitude: 0.15,\n reasoning:\n `[${curr}] ${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\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 extraction as \"currency injected\" is misleading. ' +\n 'Currency enters through faucet mechanisms (entering, rewards). ' +\n 'Fake metrics break every downstream decision.',\n check(metrics, _thresholds): PrincipleResult {\n for (const curr of metrics.currencies) {\n const faucetVolume = metrics.faucetVolumeByCurrency[curr] ?? 0;\n const netFlow = metrics.netFlowByCurrency[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n\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: { currency: curr, faucetVolume, netFlow, supplyGrowthRate },\n suggestedAction: {\n parameterType: 'yield',\n direction: 'decrease',\n scope: { currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] Supply growing at ${(supplyGrowthRate * 100).toFixed(1)}%/tick. ` +\n 'Verify currency injection tracking. Resources should not create currency directly.',\n },\n confidence: 0.55,\n estimatedLag: 5,\n };\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 'A pool at 42% of total supply means 42% of the economy is frozen. ' +\n 'Cap at 5%, decay at 2%/tick.',\n check(metrics, thresholds): PrincipleResult {\n const { poolCapPercent } = thresholds;\n\n for (const [pool, currencyAmounts] of Object.entries(metrics.poolSizesByCurrency)) {\n for (const curr of metrics.currencies) {\n const size = currencyAmounts[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n const shareOfSupply = size / Math.max(1, totalSupply);\n\n if (shareOfSupply > poolCapPercent * 2) {\n return {\n violated: true,\n severity: 6,\n evidence: { currency: curr, pool, size, shareOfSupply, cap: poolCapPercent },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'decrease',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] ${pool} pool at ${(shareOfSupply * 100).toFixed(1)}% of supply ` +\n `(cap: ${(poolCapPercent * 100).toFixed(0)}%). Currency frozen. ` +\n 'Lower fees to encourage circulation over accumulation.',\n },\n confidence: 0.85,\n estimatedLag: 5,\n };\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 for (const [poolName, currencyAmounts] of Object.entries(metrics.poolSizesByCurrency)) {\n for (const curr of metrics.currencies) {\n const poolSize = currencyAmounts[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n const stakedEstimate = totalSupply * 0.15;\n\n if (poolSize < 10 && stakedEstimate > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: { currency: curr, pool: poolName, poolSize, estimatedStaked: stakedEstimate },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.05,\n reasoning:\n `[${curr}] ${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\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 { supplyByResource } = metrics;\n const totalResources = Object.values(supplyByResource).reduce((s, v) => s + v, 0);\n\n for (const curr of metrics.currencies) {\n const velocity = metrics.velocityByCurrency[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n\n if (velocity < 3 && totalSupply > 100 && totalResources > 20) {\n return {\n violated: true,\n severity: 4,\n evidence: { currency: curr, velocity, totalSupply, totalResources },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'decrease',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.20,\n reasoning:\n `[${curr}] 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\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 for (const curr of metrics.currencies) {\n const currPrices = metrics.pricesByCurrency[curr] ?? {};\n const velocity = metrics.velocityByCurrency[curr] ?? 0;\n const totalSupply = metrics.totalSupplyByCurrency[curr] ?? 0;\n\n const priceValues = Object.values(currPrices).filter(p => p > 0);\n if (priceValues.length < 3) continue;\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 if (coeffOfVariation < 0.25 && velocity > 5 && totalSupply > 100) {\n return {\n violated: true,\n severity: 3,\n evidence: {\n currency: curr,\n coeffOfVariation,\n velocity,\n numResources: priceValues.length,\n meanPrice: mean,\n },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'increase',\n scope: { currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] 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\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 parameterType: 'fee', scope: { tags: ['entry'] },\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 agents exist\n const hasAgents = metrics.totalAgents > 0;\n for (const [resource, supply] of Object.entries(metrics.supplyByResource)) {\n if (supply === 0 && hasAgents) {\n return {\n violated: true,\n severity: 8,\n evidence: { tick: metrics.tick, resource, supply, totalAgents: metrics.totalAgents },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'decrease',\n magnitude: 0.50,\n reasoning:\n `Bootstrap failure: ${resource} supply is 0 at tick ${metrics.tick} with ${metrics.totalAgents} agents. ` +\n 'Drastically reduce production cost to allow immediate output.',\n },\n confidence: 0.90,\n estimatedLag: 2,\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 parameterType: 'reward',\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 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 parameterType: 'yield',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 produce 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 parameterType: 'cost',\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'yield',\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['entry'] },\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 parameterType: 'cost',\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 participants 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 parameterType: 'reward',\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_BottleneckDetection: Principle = {\n id: 'P29',\n name: 'Bottleneck Detection',\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 parameterType: 'cost',\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 parameterType: 'cost',\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_DynamicBottleneckRotation: Principle = {\n id: 'P30',\n name: 'Dynamic Bottleneck Rotation',\n category: 'market_dynamics',\n description:\n 'Participant progression shifts the demand curve. A static pinch point that ' +\n 'works early will be cleared later. The pinch point must move ' +\n 'with participant 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 parameterType: 'cost',\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 participant 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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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_BottleneckDetection,\n P30_DynamicBottleneckRotation,\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 for (const curr of metrics.currencies) {\n const meanMedianDivergence = metrics.meanMedianDivergenceByCurrency[curr] ?? 0;\n const giniCoefficient = metrics.giniCoefficientByCurrency[curr] ?? 0;\n const meanBalance = metrics.meanBalanceByCurrency[curr] ?? 0;\n const medianBalance = metrics.medianBalanceByCurrency[curr] ?? 0;\n\n if (meanMedianDivergence > thresholds.meanMedianDivergenceMax) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n currency: curr,\n meanMedianDivergence,\n giniCoefficient,\n meanBalance,\n medianBalance,\n },\n suggestedAction: {\n parameterType: 'fee',\n scope: { tags: ['transaction'], currency: curr },\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `[${curr}] 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 transaction fees to redistribute wealth.',\n },\n confidence: 0.85,\n estimatedLag: 15,\n };\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 parameterType: 'cost',\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 parameterType: 'cost',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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 parameterType: 'fee', scope: { tags: ['entry'] },\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 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 'Replacement/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 parameterType: 'yield',\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 parameterType: 'yield',\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 parameterType: 'fee', scope: { tags: ['transaction'] },\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: Participant 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: 'participant_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 for (const curr of metrics.currencies) {\n const giniCoefficient = metrics.giniCoefficientByCurrency[curr] ?? 0;\n\n if (giniCoefficient < 0.10) {\n return {\n violated: true,\n severity: 3,\n evidence: { currency: curr, giniCoefficient },\n suggestedAction: {\n parameterType: 'reward',\n direction: 'increase',\n scope: { currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] 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: { currency: curr, giniCoefficient },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.20,\n reasoning:\n `[${curr}] 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: { currency: curr, giniCoefficient },\n suggestedAction: {\n parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'], currency: curr },\n magnitude: 0.10,\n reasoning:\n `[${curr}] 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\n return { violated: false };\n },\n};\n\nexport const P36_MechanicFrictionDetector: Principle = {\n id: 'P36',\n name: 'Mechanism Friction Detector',\n category: 'participant_experience',\n description:\n 'Deterministic + probabilistic systems → expectation mismatch. ' +\n 'When production is guaranteed but competition is random, participants feel betrayed by ' +\n 'the random side. Mix mechanisms 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 mechanism mismatch rather than economic problems\n // (Activity exists but participants leave anyway = not economic, likely mechanism 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 parameterType: 'reward',\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 mechanism friction (deterministic vs random systems). ' +\n 'Increase rewards to compensate for perceived unfairness. ' +\n 'ADVISORY: Review if mixing guaranteed and probabilistic mechanisms.',\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: 'Late Entrant Problem',\n category: 'participant_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 = late entrant 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 parameterType: 'cost',\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: 'participant_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 parameterType: 'fee',\n direction: 'decrease',\n scope: { tags: ['entry'] },\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: 'participant_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 parameterType: 'fee',\n direction: 'increase',\n scope: { tags: ['transaction'] },\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 PARTICIPANT_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 (Number.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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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 (Number.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 parameterType: 'reward',\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 parameterType: 'reward',\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 (Number.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 parameterType: 'fee',\n scope: { tags: ['transaction'] },\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, P56: Operations Principles (from Naavik research)\n\nimport type { Principle, PrincipleResult } from '../types.js';\n\nexport const P51_CyclicalEngagement: Principle = {\n id: 'P51',\n name: 'Cyclical Engagement Pattern',\n category: 'operations',\n description:\n 'Each activity peak should be >=95% of the previous peak. ' +\n 'If peaks are shrinking (cyclical engagement becoming flat), activity fatigue is setting in. ' +\n 'If valleys are deepening, the off-activity economy is failing to sustain engagement.',\n check(metrics, thresholds): PrincipleResult {\n const { cyclicalPeaks, cyclicalValleys } = metrics;\n if (cyclicalPeaks.length < 2) return { violated: false };\n\n const lastPeak = cyclicalPeaks[cyclicalPeaks.length - 1] ?? 0;\n const prevPeak = cyclicalPeaks[cyclicalPeaks.length - 2] ?? 0;\n\n if (prevPeak > 0 && lastPeak / prevPeak < thresholds.cyclicalPeakDecay) {\n return {\n violated: true,\n severity: 5,\n evidence: {\n lastPeak,\n prevPeak,\n ratio: lastPeak / prevPeak,\n threshold: thresholds.cyclicalPeakDecay,\n },\n suggestedAction: {\n parameterType: 'reward',\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.cyclicalPeakDecay * 100).toFixed(0)}%). Activity fatigue detected. ` +\n 'Boost activity rewards to restore peak engagement.',\n },\n confidence: 0.75,\n estimatedLag: 30,\n };\n }\n\n if (cyclicalValleys.length >= 2) {\n const lastValley = cyclicalValleys[cyclicalValleys.length - 1] ?? 0;\n const prevValley = cyclicalValleys[cyclicalValleys.length - 2] ?? 0;\n if (prevValley > 0 && lastValley / prevValley < thresholds.cyclicalValleyDecay) {\n return {\n violated: true,\n severity: 4,\n evidence: { lastValley, prevValley, ratio: lastValley / prevValley },\n suggestedAction: {\n parameterType: 'cost',\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n 'Between-activity engagement declining (deepening valleys). ' +\n 'Base economy not sustaining participants between activities. ' +\n 'Lower production costs to improve off-activity 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: 'operations',\n description:\n 'Participants who never owned premium assets do not value them. ' +\n 'Free trial activities that let participants experience premium assets drive conversions ' +\n 'because ownership creates perceived value (endowment effect).',\n check(metrics, _thresholds): PrincipleResult {\n const { avgSatisfaction, churnRate } = metrics;\n\n // Proxy: if activity completion is high but satisfaction is still low,\n // activities are not creating the endowment effect (participants complete but don't value the rewards)\n const { eventCompletionRate } = metrics;\n if (Number.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 parameterType: 'reward',\n direction: 'increase',\n magnitude: 0.15,\n reasoning:\n `${(eventCompletionRate * 100).toFixed(0)}% activity completion but satisfaction only ${avgSatisfaction.toFixed(0)}. ` +\n 'Activities 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: 'Activity Completion Rate Sweet Spot',\n category: 'operations',\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 (Number.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 parameterType: 'cost',\n direction: 'decrease',\n magnitude: 0.15,\n reasoning:\n `Activity 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 parameterType: 'fee', scope: { tags: ['entry'] },\n direction: 'increase',\n magnitude: 0.05,\n reasoning:\n `Activity 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_OperationalCadence: Principle = {\n id: 'P54',\n name: 'Operational Cadence',\n category: 'operations',\n description:\n '>50% of activities that are re-wrapped existing supply → stagnation. ' +\n 'The cadence must include genuinely new supply at regular intervals. ' +\n 'This is an advisory principle — AgentE can flag but cannot fix supply.',\n check(metrics, _thresholds): PrincipleResult {\n // Proxy: declining engagement velocity over time = stagnation\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 parameterType: 'reward',\n direction: 'increase',\n magnitude: 0.10,\n reasoning:\n 'Low velocity and satisfaction after long runtime. ' +\n 'Possible supply stagnation. Increase rewards as bridge while ' +\n 'new supply 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_SupplyShockAbsorption: Principle = {\n id: 'P56',\n name: 'Supply Shock Absorption',\n category: 'operations',\n description:\n 'Every new-item injection shatters existing price equilibria — arbitrage spikes ' +\n 'as participants re-price. Build stabilization windows for price discovery before ' +\n 'measuring post-injection economic health.',\n check(metrics, thresholds): PrincipleResult {\n const { contentDropAge, arbitrageIndex } = metrics;\n\n // Only fires during the stabilization window after a supply injection\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 parameterType: 'fee', scope: { tags: ['transaction'] },\n direction: 'decrease',\n magnitude: 0.10,\n reasoning:\n `Supply injection ${contentDropAge} ticks ago — arbitrage at ${arbitrageIndex.toFixed(2)} ` +\n `exceeds post-injection 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 OPERATIONS_PRINCIPLES: Principle[] = [\n P51_CyclicalEngagement,\n P52_EndowmentEffect,\n P53_EventCompletionRate,\n P54_OperationalCadence,\n P56_SupplyShockAbsorption,\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 { PARTICIPANT_EXPERIENCE_PRINCIPLES } from './participant-experience.js';\nimport { OPEN_ECONOMY_PRINCIPLES } from './open-economy.js';\nimport { OPERATIONS_PRINCIPLES } from './operations.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 './participant-experience.js';\nexport * from './open-economy.js';\nexport * from './operations.js';\n\n/** All 60 built-in principles in priority order (supply chain → operations) */\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 ...PARTICIPANT_EXPERIENCE_PRINCIPLES, // P33, P36, P37, P45, P50\n ...OPEN_ECONOMY_PRINCIPLES, // P34, P47-P48\n ...OPERATIONS_PRINCIPLES, // P51-P54, P56\n];\n","// Stage 3: Simulator — forward Monte Carlo projection before any action is applied\n// Monte Carlo forward projection — simulates before any action is applied\n\nimport type {\n EconomyMetrics,\n SuggestedAction,\n SimulationResult,\n SimulationOutcome,\n SimulationConfig,\n Thresholds,\n} from './types.js';\nimport { emptyMetrics } from './types.js';\nimport { Diagnoser } from './Diagnoser.js';\nimport { ALL_PRINCIPLES } from './principles/index.js';\nimport type { ParameterRegistry, FlowImpact } from './ParameterRegistry.js';\n\nconst DEFAULT_SIM_CONFIG: Required<SimulationConfig> = {\n sinkMultiplier: 0.20,\n faucetMultiplier: 0.15,\n frictionMultiplier: 0.10,\n frictionVelocityScale: 10,\n redistributionMultiplier: 0.30,\n neutralMultiplier: 0.05,\n minIterations: 100,\n maxProjectionTicks: 20,\n};\n\nexport class Simulator {\n private diagnoser = new Diagnoser(ALL_PRINCIPLES);\n private registry: ParameterRegistry | undefined;\n private simConfig: Required<SimulationConfig>;\n\n constructor(registry?: ParameterRegistry, simConfig?: SimulationConfig) {\n this.registry = registry;\n this.simConfig = { ...DEFAULT_SIM_CONFIG, ...simConfig };\n }\n // Cache beforeViolations for the *current* tick only.\n private cachedViolationsTick: number = -1;\n private cachedViolations: Set<string> = new Set();\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 if (this.cachedViolationsTick !== tick) {\n this.cachedViolations = new Set(\n this.diagnoser.diagnose(currentMetrics, thresholds).map(d => d.principle.id),\n );\n this.cachedViolationsTick = tick;\n }\n const beforeViolations = this.cachedViolations;\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 const multiplier = this.actionMultiplier(action);\n const noise = () => 1 + (Math.random() - 0.5) * 0.1;\n const currencies = metrics.currencies;\n const targetCurrency = action.scope?.currency; // may be undefined (= all)\n\n // Per-currency state\n const supplies: Record<string, number> = { ...metrics.totalSupplyByCurrency };\n const netFlows: Record<string, number> = { ...metrics.netFlowByCurrency };\n const ginis: Record<string, number> = { ...metrics.giniCoefficientByCurrency };\n const velocities: Record<string, number> = { ...metrics.velocityByCurrency };\n let satisfaction = metrics.avgSatisfaction;\n\n for (let t = 0; t < ticks; t++) {\n for (const curr of currencies) {\n // Only apply action effect to the targeted currency (or all if unscoped)\n const isTarget = !targetCurrency || targetCurrency === curr;\n const effectOnFlow = isTarget\n ? this.flowEffect(action, metrics, curr) * multiplier * noise()\n : 0;\n\n netFlows[curr] = (netFlows[curr] ?? 0) * 0.9 + effectOnFlow * 0.1;\n supplies[curr] = Math.max(0, (supplies[curr] ?? 0) + (netFlows[curr] ?? 0) * noise());\n ginis[curr] = (ginis[curr] ?? 0) * 0.99 + 0.35 * 0.01 * noise();\n velocities[curr] = ((supplies[curr] ?? 0) / Math.max(1, metrics.totalAgents)) * 0.01 * noise();\n }\n\n const avgNetFlow = currencies.length > 0\n ? Object.values(netFlows).reduce((s, v) => s + v, 0) / currencies.length\n : 0;\n const satDelta = avgNetFlow > 0 && avgNetFlow < 20 ? 0.5 : avgNetFlow < 0 ? -1 : 0;\n satisfaction = Math.min(100, Math.max(0, satisfaction + satDelta * noise()));\n }\n\n // Build projected metrics\n const totalSupply = Object.values(supplies).reduce((s, v) => s + v, 0);\n const projected: EconomyMetrics = {\n ...metrics,\n tick: metrics.tick + ticks,\n currencies,\n totalSupplyByCurrency: supplies,\n netFlowByCurrency: netFlows,\n velocityByCurrency: velocities,\n giniCoefficientByCurrency: ginis,\n totalSupply,\n netFlow: Object.values(netFlows).reduce((s, v) => s + v, 0),\n velocity: totalSupply > 0 && currencies.length > 0\n ? Object.values(velocities).reduce((s, v) => s + v, 0) / currencies.length\n : 0,\n giniCoefficient: currencies.length > 0\n ? Object.values(ginis).reduce((s, v) => s + v, 0) / currencies.length\n : 0,\n avgSatisfaction: satisfaction,\n inflationRate: metrics.totalSupply > 0 ? (totalSupply - 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, currency: string): number {\n const { direction } = action;\n const sign = direction === 'increase' ? -1 : 1;\n\n const roleEntries = Object.entries(metrics.populationByRole).sort((a, b) => b[1] - a[1]);\n const dominantRoleCount = roleEntries[0]?.[1] ?? 0;\n\n // Resolve flow impact directly from registry by type+scope (independent of Planner)\n let impact: FlowImpact | undefined;\n if (this.registry) {\n const resolved = this.registry.resolve(action.parameterType, action.scope);\n if (resolved) {\n impact = resolved.flowImpact;\n }\n }\n if (!impact) {\n impact = this.inferFlowImpact(action.parameterType);\n }\n\n const cfg = this.simConfig;\n switch (impact) {\n case 'sink':\n return sign * (metrics.netFlowByCurrency[currency] ?? 0) * cfg.sinkMultiplier;\n case 'faucet':\n return -sign * dominantRoleCount * cfg.redistributionMultiplier;\n case 'neutral':\n return sign * dominantRoleCount * cfg.neutralMultiplier;\n case 'mixed':\n return sign * (metrics.faucetVolumeByCurrency[currency] ?? 0) * cfg.faucetMultiplier;\n case 'friction':\n return sign * (metrics.netFlowByCurrency[currency] ?? 0) * cfg.frictionMultiplier;\n case 'redistribution':\n return sign * dominantRoleCount * cfg.neutralMultiplier;\n default:\n return sign * (metrics.netFlowByCurrency[currency] ?? 0) * cfg.frictionMultiplier;\n }\n }\n\n /** Infer flow impact from parameter type when registry is unavailable */\n private inferFlowImpact(parameterType: string): FlowImpact {\n switch (parameterType) {\n case 'cost':\n case 'fee':\n case 'penalty':\n return 'sink';\n case 'reward':\n return 'faucet';\n case 'yield':\n return 'mixed';\n case 'cap':\n case 'multiplier':\n return 'neutral';\n default:\n return 'mixed';\n }\n }\n\n private checkImprovement(\n before: EconomyMetrics,\n after: EconomyMetrics,\n _action: SuggestedAction,\n ): boolean {\n const satisfactionImproved = after.avgSatisfaction >= before.avgSatisfaction - 2;\n\n // Check net flow improvement across all currencies\n const flowMoreBalanced = before.currencies.every(curr => {\n const afterFlow = Math.abs(after.netFlowByCurrency[curr] ?? 0);\n const beforeFlow = Math.abs(before.netFlowByCurrency[curr] ?? 0);\n return afterFlow <= beforeFlow * 1.2 || afterFlow < 1;\n });\n\n const notWorseGini = before.currencies.every(curr => {\n const afterGini = after.giniCoefficientByCurrency[curr] ?? 0;\n const beforeGini = before.giniCoefficientByCurrency[curr] ?? 0;\n return afterGini <= beforeGini + 0.05;\n });\n\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\n const avg = (key: keyof EconomyMetrics): number => {\n const vals = outcomes.map(o => o[key] as number).filter(v => typeof v === 'number' && !Number.isNaN(v));\n return vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n };\n\n const avgRecord = (key: keyof EconomyMetrics): Record<string, number> => {\n const allKeys = new Set<string>();\n for (const o of outcomes) {\n const rec = o[key];\n if (rec && typeof rec === 'object' && !Array.isArray(rec)) {\n Object.keys(rec as Record<string, unknown>).forEach(k => allKeys.add(k));\n }\n }\n const result: Record<string, number> = {};\n for (const k of allKeys) {\n const vals = outcomes\n .map(o => (o[key] as Record<string, number>)?.[k])\n .filter((v): v is number => typeof v === 'number' && !Number.isNaN(v));\n result[k] = vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n }\n return result;\n };\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 totalSupplyByCurrency: avgRecord('totalSupplyByCurrency'),\n netFlowByCurrency: avgRecord('netFlowByCurrency'),\n velocityByCurrency: avgRecord('velocityByCurrency'),\n giniCoefficientByCurrency: avgRecord('giniCoefficientByCurrency'),\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';\nimport type { ParameterRegistry, ParameterScope } from './ParameterRegistry.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 typeCooldowns = new Map<string, number>(); // type+scope key → 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 * - no matching parameter in registry\n */\n plan(\n diagnosis: Diagnosis,\n metrics: EconomyMetrics,\n simulationResult: SimulationResult,\n currentParams: Record<string, number>,\n thresholds: Thresholds,\n registry?: ParameterRegistry,\n ): ActionPlan | null {\n const action = diagnosis.violation.suggestedAction;\n\n // Type-level cooldown: prevent re-planning the same parameterType+scope before registry resolution\n const typeKey = this.typeCooldownKey(action.parameterType, action.scope);\n if (this.isTypeCooldown(typeKey, metrics.tick, thresholds.cooldownTicks)) return null;\n\n // Resolve parameterType + scope to a concrete key via registry\n let param: string;\n let resolvedBaseline: number | undefined;\n let scope: ParameterScope | undefined;\n\n if (registry) {\n const resolved = registry.resolve(action.parameterType, action.scope);\n if (!resolved) return null; // no matching parameter registered\n param = resolved.key;\n resolvedBaseline = resolved.currentValue;\n scope = resolved.scope as ParameterScope | undefined;\n action.resolvedParameter = param;\n } else {\n // Fallback: use parameterType as param name directly\n param = action.resolvedParameter ?? action.parameterType;\n scope = action.scope as ParameterScope | undefined;\n }\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 // Prefer registry's currentValue, then currentParams, then absoluteValue, then 1.0\n const currentValue = resolvedBaseline ?? currentParams[param] ?? action.absoluteValue ?? 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 ...(scope !== undefined ? { scope } : {}),\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),\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 // Also record type-level cooldown from the diagnosis action\n const action = plan.diagnosis.violation.suggestedAction;\n const typeKey = this.typeCooldownKey(action.parameterType, action.scope);\n this.typeCooldowns.set(typeKey, tick);\n this.activePlanCount++;\n }\n\n recordRolledBack(_plan: ActionPlan): void {\n this.activePlanCount = Math.max(0, this.activePlanCount - 1);\n }\n\n recordSettled(_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 this.typeCooldowns.clear();\n }\n\n /** V1.5.2: Reset active plan count (e.g., on system restart) */\n resetActivePlans(): void {\n this.activePlanCount = 0;\n }\n\n /** V1.5.2: Current active plan count (for diagnostics) */\n getActivePlanCount(): number {\n return this.activePlanCount;\n }\n\n private typeCooldownKey(type: string, scope?: Partial<ParameterScope>): string {\n const parts = [type];\n if (scope?.system) parts.push(`sys:${scope.system}`);\n if (scope?.currency) parts.push(`cur:${scope.currency}`);\n if (scope?.tags?.length) parts.push(`tags:${scope.tags.sort().join(',')}`);\n return parts.join('|');\n }\n\n private isTypeCooldown(typeKey: string, currentTick: number, cooldownTicks: number): boolean {\n const lastApplied = this.typeCooldowns.get(typeKey);\n if (lastApplied === undefined) return false;\n return currentTick - lastApplied < cooldownTicks;\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 private maxActiveTicks: number;\n\n constructor(settlementWindowTicks = 200) {\n this.maxActiveTicks = settlementWindowTicks;\n }\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, plan.scope);\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 * Returns { rolledBack, settled } — plans that were undone and plans that passed their window.\n */\n async checkRollbacks(\n metrics: EconomyMetrics,\n adapter: EconomyAdapter,\n ): Promise<{ rolledBack: ActionPlan[]; settled: ActionPlan[] }> {\n const rolledBack: ActionPlan[] = [];\n const settled: 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 // Hard TTL: evict plans that have been active for too long\n if (plan.appliedAt !== undefined && metrics.tick - plan.appliedAt > this.maxActiveTicks) {\n settled.push(plan);\n continue;\n }\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\n // Fail-safe: if metric is unresolvable, trigger rollback\n if (Number.isNaN(metricValue)) {\n console.warn(\n `[AgentE] Rollback check: metric path '${rc.metric}' resolved to NaN for plan '${plan.id}'. Triggering rollback as fail-safe.`\n );\n await adapter.setParam(plan.parameter, originalValue, plan.scope);\n rolledBack.push(plan);\n continue;\n }\n\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, plan.scope);\n rolledBack.push(plan);\n } else {\n // Plan has passed its check window — consider it settled\n const settledTick = rc.checkAfterTick + 10;\n if (metrics.tick > settledTick) {\n settled.push(plan);\n } else {\n remaining.push(active);\n }\n }\n }\n\n this.activePlans = remaining;\n return { rolledBack, settled };\n }\n\n private getMetricValue(metrics: EconomyMetrics, metricPath: string): number {\n // Support dotted paths like 'poolSizes.primary' 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.push(entry); // oldest first, newest at end\n if (this.entries.length > this.maxEntries * 1.5) {\n this.entries = this.entries.slice(-this.maxEntries);\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.push(entry);\n if (this.entries.length > this.maxEntries * 1.5) {\n this.entries = this.entries.slice(-this.maxEntries);\n }\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 getById(id: string): DecisionEntry | undefined {\n return this.entries.find(e => e.id === id);\n }\n\n updateResult(id: string, newResult: DecisionResult, reasoning?: string): boolean {\n const entry = this.entries.find(e => e.id === id);\n if (!entry) return false;\n entry.result = newResult;\n if (reasoning !== undefined) entry.reasoning = reasoning;\n return true;\n }\n\n latest(n = 30): DecisionEntry[] {\n return this.entries.slice(-n).reverse();\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.resolvedParameter ?? action.parameterType,\n ...(action.scope !== undefined ? { scope: action.scope } : {}),\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\nfunction getNestedValue(obj: Record<string, unknown>, path: string): number {\n const parts = path.split('.');\n let val: unknown = obj;\n for (const part of parts) {\n if (val !== null && typeof val === 'object') {\n val = (val as Record<string, unknown>)[part];\n } else {\n return NaN;\n }\n }\n return typeof val === 'number' ? val : NaN;\n}\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 points = filtered.map(m => ({\n tick: m.tick,\n value: getNestedValue(m as unknown as Record<string, unknown>, q.metric as string),\n }));\n\n return { metric: q.metric as string, resolution, points };\n }\n\n /** Summarized recent history for dashboard charts */\n recentHistory(count = 100): Array<{\n tick: number;\n health: number;\n giniCoefficient: number;\n totalSupply: number;\n netFlow: number;\n velocity: number;\n inflationRate: number;\n avgSatisfaction: number;\n churnRate: number;\n totalAgents: number;\n priceIndex: number;\n }> {\n const all = this.fine.toArray();\n const slice = all.slice(-count);\n return slice.map(m => {\n // Compute health inline (same formula as AgentE.getHealth())\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 health = Math.max(0, Math.min(100, health));\n\n return {\n tick: m.tick,\n health,\n giniCoefficient: m.giniCoefficient,\n totalSupply: m.totalSupply,\n netFlow: m.netFlow,\n velocity: m.velocity,\n inflationRate: m.inflationRate,\n avgSatisfaction: m.avgSatisfaction,\n churnRate: m.churnRate,\n totalAgents: m.totalAgents,\n priceIndex: m.priceIndex,\n };\n });\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 => !Number.isNaN(v));\n return vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n };\n\n const avgRecord = (key: keyof EconomyMetrics): Record<string, number> => {\n const allKeys = new Set<string>();\n for (const s of snapshots) {\n const rec = s[key];\n if (rec && typeof rec === 'object' && !Array.isArray(rec)) {\n Object.keys(rec as Record<string, unknown>).forEach(k => allKeys.add(k));\n }\n }\n const result: Record<string, number> = {};\n for (const k of allKeys) {\n const vals = snapshots\n .map(s => (s[key] as Record<string, number>)?.[k])\n .filter((v): v is number => typeof v === 'number' && !Number.isNaN(v));\n result[k] = vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;\n }\n return result;\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 // Per-currency averages\n totalSupplyByCurrency: avgRecord('totalSupplyByCurrency'),\n netFlowByCurrency: avgRecord('netFlowByCurrency'),\n velocityByCurrency: avgRecord('velocityByCurrency'),\n inflationRateByCurrency: avgRecord('inflationRateByCurrency'),\n faucetVolumeByCurrency: avgRecord('faucetVolumeByCurrency'),\n sinkVolumeByCurrency: avgRecord('sinkVolumeByCurrency'),\n tapSinkRatioByCurrency: avgRecord('tapSinkRatioByCurrency'),\n anchorRatioDriftByCurrency: avgRecord('anchorRatioDriftByCurrency'),\n giniCoefficientByCurrency: avgRecord('giniCoefficientByCurrency'),\n medianBalanceByCurrency: avgRecord('medianBalanceByCurrency'),\n meanBalanceByCurrency: avgRecord('meanBalanceByCurrency'),\n top10PctShareByCurrency: avgRecord('top10PctShareByCurrency'),\n meanMedianDivergenceByCurrency: avgRecord('meanMedianDivergenceByCurrency'),\n };\n }\n}\n","// Behavioral persona auto-classification\n// Classifies agents into 9 universal archetypes from observable signals\n// All thresholds are RELATIVE (percentile-based) — no magic numbers\n\nimport type {\n EconomyState,\n EconomicEvent,\n PersonaType,\n} from './types.js';\n\n// ── Configuration ──\n\nexport interface PersonaConfig {\n /** Top X% by holdings = Whale. Default: 0.05 (5%) */\n whalePercentile: number;\n\n /** Top X% by tx frequency = Active Trader. Default: 0.20 (20%) */\n activeTraderPercentile: number;\n\n /** Ticks to consider an agent \"new.\" Default: 10 */\n newEntrantWindow: number;\n\n /** Ticks with zero activity = Dormant. Default: 20 */\n dormantWindow: number;\n\n /** Activity drop threshold for At-Risk. Default: 0.5 (50% drop) */\n atRiskDropThreshold: number;\n\n /** Min distinct systems for Power User. Default: 3 */\n powerUserMinSystems: number;\n\n /** Rolling history window size (ticks). Default: 50 */\n historyWindow: number;\n}\n\nconst DEFAULT_PERSONA_CONFIG: PersonaConfig = {\n whalePercentile: 0.05,\n activeTraderPercentile: 0.20,\n newEntrantWindow: 10,\n dormantWindow: 20,\n atRiskDropThreshold: 0.5,\n powerUserMinSystems: 3,\n historyWindow: 50,\n};\n\n// ── Per-agent rolling signals ──\n\ninterface AgentSnapshot {\n totalHoldings: number;\n txCount: number;\n txVolume: number;\n systems: Set<string>;\n}\n\ninterface AgentRecord {\n firstSeen: number;\n lastActive: number;\n snapshots: AgentSnapshot[];\n previousTxRate: number; // tx frequency in prior window (for At-Risk detection)\n}\n\n// ── Classifier ──\n\nexport class PersonaTracker {\n private agents = new Map<string, AgentRecord>();\n private config: PersonaConfig;\n\n constructor(config?: Partial<PersonaConfig>) {\n this.config = { ...DEFAULT_PERSONA_CONFIG, ...config };\n }\n\n /**\n * Ingest a state snapshot + events and update per-agent signals.\n * Call this once per tick BEFORE getDistribution().\n */\n update(state: EconomyState, events?: EconomicEvent[]): void {\n const tick = state.tick;\n const txByAgent = new Map<string, { count: number; volume: number; systems: Set<string> }>();\n\n // Tally events per agent\n if (events) {\n for (const e of events) {\n const agents = [e.actor];\n if (e.from) agents.push(e.from);\n if (e.to) agents.push(e.to);\n\n for (const id of agents) {\n if (!id) continue;\n const entry = txByAgent.get(id) ?? { count: 0, volume: 0, systems: new Set() };\n entry.count++;\n entry.volume += e.amount ?? 0;\n if (e.system) entry.systems.add(e.system);\n txByAgent.set(id, entry);\n }\n }\n }\n\n // Update each agent's record\n for (const [agentId, balances] of Object.entries(state.agentBalances)) {\n const totalHoldings = Object.values(balances).reduce((s, v) => s + v, 0);\n const tx = txByAgent.get(agentId);\n\n const record = this.agents.get(agentId) ?? {\n firstSeen: tick,\n lastActive: tick,\n snapshots: [],\n previousTxRate: 0,\n };\n\n const snapshot: AgentSnapshot = {\n totalHoldings,\n txCount: tx?.count ?? 0,\n txVolume: tx?.volume ?? 0,\n systems: tx?.systems ?? new Set(),\n };\n\n record.snapshots.push(snapshot);\n\n // Trim to history window\n if (record.snapshots.length > this.config.historyWindow) {\n // Before trimming, save the old tx rate for At-Risk comparison\n const oldHalf = record.snapshots.slice(0, Math.floor(record.snapshots.length / 2));\n record.previousTxRate = oldHalf.reduce((s, sn) => s + sn.txCount, 0) / Math.max(1, oldHalf.length);\n record.snapshots = record.snapshots.slice(-this.config.historyWindow);\n }\n\n if ((tx?.count ?? 0) > 0) {\n record.lastActive = tick;\n }\n\n this.agents.set(agentId, record);\n }\n\n // Prune agents gone from state for >2× dormant window\n const pruneThreshold = this.config.dormantWindow * 2;\n if (tick % this.config.dormantWindow === 0) {\n for (const [id, rec] of this.agents) {\n if (tick - rec.lastActive > pruneThreshold && !(id in state.agentBalances)) {\n this.agents.delete(id);\n }\n }\n }\n }\n\n /**\n * Classify all tracked agents and return the population distribution.\n * Returns { Whale: 0.05, ActiveTrader: 0.18, Passive: 0.42, ... }\n */\n getDistribution(): Record<string, number> {\n const agentIds = [...this.agents.keys()];\n const total = agentIds.length;\n if (total === 0) return {};\n\n // ── Compute population-wide statistics ──\n\n // Holdings for percentile calculation\n const holdings = agentIds.map(id => {\n const rec = this.agents.get(id)!;\n const latest = rec.snapshots[rec.snapshots.length - 1];\n return latest?.totalHoldings ?? 0;\n }).sort((a, b) => a - b);\n\n const whaleThreshold = percentile(holdings, 1 - this.config.whalePercentile);\n\n // Tx frequency for percentile calculation\n const txRatesUnsorted = agentIds.map(id => {\n const rec = this.agents.get(id)!;\n return rec.snapshots.reduce((s, sn) => s + sn.txCount, 0) / Math.max(1, rec.snapshots.length);\n });\n const txRates = [...txRatesUnsorted].sort((a, b) => a - b);\n\n const activeTraderThreshold = percentile(txRates, 1 - this.config.activeTraderPercentile);\n const medianTxRate = percentile(txRates, 0.5);\n\n // ── Classify each agent ──\n\n const counts: Record<string, number> = {};\n const currentTick = Math.max(...agentIds.map(id => this.agents.get(id)!.lastActive), 0);\n\n for (let i = 0; i < agentIds.length; i++) {\n const id = agentIds[i]!;\n const rec = this.agents.get(id)!;\n const snaps = rec.snapshots;\n if (snaps.length === 0) continue;\n\n const latestHoldings = snaps[snaps.length - 1]!.totalHoldings;\n const agentTxRate = txRatesUnsorted[i]!;\n const ticksSinceFirst = currentTick - rec.firstSeen;\n const ticksSinceActive = currentTick - rec.lastActive;\n\n // Balance delta: compare first half vs second half of history\n const halfIdx = Math.floor(snaps.length / 2);\n const earlyAvg = snaps.slice(0, Math.max(1, halfIdx))\n .reduce((s, sn) => s + sn.totalHoldings, 0) / Math.max(1, halfIdx);\n const lateAvg = snaps.slice(halfIdx)\n .reduce((s, sn) => s + sn.totalHoldings, 0) / Math.max(1, snaps.length - halfIdx);\n const balanceDelta = lateAvg - earlyAvg;\n\n // System diversity\n const allSystems = new Set<string>();\n for (const sn of snaps) {\n for (const sys of sn.systems) allSystems.add(sys);\n }\n\n // Current window tx rate (for At-Risk comparison)\n const recentSnaps = snaps.slice(-Math.min(10, snaps.length));\n const recentTxRate = recentSnaps.reduce((s, sn) => s + sn.txCount, 0) / Math.max(1, recentSnaps.length);\n\n // ── Priority-ordered classification ──\n let persona: PersonaType;\n\n if (ticksSinceFirst <= this.config.newEntrantWindow) {\n persona = 'NewEntrant';\n } else if (latestHoldings > 0 && ticksSinceActive > this.config.dormantWindow) {\n persona = 'Dormant';\n } else if (rec.previousTxRate > 0 && recentTxRate < rec.previousTxRate * (1 - this.config.atRiskDropThreshold)) {\n persona = 'AtRisk';\n } else if (latestHoldings >= whaleThreshold && whaleThreshold > 0) {\n persona = 'Whale';\n } else if (allSystems.size >= this.config.powerUserMinSystems) {\n persona = 'PowerUser';\n } else if (agentTxRate >= activeTraderThreshold && activeTraderThreshold > 0) {\n persona = 'ActiveTrader';\n } else if (balanceDelta > 0 && agentTxRate < medianTxRate) {\n persona = 'Accumulator';\n } else if (balanceDelta < 0 && agentTxRate >= medianTxRate) {\n persona = 'Spender';\n } else {\n persona = 'Passive';\n }\n\n counts[persona] = (counts[persona] ?? 0) + 1;\n }\n\n // Convert to fractions\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\n// ── Helpers ──\n\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0;\n const idx = Math.ceil(p * sorted.length) - 1;\n return sorted[Math.max(0, Math.min(idx, sorted.length - 1))]!;\n}\n","// ParameterRegistry — type-based parameter resolution for universal economies\n// Replaces hardcoded parameter strings with a registry that resolves by type + scope.\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** High-level parameter categories (what it IS, not what it's called) */\nexport type ParameterType =\n | 'cost' // production cost, minting cost, operating cost\n | 'fee' // transaction fee, entry fee, withdrawal fee\n | 'reward' // reward rate, payout multiplier\n | 'yield' // yield rate, harvest rate, emission rate\n | 'rate' // generic rate (fallback)\n | 'cap' // supply cap, pool cap\n | 'penalty' // withdrawal penalty, decay rate\n | 'multiplier' // crowding multiplier, bonus multiplier\n | string; // extensible — any custom type\n\n/** How a parameter change affects net currency flow */\nexport type FlowImpact =\n | 'sink' // increasing this parameter drains currency (costs, fees, penalties)\n | 'faucet' // increasing this parameter injects currency (rewards, yields)\n | 'neutral' // no direct flow effect (caps, multipliers)\n | 'mixed' // depends on context\n | 'friction' // slows flow without removing currency (cooldowns, lock periods)\n | 'redistribution'; // moves currency between participants without net change\n\n/** Scope narrows which concrete parameter a type resolves to */\nexport interface ParameterScope {\n system?: string; // e.g. 'marketplace', 'staking', 'production'\n currency?: string; // e.g. 'gold', 'gems', 'ETH'\n tags?: string[]; // e.g. ['entry'], ['transaction'], ['withdrawal']\n}\n\n/** A registered parameter in the economy */\nexport interface RegisteredParameter {\n /** Concrete key used by the adapter (e.g. 'craftingCost', 'stakingYield') */\n key: string;\n /** What type of parameter this is */\n type: ParameterType;\n /** How changing this affects net flow */\n flowImpact: FlowImpact;\n /** Scope constraints — narrows resolution */\n scope?: Partial<ParameterScope>;\n /** Current value (updated after each apply) */\n currentValue?: number;\n /** Human-readable description */\n description?: string;\n /** Priority tiebreaker — higher wins when specificity scores are equal */\n priority?: number;\n /** Human-readable label for UIs and logs */\n label?: string;\n}\n\n/** Result of registry.validate() */\nexport interface RegistryValidationResult {\n valid: boolean;\n warnings: string[];\n errors: string[];\n}\n\n// ── Registry ────────────────────────────────────────────────────────────────\n\nexport class ParameterRegistry {\n private parameters = new Map<string, RegisteredParameter>();\n\n /** Register a parameter. Overwrites if key already exists. */\n register(param: RegisteredParameter): void {\n this.parameters.set(param.key, { ...param });\n }\n\n /** Register multiple parameters at once. */\n registerAll(params: RegisteredParameter[]): void {\n for (const p of params) this.register(p);\n }\n\n /**\n * Resolve a parameterType + scope to a concrete RegisteredParameter.\n * Returns the best match, or undefined if no match.\n *\n * Matching rules:\n * 1. Filter candidates by type\n * 2. Score each by scope specificity (system +10, currency +5, tags +3 each)\n * 3. Mismatched scope fields disqualify (score = -Infinity)\n * 4. Ties broken by `priority` (higher wins), then registration order\n * 5. All disqualified → undefined\n */\n resolve(type: ParameterType, scope?: Partial<ParameterScope>): RegisteredParameter | undefined {\n const candidates = this.findByType(type);\n if (candidates.length === 0) return undefined;\n if (candidates.length === 1) return candidates[0];\n\n let bestScore = -Infinity;\n let bestPriority = -Infinity;\n let best: RegisteredParameter | undefined;\n\n for (const candidate of candidates) {\n const score = this.scopeSpecificity(candidate.scope, scope);\n const prio = candidate.priority ?? 0;\n\n if (score > bestScore || (score === bestScore && prio > bestPriority)) {\n bestScore = score;\n bestPriority = prio;\n best = candidate;\n }\n }\n\n // If the best score is still -Infinity, all candidates were disqualified\n if (bestScore === -Infinity) return undefined;\n\n return best;\n }\n\n /** Find all parameters of a given type. */\n findByType(type: ParameterType): RegisteredParameter[] {\n const results: RegisteredParameter[] = [];\n for (const param of this.parameters.values()) {\n if (param.type === type) results.push(param);\n }\n return results;\n }\n\n /** Find all parameters belonging to a given system. */\n findBySystem(system: string): RegisteredParameter[] {\n const results: RegisteredParameter[] = [];\n for (const param of this.parameters.values()) {\n if (param.scope?.system === system) results.push(param);\n }\n return results;\n }\n\n /** Get a parameter by its concrete key. */\n get(key: string): RegisteredParameter | undefined {\n return this.parameters.get(key);\n }\n\n /** Get the flow impact of a parameter by its concrete key. */\n getFlowImpact(key: string): FlowImpact | undefined {\n return this.parameters.get(key)?.flowImpact;\n }\n\n /** Update the current value of a registered parameter. */\n updateValue(key: string, value: number): void {\n const param = this.parameters.get(key);\n if (param) {\n param.currentValue = value;\n }\n }\n\n /** Get all registered parameters. */\n getAll(): RegisteredParameter[] {\n return [...this.parameters.values()];\n }\n\n /** Number of registered parameters. */\n get size(): number {\n return this.parameters.size;\n }\n\n /**\n * Validate the registry for common misconfigurations.\n * Returns warnings (non-fatal) and errors (likely broken).\n */\n validate(): RegistryValidationResult {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n // Check for duplicate keys (impossible via Map, but verify types with same scope)\n const typeMap = new Map<string, RegisteredParameter[]>();\n for (const param of this.parameters.values()) {\n const list = typeMap.get(param.type) ?? [];\n list.push(param);\n typeMap.set(param.type, list);\n }\n\n // Warn: types with multiple entries but no scope differentiation\n for (const [type, params] of typeMap) {\n if (params.length > 1) {\n const unscopedCount = params.filter(p => !p.scope).length;\n if (unscopedCount > 1) {\n errors.push(\n `Type '${type}' has ${unscopedCount} unscoped parameters — resolve() cannot distinguish them`,\n );\n }\n }\n }\n\n // Warn: parameters without flowImpact\n for (const param of this.parameters.values()) {\n if (!param.flowImpact) {\n warnings.push(`Parameter '${param.key}' has no flowImpact — Simulator will use inference`);\n }\n }\n\n return {\n valid: errors.length === 0,\n warnings,\n errors,\n };\n }\n\n // ── Private ─────────────────────────────────────────────────────────────\n\n private scopeSpecificity(\n paramScope?: Partial<ParameterScope>,\n queryScope?: Partial<ParameterScope>,\n ): number {\n // No query scope → any param matches with base score\n if (!queryScope) return 0;\n // No param scope → generic match (lowest priority)\n if (!paramScope) return 0;\n\n let score = 0;\n\n // System match\n if (queryScope.system && paramScope.system) {\n if (queryScope.system === paramScope.system) score += 10;\n else return -Infinity; // system mismatch = disqualify\n }\n\n // Currency match\n if (queryScope.currency && paramScope.currency) {\n if (queryScope.currency === paramScope.currency) score += 5;\n else return -Infinity; // currency mismatch = disqualify\n }\n\n // Tag overlap\n if (queryScope.tags && queryScope.tags.length > 0 && paramScope.tags && paramScope.tags.length > 0) {\n const overlap = queryScope.tags.filter(t => paramScope.tags!.includes(t)).length;\n if (overlap > 0) {\n score += overlap * 3;\n } else {\n return -Infinity; // no tag overlap when both specify tags = disqualify\n }\n }\n\n return score;\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 EconomyMetrics,\n Principle,\n DecisionEntry,\n ActionPlan,\n Thresholds,\n MetricQuery,\n MetricQueryResult,\n} 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';\nimport { ParameterRegistry } from './ParameterRegistry.js';\nimport type { RegisteredParameter } from './ParameterRegistry.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: Simulator;\n private planner = new Planner();\n private executor!: Executor;\n private registry = new ParameterRegistry();\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 validateRegistry: config.validateRegistry ?? true,\n simulation: config.simulation ?? {},\n settlementWindowTicks: config.settlementWindowTicks ?? 200,\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 parameters: config.parameters ?? [],\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 // Register parameters if provided\n if (config.parameters) {\n this.registry.registerAll(config.parameters);\n }\n\n // Validate registry on startup (default: true)\n if (config.validateRegistry !== false && this.registry.size > 0) {\n const validation = this.registry.validate();\n for (const w of validation.warnings) console.warn(`[AgentE] Registry warning: ${w}`);\n for (const e of validation.errors) console.error(`[AgentE] Registry error: ${e}`);\n }\n\n this.executor = new Executor(config.settlementWindowTicks);\n this.simulator = new Simulator(this.registry, config.simulation);\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 reward parameter 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 (atomic swap — no window for lost events)\n const events = this.eventBuffer;\n this.eventBuffer = [];\n\n // Stage 1: Observe\n let metrics: EconomyMetrics;\n try {\n metrics = this.observer.compute(currentState, events);\n } catch (err) {\n console.error(`[AgentE] Observer.compute() failed at tick ${currentState.tick}:`, err);\n return; // skip this tick, don't crash the loop\n }\n this.store.record(metrics);\n this.personaTracker.update(currentState, events);\n metrics.personaDistribution = this.personaTracker.getDistribution();\n\n // Check rollbacks on active plans\n const { rolledBack, settled } = 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 for (const plan of settled) {\n this.planner.recordSettled(plan);\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 this.registry,\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.registry.updateValue(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.registry.updateValue(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 setMode(mode: AgentEMode): void {\n this.mode = mode;\n }\n\n getMode(): AgentEMode {\n return this.mode;\n }\n\n removePrinciple(id: string): void {\n this.diagnoser.removePrinciple(id);\n }\n\n registerParameter(param: RegisteredParameter): void {\n this.registry.register(param);\n }\n\n getRegistry(): ParameterRegistry {\n return this.registry;\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 if (!list.includes(handler)) {\n list.push(handler);\n }\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 try {\n result = handler(...args);\n if (result === false) return false; // veto\n } catch (err) {\n console.error(`[AgentE] Handler error on '${event}':`, err);\n }\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","// Utility functions for economy analysis\n\nimport type { EconomyMetrics } from './types.js';\n\n/**\n * Find the system with the worst metric value.\n * Works with flat Record<string, number> maps like flowBySystem.\n *\n * @param metrics - Current economy metrics snapshot\n * @param check - Function that returns a numeric \"badness\" score per system (higher = worse)\n * @param tolerancePercent - Only flag if the worst system exceeds the average by this % (default 0)\n * @returns The system name and its score, or undefined if no systems or none exceeds tolerance\n */\nexport function findWorstSystem(\n metrics: EconomyMetrics,\n check: (systemName: string, metrics: EconomyMetrics) => number,\n tolerancePercent: number = 0,\n): { system: string; score: number } | undefined {\n const systems = metrics.systems;\n if (systems.length === 0) return undefined;\n\n let worstSystem: string | undefined;\n let worstScore = -Infinity;\n let totalScore = 0;\n\n for (const sys of systems) {\n const score = check(sys, metrics);\n totalScore += score;\n if (score > worstScore) {\n worstScore = score;\n worstSystem = sys;\n }\n }\n\n if (!worstSystem) return undefined;\n\n // Tolerance check: only flag if worst exceeds average by tolerancePercent\n if (tolerancePercent > 0 && systems.length > 1) {\n const avg = totalScore / systems.length;\n if (avg === 0) return { system: worstSystem, score: worstScore };\n const excessPercent = ((worstScore - avg) / Math.abs(avg)) * 100;\n if (excessPercent < tolerancePercent) return undefined;\n }\n\n return { system: worstSystem, score: worstScore };\n}\n","// StateValidator — validates incoming EconomyState shape at runtime\n\nexport interface ValidationError {\n path: string;\n expected: string;\n received: string;\n message: string;\n}\n\nexport interface ValidationWarning {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n warnings: ValidationWarning[];\n}\n\nexport function validateEconomyState(state: unknown): ValidationResult {\n const errors: ValidationError[] = [];\n const warnings: ValidationWarning[] = [];\n\n if (state === null || state === undefined || typeof state !== 'object') {\n errors.push({\n path: '',\n expected: 'object',\n received: state === null ? 'null' : typeof state,\n message: 'State must be a non-null object',\n });\n return { valid: false, errors, warnings };\n }\n\n const s = state as Record<string, unknown>;\n\n // ── tick ──\n if (!isNonNegativeInteger(s['tick'])) {\n errors.push({\n path: 'tick',\n expected: 'non-negative integer',\n received: describeValue(s['tick']),\n message: 'tick must be a non-negative integer',\n });\n }\n\n // ── roles ──\n if (!isNonEmptyStringArray(s['roles'])) {\n errors.push({\n path: 'roles',\n expected: 'non-empty string[]',\n received: describeValue(s['roles']),\n message: 'roles must be a non-empty array of strings',\n });\n }\n const roles = new Set(Array.isArray(s['roles']) ? (s['roles'] as unknown[]).filter(r => typeof r === 'string') as string[] : []);\n\n // ── resources ──\n if (!isStringArray(s['resources'])) {\n errors.push({\n path: 'resources',\n expected: 'string[]',\n received: describeValue(s['resources']),\n message: 'resources must be an array of strings (can be empty)',\n });\n }\n const resources = new Set(Array.isArray(s['resources']) ? (s['resources'] as unknown[]).filter(r => typeof r === 'string') as string[] : []);\n\n // ── currencies ──\n if (!isNonEmptyStringArray(s['currencies'])) {\n errors.push({\n path: 'currencies',\n expected: 'non-empty string[]',\n received: describeValue(s['currencies']),\n message: 'currencies must be a non-empty array of strings',\n });\n }\n const currencies = new Set(\n Array.isArray(s['currencies'])\n ? (s['currencies'] as unknown[]).filter(r => typeof r === 'string') as string[]\n : [],\n );\n\n // ── agentBalances ── Record<string, Record<string, number>>\n if (isRecord(s['agentBalances'])) {\n const balances = s['agentBalances'] as Record<string, unknown>;\n for (const [agentId, currencyMap] of Object.entries(balances)) {\n if (!isRecord(currencyMap)) {\n errors.push({\n path: `agentBalances.${agentId}`,\n expected: 'Record<string, number>',\n received: describeValue(currencyMap),\n message: `agentBalances.${agentId} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [currency, value] of Object.entries(currencyMap as Record<string, unknown>)) {\n if (typeof value !== 'number' || value < 0) {\n errors.push({\n path: `agentBalances.${agentId}.${currency}`,\n expected: 'number >= 0',\n received: describeValue(value),\n message: `agentBalances.${agentId}.${currency} must be a non-negative number`,\n });\n }\n if (currencies.size > 0 && !currencies.has(currency)) {\n errors.push({\n path: `agentBalances.${agentId}.${currency}`,\n expected: `one of [${[...currencies].join(', ')}]`,\n received: currency,\n message: `agentBalances currency key \"${currency}\" is not in currencies`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'agentBalances',\n expected: 'Record<string, Record<string, number>>',\n received: describeValue(s['agentBalances']),\n message: 'agentBalances must be a nested Record<string, Record<string, number>>',\n });\n }\n\n // ── agentRoles ── Record<string, string>\n if (isRecord(s['agentRoles'])) {\n const agentRoles = s['agentRoles'] as Record<string, unknown>;\n for (const [agentId, role] of Object.entries(agentRoles)) {\n if (typeof role !== 'string') {\n errors.push({\n path: `agentRoles.${agentId}`,\n expected: 'string',\n received: describeValue(role),\n message: `agentRoles.${agentId} must be a string`,\n });\n } else if (roles.size > 0 && !roles.has(role)) {\n errors.push({\n path: `agentRoles.${agentId}`,\n expected: `one of [${[...roles].join(', ')}]`,\n received: role,\n message: `agentRoles value \"${role}\" is not in roles`,\n });\n }\n }\n } else {\n errors.push({\n path: 'agentRoles',\n expected: 'Record<string, string>',\n received: describeValue(s['agentRoles']),\n message: 'agentRoles must be a Record<string, string>',\n });\n }\n\n // ── agentInventories ── Record<string, Record<string, number>>\n if (isRecord(s['agentInventories'])) {\n const inventories = s['agentInventories'] as Record<string, unknown>;\n for (const [agentId, inv] of Object.entries(inventories)) {\n if (!isRecord(inv)) {\n errors.push({\n path: `agentInventories.${agentId}`,\n expected: 'Record<string, number>',\n received: describeValue(inv),\n message: `agentInventories.${agentId} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [resource, qty] of Object.entries(inv as Record<string, unknown>)) {\n if (typeof qty !== 'number' || qty < 0) {\n errors.push({\n path: `agentInventories.${agentId}.${resource}`,\n expected: 'number >= 0',\n received: describeValue(qty),\n message: `agentInventories.${agentId}.${resource} must be a non-negative number`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'agentInventories',\n expected: 'Record<string, Record<string, number>>',\n received: describeValue(s['agentInventories']),\n message: 'agentInventories must be a Record<string, Record<string, number>>',\n });\n }\n\n // ── marketPrices ── Record<string, Record<string, number>>\n if (isRecord(s['marketPrices'])) {\n const marketPrices = s['marketPrices'] as Record<string, unknown>;\n for (const [currency, resourcePrices] of Object.entries(marketPrices)) {\n if (currencies.size > 0 && !currencies.has(currency)) {\n errors.push({\n path: `marketPrices.${currency}`,\n expected: `one of [${[...currencies].join(', ')}]`,\n received: currency,\n message: `marketPrices outer key \"${currency}\" is not in currencies`,\n });\n }\n if (!isRecord(resourcePrices)) {\n errors.push({\n path: `marketPrices.${currency}`,\n expected: 'Record<string, number>',\n received: describeValue(resourcePrices),\n message: `marketPrices.${currency} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [resource, price] of Object.entries(resourcePrices as Record<string, unknown>)) {\n if (typeof price !== 'number' || price < 0) {\n errors.push({\n path: `marketPrices.${currency}.${resource}`,\n expected: 'number >= 0',\n received: describeValue(price),\n message: `marketPrices.${currency}.${resource} must be a non-negative number`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'marketPrices',\n expected: 'Record<string, Record<string, number>>',\n received: describeValue(s['marketPrices']),\n message: 'marketPrices must be a nested Record<string, Record<string, number>>',\n });\n }\n\n // ── recentTransactions ── array\n if (!Array.isArray(s['recentTransactions'])) {\n errors.push({\n path: 'recentTransactions',\n expected: 'array',\n received: describeValue(s['recentTransactions']),\n message: 'recentTransactions must be an array',\n });\n }\n\n // ── Optional: agentSatisfaction ──\n if (s['agentSatisfaction'] !== undefined) {\n if (isRecord(s['agentSatisfaction'])) {\n const satisfaction = s['agentSatisfaction'] as Record<string, unknown>;\n for (const [agentId, value] of Object.entries(satisfaction)) {\n if (typeof value !== 'number' || value < 0 || value > 100) {\n errors.push({\n path: `agentSatisfaction.${agentId}`,\n expected: 'number 0-100',\n received: describeValue(value),\n message: `agentSatisfaction.${agentId} must be a number between 0 and 100`,\n });\n }\n }\n } else {\n errors.push({\n path: 'agentSatisfaction',\n expected: 'Record<string, number> | undefined',\n received: describeValue(s['agentSatisfaction']),\n message: 'agentSatisfaction must be a Record<string, number> if provided',\n });\n }\n }\n\n // ── Optional: poolSizes ── Record<string, Record<string, number>>\n if (s['poolSizes'] !== undefined) {\n if (isRecord(s['poolSizes'])) {\n const pools = s['poolSizes'] as Record<string, unknown>;\n for (const [currency, poolMap] of Object.entries(pools)) {\n if (!isRecord(poolMap)) {\n errors.push({\n path: `poolSizes.${currency}`,\n expected: 'Record<string, number>',\n received: describeValue(poolMap),\n message: `poolSizes.${currency} must be a Record<string, number>`,\n });\n continue;\n }\n for (const [poolName, size] of Object.entries(poolMap as Record<string, unknown>)) {\n if (typeof size !== 'number' || size < 0) {\n errors.push({\n path: `poolSizes.${currency}.${poolName}`,\n expected: 'number >= 0',\n received: describeValue(size),\n message: `poolSizes.${currency}.${poolName} must be a non-negative number`,\n });\n }\n }\n }\n } else {\n errors.push({\n path: 'poolSizes',\n expected: 'Record<string, Record<string, number>> | undefined',\n received: describeValue(s['poolSizes']),\n message: 'poolSizes must be a nested Record if provided',\n });\n }\n }\n\n // ── Warnings ──\n\n // Currency declared but no agent holds it\n if (currencies.size > 0 && isRecord(s['agentBalances'])) {\n const heldCurrencies = new Set<string>();\n const balances = s['agentBalances'] as Record<string, Record<string, unknown>>;\n for (const currencyMap of Object.values(balances)) {\n if (isRecord(currencyMap)) {\n for (const key of Object.keys(currencyMap as Record<string, unknown>)) {\n heldCurrencies.add(key);\n }\n }\n }\n for (const currency of currencies) {\n if (!heldCurrencies.has(currency)) {\n warnings.push({\n path: `currencies`,\n message: `Currency \"${currency}\" is declared but no agent holds it`,\n });\n }\n }\n }\n\n // Agent with balance but no role\n if (isRecord(s['agentBalances']) && isRecord(s['agentRoles'])) {\n const agentRoles = s['agentRoles'] as Record<string, unknown>;\n const agentBalances = s['agentBalances'] as Record<string, unknown>;\n for (const agentId of Object.keys(agentBalances)) {\n if (!(agentId in agentRoles)) {\n warnings.push({\n path: `agentBalances.${agentId}`,\n message: `Agent \"${agentId}\" has balances but no role assigned`,\n });\n }\n }\n }\n\n // Empty resources with non-empty inventories\n if (resources.size === 0 && isRecord(s['agentInventories'])) {\n const inventories = s['agentInventories'] as Record<string, unknown>;\n let hasItems = false;\n for (const inv of Object.values(inventories)) {\n if (isRecord(inv) && Object.keys(inv as Record<string, unknown>).length > 0) {\n hasItems = true;\n break;\n }\n }\n if (hasItems) {\n warnings.push({\n path: 'resources',\n message: 'resources is empty but agents have non-empty inventories',\n });\n }\n }\n\n // Events referencing unknown currencies\n if (Array.isArray(s['recentTransactions']) && currencies.size > 0) {\n for (const event of s['recentTransactions'] as unknown[]) {\n if (isRecord(event)) {\n const e = event as Record<string, unknown>;\n if (typeof e['metadata'] === 'object' && e['metadata'] !== null) {\n const meta = e['metadata'] as Record<string, unknown>;\n if (typeof meta['currency'] === 'string' && !currencies.has(meta['currency'])) {\n warnings.push({\n path: 'recentTransactions',\n message: `Event references unknown currency \"${meta['currency']}\"`,\n });\n }\n }\n }\n }\n }\n\n return { valid: errors.length === 0, errors, warnings };\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction isRecord(value: unknown): boolean {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isStringArray(value: unknown): boolean {\n return Array.isArray(value) && value.every((v: unknown) => typeof v === 'string');\n}\n\nfunction isNonEmptyStringArray(value: unknown): boolean {\n return isStringArray(value) && (value as unknown[]).length > 0;\n}\n\nfunction isNonNegativeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0;\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return `array(${value.length})`;\n return typeof value;\n}\n"],"mappings":";AAEO,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,EAClB,mBAAmB;AAAA,EACnB,uBAAuB;AAAA;AAAA,EAGvB,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,qBAAqB;AAAA;AAAA,EAGrB,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,oBAAoB;AAAA;AAAA,EAGpB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,qBAAqB;AAAA;AAAA,EAGrB,2BAA2B;AAAA;AAAA,EAG3B,sBAAsB;AAAA,EACtB,eAAe;AAAA;AAAA,EAGf,aAAa;AAAA,EACb,mBAAmB;AAAA;AAAA,EAGnB,uBAAuB;AAAA;AAAA;AAAA,EAGvB,gBAAgB;AAAA;AAAA,EAChB,eAAe;AAAA;AAAA,EAGf,qBAAqB;AAAA;AAAA;AAAA,EAGrB,yBAAyB;AAAA;AAAA,EAGzB,mBAAmB;AAAA,EACnB,kBAAkB;AAAA;AAAA,EAGlB,eAAe;AAAA;AAAA,EAGf,sBAAsB;AAAA;AAAA,EAGtB,uBAAuB;AAAA,EACvB,wBAAwB;AAAA,EACxB,0BAA0B;AAAA,EAC1B,sBAAsB;AAAA,EACtB,gCAAgC;AAAA,EAChC,2BAA2B;AAAA,EAC3B,sB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