Repository navigation
Expand file tree
/
Copy pathnbackEngine.js
More file actions
1609 lines (1351 loc) · 57.9 KB
/
Copy pathnbackEngine.js
File metadata and controls
1609 lines (1351 loc) · 57.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
/**
* Author: BrainZag
* Repository: https://github.com/rqp314/BrainZag
* License: See LICENSE file
* Copyright (c) 2026 BrainZag
*
* Core algorithms: unified cognitive adaptive engine using
* Signal Detection Theory, Control Theory, Sequential Testing,
* Flow Theory, and Entropy based load management.
*
*/
// ============================================================================
// LOW-PASS FILTER (utility, used by main.js ReactionTimer)
// ============================================================================
class LowPassFilter {
constructor(factor = 0.1) {
this.factor = factor;
}
apply(currentValue, newSample) {
return currentValue * (1 - this.factor) + newSample * this.factor;
}
}
// ============================================================================
// WORKING MEMORY STATE TRACKER
// ============================================================================
class WorkingMemoryState {
constructor(n) {
this.n = n;
this.recentColors = [];
this.currentLoad = 0;
}
addColor(color) {
this.recentColors.push(color);
if (this.recentColors.length > this.n + 1) {
this.recentColors.shift();
}
this.currentLoad = new Set(this.recentColors).size;
}
getRecentColors() {
return [...this.recentColors];
}
getCurrentLoad() {
return this.currentLoad;
}
}
// ============================================================================
// D-PRIME (signal detection sensitivity)
// ============================================================================
function computeDPrime(hitRate, faRate) {
const cappedHitRate = Math.max(0.01, Math.min(0.99, hitRate));
const cappedFaRate = Math.max(0.01, Math.min(0.99, faRate));
function invNorm(p) {
const a1 = -3.969683028665376e1;
const a2 = 2.209460984245205e2;
const a3 = -2.759285104469687e2;
const a4 = 1.383577518672690e2;
const a5 = -3.066479806614716e1;
const a6 = 2.506628277459239e0;
const b1 = -5.447609879822406e1;
const b2 = 1.615858368580409e2;
const b3 = -1.556989798598866e2;
const b4 = 6.680131188771972e1;
const b5 = -1.328068155288572e1;
const c1 = -7.784894002430293e-3;
const c2 = -3.223964580411365e-1;
const c3 = -2.400758277161838e0;
const c4 = -2.549732539343734e0;
const c5 = 4.374664141464968e0;
const c6 = 2.938163982698783e0;
const d1 = 7.784695709041462e-3;
const d2 = 3.224671290700398e-1;
const d3 = 2.445134137142996e0;
const d4 = 3.754408661907416e0;
const pLow = 0.02425;
const pHigh = 1 - pLow;
let q, r;
if (p < pLow) {
q = Math.sqrt(-2 * Math.log(p));
return (((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
} else if (p <= pHigh) {
q = p - 0.5;
r = q * q;
return (((((a1 * r + a2) * r + a3) * r + a4) * r + a5) * r + a6) * q / (((((b1 * r + b2) * r + b3) * r + b4) * r + b5) * r + 1);
} else {
q = Math.sqrt(-2 * Math.log(1 - p));
return -(((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
}
}
return invNorm(cappedHitRate) - invNorm(cappedFaRate);
}
// ============================================================================
// ABILITY MODEL (rolling Bayesian d' as master ability signal)
// ============================================================================
class AbilityModel {
constructor() {
// Rolling window of recent trial outcomes for d' computation.
// Using a window instead of cumulative counts ensures theta responds
// to recent performance, not ancient history from 40 trials ago.
this.trialWindow = [];
this.windowSize = 30; // Last 30 trials for d' computation
// Rolling d' (theta) with EMA smoothing
this.theta = 1.5; // Start at moderate ability
this.thetaAlpha = 0.15; // EMA smoothing for theta
this.thetaWindow = []; // Last 20 theta values for trend
this.thetaWindowSize = 20;
// Reaction time tracking
this.rtWindow = [];
this.rtWindowSize = 20;
// Total trial count (cumulative, not windowed)
this.totalTrials = 0;
}
recordTrial(wasMatch, userClicked, reactionTime) {
this.totalTrials++;
// Store trial outcome in rolling window
this.trialWindow.push({ wasMatch, userClicked });
if (this.trialWindow.length > this.windowSize) {
this.trialWindow.shift();
}
// Compute d' from the rolling window using pseudo counts
let hits = 0, misses = 0, falseAlarms = 0, correctRejections = 0;
for (const t of this.trialWindow) {
if (t.wasMatch && t.userClicked) hits++;
else if (t.wasMatch && !t.userClicked) misses++;
else if (!t.wasMatch && t.userClicked) falseAlarms++;
else correctRejections++;
}
const targets = hits + misses;
const nonTargets = falseAlarms + correctRejections;
const hitRate = (hits + 0.5) / (targets + 1);
const faRate = (falseAlarms + 0.5) / (nonTargets + 1);
const rawDPrime = computeDPrime(hitRate, faRate);
// EMA smooth the theta
this.theta = this.theta * (1 - this.thetaAlpha) + rawDPrime * this.thetaAlpha;
// Store theta history for trend analysis
this.thetaWindow.push(this.theta);
if (this.thetaWindow.length > this.thetaWindowSize) {
this.thetaWindow.shift();
}
// Store RT
if (reactionTime > 0) {
this.rtWindow.push(reactionTime);
if (this.rtWindow.length > this.rtWindowSize * 2) { // TODO why do we do *2 here ?
this.rtWindow.shift();
}
}
}
// Slope of theta over recent history (positive = improving)
getThetaTrend() {
const h = this.thetaWindow;
if (h.length < 5) return 0;
// Simple linear regression slope
const n = h.length;
let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
for (let i = 0; i < n; i++) {
sumX += i;
sumY += h[i];
sumXY += i * h[i];
sumX2 += i * i;
}
const denom = n * sumX2 - sumX * sumX;
if (denom === 0) return 0;
return (n * sumXY - sumX * sumY) / denom;
}
// RT statistics
getRTStats() {
const rts = this.rtWindow.slice(-this.rtWindowSize);
if (rts.length < 3) {
return { median: 800, p90: 1200, cv: 0.2 };
}
const sorted = [...rts].sort((a, b) => a - b);
const median = sorted[Math.floor(sorted.length / 2)];
const p90 = sorted[Math.floor(sorted.length * 0.9)];
const mean = rts.reduce((a, b) => a + b, 0) / rts.length;
const variance = rts.reduce((s, rt) => s + (rt - mean) ** 2, 0) / rts.length;
const cv = mean > 0 ? Math.sqrt(variance) / mean : 0;
return { median, p90, cv };
}
// Fatigue composite: RT tail growth + RT variability + negative theta trend
// Calibrated so normal human RT variability (CV 0.25-0.35, tail ratio 1.3-1.5)
// reads near 0%. Only genuine fatigue signals (CV > 0.4, tail > 1.7) register.
getFatigueIndex() {
const rt = this.getRTStats();
const trend = this.getThetaTrend();
// RT tail ratio: normal range is 1.2-1.5, fatigue starts at 1.6+
const tailRatio = rt.median > 0 ? rt.p90 / rt.median : 1.0;
const tailComponent = Math.max(0, (tailRatio - 1.6) / 0.6); // 0 at 1.6, 1.0 at 2.2
// CV component: normal human CV is 0.2-0.35, fatigue starts at 0.4+
const cvComponent = Math.max(0, (rt.cv - 0.4) / 0.3); // 0 at 0.4, 1.0 at 0.7
// Trend component: negative trend = fatigued
const trendComponent = Math.max(0, -trend * 10);
return Math.min(1.0, (tailComponent + cvComponent + trendComponent) / 3);
}
// Flow score: good ability + low variability + positive trend.
// Mastery at steady state: low-mid 70s (small positive trend pushes into 80s).
// Strong improvement phase: 90s+. Perfect across all axes: 100%.
// Note: while improving your flow score will be higher compared to sustaining perfect score
getFlowScore() {
const rt = this.getRTStats();
const trend = this.getThetaTrend();
// Normalize theta: 0 at theta=0, 1.0 at theta=2.5
const normalizedTheta = Math.max(0, Math.min(1, this.theta / 2.5));
// CV bonus: no penalty until CV=0.15 (normal human noise floor).
// Then linear to 0 at CV=0.60. CV=0.25 earns 0.78, CV=0.35 earns 0.56.
const cvBonus = Math.max(0, Math.min(1, 1 - Math.max(0, rt.cv - 0.15) / 0.45));
// Trend bonus normalized to [0,1]: saturates at slope 0.05/trial.
const trendBonus = Math.max(0, Math.min(1, trend * 20));
// Weights: theta 55%, CV 25%, trend 20%
return Math.min(1.0, normalizedTheta * 0.55 + cvBonus * 0.25 + trendBonus * 0.20);
}
// Map theta to 0..1 for backward compatibility with performanceEMA display
getNormalizedPerformance() {
// theta 0 maps to ~0.3, theta 1.8 maps to ~0.75, theta 3.5 maps to ~1.0
return Math.max(0, Math.min(1, 0.3 + this.theta * 0.2));
}
// Get current SDT counts from the rolling window
getSDTCounts() {
let hits = 0, misses = 0, falseAlarms = 0, correctRejections = 0;
for (const t of this.trialWindow) {
if (t.wasMatch && t.userClicked) hits++;
else if (t.wasMatch && !t.userClicked) misses++;
else if (!t.wasMatch && t.userClicked) falseAlarms++;
else correctRejections++;
}
return { hits, misses, falseAlarms, correctRejections };
}
getStats() {
const rt = this.getRTStats();
const sdt = this.getSDTCounts();
return {
theta: this.theta,
thetaTrend: this.getThetaTrend(),
flowScore: this.getFlowScore(),
fatigueIndex: this.getFatigueIndex(),
rtMedian: rt.median,
rtP90: rt.p90,
rtCV: rt.cv,
totalTrials: this.totalTrials,
hits: sdt.hits,
misses: sdt.misses,
falseAlarms: sdt.falseAlarms,
correctRejections: sdt.correctRejections
};
}
reset() {
this.trialWindow = [];
this.theta = 1.5;
this.thetaWindow = [];
this.rtWindow = [];
this.totalTrials = 0;
}
}
// ============================================================================
// DIFFICULTY CONTROLLER (PI controller targeting ideal engagement zone)
// ============================================================================
class DifficultyController {
constructor(n) {
this.n = n;
// PI controller state
this.targetTheta = 1.8; // Ideal engagement zone
this.Kp = 0.3; // Proportional gain
this.Ki = 0.05; // Integral gain
this.integral = 0;
this.integralMax = 3.0; // Anti windup clamp
// Output variables
// Start at 0 = minimum load (2 unique colors). Player must earn higher load.
this.targetEntropy = 0.0;
this.matchRate = 0.30; // Dynamic match rate
this.stimulusInterval = 1.0; // Speed multiplier (1.0 = normal)
// TEMPORAL STRUCTURE ENTROPY (TSE)
// Controls transition unpredictability independent of unique color count.
// Low TSE = long runs of same color, predictable switching rhythm.
// High TSE = frequent switching, near random transitions.
// Starts at 0 after N increase so the player can stabilize the
// expanded sliding buffer before facing transition chaos.
// At low TSE the repeat bias naturally produces runs of ~N length
// because the n back constraint forces a switch once the buffer
// catches up to the run color.
this.tse = 0.0;
this.tseClimbRate = 0.03; // Half of entropy climb: TSE is a phase clock, not a sprint
this.tseDropRate = 0.06; // 2x faster to drop (same asymmetry)
// Unique colors (derived from entropy)
this.maxUniqueColors = n + 1;
this.minUniqueColors = Math.max(2, n - 1);
this.currentUniqueColors = this.minUniqueColors;
// N-adaptive step hold: scale with the color range so higher N
// levels dont require unreachable trial counts to progress.
// N=2: range=1, hold=6 increase / 3 decrease
// N=3: range=2, hold=3 increase / 2 decrease
// N=8: range=7, hold=2 increase / 1 decrease
const colorRange = this.maxUniqueColors - this.minUniqueColors;
this.stepHoldIncrease = Math.max(2, Math.round(6 / colorRange));
this.stepHoldDecrease = Math.max(1, Math.round(3 / colorRange));
this.stepHoldCounter = 0;
this.pendingUniqueColors = this.minUniqueColors;
// Post level phase system: after N increases, K expansion is gated
// behind three TSE phases to prevent overwhelming the player.
// Phase 1 (TSE < 0.5): entropy clamped, K fixed at min
// Phase 2 (TSE 0.5..0.75): entropy grows slowly, K capped at min+1
// Phase 3 (TSE > 0.75): entropy fully adaptive, K can grow +1 per cooldown
// Once TSE reaches 1.0, phases graduate and restrictions lift permanently
// for this N level so a temporary TSE dip doesnt re-clamp the player.
this.kIncreaseCooldown = 0; // Trials remaining before next K increase allowed
this.phaseGraduated = false; // Set true when TSE first reaches 1.0
// N-adaptive K cooldown: higher N has more K steps to traverse in phase 3,
// so shorter cooldowns prevent the tail from dragging.
// N=2: range=1, cooldown=12 (only 1 step total, phase 2 covers it)
// N=3: range=2, cooldown=6
// N=4: range=3, cooldown=4
// N=7: range=6, cooldown=4
this.kCooldownTrials = Math.max(4, Math.round(12 / colorRange));
// N-adaptive entropy climb rate: higher N means larger range to traverse,
// so the per trial delta needs to be proportionally larger.
// Floor of 0.06 ensures N=2 (range=1) can still reach max in 40 trials.
// N=2: range=1, climbRate=0.06, dropRate=0.12
// N=3: range=2, climbRate=0.06, dropRate=0.12
// N=4: range=3, climbRate=0.075, dropRate=0.15
// N=8: range=7, climbRate=0.12, dropRate=0.24
this.entropyClimbRate = Math.min(0.12, Math.max(0.06, 0.03 + 0.015 * colorRange));
this.entropyDropRate = this.entropyClimbRate * 2; // Always 2x faster to drop
// No LPF on entropy. The step hold counter is the sole gate preventing
// jumpy color count changes. Direct accumulation ensures a flawless player
// can traverse the full color range within a 40 trial round.
// Sustain gate: after K increases, require sustained good performance
// before allowing the next K increase. Prevents "touch and advance" pattern.
this.sustainTrialsRequired = 8; // base sustain window
this.sustainTrialsRemaining = 0; // countdown; 0 = no active sustain
this.sustainKTarget = 0; // the K value being sustained
this.sustainFailed = false; // set true if performance drops during sustain
this.fallbackCount = 0; // how many times player fell back to this K
this.sustainDoubled = false; // whether sustain was already doubled (cap at 1x doubling)
}
update(abilityModel) {
const theta = abilityModel.theta;
const trend = abilityModel.getThetaTrend();
const fatigue = abilityModel.getFatigueIndex();
const flow = abilityModel.getFlowScore();
// PI controller: positive error = player below target, negative = above target
const error = this.targetTheta - theta;
this.integral += error;
this.integral = Math.max(-this.integralMax, Math.min(this.integralMax, this.integral));
let adjustment = this.Kp * error + this.Ki * this.integral;
// Flow boost: when performing well and improving, push slightly harder
if (theta > 1.6 && trend > 0.005) {
adjustment -= 0.1; // Negative adjustment = increase difficulty
}
// Recovery: when theta trending down and fatigue rising, ease off
if (trend < -0.01 && fatigue > 0.5) {
adjustment += 0.15; // Positive adjustment = decrease difficulty
}
// ── SUSTAIN GATE CHECK ───────────────────────────────────────────
// After a K increase, the player must sustain theta >= 85% of target
// for sustainTrialsRequired trials. If performance drops, K reverts.
if (this.sustainTrialsRemaining > 0) {
this.sustainTrialsRemaining--;
if (theta < this.targetTheta * 0.85) {
this.sustainFailed = true;
}
if (this.sustainFailed) {
// Revert K increase
if (this.currentUniqueColors > this.minUniqueColors) {
this.currentUniqueColors--;
this.fallbackCount++;
}
this.sustainTrialsRemaining = 0;
this.sustainFailed = false;
this.sustainKTarget = 0;
} else if (this.sustainTrialsRemaining === 0) {
// Sustained successfully, consolidate
this.fallbackCount = 0;
this.sustainKTarget = 0;
}
}
// ── THREE PHASE POST LEVEL SYSTEM ──────────────────────────────────
// After N increases TSE starts at 0 and gates both entropy growth and
// K (unique color) expansion through three phases so the player is
// never hit with too many new demands at once.
// Phase 1 (TSE < 0.5): Span stabilization. Entropy hard clamped, K at min.
// Phase 2 (TSE 0.5..0.75): Structural stabilization. Entropy grows at
// 25% rate, K allowed up to min+1 only.
// Phase 3 (TSE > 0.75): Symbol expansion. Entropy fully adaptive,
// K can increase +1 at a time with cooldown between jumps.
// Graduate once TSE reaches 1.0: player has fully adapted at this N
if (this.tse >= 1.0) this.phaseGraduated = true;
const phase = this.phaseGraduated ? 3 : this.tse < 0.5 ? 1 : this.tse < 0.75 ? 2 : 3;
// Map adjustment to entropy delta
// Positive adjustment (struggling) = decrease entropy, negative (excelling) = increase
// Asymmetric: increasing is slower than decreasing (harder to earn, easier to lose)
let entropyDelta;
if (adjustment < 0) {
entropyDelta = -adjustment * this.entropyClimbRate;
} else {
entropyDelta = -adjustment * this.entropyDropRate;
}
// Phase gating on entropy growth (drops are never gated, player can always lose difficulty)
if (entropyDelta > 0) {
if (phase === 1) {
entropyDelta = 0; // Hard clamp: no entropy growth during span stabilization
} else if (phase === 2) {
entropyDelta *= 0.25; // 25% growth rate during structural stabilization
}
// Phase 3: full rate
}
// Post graduation softening: after phases lift, if TSE dips below 0.7
// the player is struggling with transition chaos. Boost entropy drops
// by 50% so difficulty sheds faster without re-engaging phase clamps.
if (this.phaseGraduated && this.tse < 0.7 && entropyDelta < 0) {
entropyDelta *= 1.5;
}
this.targetEntropy = Math.max(0, Math.min(1, this.targetEntropy + entropyDelta));
// ── KNOB 1: UNIQUE COLORS ──────────────────────────────────────────
// Primary difficulty lever. Controls how many distinct colors appear
// in the players attention window (n+1). More unique colors = harder
// to discriminate matches from noise.
// Entropy (0..1) maps linearly to the color range [min..max].
// Step hold gate prevents flickering: the candidate must sustain for
// several consecutive trials before the actual color count commits.
// Asymmetric: harder to earn (holdIncrease) than to lose (holdDecrease).
const range = this.maxUniqueColors - this.minUniqueColors;
const targetFloat = this.minUniqueColors + this.targetEntropy * range;
const candidateColors = Math.round(Math.max(this.minUniqueColors, Math.min(this.maxUniqueColors, targetFloat)));
// Tick down K increase cooldown
if (this.kIncreaseCooldown > 0) this.kIncreaseCooldown--;
if (candidateColors !== this.currentUniqueColors) {
if (candidateColors === this.pendingUniqueColors) {
this.stepHoldCounter++;
} else {
this.pendingUniqueColors = candidateColors;
this.stepHoldCounter = 1;
}
const requiredHold = candidateColors > this.currentUniqueColors
? this.stepHoldIncrease
: this.stepHoldDecrease;
if (this.stepHoldCounter >= requiredHold) {
const isIncrease = candidateColors > this.currentUniqueColors;
if (isIncrease) {
// Block K increases while sustain gate is active
if (this.sustainTrialsRemaining > 0) {
// blocked, sustaining current K level
// Phase 1: K locked at minimum
} else if (phase === 1) {
// blocked
// Phase 2: K capped at min+1
} else if (phase === 2 && this.currentUniqueColors >= this.minUniqueColors + 1) {
// blocked, already at phase 2 ceiling
// Phase 3: allow +1 at a time with cooldown between jumps
} else if (phase === 3 && this.kIncreaseCooldown > 0) {
// blocked, cooling down between K jumps
} else {
// Allowed: commit +1 only (never skip a step)
this.currentUniqueColors = this.currentUniqueColors + 1;
this.stepHoldCounter = 0;
if (phase === 3) this.kIncreaseCooldown = this.kCooldownTrials;
// Drop TSE so the player gets predictable transitions while
// adapting to the new color vocabulary. Larger drop at lower K
// (more room for transition chaos), smaller near max K (window
// constraint already limits run length).
const kProgress = (this.currentUniqueColors - this.minUniqueColors)
/ (this.maxUniqueColors - this.minUniqueColors);
const tseRetain = 0.4 + 0.5 * kProgress;
this.tse *= tseRetain;
// Activate sustain gate for the new K level
let sustainWindow = this.sustainTrialsRequired;
if (this.fallbackCount > 0 && !this.sustainDoubled) {
sustainWindow *= 2;
this.sustainDoubled = true;
}
this.sustainTrialsRemaining = sustainWindow;
this.sustainKTarget = this.currentUniqueColors;
}
} else {
// K decreases are never gated
this.currentUniqueColors = candidateColors;
this.stepHoldCounter = 0;
}
}
} else {
this.stepHoldCounter = 0;
}
// ── KNOB 2: MATCH RATE ───────────────────────────────────────────
// Controls how often n-back matches appear. More matches = easier
// (detecting a match is simpler than correctly inhibiting a non match).
// Struggling players get more matches (up to 40%) for more winnable
// trials. Strong players get fewer (down to 25%) forcing more
// correct rejection demands, which is the harder cognitive skill.
const matchAdj = Math.max(-0.05, Math.min(0.10, adjustment * 0.05));
this.matchRate = Math.max(0.25, Math.min(0.40, 0.30 + matchAdj));
// ── KNOB 3: STIMULUS INTERVAL (speed) ────────────────────────────
// Multiplier on display timing. < 1.0 = faster, > 1.0 = slower.
// In flow (high flow, low fatigue): speed up slightly to maintain
// engagement and prevent boredom. Under fatigue: slow down to give
// the player more processing time and reduce overwhelm.
if (flow > 0.6 && fatigue < 0.3) {
this.stimulusInterval = 0.97;
} else if (fatigue > 0.6) {
this.stimulusInterval = 1.04;
} else {
this.stimulusInterval = 1.0;
}
// ── KNOB 4: TEMPORAL STRUCTURE ENTROPY (TSE) ─────────────────────
// Controls transition unpredictability. Increases when player excels,
// decreases when struggling. Acts as the phase clock for the post level
// system: TSE < 0.5 = phase 1, 0.5..0.75 = phase 2, > 0.75 = phase 3.
// This gates both entropy growth and K expansion so difficulty ramps
// organically after an N increase.
let tseDelta;
if (adjustment < 0) {
// Player excelling: increase TSE (more transition chaos)
tseDelta = -adjustment * this.tseClimbRate;
} else {
// Player struggling: decrease TSE (more predictable transitions)
tseDelta = -adjustment * this.tseDropRate;
}
this.tse = Math.max(0, Math.min(1, this.tse + tseDelta));
}
getTargetUniqueColors() {
return this.currentUniqueColors;
}
getCurrentUniqueColors() {
return this.currentUniqueColors;
}
getMaxUniqueColors() {
return this.maxUniqueColors;
}
getMatchRate() {
return this.matchRate;
}
// Called when SPRT stops a session for poor performance.
// Aggressively reduces difficulty so the next round starts easier.
onSessionStopped() {
// Drop entropy by half (fast difficulty reduction)
this.targetEntropy = Math.max(0, this.targetEntropy * 0.5);
// Drop unique colors by 1 immediately (bypass step hold)
if (this.currentUniqueColors > this.minUniqueColors) {
this.currentUniqueColors--;
}
// Reset PI integral so accumulated "push harder" pressure is cleared
this.integral = 0;
this.stepHoldCounter = 0;
// Ease match rate toward easier
this.matchRate = Math.min(0.40, this.matchRate + 0.05);
// Drop TSE aggressively (predictable transitions for recovery)
this.tse = Math.max(0, this.tse * 0.3);
// Reset K cooldown so recovery doesnt stall behind a pending timer
this.kIncreaseCooldown = 0;
}
getStats() {
return {
currentUniqueColors: this.currentUniqueColors,
maxUniqueColors: this.maxUniqueColors,
minUniqueColors: this.minUniqueColors,
targetEntropy: this.targetEntropy,
tse: this.tse,
tsePhase: this.phaseGraduated ? 3 : this.tse < 0.5 ? 1 : this.tse < 0.75 ? 2 : 3,
matchRate: this.matchRate,
stimulusInterval: this.stimulusInterval,
piError: this.targetTheta - (this.integral / Math.max(1, Math.abs(this.integral)) * this.Ki),
piIntegral: this.integral
};
}
}
// ============================================================================
// SPRT STOPPER (Sequential Probability Ratio Test for session stopping)
// ============================================================================
class SPRTStopper {
constructor() {
// Hypotheses about theta
this.theta0 = 1.5; // H0: acceptable performance
this.theta1 = 0.8; // H1: poor performance
this.logLR = 0; // Cumulative log likelihood ratio
// Decision boundaries (alpha=0.10, beta=0.15 for faster stopping)
// logLR accumulates log(P(data|H1) / P(data|H0))
// Positive logLR = evidence for H1 (poor), negative = evidence for H0 (good)
this.stopBound = Math.log((1 - 0.15) / 0.10); // ~2.14, accept H1 (poor, stop session)
this.acceptBound = Math.log(0.15 / (1 - 0.10)); // ~-1.79, accept H0 (performing OK)
this.decision = 'continue'; // 'continue', 'stop'
this.trialsRecorded = 0;
}
recordTrial(correct, wasMatch, userClicked) {
this.trialsRecorded++;
// Likelihood of this outcome under H0 (theta=1.5) vs H1 (theta=0.8)
// For targets: P(hit|theta) approximated from d' model
// For non targets: P(correct rejection|theta)
// Using simplified logistic mapping from theta to accuracy
const p0 = this.thetaToAccuracy(this.theta0, wasMatch);
const p1 = this.thetaToAccuracy(this.theta1, wasMatch);
const pObserved0 = correct ? p0 : (1 - p0);
const pObserved1 = correct ? p1 : (1 - p1);
// Accumulate log likelihood ratio (H1 vs H0)
// Correct trials push logLR negative (toward H0), errors push positive (toward H1)
if (pObserved0 > 0 && pObserved1 > 0) {
let delta = Math.log(pObserved1 / pObserved0);
// Not clicking on a non match is passive (no active decision), so discount it heavily.
// Without this, an overwhelmed player who stops clicking gets "credit" for correct
// rejections that wash out the signal from missed targets.
if (!wasMatch && !userClicked) {
delta *= 0.25;
}
this.logLR += delta;
}
// Check boundaries
if (this.logLR >= this.stopBound) {
this.decision = 'stop'; // Strong evidence for H1: poor performance, stop session
} else if (this.logLR <= this.acceptBound) {
this.decision = 'continue'; // Strong evidence for H0: performing OK, reset and keep monitoring
this.logLR = 0;
}
return this.decision;
}
// Map theta (d') to expected accuracy for a trial type
thetaToAccuracy(theta, isTarget) {
// For targets: hit rate increases with theta
// For non targets: correct rejection rate increases with theta
// Using logistic approximation: accuracy = 1 / (1 + exp(-(theta-offset)*scale))
if (isTarget) {
return 1 / (1 + Math.exp(-(theta - 0.5) * 1.5));
} else {
return 1 / (1 + Math.exp(-(theta - 0.2) * 1.5));
}
}
shouldStop() {
// Need minimum trials before allowing stop
if (this.trialsRecorded < 8) return false;
return this.decision === 'stop';
}
getStatus() {
return {
logLR: this.logLR,
stopBound: this.stopBound,
acceptBound: this.acceptBound,
decision: this.decision,
trialsRecorded: this.trialsRecorded
};
}
reset() {
this.logLR = 0;
this.decision = 'continue';
this.trialsRecorded = 0;
}
}
// ============================================================================
// COLOR SEQUENCE GENERATOR (with rank based weighting)
// ============================================================================
class ColorSequenceGenerator {
constructor(n, availableColors) {
this.n = n;
this.availableColors = availableColors;
this.memoryState = new WorkingMemoryState(n);
this.activeSet = null;
this.swapProbability = 0.7;
}
// Compute Shannon entropy of the current memory window (for stats/monitoring)
computeEntropy(window) {
if (!window || window.length === 0) return 0;
const counts = {};
for (const c of window) {
counts[c] = (counts[c] || 0) + 1;
}
let entropy = 0;
const n = window.length;
for (const c in counts) {
const p = counts[c] / n;
if (p > 0) entropy -= p * Math.log2(p);
}
return entropy;
}
isValidMatchColor(currentWindow, candidate, target) {
// A match drops the oldest color and re-adds the n-back color.
// Only one color is ever removed so unique count can only stay the same (= target)
// or drop by exactly 1 (= target-1). target-2 or lower is impossible.
// NEVER allow target+1: matches cannot introduce a new color.
const windowSize = this.n + 1;
const simulated = [...currentWindow, candidate].slice(-windowSize);
const uniqueCount = new Set(simulated).size;
return uniqueCount <= target;
}
isValidNextColor(currentWindow, candidate, target) {
// Simulate what the window will look like after adding this candidate
const windowSize = this.n + 1;
const simulated = [...currentWindow, candidate].slice(-windowSize);
const uniqueCount = new Set(simulated).size;
return uniqueCount === target;
}
pickNextWithConstraint(currentWindow, candidates, target) {
// Filter candidates to only those that maintain the constraint
const valid = candidates.filter(c =>
this.isValidNextColor(currentWindow, c, target)
);
if (valid.length > 0) {
return valid[Math.floor(Math.random() * valid.length)];
}
// Hard fallback: force repair if no valid candidates
return this.forceRepair(currentWindow, target);
}
forceRepair(currentWindow, target) {
// If we're under target, introduce a new color
const windowSize = this.n + 1;
const recentWindow = currentWindow.slice(-windowSize);
const windowSet = new Set(recentWindow);
if (windowSet.size < target) {
// Try to introduce a new color not in window
const available = this.availableColors
.map(c => c.name)
.filter(c => !windowSet.has(c));
if (available.length > 0) {
return available[Math.floor(Math.random() * available.length)];
}
}
// If we're at or over target, repeat existing to consolidate
return [...windowSet][0];
}
generateNextColor(targetUniqueColors, shouldMatch, nBackColor, isForced = false, tse = 1.0) {
const currentWindow = this.memoryState.recentColors;
// Ensure target is at least 2
const target = Math.max(2, targetUniqueColors);
// Reset active set if target changed
if (this.lastTarget !== undefined && this.lastTarget !== target) {
this.activeSet = null;
}
this.lastTarget = target;
// If this is a match trial, validate the N-back color maintains constraint
if (shouldMatch && nBackColor) {
if (isForced) {
// Hard guarantee: always return the n-back color.
// Matches only reduce or maintain unique count so no constraint is violated.
return nBackColor;
} else {
// Normal match: only return n-back color if constraint is satisfied.
// Falls through to non-match generation if validation fails.
if (this.isValidMatchColor(currentWindow, nBackColor, target)) {
return nBackColor;
}
}
}
// When NOT creating a match, exclude the n-back color to avoid accidental matches
const excludeColor = !shouldMatch ? nBackColor : null;
// ── TSE REPEAT BIAS ──────────────────────────────────────────────
// Low TSE biases toward repeating the previous color, creating longer
// runs and more predictable transitions. At TSE=1.0 this never fires
// (pure random, current behavior). Max repeat bias = 1 - 1/(N+1) so
// mean run targets the full window width. The n back constraint hard
// caps runs at N (n back catches up), giving two cooperating forces:
// probability aims to fill the window, n back trims at the right point.
// N=2: p=0.67 mean=3. N=4: p=0.80 mean=5. N=7: p=0.875 mean=8.
if (tse < 1.0 && currentWindow.length > 0) {
const lastColor = currentWindow[currentWindow.length - 1];
if (lastColor && lastColor !== excludeColor) {
const repeatProb = (1 - 1 / (this.n + 1)) * (1 - tse);
if (Math.random() < repeatProb && this.isValidNextColor(currentWindow, lastColor, target)) {
return lastColor;
}
}
}
// ALGORITHM: Three cases based on targetUniqueColors (K)
// Case 1: K = 2 (minimum) - keep patterns simple, repeat existing
// Case 2: K = n+1 (maximum) - force all different colors
// Case 3: K = in between - maintain active set of K colors
let next;
if (target === 2) { // Case 1: K = 2 (minimum load)
next = this.generateForMinLoad(currentWindow, excludeColor, target);
} else if (target === this.n + 1) { // Case 2: K = n+1 (maximum load)
next = this.generateForMaxLoad(currentWindow, excludeColor, target);
} else { // Case 3: K = in between (use active set)
next = this.generateForMidLoad(currentWindow, excludeColor, target);
}
return next;
}
generateForMinLoad(currentWindow, excludeColor, target) {
// K = 2: Maintain exactly 2 unique colors using active pair strategy
const uniqueColors = [...new Set(currentWindow)];
// If we only have 1 unique color, introduce a second
if (uniqueColors.length < 2) {
// Build list of candidates (all colors not in window, except excluded)
const windowSet = new Set(currentWindow);
const candidates = this.availableColors
.map(c => c.name)
.filter(c => !windowSet.has(c) && c !== excludeColor);
if (candidates.length > 0) {
const newColor = this.pickNextWithConstraint(currentWindow, candidates, target);
// Initialize active pair
if (uniqueColors.length === 1) {
this.activeSet = [uniqueColors[0], newColor];
} else {
this.activeSet = [newColor];
}
return newColor;
}
}
// We have 2 or more unique colors - maintain exactly 2
// Initialize active set if not set
if (!this.activeSet || this.activeSet.length !== 2) {
this.activeSet = uniqueColors.slice(0, 2);
}
// Occasionally swap one color for novelty
if (Math.random() < this.swapProbability) {
const keep = this.activeSet[Math.floor(Math.random() * this.activeSet.length)];
const availableForSwap = this.availableColors
.map(c => c.name)
.filter(c => !this.activeSet.includes(c));
if (availableForSwap.length > 0) {
// Validate the replacement maintains constraint
const validReplacements = availableForSwap.filter(replacement =>
this.isValidNextColor(currentWindow, replacement, target)
);
if (validReplacements.length > 0) {
const replacement = validReplacements[Math.floor(Math.random() * validReplacements.length)];
this.activeSet = [keep, replacement];
return replacement;
}
}
}
// Normal behavior: stay within active pair
// Build list of candidates from active set (excluding n-back if needed)
const candidates = excludeColor
? this.activeSet.filter(c => c !== excludeColor)
: this.activeSet;
// Use constraint validation to pick
return this.pickNextWithConstraint(currentWindow, candidates, target);
}
generateForMaxLoad(currentWindow, excludeColor, target) {
// K = n+1: Force all different colors in the window
// Pick a color that's NOT in the current window (and not excluded)
const windowSet = new Set(currentWindow);
const candidates = this.availableColors
.map(c => c.name)
.filter(c => !windowSet.has(c) && c !== excludeColor);
// Use constraint validation to pick
return this.pickNextWithConstraint(currentWindow, candidates, target);
}
generateForMidLoad(currentWindow, excludeColor, target) {
// K = between 2 and n+1: Maintain active set of K colors
const uniqueColors = [...new Set(currentWindow)];
// If we have fewer than K unique colors, introduce new ones
if (uniqueColors.length < target) {
const windowSet = new Set(currentWindow);
const candidates = this.availableColors
.map(c => c.name)
.filter(c => !windowSet.has(c) && c !== excludeColor);
if (candidates.length > 0) {
const newColor = this.pickNextWithConstraint(currentWindow, candidates, target);
// Add to active set
if (!this.activeSet) {
this.activeSet = [...uniqueColors, newColor];
} else {
this.activeSet = [...new Set([...this.activeSet, newColor])].slice(0, target);
}
return newColor;
}
}
// Initialize or update active set to match target size
if (!this.activeSet || this.activeSet.length !== target) {
this.activeSet = uniqueColors.slice(0, target);