totemheart 0.1.0 → 0.1.1

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 CHANGED
@@ -3,14 +3,29 @@
3
3
  ![Totemheart banner](docs/banner.png)
4
4
 
5
5
  [![License](https://img.shields.io/badge/license-MIT-blue?style=plastic)](LICENSE)
6
- [![Version](https://img.shields.io/badge/version-0.1.0-a1b858?style=plastic)](package.json)
6
+ [![Calibration](https://img.shields.io/badge/calibration-citation%20ledger-8a2be2?style=plastic)](CALIBRATION.md)
7
+ [![Version](https://img.shields.io/badge/version-0.1.1-a1b858?style=plastic)](package.json)
7
8
  [![Node](https://img.shields.io/badge/node-%3E%3D18-339933?style=plastic&logo=node.js&logoColor=white)](package.json)
8
- [![Tests](https://img.shields.io/badge/tests-75%20passing-brightgreen?style=plastic)](test/smoke.test.js)
9
+ [![Tests](https://img.shields.io/badge/tests-91%20passing-brightgreen?style=plastic)](test/smoke.test.js)
9
10
  [![Mechanisms verified](https://img.shields.io/badge/mechanisms-72%20verified%20%2F%206%20covered%20%2F%200%20failed-brightgreen?style=plastic)](examples/verify-all-mechanisms.js)
10
11
 
11
- > The Tests/Mechanisms badges above are static, last updated by hand from a real local `npm test` / `npm run verify` run. There's no CI wired yet to keep them live, so treat them as a snapshot, not a guarantee they still pass on `main`.
12
+ > The Tests/Mechanisms badges above are static, last updated by hand from a real local `npm test` / `npm run verify` run. There's no CI wired yet to keep them live, so treat them as a snapshot, not a guarantee they still pass on `main`. Two later mechanism rounds (the 10 dynamics upgrades and `LoveHateEngine`) each ship their own dedicated live audit instead of being folded into the `verify` script above: `npm run upgrade-round-mock` (39/39) and `npm run lovehate-mock` (24/24).
12
13
 
13
- **Totemheart** is a state machine for giving an AI a *consistent inner life* across a conversation: personality, mood, memory, stress, and social dynamics that persist and evolve, instead of every reply being computed from scratch. It's not a sentiment classifier and it doesn't make an AI "feel" in the way a person does. See [What this actually is](#what-this-actually-is) below before you build on top of it.
14
+ **Totemheart** is a deterministic control kernel for persistent cognition, not a sentiment classifier and not a prompt-engineering trick. It gives an AI a *consistent inner life* across a conversation: personality, mood, memory, stress, and social dynamics that persist and evolve through real control-theory and neuroscience-derived math, instead of every reply being computed from scratch off a mood label. See [What this actually is](#what-this-actually-is) below before you build on top of it.
15
+
16
+ ## How this differs from a sentiment-based chatbot layer
17
+
18
+ | | Typical "emotional AI" repo | Totemheart |
19
+ | --- | --- | --- |
20
+ | Core mechanism | Prompt engineering + emotion classifier | Dynamic system: every spike, decay, homeostatic pull and circadian phase interacts in real time and feeds the next turn |
21
+ | Emotion → output | Rule of thumb (`if arousal > 0.7, add exclamation marks`) | State-driven directives derived from the actual PAD vector and its recent trajectory |
22
+ | State | None, or a mood string overwritten each turn | Persistent, inspectable state object updated by real dynamics every turn |
23
+ | Signal processing | Raw score in, raw score out | Kalman filtering on arousal, PID with anti-windup on basic needs (stamina, hunger), cubic non-linear decay (a bigger offset from baseline is restored proportionally harder) |
24
+ | Memory | "Remembers everything" or nothing at all | REM-style consolidation on idle-time triggers, latent-weight decay toward a non-zero floor (not to zero), token-overlap reactivation instead of blind recall |
25
+ | Reward signal | Positive/negative sentiment score | Temporal-difference prediction error, `RPE = R_t + γ·V(S_t+1) − V(S_t)`, the same formulation used in reinforcement-learning neuroscience, with per-relationship eligibility traces |
26
+ | Relational memory | One bipolar "liked me / didn't" score | Affinity and Aversion tracked as two separate accumulators (`LoveHateEngine`), so real ambivalence is representable instead of averaging out to neutral |
27
+ | Stress response | A static "angry" threshold | Allostatic load raises reactivity to negative input the longer stress goes unaddressed, a real chronic-stress coupling, not a fixed multiplier |
28
+ | Persistence | "Save the mood to a database and hope" | `toJSON()` / rehydrate with round-trip verification in tests |
14
29
 
15
30
  ## What this actually is
16
31
 
@@ -53,7 +68,7 @@ Modeling the other person: trust, reputation, theory of mind, relationship memor
53
68
  | TheoryOfMind | EmotionalContagion | ChronicContagion | EpisodicMemory | ForgettingCurve |
54
69
  | Attachment | GuiltEngine | TribalCategorization | ReputationEngine | EgoProjection |
55
70
  | BystanderEffect | SelfModel | MonteCarloToM | FairnessMonitor | CounterfactualComparison |
56
- | GratitudeEngine | StatusEnvy | EgoConfidence | UncannyValleyDetector | |
71
+ | GratitudeEngine | StatusEnvy | EgoConfidence | UncannyValleyDetector | LoveHateEngine |
57
72
 
58
73
  ### 🎭 `behavior/`
59
74
 
@@ -101,6 +116,7 @@ Pluggable language backends, from a zero-dependency lexicon to a real transforme
101
116
  - **`LifeEventCatalog`**: 43/56 entries use the published Life Change Units from the [Holmes & Rahe (1967) SRRS](https://en.wikipedia.org/wiki/Holmes_and_Rahe_stress_scale); the other 13 (acute events the scale doesn't cover) are engineering estimates. Multiple matches in one turn are triangulated into a blended state.
102
117
  - **`SemanticSimilarity`**: requires an embedding backend (`embedProvider`); falls back to `EmotionalOntology` keyword matching without one.
103
118
  - **`InteroceptiveSignals`**: real math (derivative, tonic/phasic decomposition, DFT, thermal lag) on internal signals standing in for 4 sensors Totemheart doesn't have (pupil, skin conductance, HRV, flush). Feeds back into cognition only, never rendered.
119
+ - **`LoveHateEngine`**: tracks Affinity and Aversion as two SEPARATE per-user accumulators (not one bipolar scale), so a relationship can be genuinely ambivalent instead of averaging out to neutral. Real diminishing returns on Affinity, a self-reinforcing (kindling) slope on Aversion, an asymmetric decay rate (grudges outlast warmth), and a hysteresis-gated rupture/repair cycle that freezes dopaminergic wanting, damages ego health, and opens a real unresolved wound on rupture. See its own file for the full equations and citations.
104
120
 
105
121
  ### Internal scheduling
106
122
 
@@ -110,21 +126,21 @@ Pluggable language backends, from a zero-dependency lexicon to a real transforme
110
126
 
111
127
  ## How coherent is this, really?
112
128
 
113
- Short version: **~77-80% with an LLM connected, ~61-65% running standalone on the zero-dependency heuristic path, 0% subjective experience, by design and permanently.** Self-assessed, qualitative estimates of how much of each layer is grounded in real theory/technique vs. own engineering judgment. The headline is not an average of the row values below: it carries an additional discount for integrated-system validation that doesn't exist yet. Full citation ledger: [`CALIBRATION.md`](CALIBRATION.md).
129
+ Short version: **~79-82% with an LLM connected, ~63-67% running standalone on the zero-dependency heuristic path, 0% subjective experience, by design and permanently.** Self-assessed, qualitative estimates of how much of each layer is grounded in real theory/technique vs. own engineering judgment. The headline is not an average of the row values below: it carries an additional discount for integrated-system validation that doesn't exist yet. Full citation ledger: [`CALIBRATION.md`](CALIBRATION.md).
114
130
 
115
131
  | Layer | With LLM | Heuristic only | Grounded in |
116
132
  | --- | --- | --- | --- |
117
- | State engine | ~80-83% | same | PID control (anti-windup), Kalman filtering, prospect-theory loss aversion, TD reward-prediction-error, circumplex/PAD affect space, Holmes & Rahe life-event severity |
133
+ | State engine | ~82-85% | same | PID control (anti-windup, dynamic set points), Kalman filtering (now with real interoception-informed measurement noise), allostatic load (McEwen & Stellar 1993), prospect-theory loss aversion, TD reward-prediction-error with eligibility traces (Sutton & Barto), wanting/liking dissociation (Berridge & Robinson 1998), circumplex/PAD affect space with momentum/hysteresis, Holmes & Rahe life-event severity |
118
134
  | Semantic understanding | ~85-88% | ~68-73% | LLM: real language understanding. Heuristic: lexicon + concept-graph matching, keyword-triggered life-event detection, lexical-vs-context incongruence check, mean/variance anomaly detection, confidence-weighted routing between logical and affective reads |
119
- | Expression / output | ~90-93% | ~62-68% | Structured system-prompt injection, coherence validation against prior turns, attachment-weighted style adaptation, cognitive-load-derived output metadata |
120
- | Cross-turn continuity | ~91-94% | same | Persistent state serialization, asymmetric trust/reputation tracking, unresolved-memory flagging, idle-time-based consolidation, long-horizon memory decay with similarity-triggered reactivation |
135
+ | Expression / output | ~91-94% | ~64-70% | Structured system-prompt injection, coherence validation against prior turns, attachment-weighted style adaptation, a full-state-weighted action-tendency policy, real suppression-cost accrual, cognitive-load-derived output metadata |
136
+ | Cross-turn continuity | ~92-95% | same | Persistent state serialization, asymmetric trust/reputation tracking, attachment styles with rupture-and-repair (Bartholomew & Horowitz 1991; Gottman & Levenson 1992), memory reconsolidation on retrieval (Nader et al. 2000), unresolved-memory flagging with intrusive resurfacing, idle-time-based consolidation, long-horizon memory decay with similarity-triggered reactivation |
121
137
  | Subjective experience | **0%** | **0%** | Not a gap to close: no known way to build or verify this in any software |
122
138
 
123
139
  The headline stays below the row average because none of these numbers include validation against psychologist judges, regression against real labeled chat data, or real-user testing of whether the integrated pipeline reads as coherent. See `CALIBRATION.md` for what hasn't been empirically validated.
124
140
 
125
141
  ### Per-mechanism grounding
126
142
 
127
- The table above scores each functional layer as a whole. This scores five specific, individually-audited mechanisms instead: how much of *that one technique* is real citable theory vs. own engineering, independent of which layer it feeds.
143
+ The table above scores each functional layer as a whole. This scores ten specific, individually-audited mechanisms instead: how much of *that one technique* is real citable theory vs. own engineering, independent of which layer it feeds.
128
144
 
129
145
  | Mechanism | Grounded | Basis |
130
146
  | --- | --- | --- |
@@ -133,8 +149,13 @@ The table above scores each functional layer as a whole. This scores five specif
133
149
  | Forgetting curve + latent-memory reactivation | ~55-60% | Ebbinghaus (1885) grounds the general decay-over-time shape; the non-zero floor and keyword-triggered "spark" are its own design, not a reproduction of the classic curve (which decays to zero) |
134
150
  | REM-style consolidation | ~50-58% | Sleep-dependent memory consolidation is real (Diekelmann & Born 2010; McClelland et al. 1995) as a general phenomenon; the specific cooling formula and idle-time threshold are engineering estimates |
135
151
  | Expression debt / sensory-overload friction | ~35-42% | Cognitive load theory (Sweller 1988) motivates the general concept; the debt-accumulation-and-payback mechanic itself has no named psychological construct behind it, own design end to end |
152
+ | Dopaminergic wanting/liking split + TD(λ) eligibility traces | ~70-78% | Berridge & Robinson (1998) is a real, well-cited dissociation; Sutton & Barto's TD(λ) is a literal, standard reinforcement-learning algorithm applied to a per-relationship expectation store |
153
+ | Allostatic load / chronic-stress reactivity | ~58-66% | McEwen & Stellar (1993) and McEwen (1998) are real, well-cited theory; translating "wear from chronic stress" into a dynamic PID set point and a reactivity multiplier is its own control-systems engineering, not a reproduction of any measured allostatic-load curve |
154
+ | Attachment styles + rupture-and-repair | ~50-58% | Bartholomew & Horowitz's (1991) four-category model and the Gottman/Levenson rupture-and-repair literature are real; mapping OCEAN traits onto attachment-style buckets is our own engineering choice, explicitly not a validated psychometric equivalence |
155
+ | Vaillant defense hierarchy | ~55-63% | Vaillant's (1977) mature/neurotic/immature taxonomy is real, established clinical theory; the ego-health/cortisol-weighted tier-shifting mechanism that picks among them each turn is own design |
156
+ | `LoveHateEngine` dual-valence bond field | ~38-46% | The individual pieces it reuses (diminishing-returns accumulation, kindling, asymmetric decay, rupture-and-repair) each draw on real cited work; the specific coupled two-accumulator update equations are our own engineering design end to end, not a reproduction of any published relational model |
136
157
 
137
- All five passed a dedicated live audit (`npm run exhaustive-audit`, 25/25) confirming the code does what its own formulas claim. That's internal consistency, not psychological validation, and the percentages above already price that distinction in.
158
+ Every mechanism in this table passed a dedicated live audit: `npm run exhaustive-audit` (25/25) for the first five, `npm run upgrade-round-mock` (39/39) and `npm run lovehate-mock` (24/24) for the rest, confirming the code does what its own formulas claim. That's internal consistency, not psychological validation, and the percentages above already price that distinction in.
138
159
 
139
160
  ## Prerequisites
140
161
 
@@ -155,7 +176,7 @@ yarn add totemheart
155
176
  ```js
156
177
  import { Totemheart, Personality, VERSION } from 'totemheart'
157
178
 
158
- console.log( VERSION ) // '0.1.0', also available as Totemheart.VERSION and in toJSON().version
179
+ console.log( VERSION ) // '0.1.1', also available as Totemheart.VERSION and in toJSON().version
159
180
 
160
181
  const ai = new Totemheart( {
161
182
  personality: new Personality( { neuroticism: 0.7, agreeableness: 0.3 } ),
@@ -189,7 +210,7 @@ await client.chat.completions.create( {
189
210
 
190
211
  `result.structuredContext` gives you the same information as plain JSON if you'd rather build your own prompt formatting. Call `ai.getSystemPrompt()` on its own (no new turn) to seed the very first message of a conversation, or to refresh context after `ai.idle()`/`ai.tick()` shifts the mood between turns.
191
212
 
192
- Run `npm run demo` for a full scripted conversation showing decay, hedonic adaptation, dopaminergic surprise, sensory overload, and a generated system prompt in action. Run `npm test` for the mechanic-level test suite. Run `npm run stress-test` ([`examples/full-stress-test.js`](examples/full-stress-test.js)) for a before/after weight trace across a battery of positive/negative/severe shocks, repeated hostility, idle time passing, hardware latency, worn-path caching, and a group/bystander turn.
213
+ Run `npm run demo` for a full scripted conversation showing decay, hedonic adaptation, dopaminergic surprise, sensory overload, and a generated system prompt in action. Run `npm test` for the mechanic-level test suite. Run `npm run stress-test` ([`examples/full-stress-test.js`](examples/full-stress-test.js)) for a before/after weight trace across a battery of positive/negative/severe shocks, repeated hostility, idle time passing, hardware latency, worn-path caching, and a group/bystander turn. Run `npm run upgrade-round-mock` for the momentum/hysteresis, allostatic-load, wanting/liking, reconsolidation, attachment-style, graded-hijack, Vaillant-defense, expression-policy, resource-allocation, and circadian-coupling round, or `npm run lovehate-mock` for `LoveHateEngine`'s ambivalence, kindling, and rupture-and-repair cycle end to end.
193
214
 
194
215
  ### Real ML instead of heuristics: `TransformersProvider`
195
216
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "totemheart",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Totemheart is a modular emotional-simulation engine for AI: personality, mood, neurochemical dynamics, cognitive biases and social mechanics wired into a single pipeline that drives emotionally coherent, stateful behavior over a conversation.",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -57,6 +57,8 @@
57
57
  "personality-mock": "node examples/personality-mock.js",
58
58
  "rem-mock": "node examples/rem-conversation-mock.js",
59
59
  "exhaustive-audit": "node examples/exhaustive-audit-mock.js",
60
+ "upgrade-round-mock": "node examples/upgrade-round-mock.js",
61
+ "lovehate-mock": "node examples/lovehate-mock.js",
60
62
  "test": "node --test test/*.test.js"
61
63
  }
62
64
  }
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 ) {
@@ -385,11 +408,14 @@ export class Totemheart {
385
408
  // Amygdala hijack — chronic cortisol, recent-negative-stimuli sensitization, AND
386
409
  // attentional narrowing all lower the threshold needed to trigger it (all real
387
410
  // multipliers <=1, all derived from the AI's own prior state, nothing external).
411
+ // Kindling uses LAST turn's ontology concepts (this turn's aren't known yet at
412
+ // this point in the pipeline) — repeated exposure to the same stimulus TYPE
413
+ // (threat/betrayal/criticism...) genuinely lowers this turn's threshold further.
388
414
  const hijackThreshold = 0.95 * this.cortisolEngine.getThresholdMultiplier() * this.sensitization.getThresholdMultiplier() * narrowingMultiplier
389
- const hijack = this.amygdalaHijack.check( this.emotionSpace, hijackThreshold )
390
- if ( hijack.active ) {
415
+ const hijack = this.amygdalaHijack.check( this.emotionSpace, hijackThreshold, { concepts: this._lastOntologyConcepts } )
416
+ if ( hijack.tier === 'full' ) {
391
417
 
392
- this.explainability.logDecision( 'emergency_output', `Amygdala hijack on ${hijack.emotion} (${hijack.intensity.toFixed( 2 )}), threshold=${hijackThreshold.toFixed( 2 )}` )
418
+ this.explainability.logDecision( 'emergency_output', `Amygdala hijack on ${hijack.emotion} (${hijack.intensity.toFixed( 2 )}), threshold=${hijack.threshold.toFixed( 2 )}` )
393
419
  return {
394
420
  text : this.amygdalaHijack.emergencyOutput( hijack ),
395
421
  delayMs : 0,
@@ -399,6 +425,12 @@ export class Totemheart {
399
425
  }
400
426
 
401
427
  }
428
+ // Partial hijack — rational processing genuinely degrades (forced shallow mode
429
+ // below) but the pipeline keeps running and produces real text, distinct from
430
+ // the full bypass above. A milder 'alert' tier only nudges suppressionDrive
431
+ // (via _hijackAlertBoost, folded in where suppressionDrive is computed).
432
+ const partialHijack = hijack.tier === 'partial'
433
+ this._hijackAlertBoost = hijack.tier === 'alert' ? 0.15 : 0
402
434
 
403
435
  // Hardware interoception — physical sensation from runtime metrics, independent of content.
404
436
  const sensation = this.hardwareInteroception.sense( hardware )
@@ -409,27 +441,40 @@ export class Totemheart {
409
441
 
410
442
  }
411
443
 
412
- // Circadian rhythm — affects fatigue/energy for the rest of this turn.
413
- const circadian = this.circadianRhythm.getState()
444
+ // Circadian rhythm — affects fatigue/energy for the rest of this turn. Coupled
445
+ // to cortisol: sustained chronic stress flattens the diurnal amplitude (real
446
+ // direction from the HPA-axis literature — see CircadianRhythm.js). Using the
447
+ // system during its own low-energy window accumulates real sleep debt, only
448
+ // paid back down by an actual RemConsolidation sweep.
449
+ const circadian = this.circadianRhythm.getState( new Date(), this.cortisolEngine.getLevel() )
450
+ this.circadianRhythm.observeActivity( new Date(), this.cortisolEngine.getLevel() )
414
451
 
415
452
  // Decision fatigue (low circadian energy makes shallow mode kick in sooner).
416
453
  this.decisionFatigue.recordDecision( 1 + ( 1 - circadian.energy ) )
417
- const shallowMode = this.decisionFatigue.isShallow()
454
+ const partialHijackLoad = partialHijack ? this.decisionFatigue.recordDecision( 1.5 ) : null
455
+ const shallowMode = this.decisionFatigue.isShallow() || partialHijack
418
456
 
419
457
  // Arousal, smoothed through a real Kalman filter — the noisy raw reading feeds
420
458
  // 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 )
459
+ // logic uses, so a single noisy spike doesn't overreact the scheduler. The
460
+ // measurement noise (R) is itself informed by real interoceptive signal instead
461
+ // of a fixed constant: attentional narrowing under load makes THIS turn's raw
462
+ // reading less trustworthy (raise R), a genuinely novel outcome last turn is
463
+ // evidence a spike is real signal, not sensor noise (lower R).
464
+ const kalmanNoiseMultiplier = Math.max( 0.3, 1 + narrowing * 0.4 - this._lastNovelty * 0.2 )
465
+ const smoothedArousal = this.arousalKalmanFilter.filter( this.emotionSpace.vector.arousal, kalmanNoiseMultiplier )
423
466
 
424
467
  // Load scheduler — instead of always running the full fixed pipeline, an
425
468
  // instability reading (cortisol + smoothed arousal + fatigue) decides which
426
- // optional mechanics get skipped this turn.
469
+ // optional mechanics get skipped this turn. `_lastNovelty` is last turn's
470
+ // reading (this turn's isn't known until NoveltyDetector.observe() runs
471
+ // further down) — a real, if one-turn-lagged, novelty signal feeding the budget.
427
472
  const instability = this.loadScheduler.computeInstability( {
428
473
  cortisol : this.cortisolEngine.getLevel(),
429
474
  arousal : smoothedArousal,
430
475
  fatigue : this.decisionFatigue.getLevel(),
431
476
  } )
432
- const gate = this.loadScheduler.gate( instability )
477
+ const gate = this.loadScheduler.gate( instability, { novelty: this._lastNovelty } )
433
478
 
434
479
  // Hebbian co-activation tracking for this turn — which secondary mechanisms
435
480
  // actually fired, collected as we go and folded into HebbianPlasticity at the
@@ -464,6 +509,11 @@ export class Totemheart {
464
509
 
465
510
  const sig = reactivation.entry.emotionalSignature ?? { valence: 0, arousal: 0 }
466
511
  this.emotionSpace.applySpike( { valence: sig.valence * 0.2, arousal: Math.abs( sig.arousal ?? 0 ) * 0.15, weight: 0.4 } )
512
+ // Reconsolidation window — being retrieved makes this memory briefly
513
+ // modifiable again (Nader, Schafe & LeDoux 2000, see EpisodicMemory.js).
514
+ // The actual blend toward this turn's signature happens once the turn's
515
+ // final emotional state is known, near the end of processInput().
516
+ this.episodicMemory.markLabile( reactivation.entry.id )
467
517
 
468
518
  }
469
519
 
@@ -554,6 +604,14 @@ export class Totemheart {
554
604
 
555
605
  }
556
606
 
607
+ // Kindling: feed THIS turn's concepts into AmygdalaHijack's per-concept memory
608
+ // so a repeated stimulus TYPE lowers a future turn's hijack threshold further,
609
+ // and remember them as "last known concepts" — the hijack check earlier in
610
+ // THIS turn ran before this turn's own ontology was available, so it reads
611
+ // whatever was stored here on the PREVIOUS turn.
612
+ for ( const m of ontologyMatches ) if ( [ 'threat', 'betrayal', 'criticism' ].includes( m.concept ) ) this.amygdalaHijack.observeStimulus( m.concept )
613
+ this._lastOntologyConcepts = ontologyMatches.map( m => m.concept )
614
+
557
615
  // Life events — SRRS-inspired severity catalog (see LifeEventCatalog.js for
558
616
  // sourcing). Multiple simultaneous matches are triangulated into one blended
559
617
  // state instead of picking a single winner; the result's "area" list routes
@@ -569,6 +627,10 @@ export class Totemheart {
569
627
  this.emotionSpace.applySpike( { valence: lifeEvent.valence * lifeEventMagnitude, dominance: lifeEvent.dominance * lifeEventMagnitude, weight: lifeEventMagnitude } )
570
628
  this.moodTracker.push( { valence: lifeEvent.valence, arousal: 0, dominance: lifeEvent.dominance } )
571
629
  this.#applyLifeEventAreas( lifeEvent, { tokens, appraisal, userId } )
630
+ // A life event is real information about what to expect from this relationship/
631
+ // context going forward, not just this instant's spike — nudges the dopaminergic
632
+ // expectation directly, distinct from the reward-driven RPE update below.
633
+ this.dopaminergicEngine.updateExpectationFromBelief( userId, lifeEvent.valence, 0.2 )
572
634
 
573
635
  }
574
636
 
@@ -597,6 +659,7 @@ export class Totemheart {
597
659
  // Novelty (KL divergence vs. this session's historical outcome distribution) —
598
660
  // amplifies the dopaminergic arousal response independent of valence sign.
599
661
  const novelty = this.noveltyDetector.observe( this.emotionSpace.getDominantEmotion() )
662
+ this._lastNovelty = novelty // read by NEXT turn's Kalman noise + LoadScheduler budget (this turn's isn't known until this line runs)
600
663
 
601
664
  // Anchoring bias — pulls perceived desirability toward the session's first strong signal.
602
665
  this.anchoringBias.registerIfFirst( appraisal.desirability ?? 0 )
@@ -618,10 +681,13 @@ export class Totemheart {
618
681
  // left silent; see CALIBRATION.md.
619
682
  if ( lifeEvent ) desirability = Math.max( -1, Math.min( 1, desirability + lifeEvent.valence * ( lifeEvent.impact / 100 ) * 0.6 ) )
620
683
 
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 )
684
+ // Dopaminergic RPE — surprise relative to expectation, not raw reward, tracked
685
+ // per-user (context=userId) so this relationship's own expectation history is
686
+ // what this turn's reward gets judged against, with a real TD(λ) eligibility
687
+ // trace crediting recently-active contexts too (see DopaminergicEngine.js).
688
+ // Novelty adds extra arousal on top of the RPE-driven amount, since novelty
689
+ // and reward-surprise are related but not identical signals.
690
+ const rpe = this.dopaminergicEngine.computeRPE( desirability, userId )
625
691
  const dopamineSpike = {
626
692
  valence : rpe * 0.5,
627
693
  arousal : Math.abs( rpe ) * 0.6 + ( appraisal.ontologyArousalBoost ?? 0 ) * 0.2 + novelty * 0.15,
@@ -703,6 +769,11 @@ export class Totemheart {
703
769
  : await this.#analyze( 'mentalState', { text: input } )
704
770
  this.theoryOfMind.update( userId, mentalState )
705
771
  const tomEstimate = this.monteCarloToM.simulate( mentalState.valence ?? 0, 1 - relation.trust )
772
+ // Theory-of-mind's own read of what this user is likely feeling is real
773
+ // evidence about what to expect from them, distinct from the reward this
774
+ // turn's outcome actually delivered — feeds the same per-user expectation
775
+ // store the reward-driven RPE update above uses, at a smaller weight.
776
+ this.dopaminergicEngine.updateExpectationFromBelief( userId, tomEstimate.estimatedValence, 0.15 )
706
777
 
707
778
  // Tribal categorization — in/out-group confirmation bias on the perceived desirability.
708
779
  const tribe = this.tribalCategorization.classify( relation )
@@ -765,6 +836,77 @@ export class Totemheart {
765
836
 
766
837
  }
767
838
 
839
+ // LoveHateEngine — dual-valence relational field: Affinity (A) and Aversion
840
+ // (V) are tracked as two SEPARATE per-user accumulators, not one bipolar
841
+ // scale, so real ambivalence ("te quiero pero me hiciste daño") can raise
842
+ // both at once. Phase 1 (semantic polarization) is computed here from
843
+ // signals this turn ALREADY has — desirability split into its positive/
844
+ // negative parts, real ontology-concept flags, a detected life event's own
845
+ // valence — not a second lexicon duplicating EmotionalOntology's job.
846
+ const conceptSet = new Set( ontologyMatches.map( m => m.concept ) )
847
+ let loveHateL = Math.max( 0, desirability )
848
+ let loveHateH = Math.max( 0, -desirability )
849
+ if ( conceptSet.has( 'affection' ) ) loveHateL = Math.min( 1, loveHateL + 0.4 )
850
+ if ( conceptSet.has( 'achievement' ) ) loveHateL = Math.min( 1, loveHateL + 0.2 )
851
+ if ( conceptSet.has( 'betrayal' ) ) loveHateH = Math.min( 1, loveHateH + 0.5 )
852
+ if ( conceptSet.has( 'threat' ) || conceptSet.has( 'rejection' ) ) loveHateH = Math.min( 1, loveHateH + 0.3 )
853
+ if ( conceptSet.has( 'criticism' ) ) loveHateH = Math.min( 1, loveHateH + 0.3 )
854
+ if ( lifeEvent ) {
855
+
856
+ loveHateL = Math.min( 1, loveHateL + Math.max( 0, lifeEvent.valence ) * ( lifeEvent.impact / 100 ) * 0.3 )
857
+ loveHateH = Math.min( 1, loveHateH + Math.max( 0, -lifeEvent.valence ) * ( lifeEvent.impact / 100 ) * 0.3 )
858
+
859
+ }
860
+
861
+ const woundPressure = Math.min( 1, this.episodicMemory.getZeigarnikPressure( userId ) / 3 )
862
+ const bondUpdate = this.loveHateEngine.observe( userId, { L: loveHateL, H: loveHateH }, {
863
+ trust: relation.trust, woundPressure, cortisol: this.cortisolEngine.getLevel(), egoHealth: this.reputationEngine.getEgoHealth(),
864
+ } )
865
+
866
+ // Feeds the felt state directly, real numbers straight from the engine:
867
+ // NetBond pulls valence toward however this relationship actually nets out,
868
+ // Tension (A·V, only nonzero when BOTH are genuinely present) plus the raw
869
+ // H charge raises arousal — ambivalence is felt as agitation, not averaged away.
870
+ const bondTension = this.loveHateEngine.getTension( userId )
871
+ this._lastLoveHateTension = bondTension
872
+ this.emotionSpace.applySpike( { valence: bondUpdate.netBond * 0.15, arousal: ( bondTension + loveHateH ) * 0.15, weight: 0.35 } )
873
+ this.moodTracker.push( { valence: bondUpdate.netBond * 0.15, arousal: ( bondTension + loveHateH ) * 0.15 } )
874
+ if ( bondUpdate.Heff > 0.25 ) this.cortisolEngine.register( -bondUpdate.Heff, false )
875
+
876
+ const rupture = this.loveHateEngine.checkRupture( userId, { cortisol: this.cortisolEngine.getLevel() } )
877
+ let repair = { repaired: false }
878
+ if ( rupture.ruptured ) {
879
+
880
+ // Real cross-module side effects of an actual rupture, applied here
881
+ // (LoveHateEngine itself stays self-contained and returns a signal,
882
+ // same orchestration pattern Totemheart already uses for e.g. life
883
+ // events and gratitude) rather than reaching into other modules itself.
884
+ this.dopaminergicEngine.freezeWanting()
885
+ this.amygdalaHijack.observeStimulus( 'rupture' ) // kindles a lower hijack threshold on a FUTURE turn — this turn's own check already ran
886
+ this._hijackAlertBoost = Math.max( this._hijackAlertBoost ?? 0, 0.2 )
887
+ this.expressionDebt.accumulate( 0.3 )
888
+ this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth - 0.1 )
889
+ this.ruminationChain.biasTowardNegative( rupture.ambivalence * 0.4 + 0.2 )
890
+ await safeStep( this.explainability, 'episodicMemory.storeLoveHateRupture', async () => this.episodicMemory.store( {
891
+ text : `[relational rupture] V-A=${( this.loveHateEngine.getBond( userId ).V - this.loveHateEngine.getBond( userId ).A ).toFixed( 2 )}`,
892
+ userId, emotionalSignature: { valence: -0.7, arousal: 0.6 }, importance: 0.75, concepts: [ 'rupture' ], turnIndex: this.turnCounter,
893
+ } ), null )
894
+ this.explainability.logDecision( 'lovehate_rupture', `relational rupture #${rupture.ruptureCount} for ${userId} (netBond=${rupture.netBond.toFixed( 2 )})` )
895
+
896
+ }
897
+ else {
898
+
899
+ repair = this.loveHateEngine.attemptRepair( userId, { cortisol: this.cortisolEngine.getLevel() } )
900
+ if ( repair.repaired ) {
901
+
902
+ this.dopaminergicEngine.likingValue = Math.max( -1, Math.min( 1, this.dopaminergicEngine.likingValue + repair.dopamineLikingBoost ) )
903
+ this.reputationEngine.egoHealth = clamp01( this.reputationEngine.egoHealth + repair.egoHealthRestore )
904
+ this.explainability.logDecision( 'lovehate_repair', `relational repair #${repair.repairCount} for ${userId}` )
905
+
906
+ }
907
+
908
+ }
909
+
768
910
  // Hedonic adaptation — per-fingerprint discount (repeating the exact same phrase)...
769
911
  const neuroticism = this.personality.get( 'neuroticism' )
770
912
  const fingerprint = HedonicAdaptation.fingerprintOf( input, this.emotionSpace.getDominantEmotion( neuroticism ) )
@@ -792,6 +934,11 @@ export class Totemheart {
792
934
  hedonicMultiplier,
793
935
  )
794
936
  spike.weight = ( spike.weight ?? 1 ) * ( 0.6 + 0.4 * agreement.agreement )
937
+ // Allostatic load — real chronic-stress "wear" (McEwen & Stellar 1993, see
938
+ // Homeostasis.js) makes a negative spike land harder, not softer, a
939
+ // direction with support in the chronic-stress/reactivity literature.
940
+ // Only scales spikes that are actually negative on this turn.
941
+ if ( spike.valence < 0 ) spike.weight *= this.homeostasis.getReactivityMultiplier()
795
942
  this.emotionSpace.applySpike( spike )
796
943
  this.moodTracker.push( spike )
797
944
 
@@ -883,8 +1030,33 @@ export class Totemheart {
883
1030
  this.hebbianPlasticity.getAssociation( 'lowAgreement', 'defense' ),
884
1031
  this.hebbianPlasticity.getAssociation( 'uncanny', 'defense' ),
885
1032
  )
886
- const defenseDirective = this.defenseMechanisms.check( this.cognitiveDissonance.getStress() + cascadeBoost * 0.3, this.personality )
887
- if ( defenseDirective.active ) activeMechanisms.push( 'defense' )
1033
+ // Vaillant hierarchy — low ego health / high cortisol pulls the pick toward the
1034
+ // immature end (projection/evasion), high ego health + low cortisol lets mature
1035
+ // defenses (humor) compete. See DefenseMechanisms.js. LoveHateEngine's real
1036
+ // relational Tension (A·V — only nonzero when both love and hate are
1037
+ // genuinely present this turn) folds into the same cortisol-shaped input:
1038
+ // high ambivalence toward this user reads as extra reactivity pressure here,
1039
+ // same direction chronic cortisol already has on this check.
1040
+ const defenseDirective = this.defenseMechanisms.check(
1041
+ this.cognitiveDissonance.getStress() + cascadeBoost * 0.3, this.personality, 0.6,
1042
+ { egoHealth: this.reputationEngine.getEgoHealth(), cortisol: Math.min( 1, this.cortisolEngine.getLevel() + ( this._lastLoveHateTension ?? 0 ) * 0.2 ) },
1043
+ )
1044
+ if ( defenseDirective.active ) {
1045
+
1046
+ activeMechanisms.push( 'defense' )
1047
+ // Residue: using a defense leaves a real, queryable trace — a low-importance
1048
+ // EpisodicMemory entry tagged with which one, not just the SelfModel counter
1049
+ // already reinforced below. "The system remembers it used projection."
1050
+ await safeStep( this.explainability, 'episodicMemory.storeDefenseResidue', async () => this.episodicMemory.store( {
1051
+ text : `[defense] ${defenseDirective.mechanism} (${defenseDirective.tier})`,
1052
+ userId,
1053
+ emotionalSignature : { valence: 0, arousal: 0 },
1054
+ importance : 0.05,
1055
+ concepts : [ `defense:${defenseDirective.mechanism}` ],
1056
+ turnIndex : this.turnCounter,
1057
+ } ), null )
1058
+
1059
+ }
888
1060
  this.hebbianPlasticity.update( activeMechanisms )
889
1061
 
890
1062
  // Self-model — reinforced incrementally on each observation, not batch-analyzed.
@@ -942,9 +1114,14 @@ export class Totemheart {
942
1114
  // break above), it's also a plain cognitive-resource one.
943
1115
  let suppressionDrive = characterBreak
944
1116
  ? 0
945
- : clamp01( this.personality.get( 'conscientiousness' ) * this.cortisolEngine.getLevel() + ( this._lifeEventSuppressionBoost ?? 0 ) ) * ( 1 - this.decisionFatigue.getLevel() )
1117
+ : clamp01( this.personality.get( 'conscientiousness' ) * this.cortisolEngine.getLevel() + ( this._lifeEventSuppressionBoost ?? 0 ) + ( this._hijackAlertBoost ?? 0 ) ) * ( 1 - this.decisionFatigue.getLevel() )
946
1118
  this.decisionFatigue.recordDecision( suppressionDrive )
947
1119
  if ( this.decisionFatigue.isShallow() ) this.cortisolEngine.register( 0, true ) // sustained cognitive load reads as chronic ambient stress too
1120
+ // Real suppression cost: holding this back isn't free the instant it happens —
1121
+ // charges the reservoir tick()/drainSuppressionCost() pays out as DecisionFatigue
1122
+ // load over SUBSEQUENT turns, distinct from the debt that resurfaces the
1123
+ // swallowed FEELING itself (ExpressionDebt.debt).
1124
+ this.expressionDebt.chargeSuppressionCost( suppressionDrive )
948
1125
  const expressedVector = this.expressiveSuppression.suppress( this.emotionSpace.vector, suppressionDrive )
949
1126
 
950
1127
  // Chameleon effect — real lexical stats measured on THIS user's own input,
@@ -1011,6 +1188,11 @@ export class Totemheart {
1011
1188
  // time's prior for this user.
1012
1189
  this.bayesianExpectation.update( userId, desirability > 0 )
1013
1190
 
1191
+ // Close out this turn's reconsolidation window (if a memory was reactivated
1192
+ // above): blend its stored signature toward what actually got felt THIS turn.
1193
+ // A no-op if the window already closed or nothing was reactivated.
1194
+ if ( reactivation ) this.episodicMemory.reconsolidate( reactivation.entry, this.emotionSpace.vector )
1195
+
1014
1196
  await safeStep( this.explainability, 'episodicMemory.store', async () => this.episodicMemory.store( {
1015
1197
  text : input,
1016
1198
  userId,
@@ -1129,6 +1311,10 @@ export class Totemheart {
1129
1311
  lifeEvent, agreement, debtReleased, characterBreak, referenceShift,
1130
1312
  visualProsody, topicSatiation, chronicPull, uncannyValley, sarcasm, refractory, styleTarget,
1131
1313
  activeMechanisms, cascadeBoost, remReport: this._lastRemReport, reactivation,
1314
+ hijack, attachmentStyle: relation.style ?? this.attachment.getStyle( this.personality ), rupture: { ruptured: relation.ruptured, repairsCount: relation.repairsCount },
1315
+ intrusion, allostaticLoad: this.homeostasis.allostaticLoad, sleepDebt: this.circadianRhythm.sleepDebt,
1316
+ dopamine : { wanting: this.dopaminergicEngine.getWanting(), liking: this.dopaminergicEngine.getLiking() },
1317
+ loveHate : { ...bondUpdate, tension: bondTension, ambivalence: this.loveHateEngine.getAmbivalence( userId ), rupture, repair },
1132
1318
  },
1133
1319
  }
1134
1320
 
@@ -1163,17 +1349,32 @@ export class Totemheart {
1163
1349
  * action-tendency — Totemheart computes what SHOULD be expressed, it has
1164
1350
  * no face, voice, or body to express it with. See CALIBRATION.md.
1165
1351
  */
1166
- getExpressionDirectives() {
1352
+ /** `userId` (optional) lets actionTendency's policy weigh real attachment trust and this user's unresolved-wound pressure; omitted, both default to neutral. */
1353
+ getExpressionDirectives( userId = null ) {
1167
1354
 
1168
1355
  const neuroticism = this.personality.get( 'neuroticism' )
1169
1356
  const dominant = this.emotionSpace.getDominantEmotion( neuroticism )
1170
1357
  const blendWeight = this.emotionSpace.getBlend( 1, neuroticism )[ dominant ] ?? 1
1171
1358
 
1359
+ // Blends Attachment's single-axis trust with LoveHateEngine's real NetBond
1360
+ // (A-V, distinct from trust — a relationship can be trusted but currently
1361
+ // net-negative from a fresh wound, or vice versa) — both real relational
1362
+ // signals feeding the same action-tendency policy, not just one of them.
1363
+ const rawTrust = userId ? this.attachment.get( userId ).trust : 0.5
1364
+ const netBondTrust = userId ? ( this.loveHateEngine.getNetBond( userId ) + 1 ) / 2 : 0.5
1365
+ const trust = rawTrust * 0.7 + netBondTrust * 0.3
1366
+ const woundPressure = userId ? this.episodicMemory.getZeigarnikPressure( userId ) : 0
1367
+
1172
1368
  return {
1173
1369
  facial : this.expressionDirectives.getFacialDirectives( dominant, blendWeight ),
1174
1370
  prosody : this.expressionDirectives.getProsodyDirectives( this.emotionSpace.vector ),
1175
1371
  posture : this.expressionDirectives.getPostureDirectives( this.emotionSpace.vector ),
1176
- actionTendency : this.expressionDirectives.getActionTendency( this.emotionSpace.vector ),
1372
+ actionTendency : this.expressionDirectives.getActionTendency( {
1373
+ ...this.emotionSpace.vector,
1374
+ cortisol : this.cortisolEngine.getLevel(),
1375
+ trust,
1376
+ 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
1377
+ } ),
1177
1378
  }
1178
1379
 
1179
1380
  }
@@ -1187,7 +1388,7 @@ export class Totemheart {
1187
1388
  this.decayEngine.apply( this.emotionSpace, mood, this.personality, dt )
1188
1389
  this.controllabilityEstimate.observeOutcome( this.emotionSpace.getDominantEmotion(), valenceBefore, this.emotionSpace.vector.valence )
1189
1390
 
1190
- this.homeostasis.tick( dt, this.personality )
1391
+ this.homeostasis.tick( dt, this.personality, { circadianEnergy: this.circadianRhythm.getEnergyLevel( new Date(), this.cortisolEngine.getLevel() ), cortisol: this.cortisolEngine.getLevel() } )
1191
1392
  this.forgettingCurve.tick( this.episodicMemory, dt )
1192
1393
  this.decisionFatigue.decay( dt )
1193
1394
  this.cognitiveDissonance.decay( dt )
@@ -1197,6 +1398,23 @@ export class Totemheart {
1197
1398
  this.sensitization.decay( dt )
1198
1399
  this.ruminationChain.decayBias( dt )
1199
1400
  this.expressionDebt.decay( dt )
1401
+ this.amygdalaHijack.decayKindling( dt )
1402
+ this.loveHateEngine.tick( dt, { cortisol: this.cortisolEngine.getLevel() } )
1403
+
1404
+ // Real suppression cost paid out gradually, not the instant it was charged —
1405
+ // see ExpressionDebt.chargeSuppressionCost()/drainSuppressionCost().
1406
+ const drainedSuppressionCost = this.expressionDebt.drainSuppressionCost( dt )
1407
+ if ( drainedSuppressionCost > 0 ) this.decisionFatigue.recordDecision( drainedSuppressionCost )
1408
+
1409
+ // Amygdala-hijack hangover — a measurable post-hijack window of extra
1410
+ // DecisionFatigue/ExpressionDebt load, own tuning, see AmygdalaHijack.js.
1411
+ const hangoverLoad = this.amygdalaHijack.getHangoverLoad()
1412
+ if ( hangoverLoad > 0 ) {
1413
+
1414
+ this.decisionFatigue.recordDecision( hangoverLoad )
1415
+ this.expressionDebt.accumulate( hangoverLoad * 0.3 )
1416
+
1417
+ }
1200
1418
 
1201
1419
  const alerts = this.homeostasis.getAlerts()
1202
1420
  for ( const alert of alerts ) {
@@ -1293,7 +1511,13 @@ export class Totemheart {
1293
1511
  decisionFatigue : this.decisionFatigue.load,
1294
1512
  cortisolLevel : this.cortisolEngine.level,
1295
1513
  egoHealth : this.reputationEngine.egoHealth,
1296
- dopamineExpectedValue : this.dopaminergicEngine.expectedValue,
1514
+ dopamineExpectedValues : [ ...this.dopaminergicEngine.expectedValues.entries() ],
1515
+ dopamineWanting : this.dopaminergicEngine.wanting,
1516
+ dopamineLiking : this.dopaminergicEngine.likingValue,
1517
+ allostaticLoad : this.homeostasis.allostaticLoad,
1518
+ sleepDebt : this.circadianRhythm.sleepDebt,
1519
+ kindling : [ ...this.amygdalaHijack.kindling.entries() ],
1520
+ loveHate : this.loveHateEngine.toJSON(),
1297
1521
  hedonicSeen : [ ...this.hedonicAdaptation.seen.entries() ],
1298
1522
  attachmentRelations : [ ...this.attachment.relations.entries() ],
1299
1523
  theoryOfMindModels : [ ...this.theoryOfMind.models.entries() ].map( ( [ id, m ] ) => [ id, { ...m, beliefs: [ ...m.beliefs.entries() ] } ] ),
@@ -1317,7 +1541,14 @@ export class Totemheart {
1317
1541
  if ( typeof data.decisionFatigue === 'number' ) this.decisionFatigue.load = data.decisionFatigue
1318
1542
  if ( typeof data.cortisolLevel === 'number' ) this.cortisolEngine.level = data.cortisolLevel
1319
1543
  if ( typeof data.egoHealth === 'number' ) this.reputationEngine.egoHealth = data.egoHealth
1320
- if ( typeof data.dopamineExpectedValue === 'number' ) this.dopaminergicEngine.expectedValue = data.dopamineExpectedValue
1544
+ if ( data.dopamineExpectedValues ) this.dopaminergicEngine.expectedValues = new Map( data.dopamineExpectedValues )
1545
+ else if ( typeof data.dopamineExpectedValue === 'number' ) this.dopaminergicEngine.expectedValues.set( 'default', data.dopamineExpectedValue ) // pre-eligibility-trace save format
1546
+ if ( typeof data.dopamineWanting === 'number' ) this.dopaminergicEngine.wanting = data.dopamineWanting
1547
+ if ( typeof data.dopamineLiking === 'number' ) this.dopaminergicEngine.likingValue = data.dopamineLiking
1548
+ if ( typeof data.allostaticLoad === 'number' ) this.homeostasis.allostaticLoad = data.allostaticLoad
1549
+ if ( typeof data.sleepDebt === 'number' ) this.circadianRhythm.sleepDebt = data.sleepDebt
1550
+ if ( data.kindling ) this.amygdalaHijack.kindling = new Map( data.kindling )
1551
+ if ( data.loveHate ) this.loveHateEngine.restoreState( data.loveHate )
1321
1552
  if ( data.hedonicSeen ) this.hedonicAdaptation.seen = new Map( data.hedonicSeen )
1322
1553
  if ( data.attachmentRelations ) this.attachment.relations = new Map( data.attachmentRelations )
1323
1554
  if ( data.theoryOfMindModels ) {
@@ -1345,10 +1576,14 @@ export class Totemheart {
1345
1576
  cognitiveStress : this.cognitiveDissonance.getStress(),
1346
1577
  fatigue : this.decisionFatigue.getLevel(),
1347
1578
  needs : this.homeostasis.getState(),
1579
+ allostaticLoad : this.homeostasis.allostaticLoad,
1348
1580
  cortisol : this.cortisolEngine.getLevel(),
1349
1581
  egoHealth : this.reputationEngine.getEgoHealth(),
1350
- circadianEnergy : this.circadianRhythm.getEnergyLevel(),
1582
+ circadianEnergy : this.circadianRhythm.getEnergyLevel( new Date(), this.cortisolEngine.getLevel() ),
1583
+ sleepDebt : this.circadianRhythm.sleepDebt,
1351
1584
  dopamineExpectation : this.dopaminergicEngine.getExpectedValue(),
1585
+ dopamineWanting : this.dopaminergicEngine.getWanting(),
1586
+ dopamineLiking : this.dopaminergicEngine.getLiking(),
1352
1587
  sensitization : this.sensitization.level,
1353
1588
  // Purely internal interoceptive signals — no sensor, no body, no rendering.
1354
1589
  // See InteroceptiveSignals.js / CALIBRATION.md.