totemheart 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.
@@ -474,6 +535,15 @@ export class Totemheart {
474
535
  const kalmanNoiseMultiplier = Math.max( 0.3, 1 + narrowing * 0.4 - this._lastNovelty * 0.2 )
475
536
  const smoothedArousal = this.arousalKalmanFilter.filter( this.emotionSpace.vector.arousal, kalmanNoiseMultiplier )
476
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
+
477
547
  // Load scheduler — instead of always running the full fixed pipeline, an
478
548
  // instability reading (cortisol + smoothed arousal + fatigue) decides which
479
549
  // optional mechanics get skipped this turn. `_lastNovelty` is last turn's
@@ -697,7 +767,7 @@ export class Totemheart {
697
767
  // trace crediting recently-active contexts too (see DopaminergicEngine.js).
698
768
  // Novelty adds extra arousal on top of the RPE-driven amount, since novelty
699
769
  // and reward-surprise are related but not identical signals.
700
- const rpe = this.dopaminergicEngine.computeRPE( desirability, userId )
770
+ const rpe = this.dopaminergicEngine.computeRPE( desirability, userId, this.homeostasis.allostaticLoad )
701
771
  const dopamineSpike = {
702
772
  valence : rpe * 0.5,
703
773
  arousal : Math.abs( rpe ) * 0.6 + ( appraisal.ontologyArousalBoost ?? 0 ) * 0.2 + novelty * 0.15,
@@ -706,6 +776,23 @@ export class Totemheart {
706
776
  this.emotionSpace.applySpike( dopamineSpike )
707
777
  this.moodTracker.push( dopamineSpike )
708
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
+
709
796
  // Cortisol — chronic stress accumulator. Threat/betrayal concepts, high Bayesian
710
797
  // anxiety, high situational stress, or a strong real-embedding similarity to
711
798
  // the "hostilidad" cluster (when semantic similarity is available) all
@@ -745,6 +832,21 @@ export class Totemheart {
745
832
  const dissonance = this.cognitiveDissonance.registerConflict( conflict.score ?? 0, this.personality )
746
833
  const acceptability = this.fuzzyNormativeCheck.evaluate( conflict.score ?? 0, relation.trust )
747
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
+
748
850
  // Logic — a cold, boolean read run IN PARALLEL to the emotional appraisal
749
851
  // above, deliberately NOT feeding into EmotionSpace: this is the AI's
750
852
  // dispassionate read of whether the input is logically consistent with its
@@ -861,6 +963,21 @@ export class Totemheart {
861
963
  if ( conceptSet.has( 'betrayal' ) ) loveHateH = Math.min( 1, loveHateH + 0.5 )
862
964
  if ( conceptSet.has( 'threat' ) || conceptSet.has( 'rejection' ) ) loveHateH = Math.min( 1, loveHateH + 0.3 )
863
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
+ }
864
981
  if ( lifeEvent ) {
865
982
 
866
983
  loveHateL = Math.min( 1, loveHateL + Math.max( 0, lifeEvent.valence ) * ( lifeEvent.impact / 100 ) * 0.3 )
@@ -883,10 +1000,28 @@ export class Totemheart {
883
1000
  this.moodTracker.push( { valence: bondUpdate.netBond * 0.15, arousal: ( bondTension + loveHateH ) * 0.15 } )
884
1001
  if ( bondUpdate.Heff > 0.25 ) this.cortisolEngine.register( -bondUpdate.Heff, false )
885
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
+
886
1017
  const rupture = this.loveHateEngine.checkRupture( userId, { cortisol: this.cortisolEngine.getLevel() } )
887
1018
  let repair = { repaired: false }
888
1019
  if ( rupture.ruptured ) {
889
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
+
890
1025
  // Real cross-module side effects of an actual rupture, applied here
891
1026
  // (LoveHateEngine itself stays self-contained and returns a signal,
892
1027
  // same orchestration pattern Totemheart already uses for e.g. life
@@ -913,6 +1048,18 @@ export class Totemheart {
913
1048
  this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth + repair.egoHealthRestore )
914
1049
  this.explainability.logDecision( 'lovehate_repair', `relational repair #${repair.repairCount} for ${userId}` )
915
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
+
916
1063
  }
917
1064
 
918
1065
  }
@@ -965,11 +1112,36 @@ export class Totemheart {
965
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` )
966
1113
  this.expressionDebt.decay( 1 )
967
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
+
968
1127
  // Reputation / ego — a 'shame' reaction (submissive personalities) also drops the
969
1128
  // felt sense of Dominance directly and biases toward withdrawal, matching the
970
1129
  // real phenomenon (shame collapses posture/control, not just mood).
971
1130
  const reputation = this.reputationEngine.evaluate( appraisal, this.personality )
972
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
+
973
1145
  // Flush — purely internal analog of peripheral blood flow, a real first-order
974
1146
  // thermal lag driven by the shame/anger blend weight instead of a Navier-Stokes
975
1147
  // simulation (there's no skin here either). It outlasts its trigger the way a
@@ -1006,6 +1178,14 @@ export class Totemheart {
1006
1178
  const fairness = this.fairnessMonitor.evaluate( relation.affinity, othersTreatment )
1007
1179
  if ( fairness.envy > 0.15 ) this.emotionSpace.applySpike( { valence: -fairness.envy * 0.3, dominance: -fairness.envy * 0.2, weight: 0.4 } )
1008
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
+
1009
1189
  // Status envy — falling status while a known rival's rises, independent of
1010
1190
  // absolute treatment level (item 39's actual trigger condition).
1011
1191
  const selfTrend = this.statusEnvy.observe( userId, relation.powerDynamic )
@@ -1016,6 +1196,12 @@ export class Totemheart {
1016
1196
  const envyCheck = this.statusEnvy.checkEnvy( selfTrend, rivalTrend )
1017
1197
  if ( envyCheck.triggered ) this.emotionSpace.applySpike( { valence: -envyCheck.intensity * 0.3, arousal: envyCheck.intensity * 0.2, weight: 0.4 } )
1018
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
+
1019
1205
  }
1020
1206
 
1021
1207
  // Controllability — high estimated control over this kind of situation dampens
@@ -1088,6 +1274,14 @@ export class Totemheart {
1088
1274
  const guardedness = Math.min( 1, unresolvedCount * 0.2 )
1089
1275
  const blend = this.emotionSpace.getBlend( 3, neuroticism )
1090
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
+
1091
1285
  // Ego confidence — real Shannon entropy of the blend distribution (perplexity =
1092
1286
  // 2^H). A flat, confused blend reads as low self-confidence and drops Dominance
1093
1287
  // defensively — the honest triangulated version of "the model doubts itself".
@@ -1124,8 +1318,15 @@ export class Totemheart {
1124
1318
  // break above), it's also a plain cognitive-resource one.
1125
1319
  let suppressionDrive = characterBreak
1126
1320
  ? 0
1127
- : clamp01( this.personality.get( 'conscientiousness' ) * this.cortisolEngine.getLevel() + ( this._lifeEventSuppressionBoost ?? 0 ) + ( this._hijackAlertBoost ?? 0 ) ) * ( 1 - this.decisionFatigue.getLevel() )
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()
1128
1328
  this.decisionFatigue.recordDecision( suppressionDrive )
1329
+ this.egoDepletionBudget.spend( suppressionDrive * 0.3 )
1129
1330
  if ( this.decisionFatigue.isShallow() ) this.cortisolEngine.register( 0, true ) // sustained cognitive load reads as chronic ambient stress too
1130
1331
  // Real suppression cost: holding this back isn't free the instant it happens —
1131
1332
  // charges the reservoir tick()/drainSuppressionCost() pays out as DecisionFatigue
@@ -1148,6 +1349,7 @@ export class Totemheart {
1148
1349
  } )
1149
1350
  if ( suppressionDrive > 0.5 ) modulated.styleTags.push( 'suppressed' )
1150
1351
  if ( characterBreak ) modulated.styleTags.push( 'character_break' )
1352
+ if ( motivConflict.vacillating ) modulated.styleTags.push( 'conflicted' )
1151
1353
  if ( circadian.lowEnergyWindow && Math.random() < circadian.erraticChance ) {
1152
1354
 
1153
1355
  modulated.styleTags.push( 'drowsy' )
@@ -1165,6 +1367,17 @@ export class Totemheart {
1165
1367
  // to (real Attachment affinity, the same signal already driving TribalCategorization)
1166
1368
  // costs more than failing a stranger.
1167
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 )
1168
1381
  const projection = this.egoProjection.resolve( guilt, reputation.reaction )
1169
1382
  const regret = this.counterfactualComparison.computeRegret( this.emotionSpace.vector.valence, Math.max( 0, appraisal.desirability ?? 0 ) )
1170
1383
 
@@ -1194,6 +1407,13 @@ export class Totemheart {
1194
1407
  betrayalDetected : ( ontologyFlagsThreat && ontologyMatches.some( m => m.concept === 'betrayal' ) ) || uncannyValley.suspicious,
1195
1408
  }, this.personality )
1196
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
+
1197
1417
  // Bayesian expectation update — fold this turn's actual outcome into next
1198
1418
  // time's prior for this user.
1199
1419
  this.bayesianExpectation.update( userId, desirability > 0 )
@@ -1201,7 +1421,23 @@ export class Totemheart {
1201
1421
  // Close out this turn's reconsolidation window (if a memory was reactivated
1202
1422
  // above): blend its stored signature toward what actually got felt THIS turn.
1203
1423
  // A no-op if the window already closed or nothing was reactivated.
1204
- if ( reactivation ) this.episodicMemory.reconsolidate( reactivation.entry, this.emotionSpace.vector )
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
+ }
1205
1441
 
1206
1442
  await safeStep( this.explainability, 'episodicMemory.store', async () => this.episodicMemory.store( {
1207
1443
  text : input,
@@ -1234,6 +1470,7 @@ export class Totemheart {
1234
1470
  // hot last turn (residual) — not on every short, unrelated reply.
1235
1471
  const topicTrigger = this.triggerSentinel.check( 'topicSatiation', tokens, this._lastTopicFatigue ?? 0 )
1236
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
1237
1474
  this._lastTopicFatigue = topicSatiation.fatigue
1238
1475
 
1239
1476
  // Homeostasis: interacting satisfies socialization/curiosity. Drive — curiosity
@@ -1394,15 +1631,40 @@ export class Totemheart {
1394
1631
 
1395
1632
  const mood = this.moodTracker.getMood()
1396
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
+
1397
1643
  const valenceBefore = this.emotionSpace.vector.valence
1398
1644
  this.decayEngine.apply( this.emotionSpace, mood, this.personality, dt )
1399
1645
  this.controllabilityEstimate.observeOutcome( this.emotionSpace.getDominantEmotion(), valenceBefore, this.emotionSpace.vector.valence )
1400
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
+
1401
1657
  this.homeostasis.tick( dt, this.personality, { circadianEnergy: this.circadianRhythm.getEnergyLevel( new Date(), this.cortisolEngine.getLevel() ), cortisol: this.cortisolEngine.getLevel() } )
1402
- this.forgettingCurve.tick( this.episodicMemory, dt )
1658
+ this.forgettingCurve.tick( this.episodicMemory, subjectiveDt )
1403
1659
  this.decisionFatigue.decay( dt )
1404
1660
  this.cognitiveDissonance.decay( dt )
1405
- this.cortisolEngine.decay( dt )
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 )
1406
1668
  this.reputationEngine.regenerate( dt )
1407
1669
  this.selfModel.decay( dt )
1408
1670
  this.sensitization.decay( dt )
@@ -1536,6 +1798,16 @@ export class Totemheart {
1536
1798
  classicalConditioningAssociations : [ ...this.classicalConditioning.associations.entries() ],
1537
1799
  coreBeliefs : this.coreBeliefs.getAll(),
1538
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,
1539
1811
  }
1540
1812
 
1541
1813
  }
@@ -1571,6 +1843,16 @@ export class Totemheart {
1571
1843
  if ( data.classicalConditioningAssociations ) this.classicalConditioning.associations = new Map( data.classicalConditioningAssociations )
1572
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 )
1573
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
1574
1856
 
1575
1857
  }
1576
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
+ }