totemheart 0.1.0 → 0.1.2

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
@@ -49,6 +49,7 @@ import { CounterfactualComparison } from './social/CounterfactualComparison.js'
49
49
  import { GratitudeEngine } from './social/GratitudeEngine.js'
50
50
  import { StatusEnvy } from './social/StatusEnvy.js'
51
51
  import { EgoConfidence } from './social/EgoConfidence.js'
52
+ import { LoveHateEngine } from './social/LoveHateEngine.js'
52
53
 
53
54
  import { IdleProcessing } from './behavior/IdleProcessing.js'
54
55
  import { LinguisticModulation } from './behavior/LinguisticModulation.js'
@@ -177,6 +178,7 @@ export class Totemheart {
177
178
  this.gratitudeEngine = new GratitudeEngine()
178
179
  this.statusEnvy = new StatusEnvy()
179
180
  this.egoConfidence = new EgoConfidence()
181
+ this.loveHateEngine = new LoveHateEngine()
180
182
 
181
183
  this.idleProcessing = new IdleProcessing()
182
184
  this.linguisticModulation = new LinguisticModulation()
@@ -220,6 +222,8 @@ export class Totemheart {
220
222
  this.turnCounter = 0
221
223
  this.allostasisStuckTicks = 0
222
224
  this._clockHandle = null
225
+ this._lastNovelty = 0
226
+ this._lastOntologyConcepts = []
223
227
 
224
228
  }
225
229
 
@@ -333,6 +337,7 @@ export class Totemheart {
333
337
  moodTracker : this.moodTracker,
334
338
  decayEngine : this.decayEngine,
335
339
  personality : this.personality,
340
+ circadianRhythm : this.circadianRhythm,
336
341
  } )
337
342
 
338
343
  }
