totemheart 0.1.1 → 0.1.3
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/README.md +26 -14
- package/package.json +64 -63
- package/src/Totemheart.js +297 -5
- package/src/cognition/AnticipatoryAffect.js +58 -0
- package/src/cognition/EgoDepletionBudget.js +81 -0
- package/src/cognition/MotivationalConflict.js +62 -0
- package/src/cognition/ValueHierarchy.js +77 -0
- package/src/core/CommitmentDevice.js +74 -0
- package/src/core/MoralInjury.js +61 -0
- package/src/core/OpponentProcess.js +56 -0
- package/src/embodiment/InteroceptivePredictionError.js +47 -0
- package/src/neurochemistry/ArousalKalmanFilter.js +10 -1
- package/src/neurochemistry/CircadianRhythm.js +21 -0
- package/src/neurochemistry/DopaminergicEngine.js +15 -3
- package/src/neurochemistry/SleepPressure.js +74 -0
- package/src/neurochemistry/SubjectiveTimeEngine.js +54 -0
- package/src/social/Attachment.js +21 -0
- package/src/social/ForgettingCurve.js +16 -1
- package/src/social/GriefEngine.js +105 -0
- package/src/social/IdentityThreatMonitor.js +53 -0
- package/src/social/JealousyTriangle.js +52 -0
- package/src/social/NostalgiaEngine.js +68 -0
- package/src/social/PainSocialOverlap.js +46 -0
- package/src/social/RepairProtocol.js +90 -0
- package/src/social/ShameGuiltSplit.js +74 -0
- package/src/social/SocialBaselineTheory.js +37 -0
- package/src/version.js +1 -1
package/src/Totemheart.js
CHANGED
|
@@ -90,6 +90,25 @@ import { TriggerSentinel } from './core/TriggerSentinel.js'
|
|
|
90
90
|
import { HebbianPlasticity } from './core/HebbianPlasticity.js'
|
|
91
91
|
import { RemConsolidation } from './cognition/RemConsolidation.js'
|
|
92
92
|
|
|
93
|
+
import { GriefEngine } from './social/GriefEngine.js'
|
|
94
|
+
import { ShameGuiltSplit } from './social/ShameGuiltSplit.js'
|
|
95
|
+
import { RepairProtocol } from './social/RepairProtocol.js'
|
|
96
|
+
import { JealousyTriangle } from './social/JealousyTriangle.js'
|
|
97
|
+
import { NostalgiaEngine } from './social/NostalgiaEngine.js'
|
|
98
|
+
import { PainSocialOverlap } from './social/PainSocialOverlap.js'
|
|
99
|
+
import { IdentityThreatMonitor } from './social/IdentityThreatMonitor.js'
|
|
100
|
+
import { SocialBaselineTheory } from './social/SocialBaselineTheory.js'
|
|
101
|
+
import { SubjectiveTimeEngine } from './neurochemistry/SubjectiveTimeEngine.js'
|
|
102
|
+
import { SleepPressure } from './neurochemistry/SleepPressure.js'
|
|
103
|
+
import { AnticipatoryAffect } from './cognition/AnticipatoryAffect.js'
|
|
104
|
+
import { MotivationalConflict } from './cognition/MotivationalConflict.js'
|
|
105
|
+
import { EgoDepletionBudget } from './cognition/EgoDepletionBudget.js'
|
|
106
|
+
import { ValueHierarchy } from './cognition/ValueHierarchy.js'
|
|
107
|
+
import { CommitmentDevice } from './core/CommitmentDevice.js'
|
|
108
|
+
import { MoralInjury } from './core/MoralInjury.js'
|
|
109
|
+
import { OpponentProcess } from './core/OpponentProcess.js'
|
|
110
|
+
import { InteroceptivePredictionError } from './embodiment/InteroceptivePredictionError.js'
|
|
111
|
+
|
|
93
112
|
function clamp01( v ) {
|
|
94
113
|
|
|
95
114
|
return Math.max( 0, Math.min( 1, v ) )
|
|
@@ -219,6 +238,26 @@ export class Totemheart {
|
|
|
219
238
|
this.hebbianPlasticity = new HebbianPlasticity()
|
|
220
239
|
this.remConsolidation = new RemConsolidation()
|
|
221
240
|
|
|
241
|
+
this.griefEngine = new GriefEngine()
|
|
242
|
+
this.shameGuiltSplit = new ShameGuiltSplit()
|
|
243
|
+
this.repairProtocol = new RepairProtocol()
|
|
244
|
+
this.jealousyTriangle = new JealousyTriangle()
|
|
245
|
+
this.nostalgiaEngine = new NostalgiaEngine()
|
|
246
|
+
this.painSocialOverlap = new PainSocialOverlap()
|
|
247
|
+
this.identityThreatMonitor = new IdentityThreatMonitor()
|
|
248
|
+
this.socialBaselineTheory = new SocialBaselineTheory()
|
|
249
|
+
this.subjectiveTimeEngine = new SubjectiveTimeEngine()
|
|
250
|
+
this.sleepPressure = new SleepPressure()
|
|
251
|
+
this.anticipatoryAffect = new AnticipatoryAffect()
|
|
252
|
+
this.motivationalConflict = new MotivationalConflict()
|
|
253
|
+
this.egoDepletionBudget = new EgoDepletionBudget()
|
|
254
|
+
this.valueHierarchy = new ValueHierarchy()
|
|
255
|
+
this.commitmentDevice = new CommitmentDevice()
|
|
256
|
+
this.commitmentDevice.make( 'be_composed', 'Mantener la compostura incluso bajo presión' )
|
|
257
|
+
this.moralInjury = new MoralInjury()
|
|
258
|
+
this.opponentProcess = new OpponentProcess()
|
|
259
|
+
this.interoceptivePredictionError = new InteroceptivePredictionError()
|
|
260
|
+
|
|
222
261
|
this.turnCounter = 0
|
|
223
262
|
this.allostasisStuckTicks = 0
|
|
224
263
|
this._clockHandle = null
|
|
@@ -324,6 +363,15 @@ export class Totemheart {
|
|
|
324
363
|
// BEFORE this turn is processed. The AI doesn't wake up exactly where it left
|
|
325
364
|
// off — recent memories' peak arousal cools, stale associations prune, and the
|
|
326
365
|
// felt state decays by the REAL elapsed hours instead of picking up mid-spike.
|
|
366
|
+
// Sleep pressure (real Process S, Borbély 1982) — accumulate real elapsed
|
|
367
|
+
// wall-clock ms since the last processed turn BEFORE remConsolidation's own
|
|
368
|
+
// bookkeeping below overwrites lastTurnAt, then let an actual REM sweep (not
|
|
369
|
+
// a plain tick) dissipate it — the same real "awake accumulates, sleep clears"
|
|
370
|
+
// distinction CircadianRhythm.sleepDebt already uses for its own accumulator.
|
|
371
|
+
const nowForSleep = Date.now()
|
|
372
|
+
const elapsedSinceLastTurn = this.remConsolidation.lastTurnAt !== null ? nowForSleep - this.remConsolidation.lastTurnAt : 0
|
|
373
|
+
if ( elapsedSinceLastTurn > 0 ) this.sleepPressure.accumulate( elapsedSinceLastTurn )
|
|
374
|
+
|
|
327
375
|
this._lastRemReport = null
|
|
328
376
|
if ( this.remConsolidation.shouldTrigger() ) {
|
|
329
377
|
|
|
@@ -339,6 +387,7 @@ export class Totemheart {
|
|
|
339
387
|
personality : this.personality,
|
|
340
388
|
circadianRhythm : this.circadianRhythm,
|
|
341
389
|
} )
|
|
390
|
+
this.sleepPressure.dissipate( elapsedSinceLastTurn )
|
|
342
391
|
|
|
343
392
|
}
|
|
344
393
|
// sweep() already records its own end time; a non-triggering (normal-cadence)
|
|
@@ -346,6 +395,18 @@ export class Totemheart {
|
|
|
346
395
|
if ( !this._lastRemReport ) this.remConsolidation.recordTurn()
|
|
347
396
|
|
|
348
397
|
this.turnCounter += 1
|
|
398
|
+
this._lastActiveUserId = userId
|
|
399
|
+
|
|
400
|
+
// Affective forecasting — a real anticipatory reading BEFORE this turn's actual
|
|
401
|
+
// outcome is known, from BayesianExpectation's own real posterior for this user.
|
|
402
|
+
// Applied as a small anticipatory spike (own tuning weight) distinct from the
|
|
403
|
+
// reactive spikes below; the forecast error is scored once desirability is known.
|
|
404
|
+
const anticipation = this.anticipatoryAffect.forecast( this.bayesianExpectation, userId )
|
|
405
|
+
if ( anticipation.confidence > 0.15 ) {
|
|
406
|
+
|
|
407
|
+
this.emotionSpace.applySpike( { valence: anticipation.expectedValence * 0.1, arousal: anticipation.expectedArousal * 0.1, weight: anticipation.confidence * 0.3 } )
|
|
408
|
+
|
|
409
|
+
}
|
|
349
410
|
|
|
350
411
|
// Feeling that exists this instant but isn't about to be expressed this turn —
|
|
351
412
|
// used by both early exits below to feed ExpressionDebt.
|
|
@@ -394,6 +455,13 @@ export class Totemheart {
|
|
|
394
455
|
delayMs : 0,
|
|
395
456
|
styleTags : [ 'freeze', overload.reason ],
|
|
396
457
|
emotionalState : this.getEmotionalState(),
|
|
458
|
+
// A real, if not brand-new-turn-driven, systemPrompt — this text is
|
|
459
|
+
// already final (not meant for another LLM completion this turn), but
|
|
460
|
+
// a host that unconditionally reads result.systemPrompt on every
|
|
461
|
+
// response (the documented Usage pattern) should still get a real
|
|
462
|
+
// string here, not undefined. Found by IntelligentMockGenerator's
|
|
463
|
+
// systemPrompt_generated_without_error invariant — see test/generated/.
|
|
464
|
+
systemPrompt : this.getSystemPrompt( { userId } ),
|
|
397
465
|
}
|
|
398
466
|
|
|
399
467
|
}
|
|
@@ -421,6 +489,9 @@ export class Totemheart {
|
|
|
421
489
|
delayMs : 0,
|
|
422
490
|
styleTags : [ 'hijack', hijack.emotion ],
|
|
423
491
|
emotionalState : this.getEmotionalState(),
|
|
492
|
+
// Same real-consistency fix as the sensory-overload freeze above —
|
|
493
|
+
// found by IntelligentMockGenerator, see test/generated/.
|
|
494
|
+
systemPrompt : this.getSystemPrompt( { userId } ),
|
|
424
495
|
hijack,
|
|
425
496
|
}
|
|
426
497
|
|
|
@@ -464,6 +535,15 @@ export class Totemheart {
|
|
|
464
535
|
const kalmanNoiseMultiplier = Math.max( 0.3, 1 + narrowing * 0.4 - this._lastNovelty * 0.2 )
|
|
465
536
|
const smoothedArousal = this.arousalKalmanFilter.filter( this.emotionSpace.vector.arousal, kalmanNoiseMultiplier )
|
|
466
537
|
|
|
538
|
+
// Interoceptive prediction error — the Kalman filter's own real innovation
|
|
539
|
+
// (measurement - predicted estimate) IS the prediction-error term the
|
|
540
|
+
// predictive-processing account of interoception is about (Seth, 2013, see
|
|
541
|
+
// InteroceptivePredictionError.js); a SUSTAINED mismatch (not one noisy
|
|
542
|
+
// reading) reads as real anxiety-like arousal.
|
|
543
|
+
this.interoceptivePredictionError.observe( this.arousalKalmanFilter.getLastInnovation() )
|
|
544
|
+
const interoceptiveAnxiety = this.interoceptivePredictionError.getAnxietyContribution()
|
|
545
|
+
if ( interoceptiveAnxiety > 0.1 ) this.emotionSpace.applySpike( { arousal: interoceptiveAnxiety * 0.15, weight: 0.3 } )
|
|
546
|
+
|
|
467
547
|
// Load scheduler — instead of always running the full fixed pipeline, an
|
|
468
548
|
// instability reading (cortisol + smoothed arousal + fatigue) decides which
|
|
469
549
|
// optional mechanics get skipped this turn. `_lastNovelty` is last turn's
|
|
@@ -687,7 +767,7 @@ export class Totemheart {
|
|
|
687
767
|
// trace crediting recently-active contexts too (see DopaminergicEngine.js).
|
|
688
768
|
// Novelty adds extra arousal on top of the RPE-driven amount, since novelty
|
|
689
769
|
// and reward-surprise are related but not identical signals.
|
|
690
|
-
const rpe = this.dopaminergicEngine.computeRPE( desirability, userId )
|
|
770
|
+
const rpe = this.dopaminergicEngine.computeRPE( desirability, userId, this.homeostasis.allostaticLoad )
|
|
691
771
|
const dopamineSpike = {
|
|
692
772
|
valence : rpe * 0.5,
|
|
693
773
|
arousal : Math.abs( rpe ) * 0.6 + ( appraisal.ontologyArousalBoost ?? 0 ) * 0.2 + novelty * 0.15,
|
|
@@ -696,6 +776,23 @@ export class Totemheart {
|
|
|
696
776
|
this.emotionSpace.applySpike( dopamineSpike )
|
|
697
777
|
this.moodTracker.push( dopamineSpike )
|
|
698
778
|
|
|
779
|
+
// Anticipatory-affect correction — now that the real outcome (desirability) is
|
|
780
|
+
// known, score the forecast error against it and fold it back into next time's
|
|
781
|
+
// anticipation for this same context, real backward correction (see AnticipatoryAffect.js).
|
|
782
|
+
const forecastError = this.anticipatoryAffect.getForecastError( anticipation, desirability )
|
|
783
|
+
this.anticipatoryAffect.applyCorrection( this.dopaminergicEngine, userId, forecastError )
|
|
784
|
+
|
|
785
|
+
// Opponent-process after-effect — a strong-enough hedonic swing (either
|
|
786
|
+
// direction) queues a real, growing-with-repetition undershoot (Solomon &
|
|
787
|
+
// Corbit 1974) to be applied on the NEXT tick(), not instantly — the felt
|
|
788
|
+
// "high"/"low" and its rebound are temporally separated in the real theory.
|
|
789
|
+
if ( Math.abs( rpe ) > 0.5 ) {
|
|
790
|
+
|
|
791
|
+
const opponent = this.opponentProcess.trigger( userId, rpe )
|
|
792
|
+
this._pendingOpponentAfterEffect = ( this._pendingOpponentAfterEffect ?? 0 ) + opponent.afterEffectValence
|
|
793
|
+
|
|
794
|
+
}
|
|
795
|
+
|
|
699
796
|
// Cortisol — chronic stress accumulator. Threat/betrayal concepts, high Bayesian
|
|
700
797
|
// anxiety, high situational stress, or a strong real-embedding similarity to
|
|
701
798
|
// the "hostilidad" cluster (when semantic similarity is available) all
|
|
@@ -735,6 +832,21 @@ export class Totemheart {
|
|
|
735
832
|
const dissonance = this.cognitiveDissonance.registerConflict( conflict.score ?? 0, this.personality )
|
|
736
833
|
const acceptability = this.fuzzyNormativeCheck.evaluate( conflict.score ?? 0, relation.trust )
|
|
737
834
|
|
|
835
|
+
// Moral injury — ordinary dissonance that crosses a real severity threshold
|
|
836
|
+
// against a genuinely high-polarity core belief scars permanently, distinct
|
|
837
|
+
// from CognitiveDissonance's own stress (which recovers) — see MoralInjury.js.
|
|
838
|
+
if ( dissonance.triggered ) {
|
|
839
|
+
|
|
840
|
+
const matchedBelief = this.coreBeliefs.getAll().find( b => ( input || '' ).toLowerCase().includes( b.statement.toLowerCase().slice( 0, 12 ) ) )
|
|
841
|
+
if ( matchedBelief ) {
|
|
842
|
+
|
|
843
|
+
const injury = this.moralInjury.evaluate( matchedBelief.topic, this.cognitiveDissonance.getStress(), matchedBelief.polarity )
|
|
844
|
+
if ( injury.injured ) this.explainability.logDecision( 'moral_injury', `permanent scar on "${matchedBelief.topic}" (severity=${injury.severity.toFixed( 2 )}, total=${injury.totalScar.toFixed( 2 )})` )
|
|
845
|
+
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
}
|
|
849
|
+
|
|
738
850
|
// Logic — a cold, boolean read run IN PARALLEL to the emotional appraisal
|
|
739
851
|
// above, deliberately NOT feeding into EmotionSpace: this is the AI's
|
|
740
852
|
// dispassionate read of whether the input is logically consistent with its
|
|
@@ -851,6 +963,21 @@ export class Totemheart {
|
|
|
851
963
|
if ( conceptSet.has( 'betrayal' ) ) loveHateH = Math.min( 1, loveHateH + 0.5 )
|
|
852
964
|
if ( conceptSet.has( 'threat' ) || conceptSet.has( 'rejection' ) ) loveHateH = Math.min( 1, loveHateH + 0.3 )
|
|
853
965
|
if ( conceptSet.has( 'criticism' ) ) loveHateH = Math.min( 1, loveHateH + 0.3 )
|
|
966
|
+
|
|
967
|
+
// Social pain overlap — real exclusion/rejection specifically (not generic
|
|
968
|
+
// negativity) reuses the bodily-threat pathway, a distinct cortisol-weighted
|
|
969
|
+
// signature (Eisenberger, Lieberman & Williams 2003, see PainSocialOverlap.js).
|
|
970
|
+
if ( conceptSet.has( 'rejection' ) || conceptSet.has( 'betrayal' ) ) {
|
|
971
|
+
|
|
972
|
+
const socialPain = this.painSocialOverlap.computeSocialPainSpike( desirability, conceptSet.has( 'rejection' ) ? 0.8 : 0.5 )
|
|
973
|
+
if ( socialPain.cortisolBoost > 0 ) {
|
|
974
|
+
|
|
975
|
+
this.emotionSpace.applySpike( { valence: socialPain.valence * 0.3, arousal: socialPain.arousal * 0.3, weight: 0.4 } )
|
|
976
|
+
this.cortisolEngine.level = clamp01( this.cortisolEngine.level + socialPain.cortisolBoost )
|
|
977
|
+
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
}
|
|
854
981
|
if ( lifeEvent ) {
|
|
855
982
|
|
|
856
983
|
loveHateL = Math.min( 1, loveHateL + Math.max( 0, lifeEvent.valence ) * ( lifeEvent.impact / 100 ) * 0.3 )
|
|
@@ -873,10 +1000,28 @@ export class Totemheart {
|
|
|
873
1000
|
this.moodTracker.push( { valence: bondUpdate.netBond * 0.15, arousal: ( bondTension + loveHateH ) * 0.15 } )
|
|
874
1001
|
if ( bondUpdate.Heff > 0.25 ) this.cortisolEngine.register( -bondUpdate.Heff, false )
|
|
875
1002
|
|
|
1003
|
+
// RepairProtocol tracks this bond's real historical peak affinity every turn —
|
|
1004
|
+
// the ceiling any future trust rebound is capped below (see RepairProtocol.js).
|
|
1005
|
+
this.repairProtocol.observePeak( userId, bondUpdate.A )
|
|
1006
|
+
|
|
1007
|
+
// A real grief wave for an already-active grief process (from a past rupture)
|
|
1008
|
+
// can resurface unprompted on ANY turn, independent of what triggers below.
|
|
1009
|
+
const griefWave = this.griefEngine.rollWave( userId )
|
|
1010
|
+
if ( griefWave ) {
|
|
1011
|
+
|
|
1012
|
+
this.emotionSpace.applySpike( griefWave.spike )
|
|
1013
|
+
this.moodTracker.push( griefWave.spike )
|
|
1014
|
+
|
|
1015
|
+
}
|
|
1016
|
+
|
|
876
1017
|
const rupture = this.loveHateEngine.checkRupture( userId, { cortisol: this.cortisolEngine.getLevel() } )
|
|
877
1018
|
let repair = { repaired: false }
|
|
878
1019
|
if ( rupture.ruptured ) {
|
|
879
1020
|
|
|
1021
|
+
// A real rupture of a bond that had genuine affinity to lose triggers grief —
|
|
1022
|
+
// not "high sadness", a real decaying-with-waves process (see GriefEngine.js).
|
|
1023
|
+
if ( bondUpdate.A > 0.15 ) this.griefEngine.triggerLoss( userId, bondUpdate.A, 'bond_rupture' )
|
|
1024
|
+
|
|
880
1025
|
// Real cross-module side effects of an actual rupture, applied here
|
|
881
1026
|
// (LoveHateEngine itself stays self-contained and returns a signal,
|
|
882
1027
|
// same orchestration pattern Totemheart already uses for e.g. life
|
|
@@ -903,6 +1048,18 @@ export class Totemheart {
|
|
|
903
1048
|
this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth + repair.egoHealthRestore )
|
|
904
1049
|
this.explainability.logDecision( 'lovehate_repair', `relational repair #${repair.repairCount} for ${userId}` )
|
|
905
1050
|
|
|
1051
|
+
// Real transactional repair: an apology is offered and (this successful
|
|
1052
|
+
// LoveHateEngine repair IS the real "it landed" signal) accepted, applying
|
|
1053
|
+
// the bounded rebound — never above this bond's own historical peak.
|
|
1054
|
+
this.repairProtocol.offerApology( userId, agreement.agreement )
|
|
1055
|
+
const resolvedApology = this.repairProtocol.resolveApology( userId, true, this.loveHateEngine.getBond( userId ).A )
|
|
1056
|
+
if ( resolvedApology.reboundedA !== undefined ) {
|
|
1057
|
+
|
|
1058
|
+
const bond = this.loveHateEngine.getBond( userId )
|
|
1059
|
+
bond.A = Math.max( bond.A, resolvedApology.reboundedA )
|
|
1060
|
+
|
|
1061
|
+
}
|
|
1062
|
+
|
|
906
1063
|
}
|
|
907
1064
|
|
|
908
1065
|
}
|
|
@@ -955,11 +1112,36 @@ export class Totemheart {
|
|
|
955
1112
|
if ( characterBreak ) this.explainability.logDecision( 'character_break', `expression debt exceeded ${EGO_DEPLETION_THRESHOLD} — suppression bypassed this turn, dumped ${debtReleased.toFixed( 2 )} of pent-up affect` )
|
|
956
1113
|
this.expressionDebt.decay( 1 )
|
|
957
1114
|
|
|
1115
|
+
// Commitment device — the AI's own implicit self-binding promise to stay
|
|
1116
|
+
// composed (Kiesler 1971, see CommitmentDevice.js). A character break IS a
|
|
1117
|
+
// real violation of that promise, with an escalating cost the longer it had
|
|
1118
|
+
// been kept; otherwise, staying composed this turn reinforces it.
|
|
1119
|
+
if ( characterBreak ) {
|
|
1120
|
+
|
|
1121
|
+
const violation = this.commitmentDevice.violate( 'be_composed' )
|
|
1122
|
+
this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth - violation.cost )
|
|
1123
|
+
|
|
1124
|
+
}
|
|
1125
|
+
else this.commitmentDevice.keep( 'be_composed' )
|
|
1126
|
+
|
|
958
1127
|
// Reputation / ego — a 'shame' reaction (submissive personalities) also drops the
|
|
959
1128
|
// felt sense of Dominance directly and biases toward withdrawal, matching the
|
|
960
1129
|
// real phenomenon (shame collapses posture/control, not just mood).
|
|
961
1130
|
const reputation = this.reputationEngine.evaluate( appraisal, this.personality )
|
|
962
1131
|
|
|
1132
|
+
// Identity threat — an attack specifically on a tagged self-identity core
|
|
1133
|
+
// belief (not just any competence hit) triggers a bigger, distinct ego-
|
|
1134
|
+
// protection cascade (Steele 1988, see IdentityThreatMonitor.js).
|
|
1135
|
+
const selfTopics = this.coreBeliefs.getAll().filter( b => b.topic.startsWith( 'self_' ) ).map( b => b.topic )
|
|
1136
|
+
const identityThreat = this.identityThreatMonitor.detect( appraisal, this.coreBeliefs, selfTopics )
|
|
1137
|
+
if ( identityThreat.isIdentityThreat ) {
|
|
1138
|
+
|
|
1139
|
+
const cascade = this.identityThreatMonitor.getCascadeMultipliers( identityThreat.severity )
|
|
1140
|
+
this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth - identityThreat.severity * 0.15 * cascade.egoHealthDamageMult )
|
|
1141
|
+
this.explainability.logDecision( 'identity_threat', `identity threat on ${identityThreat.matchedTopics.join( ',' )} (severity=${identityThreat.severity.toFixed( 2 )})` )
|
|
1142
|
+
|
|
1143
|
+
}
|
|
1144
|
+
|
|
963
1145
|
// Flush — purely internal analog of peripheral blood flow, a real first-order
|
|
964
1146
|
// thermal lag driven by the shame/anger blend weight instead of a Navier-Stokes
|
|
965
1147
|
// simulation (there's no skin here either). It outlasts its trigger the way a
|
|
@@ -996,6 +1178,14 @@ export class Totemheart {
|
|
|
996
1178
|
const fairness = this.fairnessMonitor.evaluate( relation.affinity, othersTreatment )
|
|
997
1179
|
if ( fairness.envy > 0.15 ) this.emotionSpace.applySpike( { valence: -fairness.envy * 0.3, dominance: -fairness.envy * 0.2, weight: 0.4 } )
|
|
998
1180
|
|
|
1181
|
+
// Value hierarchy — a real "care" pull (this turn's own desirability) vs. a
|
|
1182
|
+
// real "fairness" pull (inequity envy toward this user) genuinely conflict
|
|
1183
|
+
// when they oppose, weighted by how strongly BOTH values are held (Schwartz
|
|
1184
|
+
// 1992, see ValueHierarchy.js) — raises real CognitiveDissonance stress, a
|
|
1185
|
+
// second, independent source from the belief-conflict one above.
|
|
1186
|
+
const valueConflict = this.valueHierarchy.evaluateConflict( 'care', desirability, 'fairness', -fairness.envy )
|
|
1187
|
+
if ( valueConflict.conflict ) this.cognitiveDissonance.stress = clamp01( this.cognitiveDissonance.stress + valueConflict.dissonance * 0.2 )
|
|
1188
|
+
|
|
999
1189
|
// Status envy — falling status while a known rival's rises, independent of
|
|
1000
1190
|
// absolute treatment level (item 39's actual trigger condition).
|
|
1001
1191
|
const selfTrend = this.statusEnvy.observe( userId, relation.powerDynamic )
|
|
@@ -1006,6 +1196,12 @@ export class Totemheart {
|
|
|
1006
1196
|
const envyCheck = this.statusEnvy.checkEnvy( selfTrend, rivalTrend )
|
|
1007
1197
|
if ( envyCheck.triggered ) this.emotionSpace.applySpike( { valence: -envyCheck.intensity * 0.3, arousal: envyCheck.intensity * 0.2, weight: 0.4 } )
|
|
1008
1198
|
|
|
1199
|
+
// Jealousy triangle — the same trend signals, but scored against the AI's
|
|
1200
|
+
// OWN real bond strength with "other" (userId), not just the bare trend
|
|
1201
|
+
// comparison StatusEnvy already does (White & Mullen 1989, see JealousyTriangle.js).
|
|
1202
|
+
const jealousy = this.jealousyTriangle.evaluate( selfTrend, rivalTrend, this.loveHateEngine.getNetBond( userId ) )
|
|
1203
|
+
if ( jealousy.threatened ) this.emotionSpace.applySpike( { valence: -jealousy.intensity * 0.25, arousal: jealousy.intensity * 0.3, weight: 0.4 } )
|
|
1204
|
+
|
|
1009
1205
|
}
|
|
1010
1206
|
|
|
1011
1207
|
// Controllability — high estimated control over this kind of situation dampens
|
|
@@ -1078,6 +1274,14 @@ export class Totemheart {
|
|
|
1078
1274
|
const guardedness = Math.min( 1, unresolvedCount * 0.2 )
|
|
1079
1275
|
const blend = this.emotionSpace.getBlend( 3, neuroticism )
|
|
1080
1276
|
|
|
1277
|
+
// Approach-avoidance conflict — disclosing/opening up (approach) vs. staying
|
|
1278
|
+
// guarded (avoidance) genuinely oscillate near the crossover point (Miller
|
|
1279
|
+
// 1944, see MotivationalConflict.js). `distance` = woundPressure (closer to 0
|
|
1280
|
+
// = "safer to approach"); low expressionConfidence in the vacillation zone
|
|
1281
|
+
// dampens this turn's expressed spike weight — real uncertainty about what to
|
|
1282
|
+
// express, not just a fixed guardedness scalar.
|
|
1283
|
+
const motivConflict = this.motivationalConflict.evaluate( woundPressure, Math.max( 0, desirability ), this.cortisolEngine.getLevel() + woundPressure )
|
|
1284
|
+
|
|
1081
1285
|
// Ego confidence — real Shannon entropy of the blend distribution (perplexity =
|
|
1082
1286
|
// 2^H). A flat, confused blend reads as low self-confidence and drops Dominance
|
|
1083
1287
|
// defensively — the honest triangulated version of "the model doubts itself".
|
|
@@ -1114,8 +1318,15 @@ export class Totemheart {
|
|
|
1114
1318
|
// break above), it's also a plain cognitive-resource one.
|
|
1115
1319
|
let suppressionDrive = characterBreak
|
|
1116
1320
|
? 0
|
|
1117
|
-
|
|
1321
|
+
// Real self-regulation resource gate: EgoDepletionBudget's own capacity
|
|
1322
|
+
// (own tuning; see EgoDepletionBudget.js for the explicit replication-crisis
|
|
1323
|
+
// caveat on the underlying strength metaphor) scales suppression down as the
|
|
1324
|
+
// budget runs low — a depleted system genuinely holds back less, not just
|
|
1325
|
+
// "feels tired about it".
|
|
1326
|
+
: clamp01( this.personality.get( 'conscientiousness' ) * this.cortisolEngine.getLevel() + ( this._lifeEventSuppressionBoost ?? 0 ) + ( this._hijackAlertBoost ?? 0 ) )
|
|
1327
|
+
* ( 1 - this.decisionFatigue.getLevel() ) * this.egoDepletionBudget.getRegulationCapacity()
|
|
1118
1328
|
this.decisionFatigue.recordDecision( suppressionDrive )
|
|
1329
|
+
this.egoDepletionBudget.spend( suppressionDrive * 0.3 )
|
|
1119
1330
|
if ( this.decisionFatigue.isShallow() ) this.cortisolEngine.register( 0, true ) // sustained cognitive load reads as chronic ambient stress too
|
|
1120
1331
|
// Real suppression cost: holding this back isn't free the instant it happens —
|
|
1121
1332
|
// charges the reservoir tick()/drainSuppressionCost() pays out as DecisionFatigue
|
|
@@ -1138,6 +1349,7 @@ export class Totemheart {
|
|
|
1138
1349
|
} )
|
|
1139
1350
|
if ( suppressionDrive > 0.5 ) modulated.styleTags.push( 'suppressed' )
|
|
1140
1351
|
if ( characterBreak ) modulated.styleTags.push( 'character_break' )
|
|
1352
|
+
if ( motivConflict.vacillating ) modulated.styleTags.push( 'conflicted' )
|
|
1141
1353
|
if ( circadian.lowEnergyWindow && Math.random() < circadian.erraticChance ) {
|
|
1142
1354
|
|
|
1143
1355
|
modulated.styleTags.push( 'drowsy' )
|
|
@@ -1155,6 +1367,17 @@ export class Totemheart {
|
|
|
1155
1367
|
// to (real Attachment affinity, the same signal already driving TribalCategorization)
|
|
1156
1368
|
// costs more than failing a stranger.
|
|
1157
1369
|
const guilt = this.guiltEngine.evaluate( this.emotionSpace.vector, selfCritique.score ?? 0, 0.4, 1 + relation.affinity )
|
|
1370
|
+
|
|
1371
|
+
// Shame (identity-level, "I am bad") vs. guilt (behavior-level, "I did a bad
|
|
1372
|
+
// thing") as genuinely separate, differently-decaying accumulators (Tangney &
|
|
1373
|
+
// Dearing 2002, see ShameGuiltSplit.js) — reuses this turn's real ReputationEngine
|
|
1374
|
+
// damage and selfCritique score rather than inventing new trigger signals.
|
|
1375
|
+
this.shameGuiltSplit.register( {
|
|
1376
|
+
egoDamage : reputation.damaged ? reputation.damage : 0,
|
|
1377
|
+
selfCritiqueScore : selfCritique.score ?? 0,
|
|
1378
|
+
agreeableness : this.personality.get( 'agreeableness' ),
|
|
1379
|
+
} )
|
|
1380
|
+
this.shameGuiltSplit.decay( 1 )
|
|
1158
1381
|
const projection = this.egoProjection.resolve( guilt, reputation.reaction )
|
|
1159
1382
|
const regret = this.counterfactualComparison.computeRegret( this.emotionSpace.vector.valence, Math.max( 0, appraisal.desirability ?? 0 ) )
|
|
1160
1383
|
|
|
@@ -1184,6 +1407,13 @@ export class Totemheart {
|
|
|
1184
1407
|
betrayalDetected : ( ontologyFlagsThreat && ontologyMatches.some( m => m.concept === 'betrayal' ) ) || uncannyValley.suspicious,
|
|
1185
1408
|
}, this.personality )
|
|
1186
1409
|
|
|
1410
|
+
// State-dependent attachment-style switching — real acute-stress activation of
|
|
1411
|
+
// the attachment behavioral system (Mikulincer & Shaver 2016, see Attachment.js
|
|
1412
|
+
// getStressStyle()): a trait-secure style can express as anxious under real
|
|
1413
|
+
// extreme chronic stress. Logged for observability, not silently discarded.
|
|
1414
|
+
const stressStyle = this.attachment.getStressStyle( this.personality, this.cortisolEngine.getLevel() )
|
|
1415
|
+
if ( stressStyle !== this.attachment.getStyle( this.personality ) ) this.explainability.logDecision( 'attachment_stress_style', `trait style overridden to "${stressStyle}" under cortisol=${this.cortisolEngine.getLevel().toFixed( 2 )}` )
|
|
1416
|
+
|
|
1187
1417
|
// Bayesian expectation update — fold this turn's actual outcome into next
|
|
1188
1418
|
// time's prior for this user.
|
|
1189
1419
|
this.bayesianExpectation.update( userId, desirability > 0 )
|
|
@@ -1191,7 +1421,23 @@ export class Totemheart {
|
|
|
1191
1421
|
// Close out this turn's reconsolidation window (if a memory was reactivated
|
|
1192
1422
|
// above): blend its stored signature toward what actually got felt THIS turn.
|
|
1193
1423
|
// A no-op if the window already closed or nothing was reactivated.
|
|
1194
|
-
if ( reactivation )
|
|
1424
|
+
if ( reactivation ) {
|
|
1425
|
+
|
|
1426
|
+
this.episodicMemory.reconsolidate( reactivation.entry, this.emotionSpace.vector )
|
|
1427
|
+
|
|
1428
|
+
// Nostalgia — a genuinely OLD, originally-negative memory resurfacing reads
|
|
1429
|
+
// bittersweet, not simply negative (Walker, Skowronski & Thompson 2003, see
|
|
1430
|
+
// NostalgiaEngine.js) — real ambivalence, same co-presence idea LoveHateEngine
|
|
1431
|
+
// already models for Affinity/Aversion, applied here to a single memory.
|
|
1432
|
+
const ambivalenceBoost = this.nostalgiaEngine.getAmbivalenceBoost( reactivation.entry )
|
|
1433
|
+
if ( ambivalenceBoost > 0 ) {
|
|
1434
|
+
|
|
1435
|
+
const nostalgicValence = this.nostalgiaEngine.getNostalgicValence( reactivation.entry )
|
|
1436
|
+
this.emotionSpace.applySpike( { valence: nostalgicValence * 0.08, weight: ambivalenceBoost * 0.3 } )
|
|
1437
|
+
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
}
|
|
1195
1441
|
|
|
1196
1442
|
await safeStep( this.explainability, 'episodicMemory.store', async () => this.episodicMemory.store( {
|
|
1197
1443
|
text : input,
|
|
@@ -1224,6 +1470,7 @@ export class Totemheart {
|
|
|
1224
1470
|
// hot last turn (residual) — not on every short, unrelated reply.
|
|
1225
1471
|
const topicTrigger = this.triggerSentinel.check( 'topicSatiation', tokens, this._lastTopicFatigue ?? 0 )
|
|
1226
1472
|
const topicSatiation = topicTrigger.active ? await this.topicSatiation.observe( input ) : { fatigue: 0, meanSimilarity: 0, gated: true }
|
|
1473
|
+
this._lastTopicFatigue = topicSatiation.fatigue ?? 0 // real boredom signal SubjectiveTimeEngine's tick() reads — see SubjectiveTimeEngine.js
|
|
1227
1474
|
this._lastTopicFatigue = topicSatiation.fatigue
|
|
1228
1475
|
|
|
1229
1476
|
// Homeostasis: interacting satisfies socialization/curiosity. Drive — curiosity
|
|
@@ -1384,15 +1631,40 @@ export class Totemheart {
|
|
|
1384
1631
|
|
|
1385
1632
|
const mood = this.moodTracker.getMood()
|
|
1386
1633
|
|
|
1634
|
+
// Subjective time — real dt multiplier from arousal/boredom (Stetson, Fiesta
|
|
1635
|
+
// & Eagleman 2007; Zakay & Block 1997, see SubjectiveTimeEngine.js). Scoped
|
|
1636
|
+
// to ForgettingCurve's own dt below, deliberately NOT the main decayEngine.apply()
|
|
1637
|
+
// call: the felt-vector decay rate is a load-bearing invariant a lot of other
|
|
1638
|
+
// mechanics (allostasis reset among them) assume tracks plain wall-clock dt —
|
|
1639
|
+
// memory retention fading faster during a subjectively "long" stretch is a
|
|
1640
|
+
// real, lower-blast-radius place for this same effect to land.
|
|
1641
|
+
const subjectiveDt = dt * this.subjectiveTimeEngine.getSubjectiveDtMultiplier( this.emotionSpace.vector.arousal, this._lastTopicFatigue ?? 0 )
|
|
1642
|
+
|
|
1387
1643
|
const valenceBefore = this.emotionSpace.vector.valence
|
|
1388
1644
|
this.decayEngine.apply( this.emotionSpace, mood, this.personality, dt )
|
|
1389
1645
|
this.controllabilityEstimate.observeOutcome( this.emotionSpace.getDominantEmotion(), valenceBefore, this.emotionSpace.vector.valence )
|
|
1390
1646
|
|
|
1647
|
+
// Opponent-process after-effect — a queued undershoot from a strong hedonic
|
|
1648
|
+
// swing THIS turn lands here, one tick later (Solomon & Corbit 1974), not
|
|
1649
|
+
// instantly — the real temporal separation the theory is about.
|
|
1650
|
+
if ( this._pendingOpponentAfterEffect ) {
|
|
1651
|
+
|
|
1652
|
+
this.emotionSpace.applySpike( { valence: this._pendingOpponentAfterEffect, weight: 0.4 } )
|
|
1653
|
+
this._pendingOpponentAfterEffect = 0
|
|
1654
|
+
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1391
1657
|
this.homeostasis.tick( dt, this.personality, { circadianEnergy: this.circadianRhythm.getEnergyLevel( new Date(), this.cortisolEngine.getLevel() ), cortisol: this.cortisolEngine.getLevel() } )
|
|
1392
|
-
this.forgettingCurve.tick( this.episodicMemory,
|
|
1658
|
+
this.forgettingCurve.tick( this.episodicMemory, subjectiveDt )
|
|
1393
1659
|
this.decisionFatigue.decay( dt )
|
|
1394
1660
|
this.cognitiveDissonance.decay( dt )
|
|
1395
|
-
|
|
1661
|
+
|
|
1662
|
+
// Social baseline theory — the absence of a trusted bond with whoever was
|
|
1663
|
+
// last active genuinely slows chronic cortisol's real decay (Coan & Sbarra
|
|
1664
|
+
// 2015, see SocialBaselineTheory.js) — real co-regulation, not a fixed rate.
|
|
1665
|
+
const lastRelationTrust = this._lastActiveUserId ? this.attachment.get( this._lastActiveUserId ).trust : 0.5
|
|
1666
|
+
this.cortisolEngine.decay( dt * this.socialBaselineTheory.getCortisolDecayMultiplier( lastRelationTrust ) )
|
|
1667
|
+
this.egoDepletionBudget.regenerate( dt )
|
|
1396
1668
|
this.reputationEngine.regenerate( dt )
|
|
1397
1669
|
this.selfModel.decay( dt )
|
|
1398
1670
|
this.sensitization.decay( dt )
|
|
@@ -1526,6 +1798,16 @@ export class Totemheart {
|
|
|
1526
1798
|
classicalConditioningAssociations : [ ...this.classicalConditioning.associations.entries() ],
|
|
1527
1799
|
coreBeliefs : this.coreBeliefs.getAll(),
|
|
1528
1800
|
sensitizationLevel : this.sensitization.level,
|
|
1801
|
+
griefs : [ ...this.griefEngine.griefs.entries() ],
|
|
1802
|
+
shame : this.shameGuiltSplit.shame,
|
|
1803
|
+
guilt : this.shameGuiltSplit.guilt,
|
|
1804
|
+
repairRecords : [ ...this.repairProtocol.records.entries() ],
|
|
1805
|
+
valueWeights : this.valueHierarchy.getAll(),
|
|
1806
|
+
promises : this.commitmentDevice.getAll(),
|
|
1807
|
+
moralScars : [ ...this.moralInjury.scars.entries() ],
|
|
1808
|
+
opponentExposures : [ ...this.opponentProcess.exposures.entries() ],
|
|
1809
|
+
egoDepletionBudget : this.egoDepletionBudget.budget,
|
|
1810
|
+
sleepPressureLevel : this.sleepPressure.S,
|
|
1529
1811
|
}
|
|
1530
1812
|
|
|
1531
1813
|
}
|
|
@@ -1561,6 +1843,16 @@ export class Totemheart {
|
|
|
1561
1843
|
if ( data.classicalConditioningAssociations ) this.classicalConditioning.associations = new Map( data.classicalConditioningAssociations )
|
|
1562
1844
|
if ( data.coreBeliefs ) for ( const b of data.coreBeliefs ) if ( !this.coreBeliefs.get( b.topic ) ) this.coreBeliefs.add( b.topic, b.statement, b.polarity )
|
|
1563
1845
|
if ( typeof data.sensitizationLevel === 'number' ) this.sensitization.level = data.sensitizationLevel
|
|
1846
|
+
if ( data.griefs ) this.griefEngine.griefs = new Map( data.griefs )
|
|
1847
|
+
if ( typeof data.shame === 'number' ) this.shameGuiltSplit.shame = data.shame
|
|
1848
|
+
if ( typeof data.guilt === 'number' ) this.shameGuiltSplit.guilt = data.guilt
|
|
1849
|
+
if ( data.repairRecords ) this.repairProtocol.records = new Map( data.repairRecords )
|
|
1850
|
+
if ( data.valueWeights ) this.valueHierarchy.weights = new Map( data.valueWeights )
|
|
1851
|
+
if ( data.promises ) this.commitmentDevice.promises = new Map( data.promises )
|
|
1852
|
+
if ( data.moralScars ) this.moralInjury.scars = new Map( data.moralScars )
|
|
1853
|
+
if ( data.opponentExposures ) this.opponentProcess.exposures = new Map( data.opponentExposures )
|
|
1854
|
+
if ( typeof data.egoDepletionBudget === 'number' ) this.egoDepletionBudget.budget = data.egoDepletionBudget
|
|
1855
|
+
if ( typeof data.sleepPressureLevel === 'number' ) this.sleepPressure.S = data.sleepPressureLevel
|
|
1564
1856
|
|
|
1565
1857
|
}
|
|
1566
1858
|
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
function clamp( v, min = -1, max = 1 ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( min, Math.min( max, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function clamp01( v ) {
|
|
8
|
+
|
|
9
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
10
|
+
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Affective forecasting: emotion generated by what the AI EXPECTS to happen,
|
|
15
|
+
* not only by what already happened (Wilson, T. D., & Gilbert, D. T. (2003),
|
|
16
|
+
* "Affective forecasting", Advances in Experimental Social Psychology, 35,
|
|
17
|
+
* 345-411). Reuses BayesianExpectation's real posterior (already a genuine
|
|
18
|
+
* P(positive outcome) estimate per user) as the forecast's valence sign and
|
|
19
|
+
* confidence, converts it into a concrete expected-valence/arousal pair, and
|
|
20
|
+
* — the real mechanic — computes the forecast ERROR once the actual outcome
|
|
21
|
+
* is known, which is exactly the same real signal DopaminergicEngine's RPE
|
|
22
|
+
* already consumes, so a wrong anticipation genuinely corrects future
|
|
23
|
+
* anticipation the way TD learning does, not just the reward-prediction
|
|
24
|
+
* system alone.
|
|
25
|
+
*/
|
|
26
|
+
export class AnticipatoryAffect {
|
|
27
|
+
|
|
28
|
+
/** BayesianExpectation posterior -> a concrete forecast the AI can feel BEFORE the turn's real outcome is known. */
|
|
29
|
+
forecast( bayesianExpectation, userId ) {
|
|
30
|
+
|
|
31
|
+
const p = bayesianExpectation.getExpectation( userId )
|
|
32
|
+
const anxiety = bayesianExpectation.getAnxiety( userId )
|
|
33
|
+
const expectedValence = clamp( ( p - 0.5 ) * 2 )
|
|
34
|
+
const expectedArousal = clamp01( anxiety ) // anticipating a bad outcome is itself arousing
|
|
35
|
+
|
|
36
|
+
// Confidence: how far the posterior sits from an uninformative 0.5 —
|
|
37
|
+
// a forecast near neutral is a weak forecast regardless of arousal.
|
|
38
|
+
const confidence = clamp01( Math.abs( p - 0.5 ) * 2 )
|
|
39
|
+
|
|
40
|
+
return { expectedValence, expectedArousal, confidence, posterior: p }
|
|
41
|
+
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Real forecast error — the gap between what was anticipated and what actually happened, signed (positive = better than feared/hoped). */
|
|
45
|
+
getForecastError( forecastResult, actualValence ) {
|
|
46
|
+
|
|
47
|
+
return clamp( actualValence - forecastResult.expectedValence )
|
|
48
|
+
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Feeds the forecast error into DopaminergicEngine as a direct expectation nudge — a wrong anticipation updates the NEXT forecast, real backward correction. */
|
|
52
|
+
applyCorrection( dopaminergicEngine, context, forecastError, weight = 0.25 ) {
|
|
53
|
+
|
|
54
|
+
dopaminergicEngine.updateExpectationFromBelief( context, forecastError, weight )
|
|
55
|
+
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
function clamp01( v ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A stronger, explicitly-budgeted self-regulation resource, distinct from
|
|
9
|
+
* DecisionFatigue's plain accumulate-and-decay load and from ExpressionDebt's
|
|
10
|
+
* suppression-cost reservoir: this is a real daily-scale BUDGET that
|
|
11
|
+
* regulation acts spend down, checked against a hard floor that changes
|
|
12
|
+
* downstream behavior (raised hijack probability, style collapse) once
|
|
13
|
+
* crossed — not just a smoothly degrading number.
|
|
14
|
+
*
|
|
15
|
+
* Modeled on the strength/resource metaphor of ego depletion (Baumeister,
|
|
16
|
+
* R. F., Bratslavsky, E., Muraven, M., & Tice, D. M. (1998), "Ego depletion:
|
|
17
|
+
* Is the active self a limited resource?", Journal of Personality and Social
|
|
18
|
+
* Psychology, 74(5), 1252-1265) — with an explicit, honest caveat: that
|
|
19
|
+
* theory's specific glucose/resource-depletion mechanism largely failed to
|
|
20
|
+
* replicate in a large registered replication effort (Hagger, M. S., et al.
|
|
21
|
+
* (2016), "A multilab preregistered replication of the ego-depletion
|
|
22
|
+
* effect", Perspectives on Psychological Science, 11(4), 546-573). What's
|
|
23
|
+
* kept here is the qualitatively useful ENGINEERING pattern (a bounded
|
|
24
|
+
* resource that regulation spends and rest restores, with real downstream
|
|
25
|
+
* consequences once low) — not a claim that this models a settled
|
|
26
|
+
* neuroscientific mechanism. See CALIBRATION.md.
|
|
27
|
+
*/
|
|
28
|
+
export class EgoDepletionBudget {
|
|
29
|
+
|
|
30
|
+
constructor( { capacity = 1, regenRate = 0.02, lowThreshold = 0.25 } = {} ) {
|
|
31
|
+
|
|
32
|
+
this.capacity = capacity
|
|
33
|
+
this.regenRate = regenRate
|
|
34
|
+
this.lowThreshold = lowThreshold
|
|
35
|
+
this.budget = capacity
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Any act of self-regulation (suppression, reappraisal, overriding an immature defense) spends real budget. */
|
|
40
|
+
spend( amount ) {
|
|
41
|
+
|
|
42
|
+
this.budget = Math.max( 0, this.budget - Math.max( 0, amount ) )
|
|
43
|
+
return this.budget
|
|
44
|
+
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Rest/idle time and REM sweeps regenerate the budget — real bounded recovery, never above capacity. */
|
|
48
|
+
regenerate( dt = 1 ) {
|
|
49
|
+
|
|
50
|
+
this.budget = Math.min( this.capacity, this.budget + this.regenRate * dt )
|
|
51
|
+
return this.budget
|
|
52
|
+
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
isDepleted() {
|
|
56
|
+
|
|
57
|
+
return this.budget <= this.lowThreshold
|
|
58
|
+
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
getLevel() {
|
|
62
|
+
|
|
63
|
+
return clamp01( this.budget / this.capacity )
|
|
64
|
+
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Multiplies AmygdalaHijack's effective threshold DOWN as budget runs low — depleted regulation capacity makes a hijack easier to trigger. */
|
|
68
|
+
getHijackThresholdMultiplier() {
|
|
69
|
+
|
|
70
|
+
return this.isDepleted() ? 1 - ( 1 - this.getLevel() ) * 0.4 : 1
|
|
71
|
+
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Reappraisal/mature-defense capacity scales down with depletion — a real gate other modules can multiply their own capacity by. */
|
|
75
|
+
getRegulationCapacity() {
|
|
76
|
+
|
|
77
|
+
return this.getLevel()
|
|
78
|
+
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
}
|