@agent-e/core 1.4.4 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,79 @@
1
- type EconomicEventType = 'trade' | 'mint' | 'burn' | 'transfer' | 'produce' | 'consume' | 'role_change' | 'spawn' | 'churn';
1
+ /** High-level parameter categories (what it IS, not what it's called) */
2
+ type ParameterType = 'cost' | 'fee' | 'reward' | 'yield' | 'rate' | 'cap' | 'penalty' | 'multiplier' | string;
3
+ /** How a parameter change affects net currency flow */
4
+ type FlowImpact = 'sink' | 'faucet' | 'neutral' | 'mixed' | 'friction' | 'redistribution';
5
+ /** Scope narrows which concrete parameter a type resolves to */
6
+ interface ParameterScope {
7
+ system?: string;
8
+ currency?: string;
9
+ tags?: string[];
10
+ }
11
+ /** A registered parameter in the economy */
12
+ interface RegisteredParameter {
13
+ /** Concrete key used by the adapter (e.g. 'craftingCost', 'stakingYield') */
14
+ key: string;
15
+ /** What type of parameter this is */
16
+ type: ParameterType;
17
+ /** How changing this affects net flow */
18
+ flowImpact: FlowImpact;
19
+ /** Scope constraints — narrows resolution */
20
+ scope?: Partial<ParameterScope>;
21
+ /** Current value (updated after each apply) */
22
+ currentValue?: number;
23
+ /** Human-readable description */
24
+ description?: string;
25
+ /** Priority tiebreaker — higher wins when specificity scores are equal */
26
+ priority?: number;
27
+ /** Human-readable label for UIs and logs */
28
+ label?: string;
29
+ }
30
+ /** Result of registry.validate() */
31
+ interface RegistryValidationResult {
32
+ valid: boolean;
33
+ warnings: string[];
34
+ errors: string[];
35
+ }
36
+ declare class ParameterRegistry {
37
+ private parameters;
38
+ /** Register a parameter. Overwrites if key already exists. */
39
+ register(param: RegisteredParameter): void;
40
+ /** Register multiple parameters at once. */
41
+ registerAll(params: RegisteredParameter[]): void;
42
+ /**
43
+ * Resolve a parameterType + scope to a concrete RegisteredParameter.
44
+ * Returns the best match, or undefined if no match.
45
+ *
46
+ * Matching rules:
47
+ * 1. Filter candidates by type
48
+ * 2. Score each by scope specificity (system +10, currency +5, tags +3 each)
49
+ * 3. Mismatched scope fields disqualify (score = -Infinity)
50
+ * 4. Ties broken by `priority` (higher wins), then registration order
51
+ * 5. All disqualified → undefined
52
+ */
53
+ resolve(type: ParameterType, scope?: Partial<ParameterScope>): RegisteredParameter | undefined;
54
+ /** Find all parameters of a given type. */
55
+ findByType(type: ParameterType): RegisteredParameter[];
56
+ /** Find all parameters belonging to a given system. */
57
+ findBySystem(system: string): RegisteredParameter[];
58
+ /** Get a parameter by its concrete key. */
59
+ get(key: string): RegisteredParameter | undefined;
60
+ /** Get the flow impact of a parameter by its concrete key. */
61
+ getFlowImpact(key: string): FlowImpact | undefined;
62
+ /** Update the current value of a registered parameter. */
63
+ updateValue(key: string, value: number): void;
64
+ /** Get all registered parameters. */
65
+ getAll(): RegisteredParameter[];
66
+ /** Number of registered parameters. */
67
+ get size(): number;
68
+ /**
69
+ * Validate the registry for common misconfigurations.
70
+ * Returns warnings (non-fatal) and errors (likely broken).
71
+ */
72
+ validate(): RegistryValidationResult;
73
+ private scopeSpecificity;
74
+ }
75
+
76
+ type EconomicEventType = 'trade' | 'mint' | 'burn' | 'transfer' | 'produce' | 'consume' | 'role_change' | 'enter' | 'churn';
2
77
  interface EconomicEvent {
3
78
  type: EconomicEventType;
4
79
  timestamp: number;
@@ -10,6 +85,8 @@ interface EconomicEvent {
10
85
  price?: number;
11
86
  from?: string;
12
87
  to?: string;
88
+ system?: string;
89
+ sourceOrSink?: string;
13
90
  metadata?: Record<string, unknown>;
14
91
  }
15
92
  type PinchPointStatus = 'optimal' | 'oversupplied' | 'scarce';
@@ -82,10 +159,20 @@ interface EconomyMetrics {
82
159
  giftTradeRatio: number;
83
160
  disposalTradeRatioByCurrency: Record<string, number>;
84
161
  disposalTradeRatio: number;
162
+ systems: string[];
163
+ sources: string[];
164
+ sinks: string[];
165
+ flowBySystem: Record<string, number>;
166
+ activityBySystem: Record<string, number>;
167
+ participantsBySystem: Record<string, number>;
168
+ flowBySource: Record<string, number>;
169
+ flowBySink: Record<string, number>;
170
+ sourceShare: Record<string, number>;
171
+ sinkShare: Record<string, number>;
85
172
  custom: Record<string, number>;
86
173
  }
87
174
  declare function emptyMetrics(tick?: number): EconomyMetrics;
88
- type PrincipleCategory = 'supply_chain' | 'incentive' | 'population' | 'currency' | 'bootstrap' | 'feedback' | 'regulator' | 'market_dynamics' | 'measurement' | 'wealth_distribution' | 'resource' | 'system_design' | 'player_experience' | 'statistical' | 'system_dynamics' | 'open_economy' | 'liveops';
175
+ type PrincipleCategory = 'supply_chain' | 'incentive' | 'population' | 'currency' | 'bootstrap' | 'feedback' | 'regulator' | 'market_dynamics' | 'measurement' | 'wealth_distribution' | 'resource' | 'system_design' | 'participant_experience' | 'statistical' | 'system_dynamics' | 'open_economy' | 'operations';
89
176
  interface PrincipleViolation {
90
177
  violated: true;
91
178
  severity: number;
@@ -106,18 +193,19 @@ interface Principle {
106
193
  check: (metrics: EconomyMetrics, thresholds: Thresholds) => PrincipleResult;
107
194
  }
108
195
  interface SuggestedAction {
109
- parameter: string;
196
+ parameterType: ParameterType;
110
197
  direction: 'increase' | 'decrease' | 'set';
111
198
  magnitude?: number;
112
199
  absoluteValue?: number;
113
- currency?: string;
200
+ scope?: Partial<ParameterScope>;
201
+ resolvedParameter?: string;
114
202
  reasoning: string;
115
203
  }
116
204
  interface ActionPlan {
117
205
  id: string;
118
206
  diagnosis: Diagnosis;
119
207
  parameter: string;
120
- currency?: string;
208
+ scope?: ParameterScope;
121
209
  currentValue: number;
122
210
  targetValue: number;
123
211
  maxChangePercent: number;
@@ -178,13 +266,16 @@ interface EconomyState {
178
266
  marketPrices: Record<string, Record<string, number>>;
179
267
  recentTransactions: EconomicEvent[];
180
268
  poolSizes?: Record<string, Record<string, number>>;
269
+ systems?: string[];
270
+ sources?: string[];
271
+ sinks?: string[];
181
272
  customData?: Record<string, unknown>;
182
273
  }
183
274
  interface EconomyAdapter {
184
275
  /** Return current full state snapshot */
185
276
  getState(): EconomyState | Promise<EconomyState>;
186
277
  /** Apply a parameter change to the host system */
187
- setParam(key: string, value: number, currency?: string): void | Promise<void>;
278
+ setParam(key: string, value: number, scope?: ParameterScope): void | Promise<void>;
188
279
  /** Optional: adapter pushes events as they happen */
189
280
  onEvent?: (handler: (event: EconomicEvent) => void) => void;
190
281
  }
@@ -247,6 +338,9 @@ interface AgentEConfig {
247
338
  mode?: AgentEMode;
248
339
  dominantRoles?: string[];
249
340
  idealDistribution?: Record<string, number>;
341
+ parameters?: RegisteredParameter[];
342
+ /** Run registry.validate() on startup and log warnings/errors (default: true) */
343
+ validateRegistry?: boolean;
250
344
  tickConfig?: Partial<TickConfig>;
251
345
  gracePeriod?: number;
252
346
  checkInterval?: number;
@@ -257,7 +351,7 @@ interface AgentEConfig {
257
351
  onAlert?: (diagnosis: Diagnosis) => void;
258
352
  onRollback?: (plan: ActionPlan, reason: string) => void;
259
353
  }
260
- type PersonaType = 'Active' | 'Trader' | 'Collector' | 'Speculator' | 'Earner' | 'Builder' | 'Social' | 'Whale' | 'Influencer';
354
+ type PersonaType = 'Active' | 'Trader' | 'Collector' | 'Speculator' | 'Earner' | 'Builder' | 'Social' | 'HighValue' | 'Influencer' | string;
261
355
  interface PersonaProfile {
262
356
  type: PersonaType;
263
357
  share: number;
@@ -347,6 +441,7 @@ declare class AgentE {
347
441
  private simulator;
348
442
  private planner;
349
443
  private executor;
444
+ private registry;
350
445
  readonly log: DecisionLog;
351
446
  readonly store: MetricStore;
352
447
  private personaTracker;
@@ -375,6 +470,8 @@ declare class AgentE {
375
470
  setMode(mode: AgentEMode): void;
376
471
  getMode(): AgentEMode;
377
472
  removePrinciple(id: string): void;
473
+ registerParameter(param: RegisteredParameter): void;
474
+ getRegistry(): ParameterRegistry;
378
475
  registerCustomMetric(name: string, fn: (state: EconomyState) => number): void;
379
476
  getDecisions(filter?: Parameters<DecisionLog['query']>[0]): DecisionEntry[];
380
477
  getPrinciples(): Principle[];
@@ -405,6 +502,8 @@ declare class Observer {
405
502
 
406
503
  declare class Simulator {
407
504
  private diagnoser;
505
+ private registry;
506
+ constructor(registry?: ParameterRegistry);
408
507
  private beforeViolationsCache;
409
508
  /**
410
509
  * Simulate the effect of applying `action` to the current economy forward `forwardTicks`.
@@ -422,6 +521,8 @@ declare class Simulator {
422
521
  private runForward;
423
522
  private actionMultiplier;
424
523
  private flowEffect;
524
+ /** Infer flow impact from parameter type when registry is unavailable */
525
+ private inferFlowImpact;
425
526
  private checkImprovement;
426
527
  private averageMetrics;
427
528
  }
@@ -434,6 +535,7 @@ declare class Planner {
434
535
  private lockedParams;
435
536
  private constraints;
436
537
  private cooldowns;
538
+ private typeCooldowns;
437
539
  private activePlanCount;
438
540
  lock(param: string): void;
439
541
  unlock(param: string): void;
@@ -445,13 +547,17 @@ declare class Planner {
445
547
  * - parameter is still in cooldown
446
548
  * - simulation result failed
447
549
  * - complexity budget exceeded
550
+ * - no matching parameter in registry
448
551
  */
449
- plan(diagnosis: Diagnosis, metrics: EconomyMetrics, simulationResult: SimulationResult, currentParams: Record<string, number>, thresholds: Thresholds): ActionPlan | null;
552
+ plan(diagnosis: Diagnosis, metrics: EconomyMetrics, simulationResult: SimulationResult, currentParams: Record<string, number>, thresholds: Thresholds, registry?: ParameterRegistry): ActionPlan | null;
450
553
  recordApplied(plan: ActionPlan, tick: number): void;
451
554
  recordRolledBack(_plan: ActionPlan): void;
555
+ recordSettled(_plan: ActionPlan): void;
452
556
  isOnCooldown(param: string, currentTick: number, cooldownTicks: number): boolean;
453
557
  /** Reset all cooldowns (useful for testing) */
454
558
  resetCooldowns(): void;
559
+ private typeCooldownKey;
560
+ private isTypeCooldown;
455
561
  }
456
562
 
457
563
  declare class Executor {
@@ -459,10 +565,12 @@ declare class Executor {
459
565
  apply(plan: ActionPlan, adapter: EconomyAdapter, currentParams: Record<string, number>): Promise<void>;
460
566
  /**
461
567
  * Check all active plans for rollback conditions.
462
- * Called every tick after metrics are computed.
463
- * Returns list of plans that were rolled back.
568
+ * Returns { rolledBack, settled } plans that were undone and plans that passed their window.
464
569
  */
465
- checkRollbacks(metrics: EconomyMetrics, adapter: EconomyAdapter): Promise<ActionPlan[]>;
570
+ checkRollbacks(metrics: EconomyMetrics, adapter: EconomyAdapter): Promise<{
571
+ rolledBack: ActionPlan[];
572
+ settled: ActionPlan[];
573
+ }>;
466
574
  private getMetricValue;
467
575
  getActivePlans(): ActionPlan[];
468
576
  }
@@ -476,6 +584,20 @@ declare class PersonaTracker {
476
584
  private classify;
477
585
  }
478
586
 
587
+ /**
588
+ * Find the system with the worst metric value.
589
+ * Works with flat Record<string, number> maps like flowBySystem.
590
+ *
591
+ * @param metrics - Current economy metrics snapshot
592
+ * @param check - Function that returns a numeric "badness" score per system (higher = worse)
593
+ * @param tolerancePercent - Only flag if the worst system exceeds the average by this % (default 0)
594
+ * @returns The system name and its score, or undefined if no systems or none exceeds tolerance
595
+ */
596
+ declare function findWorstSystem(metrics: EconomyMetrics, check: (systemName: string, metrics: EconomyMetrics) => number, tolerancePercent?: number): {
597
+ system: string;
598
+ score: number;
599
+ } | undefined;
600
+
479
601
  interface ValidationError {
480
602
  path: string;
481
603
  expected: string;
@@ -513,7 +635,7 @@ declare const P8_RegulatorCannotFightDesign: Principle;
513
635
  declare const INCENTIVE_PRINCIPLES: Principle[];
514
636
 
515
637
  declare const P9_RoleSwitchingNeedsFriction: Principle;
516
- declare const P10_SpawnWeightingUsesInversePopulation: Principle;
638
+ declare const P10_EntryWeightingUsesInversePopulation: Principle;
517
639
  declare const P11_TwoTierPressure: Principle;
518
640
  declare const P46_PersonaDiversity: Principle;
519
641
  declare const POPULATION_PRINCIPLES: Principle[];
@@ -546,8 +668,8 @@ declare const P28_StructuralDominanceIsNotPathological: Principle;
546
668
  declare const P38_CommunicationPreventsRevolt: Principle;
547
669
  declare const REGULATOR_PRINCIPLES: Principle[];
548
670
 
549
- declare const P29_PinchPoint: Principle;
550
- declare const P30_MovingPinchPoint: Principle;
671
+ declare const P29_BottleneckDetection: Principle;
672
+ declare const P30_DynamicBottleneckRotation: Principle;
551
673
  declare const P57_CombinatorialPriceSpace: Principle;
552
674
  declare const MARKET_DYNAMICS_PRINCIPLES: Principle[];
553
675
 
@@ -575,21 +697,21 @@ declare const P36_MechanicFrictionDetector: Principle;
575
697
  declare const P37_LatecommerProblem: Principle;
576
698
  declare const P45_TimeBudget: Principle;
577
699
  declare const P50_PayPowerRatio: Principle;
578
- declare const PLAYER_EXPERIENCE_PRINCIPLES: Principle[];
700
+ declare const PARTICIPANT_EXPERIENCE_PRINCIPLES: Principle[];
579
701
 
580
702
  declare const P34_ExtractionRatio: Principle;
581
703
  declare const P47_SmokeTest: Principle;
582
704
  declare const P48_CurrencyInsulation: Principle;
583
705
  declare const OPEN_ECONOMY_PRINCIPLES: Principle[];
584
706
 
585
- declare const P51_SharkTooth: Principle;
707
+ declare const P51_CyclicalEngagement: Principle;
586
708
  declare const P52_EndowmentEffect: Principle;
587
709
  declare const P53_EventCompletionRate: Principle;
588
- declare const P54_LiveOpsCadence: Principle;
589
- declare const P56_ContentDropShock: Principle;
590
- declare const LIVEOPS_PRINCIPLES: Principle[];
710
+ declare const P54_OperationalCadence: Principle;
711
+ declare const P56_SupplyShockAbsorption: Principle;
712
+ declare const OPERATIONS_PRINCIPLES: Principle[];
591
713
 
592
- /** All 60 built-in principles in priority order (supply chain → liveops) */
714
+ /** All 60 built-in principles in priority order (supply chain → operations) */
593
715
  declare const ALL_PRINCIPLES: Principle[];
594
716
 
595
- export { ALL_PRINCIPLES, type ActionPlan, AgentE, type AgentEConfig, type AgentEMode, BOOTSTRAP_PRINCIPLES, CURRENCY_FLOW_PRINCIPLES, DEFAULT_THRESHOLDS, type DecisionEntry, DecisionLog, type DecisionResult, Diagnoser, type Diagnosis, type EconomicEvent, type EconomicEventType, type EconomyAdapter, type EconomyMetrics, type EconomyState, Executor, FEEDBACK_LOOP_PRINCIPLES, INCENTIVE_PRINCIPLES, LIVEOPS_PRINCIPLES, MARKET_DYNAMICS_PRINCIPLES, MEASUREMENT_PRINCIPLES, type MetricQuery, type MetricQueryResult, type MetricResolution, MetricStore, OPEN_ECONOMY_PRINCIPLES, Observer, P10_SpawnWeightingUsesInversePopulation, P11_TwoTierPressure, P12_OnePrimaryFaucet, P13_PotsAreZeroSumAndSelfRegulate, P14_TrackActualInjection, P15_PoolsNeedCapAndDecay, P16_WithdrawalPenaltyScales, P17_GracePeriodBeforeIntervention, P18_FirstProducerNeedsStartingInventory, P19_StartingSupplyExceedsDemand, P1_ProductionMatchesConsumption, P20_DecayPreventsAccumulation, P21_PriceFromGlobalSupply, P22_MarketAwarenessPreventsSurplus, P23_ProfitabilityFactorsFeasibility, P24_BlockedAgentsDecayFaster, P25_CorrectLeversForCorrectProblems, P26_ContinuousPressureBeatsThresholdCuts, P27_AdjustmentsNeedCooldowns, P28_StructuralDominanceIsNotPathological, P29_PinchPoint, P2_ClosedLoopsNeedDirectHandoff, P30_MovingPinchPoint, P31_AnchorValueTracking, P32_VelocityAboveSupply, P33_FairNotEqual, P34_ExtractionRatio, P35_DestructionCreatesValue, P36_MechanicFrictionDetector, P37_LatecommerProblem, P38_CommunicationPreventsRevolt, P39_TheLagPrinciple, P3_BootstrapCapitalCoversFirstTransaction, P40_ReplacementRate, P41_MultiResolutionMonitoring, P42_TheMedianPrinciple, P43_SimulationMinimum, P44_ComplexityBudget, P45_TimeBudget, P46_PersonaDiversity, P47_SmokeTest, P48_CurrencyInsulation, P49_IdleAssetTax, P4_MaterialsFlowFasterThanCooldown, P50_PayPowerRatio, P51_SharkTooth, P52_EndowmentEffect, P53_EventCompletionRate, P54_LiveOpsCadence, P55_ArbitrageThermometer, P56_ContentDropShock, P57_CombinatorialPriceSpace, P58_NoNaturalNumeraire, P59_GiftEconomyNoise, P5_ProfitabilityIsCompetitive, P60_SurplusDisposalAsymmetry, P6_CrowdingMultiplierOnAllRoles, P7_NonSpecialistsSubsidiseSpecialists, P8_RegulatorCannotFightDesign, P9_RoleSwitchingNeedsFriction, PERSONA_HEALTHY_RANGES, PLAYER_EXPERIENCE_PRINCIPLES, POPULATION_PRINCIPLES, type PersonaProfile, PersonaTracker, type PersonaType, type PinchPointStatus, Planner, type Principle, type PrincipleCategory, type PrincipleOk, type PrincipleResult, type PrincipleViolation, REGULATOR_PRINCIPLES, RESOURCE_MGMT_PRINCIPLES, type RollbackCondition, STATISTICAL_PRINCIPLES, SUPPLY_CHAIN_PRINCIPLES, SYSTEM_DYNAMICS_PRINCIPLES, type SimulationOutcome, type SimulationResult, Simulator, type SuggestedAction, type Thresholds, type TickConfig, type ValidationError, type ValidationResult, type ValidationWarning, emptyMetrics, validateEconomyState };
717
+ export { ALL_PRINCIPLES, type ActionPlan, AgentE, type AgentEConfig, type AgentEMode, BOOTSTRAP_PRINCIPLES, CURRENCY_FLOW_PRINCIPLES, DEFAULT_THRESHOLDS, type DecisionEntry, DecisionLog, type DecisionResult, Diagnoser, type Diagnosis, type EconomicEvent, type EconomicEventType, type EconomyAdapter, type EconomyMetrics, type EconomyState, Executor, FEEDBACK_LOOP_PRINCIPLES, type FlowImpact, INCENTIVE_PRINCIPLES, MARKET_DYNAMICS_PRINCIPLES, MEASUREMENT_PRINCIPLES, type MetricQuery, type MetricQueryResult, type MetricResolution, MetricStore, OPEN_ECONOMY_PRINCIPLES, OPERATIONS_PRINCIPLES, Observer, P10_EntryWeightingUsesInversePopulation, P11_TwoTierPressure, P12_OnePrimaryFaucet, P13_PotsAreZeroSumAndSelfRegulate, P14_TrackActualInjection, P15_PoolsNeedCapAndDecay, P16_WithdrawalPenaltyScales, P17_GracePeriodBeforeIntervention, P18_FirstProducerNeedsStartingInventory, P19_StartingSupplyExceedsDemand, P1_ProductionMatchesConsumption, P20_DecayPreventsAccumulation, P21_PriceFromGlobalSupply, P22_MarketAwarenessPreventsSurplus, P23_ProfitabilityFactorsFeasibility, P24_BlockedAgentsDecayFaster, P25_CorrectLeversForCorrectProblems, P26_ContinuousPressureBeatsThresholdCuts, P27_AdjustmentsNeedCooldowns, P28_StructuralDominanceIsNotPathological, P29_BottleneckDetection, P2_ClosedLoopsNeedDirectHandoff, P30_DynamicBottleneckRotation, P31_AnchorValueTracking, P32_VelocityAboveSupply, P33_FairNotEqual, P34_ExtractionRatio, P35_DestructionCreatesValue, P36_MechanicFrictionDetector, P37_LatecommerProblem, P38_CommunicationPreventsRevolt, P39_TheLagPrinciple, P3_BootstrapCapitalCoversFirstTransaction, P40_ReplacementRate, P41_MultiResolutionMonitoring, P42_TheMedianPrinciple, P43_SimulationMinimum, P44_ComplexityBudget, P45_TimeBudget, P46_PersonaDiversity, P47_SmokeTest, P48_CurrencyInsulation, P49_IdleAssetTax, P4_MaterialsFlowFasterThanCooldown, P50_PayPowerRatio, P51_CyclicalEngagement, P52_EndowmentEffect, P53_EventCompletionRate, P54_OperationalCadence, P55_ArbitrageThermometer, P56_SupplyShockAbsorption, P57_CombinatorialPriceSpace, P58_NoNaturalNumeraire, P59_GiftEconomyNoise, P5_ProfitabilityIsCompetitive, P60_SurplusDisposalAsymmetry, P6_CrowdingMultiplierOnAllRoles, P7_NonSpecialistsSubsidiseSpecialists, P8_RegulatorCannotFightDesign, P9_RoleSwitchingNeedsFriction, PARTICIPANT_EXPERIENCE_PRINCIPLES, PERSONA_HEALTHY_RANGES, POPULATION_PRINCIPLES, ParameterRegistry, type ParameterScope, type ParameterType, type PersonaProfile, PersonaTracker, type PersonaType, type PinchPointStatus, Planner, type Principle, type PrincipleCategory, type PrincipleOk, type PrincipleResult, type PrincipleViolation, REGULATOR_PRINCIPLES, RESOURCE_MGMT_PRINCIPLES, type RegisteredParameter, type RegistryValidationResult, type RollbackCondition, STATISTICAL_PRINCIPLES, SUPPLY_CHAIN_PRINCIPLES, SYSTEM_DYNAMICS_PRINCIPLES, type SimulationOutcome, type SimulationResult, Simulator, type SuggestedAction, type Thresholds, type TickConfig, type ValidationError, type ValidationResult, type ValidationWarning, emptyMetrics, findWorstSystem, validateEconomyState };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,79 @@
1
- type EconomicEventType = 'trade' | 'mint' | 'burn' | 'transfer' | 'produce' | 'consume' | 'role_change' | 'spawn' | 'churn';
1
+ /** High-level parameter categories (what it IS, not what it's called) */
2
+ type ParameterType = 'cost' | 'fee' | 'reward' | 'yield' | 'rate' | 'cap' | 'penalty' | 'multiplier' | string;
3
+ /** How a parameter change affects net currency flow */
4
+ type FlowImpact = 'sink' | 'faucet' | 'neutral' | 'mixed' | 'friction' | 'redistribution';
5
+ /** Scope narrows which concrete parameter a type resolves to */
6
+ interface ParameterScope {
7
+ system?: string;
8
+ currency?: string;
9
+ tags?: string[];
10
+ }
11
+ /** A registered parameter in the economy */
12
+ interface RegisteredParameter {
13
+ /** Concrete key used by the adapter (e.g. 'craftingCost', 'stakingYield') */
14
+ key: string;
15
+ /** What type of parameter this is */
16
+ type: ParameterType;
17
+ /** How changing this affects net flow */
18
+ flowImpact: FlowImpact;
19
+ /** Scope constraints — narrows resolution */
20
+ scope?: Partial<ParameterScope>;
21
+ /** Current value (updated after each apply) */
22
+ currentValue?: number;
23
+ /** Human-readable description */
24
+ description?: string;
25
+ /** Priority tiebreaker — higher wins when specificity scores are equal */
26
+ priority?: number;
27
+ /** Human-readable label for UIs and logs */
28
+ label?: string;
29
+ }
30
+ /** Result of registry.validate() */
31
+ interface RegistryValidationResult {
32
+ valid: boolean;
33
+ warnings: string[];
34
+ errors: string[];
35
+ }
36
+ declare class ParameterRegistry {
37
+ private parameters;
38
+ /** Register a parameter. Overwrites if key already exists. */
39
+ register(param: RegisteredParameter): void;
40
+ /** Register multiple parameters at once. */
41
+ registerAll(params: RegisteredParameter[]): void;
42
+ /**
43
+ * Resolve a parameterType + scope to a concrete RegisteredParameter.
44
+ * Returns the best match, or undefined if no match.
45
+ *
46
+ * Matching rules:
47
+ * 1. Filter candidates by type
48
+ * 2. Score each by scope specificity (system +10, currency +5, tags +3 each)
49
+ * 3. Mismatched scope fields disqualify (score = -Infinity)
50
+ * 4. Ties broken by `priority` (higher wins), then registration order
51
+ * 5. All disqualified → undefined
52
+ */
53
+ resolve(type: ParameterType, scope?: Partial<ParameterScope>): RegisteredParameter | undefined;
54
+ /** Find all parameters of a given type. */
55
+ findByType(type: ParameterType): RegisteredParameter[];
56
+ /** Find all parameters belonging to a given system. */
57
+ findBySystem(system: string): RegisteredParameter[];
58
+ /** Get a parameter by its concrete key. */
59
+ get(key: string): RegisteredParameter | undefined;
60
+ /** Get the flow impact of a parameter by its concrete key. */
61
+ getFlowImpact(key: string): FlowImpact | undefined;
62
+ /** Update the current value of a registered parameter. */
63
+ updateValue(key: string, value: number): void;
64
+ /** Get all registered parameters. */
65
+ getAll(): RegisteredParameter[];
66
+ /** Number of registered parameters. */
67
+ get size(): number;
68
+ /**
69
+ * Validate the registry for common misconfigurations.
70
+ * Returns warnings (non-fatal) and errors (likely broken).
71
+ */
72
+ validate(): RegistryValidationResult;
73
+ private scopeSpecificity;
74
+ }
75
+
76
+ type EconomicEventType = 'trade' | 'mint' | 'burn' | 'transfer' | 'produce' | 'consume' | 'role_change' | 'enter' | 'churn';
2
77
  interface EconomicEvent {
3
78
  type: EconomicEventType;
4
79
  timestamp: number;
@@ -10,6 +85,8 @@ interface EconomicEvent {
10
85
  price?: number;
11
86
  from?: string;
12
87
  to?: string;
88
+ system?: string;
89
+ sourceOrSink?: string;
13
90
  metadata?: Record<string, unknown>;
14
91
  }
15
92
  type PinchPointStatus = 'optimal' | 'oversupplied' | 'scarce';
@@ -82,10 +159,20 @@ interface EconomyMetrics {
82
159
  giftTradeRatio: number;
83
160
  disposalTradeRatioByCurrency: Record<string, number>;
84
161
  disposalTradeRatio: number;
162
+ systems: string[];
163
+ sources: string[];
164
+ sinks: string[];
165
+ flowBySystem: Record<string, number>;
166
+ activityBySystem: Record<string, number>;
167
+ participantsBySystem: Record<string, number>;
168
+ flowBySource: Record<string, number>;
169
+ flowBySink: Record<string, number>;
170
+ sourceShare: Record<string, number>;
171
+ sinkShare: Record<string, number>;
85
172
  custom: Record<string, number>;
86
173
  }
87
174
  declare function emptyMetrics(tick?: number): EconomyMetrics;
88
- type PrincipleCategory = 'supply_chain' | 'incentive' | 'population' | 'currency' | 'bootstrap' | 'feedback' | 'regulator' | 'market_dynamics' | 'measurement' | 'wealth_distribution' | 'resource' | 'system_design' | 'player_experience' | 'statistical' | 'system_dynamics' | 'open_economy' | 'liveops';
175
+ type PrincipleCategory = 'supply_chain' | 'incentive' | 'population' | 'currency' | 'bootstrap' | 'feedback' | 'regulator' | 'market_dynamics' | 'measurement' | 'wealth_distribution' | 'resource' | 'system_design' | 'participant_experience' | 'statistical' | 'system_dynamics' | 'open_economy' | 'operations';
89
176
  interface PrincipleViolation {
90
177
  violated: true;
91
178
  severity: number;
@@ -106,18 +193,19 @@ interface Principle {
106
193
  check: (metrics: EconomyMetrics, thresholds: Thresholds) => PrincipleResult;
107
194
  }
108
195
  interface SuggestedAction {
109
- parameter: string;
196
+ parameterType: ParameterType;
110
197
  direction: 'increase' | 'decrease' | 'set';
111
198
  magnitude?: number;
112
199
  absoluteValue?: number;
113
- currency?: string;
200
+ scope?: Partial<ParameterScope>;
201
+ resolvedParameter?: string;
114
202
  reasoning: string;
115
203
  }
116
204
  interface ActionPlan {
117
205
  id: string;
118
206
  diagnosis: Diagnosis;
119
207
  parameter: string;
120
- currency?: string;
208
+ scope?: ParameterScope;
121
209
  currentValue: number;
122
210
  targetValue: number;
123
211
  maxChangePercent: number;
@@ -178,13 +266,16 @@ interface EconomyState {
178
266
  marketPrices: Record<string, Record<string, number>>;
179
267
  recentTransactions: EconomicEvent[];
180
268
  poolSizes?: Record<string, Record<string, number>>;
269
+ systems?: string[];
270
+ sources?: string[];
271
+ sinks?: string[];
181
272
  customData?: Record<string, unknown>;
182
273
  }
183
274
  interface EconomyAdapter {
184
275
  /** Return current full state snapshot */
185
276
  getState(): EconomyState | Promise<EconomyState>;
186
277
  /** Apply a parameter change to the host system */
187
- setParam(key: string, value: number, currency?: string): void | Promise<void>;
278
+ setParam(key: string, value: number, scope?: ParameterScope): void | Promise<void>;
188
279
  /** Optional: adapter pushes events as they happen */
189
280
  onEvent?: (handler: (event: EconomicEvent) => void) => void;
190
281
  }
@@ -247,6 +338,9 @@ interface AgentEConfig {
247
338
  mode?: AgentEMode;
248
339
  dominantRoles?: string[];
249
340
  idealDistribution?: Record<string, number>;
341
+ parameters?: RegisteredParameter[];
342
+ /** Run registry.validate() on startup and log warnings/errors (default: true) */
343
+ validateRegistry?: boolean;
250
344
  tickConfig?: Partial<TickConfig>;
251
345
  gracePeriod?: number;
252
346
  checkInterval?: number;
@@ -257,7 +351,7 @@ interface AgentEConfig {
257
351
  onAlert?: (diagnosis: Diagnosis) => void;
258
352
  onRollback?: (plan: ActionPlan, reason: string) => void;
259
353
  }
260
- type PersonaType = 'Active' | 'Trader' | 'Collector' | 'Speculator' | 'Earner' | 'Builder' | 'Social' | 'Whale' | 'Influencer';
354
+ type PersonaType = 'Active' | 'Trader' | 'Collector' | 'Speculator' | 'Earner' | 'Builder' | 'Social' | 'HighValue' | 'Influencer' | string;
261
355
  interface PersonaProfile {
262
356
  type: PersonaType;
263
357
  share: number;
@@ -347,6 +441,7 @@ declare class AgentE {
347
441
  private simulator;
348
442
  private planner;
349
443
  private executor;
444
+ private registry;
350
445
  readonly log: DecisionLog;
351
446
  readonly store: MetricStore;
352
447
  private personaTracker;
@@ -375,6 +470,8 @@ declare class AgentE {
375
470
  setMode(mode: AgentEMode): void;
376
471
  getMode(): AgentEMode;
377
472
  removePrinciple(id: string): void;
473
+ registerParameter(param: RegisteredParameter): void;
474
+ getRegistry(): ParameterRegistry;
378
475
  registerCustomMetric(name: string, fn: (state: EconomyState) => number): void;
379
476
  getDecisions(filter?: Parameters<DecisionLog['query']>[0]): DecisionEntry[];
380
477
  getPrinciples(): Principle[];
@@ -405,6 +502,8 @@ declare class Observer {
405
502
 
406
503
  declare class Simulator {
407
504
  private diagnoser;
505
+ private registry;
506
+ constructor(registry?: ParameterRegistry);
408
507
  private beforeViolationsCache;
409
508
  /**
410
509
  * Simulate the effect of applying `action` to the current economy forward `forwardTicks`.
@@ -422,6 +521,8 @@ declare class Simulator {
422
521
  private runForward;
423
522
  private actionMultiplier;
424
523
  private flowEffect;
524
+ /** Infer flow impact from parameter type when registry is unavailable */
525
+ private inferFlowImpact;
425
526
  private checkImprovement;
426
527
  private averageMetrics;
427
528
  }
@@ -434,6 +535,7 @@ declare class Planner {
434
535
  private lockedParams;
435
536
  private constraints;
436
537
  private cooldowns;
538
+ private typeCooldowns;
437
539
  private activePlanCount;
438
540
  lock(param: string): void;
439
541
  unlock(param: string): void;
@@ -445,13 +547,17 @@ declare class Planner {
445
547
  * - parameter is still in cooldown
446
548
  * - simulation result failed
447
549
  * - complexity budget exceeded
550
+ * - no matching parameter in registry
448
551
  */
449
- plan(diagnosis: Diagnosis, metrics: EconomyMetrics, simulationResult: SimulationResult, currentParams: Record<string, number>, thresholds: Thresholds): ActionPlan | null;
552
+ plan(diagnosis: Diagnosis, metrics: EconomyMetrics, simulationResult: SimulationResult, currentParams: Record<string, number>, thresholds: Thresholds, registry?: ParameterRegistry): ActionPlan | null;
450
553
  recordApplied(plan: ActionPlan, tick: number): void;
451
554
  recordRolledBack(_plan: ActionPlan): void;
555
+ recordSettled(_plan: ActionPlan): void;
452
556
  isOnCooldown(param: string, currentTick: number, cooldownTicks: number): boolean;
453
557
  /** Reset all cooldowns (useful for testing) */
454
558
  resetCooldowns(): void;
559
+ private typeCooldownKey;
560
+ private isTypeCooldown;
455
561
  }
456
562
 
457
563
  declare class Executor {
@@ -459,10 +565,12 @@ declare class Executor {
459
565
  apply(plan: ActionPlan, adapter: EconomyAdapter, currentParams: Record<string, number>): Promise<void>;
460
566
  /**
461
567
  * Check all active plans for rollback conditions.
462
- * Called every tick after metrics are computed.
463
- * Returns list of plans that were rolled back.
568
+ * Returns { rolledBack, settled } plans that were undone and plans that passed their window.
464
569
  */
465
- checkRollbacks(metrics: EconomyMetrics, adapter: EconomyAdapter): Promise<ActionPlan[]>;
570
+ checkRollbacks(metrics: EconomyMetrics, adapter: EconomyAdapter): Promise<{
571
+ rolledBack: ActionPlan[];
572
+ settled: ActionPlan[];
573
+ }>;
466
574
  private getMetricValue;
467
575
  getActivePlans(): ActionPlan[];
468
576
  }
@@ -476,6 +584,20 @@ declare class PersonaTracker {
476
584
  private classify;
477
585
  }
478
586
 
587
+ /**
588
+ * Find the system with the worst metric value.
589
+ * Works with flat Record<string, number> maps like flowBySystem.
590
+ *
591
+ * @param metrics - Current economy metrics snapshot
592
+ * @param check - Function that returns a numeric "badness" score per system (higher = worse)
593
+ * @param tolerancePercent - Only flag if the worst system exceeds the average by this % (default 0)
594
+ * @returns The system name and its score, or undefined if no systems or none exceeds tolerance
595
+ */
596
+ declare function findWorstSystem(metrics: EconomyMetrics, check: (systemName: string, metrics: EconomyMetrics) => number, tolerancePercent?: number): {
597
+ system: string;
598
+ score: number;
599
+ } | undefined;
600
+
479
601
  interface ValidationError {
480
602
  path: string;
481
603
  expected: string;
@@ -513,7 +635,7 @@ declare const P8_RegulatorCannotFightDesign: Principle;
513
635
  declare const INCENTIVE_PRINCIPLES: Principle[];
514
636
 
515
637
  declare const P9_RoleSwitchingNeedsFriction: Principle;
516
- declare const P10_SpawnWeightingUsesInversePopulation: Principle;
638
+ declare const P10_EntryWeightingUsesInversePopulation: Principle;
517
639
  declare const P11_TwoTierPressure: Principle;
518
640
  declare const P46_PersonaDiversity: Principle;
519
641
  declare const POPULATION_PRINCIPLES: Principle[];
@@ -546,8 +668,8 @@ declare const P28_StructuralDominanceIsNotPathological: Principle;
546
668
  declare const P38_CommunicationPreventsRevolt: Principle;
547
669
  declare const REGULATOR_PRINCIPLES: Principle[];
548
670
 
549
- declare const P29_PinchPoint: Principle;
550
- declare const P30_MovingPinchPoint: Principle;
671
+ declare const P29_BottleneckDetection: Principle;
672
+ declare const P30_DynamicBottleneckRotation: Principle;
551
673
  declare const P57_CombinatorialPriceSpace: Principle;
552
674
  declare const MARKET_DYNAMICS_PRINCIPLES: Principle[];
553
675
 
@@ -575,21 +697,21 @@ declare const P36_MechanicFrictionDetector: Principle;
575
697
  declare const P37_LatecommerProblem: Principle;
576
698
  declare const P45_TimeBudget: Principle;
577
699
  declare const P50_PayPowerRatio: Principle;
578
- declare const PLAYER_EXPERIENCE_PRINCIPLES: Principle[];
700
+ declare const PARTICIPANT_EXPERIENCE_PRINCIPLES: Principle[];
579
701
 
580
702
  declare const P34_ExtractionRatio: Principle;
581
703
  declare const P47_SmokeTest: Principle;
582
704
  declare const P48_CurrencyInsulation: Principle;
583
705
  declare const OPEN_ECONOMY_PRINCIPLES: Principle[];
584
706
 
585
- declare const P51_SharkTooth: Principle;
707
+ declare const P51_CyclicalEngagement: Principle;
586
708
  declare const P52_EndowmentEffect: Principle;
587
709
  declare const P53_EventCompletionRate: Principle;
588
- declare const P54_LiveOpsCadence: Principle;
589
- declare const P56_ContentDropShock: Principle;
590
- declare const LIVEOPS_PRINCIPLES: Principle[];
710
+ declare const P54_OperationalCadence: Principle;
711
+ declare const P56_SupplyShockAbsorption: Principle;
712
+ declare const OPERATIONS_PRINCIPLES: Principle[];
591
713
 
592
- /** All 60 built-in principles in priority order (supply chain → liveops) */
714
+ /** All 60 built-in principles in priority order (supply chain → operations) */
593
715
  declare const ALL_PRINCIPLES: Principle[];
594
716
 
595
- export { ALL_PRINCIPLES, type ActionPlan, AgentE, type AgentEConfig, type AgentEMode, BOOTSTRAP_PRINCIPLES, CURRENCY_FLOW_PRINCIPLES, DEFAULT_THRESHOLDS, type DecisionEntry, DecisionLog, type DecisionResult, Diagnoser, type Diagnosis, type EconomicEvent, type EconomicEventType, type EconomyAdapter, type EconomyMetrics, type EconomyState, Executor, FEEDBACK_LOOP_PRINCIPLES, INCENTIVE_PRINCIPLES, LIVEOPS_PRINCIPLES, MARKET_DYNAMICS_PRINCIPLES, MEASUREMENT_PRINCIPLES, type MetricQuery, type MetricQueryResult, type MetricResolution, MetricStore, OPEN_ECONOMY_PRINCIPLES, Observer, P10_SpawnWeightingUsesInversePopulation, P11_TwoTierPressure, P12_OnePrimaryFaucet, P13_PotsAreZeroSumAndSelfRegulate, P14_TrackActualInjection, P15_PoolsNeedCapAndDecay, P16_WithdrawalPenaltyScales, P17_GracePeriodBeforeIntervention, P18_FirstProducerNeedsStartingInventory, P19_StartingSupplyExceedsDemand, P1_ProductionMatchesConsumption, P20_DecayPreventsAccumulation, P21_PriceFromGlobalSupply, P22_MarketAwarenessPreventsSurplus, P23_ProfitabilityFactorsFeasibility, P24_BlockedAgentsDecayFaster, P25_CorrectLeversForCorrectProblems, P26_ContinuousPressureBeatsThresholdCuts, P27_AdjustmentsNeedCooldowns, P28_StructuralDominanceIsNotPathological, P29_PinchPoint, P2_ClosedLoopsNeedDirectHandoff, P30_MovingPinchPoint, P31_AnchorValueTracking, P32_VelocityAboveSupply, P33_FairNotEqual, P34_ExtractionRatio, P35_DestructionCreatesValue, P36_MechanicFrictionDetector, P37_LatecommerProblem, P38_CommunicationPreventsRevolt, P39_TheLagPrinciple, P3_BootstrapCapitalCoversFirstTransaction, P40_ReplacementRate, P41_MultiResolutionMonitoring, P42_TheMedianPrinciple, P43_SimulationMinimum, P44_ComplexityBudget, P45_TimeBudget, P46_PersonaDiversity, P47_SmokeTest, P48_CurrencyInsulation, P49_IdleAssetTax, P4_MaterialsFlowFasterThanCooldown, P50_PayPowerRatio, P51_SharkTooth, P52_EndowmentEffect, P53_EventCompletionRate, P54_LiveOpsCadence, P55_ArbitrageThermometer, P56_ContentDropShock, P57_CombinatorialPriceSpace, P58_NoNaturalNumeraire, P59_GiftEconomyNoise, P5_ProfitabilityIsCompetitive, P60_SurplusDisposalAsymmetry, P6_CrowdingMultiplierOnAllRoles, P7_NonSpecialistsSubsidiseSpecialists, P8_RegulatorCannotFightDesign, P9_RoleSwitchingNeedsFriction, PERSONA_HEALTHY_RANGES, PLAYER_EXPERIENCE_PRINCIPLES, POPULATION_PRINCIPLES, type PersonaProfile, PersonaTracker, type PersonaType, type PinchPointStatus, Planner, type Principle, type PrincipleCategory, type PrincipleOk, type PrincipleResult, type PrincipleViolation, REGULATOR_PRINCIPLES, RESOURCE_MGMT_PRINCIPLES, type RollbackCondition, STATISTICAL_PRINCIPLES, SUPPLY_CHAIN_PRINCIPLES, SYSTEM_DYNAMICS_PRINCIPLES, type SimulationOutcome, type SimulationResult, Simulator, type SuggestedAction, type Thresholds, type TickConfig, type ValidationError, type ValidationResult, type ValidationWarning, emptyMetrics, validateEconomyState };
717
+ export { ALL_PRINCIPLES, type ActionPlan, AgentE, type AgentEConfig, type AgentEMode, BOOTSTRAP_PRINCIPLES, CURRENCY_FLOW_PRINCIPLES, DEFAULT_THRESHOLDS, type DecisionEntry, DecisionLog, type DecisionResult, Diagnoser, type Diagnosis, type EconomicEvent, type EconomicEventType, type EconomyAdapter, type EconomyMetrics, type EconomyState, Executor, FEEDBACK_LOOP_PRINCIPLES, type FlowImpact, INCENTIVE_PRINCIPLES, MARKET_DYNAMICS_PRINCIPLES, MEASUREMENT_PRINCIPLES, type MetricQuery, type MetricQueryResult, type MetricResolution, MetricStore, OPEN_ECONOMY_PRINCIPLES, OPERATIONS_PRINCIPLES, Observer, P10_EntryWeightingUsesInversePopulation, P11_TwoTierPressure, P12_OnePrimaryFaucet, P13_PotsAreZeroSumAndSelfRegulate, P14_TrackActualInjection, P15_PoolsNeedCapAndDecay, P16_WithdrawalPenaltyScales, P17_GracePeriodBeforeIntervention, P18_FirstProducerNeedsStartingInventory, P19_StartingSupplyExceedsDemand, P1_ProductionMatchesConsumption, P20_DecayPreventsAccumulation, P21_PriceFromGlobalSupply, P22_MarketAwarenessPreventsSurplus, P23_ProfitabilityFactorsFeasibility, P24_BlockedAgentsDecayFaster, P25_CorrectLeversForCorrectProblems, P26_ContinuousPressureBeatsThresholdCuts, P27_AdjustmentsNeedCooldowns, P28_StructuralDominanceIsNotPathological, P29_BottleneckDetection, P2_ClosedLoopsNeedDirectHandoff, P30_DynamicBottleneckRotation, P31_AnchorValueTracking, P32_VelocityAboveSupply, P33_FairNotEqual, P34_ExtractionRatio, P35_DestructionCreatesValue, P36_MechanicFrictionDetector, P37_LatecommerProblem, P38_CommunicationPreventsRevolt, P39_TheLagPrinciple, P3_BootstrapCapitalCoversFirstTransaction, P40_ReplacementRate, P41_MultiResolutionMonitoring, P42_TheMedianPrinciple, P43_SimulationMinimum, P44_ComplexityBudget, P45_TimeBudget, P46_PersonaDiversity, P47_SmokeTest, P48_CurrencyInsulation, P49_IdleAssetTax, P4_MaterialsFlowFasterThanCooldown, P50_PayPowerRatio, P51_CyclicalEngagement, P52_EndowmentEffect, P53_EventCompletionRate, P54_OperationalCadence, P55_ArbitrageThermometer, P56_SupplyShockAbsorption, P57_CombinatorialPriceSpace, P58_NoNaturalNumeraire, P59_GiftEconomyNoise, P5_ProfitabilityIsCompetitive, P60_SurplusDisposalAsymmetry, P6_CrowdingMultiplierOnAllRoles, P7_NonSpecialistsSubsidiseSpecialists, P8_RegulatorCannotFightDesign, P9_RoleSwitchingNeedsFriction, PARTICIPANT_EXPERIENCE_PRINCIPLES, PERSONA_HEALTHY_RANGES, POPULATION_PRINCIPLES, ParameterRegistry, type ParameterScope, type ParameterType, type PersonaProfile, PersonaTracker, type PersonaType, type PinchPointStatus, Planner, type Principle, type PrincipleCategory, type PrincipleOk, type PrincipleResult, type PrincipleViolation, REGULATOR_PRINCIPLES, RESOURCE_MGMT_PRINCIPLES, type RegisteredParameter, type RegistryValidationResult, type RollbackCondition, STATISTICAL_PRINCIPLES, SUPPLY_CHAIN_PRINCIPLES, SYSTEM_DYNAMICS_PRINCIPLES, type SimulationOutcome, type SimulationResult, Simulator, type SuggestedAction, type Thresholds, type TickConfig, type ValidationError, type ValidationResult, type ValidationWarning, emptyMetrics, findWorstSystem, validateEconomyState };