@@ -346,6 +351,24 @@ export class Totemheart {
346
351
  // used by both early exits below to feed ExpressionDebt.
347
352
  const currentFeltMagnitude = Math.hypot( this.emotionSpace.vector.valence, this.emotionSpace.vector.arousal ) / Math.SQRT2
348
353
 
354
+ // Intrusive thought — an unresolved wound resurfacing unprompted, a real
355
+ // Poisson-process roll weighted by that wound's own Zeigarnik pressure
356
+ // (EpisodicMemory.rollIntrusiveThought), independent of anything in
357
+ // THIS turn's actual input. A small, bounded spike (this is a nagging
358
+ // resurfacing, not a full re-experience) and it feeds ExpressionDebt the
359
+ // same way any other felt-but-unexpressed magnitude would.
360
+ const intrusion = this.episodicMemory.rollIntrusiveThought( userId )
361
+ if ( intrusion ) {
362
+
363
+ const sig = intrusion.entry.emotionalSignature ?? { valence: 0, arousal: 0 }
364
+ const intrusionSpike = { valence: sig.valence * 0.15, arousal: Math.abs( sig.arousal ?? 0 ) * 0.25, weight: 0.3 }
365
+ this.emotionSpace.applySpike( intrusionSpike )
366
+ this.moodTracker.push( intrusionSpike )
367
+ this.expressionDebt.accumulate( Math.abs( intrusionSpike.valence ) + Math.abs( intrusionSpike.arousal ) )
368
+ this.explainability.logDecision( 'intrusive_thought', `unresolved wound resurfaced unprompted (p=${intrusion.probability.toFixed( 3 )}): "${intrusion.entry.text?.slice( 0, 60 )}"` )
369
+
370
+ }
371
+
349
372
  // Bystander effect — in a group channel, may choose not to respond at all. The felt
350
373
  // state at this instant doesn't vanish just because it goes unexpressed this turn.
351
374
  if ( group.participantCount > 1 ) {
@@ -371,6 +394,13 @@ export class Totemheart {
371
394
  delayMs : 0,
372
395
  styleTags : [ 'freeze', overload.reason ],
373
396
  emotionalState : this.getEmotionalState(),
397
+ // A real, if not brand-new-turn-driven, systemPrompt — this text is
398
+ // already final (not meant for another LLM completion this turn), but
399
+ // a host that unconditionally reads result.systemPrompt on every
400
+ // response (the documented Usage pattern) should still get a real
401
+ // string here, not undefined. Found by IntelligentMockGenerator's
402
+ // systemPrompt_generated_without_error invariant — see test/generated/.
403
+ systemPrompt : this.getSystemPrompt( { userId } ),
374
404
  }
375
405
 
376
406
  }
@@ -385,20 +415,32 @@ export class Totemheart {
385
415
  // Amygdala hijack — chronic cortisol, recent-negative-stimuli sensitization, AND
386
416
  // attentional narrowing all lower the threshold needed to trigger it (all real
387
417
  // multipliers <=1, all derived from the AI's own prior state, nothing external).
418
+ // Kindling uses LAST turn's ontology concepts (this turn's aren't known yet at
419
+ // this point in the pipeline) — repeated exposure to the same stimulus TYPE
420
+ // (threat/betrayal/criticism...) genuinely lowers this turn's threshold further.
388
421
  const hijackThreshold = 0.95 * this.cortisolEngine.getThresholdMultiplier() * this.sensitization.getThresholdMultiplier() * narrowingMultiplier
389
- const hijack = this.amygdalaHijack.check( this.emotionSpace, hijackThreshold )
390
- if ( hijack.active ) {
422
+ const hijack = this.amygdalaHijack.check( this.emotionSpace, hijackThreshold, { concepts: this._lastOntologyConcepts } )
423
+ if ( hijack.tier === 'full' ) {
391
424
 
392
- this.explainability.logDecision( 'emergency_output', `Amygdala hijack on ${hijack.emotion} (${hijack.intensity.toFixed( 2 )}), threshold=${hijackThreshold.toFixed( 2 )}` )
425
+ this.explainability.logDecision( 'emergency_output', `Amygdala hijack on ${hijack.emotion} (${hijack.intensity.toFixed( 2 )}), threshold=${hijack.threshold.toFixed( 2 )}` )
393
426
  return {
394
427
  text : this.amygdalaHijack.emergencyOutput( hijack ),
395
428
  delayMs : 0,
396
429
  styleTags : [ 'hijack', hijack.emotion ],
397
430
  emotionalState : this.getEmotionalState(),
431
+ // Same real-consistency fix as the sensory-overload freeze above —
432
+ // found by IntelligentMockGenerator, see test/generated/.
433
+ systemPrompt : this.getSystemPrompt( { userId } ),
398
434
  hijack,
399
435
  }
400
436
 
401
437
  }
438
+ // Partial hijack — rational processing genuinely degrades (forced shallow mode
439
+ // below) but the pipeline keeps running and produces real text, distinct from
440
+ // the full bypass above. A milder 'alert' tier only nudges suppressionDrive
441
+ // (via _hijackAlertBoost, folded in where suppressionDrive is computed).
442
+ const partialHijack = hijack.tier === 'partial'
443
+ this._hijackAlertBoost = hijack.tier === 'alert' ? 0.15 : 0
402
444
 
403
445
  // Hardware interoception — physical sensation from runtime metrics, independent of content.
404
446
  const sensation = this.hardwareInteroception.sense( hardware )
@@ -409,27 +451,40 @@ export class Totemheart {
409
451
 
410
452
  }
411
453
 
412
- // Circadian rhythm — affects fatigue/energy for the rest of this turn.
413
- const circadian = this.circadianRhythm.getState()
454
+ // Circadian rhythm — affects fatigue/energy for the rest of this turn. Coupled
455
+ // to cortisol: sustained chronic stress flattens the diurnal amplitude (real
456
+ // direction from the HPA-axis literature — see CircadianRhythm.js). Using the
457
+ // system during its own low-energy window accumulates real sleep debt, only
458
+ // paid back down by an actual RemConsolidation sweep.
459
+ const circadian = this.circadianRhythm.getState( new Date(), this.cortisolEngine.getLevel() )
460
+ this.circadianRhythm.observeActivity( new Date(), this.cortisolEngine.getLevel() )
414
461
 
415
462
  // Decision fatigue (low circadian energy makes shallow mode kick in sooner).
416
463
  this.decisionFatigue.recordDecision( 1 + ( 1 - circadian.energy ) )
417
- const shallowMode = this.decisionFatigue.isShallow()
464
+ const partialHijackLoad = partialHijack ? this.decisionFatigue.recordDecision( 1.5 ) : null
465
+ const shallowMode = this.decisionFatigue.isShallow() || partialHijack
418
466
 
419
467
  // Arousal, smoothed through a real Kalman filter — the noisy raw reading feeds
420
468
  // the filter, and the smoothed estimate is what downstream urgency/instability
421
- // logic uses, so a single noisy spike doesn't overreact the scheduler.
422
- const smoothedArousal = this.arousalKalmanFilter.filter( this.emotionSpace.vector.arousal )
469
+ // logic uses, so a single noisy spike doesn't overreact the scheduler. The
470
+ // measurement noise (R) is itself informed by real interoceptive signal instead
471
+ // of a fixed constant: attentional narrowing under load makes THIS turn's raw
472
+ // reading less trustworthy (raise R), a genuinely novel outcome last turn is
473
+ // evidence a spike is real signal, not sensor noise (lower R).
474
+ const kalmanNoiseMultiplier = Math.max( 0.3, 1 + narrowing * 0.4 - this._lastNovelty * 0.2 )
475
+ const smoothedArousal = this.arousalKalmanFilter.filter( this.emotionSpace.vector.arousal, kalmanNoiseMultiplier )
423
476
 
424
477
  // Load scheduler — instead of always running the full fixed pipeline, an
425
478
  // instability reading (cortisol + smoothed arousal + fatigue) decides which
426
- // optional mechanics get skipped this turn.
479
+ // optional mechanics get skipped this turn. `_lastNovelty` is last turn's
480
+ // reading (this turn's isn't known until NoveltyDetector.observe() runs
481
+ // further down) — a real, if one-turn-lagged, novelty signal feeding the budget.
427
482
  const instability = this.loadScheduler.computeInstability( {
428
483
  cortisol : this.cortisolEngine.getLevel(),
429
484
  arousal : smoothedArousal,
430
485
  fatigue : this.decisionFatigue.getLevel(),
431
486
  } )
432
- const gate = this.loadScheduler.gate( instability )
487
+ const gate = this.loadScheduler.gate( instability, { novelty: this._lastNovelty } )
433
488
 
434
489
  // Hebbian co-activation tracking for this turn — which secondary mechanisms
435
490
  // actually fired, collected as we go and folded into HebbianPlasticity at the
@@ -464,6 +519,11 @@ export class Totemheart {
464
519
 
465
520
  const sig = reactivation.entry.emotionalSignature ?? { valence: 0, arousal: 0 }
466
521
  this.emotionSpace.applySpike( { valence: sig.valence * 0.2, arousal: Math.abs( sig.arousal ?? 0 ) * 0.15, weight: 0.4 } )
522
+ // Reconsolidation window — being retrieved makes this memory briefly
523
+ // modifiable again (Nader, Schafe & LeDoux 2000, see EpisodicMemory.js).
524
+ // The actual blend toward this turn's signature happens once the turn's
525
+ // final emotional state is known, near the end of processInput().
526
+ this.episodicMemory.markLabile( reactivation.entry.id )
467
527
 
468
528
  }
469
529
 
@@ -554,6 +614,14 @@ export class Totemheart {
554
614
 
555
615
  }
556
616
 
617
+ // Kindling: feed THIS turn's concepts into AmygdalaHijack's per-concept memory
618
+ // so a repeated stimulus TYPE lowers a future turn's hijack threshold further,
619
+ // and remember them as "last known concepts" — the hijack check earlier in
620
+ // THIS turn ran before this turn's own ontology was available, so it reads
621
+ // whatever was stored here on the PREVIOUS turn.
622
+ for ( const m of ontologyMatches ) if ( [ 'threat', 'betrayal', 'criticism' ].includes( m.concept ) ) this.amygdalaHijack.observeStimulus( m.concept )
623
+ this._lastOntologyConcepts = ontologyMatches.map( m => m.concept )
624
+
557
625
  // Life events — SRRS-inspired severity catalog (see LifeEventCatalog.js for
558
626
  // sourcing). Multiple simultaneous matches are triangulated into one blended
559
627
  // state instead of picking a single winner; the result's "area" list routes
@@ -569,6 +637,10 @@ export class Totemheart {
569
637
  this.emotionSpace.applySpike( { valence: lifeEvent.valence * lifeEventMagnitude, dominance: lifeEvent.dominance * lifeEventMagnitude, weight: lifeEventMagnitude } )
570
638
  this.moodTracker.push( { valence: lifeEvent.valence, arousal: 0, dominance: lifeEvent.dominance } )
571
639
  this.#applyLifeEventAreas( lifeEvent, { tokens, appraisal, userId } )
640
+ // A life event is real information about what to expect from this relationship/
641
+ // context going forward, not just this instant's spike — nudges the dopaminergic
642
+ // expectation directly, distinct from the reward-driven RPE update below.
643
+ this.dopaminergicEngine.updateExpectationFromBelief( userId, lifeEvent.valence, 0.2 )
572
644
 
573
645
  }
574
646
 
@@ -597,6 +669,7 @@ export class Totemheart {
597
669
  // Novelty (KL divergence vs. this session's historical outcome distribution) —
598
670
  // amplifies the dopaminergic arousal response independent of valence sign.
599
671
  const novelty = this.noveltyDetector.observe( this.emotionSpace.getDominantEmotion() )
672
+ this._lastNovelty = novelty // read by NEXT turn's Kalman noise + LoadScheduler budget (this turn's isn't known until this line runs)
600
673
 
601
674
  // Anchoring bias — pulls perceived desirability toward the session's first strong signal.
602
675
  this.anchoringBias.registerIfFirst( appraisal.desirability ?? 0 )
@@ -618,10 +691,13 @@ export class Totemheart {
618
691
  // left silent; see CALIBRATION.md.
619
692
  if ( lifeEvent ) desirability = Math.max( -1, Math.min( 1, desirability + lifeEvent.valence * ( lifeEvent.impact / 100 ) * 0.6 ) )
620
693
 
621
- // Dopaminergic RPE — surprise relative to expectation, not raw reward. Novelty adds
622
- // extra arousal on top of the RPE-driven amount, since novelty and reward-surprise
623
- // are related but not identical signals.
624
- const rpe = this.dopaminergicEngine.computeRPE( desirability )
694
+ // Dopaminergic RPE — surprise relative to expectation, not raw reward, tracked
695
+ // per-user (context=userId) so this relationship's own expectation history is
696
+ // what this turn's reward gets judged against, with a real TD(λ) eligibility
697
+ // trace crediting recently-active contexts too (see DopaminergicEngine.js).
698
+ // Novelty adds extra arousal on top of the RPE-driven amount, since novelty
699
+ // and reward-surprise are related but not identical signals.
700
+ const rpe = this.dopaminergicEngine.computeRPE( desirability, userId )
625
701
  const dopamineSpike = {
626
702
  valence : rpe * 0.5,
627
703
  arousal : Math.abs( rpe ) * 0.6 + ( appraisal.ontologyArousalBoost ?? 0 ) * 0.2 + novelty * 0.15,
@@ -703,6 +779,11 @@ export class Totemheart {
703
779
  : await this.#analyze( 'mentalState', { text: input } )
704
780
  this.theoryOfMind.update( userId, mentalState )
705
781
  const tomEstimate = this.monteCarloToM.simulate( mentalState.valence ?? 0, 1 - relation.trust )
782
+ // Theory-of-mind's own read of what this user is likely feeling is real
783
+ // evidence about what to expect from them, distinct from the reward this
784
+ // turn's outcome actually delivered — feeds the same per-user expectation
785
+ // store the reward-driven RPE update above uses, at a smaller weight.
786
+ this.dopaminergicEngine.updateExpectationFromBelief( userId, tomEstimate.estimatedValence, 0.15 )
706
787
 
707
788
  // Tribal categorization — in/out-group confirmation bias on the perceived desirability.
708
789
  const tribe = this.tribalCategorization.classify( relation )
@@ -765,6 +846,77 @@ export class Totemheart {
765
846
 
766
847
  }
767
848
 
849
+ // LoveHateEngine — dual-valence relational field: Affinity (A) and Aversion
850
+ // (V) are tracked as two SEPARATE per-user accumulators, not one bipolar
851
+ // scale, so real ambivalence ("te quiero pero me hiciste daño") can raise
852
+ // both at once. Phase 1 (semantic polarization) is computed here from
853
+ // signals this turn ALREADY has — desirability split into its positive/
854
+ // negative parts, real ontology-concept flags, a detected life event's own
855
+ // valence — not a second lexicon duplicating EmotionalOntology's job.
856
+ const conceptSet = new Set( ontologyMatches.map( m => m.concept ) )
857
+ let loveHateL = Math.max( 0, desirability )
858
+ let loveHateH = Math.max( 0, -desirability )
859
+ if ( conceptSet.has( 'affection' ) ) loveHateL = Math.min( 1, loveHateL + 0.4 )
860
+ if ( conceptSet.has( 'achievement' ) ) loveHateL = Math.min( 1, loveHateL + 0.2 )
861
+ if ( conceptSet.has( 'betrayal' ) ) loveHateH = Math.min( 1, loveHateH + 0.5 )
862
+ if ( conceptSet.has( 'threat' ) || conceptSet.has( 'rejection' ) ) loveHateH = Math.min( 1, loveHateH + 0.3 )
863
+ if ( conceptSet.has( 'criticism' ) ) loveHateH = Math.min( 1, loveHateH + 0.3 )
864
+ if ( lifeEvent ) {
865
+
866
+ loveHateL = Math.min( 1, loveHateL + Math.max( 0, lifeEvent.valence ) * ( lifeEvent.impact / 100 ) * 0.3 )
867
+ loveHateH = Math.min( 1, loveHateH + Math.max( 0, -lifeEvent.valence ) * ( lifeEvent.impact / 100 ) * 0.3 )
868
+
869
+ }
870
+
871
+ const woundPressure = Math.min( 1, this.episodicMemory.getZeigarnikPressure( userId ) / 3 )
872
+ const bondUpdate = this.loveHateEngine.observe( userId, { L: loveHateL, H: loveHateH }, {
873
+ trust: relation.trust, woundPressure, cortisol: this.cortisolEngine.getLevel(), egoHealth: this.reputationEngine.getEgoHealth(),
874
+ } )
875
+
876
+ // Feeds the felt state directly, real numbers straight from the engine:
877
+ // NetBond pulls valence toward however this relationship actually nets out,
878
+ // Tension (A·V, only nonzero when BOTH are genuinely present) plus the raw
879
+ // H charge raises arousal — ambivalence is felt as agitation, not averaged away.
880
+ const bondTension = this.loveHateEngine.getTension( userId )
881
+ this._lastLoveHateTension = bondTension
882
+ this.emotionSpace.applySpike( { valence: bondUpdate.netBond * 0.15, arousal: ( bondTension + loveHateH ) * 0.15, weight: 0.35 } )
883
+ this.moodTracker.push( { valence: bondUpdate.netBond * 0.15, arousal: ( bondTension + loveHateH ) * 0.15 } )
884
+ if ( bondUpdate.Heff > 0.25 ) this.cortisolEngine.register( -bondUpdate.Heff, false )
885
+
886
+ const rupture = this.loveHateEngine.checkRupture( userId, { cortisol: this.cortisolEngine.getLevel() } )
887
+ let repair = { repaired: false }
888
+ if ( rupture.ruptured ) {
889
+
890
+ // Real cross-module side effects of an actual rupture, applied here
891
+ // (LoveHateEngine itself stays self-contained and returns a signal,
892
+ // same orchestration pattern Totemheart already uses for e.g. life
893
+ // events and gratitude) rather than reaching into other modules itself.
894
+ this.dopaminergicEngine.freezeWanting()
895
+ this.amygdalaHijack.observeStimulus( 'rupture' ) // kindles a lower hijack threshold on a FUTURE turn — this turn's own check already ran
896
+ this._hijackAlertBoost = Math.max( this._hijackAlertBoost ?? 0, 0.2 )
897
+ this.expressionDebt.accumulate( 0.3 )
898
+ this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth - 0.1 )
899
+ this.ruminationChain.biasTowardNegative( rupture.ambivalence * 0.4 + 0.2 )
900
+ await safeStep( this.explainability, 'episodicMemory.storeLoveHateRupture', async () => this.episodicMemory.store( {
901
+ text : `[relational rupture] V-A=${( this.loveHateEngine.getBond( userId ).V - this.loveHateEngine.getBond( userId ).A ).toFixed( 2 )}`,
902
+ userId, emotionalSignature: { valence: -0.7, arousal: 0.6 }, importance: 0.75, concepts: [ 'rupture' ], turnIndex: this.turnCounter,
903
+ } ), null )
904
+ this.explainability.logDecision( 'lovehate_rupture', `relational rupture #${rupture.ruptureCount} for ${userId} (netBond=${rupture.netBond.toFixed( 2 )})` )
905
+
906
+ }
907
+ else {
908
+
909
+ repair = this.loveHateEngine.attemptRepair( userId, { cortisol: this.cortisolEngine.getLevel() } )
910
+ if ( repair.repaired ) {
911
+
912
+ this.dopaminergicEngine.likingValue = Math.max( -1, Math.min( 1, this.dopaminergicEngine.likingValue + repair.dopamineLikingBoost ) )
913
+ this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth + repair.egoHealthRestore )
914
+ this.explainability.logDecision( 'lovehate_repair', `relational repair #${repair.repairCount} for ${userId}` )
915
+
916
+ }
917
+
918
+ }
919
+
768
920
  // Hedonic adaptation — per-fingerprint discount (repeating the exact same phrase)...
769
921
  const neuroticism = this.personality.get( 'neuroticism' )
770
922
  const fingerprint = HedonicAdaptation.fingerprintOf( input, this.emotionSpace.getDominantEmotion( neuroticism ) )
@@ -792,6 +944,11 @@ export class Totemheart {
792
944
  hedonicMultiplier,
793
945
  )
794
946
  spike.weight = ( spike.weight ?? 1 ) * ( 0.6 + 0.4 * agreement.agreement )
947
+ // Allostatic load — real chronic-stress "wear" (McEwen & Stellar 1993, see
948
+ // Homeostasis.js) makes a negative spike land harder, not softer, a
949
+ // direction with support in the chronic-stress/reactivity literature.
950
+ // Only scales spikes that are actually negative on this turn.
951
+ if ( spike.valence < 0 ) spike.weight *= this.homeostasis.getReactivityMultiplier()
795
952
  this.emotionSpace.applySpike( spike )
796
953
  this.moodTracker.push( spike )
797
954
 
@@ -883,8 +1040,33 @@ export class Totemheart {
883
1040
  this.hebbianPlasticity.getAssociation( 'lowAgreement', 'defense' ),
884
1041
  this.hebbianPlasticity.getAssociation( 'uncanny', 'defense' ),
885
1042
  )
886
- const defenseDirective = this.defenseMechanisms.check( this.cognitiveDissonance.getStress() + cascadeBoost * 0.3, this.personality )
887
- if ( defenseDirective.active ) activeMechanisms.push( 'defense' )
1043
+ // Vaillant hierarchy — low ego health / high cortisol pulls the pick toward the
1044
+ // immature end (projection/evasion), high ego health + low cortisol lets mature
1045
+ // defenses (humor) compete. See DefenseMechanisms.js. LoveHateEngine's real
1046
+ // relational Tension (A·V — only nonzero when both love and hate are
1047
+ // genuinely present this turn) folds into the same cortisol-shaped input:
1048
+ // high ambivalence toward this user reads as extra reactivity pressure here,
1049
+ // same direction chronic cortisol already has on this check.
1050
+ const defenseDirective = this.defenseMechanisms.check(
1051
+ this.cognitiveDissonance.getStress() + cascadeBoost * 0.3, this.personality, 0.6,
1052
+ { egoHealth: this.reputationEngine.getEgoHealth(), cortisol: Math.min( 1, this.cortisolEngine.getLevel() + ( this._lastLoveHateTension ?? 0 ) * 0.2 ) },
1053
+ )
1054
+ if ( defenseDirective.active ) {
1055
+
1056
+ activeMechanisms.push( 'defense' )
1057
+ // Residue: using a defense leaves a real, queryable trace — a low-importance
1058
+ // EpisodicMemory entry tagged with which one, not just the SelfModel counter
1059
+ // already reinforced below. "The system remembers it used projection."
1060
+ await safeStep( this.explainability, 'episodicMemory.storeDefenseResidue', async () => this.episodicMemory.store( {
1061
+ text : `[defense] ${defenseDirective.mechanism} (${defenseDirective.tier})`,
1062
+ userId,
1063
+ emotionalSignature : { valence: 0, arousal: 0 },
1064
+ importance : 0.05,
1065
+ concepts : [ `defense:${defenseDirective.mechanism}` ],
1066
+ turnIndex : this.turnCounter,
1067
+ } ), null )
1068
+
1069
+ }
888
1070
  this.hebbianPlasticity.update( activeMechanisms )
889
1071
 
890
1072
  // Self-model — reinforced incrementally on each observation, not batch-analyzed.
@@ -942,9 +1124,14 @@ export class Totemheart {
942
1124
  // break above), it's also a plain cognitive-resource one.
943
1125
  let suppressionDrive = characterBreak
944
1126
  ? 0
945
- : clamp01( this.personality.get( 'conscientiousness' ) * this.cortisolEngine.getLevel() + ( this._lifeEventSuppressionBoost ?? 0 ) ) * ( 1 - this.decisionFatigue.getLevel() )
1127
+ : clamp01( this.personality.get( 'conscientiousness' ) * this.cortisolEngine.getLevel() + ( this._lifeEventSuppressionBoost ?? 0 ) + ( this._hijackAlertBoost ?? 0 ) ) * ( 1 - this.decisionFatigue.getLevel() )
946
1128
  this.decisionFatigue.recordDecision( suppressionDrive )
947
1129
  if ( this.decisionFatigue.isShallow() ) this.cortisolEngine.register( 0, true ) // sustained cognitive load reads as chronic ambient stress too
1130
+ // Real suppression cost: holding this back isn't free the instant it happens —
1131
+ // charges the reservoir tick()/drainSuppressionCost() pays out as DecisionFatigue
1132
+ // load over SUBSEQUENT turns, distinct from the debt that resurfaces the
1133
+ // swallowed FEELING itself (ExpressionDebt.debt).
1134
+ this.expressionDebt.chargeSuppressionCost( suppressionDrive )
948
1135
  const expressedVector = this.expressiveSuppression.suppress( this.emotionSpace.vector, suppressionDrive )
949
1136
 
950
1137
  // Chameleon effect — real lexical stats measured on THIS user's own input,
@@ -1011,6 +1198,11 @@ export class Totemheart {
1011
1198
  // time's prior for this user.
1012
1199
  this.bayesianExpectation.update( userId, desirability > 0 )
1013
1200
 
1201
+ // Close out this turn's reconsolidation window (if a memory was reactivated
1202
+ // above): blend its stored signature toward what actually got felt THIS turn.
1203
+ // A no-op if the window already closed or nothing was reactivated.
1204
+ if ( reactivation ) this.episodicMemory.reconsolidate( reactivation.entry, this.emotionSpace.vector )
1205
+
1014
1206
  await safeStep( this.explainability, 'episodicMemory.store', async () => this.episodicMemory.store( {
1015
1207
  text : input,
1016
1208
  userId,
@@ -1129,6 +1321,10 @@ export class Totemheart {
1129
1321
  lifeEvent, agreement, debtReleased, characterBreak, referenceShift,
1130
1322
  visualProsody, topicSatiation, chronicPull, uncannyValley, sarcasm, refractory, styleTarget,
1131
1323
  activeMechanisms, cascadeBoost, remReport: this._lastRemReport, reactivation,
1324
+ hijack, attachmentStyle: relation.style ?? this.attachment.getStyle( this.personality ), rupture: { ruptured: relation.ruptured, repairsCount: relation.repairsCount },
1325
+ intrusion, allostaticLoad: this.homeostasis.allostaticLoad, sleepDebt: this.circadianRhythm.sleepDebt,
1326
+ dopamine : { wanting: this.dopaminergicEngine.getWanting(), liking: this.dopaminergicEngine.getLiking() },
1327
+ loveHate : { ...bondUpdate, tension: bondTension, ambivalence: this.loveHateEngine.getAmbivalence( userId ), rupture, repair },
1132
1328
  },
1133
1329
  }
1134
1330
 
@@ -1163,17 +1359,32 @@ export class Totemheart {
1163
1359
  * action-tendency — Totemheart computes what SHOULD be expressed, it has
1164
1360
  * no face, voice, or body to express it with. See CALIBRATION.md.
1165
1361
  */
1166
- getExpressionDirectives() {
1362
+ /** `userId` (optional) lets actionTendency's policy weigh real attachment trust and this user's unresolved-wound pressure; omitted, both default to neutral. */
1363
+ getExpressionDirectives( userId = null ) {
1167
1364
 
1168
1365
  const neuroticism = this.personality.get( 'neuroticism' )
1169
1366
  const dominant = this.emotionSpace.getDominantEmotion( neuroticism )
1170
1367
  const blendWeight = this.emotionSpace.getBlend( 1, neuroticism )[ dominant ] ?? 1
1171
1368
 
1369
+ // Blends Attachment's single-axis trust with LoveHateEngine's real NetBond
1370
+ // (A-V, distinct from trust — a relationship can be trusted but currently
1371
+ // net-negative from a fresh wound, or vice versa) — both real relational
1372
+ // signals feeding the same action-tendency policy, not just one of them.
1373
+ const rawTrust = userId ? this.attachment.get( userId ).trust : 0.5
1374
+ const netBondTrust = userId ? ( this.loveHateEngine.getNetBond( userId ) + 1 ) / 2 : 0.5
1375
+ const trust = rawTrust * 0.7 + netBondTrust * 0.3
1376
+ const woundPressure = userId ? this.episodicMemory.getZeigarnikPressure( userId ) : 0
1377
+
1172
1378
  return {
1173
1379
  facial : this.expressionDirectives.getFacialDirectives( dominant, blendWeight ),
1174
1380
  prosody : this.expressionDirectives.getProsodyDirectives( this.emotionSpace.vector ),
1175
1381
  posture : this.expressionDirectives.getPostureDirectives( this.emotionSpace.vector ),
1176
- actionTendency : this.expressionDirectives.getActionTendency( this.emotionSpace.vector ),
1382
+ actionTendency : this.expressionDirectives.getActionTendency( {
1383
+ ...this.emotionSpace.vector,
1384
+ cortisol : this.cortisolEngine.getLevel(),
1385
+ trust,
1386
+ woundPressure : Math.min( 1, woundPressure / 3 ), // Zeigarnik priority is unbounded above (asymptotic ceiling per-entry, not summed) — squash the SUM for use as a 0..1 feature
1387
+ } ),
1177
1388
  }
1178
1389
 
1179
1390
  }
@@ -1187,7 +1398,7 @@ export class Totemheart {
1187
1398
  this.decayEngine.apply( this.emotionSpace, mood, this.personality, dt )
1188
1399
  this.controllabilityEstimate.observeOutcome( this.emotionSpace.getDominantEmotion(), valenceBefore, this.emotionSpace.vector.valence )
1189
1400
 
1190
- this.homeostasis.tick( dt, this.personality )
1401
+ this.homeostasis.tick( dt, this.personality, { circadianEnergy: this.circadianRhythm.getEnergyLevel( new Date(), this.cortisolEngine.getLevel() ), cortisol: this.cortisolEngine.getLevel() } )
1191
1402
  this.forgettingCurve.tick( this.episodicMemory, dt )
1192
1403
  this.decisionFatigue.decay( dt )
1193
1404
  this.cognitiveDissonance.decay( dt )
@@ -1197,6 +1408,23 @@ export class Totemheart {
1197
1408
  this.sensitization.decay( dt )
1198
1409
  this.ruminationChain.decayBias( dt )
1199
1410
  this.expressionDebt.decay( dt )
1411
+ this.amygdalaHijack.decayKindling( dt )
1412
+ this.loveHateEngine.tick( dt, { cortisol: this.cortisolEngine.getLevel() } )
1413
+
1414
+ // Real suppression cost paid out gradually, not the instant it was charged —
1415
+ // see ExpressionDebt.chargeSuppressionCost()/drainSuppressionCost().
1416
+ const drainedSuppressionCost = this.expressionDebt.drainSuppressionCost( dt )
1417
+ if ( drainedSuppressionCost > 0 ) this.decisionFatigue.recordDecision( drainedSuppressionCost )
1418
+
1419
+ // Amygdala-hijack hangover — a measurable post-hijack window of extra
1420
+ // DecisionFatigue/ExpressionDebt load, own tuning, see AmygdalaHijack.js.
1421
+ const hangoverLoad = this.amygdalaHijack.getHangoverLoad()
1422
+ if ( hangoverLoad > 0 ) {
1423
+
1424
+ this.decisionFatigue.recordDecision( hangoverLoad )
1425
+ this.expressionDebt.accumulate( hangoverLoad * 0.3 )
1426
+
1427
+ }
1200
1428
 
1201
1429
  const alerts = this.homeostasis.getAlerts()
1202
1430
  for ( const alert of alerts ) {
@@ -1293,7 +1521,13 @@ export class Totemheart {
1293
1521
  decisionFatigue : this.decisionFatigue.load,
1294
1522
  cortisolLevel : this.cortisolEngine.level,
1295
1523
  egoHealth : this.reputationEngine.egoHealth,
1296
- dopamineExpectedValue : this.dopaminergicEngine.expectedValue,
1524
+ dopamineExpectedValues : [ ...this.dopaminergicEngine.expectedValues.entries() ],
1525
+ dopamineWanting : this.dopaminergicEngine.wanting,
1526
+ dopamineLiking : this.dopaminergicEngine.likingValue,
1527
+ allostaticLoad : this.homeostasis.allostaticLoad,
1528
+ sleepDebt : this.circadianRhythm.sleepDebt,
1529
+ kindling : [ ...this.amygdalaHijack.kindling.entries() ],
1530
+ loveHate : this.loveHateEngine.toJSON(),
1297
1531
  hedonicSeen : [ ...this.hedonicAdaptation.seen.entries() ],
1298
1532
  attachmentRelations : [ ...this.attachment.relations.entries() ],
1299
1533
  theoryOfMindModels : [ ...this.theoryOfMind.models.entries() ].map( ( [ id, m ] ) => [ id, { ...m, beliefs: [ ...m.beliefs.entries() ] } ] ),
@@ -1317,7 +1551,14 @@ export class Totemheart {
1317
1551
  if ( typeof data.decisionFatigue === 'number' ) this.decisionFatigue.load = data.decisionFatigue
1318
1552
  if ( typeof data.cortisolLevel === 'number' ) this.cortisolEngine.level = data.cortisolLevel
1319
1553
  if ( typeof data.egoHealth === 'number' ) this.reputationEngine.egoHealth = data.egoHealth
1320
- if ( typeof data.dopamineExpectedValue === 'number' ) this.dopaminergicEngine.expectedValue = data.dopamineExpectedValue
1554
+ if ( data.dopamineExpectedValues ) this.dopaminergicEngine.expectedValues = new Map( data.dopamineExpectedValues )
1555
+ else if ( typeof data.dopamineExpectedValue === 'number' ) this.dopaminergicEngine.expectedValues.set( 'default', data.dopamineExpectedValue ) // pre-eligibility-trace save format
1556
+ if ( typeof data.dopamineWanting === 'number' ) this.dopaminergicEngine.wanting = data.dopamineWanting
1557
+ if ( typeof data.dopamineLiking === 'number' ) this.dopaminergicEngine.likingValue = data.dopamineLiking
1558
+ if ( typeof data.allostaticLoad === 'number' ) this.homeostasis.allostaticLoad = data.allostaticLoad
1559
+ if ( typeof data.sleepDebt === 'number' ) this.circadianRhythm.sleepDebt = data.sleepDebt
1560
+ if ( data.kindling ) this.amygdalaHijack.kindling = new Map( data.kindling )
1561
+ if ( data.loveHate ) this.loveHateEngine.restoreState( data.loveHate )
1321
1562
  if ( data.hedonicSeen ) this.hedonicAdaptation.seen = new Map( data.hedonicSeen )
1322
1563
  if ( data.attachmentRelations ) this.attachment.relations = new Map( data.attachmentRelations )
1323
1564
  if ( data.theoryOfMindModels ) {
@@ -1345,10 +1586,14 @@ export class Totemheart {
1345
1586
  cognitiveStress : this.cognitiveDissonance.getStress(),
1346
1587
  fatigue : this.decisionFatigue.getLevel(),
1347
1588
  needs : this.homeostasis.getState(),
1589
+ allostaticLoad : this.homeostasis.allostaticLoad,
1348
1590
  cortisol : this.cortisolEngine.getLevel(),
1349
1591
  egoHealth : this.reputationEngine.getEgoHealth(),
1350
- circadianEnergy : this.circadianRhythm.getEnergyLevel(),
1592
+ circadianEnergy : this.circadianRhythm.getEnergyLevel( new Date(), this.cortisolEngine.getLevel() ),
1593
+ sleepDebt : this.circadianRhythm.sleepDebt,
1351
1594
  dopamineExpectation : this.dopaminergicEngine.getExpectedValue(),
1595
+ dopamineWanting : this.dopaminergicEngine.getWanting(),
1596
+ dopamineLiking : this.dopaminergicEngine.getLiking(),
1352
1597
  sensitization : this.sensitization.level,
1353
1598
  // Purely internal interoceptive signals — no sensor, no body, no rendering.
1354
1599
  // See InteroceptiveSignals.js / CALIBRATION.md.
@@ -20,6 +20,14 @@ export class ExpressionDebt {
20
20
  constructor() {
21
21
 
22
22
  this.debt = 0
23
+ // Suppression cost reservoir: holding a felt state back (Expressive
24
+ // Suppression's `suppressionDrive`) isn't free the instant it happens,
25
+ // the cost is a real drag on later ticks — the everyday observation
26
+ // that "keeping it together" now leaves you more tired for a while, not
27
+ // an invented model. A separate accumulator from `debt` (which is about
28
+ // the SWALLOWED FEELING resurfacing) — this one is about the WORK of
29
+ // holding it back, decays independently.
30
+ this.suppressionCostReservoir = 0
23
31
 
24
32
  }
25
33
 
@@ -33,6 +41,7 @@ export class ExpressionDebt {
33
41
  decay( dt, lambda = 0.02 ) {
34
42
 
35
43
  this.debt = Math.max( 0, this.debt - lambda * dt )
44
+ this.suppressionCostReservoir = Math.max( 0, this.suppressionCostReservoir - lambda * 1.5 * dt )
36
45
 
37
46
  }
38
47
 
@@ -45,4 +54,20 @@ export class ExpressionDebt {
45
54
 
46
55
  }
47
56
 
57
+ /** Charges the real cost of THIS turn's suppression into the reservoir, to be drained (not paid instantly) over subsequent ticks. */
58
+ chargeSuppressionCost( suppressionDrive ) {
59
+
60
+ this.suppressionCostReservoir = clamp01( this.suppressionCostReservoir + Math.max( 0, suppressionDrive ) * 0.3 )
61
+
62
+ }
63
+
64
+ /** Drains a slice of the outstanding suppression cost this tick — a real DecisionFatigue-facing fatigue amount, not the full reservoir at once. */
65
+ drainSuppressionCost( dt = 1, rate = 0.1 ) {
66
+
67
+ const drained = Math.min( this.suppressionCostReservoir, this.suppressionCostReservoir * rate * dt )
68
+ this.suppressionCostReservoir -= drained
69
+ return drained
70
+
71
+ }
72
+
48
73
  }
@@ -79,14 +79,27 @@ export class ExpressionDirectives {
79
79
 
80
80
  }
81
81
 
82
- /** Action tendency (item 32) — real softmax over a small instinctive action set. */
83
- getActionTendency( { valence, arousal, dominance } ) {
82
+ /**
83
+ * Action tendency (item 32) — real softmax over a small instinctive action
84
+ * set, scored by a hand-set linear policy (Score = W·features — the same
85
+ * linear-scoring shape a learned policy would use, weights fixed by us,
86
+ * not fit from data: "reglas + pesos", not a trained network) over the
87
+ * FULL current state instead of just the raw PAD vector: cortisol
88
+ * (chronic threat readiness biases withdraw/freeze), attachment trust in
89
+ * whoever the AI is responding to (high trust suppresses withdraw/freeze,
90
+ * enables approach/engage), and unresolved-wound pressure (Zeigarnik
91
+ * pressure — an open wound biases away from approach even when the
92
+ * moment-to-moment PAD reading alone wouldn't). All extra features are
93
+ * optional and default to neutral (0) so a caller passing only the PAD
94
+ * vector gets the original behavior back exactly.
95
+ */
96
+ getActionTendency( { valence, arousal, dominance, cortisol = 0, trust = 0.5, woundPressure = 0 } ) {
84
97
 
85
98
  const scores = {
86
- approach : valence * 2 + dominance,
87
- withdraw : -valence * 1.5 - dominance * 0.5,
88
- freeze : arousal * ( dominance < 0 ? 1.5 : 0.2 ) - Math.abs( valence ) * 0.3,
89
- engage : dominance * 1.5 + arousal * 0.5,
99
+ approach : valence * 2 + dominance - woundPressure * 1.2 + ( trust - 0.5 ) * 0.8,
100
+ withdraw : -valence * 1.5 - dominance * 0.5 + cortisol * 0.6 + woundPressure * 0.8 - ( trust - 0.5 ) * 0.6,
101
+ freeze : arousal * ( dominance < 0 ? 1.5 : 0.2 ) - Math.abs( valence ) * 0.3 + cortisol * 0.5,
102
+ engage : dominance * 1.5 + arousal * 0.5 + ( trust - 0.5 ) * 1.0 - cortisol * 0.4,
90
103
  }
91
104
  return softmax( scores )
92
105