-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcherry-diff.patch
More file actions
1400 lines (1386 loc) · 45.9 KB
/
cherry-diff.patch
File metadata and controls
1400 lines (1386 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/docs/horizon-aware-planning.md b/docs/horizon-aware-planning.md
index 2f45c71876c1f170370faf148146fb6b3089264b..cdbeae380486092a914d9400a604d2f00f92920e 100644
--- a/docs/horizon-aware-planning.md
+++ b/docs/horizon-aware-planning.md
@@ -59,8 +59,22 @@ This is not a UI redesign.
The horizon subsystem is generic. It accepts injected policy and transition
functions and does not import solver internals.
+## Expected-Value Overlay
+
+PR12 adds a separate expected-value wrapper for horizon rollout. Deterministic
+`runHorizonRollout` remains the base primitive.
+
+Expected-value rollout samples labeled numeric uncertainty before each
+deterministic rollout, then aggregates utility in `utility_usd_cents` through an
+explicit utility extractor. Transition functions still receive concrete state,
+not distributions.
+
+Expected-value output is labeled as expectation. It must not be described as a
+guaranteed future outcome.
+
## Related docs
- `docs/engine-time-semantics.md`
- `docs/engine-optimality/trace.md`
- `docs/simulation/objective-semantics.md`
+- `docs/simulation/uncertainty-modeling.md`
diff --git a/docs/simulation/objective-semantics.md b/docs/simulation/objective-semantics.md
index 22462ed4d62c1b74b697925450ed1b3816841064..48de22bb2edb5b7ef0cdeb15187f9e15e3747924 100644
--- a/docs/simulation/objective-semantics.md
+++ b/docs/simulation/objective-semantics.md
@@ -1,5 +1,5 @@
Status: Active
-Last updated: 2026-04-28
+Last updated: 2026-04-29
# Objective Semantics
@@ -60,15 +60,29 @@ does not define a true global utility function.
Cherry does not claim long-horizon global optimality. It ranks the currently generated candidate set under a documented, unit-consistent objective.
+### Expected-value overlay
+
+Expected-value simulation aggregates sample utility in the same canonical
+`utility_usd_cents` unit. It is an overlay on deterministic scoring, not a
+replacement for the live objective.
+
+Variance stays in utility-space. Risk-adjusted utility, when used, is computed
+from expected utility and variance with an explicit dimensionless risk
+coefficient. Expected-value explanations must label outputs as expectations,
+not guarantees.
+
## Future/Target behavior
- Any new score dimension must either convert into `objectiveUtilityCents` or be
explicitly documented as a bounded non-utility heuristic contribution.
- Any change to live objective semantics must update this document, tests, and
engine behavior versioning.
+- Add uncertainty or risk metrics only when their unit semantics remain explicit
+ and bounded.
## Related docs
- `docs/engine-optimality/objective.md`
- `docs/engine-optimality/status.md`
- `docs/engine-optimality/candidate-space.md`
+- `docs/simulation/uncertainty-modeling.md`
diff --git a/docs/simulation/uncertainty-modeling.md b/docs/simulation/uncertainty-modeling.md
new file mode 100644
index 0000000000000000000000000000000000000000..789feb99684dcc88dafc52e7b66347f7083b2882
--- /dev/null
+++ b/docs/simulation/uncertainty-modeling.md
@@ -0,0 +1,139 @@
+Status: Active
+Last updated: 2026-04-29
+
+# Uncertainty Modeling
+
+## Current behavior
+
+Cherry's deterministic engine remains primary. PR12 adds an expected-value
+overlay for simulation and horizon planning; it does not rewrite transition
+functions or present-time recommendation semantics.
+
+Uncertain inputs are numeric only. They must be represented as labeled
+`UncertainNumber` values at leaf fields:
+
+```ts
+{
+ incomeCents: {
+ label: 'monthly_income',
+ distribution: { kind: 'lognormal', mu: 8, sigma: 0.1 },
+ },
+}
+```
+
+Sampling happens before deterministic rollout. Transition functions receive
+realized numeric state, never distributions.
+
+Only `distribution` creates uncertainty-shape intent. `label` alone is always
+ordinary domain data.
+
+## Supported distributions
+
+The supported numeric distributions are:
+
+- `point(value)`
+- `normal(mu, sigma)`
+- `lognormal(mu, sigma)`
+- `discrete(values, probs)`
+
+Distribution parameters are validated before use. Discrete probabilities must
+sum to 1. Nonnegative engine domains such as cents, income, expense, balances,
+limits, cash, liquid amounts, rates, and utilization reject distributions that
+can produce negative samples. Use `lognormal`, nonnegative `point`, or
+nonnegative `discrete` values for positive-only financial quantities.
+
+This domain validation is a PR12 path-name heuristic for common engine fields,
+not a full semantic domain annotation system.
+
+Represent event/value probability as `discrete(values=[0,X], probs=[1-p,p])`.
+
+## Expected-value rollout
+
+Expected-value rollout is exposed separately from deterministic rollout.
+
+```txt
+runHorizonRollout(...) -> deterministic projection
+runExpectedValueHorizonRollout(...) -> expected-value projection
+```
+
+The EV wrapper realizes uncertain state once per sample, calls deterministic
+rollout, extracts utility through an explicit `utilityOfRollout` callback, and
+aggregates sample utility.
+
+Sample count is bounded:
+
+- minimum: `100`
+- default: `500`
+- maximum: `5000`
+
+Computational cost is:
+
+```txt
+O(samples * horizon * transition cost)
+```
+
+## Reproducibility
+
+EV runs require an explicit seed. The engine uses a deterministic seeded RNG;
+EV engine paths must not call `Math.random`.
+
+Explanations include the seed and sample count so a simulation can be
+reproduced when the same inputs, policy, transition, and utility extractor are
+used.
+
+## Utility and risk units
+
+Expected utility is aggregated in `utility_usd_cents`, the same canonical unit
+as `objectiveUtilityCents`.
+
+Variance remains in utility-space. PR12 implements only variance-based risk
+adjustment:
+
+```txt
+riskAdjustedUtility = expectedUtility - lambda * variance
+```
+
+`lambda` is a dimensionless risk-aversion coefficient and defaults to `0`
+risk-neutral behavior.
+
+The type surface reserves future risk metric names for semivariance and CVaR,
+but those are not implemented in PR12.
+
+## Explanation contract
+
+Expected-value explanations must label scalars as expectations. They include:
+
+- labeled assumptions
+- distribution strings
+- seed
+- sample count
+- expected outcome
+- variance
+- risk inputs
+- `uncertaintyLevel`
+- `results are expectations, not guarantees`
+
+`uncertaintyLevel` is a relative volatility classification using coefficient
+of variation:
+
+```txt
+cv = sqrt(variance) / abs(expectedUtility)
+```
+
+- `low`: `cv < 0.10`
+- `medium`: `0.10 <= cv <= 0.30`
+- `high`: `cv > 0.30`
+- `unknown`: expected utility is zero or variance is missing
+
+## Future/Target behavior
+
+- Add downside-aware risk metrics only when the explanation and unit semantics
+ are equally explicit.
+- Do not use EV output in production recommendation surfaces until the model is
+ bounded, explainable, and runtime-verified.
+
+## Related docs
+
+- `docs/horizon-aware-planning.md`
+- `docs/simulation/objective-semantics.md`
+- `docs/engine-optimality/objective.md`
diff --git a/lib/engine/explain/uncertainty.ts b/lib/engine/explain/uncertainty.ts
new file mode 100644
index 0000000000000000000000000000000000000000..fb2885adc976f06489135b7f402af4adc08cb9f9
--- /dev/null
+++ b/lib/engine/explain/uncertainty.ts
@@ -0,0 +1,113 @@
+import {
+ collectUncertaintyAssumptions,
+ type UncertaintyAssumption,
+} from '../uncertainty/policy.js';
+import type {
+ NumericDistribution,
+ UncertaintyLevel,
+ UncertaintySeed,
+} from '../uncertainty/types.js';
+
+export type ExpectedValueAssumptionExplanation = {
+ label: string;
+ path: string;
+ distribution: string;
+};
+
+export type ExpectedValueUncertaintyExplanation = {
+ type: 'expected_value';
+ assumptions: readonly ExpectedValueAssumptionExplanation[];
+ seed: UncertaintySeed;
+ samples: number;
+ expectedOutcome: unknown;
+ expectedUtility: number;
+ variance?: number;
+ riskLambda: number;
+ riskAdjustedExpectedUtility?: number;
+ uncertaintyLevel: UncertaintyLevel;
+ confidenceNote: 'results are expectations, not guarantees';
+};
+
+export function formatNumericDistribution(d: NumericDistribution): string {
+ switch (d.kind) {
+ case 'point':
+ return `point(value=${d.value})`;
+ case 'normal':
+ return `normal(mu=${d.mean}, sigma=${d.std})`;
+ case 'lognormal':
+ return `lognormal(mu=${d.mu}, sigma=${d.sigma})`;
+ case 'discrete':
+ return `discrete(values=[${d.values.join(',')}], probs=[${d.probs.join(',')}])`;
+ default: {
+ const exhaustive: never = d;
+ throw new Error(`Unsupported distribution: ${JSON.stringify(exhaustive)}`);
+ }
+ }
+}
+
+export function classifyRelativeUncertainty(params: {
+ expectedUtility: number;
+ variance?: number;
+}): UncertaintyLevel {
+ if (
+ params.variance === undefined ||
+ params.variance < 0 ||
+ !Number.isFinite(params.variance) ||
+ !Number.isFinite(params.expectedUtility) ||
+ params.expectedUtility === 0
+ ) {
+ return 'unknown';
+ }
+
+ const cv = Math.sqrt(params.variance) / Math.abs(params.expectedUtility);
+ if (cv < 0.1) return 'low';
+ if (cv <= 0.3) return 'medium';
+ return 'high';
+}
+
+function explainAssumption(
+ assumption: UncertaintyAssumption
+): ExpectedValueAssumptionExplanation {
+ return {
+ label: assumption.label,
+ path: assumption.path,
+ distribution: formatNumericDistribution(assumption.distribution),
+ };
+}
+
+export function buildExpectedValueUncertaintyExplanation(params: {
+ state: unknown;
+ seed: UncertaintySeed;
+ samples: number;
+ expectedOutcome: unknown;
+ expectedUtility: number;
+ variance?: number;
+ riskLambda?: number;
+ riskAdjustedExpectedUtility?: number;
+}): ExpectedValueUncertaintyExplanation {
+ const riskLambda = params.riskLambda === undefined ? 0 : params.riskLambda;
+ const explanation: ExpectedValueUncertaintyExplanation = {
+ type: 'expected_value',
+ assumptions: collectUncertaintyAssumptions(params.state).map(explainAssumption),
+ seed: params.seed,
+ samples: params.samples,
+ expectedOutcome: params.expectedOutcome,
+ expectedUtility: params.expectedUtility,
+ riskLambda,
+ uncertaintyLevel: classifyRelativeUncertainty(
+ params.variance === undefined
+ ? { expectedUtility: params.expectedUtility }
+ : { expectedUtility: params.expectedUtility, variance: params.variance }
+ ),
+ confidenceNote: 'results are expectations, not guarantees',
+ };
+
+ if (params.variance !== undefined) {
+ explanation.variance = params.variance;
+ }
+ if (params.riskAdjustedExpectedUtility !== undefined) {
+ explanation.riskAdjustedExpectedUtility = params.riskAdjustedExpectedUtility;
+ }
+
+ return explanation;
+}
diff --git a/lib/engine/horizon/expected-value.ts b/lib/engine/horizon/expected-value.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8ef10275369f0a5ad4076101e54f0b3b798b8416
--- /dev/null
+++ b/lib/engine/horizon/expected-value.ts
@@ -0,0 +1,102 @@
+import type { HorizonConfig } from './config.js';
+import {
+ runHorizonRollout,
+} from './rollout.js';
+import type {
+ HorizonRollout,
+ SnapshotStateFn,
+} from './types.js';
+import type { PolicyEvaluator } from './policy.js';
+import type { TransitionFn } from './transition.js';
+import { aggregateUtilitySamples } from '../objective/utility.js';
+import {
+ DEFAULT_RISK_LAMBDA,
+ riskAdjustedUtility,
+ validateRiskLambda,
+} from '../objective/risk.js';
+import {
+ DEFAULT_EXPECTED_VALUE_SAMPLES,
+ normalizeExpectedValueSamples,
+ validateUncertaintyState,
+} from '../uncertainty/policy.js';
+import { createSeededRng } from '../uncertainty/rng.js';
+import { realizeState } from '../uncertainty/realize.js';
+import type { UncertaintySeed } from '../uncertainty/types.js';
+
+export type ExpectedValueHorizonRollout<TState, TAction, TObjective> = {
+ type: 'expected_value';
+ seed: UncertaintySeed;
+ samples: number;
+ expectedUtility: number;
+ variance: number;
+ riskLambda: number;
+ riskAdjustedUtility: number;
+ sampleUtilities: readonly number[];
+ firstSampleRollout: HorizonRollout<TState, TAction, TObjective>;
+};
+
+export function runExpectedValueHorizonRollout<TState, TAction, TObjective>(args: {
+ initialState: TState;
+ config: HorizonConfig;
+ evaluatePolicy: PolicyEvaluator<TState, TAction, TObjective>;
+ applyAction: TransitionFn<TState, TAction>;
+ utilityOfRollout: (rollout: HorizonRollout<TState, TAction, TObjective>) => number;
+ samples?: number;
+ seed: UncertaintySeed;
+ riskLambda?: number;
+ snapshotState?: SnapshotStateFn<TState>;
+}): ExpectedValueHorizonRollout<TState, TAction, TObjective> {
+ const samples = normalizeExpectedValueSamples(
+ args.samples === undefined ? DEFAULT_EXPECTED_VALUE_SAMPLES : args.samples
+ );
+ const riskLambda =
+ args.riskLambda === undefined ? DEFAULT_RISK_LAMBDA : args.riskLambda;
+ validateRiskLambda(riskLambda);
+ const rng = createSeededRng(args.seed);
+ const utilities: number[] = [];
+ let firstSampleRollout: HorizonRollout<TState, TAction, TObjective> | null = null;
+
+ validateUncertaintyState(args.initialState);
+
+ // Expected-value rollout cost is O(samples * horizon * transition cost).
+ for (let sampleIndex = 0; sampleIndex < samples; sampleIndex += 1) {
+ const realizedState = realizeState(args.initialState, rng);
+ const rollout = runHorizonRollout<TState, TAction, TObjective>({
+ initialState: realizedState,
+ config: args.config,
+ evaluatePolicy: args.evaluatePolicy,
+ applyAction: args.applyAction,
+ ...(args.snapshotState === undefined ? {} : { snapshotState: args.snapshotState }),
+ });
+ const utility = args.utilityOfRollout(rollout);
+ if (!Number.isFinite(utility)) {
+ throw new Error('Expected-value rollout utility must be finite');
+ }
+ utilities.push(utility);
+ if (firstSampleRollout === null) {
+ firstSampleRollout = rollout;
+ }
+ }
+
+ if (firstSampleRollout === null) {
+ throw new Error('Expected-value rollout produced no samples');
+ }
+
+ const aggregate = aggregateUtilitySamples(utilities);
+ const variance = aggregate.variance;
+ return {
+ type: 'expected_value',
+ seed: args.seed,
+ samples,
+ expectedUtility: aggregate.expectedUtility,
+ variance,
+ riskLambda,
+ riskAdjustedUtility: riskAdjustedUtility(
+ aggregate.expectedUtility,
+ variance,
+ riskLambda
+ ),
+ sampleUtilities: utilities,
+ firstSampleRollout,
+ };
+}
diff --git a/lib/engine/horizon/index.ts b/lib/engine/horizon/index.ts
index 4631ef148dfba06557869d4824e3ae910e94f406..769ed66818e18b0f0cddd2d334ba5613d86b3abd 100644
--- a/lib/engine/horizon/index.ts
+++ b/lib/engine/horizon/index.ts
@@ -3,3 +3,4 @@ export * from './types.js';
export * from './policy.js';
export * from './transition.js';
export * from './rollout.js';
+export * from './expected-value.js';
diff --git a/lib/engine/index.ts b/lib/engine/index.ts
index 24f6cb454828e025057a3e4c73491560e5cb2892..f61fdd4a07f898963022a2ae84af9ac31bbbf76b 100644
--- a/lib/engine/index.ts
+++ b/lib/engine/index.ts
@@ -14,3 +14,5 @@ export * from './temporal-response.js';
export * from './public-types.js';
export * from './public.js';
export * from './horizon/index.js';
+export * from './uncertainty/index.js';
+export * from './explain/uncertainty.js';
diff --git a/lib/engine/objective.ts b/lib/engine/objective.ts
index e41a9cbf87564651162629fe540479ab30becfec..3bc8f3ebaf78fb024bc41f236e6118c2dd13a61f 100644
--- a/lib/engine/objective.ts
+++ b/lib/engine/objective.ts
@@ -33,6 +33,7 @@ export {
OBJECTIVE_SCORE_UNIT,
POINTS_PER_DOLLAR,
REWARD_POINT_VALUE_CENTS,
+ aggregateUtilitySamples,
centsToUtilityCents,
dollarsToUtilityCents,
pointsToUtilityCents,
@@ -42,9 +43,16 @@ export {
type ObjectiveComponent,
type ObjectiveComponentKind,
type ObjectiveScoreUnit,
+ type UtilityResult,
type UtilityCents,
} from './objective/utility.js';
+export {
+ DEFAULT_RISK_LAMBDA,
+ riskAdjustedUtility,
+ validateRiskLambda,
+} from './objective/risk.js';
+
export const UTILIZATION_RELIEF_UTILITY_CENTS_PER_BASIS_POINT = 0.0001;
export const DEBT_BALANCE_RELIEF_UTILITY_CENTS_PER_DEBT_CENT = 0.0001;
export const PAYDOWN_ACTION_BONUS_UTILITY_CENTS = 1;
diff --git a/lib/engine/objective/risk.ts b/lib/engine/objective/risk.ts
new file mode 100644
index 0000000000000000000000000000000000000000..705fe3c7c4043399e14ab972b395766141f8a8fe
--- /dev/null
+++ b/lib/engine/objective/risk.ts
@@ -0,0 +1,22 @@
+export const DEFAULT_RISK_LAMBDA = 0;
+
+export function validateRiskLambda(lambda: number): void {
+ if (!Number.isFinite(lambda) || lambda < 0) {
+ throw new Error('Risk lambda must be finite and nonnegative');
+ }
+}
+
+export function riskAdjustedUtility(
+ ev: number,
+ variance: number,
+ lambda: number = DEFAULT_RISK_LAMBDA
+): number {
+ if (!Number.isFinite(ev)) {
+ throw new Error('Expected utility must be finite');
+ }
+ if (!Number.isFinite(variance) || variance < 0) {
+ throw new Error('Variance must be finite and nonnegative');
+ }
+ validateRiskLambda(lambda);
+ return ev - lambda * variance;
+}
diff --git a/lib/engine/objective/utility.ts b/lib/engine/objective/utility.ts
index 32118866d11445f8c80d83e4dc087ec9682b4d59..bd44caf70de64a5b86b3855d58f6c70cdc949f17 100644
--- a/lib/engine/objective/utility.ts
+++ b/lib/engine/objective/utility.ts
@@ -26,6 +26,12 @@ export type ObjectiveComponent = {
boundedHeuristic?: boolean;
};
+export type UtilityResult = {
+ expectedUtility: number;
+ variance?: number;
+ samples?: number;
+};
+
export function utilityCents(value: number): UtilityCents {
if (!Number.isFinite(value)) {
throw new Error('Utility cents must be finite');
@@ -56,3 +62,29 @@ export function sumObjectiveUtility(
components.reduce((sum, component) => sum + component.utilityCents, 0)
);
}
+
+export function aggregateUtilitySamples(samples: readonly number[]): Required<UtilityResult> {
+ if (samples.length === 0) {
+ throw new Error('Utility samples must not be empty');
+ }
+
+ let total = 0;
+ for (const value of samples) {
+ if (!Number.isFinite(value)) {
+ throw new Error('Utility samples must be finite');
+ }
+ total += value;
+ }
+
+ const expectedUtility = total / samples.length;
+ const squaredErrorTotal = samples.reduce((sum, value) => {
+ const delta = value - expectedUtility;
+ return sum + delta * delta;
+ }, 0);
+
+ return {
+ expectedUtility,
+ variance: squaredErrorTotal / samples.length,
+ samples: samples.length,
+ };
+}
diff --git a/lib/engine/uncertainty/index.ts b/lib/engine/uncertainty/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5028ebff990625ff5a0c9387801e8a74ff36c9ed
--- /dev/null
+++ b/lib/engine/uncertainty/index.ts
@@ -0,0 +1,5 @@
+export * from './types.js';
+export * from './sampling.js';
+export * from './rng.js';
+export * from './policy.js';
+export * from './realize.js';
diff --git a/lib/engine/uncertainty/policy.ts b/lib/engine/uncertainty/policy.ts
new file mode 100644
index 0000000000000000000000000000000000000000..99a7d3482444d6b508d09e2a58b61e7c0fa70d50
--- /dev/null
+++ b/lib/engine/uncertainty/policy.ts
@@ -0,0 +1,129 @@
+import { validateNumericDistribution } from './sampling.js';
+import {
+ hasUncertaintyShapeIntent,
+ isRecord,
+ isUncertainNumber,
+ type NumericDistribution,
+ type UncertainNumber,
+} from './types.js';
+
+export const MIN_EXPECTED_VALUE_SAMPLES = 100;
+export const DEFAULT_EXPECTED_VALUE_SAMPLES = 500;
+export const MAX_EXPECTED_VALUE_SAMPLES = 5000;
+
+const NONNEGATIVE_PATH_PATTERN =
+ /(?:cents|amount|balance|limit|income|expense|spend|cash|liquid|paycheck|rate|utilization)$/i;
+
+export type UncertaintyAssumption = {
+ path: string;
+ label: string;
+ distribution: NumericDistribution;
+};
+
+export function normalizeExpectedValueSamples(samples: number): number {
+ if (!Number.isInteger(samples)) {
+ throw new Error(`Expected-value samples must be an integer: ${samples}`);
+ }
+ const belowMinimum = samples < MIN_EXPECTED_VALUE_SAMPLES;
+ const aboveMaximum = samples > MAX_EXPECTED_VALUE_SAMPLES;
+ if (belowMinimum) {
+ throw new Error(
+ `Expected-value samples must be between ${MIN_EXPECTED_VALUE_SAMPLES} and ${MAX_EXPECTED_VALUE_SAMPLES}: ${samples}`
+ );
+ }
+ if (aboveMaximum) {
+ throw new Error(
+ `Expected-value samples must be between ${MIN_EXPECTED_VALUE_SAMPLES} and ${MAX_EXPECTED_VALUE_SAMPLES}: ${samples}`
+ );
+ }
+ return samples;
+}
+
+function pathString(segments: readonly string[]): string {
+ return segments.length === 0 ? '$' : segments.join('.');
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ if (!isRecord(value)) return false;
+ const prototype: unknown = Object.getPrototypeOf(value);
+ if (prototype === Object.prototype) return true;
+ if (prototype === null) return true;
+ return false;
+}
+
+function isNonnegativeDomain(segments: readonly string[]): boolean {
+ const last = segments[segments.length - 1];
+ return last !== undefined && NONNEGATIVE_PATH_PATTERN.test(last);
+}
+
+function distributionCanProduceNegative(d: NumericDistribution): boolean {
+ switch (d.kind) {
+ case 'point':
+ return d.value < 0;
+ case 'lognormal':
+ return false;
+ case 'normal':
+ if (d.std > 0) return true;
+ return d.mean < 0;
+ case 'discrete':
+ return d.values.some((value) => value < 0);
+ default: {
+ const exhaustive: never = d;
+ throw new Error(`Unsupported distribution: ${JSON.stringify(exhaustive)}`);
+ }
+ }
+}
+
+function validateUncertainNumber(value: UncertainNumber, segments: readonly string[]): void {
+ if (value.label.trim().length === 0) {
+ throw new Error(`Uncertain number at ${pathString(segments)} must have a label`);
+ }
+
+ validateNumericDistribution(value.distribution);
+
+ if (isNonnegativeDomain(segments) && distributionCanProduceNegative(value.distribution)) {
+ throw new Error(
+ `Uncertain number at ${pathString(segments)} uses a distribution that can produce negative values for a nonnegative domain`
+ );
+ }
+}
+
+export function collectUncertaintyAssumptions(value: unknown): UncertaintyAssumption[] {
+ const assumptions: UncertaintyAssumption[] = [];
+
+ function visit(current: unknown, segments: string[]): void {
+ if (isUncertainNumber(current)) {
+ validateUncertainNumber(current, segments);
+ assumptions.push({
+ path: pathString(segments),
+ label: current.label,
+ distribution: current.distribution,
+ });
+ return;
+ }
+
+ if (Array.isArray(current)) {
+ current.forEach((entry, index) => visit(entry, [...segments, String(index)]));
+ return;
+ }
+
+ if (isRecord(current)) {
+ if (hasUncertaintyShapeIntent(current)) {
+ throw new Error(`Invalid uncertain number at ${pathString(segments)}`);
+ }
+ if (!isPlainObject(current)) {
+ throw new Error(`Expected JSON-plain object at ${pathString(segments)}`);
+ }
+ for (const [key, entry] of Object.entries(current)) {
+ visit(entry, [...segments, key]);
+ }
+ }
+ }
+
+ visit(value, []);
+ return assumptions;
+}
+
+export function validateUncertaintyState(value: unknown): void {
+ collectUncertaintyAssumptions(value);
+}
diff --git a/lib/engine/uncertainty/realize.ts b/lib/engine/uncertainty/realize.ts
new file mode 100644
index 0000000000000000000000000000000000000000..cfd58da6723cf3d609ac038fef863fc62f6783e0
--- /dev/null
+++ b/lib/engine/uncertainty/realize.ts
@@ -0,0 +1,47 @@
+import { sample } from './sampling.js';
+import {
+ hasUncertaintyShapeIntent,
+ isRecord,
+ isUncertainNumber,
+} from './types.js';
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ if (!isRecord(value)) return false;
+ const prototype: unknown = Object.getPrototypeOf(value);
+ if (prototype === Object.prototype) return true;
+ if (prototype === null) return true;
+ return false;
+}
+
+function realizeValue(value: unknown, rng: () => number, segments: readonly string[]): unknown {
+ if (isUncertainNumber(value)) {
+ return sample(value.distribution, rng);
+ }
+
+ if (Array.isArray(value)) {
+ return value.map((entry, index) => realizeValue(entry, rng, [...segments, String(index)]));
+ }
+
+ if (isRecord(value)) {
+ if (hasUncertaintyShapeIntent(value)) {
+ const location = segments.length === 0 ? '$' : segments.join('.');
+ throw new Error(`Invalid uncertain number at ${location}`);
+ }
+ if (!isPlainObject(value)) {
+ const location = segments.length === 0 ? '$' : segments.join('.');
+ throw new Error(`Expected JSON-plain object at ${location}`);
+ }
+
+ const realized: Record<string, unknown> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ realized[key] = realizeValue(entry, rng, [...segments, key]);
+ }
+ return realized;
+ }
+
+ return value;
+}
+
+export function realizeState<T>(state: T, rng: () => number): T {
+ return realizeValue(state, rng, []) as T;
+}
diff --git a/lib/engine/uncertainty/rng.ts b/lib/engine/uncertainty/rng.ts
new file mode 100644
index 0000000000000000000000000000000000000000..2d1378c7f7e426cf38e2f57335146b24d1148c08
--- /dev/null
+++ b/lib/engine/uncertainty/rng.ts
@@ -0,0 +1,26 @@
+import type { UncertaintySeed } from './types.js';
+
+function hashSeed(seed: UncertaintySeed): number {
+ const text = String(seed);
+ let hash = 2166136261;
+
+ for (let index = 0; index < text.length; index += 1) {
+ const code = text.charCodeAt(index);
+ hash ^= code;
+ hash = Math.imul(hash, 16777619);
+ }
+
+ return hash >>> 0;
+}
+
+export function createSeededRng(seed: UncertaintySeed): () => number {
+ let state = hashSeed(seed);
+
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let value = state;
+ value = Math.imul(value ^ (value >>> 15), value | 1);
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
+ };
+}
diff --git a/lib/engine/uncertainty/sampling.ts b/lib/engine/uncertainty/sampling.ts
new file mode 100644
index 0000000000000000000000000000000000000000..f5e26e5a30e412b118ff02f57b15fed140fff13b
--- /dev/null
+++ b/lib/engine/uncertainty/sampling.ts
@@ -0,0 +1,120 @@
+import type { NumericDistribution } from './types.js';
+
+const PROBABILITY_SUM_TOLERANCE = 1e-9;
+
+function assertFiniteNumber(value: number, label: string): void {
+ if (!Number.isFinite(value)) {
+ throw new Error(`${label} must be finite`);
+ }
+}
+
+function assertProbability(value: number, label: string): void {
+ assertFiniteNumber(value, label);
+ if (value < 0 || value > 1) {
+ throw new Error(`${label} must be between 0 and 1`);
+ }
+}
+
+export function validateNumericDistribution(d: NumericDistribution): void {
+ switch (d.kind) {
+ case 'point':
+ assertFiniteNumber(d.value, 'point.value');
+ return;
+ case 'normal':
+ assertFiniteNumber(d.mean, 'normal.mean');
+ assertFiniteNumber(d.std, 'normal.std');
+ if (d.std < 0) throw new Error('normal.std must be nonnegative');
+ return;
+ case 'lognormal':
+ assertFiniteNumber(d.mu, 'lognormal.mu');
+ assertFiniteNumber(d.sigma, 'lognormal.sigma');
+ if (d.sigma < 0) throw new Error('lognormal.sigma must be nonnegative');
+ return;
+ case 'discrete': {
+ if (d.values.length === 0) throw new Error('discrete.values must not be empty');
+ if (d.values.length !== d.probs.length) {
+ throw new Error('discrete.values and discrete.probs must have the same length');
+ }
+ let total = 0;
+ for (let index = 0; index < d.values.length; index += 1) {
+ const value = d.values[index];
+ const probability = d.probs[index];
+ if (value === undefined || probability === undefined) {
+ throw new Error('discrete entries must be defined');
+ }
+ assertFiniteNumber(value, `discrete.values[${index}]`);
+ assertProbability(probability, `discrete.probs[${index}]`);
+ total += probability;
+ }
+ if (Math.abs(total - 1) > PROBABILITY_SUM_TOLERANCE) {
+ throw new Error('discrete.probs must sum to 1');
+ }
+ return;
+ }
+ default: {
+ const exhaustive: never = d;
+ throw new Error(`Unsupported distribution: ${JSON.stringify(exhaustive)}`);
+ }
+ }
+}
+
+export function expectation(d: NumericDistribution): number {
+ validateNumericDistribution(d);
+
+ switch (d.kind) {
+ case 'point':
+ return d.value;
+ case 'normal':
+ return d.mean;
+ case 'lognormal':
+ return Math.exp(d.mu + (d.sigma * d.sigma) / 2);
+ case 'discrete':
+ return d.values.reduce((sum, value, index) => {
+ const probability = d.probs[index];
+ return probability === undefined ? sum : sum + value * probability;
+ }, 0);
+ default: {
+ const exhaustive: never = d;
+ throw new Error(`Unsupported distribution: ${JSON.stringify(exhaustive)}`);
+ }
+ }
+}
+
+function standardNormalSample(rng: () => number): number {
+ const u1 = Math.max(Number.MIN_VALUE, rng());
+ const u2 = rng();
+ return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
+}
+
+export function sample(d: NumericDistribution, rng: () => number): number {
+ validateNumericDistribution(d);
+
+ switch (d.kind) {
+ case 'point':
+ return d.value;
+ case 'normal':
+ return d.mean + d.std * standardNormalSample(rng);
+ case 'lognormal':
+ return Math.exp(d.mu + d.sigma * standardNormalSample(rng));
+ case 'discrete': {
+ const draw = rng();
+ let cumulative = 0;
+ for (let index = 0; index < d.values.length; index += 1) {
+ const probability = d.probs[index];
+ const value = d.values[index];
+ if (probability === undefined || value === undefined) {
+ throw new Error('discrete entries must be defined');
+ }
+ cumulative += probability;
+ if (draw <= cumulative || index === d.values.length - 1) {
+ return value;
+ }
+ }
+ throw new Error('discrete sample failed');
+ }
+ default: {
+ const exhaustive: never = d;
+ throw new Error(`Unsupported distribution: ${JSON.stringify(exhaustive)}`);
+ }
+ }
+}
diff --git a/lib/engine/uncertainty/types.ts b/lib/engine/uncertainty/types.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b27bc633d6bb67c06f9e11f46431c8634c77fdb6
--- /dev/null
+++ b/lib/engine/uncertainty/types.ts
@@ -0,0 +1,66 @@
+export type NumericDistributionKind =
+ | 'point'
+ | 'normal'
+ | 'lognormal'
+ | 'discrete';
+
+export type NumericDistribution =
+ | { kind: 'point'; value: number }
+ | { kind: 'normal'; mean: number; std: number }
+ | { kind: 'lognormal'; mu: number; sigma: number }
+ | { kind: 'discrete'; values: number[]; probs: number[] };
+
+export type UncertainNumber = {
+ distribution: NumericDistribution;
+ label: string;
+};
+
+export type UncertaintySeed = string | number;
+
+export type UncertaintyLevel = 'low' | 'medium' | 'high' | 'unknown';
+
+export type RiskMetricKind = 'variance' | 'semivariance' | 'cvar';
+
+export type ImplementedRiskMetricKind = Extract<RiskMetricKind, 'variance'>;
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export function hasUncertaintyShapeIntent(value: unknown): value is Record<string, unknown> {
+ return isRecord(value) && 'distribution' in value;
+}
+
+export function isNumericDistribution(value: unknown): value is NumericDistribution {
+ if (!isRecord(value)) return false;
+ if (typeof value['kind'] !== 'string') return false;
+
+ switch (value['kind']) {
+ case 'point':
+ return typeof value['value'] === 'number';
+ case 'normal':
+ return typeof value['mean'] === 'number' && typeof value['std'] === 'number';
+ case 'lognormal':
+ return typeof value['mu'] === 'number' && typeof value['sigma'] === 'number';
+ case 'discrete':
+ return Array.isArray(value['values']) && Array.isArray(value['probs']);
+ default:
+ return false;
+ }
+}
+
+export function isUncertainNumber(value: unknown): value is UncertainNumber {
+ if (!hasUncertaintyShapeIntent(value)) return false;
+ const keys = Object.keys(value).sort((a, b) => {
+ if (a < b) return -1;
+ if (a > b) return 1;
+ return 0;
+ });
+ if (keys.length !== 2) return false;
+ if (keys[0] !== 'distribution') return false;
+ if (keys[1] !== 'label') return false;
+ return (
+ typeof value['label'] === 'string' &&
+ isNumericDistribution(value['distribution'])
+ );
+}
diff --git a/lib/engine/version.ts b/lib/engine/version.ts
index c53fc2876298eedd8752e46238bcf6088fb75af8..1118a68d2ec42e6d0a046f36c828fe4787250b79 100644
--- a/lib/engine/version.ts
+++ b/lib/engine/version.ts
@@ -1,4 +1,4 @@
-export const engineBehaviorVersion = 'engine_behavior_v7' as const;
+export const engineBehaviorVersion = 'engine_behavior_v8' as const;
export const engineInputVersion = 'engine_input_v1' as const;