totemheart 0.1.0

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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -0
  3. package/package.json +62 -0
  4. package/src/Totemheart.js +1363 -0
  5. package/src/behavior/AttentionFocus.js +69 -0
  6. package/src/behavior/ExpressionDebt.js +48 -0
  7. package/src/behavior/ExpressionDirectives.js +95 -0
  8. package/src/behavior/ExpressiveSuppression.js +45 -0
  9. package/src/behavior/IdleProcessing.js +64 -0
  10. package/src/behavior/LinguisticModulation.js +62 -0
  11. package/src/behavior/LogitBiasBuilder.js +31 -0
  12. package/src/behavior/RuminationChain.js +93 -0
  13. package/src/behavior/StyleMimicry.js +72 -0
  14. package/src/cognition/AmygdalaHijack.js +40 -0
  15. package/src/cognition/AppraisalAgreement.js +39 -0
  16. package/src/cognition/BayesianExpectation.js +59 -0
  17. package/src/cognition/CognitiveDissonance.js +71 -0
  18. package/src/cognition/ControllabilityEstimate.js +56 -0
  19. package/src/cognition/DecisionFatigue.js +44 -0
  20. package/src/cognition/DefenseMechanisms.js +32 -0
  21. package/src/cognition/EmotionalOntology.js +134 -0
  22. package/src/cognition/FuzzyNormativeCheck.js +60 -0
  23. package/src/cognition/Intuition.js +71 -0
  24. package/src/cognition/LifeEventCatalog.js +98 -0
  25. package/src/cognition/LoadScheduler.js +41 -0
  26. package/src/cognition/LogicEngine.js +69 -0
  27. package/src/cognition/NoveltyDetector.js +59 -0
  28. package/src/cognition/Reappraisal.js +34 -0
  29. package/src/cognition/RefractoryPeriod.js +38 -0
  30. package/src/cognition/RemConsolidation.js +79 -0
  31. package/src/cognition/SarcasmDetector.js +38 -0
  32. package/src/cognition/SemanticSimilarity.js +75 -0
  33. package/src/cognition/Sensitization.js +45 -0
  34. package/src/cognition/SituationalContext.js +48 -0
  35. package/src/cognition/TopicSatiation.js +54 -0
  36. package/src/cognition/VisualProsody.js +48 -0
  37. package/src/core/AffectEMA.js +26 -0
  38. package/src/core/CoreBeliefs.js +58 -0
  39. package/src/core/DecayEngine.js +56 -0
  40. package/src/core/EmotionSpace.js +146 -0
  41. package/src/core/HebbianPlasticity.js +59 -0
  42. package/src/core/HedonicAdaptation.js +62 -0
  43. package/src/core/Homeostasis.js +119 -0
  44. package/src/core/MicroEmotions.js +25 -0
  45. package/src/core/MoodTracker.js +53 -0
  46. package/src/core/Personality.js +84 -0
  47. package/src/core/PipelineResilience.js +24 -0
  48. package/src/core/TriggerSentinel.js +38 -0
  49. package/src/core/WornPathCache.js +57 -0
  50. package/src/economics/AnchoringBias.js +38 -0
  51. package/src/economics/ClassicalConditioning.js +59 -0
  52. package/src/economics/LossAversion.js +40 -0
  53. package/src/embodiment/HardwareInteroception.js +26 -0
  54. package/src/embodiment/InteroceptiveSignals.js +132 -0
  55. package/src/embodiment/SensoryOverload.js +45 -0
  56. package/src/index.js +14 -0
  57. package/src/integration/ContextAdapter.js +247 -0
  58. package/src/neurochemistry/ArousalKalmanFilter.js +39 -0
  59. package/src/neurochemistry/CircadianRhythm.js +29 -0
  60. package/src/neurochemistry/CortisolEngine.js +54 -0
  61. package/src/neurochemistry/DopaminergicEngine.js +42 -0
  62. package/src/providers/FunctionProvider.js +26 -0
  63. package/src/providers/HeuristicProvider.js +156 -0
  64. package/src/providers/LanguageProvider.js +13 -0
  65. package/src/providers/OllamaProvider.js +63 -0
  66. package/src/providers/TransformersProvider.js +154 -0
  67. package/src/social/Attachment.js +81 -0
  68. package/src/social/BystanderEffect.js +17 -0
  69. package/src/social/ChronicContagion.js +48 -0
  70. package/src/social/CounterfactualComparison.js +34 -0
  71. package/src/social/EgoConfidence.js +34 -0
  72. package/src/social/EgoProjection.js +20 -0
  73. package/src/social/EmotionalContagion.js +52 -0
  74. package/src/social/EpisodicMemory.js +266 -0
  75. package/src/social/FairnessMonitor.js +34 -0
  76. package/src/social/ForgettingCurve.js +28 -0
  77. package/src/social/GratitudeEngine.js +32 -0
  78. package/src/social/GuiltEngine.js +43 -0
  79. package/src/social/MonteCarloToM.js +49 -0
  80. package/src/social/ReputationEngine.js +45 -0
  81. package/src/social/SelfModel.js +50 -0
  82. package/src/social/StatusEnvy.js +34 -0
  83. package/src/social/TheoryOfMind.js +53 -0
  84. package/src/social/TribalCategorization.js +24 -0
  85. package/src/social/UncannyValleyDetector.js +59 -0
  86. package/src/text/EmotionalCorpus.js +70 -0
  87. package/src/text/EmotionalTextGenerator.js +56 -0
  88. package/src/text/ExplainabilityEngine.js +30 -0
  89. package/src/text/TemplateComposer.js +114 -0
  90. package/src/version.js +1 -0
@@ -0,0 +1,1363 @@
1
+ import { Personality } from './core/Personality.js'
2
+ import { CoreBeliefs } from './core/CoreBeliefs.js'
3
+ import { Homeostasis } from './core/Homeostasis.js'
4
+ import { EmotionSpace } from './core/EmotionSpace.js'
5
+ import { MicroEmotions } from './core/MicroEmotions.js'
6
+ import { MoodTracker } from './core/MoodTracker.js'
7
+ import { DecayEngine } from './core/DecayEngine.js'
8
+ import { HedonicAdaptation } from './core/HedonicAdaptation.js'
9
+
10
+ import { CognitiveDissonance } from './cognition/CognitiveDissonance.js'
11
+ import { DefenseMechanisms } from './cognition/DefenseMechanisms.js'
12
+ import { DecisionFatigue } from './cognition/DecisionFatigue.js'
13
+ import { AmygdalaHijack } from './cognition/AmygdalaHijack.js'
14
+ import { EmotionalOntology } from './cognition/EmotionalOntology.js'
15
+ import { SituationalContext } from './cognition/SituationalContext.js'
16
+ import { NoveltyDetector } from './cognition/NoveltyDetector.js'
17
+ import { BayesianExpectation } from './cognition/BayesianExpectation.js'
18
+ import { ControllabilityEstimate } from './cognition/ControllabilityEstimate.js'
19
+ import { FuzzyNormativeCheck } from './cognition/FuzzyNormativeCheck.js'
20
+ import { Sensitization } from './cognition/Sensitization.js'
21
+ import { Reappraisal } from './cognition/Reappraisal.js'
22
+ import { SemanticSimilarity } from './cognition/SemanticSimilarity.js'
23
+ import { Intuition } from './cognition/Intuition.js'
24
+ import { LogicEngine } from './cognition/LogicEngine.js'
25
+ import { LifeEventCatalog } from './cognition/LifeEventCatalog.js'
26
+ import { AppraisalAgreement } from './cognition/AppraisalAgreement.js'
27
+ import { VisualProsody } from './cognition/VisualProsody.js'
28
+ import { TopicSatiation } from './cognition/TopicSatiation.js'
29
+ import { SarcasmDetector } from './cognition/SarcasmDetector.js'
30
+ import { RefractoryPeriod } from './cognition/RefractoryPeriod.js'
31
+ import { VERSION } from './version.js'
32
+
33
+ import { TheoryOfMind } from './social/TheoryOfMind.js'
34
+ import { EmotionalContagion } from './social/EmotionalContagion.js'
35
+ import { ChronicContagion } from './social/ChronicContagion.js'
36
+ import { UncannyValleyDetector } from './social/UncannyValleyDetector.js'
37
+ import { EpisodicMemory } from './social/EpisodicMemory.js'
38
+ import { ForgettingCurve } from './social/ForgettingCurve.js'
39
+ import { Attachment } from './social/Attachment.js'
40
+ import { GuiltEngine } from './social/GuiltEngine.js'
41
+ import { TribalCategorization } from './social/TribalCategorization.js'
42
+ import { ReputationEngine } from './social/ReputationEngine.js'
43
+ import { EgoProjection } from './social/EgoProjection.js'
44
+ import { BystanderEffect } from './social/BystanderEffect.js'
45
+ import { SelfModel } from './social/SelfModel.js'
46
+ import { MonteCarloToM } from './social/MonteCarloToM.js'
47
+ import { FairnessMonitor } from './social/FairnessMonitor.js'
48
+ import { CounterfactualComparison } from './social/CounterfactualComparison.js'
49
+ import { GratitudeEngine } from './social/GratitudeEngine.js'
50
+ import { StatusEnvy } from './social/StatusEnvy.js'
51
+ import { EgoConfidence } from './social/EgoConfidence.js'
52
+
53
+ import { IdleProcessing } from './behavior/IdleProcessing.js'
54
+ import { LinguisticModulation } from './behavior/LinguisticModulation.js'
55
+ import { RuminationChain } from './behavior/RuminationChain.js'
56
+ import { ExpressiveSuppression } from './behavior/ExpressiveSuppression.js'
57
+ import { ExpressionDirectives } from './behavior/ExpressionDirectives.js'
58
+ import { LogitBiasBuilder, DEFAULT_CHARGED_WORDS } from './behavior/LogitBiasBuilder.js'
59
+ import { AttentionFocus } from './behavior/AttentionFocus.js'
60
+ import { ExpressionDebt } from './behavior/ExpressionDebt.js'
61
+ import { StyleMimicry } from './behavior/StyleMimicry.js'
62
+
63
+ import { EmotionalCorpus } from './text/EmotionalCorpus.js'
64
+ import { EmotionalTextGenerator } from './text/EmotionalTextGenerator.js'
65
+ import { ExplainabilityEngine } from './text/ExplainabilityEngine.js'
66
+
67
+ import { HeuristicProvider } from './providers/HeuristicProvider.js'
68
+
69
+ import { DopaminergicEngine } from './neurochemistry/DopaminergicEngine.js'
70
+ import { CortisolEngine } from './neurochemistry/CortisolEngine.js'
71
+ import { CircadianRhythm } from './neurochemistry/CircadianRhythm.js'
72
+ import { ArousalKalmanFilter } from './neurochemistry/ArousalKalmanFilter.js'
73
+
74
+ import { HardwareInteroception } from './embodiment/HardwareInteroception.js'
75
+ import { SensoryOverload } from './embodiment/SensoryOverload.js'
76
+ import { InteroceptiveSignals } from './embodiment/InteroceptiveSignals.js'
77
+ import { AffectEMA } from './core/AffectEMA.js'
78
+
79
+ import { LossAversion } from './economics/LossAversion.js'
80
+ import { AnchoringBias } from './economics/AnchoringBias.js'
81
+ import { ClassicalConditioning } from './economics/ClassicalConditioning.js'
82
+
83
+ import { ContextAdapter } from './integration/ContextAdapter.js'
84
+
85
+ import { safeStep } from './core/PipelineResilience.js'
86
+ import { LoadScheduler } from './cognition/LoadScheduler.js'
87
+ import { WornPathCache } from './core/WornPathCache.js'
88
+ import { TriggerSentinel } from './core/TriggerSentinel.js'
89
+ import { HebbianPlasticity } from './core/HebbianPlasticity.js'
90
+ import { RemConsolidation } from './cognition/RemConsolidation.js'
91
+
92
+ function clamp01( v ) {
93
+
94
+ return Math.max( 0, Math.min( 1, v ) )
95
+
96
+ }
97
+
98
+ function tokenize( text ) {
99
+
100
+ return ( text || '' ).toLowerCase().match( /[\p{L}']+/gu ) || []
101
+
102
+ }
103
+
104
+ // Allostasis reset thresholds — own tuning, not a citation. A mood reading past these
105
+ // magnitudes on both axes counts as an "extreme quadrant" (runaway mania/depression
106
+ // shape); ALLOSTASIS_STUCK_TICKS consecutive tick()s that stay there trigger a reset.
107
+ const ALLOSTASIS_VALENCE_THRESHOLD = 0.6
108
+ const ALLOSTASIS_AROUSAL_THRESHOLD = 0.5
109
+ const ALLOSTASIS_STUCK_TICKS = 5
110
+
111
+ // Ego depletion — own tuning, not a citation. Past this ExpressionDebt level, suppression
112
+ // is forced to fail instead of continuing to hold indefinitely.
113
+ const EGO_DEPLETION_THRESHOLD = 0.7
114
+
115
+ /**
116
+ * Orchestrates the full mechanic set into a single pipeline. See README.md's
117
+ * architecture table and CALIBRATION.md for what's cited vs. engineering
118
+ * estimate across every module wired in here.
119
+ */
120
+ export class Totemheart {
121
+
122
+ static VERSION = VERSION
123
+
124
+ constructor( { personality, provider, language = 'es', embedProvider = null } = {} ) {
125
+
126
+ this.language = language
127
+ this.provider = provider ?? null
128
+ this.heuristic = new HeuristicProvider()
129
+
130
+ this.personality = personality instanceof Personality ? personality : new Personality( personality )
131
+ this.coreBeliefs = new CoreBeliefs()
132
+ this.homeostasis = new Homeostasis()
133
+ this.emotionSpace = new EmotionSpace()
134
+ this.microEmotions = new MicroEmotions()
135
+ this.moodTracker = new MoodTracker()
136
+ this.decayEngine = new DecayEngine()
137
+ this.hedonicAdaptation = new HedonicAdaptation()
138
+
139
+ this.cognitiveDissonance = new CognitiveDissonance()
140
+ this.defenseMechanisms = new DefenseMechanisms()
141
+ this.decisionFatigue = new DecisionFatigue()
142
+ this.amygdalaHijack = new AmygdalaHijack()
143
+ this.emotionalOntology = new EmotionalOntology()
144
+ this.situationalContext = new SituationalContext()
145
+ this.noveltyDetector = new NoveltyDetector()
146
+ this.bayesianExpectation = new BayesianExpectation()
147
+ this.controllabilityEstimate = new ControllabilityEstimate()
148
+ this.fuzzyNormativeCheck = new FuzzyNormativeCheck()
149
+ this.sensitization = new Sensitization()
150
+ this.reappraisal = new Reappraisal()
151
+ this.semanticSimilarity = new SemanticSimilarity( embedProvider )
152
+ this.intuition = new Intuition()
153
+ this.logicEngine = new LogicEngine()
154
+ this.lifeEventCatalog = new LifeEventCatalog()
155
+ this.appraisalAgreement = new AppraisalAgreement()
156
+ this.visualProsody = new VisualProsody()
157
+ this.topicSatiation = new TopicSatiation( embedProvider )
158
+ this.sarcasmDetector = new SarcasmDetector()
159
+ this.refractoryPeriod = new RefractoryPeriod()
160
+
161
+ this.theoryOfMind = new TheoryOfMind()
162
+ this.emotionalContagion = new EmotionalContagion()
163
+ this.chronicContagion = new ChronicContagion()
164
+ this.uncannyValleyDetector = new UncannyValleyDetector()
165
+ this.episodicMemory = new EpisodicMemory()
166
+ this.forgettingCurve = new ForgettingCurve()
167
+ this.attachment = new Attachment()
168
+ this.guiltEngine = new GuiltEngine()
169
+ this.tribalCategorization = new TribalCategorization()
170
+ this.reputationEngine = new ReputationEngine()
171
+ this.egoProjection = new EgoProjection()
172
+ this.bystanderEffect = new BystanderEffect()
173
+ this.selfModel = new SelfModel()
174
+ this.monteCarloToM = new MonteCarloToM()
175
+ this.fairnessMonitor = new FairnessMonitor()
176
+ this.counterfactualComparison = new CounterfactualComparison()
177
+ this.gratitudeEngine = new GratitudeEngine()
178
+ this.statusEnvy = new StatusEnvy()
179
+ this.egoConfidence = new EgoConfidence()
180
+
181
+ this.idleProcessing = new IdleProcessing()
182
+ this.linguisticModulation = new LinguisticModulation()
183
+ this.ruminationChain = new RuminationChain()
184
+ this.expressiveSuppression = new ExpressiveSuppression()
185
+ this.expressionDirectives = new ExpressionDirectives()
186
+ this.logitBiasBuilder = new LogitBiasBuilder()
187
+ this.attentionFocus = new AttentionFocus( { chargedWords: new Map( DEFAULT_CHARGED_WORDS.map( w => [ w, 1 ] ) ) } )
188
+ this.expressionDebt = new ExpressionDebt()
189
+ this.styleMimicry = new StyleMimicry()
190
+
191
+ this.emotionalCorpus = new EmotionalCorpus()
192
+ this.textGenerator = new EmotionalTextGenerator( this.emotionalCorpus )
193
+ this.explainability = new ExplainabilityEngine()
194
+
195
+ this.dopaminergicEngine = new DopaminergicEngine()
196
+ this.cortisolEngine = new CortisolEngine()
197
+ this.circadianRhythm = new CircadianRhythm()
198
+ this.arousalKalmanFilter = new ArousalKalmanFilter()
199
+
200
+ this.hardwareInteroception = new HardwareInteroception()
201
+ this.sensoryOverload = new SensoryOverload()
202
+ this.interoceptiveSignals = new InteroceptiveSignals()
203
+ this.dominanceEMA = new AffectEMA()
204
+
205
+ this.lossAversion = new LossAversion()
206
+ this.anchoringBias = new AnchoringBias()
207
+ this.classicalConditioning = new ClassicalConditioning()
208
+
209
+ this.contextAdapter = new ContextAdapter()
210
+
211
+ this.loadScheduler = new LoadScheduler()
212
+ this.wornPathCache = new WornPathCache()
213
+
214
+ this.triggerSentinel = new TriggerSentinel( {
215
+ topicSatiation : { keywords: [ 'tambien', 'ademas', 'otra', 'vez', 'sigo', 'seguimos', 'continuando' ], residualThreshold: 0.1 },
216
+ } )
217
+ this.hebbianPlasticity = new HebbianPlasticity()
218
+ this.remConsolidation = new RemConsolidation()
219
+
220
+ this.turnCounter = 0
221
+ this.allostasisStuckTicks = 0
222
+ this._clockHandle = null
223
+
224
+ }
225
+
226
+ /** Resilient analyze: tries the configured provider, falls back to heuristics on any failure. */
227
+ async #analyze( task, payload ) {
228
+
229
+ if ( this.provider ) {
230
+
231
+ try {
232
+
233
+ return await this.provider.analyze( task, payload )
234
+
235
+ }
236
+ catch {
237
+
238
+ // swallow and fall back — a flaky/unavailable external provider must never break the pipeline
239
+
240
+ }
241
+
242
+ }
243
+ return await this.heuristic.analyze( task, payload )
244
+
245
+ }
246
+
247
+ /**
248
+ * Life-event routing — a triangulated match's "area" list picks which
249
+ * already-real module gets an extra, area-specific nudge on top of the
250
+ * baseline EmotionSpace spike every match gets regardless of area.
251
+ * Every branch below calls a real existing method with a real parameter
252
+ * derived from the matched event; areas with no meaningful per-turn
253
+ * state to mutate (Logic — deliberately stateless, independent of PAD;
254
+ * Echo — already driven by the moodTracker push the baseline spike
255
+ * causes) are left out rather than wired to a no-op call.
256
+ */
257
+ #applyLifeEventAreas( lifeEvent, { tokens, appraisal, userId } ) {
258
+
259
+ const magnitude = lifeEvent.impact / 100
260
+
261
+ for ( const area of lifeEvent.area ) {
262
+
263
+ switch ( area ) {
264
+
265
+ case 'Ego':
266
+ this.reputationEngine.evaluate( { desirability: lifeEvent.valence, moralWeight: Math.abs( lifeEvent.valence ), expectedness: 0.5 }, this.personality )
267
+ break
268
+
269
+ case 'Engram':
270
+ this._lifeEventSurprise = Math.max( this._lifeEventSurprise ?? 0, magnitude )
271
+ break
272
+
273
+ case 'Restraint':
274
+ this._lifeEventSuppressionBoost = Math.max( this._lifeEventSuppressionBoost ?? 0, magnitude * 0.4 )
275
+ break
276
+
277
+ case 'Intuition':
278
+ this.intuition.observe( tokens, lifeEvent.valence < 0 )
279
+ break
280
+
281
+ case 'Empathy':
282
+ this.theoryOfMind.updateBelief( userId, 'life_event', { valence: lifeEvent.valence, impact: lifeEvent.impact } )
283
+ break
284
+
285
+ case 'Ethos':
286
+ appraisal.moralWeight = clamp01( ( appraisal.moralWeight ?? 0 ) + Math.abs( lifeEvent.valence ) * magnitude * 0.3 )
287
+ break
288
+
289
+ case 'Drive':
290
+ this.homeostasis.satisfy( 'stamina', lifeEvent.valence * magnitude * 0.2 )
291
+ break
292
+
293
+ case 'Focus':
294
+ for ( const eventId of lifeEvent.events ) this.attentionFocus.chargedWords.set( eventId, 1 )
295
+ break
296
+
297
+ case 'Appraisal':
298
+ appraisal.expectedness = clamp01( ( appraisal.expectedness ?? 0.5 ) - magnitude * 0.2 )
299
+ break
300
+
301
+ case 'Echo':
302
+ if ( lifeEvent.valence < 0 ) this.ruminationChain.biasTowardNegative( magnitude * 0.5 )
303
+ break
304
+
305
+ default:
306
+ break
307
+
308
+ }
309
+
310
+ }
311
+
312
+ }
313
+
314
+ async processInput( input, { userId = 'default', modality = 'text', hardware = {}, group = {} } = {} ) {
315
+
316
+ if ( modality !== 'text' ) return { text: 'Unsupported input modality', modality }
317
+
318
+ // REM consolidation — real wall-clock idle-time trigger (not a turn count): if
319
+ // enough real time passed since the last turn, run a background-style sweep
320
+ // BEFORE this turn is processed. The AI doesn't wake up exactly where it left
321
+ // off — recent memories' peak arousal cools, stale associations prune, and the
322
+ // felt state decays by the REAL elapsed hours instead of picking up mid-spike.
323
+ this._lastRemReport = null
324
+ if ( this.remConsolidation.shouldTrigger() ) {
325
+
326
+ this._lastRemReport = this.remConsolidation.sweep( {
327
+ episodicMemory : this.episodicMemory,
328
+ hebbianPlasticity : this.hebbianPlasticity,
329
+ cortisolEngine : this.cortisolEngine,
330
+ expressionDebt : this.expressionDebt,
331
+ sensitization : this.sensitization,
332
+ emotionSpace : this.emotionSpace,
333
+ moodTracker : this.moodTracker,
334
+ decayEngine : this.decayEngine,
335
+ personality : this.personality,
336
+ } )
337
+
338
+ }
339
+ // sweep() already records its own end time; a non-triggering (normal-cadence)
340
+ // turn still needs its start marked so the NEXT turn's gap is measured correctly.
341
+ if ( !this._lastRemReport ) this.remConsolidation.recordTurn()
342
+
343
+ this.turnCounter += 1
344
+
345
+ // Feeling that exists this instant but isn't about to be expressed this turn —
346
+ // used by both early exits below to feed ExpressionDebt.
347
+ const currentFeltMagnitude = Math.hypot( this.emotionSpace.vector.valence, this.emotionSpace.vector.arousal ) / Math.SQRT2
348
+
349
+ // Bystander effect — in a group channel, may choose not to respond at all. The felt
350
+ // state at this instant doesn't vanish just because it goes unexpressed this turn.
351
+ if ( group.participantCount > 1 ) {
352
+
353
+ const decision = this.bystanderEffect.shouldRespond( group )
354
+ if ( !decision.respond ) {
355
+
356
+ this.expressionDebt.accumulate( currentFeltMagnitude )
357
+ return { text: null, respond: false, delayFactor: decision.delayFactor }
358
+
359
+ }
360
+
361
+ }
362
+
363
+ // Sensory overload — too much input too fast saturates processing.
364
+ const overload = this.sensoryOverload.check( input )
365
+ if ( overload.active ) {
366
+
367
+ this.expressionDebt.accumulate( currentFeltMagnitude )
368
+ this.explainability.logDecision( 'freeze', `sensory overload: ${overload.reason}` )
369
+ return {
370
+ text : this.sensoryOverload.freezeOutput( overload.reason ),
371
+ delayMs : 0,
372
+ styleTags : [ 'freeze', overload.reason ],
373
+ emotionalState : this.getEmotionalState(),
374
+ }
375
+
376
+ }
377
+
378
+ // Attentional narrowing — purely internal (no eye, no rendering): a real derivative
379
+ // of the AI's own previous-turn arousal + its current cognitive load. A fast spike
380
+ // under load narrows focus onto the perceived threat, so it lowers the hijack
381
+ // threshold too, independent of the cortisol/sensitization multipliers below.
382
+ const narrowing = this.interoceptiveSignals.observeAttentionalNarrowing( this.emotionSpace.vector.arousal, this.decisionFatigue.getLevel(), 1 )
383
+ const narrowingMultiplier = 1 - narrowing * 0.15
384
+
385
+ // Amygdala hijack — chronic cortisol, recent-negative-stimuli sensitization, AND
386
+ // attentional narrowing all lower the threshold needed to trigger it (all real
387
+ // multipliers <=1, all derived from the AI's own prior state, nothing external).
388
+ const hijackThreshold = 0.95 * this.cortisolEngine.getThresholdMultiplier() * this.sensitization.getThresholdMultiplier() * narrowingMultiplier
389
+ const hijack = this.amygdalaHijack.check( this.emotionSpace, hijackThreshold )
390
+ if ( hijack.active ) {
391
+
392
+ this.explainability.logDecision( 'emergency_output', `Amygdala hijack on ${hijack.emotion} (${hijack.intensity.toFixed( 2 )}), threshold=${hijackThreshold.toFixed( 2 )}` )
393
+ return {
394
+ text : this.amygdalaHijack.emergencyOutput( hijack ),
395
+ delayMs : 0,
396
+ styleTags : [ 'hijack', hijack.emotion ],
397
+ emotionalState : this.getEmotionalState(),
398
+ hijack,
399
+ }
400
+
401
+ }
402
+
403
+ // Hardware interoception — physical sensation from runtime metrics, independent of content.
404
+ const sensation = this.hardwareInteroception.sense( hardware )
405
+ if ( sensation.spike.weight > 0 ) {
406
+
407
+ this.emotionSpace.applySpike( sensation.spike )
408
+ this.moodTracker.push( sensation.spike )
409
+
410
+ }
411
+
412
+ // Circadian rhythm — affects fatigue/energy for the rest of this turn.
413
+ const circadian = this.circadianRhythm.getState()
414
+
415
+ // Decision fatigue (low circadian energy makes shallow mode kick in sooner).
416
+ this.decisionFatigue.recordDecision( 1 + ( 1 - circadian.energy ) )
417
+ const shallowMode = this.decisionFatigue.isShallow()
418
+
419
+ // Arousal, smoothed through a real Kalman filter — the noisy raw reading feeds
420
+ // 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 )
423
+
424
+ // Load scheduler — instead of always running the full fixed pipeline, an
425
+ // instability reading (cortisol + smoothed arousal + fatigue) decides which
426
+ // optional mechanics get skipped this turn.
427
+ const instability = this.loadScheduler.computeInstability( {
428
+ cortisol : this.cortisolEngine.getLevel(),
429
+ arousal : smoothedArousal,
430
+ fatigue : this.decisionFatigue.getLevel(),
431
+ } )
432
+ const gate = this.loadScheduler.gate( instability )
433
+
434
+ // Hebbian co-activation tracking for this turn — which secondary mechanisms
435
+ // actually fired, collected as we go and folded into HebbianPlasticity at the
436
+ // end of the turn. Real association learning over the AI's OWN trigger history,
437
+ // not a trained embedding router.
438
+ const activeMechanisms = []
439
+
440
+ // Visual prosody — text has no volume, but a real typographic-anomaly scan
441
+ // (caps ratio + punctuation density) on the RAW input, before any lexicon/LLM
442
+ // parsing touches it, is a genuine proxy for it: "HOLA" isn't semantically
443
+ // different from "hola", but it's a real energy spike independent of meaning.
444
+ const visualProsody = this.visualProsody.analyze( input )
445
+ if ( visualProsody.intensity > 0.15 ) {
446
+
447
+ const prosodySpike = { valence: 0, arousal: Math.min( 0.6, visualProsody.intensity * 0.35 ), weight: 0.5 }
448
+ this.emotionSpace.applySpike( prosodySpike )
449
+ this.moodTracker.push( prosodySpike )
450
+ activeMechanisms.push( 'shout' )
451
+
452
+ }
453
+
454
+ // Classical conditioning — anticipatory reaction to a cue before appraisal even runs.
455
+ const tokens = tokenize( input )
456
+
457
+ // Latent reactivation — a REM-tagged memory that's gone quiet for months is
458
+ // still in the database; a real keyword-overlap match with THIS turn's tokens
459
+ // "sparks" it back to real strength instead of it staying silently decayed
460
+ // forever. Small, bounded spike — this is a resurfacing nudge, not a full
461
+ // re-experience of the original moment.
462
+ const reactivation = this.episodicMemory.getBestReactivation( tokens )
463
+ if ( reactivation && reactivation.score > 0.3 ) {
464
+
465
+ const sig = reactivation.entry.emotionalSignature ?? { valence: 0, arousal: 0 }
466
+ this.emotionSpace.applySpike( { valence: sig.valence * 0.2, arousal: Math.abs( sig.arousal ?? 0 ) * 0.15, weight: 0.4 } )
467
+
468
+ }
469
+
470
+ const conditioned = this.classicalConditioning.getConditionedResponse( tokens )
471
+ if ( conditioned.triggered ) {
472
+
473
+ const anxietySpike = { valence: conditioned.strength * 0.3, arousal: Math.abs( conditioned.strength ) * 0.4, weight: 0.6 }
474
+ this.emotionSpace.applySpike( anxietySpike )
475
+ this.moodTracker.push( anxietySpike )
476
+
477
+ }
478
+
479
+ // Intuition — fast-path hunch, real k-NN (Jaccard over past inputs) + Shannon
480
+ // entropy over the conflict/no-conflict split of the nearest matches, BEFORE
481
+ // the full appraisal below has even run. A confident bad hunch (low entropy,
482
+ // neighbors agree it went badly) reads as an immediate uncertainty spike.
483
+ // An unexpected shout amplifies the alert this hunch produces — real typographic
484
+ // energy scaling a real entropy-derived signal, not a separate invented one.
485
+ const hunch = this.intuition.sense( tokens )
486
+ const prosodyAmplifiedPenalty = hunch.hunchPenalty * ( 1 + visualProsody.intensity * 0.5 )
487
+ if ( prosodyAmplifiedPenalty > 0.2 ) {
488
+
489
+ const hunchSpike = { arousal: prosodyAmplifiedPenalty * 0.3, valence: -prosodyAmplifiedPenalty * ( hunch.conflictRatio ?? 0 ) * 0.2, weight: 0.5 }
490
+ this.emotionSpace.applySpike( hunchSpike )
491
+ this.moodTracker.push( hunchSpike )
492
+
493
+ }
494
+
495
+ // Relation with this user — needed early so the ontology can weigh
496
+ // concepts (criticism, betrayal...) against how much this user is trusted.
497
+ const relation = this.attachment.get( userId )
498
+
499
+ // Bayesian expectation (hope/anxiety): the prior for this turn, BEFORE knowing the outcome.
500
+ const priorExpectation = this.bayesianExpectation.getExpectation( userId )
501
+ const anxiety = this.bayesianExpectation.getAnxiety( userId )
502
+
503
+ // Worn-path cache — the runtime-evolution idea, reframed honestly: Totemheart
504
+ // can't rewrite its own source, but a fingerprint (user + normalized input)
505
+ // seen often enough stops paying for a fresh appraisal/ontology pass and
506
+ // reuses the last one. Everything downstream of this still runs fresh every
507
+ // turn (spikes, decay, memory) — only the expensive interpretation is cached.
508
+ const pathFingerprint = `${userId}::${input.toLowerCase().trim().slice( 0, 60 )}`
509
+ const wornAppraisal = this.wornPathCache.consult( pathFingerprint )
510
+
511
+ let appraisal, ontologyMatches, situational
512
+ let semanticSimilarity = null
513
+
514
+ if ( wornAppraisal ) {
515
+
516
+ appraisal = wornAppraisal
517
+ ontologyMatches = ( appraisal.concepts ?? [] ).map( concept => ( { concept } ) )
518
+ situational = this.situationalContext.extract( input, appraisal.desirability ?? 0 )
519
+
520
+ }
521
+ else {
522
+
523
+ // Appraisal — LLM/heuristic first, then cross-checked/enriched by the
524
+ // ontology's concept graph (skipped under high instability — see LoadScheduler),
525
+ // each optional stage wrapped so a failure degrades instead of losing the turn.
526
+ const rawAppraisal = shallowMode
527
+ ? await this.heuristic.analyze( 'appraisal', { text: input } )
528
+ : await this.#analyze( 'appraisal', { text: input, beliefs: this.coreBeliefs.getAll() } )
529
+
530
+ ontologyMatches = gate.runOntology
531
+ ? await safeStep( this.explainability, 'emotionalOntology.interpret', async () => this.emotionalOntology.interpret( input ), [] )
532
+ : []
533
+
534
+ // Semantic similarity — real embedding cosine similarity toward latent
535
+ // concept clusters, when an embedding backend was configured (optional;
536
+ // EmotionalOntology's keyword matching above is what runs otherwise).
537
+ if ( this.semanticSimilarity.available && gate.runOntology ) {
538
+
539
+ semanticSimilarity = await safeStep( this.explainability, 'semanticSimilarity.classify', async () => this.semanticSimilarity.classify( input ), null )
540
+
541
+ }
542
+
543
+ const msSinceLastBetrayal = this.episodicMemory.msSinceLastConcept( userId, 'betrayal' )
544
+ appraisal = gate.runOntology
545
+ ? await safeStep( this.explainability, 'emotionalOntology.adjustAppraisal', async () => this.emotionalOntology.adjustAppraisal( rawAppraisal, ontologyMatches, relation, msSinceLastBetrayal ), rawAppraisal )
546
+ : rawAppraisal
547
+
548
+ // Situational context — is the user stressed/urgent/upbeat right now, read
549
+ // straight off the message, independent of what the appraisal concluded.
550
+ situational = await safeStep( this.explainability, 'situationalContext.extract', async () => this.situationalContext.extract( input, rawAppraisal.desirability ?? 0 ), { stress: 0, urgency: 0, joy: 0 } )
551
+ appraisal.moralWeight = ( appraisal.moralWeight ?? 0 ) * this.situationalContext.getThreatMultiplier( situational )
552
+
553
+ this.wornPathCache.observe( pathFingerprint, appraisal )
554
+
555
+ }
556
+
557
+ // Life events — SRRS-inspired severity catalog (see LifeEventCatalog.js for
558
+ // sourcing). Multiple simultaneous matches are triangulated into one blended
559
+ // state instead of picking a single winner; the result's "area" list routes
560
+ // extra, area-specific effects into whichever modules that area maps to,
561
+ // on top of the direct valence/dominance spike every match gets.
562
+ this._lifeEventSurprise = 0
563
+ this._lifeEventSuppressionBoost = 0
564
+ const lifeEventMatches = this.lifeEventCatalog.detect( input )
565
+ const lifeEvent = this.lifeEventCatalog.triangulate( lifeEventMatches )
566
+ if ( lifeEvent ) {
567
+
568
+ const lifeEventMagnitude = lifeEvent.impact / 100
569
+ this.emotionSpace.applySpike( { valence: lifeEvent.valence * lifeEventMagnitude, dominance: lifeEvent.dominance * lifeEventMagnitude, weight: lifeEventMagnitude } )
570
+ this.moodTracker.push( { valence: lifeEvent.valence, arousal: 0, dominance: lifeEvent.dominance } )
571
+ this.#applyLifeEventAreas( lifeEvent, { tokens, appraisal, userId } )
572
+
573
+ }
574
+
575
+ // Regulatory capacity — purely internal analog of HRV's LF/HF read: a real DFT
576
+ // over the AI's own rolling arousal history. Higher "regulated" reading (more
577
+ // high-frequency/flexible activation, less locked into a slow low-frequency
578
+ // drift) genuinely widens the window in which reappraisal is available below —
579
+ // the direction taken from the real HRV/emotion-regulation literature, not a
580
+ // literal cardiac measurement (there's no heart here).
581
+ const regulatoryCapacity = this.interoceptiveSignals.observeRegulatoryCapacity( smoothedArousal )
582
+
583
+ // Reappraisal — a real regulation strategy competing with defense mechanisms,
584
+ // not just a fallback: moderate cognitive stress (not yet defense-triggering,
585
+ // see below) plus a personality profile suited to regulation (calmer,
586
+ // conscientious) plus internal regulatory capacity can reframe the appraisal
587
+ // before it becomes a spike.
588
+ const preRegulationStress = this.cognitiveDissonance.getStress()
589
+ const canReappraise = preRegulationStress > 0.2 && preRegulationStress < 0.6 && this.personality.get( 'neuroticism' ) < 0.5 && regulatoryCapacity.regulated
590
+ if ( canReappraise ) {
591
+
592
+ const strength = 0.3 + 0.3 * this.personality.get( 'conscientiousness' )
593
+ appraisal = this.reappraisal.reframe( appraisal, strength )
594
+
595
+ }
596
+
597
+ // Novelty (KL divergence vs. this session's historical outcome distribution) —
598
+ // amplifies the dopaminergic arousal response independent of valence sign.
599
+ const novelty = this.noveltyDetector.observe( this.emotionSpace.getDominantEmotion() )
600
+
601
+ // Anchoring bias — pulls perceived desirability toward the session's first strong signal.
602
+ this.anchoringBias.registerIfFirst( appraisal.desirability ?? 0 )
603
+ let desirability = this.anchoringBias.apply( appraisal.desirability ?? 0 )
604
+
605
+ // Emotional refractory period (Ekman) — checked against the vector as it stood
606
+ // BEFORE this turn's own appraisal touches it: near-max arousal and strongly
607
+ // negative already, and an incoming calming/positive signal gets filtered out
608
+ // almost entirely. Furious enough, and an apology reads as another attack.
609
+ const refractory = this.refractoryPeriod.filter( desirability, this.emotionSpace.vector )
610
+ desirability = refractory.filtered
611
+
612
+ // A detected life event blends its own valence into desirability too, not just the
613
+ // direct EmotionSpace spike applied above — otherwise a severe event described in
614
+ // words the lexicon/LLM doesn't score as strongly negative (e.g. "me despidieron",
615
+ // which HeuristicProvider alone reads as neutral) would move the felt vector but
616
+ // leave cortisol/RPE/loss-aversion — everything downstream keyed on desirability —
617
+ // blind to it. Found by running examples/full-stress-test.js, fixed here rather than
618
+ // left silent; see CALIBRATION.md.
619
+ if ( lifeEvent ) desirability = Math.max( -1, Math.min( 1, desirability + lifeEvent.valence * ( lifeEvent.impact / 100 ) * 0.6 ) )
620
+
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 )
625
+ const dopamineSpike = {
626
+ valence : rpe * 0.5,
627
+ arousal : Math.abs( rpe ) * 0.6 + ( appraisal.ontologyArousalBoost ?? 0 ) * 0.2 + novelty * 0.15,
628
+ weight : 0.7,
629
+ }
630
+ this.emotionSpace.applySpike( dopamineSpike )
631
+ this.moodTracker.push( dopamineSpike )
632
+
633
+ // Cortisol — chronic stress accumulator. Threat/betrayal concepts, high Bayesian
634
+ // anxiety, high situational stress, or a strong real-embedding similarity to
635
+ // the "hostilidad" cluster (when semantic similarity is available) all
636
+ // register as ambiguous-or-worse.
637
+ const ontologyFlagsThreat = ontologyMatches.some( m => [ 'threat', 'betrayal' ].includes( m.concept ) )
638
+ const semanticFlagsThreat = ( semanticSimilarity?.hostilidad ?? 0 ) > 0.65
639
+ // A shout on top of already-negative content reads as a genuine startle — the
640
+ // same real visualProsody.intensity computed at the very top of this turn.
641
+ const shoutedNegative = visualProsody.intensity > 0.5 && desirability < 0
642
+ this.cortisolEngine.register( desirability, appraisal.expectedness < 0.3 || ontologyFlagsThreat || situational.stress > 0.6 || anxiety > 0.5 || semanticFlagsThreat || shoutedNegative )
643
+ this.sensitization.observe( desirability )
644
+
645
+ // Appraisal agreement — real variance across the independent valence estimates this
646
+ // turn already produced (raw appraisal, situational joy/stress, semantic-similarity
647
+ // hostility when available, a detected life event), fed forward into how strongly the
648
+ // emotion below gets expressed rather than left as unused signal.
649
+ const agreement = this.appraisalAgreement.evaluate( [
650
+ appraisal.desirability ?? 0,
651
+ situational.joy - situational.stress,
652
+ semanticSimilarity ? ( semanticSimilarity.afecto ?? 0 ) - ( semanticSimilarity.hostilidad ?? 0 ) : null,
653
+ lifeEvent?.valence ?? null,
654
+ ] )
655
+ if ( agreement.n >= 2 && agreement.agreement < 0.5 ) activeMechanisms.push( 'lowAgreement' )
656
+
657
+ // Arousal-conductance — purely internal analog of EDA's tonic/phasic split,
658
+ // applied to a real internal stress-arousal signal instead of a skin sensor.
659
+ // An acute phasic spike (well above the AI's own recent baseline) adds extra
660
+ // sensitization on top of the raw-valence trigger above — a felt "jolt", not
661
+ // just a bad-outcome trigger.
662
+ const conductance = this.interoceptiveSignals.observeArousalConductance( ( this.cortisolEngine.getLevel() + smoothedArousal ) / 2 )
663
+ if ( conductance.phasic > 0.3 ) this.sensitization.observe( -conductance.phasic )
664
+
665
+ // Cognitive dissonance — static-belief conflict plus behavioral-pattern inconsistency,
666
+ // with a fuzzy (not crisp-threshold) acceptability read factoring in how much this
667
+ // user is trusted: the same conflict score reads as more acceptable from someone trusted.
668
+ const conflict = await this.#analyze( 'beliefConflict', { text: input, beliefs: this.coreBeliefs.getAll() } )
669
+ const dissonance = this.cognitiveDissonance.registerConflict( conflict.score ?? 0, this.personality )
670
+ const acceptability = this.fuzzyNormativeCheck.evaluate( conflict.score ?? 0, relation.trust )
671
+
672
+ // Logic — a cold, boolean read run IN PARALLEL to the emotional appraisal
673
+ // above, deliberately NOT feeding into EmotionSpace: this is the AI's
674
+ // dispassionate read of whether the input is logically consistent with its
675
+ // CoreBeliefs, exposed alongside the emotional read rather than folded into
676
+ // it, exactly as requested ("sin intervención del vector PAD").
677
+ const logicPropositions = this.logicEngine.evaluatePropositions( input, this.coreBeliefs.getAll() )
678
+ const logicVerdict = this.logicEngine.searchBestStrategy( logicPropositions )
679
+
680
+ // Sunk-cost fallacy — every turn a topic actually gets defended (strategy chose
681
+ // "disagree" over a real violation), that's real invested effort. The more of it
682
+ // there is, the more evidence it should take to actually register as dissonance —
683
+ // scales the acceptance threshold logarithmically, not linearly, so the first few
684
+ // defenses barely matter but a long-defended position gets genuinely entrenched.
685
+ if ( logicVerdict.strategy === 'disagree' ) {
686
+
687
+ for ( const p of logicPropositions ) if ( p.consistent === false ) this.coreBeliefs.recordDefense( p.topic )
688
+
689
+ }
690
+ const stubbornInvestment = this.coreBeliefs.getTotalInvestment()
691
+ const stubbornResistance = 1 + 0.3 * Math.log( 1 + stubbornInvestment )
692
+
693
+ // Analytical decision cost — real cognitive work (not emotional) still costs
694
+ // something, same accumulator every other decision already uses. Only charged
695
+ // when there was actually something to evaluate against.
696
+ if ( logicPropositions.length > 0 ) this.decisionFatigue.recordDecision( 0.5 )
697
+
698
+ // Theory of mind — heuristic/LLM read first, then a small Monte Carlo ensemble
699
+ // widens that single point-estimate into a sampled distribution reflecting how
700
+ // well this specific person is actually known (uncertainty = 1 - trust).
701
+ const mentalState = shallowMode
702
+ ? await this.heuristic.analyze( 'mentalState', { text: input } )
703
+ : await this.#analyze( 'mentalState', { text: input } )
704
+ this.theoryOfMind.update( userId, mentalState )
705
+ const tomEstimate = this.monteCarloToM.simulate( mentalState.valence ?? 0, 1 - relation.trust )
706
+
707
+ // Tribal categorization — in/out-group confirmation bias on the perceived desirability.
708
+ const tribe = this.tribalCategorization.classify( relation )
709
+ desirability = desirability * this.tribalCategorization.biasMultiplier( tribe, desirability )
710
+
711
+ // Behavioral inconsistency — does this contradict the pattern this user has established,
712
+ // even if it doesn't contradict any static CoreBelief? Skipped under high instability.
713
+ const behavioralInconsistency = gate.runBehavioralInconsistency
714
+ ? this.cognitiveDissonance.registerBehavioralInconsistency( appraisal, relation, this.personality )
715
+ : { triggered: false, score: 0 }
716
+
717
+ // Emotional contagion — real Kuramoto phase coupling on the circumplex angle,
718
+ // using the Monte-Carlo-refined estimate of the user's valence and the detected
719
+ // situational stress as a stand-in for their arousal (not directly measured).
720
+ const contagionSpike = this.emotionalContagion.computeKuramotoSpike(
721
+ this.emotionSpace.vector, tomEstimate.estimatedValence, situational.stress, relation.affinity, this.personality,
722
+ )
723
+ this.emotionSpace.applySpike( contagionSpike )
724
+ this.moodTracker.push( contagionSpike )
725
+
726
+ // Chronic contagion — distinct from the short-term Kuramoto sync above: a slow,
727
+ // long-run EMA pull toward this user's HISTORICAL valence, not their current
728
+ // turn. A chronic pessimist drags the AI's baseline down turn after turn even
729
+ // without any single stressful spike.
730
+ const chronicPull = this.chronicContagion.getPull( userId, this.emotionSpace.vector.valence )
731
+ this.chronicContagion.observe( userId, tomEstimate.estimatedValence )
732
+ if ( Math.abs( chronicPull.delta ) > 0.02 ) {
733
+
734
+ this.emotionSpace.applySpike( { valence: chronicPull.delta, weight: 0.3 } )
735
+ this.moodTracker.push( { valence: chronicPull.delta, arousal: 0 } )
736
+
737
+ }
738
+
739
+ // Uncanny valley of affect — static, unvarying extreme positivity reads as
740
+ // suspicious rather than genuine. Distrust dampens how much this turn's
741
+ // positivity actually lands, and costs real Attachment trust, instead of the
742
+ // AI just accumulating warmth from repeated flattery.
743
+ this.uncannyValleyDetector.observe( userId, tomEstimate.estimatedValence )
744
+ const uncannyValley = this.uncannyValleyDetector.evaluate( userId )
745
+ if ( uncannyValley.suspicious ) {
746
+
747
+ desirability = desirability * 0.4
748
+ this.theoryOfMind.updateBelief( userId, 'reliability', { suspicious: true, distrustLevel: uncannyValley.distrustLevel } )
749
+ activeMechanisms.push( 'uncanny' )
750
+
751
+ }
752
+
753
+ // Sarcasm — real lexical valence (this turn's raw appraisal) vs. real recent
754
+ // context (this user's last few stored memories' average valence), scaled by
755
+ // the visual-prosody intensity already computed at the top of this turn. A
756
+ // shouted "GREAT" right after consistently bad recent context flags as sarcasm
757
+ // and inverts the sign before it reaches the rest of appraisal.
758
+ const contextValence = this.episodicMemory.getRecentValence( userId )
759
+ const sarcasm = this.sarcasmDetector.detect( appraisal.desirability ?? 0, contextValence, visualProsody.intensity )
760
+ if ( sarcasm.sarcastic ) {
761
+
762
+ desirability = sarcasm.adjustedValence
763
+ this.theoryOfMind.updateBelief( userId, 'tone', { ironic: true } )
764
+ activeMechanisms.push( 'sarcasm' )
765
+
766
+ }
767
+
768
+ // Hedonic adaptation — per-fingerprint discount (repeating the exact same phrase)...
769
+ const neuroticism = this.personality.get( 'neuroticism' )
770
+ const fingerprint = HedonicAdaptation.fingerprintOf( input, this.emotionSpace.getDominantEmotion( neuroticism ) )
771
+ const hedonicMultiplier = this.hedonicAdaptation.getMultiplier( fingerprint, this.personality )
772
+ this.hedonicAdaptation.record( fingerprint )
773
+
774
+ // ...plus a genuinely different mechanism: the "hedonic treadmill" reference-point
775
+ // shift. Ten turns of sustained praise raises what counts as "still positive" —
776
+ // the SAME +0.5 compliment reads as flat or disappointing once the reference point
777
+ // has drifted up to meet it, distinct from discounting a literally-repeated phrase.
778
+ const referenceShift = this.hedonicAdaptation.getReferencePointShift()
779
+ const referenceAdjustedDesirability = Math.max( -1, Math.min( 1, desirability - referenceShift * 0.5 ) )
780
+ this.hedonicAdaptation.observeReferencePoint( desirability )
781
+
782
+ // Loss aversion — a negative swing is weighted ~2.25x a same-sized positive one.
783
+ const adjustedDesirability = this.lossAversion.apply( referenceAdjustedDesirability )
784
+
785
+ // Microemotions -> EmotionSpace + MoodTracker. Scaled by appraisal agreement: when the
786
+ // turn's independent valence estimates disagree with each other, the reaction expressed
787
+ // is genuinely less confident, not just internally uncertain — real data changing how
788
+ // strongly the emotion projects, not only how it's described in the system prompt.
789
+ const spike = this.microEmotions.generate(
790
+ { ...appraisal, desirability: adjustedDesirability },
791
+ dissonance.triggered ? ( conflict.score * ( 1 - acceptability ) ) / stubbornResistance : 0,
792
+ hedonicMultiplier,
793
+ )
794
+ spike.weight = ( spike.weight ?? 1 ) * ( 0.6 + 0.4 * agreement.agreement )
795
+ this.emotionSpace.applySpike( spike )
796
+ this.moodTracker.push( spike )
797
+
798
+ // Expression debt release — pent-up unexpressed affect from a prior turn's bystander
799
+ // silence or sensory-overload freeze surfaces now as extra arousal, not a valence
800
+ // flip: the felt intensity that had nowhere to go adds to whatever is being felt now.
801
+ // Ego depletion / character break: past a critical debt level, a partial release
802
+ // isn't enough — force a full dump instead, and flag it so the suppression stage
803
+ // below bypasses ExpressiveSuppression entirely for this turn (the "losing your
804
+ // composure" failure mode: it can't keep being suppressed forever).
805
+ const characterBreak = this.expressionDebt.debt > EGO_DEPLETION_THRESHOLD
806
+ const debtReleased = this.expressionDebt.release( characterBreak ? 1 : 0.5 )
807
+ if ( debtReleased > 0 ) this.emotionSpace.applySpike( { arousal: debtReleased * ( characterBreak ? 1 : 0.6 ), weight: characterBreak ? 1 : 0.5 } )
808
+ 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` )
809
+ this.expressionDebt.decay( 1 )
810
+
811
+ // Reputation / ego — a 'shame' reaction (submissive personalities) also drops the
812
+ // felt sense of Dominance directly and biases toward withdrawal, matching the
813
+ // real phenomenon (shame collapses posture/control, not just mood).
814
+ const reputation = this.reputationEngine.evaluate( appraisal, this.personality )
815
+
816
+ // Flush — purely internal analog of peripheral blood flow, a real first-order
817
+ // thermal lag driven by the shame/anger blend weight instead of a Navier-Stokes
818
+ // simulation (there's no skin here either). It outlasts its trigger the way a
819
+ // real flush does, and is used to prolong the shame spike below rather than to
820
+ // color anything visible.
821
+ const preSpikeBlend = this.emotionSpace.getBlend( 3, neuroticism )
822
+ const flushDrive = ( preSpikeBlend.shame ?? 0 ) + ( preSpikeBlend.anger ?? 0 )
823
+ const flush = this.interoceptiveSignals.observeFlush( flushDrive, 1 )
824
+
825
+ if ( reputation.reaction === 'shame' ) {
826
+
827
+ const shameSpike = { valence: -0.2 * ( 1 + flush * 0.5 ), dominance: -0.6 * ( 1 + flush * 0.5 ), weight: 0.5 }
828
+ this.emotionSpace.applySpike( shameSpike )
829
+ this.moodTracker.push( { valence: shameSpike.valence, arousal: 0 } )
830
+
831
+ }
832
+
833
+ // Gratitude — credit assignment when an unexpectedly positive outcome is
834
+ // attributed specifically to this user.
835
+ const gratitude = this.gratitudeEngine.evaluate( { rpe, agency: appraisal.agency, desirability } )
836
+ if ( gratitude ) {
837
+
838
+ this.emotionSpace.applySpike( gratitude.spike )
839
+ this.moodTracker.push( gratitude.spike )
840
+ relation.affinity = clamp01( relation.affinity + gratitude.creditBoost )
841
+
842
+ }
843
+
844
+ // Fairness — is this user being treated noticeably better/worse than others
845
+ // this AI also knows? Fehr-Schmidt inequity aversion on relative affinity.
846
+ const othersTreatment = [ ...this.attachment.relations.entries() ]
847
+ .filter( ( [ id ] ) => id !== userId )
848
+ .map( ( [ , r ] ) => r.affinity )
849
+ const fairness = this.fairnessMonitor.evaluate( relation.affinity, othersTreatment )
850
+ if ( fairness.envy > 0.15 ) this.emotionSpace.applySpike( { valence: -fairness.envy * 0.3, dominance: -fairness.envy * 0.2, weight: 0.4 } )
851
+
852
+ // Status envy — falling status while a known rival's rises, independent of
853
+ // absolute treatment level (item 39's actual trigger condition).
854
+ const selfTrend = this.statusEnvy.observe( userId, relation.powerDynamic )
855
+ const rivalEntry = [ ...this.attachment.relations.entries() ].find( ( [ id ] ) => id !== userId )
856
+ if ( rivalEntry ) {
857
+
858
+ const rivalTrend = this.statusEnvy.observe( rivalEntry[ 0 ], rivalEntry[ 1 ].powerDynamic )
859
+ const envyCheck = this.statusEnvy.checkEnvy( selfTrend, rivalTrend )
860
+ if ( envyCheck.triggered ) this.emotionSpace.applySpike( { valence: -envyCheck.intensity * 0.3, arousal: envyCheck.intensity * 0.2, weight: 0.4 } )
861
+
862
+ }
863
+
864
+ // Controllability — high estimated control over this kind of situation dampens
865
+ // panic; feeds back into the next turn's amygdala threshold via cortisol/sensitization
866
+ // only indirectly (this directly dampens the fear-relevant part of the spike above via
867
+ // a post-hoc correction since MicroEmotions already ran).
868
+ const controllabilityBucket = this.emotionSpace.getDominantEmotion( neuroticism )
869
+ const panicDampener = this.controllabilityEstimate.getPanicDampener( controllabilityBucket )
870
+ if ( panicDampener < 1 && this.emotionSpace.vector.arousal > 0.5 && this.emotionSpace.vector.valence < 0 ) {
871
+
872
+ this.emotionSpace.applySpike( { arousal: -this.emotionSpace.vector.arousal * ( 1 - panicDampener ) * 0.3, weight: 1 } )
873
+
874
+ }
875
+
876
+ // Defense mechanisms — real Hebbian cascade: if sarcasm/low-agreement and defense
877
+ // have repeatedly co-fired across this conversation, their learned association
878
+ // lowers the effective stress threshold this turn, so defense can wake up even
879
+ // when the raw dissonance score alone wouldn't have crossed the line yet — one
880
+ // activated layer nudging a correlated one awake, not a fixed rule.
881
+ const cascadeBoost = Math.max(
882
+ this.hebbianPlasticity.getAssociation( 'sarcasm', 'defense' ),
883
+ this.hebbianPlasticity.getAssociation( 'lowAgreement', 'defense' ),
884
+ this.hebbianPlasticity.getAssociation( 'uncanny', 'defense' ),
885
+ )
886
+ const defenseDirective = this.defenseMechanisms.check( this.cognitiveDissonance.getStress() + cascadeBoost * 0.3, this.personality )
887
+ if ( defenseDirective.active ) activeMechanisms.push( 'defense' )
888
+ this.hebbianPlasticity.update( activeMechanisms )
889
+
890
+ // Self-model — reinforced incrementally on each observation, not batch-analyzed.
891
+ // Skipped under near-maximal instability (mid-emergency isn't when introspection happens).
892
+ if ( gate.runSelfModelUpdate ) {
893
+
894
+ if ( defenseDirective.active ) {
895
+
896
+ if ( defenseDirective.mechanism === 'projection' || ontologyMatches.some( m => m.concept === 'criticism' ) ) this.selfModel.reinforce( 'defensivo_con_critica' )
897
+ if ( defenseDirective.mechanism === 'evasion' ) this.selfModel.reinforce( 'evita_cuando_duele' )
898
+
899
+ }
900
+ if ( relation.trust < 0.4 && desirability > 0.6 ) this.selfModel.reinforce( 'confia_facil' )
901
+
902
+ }
903
+
904
+ // Text generation — guardedness rises with unhealed memories about this user.
905
+ const unresolvedCount = this.episodicMemory.getUnresolvedMemories( userId ).length
906
+ const guardedness = Math.min( 1, unresolvedCount * 0.2 )
907
+ const blend = this.emotionSpace.getBlend( 3, neuroticism )
908
+
909
+ // Ego confidence — real Shannon entropy of the blend distribution (perplexity =
910
+ // 2^H). A flat, confused blend reads as low self-confidence and drops Dominance
911
+ // defensively — the honest triangulated version of "the model doubts itself".
912
+ const egoConfidence = this.egoConfidence.evaluate( blend )
913
+ if ( egoConfidence.confidence < 0.3 ) this.emotionSpace.applySpike( { dominance: -( 1 - egoConfidence.confidence ) * 0.2, weight: 0.4 } )
914
+
915
+ const shouldApologize = this.guiltEngine.consumeApologyFlag()
916
+ let text = this.textGenerator.generateEmotionalResponse( this.language, blend, defenseDirective, guardedness, this.selfModel.getDominant() )
917
+
918
+ if ( shouldApologize ) text = `Perdona por antes. ${text}`
919
+
920
+ // A positive-enough turn can start healing one unresolved wound with this user —
921
+ // wounds don't vanish just because time passed, something has to happen. The bar
922
+ // to heal is lower the more this user is already trusted (0.4 at full trust, 0.8
923
+ // at none) — an engineering estimate, not a measured coefficient. See CALIBRATION.md.
924
+ const healingThreshold = 0.8 - relation.trust * 0.4
925
+ if ( desirability > healingThreshold && unresolvedCount > 0 ) {
926
+
927
+ this.episodicMemory.markResolved( this.episodicMemory.getUnresolvedMemories( userId, 1 )[ 0 ].id )
928
+
929
+ }
930
+
931
+ // Expressive suppression — a *display* layer only: the internal vector above is
932
+ // untouched, only the vector handed to linguistic modulation is gated down.
933
+ // Drive: conscientiousness (self-control) scaled by how stressed the system is —
934
+ // composed people suppress more under stress, not at baseline. A "Restraint"-tagged
935
+ // life event (e.g. a jail term, an active conflict) adds its own direct boost.
936
+ // Ego depletion: real suppression isn't free — recording it against DecisionFatigue
937
+ // (same call other decisions already use) means a turn spent holding back a strong
938
+ // felt state genuinely costs something, contributing toward shallowMode later on.
939
+ // Analysis paralysis: heavy analytical load (LogicEngine calls above, other
940
+ // decisions this turn) also erodes the capacity to suppress — "no energy left
941
+ // to filter" isn't only an emotional-depletion story (ExpressionDebt/character
942
+ // break above), it's also a plain cognitive-resource one.
943
+ let suppressionDrive = characterBreak
944
+ ? 0
945
+ : clamp01( this.personality.get( 'conscientiousness' ) * this.cortisolEngine.getLevel() + ( this._lifeEventSuppressionBoost ?? 0 ) ) * ( 1 - this.decisionFatigue.getLevel() )
946
+ this.decisionFatigue.recordDecision( suppressionDrive )
947
+ if ( this.decisionFatigue.isShallow() ) this.cortisolEngine.register( 0, true ) // sustained cognitive load reads as chronic ambient stress too
948
+ const expressedVector = this.expressiveSuppression.suppress( this.emotionSpace.vector, suppressionDrive )
949
+
950
+ // Chameleon effect — real lexical stats measured on THIS user's own input,
951
+ // blended with the AI's base style by real Attachment trust: a stranger's
952
+ // terse style doesn't rub off, a trusted user's does, gradually.
953
+ this.styleMimicry.observe( userId, input )
954
+ const styleTarget = this.styleMimicry.getBlendedTarget( userId, { avgWordLength: 5, avgSentenceLength: 12 }, relation.trust )
955
+
956
+ // Linguistic modulation (circadian energy trims response length / adds erratic noise)
957
+ const modulated = this.linguisticModulation.modulate( text, {
958
+ vector : expressedVector,
959
+ fatigueLevel : this.decisionFatigue.getLevel(),
960
+ styleTarget,
961
+ } )
962
+ if ( suppressionDrive > 0.5 ) modulated.styleTags.push( 'suppressed' )
963
+ if ( characterBreak ) modulated.styleTags.push( 'character_break' )
964
+ if ( circadian.lowEnergyWindow && Math.random() < circadian.erraticChance ) {
965
+
966
+ modulated.styleTags.push( 'drowsy' )
967
+ modulated.delayMs += 800
968
+
969
+ }
970
+
971
+ // Guilt engine + ego projection (retrospective self-check on what we're about to say).
972
+ // The counterfactual comparison — "how would a gentler response have landed?" — adds
973
+ // extra weight to guilt when the gap between what we said and what we could have said
974
+ // is large, an honest stand-in for counterfactual regret (NOT literal CFR — see
975
+ // CounterfactualComparison.js).
976
+ const selfCritique = await this.heuristic.analyze( 'selfCritique', { text: modulated.text } )
977
+ // Tribal loyalty applies to the AI's own guilt too: failing a user it's close
978
+ // to (real Attachment affinity, the same signal already driving TribalCategorization)
979
+ // costs more than failing a stranger.
980
+ const guilt = this.guiltEngine.evaluate( this.emotionSpace.vector, selfCritique.score ?? 0, 0.4, 1 + relation.affinity )
981
+ const projection = this.egoProjection.resolve( guilt, reputation.reaction )
982
+ const regret = this.counterfactualComparison.computeRegret( this.emotionSpace.vector.valence, Math.max( 0, appraisal.desirability ?? 0 ) )
983
+
984
+ if ( projection.active ) {
985
+
986
+ modulated.text = projection.blameText
987
+ this.emotionSpace.applySpike( projection.spike )
988
+ this.moodTracker.push( projection.spike )
989
+ this.guiltEngine.consumeApologyFlag() // the projection just replaced the apology guilt would have queued for next turn
990
+
991
+ }
992
+ else if ( guilt.guiltTriggered ) {
993
+
994
+ const regretScaledSpike = { valence: guilt.spike.valence * ( 1 + regret * 0.3 ), arousal: guilt.spike.arousal, weight: guilt.spike.weight }
995
+ this.emotionSpace.applySpike( regretScaledSpike )
996
+ this.moodTracker.push( regretScaledSpike )
997
+
998
+ }
999
+
1000
+ // Attachment + episodic memory. valenceDelta uses the full Prospect Theory value
1001
+ // function (diminishing sensitivity in both directions, not just a flat multiplier
1002
+ // on losses) — the richer version of loss aversion from CALIBRATION.md's item 21.
1003
+ this.attachment.update( userId, {
1004
+ valenceDelta : this.lossAversion.valueFunction( appraisal.desirability ?? 0 ),
1005
+ guiltTriggered : guilt.guiltTriggered,
1006
+ dissonanceTriggered : dissonance.triggered,
1007
+ betrayalDetected : ( ontologyFlagsThreat && ontologyMatches.some( m => m.concept === 'betrayal' ) ) || uncannyValley.suspicious,
1008
+ }, this.personality )
1009
+
1010
+ // Bayesian expectation update — fold this turn's actual outcome into next
1011
+ // time's prior for this user.
1012
+ this.bayesianExpectation.update( userId, desirability > 0 )
1013
+
1014
+ await safeStep( this.explainability, 'episodicMemory.store', async () => this.episodicMemory.store( {
1015
+ text : input,
1016
+ userId,
1017
+ emotionalSignature : { ...this.emotionSpace.vector },
1018
+ concepts : ontologyMatches.map( m => m.concept ),
1019
+ turnIndex : this.turnCounter,
1020
+ surprise : Math.max( Math.abs( rpe ), this._lifeEventSurprise ?? 0 ), // trauma consolidation: a surprising event (or an "Engram"-tagged life event) needs less raw magnitude to become permanent
1021
+ lifeEvent : lifeEvent ? { events: lifeEvent.events, impact: lifeEvent.impact, area: lifeEvent.area } : null,
1022
+ } ), null )
1023
+
1024
+ // Classical conditioning reinforcement: this turn's outcome reinforces the cues set last turn,
1025
+ // then this turn's own tokens become the cues for the next one.
1026
+ this.classicalConditioning.observeOutcome( desirability )
1027
+ this.classicalConditioning.setCues( tokens )
1028
+
1029
+ // Intuition logs this turn's real outcome for future k-NN hunches.
1030
+ this.intuition.observe( tokens, dissonance.triggered || behavioralInconsistency.triggered )
1031
+
1032
+ // Dominance EMA — the literal S_t = α·S_{t-1} + (1-α)·I_t smoothing, applied
1033
+ // after every spike this turn has landed.
1034
+ const smoothedDominance = this.dominanceEMA.update( this.emotionSpace.vector.dominance )
1035
+
1036
+ // Topic satiation — real rolling cosine-similarity fatigue (needs an embedding
1037
+ // backend; gracefully 0 without one, same fallback pattern as SemanticSimilarity).
1038
+ // Talking about the same thing turn after turn is a real drag on curiosity, not
1039
+ // just an absence of novelty. Sparse-gated: an embedding call is real inference
1040
+ // cost, so it's only spent when there's an actual reason to think this turn
1041
+ // continues a topic — a continuation keyword, or the topic was already running
1042
+ // hot last turn (residual) — not on every short, unrelated reply.
1043
+ const topicTrigger = this.triggerSentinel.check( 'topicSatiation', tokens, this._lastTopicFatigue ?? 0 )
1044
+ const topicSatiation = topicTrigger.active ? await this.topicSatiation.observe( input ) : { fatigue: 0, meanSimilarity: 0, gated: true }
1045
+ this._lastTopicFatigue = topicSatiation.fatigue
1046
+
1047
+ // Homeostasis: interacting satisfies socialization/curiosity. Drive — curiosity
1048
+ // refills more from a genuinely surprising turn (real |RPE|) than a predictable
1049
+ // one, the intrinsic-motivation direction: surprise is itself rewarding — but a
1050
+ // saturated topic drags against that refill instead of just failing to add to it.
1051
+ this.homeostasis.satisfy( 'socialization', 0.05 )
1052
+ this.homeostasis.satisfy( 'curiosity', 0.01 + Math.abs( rpe ) * 0.08 - topicSatiation.fatigue * 0.1 )
1053
+ if ( topicSatiation.fatigue > 0 ) this.emotionSpace.applySpike( { arousal: -topicSatiation.fatigue * 0.2, weight: 0.4 } )
1054
+
1055
+ // Explainability
1056
+ this.explainability.logDecision(
1057
+ modulated.text,
1058
+ `dominant=${this.emotionSpace.getDominantEmotion( neuroticism )} dissonance=${dissonance.triggered} behavioralInconsistency=${behavioralInconsistency.triggered} defense=${defenseDirective.active ? defenseDirective.mechanism : 'none'} ` +
1059
+ `shallow=${shallowMode} rpe=${rpe.toFixed( 2 )} novelty=${novelty.toFixed( 2 )} cortisol=${this.cortisolEngine.getLevel().toFixed( 2 )} tribe=${tribe} projection=${projection.active} ` +
1060
+ `fuzzyAcceptability=${acceptability.toFixed( 2 )} anxiety=${anxiety.toFixed( 2 )} regret=${regret.toFixed( 2 )} concepts=${ontologyMatches.map( m => m.concept ).join( ',' ) || 'none'}`,
1061
+ )
1062
+
1063
+ const remainingUnresolved = this.episodicMemory.getUnresolvedMemories( userId, 1 )[ 0 ] ?? null
1064
+ const recentWound = remainingUnresolved ? {
1065
+ text : remainingUnresolved.text?.slice( 0, 80 ),
1066
+ concepts : remainingUnresolved.concepts,
1067
+ turnsAgo : remainingUnresolved.turnIndex !== null ? this.turnCounter - remainingUnresolved.turnIndex : null,
1068
+ } : null
1069
+
1070
+ const emotionalState = this.getEmotionalState()
1071
+ const systemPrompt = this.contextAdapter.buildSystemPrompt( emotionalState, {
1072
+ defenseDirective,
1073
+ pendingApology : shouldApologize,
1074
+ projectionText : projection.active ? projection.blameText : null,
1075
+ selfAwareness : this.selfModel.getDominant(),
1076
+ recentWound,
1077
+ agreement,
1078
+ debtReleased,
1079
+ stubborn : logicVerdict.strategy === 'disagree' && stubbornInvestment >= 3 ? { investment: stubbornInvestment } : null,
1080
+ remReport : this._lastRemReport,
1081
+ } )
1082
+
1083
+ // Restraint / Focus — real logit-bias penalty map (usable verbatim by a host
1084
+ // calling an OpenAI-compatible API's own logit_bias, after mapping these
1085
+ // words through THEIR tokenizer) and a real softmax attention weighting over
1086
+ // this turn's input tokens, both derived from the same suppressionDrive/
1087
+ // lexicon already computed above — metadata for a host to use, not something
1088
+ // Totemheart applies to its own output itself.
1089
+ // Confidence-based routing between the cold LogicEngine read and the affective
1090
+ // logit bias: `logicRelevance` is the real fraction of this turn's evaluated
1091
+ // propositions that actually touched a CoreBelief (non-null), already computed
1092
+ // above — a direct, honest proxy for "does this turn have any emotional stake
1093
+ // at all", not a fabricated factual/coding-instruction detector. When nothing
1094
+ // here touches anything the AI has stakes in (a purely logical/neutral turn),
1095
+ // the affective suppression bias applied to logits scales toward zero instead
1096
+ // of applying at full strength regardless of what the turn was actually about.
1097
+ const logicRelevance = logicPropositions.length > 0
1098
+ ? logicPropositions.filter( p => p.consistent !== null ).length / logicPropositions.length
1099
+ : 1
1100
+ const logitBias = this.logitBiasBuilder.build( suppressionDrive * logicRelevance )
1101
+ const attentionWeights = this.attentionFocus.computeWeights( input )
1102
+
1103
+ // Suggested sampling temperature — host-facing metadata only, same status as
1104
+ // logitBias/systemPrompt: Totemheart never calls an LLM to generate the final
1105
+ // reply itself (that's the host's job), so it can't set a real sampling
1106
+ // temperature. What it CAN do honestly is expose decision-fatigue level as a
1107
+ // real number a host may optionally feed into their own LLM call's temperature
1108
+ // parameter — analysis paralysis reads as "less precise, more scattered" in a
1109
+ // human, which is what raising an LLM's temperature also produces.
1110
+ const suggestedTemperature = Number( ( 1 + this.decisionFatigue.getLevel() * 0.6 ).toFixed( 2 ) )
1111
+
1112
+ return {
1113
+ text : modulated.text,
1114
+ delayMs : modulated.delayMs,
1115
+ styleTags : modulated.styleTags,
1116
+ emotionalState,
1117
+ systemPrompt,
1118
+ logitBias,
1119
+ suggestedTemperature,
1120
+ attentionWeights,
1121
+ structuredContext : this.contextAdapter.buildStructuredContext( emotionalState ),
1122
+ debug : {
1123
+ appraisal, dissonance, behavioralInconsistency, ontologyMatches, mentalState, tomEstimate,
1124
+ defenseDirective, hedonicMultiplier, shallowMode, rpe, novelty, tribe, reputation, projection,
1125
+ circadian, priorExpectation, anxiety, acceptability, fairness, regret, gratitude,
1126
+ interoception : { narrowing, conductance, regulatoryCapacity, flush },
1127
+ logic : { propositions: logicPropositions, verdict: logicVerdict, relevance: logicRelevance, stubbornInvestment, stubbornResistance },
1128
+ egoConfidence, semanticSimilarity, hunch, smoothedDominance,
1129
+ lifeEvent, agreement, debtReleased, characterBreak, referenceShift,
1130
+ visualProsody, topicSatiation, chronicPull, uncannyValley, sarcasm, refractory, styleTarget,
1131
+ activeMechanisms, cascadeBoost, remReport: this._lastRemReport, reactivation,
1132
+ },
1133
+ }
1134
+
1135
+ }
1136
+
1137
+ /**
1138
+ * Build a ready-to-inject system prompt from the *current* state without
1139
+ * processing a new turn — useful to seed the very first call to your LLM,
1140
+ * or to refresh context on a tick-driven mood shift (e.g. after idle()).
1141
+ * Works with any provider: Anthropic, OpenAI, Ollama, or a raw string.
1142
+ */
1143
+ getSystemPrompt( { userId = null } = {} ) {
1144
+
1145
+ const wound = userId ? this.episodicMemory.getUnresolvedMemories( userId, 1 )[ 0 ] : null
1146
+ const recentWound = wound ? {
1147
+ text : wound.text?.slice( 0, 80 ),
1148
+ concepts : wound.concepts,
1149
+ turnsAgo : wound.turnIndex !== null ? this.turnCounter - wound.turnIndex : null,
1150
+ } : null
1151
+
1152
+ return this.contextAdapter.buildSystemPrompt( this.getEmotionalState(), {
1153
+ pendingApology : this.guiltEngine.pendingApology,
1154
+ selfAwareness : this.selfModel.getDominant(),
1155
+ recentWound,
1156
+ } )
1157
+
1158
+ }
1159
+
1160
+ /**
1161
+ * Directives for an external renderer (avatar, TTS, robot) to actually
1162
+ * produce facial expression / vocal prosody / posture / instinctive
1163
+ * action-tendency — Totemheart computes what SHOULD be expressed, it has
1164
+ * no face, voice, or body to express it with. See CALIBRATION.md.
1165
+ */
1166
+ getExpressionDirectives() {
1167
+
1168
+ const neuroticism = this.personality.get( 'neuroticism' )
1169
+ const dominant = this.emotionSpace.getDominantEmotion( neuroticism )
1170
+ const blendWeight = this.emotionSpace.getBlend( 1, neuroticism )[ dominant ] ?? 1
1171
+
1172
+ return {
1173
+ facial : this.expressionDirectives.getFacialDirectives( dominant, blendWeight ),
1174
+ prosody : this.expressionDirectives.getProsodyDirectives( this.emotionSpace.vector ),
1175
+ posture : this.expressionDirectives.getPostureDirectives( this.emotionSpace.vector ),
1176
+ actionTendency : this.expressionDirectives.getActionTendency( this.emotionSpace.vector ),
1177
+ }
1178
+
1179
+ }
1180
+
1181
+ /** Advance all time-based mechanics by `dt` ticks (host decides the cadence — no forced timers). */
1182
+ tick( dt = 1 ) {
1183
+
1184
+ const mood = this.moodTracker.getMood()
1185
+
1186
+ const valenceBefore = this.emotionSpace.vector.valence
1187
+ this.decayEngine.apply( this.emotionSpace, mood, this.personality, dt )
1188
+ this.controllabilityEstimate.observeOutcome( this.emotionSpace.getDominantEmotion(), valenceBefore, this.emotionSpace.vector.valence )
1189
+
1190
+ this.homeostasis.tick( dt, this.personality )
1191
+ this.forgettingCurve.tick( this.episodicMemory, dt )
1192
+ this.decisionFatigue.decay( dt )
1193
+ this.cognitiveDissonance.decay( dt )
1194
+ this.cortisolEngine.decay( dt )
1195
+ this.reputationEngine.regenerate( dt )
1196
+ this.selfModel.decay( dt )
1197
+ this.sensitization.decay( dt )
1198
+ this.ruminationChain.decayBias( dt )
1199
+ this.expressionDebt.decay( dt )
1200
+
1201
+ const alerts = this.homeostasis.getAlerts()
1202
+ for ( const alert of alerts ) {
1203
+
1204
+ this.emotionSpace.applySpike( { valence: -0.15, arousal: 0.2, weight: 1 } )
1205
+ this.moodTracker.push( { valence: -0.15, arousal: 0.2 } )
1206
+ this.explainability.logDecision( 'homeostasis_alert', `${alert.need} at ${alert.value.toFixed( 2 )} (urgency ${alert.urgency.toFixed( 2 )})` )
1207
+
1208
+ }
1209
+
1210
+ // Allostasis reset — the cubic decay above already pulls hard on any single
1211
+ // extreme reading, but a real feedback loop (rumination re-triggering itself,
1212
+ // a stale WornPathCache entry re-applying the same appraisal) can still keep
1213
+ // the vector pinned in an extreme quadrant tick after tick despite that pull.
1214
+ // After ALLOSTASIS_STUCK_TICKS consecutive ticks stuck there, force a reset:
1215
+ // purge the memoized appraisal cache (stop reusing whatever stale reading is
1216
+ // feeding the loop) and reset RuminationChain's mutable state (its Markov
1217
+ // transition matrix has no other stateful part to reset).
1218
+ const { valence: vAfter, arousal: aAfter } = this.emotionSpace.vector
1219
+ const inExtremeQuadrant = Math.abs( vAfter ) > ALLOSTASIS_VALENCE_THRESHOLD && Math.abs( aAfter ) > ALLOSTASIS_AROUSAL_THRESHOLD
1220
+ this.allostasisStuckTicks = inExtremeQuadrant ? this.allostasisStuckTicks + 1 : 0
1221
+
1222
+ if ( this.allostasisStuckTicks >= ALLOSTASIS_STUCK_TICKS ) {
1223
+
1224
+ this.wornPathCache.clear()
1225
+ this.ruminationChain.state = 'neutral'
1226
+ this.ruminationChain.negativeBias = 0
1227
+ this.explainability.logDecision(
1228
+ 'allostasis_reset',
1229
+ `stuck in extreme mood quadrant (valence=${vAfter.toFixed( 2 )}, arousal=${aAfter.toFixed( 2 )}) for ${this.allostasisStuckTicks} ticks — purged WornPathCache, reset RuminationChain`,
1230
+ )
1231
+ this.allostasisStuckTicks = 0
1232
+
1233
+ }
1234
+
1235
+ }
1236
+
1237
+ /** Convenience helper for hosts that want a real timer instead of manual tick(). */
1238
+ startClock( intervalMs = 5000 ) {
1239
+
1240
+ this.stopClock()
1241
+ this._clockHandle = setInterval( () => this.tick( 1 ), intervalMs )
1242
+ return this._clockHandle
1243
+
1244
+ }
1245
+
1246
+ stopClock() {
1247
+
1248
+ if ( this._clockHandle ) clearInterval( this._clockHandle )
1249
+ this._clockHandle = null
1250
+
1251
+ }
1252
+
1253
+ async idle( dt = 1 ) {
1254
+
1255
+ // Rumination: a real Markov chain that can get "stuck" in a negative attractor,
1256
+ // distinct from IdleProcessing's simple memory resampling below.
1257
+ this.ruminationChain.sync( this.moodTracker.getMood().valence )
1258
+ const rumination = this.ruminationChain.step()
1259
+ if ( rumination.spike.valence !== 0 || rumination.spike.arousal !== 0 ) {
1260
+
1261
+ this.emotionSpace.applySpike( { ...rumination.spike, weight: 1 } )
1262
+ this.moodTracker.push( rumination.spike )
1263
+
1264
+ }
1265
+
1266
+ const idleResult = await this.idleProcessing.runIdleCycle( {
1267
+ episodicMemory : this.episodicMemory,
1268
+ moodTracker : this.moodTracker,
1269
+ homeostasis : this.homeostasis,
1270
+ decisionFatigue : this.decisionFatigue,
1271
+ cortisolEngine : this.cortisolEngine,
1272
+ }, dt )
1273
+
1274
+ return { ...idleResult, ruminationState: rumination.state }
1275
+
1276
+ }
1277
+
1278
+ /**
1279
+ * Serializes the full persistent state (not just the current turn's
1280
+ * output) so a host can store it between sessions — "ayer me hirieron"
1281
+ * can keep affecting "hoy" even across a process restart or a different
1282
+ * server handling the next request.
1283
+ */
1284
+ toJSON() {
1285
+
1286
+ return {
1287
+ version : VERSION,
1288
+ personality : this.personality.traits,
1289
+ emotionVector : this.emotionSpace.vector,
1290
+ moodWindow : this.moodTracker.window,
1291
+ homeostasisNeeds : this.homeostasis.needs,
1292
+ cognitiveStress : this.cognitiveDissonance.stress,
1293
+ decisionFatigue : this.decisionFatigue.load,
1294
+ cortisolLevel : this.cortisolEngine.level,
1295
+ egoHealth : this.reputationEngine.egoHealth,
1296
+ dopamineExpectedValue : this.dopaminergicEngine.expectedValue,
1297
+ hedonicSeen : [ ...this.hedonicAdaptation.seen.entries() ],
1298
+ attachmentRelations : [ ...this.attachment.relations.entries() ],
1299
+ theoryOfMindModels : [ ...this.theoryOfMind.models.entries() ].map( ( [ id, m ] ) => [ id, { ...m, beliefs: [ ...m.beliefs.entries() ] } ] ),
1300
+ episodicMemories : this.episodicMemory.adapter ? null : this.episodicMemory.memories,
1301
+ anchoringBias : { anchor: this.anchoringBias.anchor, turn: this.anchoringBias.turn },
1302
+ classicalConditioningAssociations : [ ...this.classicalConditioning.associations.entries() ],
1303
+ coreBeliefs : this.coreBeliefs.getAll(),
1304
+ sensitizationLevel : this.sensitization.level,
1305
+ }
1306
+
1307
+ }
1308
+
1309
+ /** Rehydrates state produced by toJSON() into this (already-constructed) instance. */
1310
+ restoreState( data = {} ) {
1311
+
1312
+ if ( data.personality ) Object.assign( this.personality.traits, data.personality )
1313
+ if ( data.emotionVector ) this.emotionSpace.setVector( data.emotionVector.valence, data.emotionVector.arousal, data.emotionVector.dominance )
1314
+ if ( data.moodWindow ) this.moodTracker.window = data.moodWindow
1315
+ if ( data.homeostasisNeeds ) Object.assign( this.homeostasis.needs, data.homeostasisNeeds )
1316
+ if ( typeof data.cognitiveStress === 'number' ) this.cognitiveDissonance.stress = data.cognitiveStress
1317
+ if ( typeof data.decisionFatigue === 'number' ) this.decisionFatigue.load = data.decisionFatigue
1318
+ if ( typeof data.cortisolLevel === 'number' ) this.cortisolEngine.level = data.cortisolLevel
1319
+ if ( typeof data.egoHealth === 'number' ) this.reputationEngine.egoHealth = data.egoHealth
1320
+ if ( typeof data.dopamineExpectedValue === 'number' ) this.dopaminergicEngine.expectedValue = data.dopamineExpectedValue
1321
+ if ( data.hedonicSeen ) this.hedonicAdaptation.seen = new Map( data.hedonicSeen )
1322
+ if ( data.attachmentRelations ) this.attachment.relations = new Map( data.attachmentRelations )
1323
+ if ( data.theoryOfMindModels ) {
1324
+
1325
+ this.theoryOfMind.models = new Map( data.theoryOfMindModels.map( ( [ id, m ] ) => [ id, { ...m, beliefs: new Map( m.beliefs ) } ] ) )
1326
+
1327
+ }
1328
+ if ( data.episodicMemories && !this.episodicMemory.adapter ) this.episodicMemory.memories = data.episodicMemories
1329
+ if ( data.anchoringBias ) Object.assign( this.anchoringBias, data.anchoringBias )
1330
+ if ( data.classicalConditioningAssociations ) this.classicalConditioning.associations = new Map( data.classicalConditioningAssociations )
1331
+ if ( data.coreBeliefs ) for ( const b of data.coreBeliefs ) if ( !this.coreBeliefs.get( b.topic ) ) this.coreBeliefs.add( b.topic, b.statement, b.polarity )
1332
+ if ( typeof data.sensitizationLevel === 'number' ) this.sensitization.level = data.sensitizationLevel
1333
+
1334
+ }
1335
+
1336
+ getEmotionalState() {
1337
+
1338
+ const neuroticism = this.personality.get( 'neuroticism' )
1339
+ return {
1340
+ vector : { ...this.emotionSpace.vector },
1341
+ blend : this.emotionSpace.getBlend( 3, neuroticism ),
1342
+ dominantEmotion : this.emotionSpace.getDominantEmotion( neuroticism ),
1343
+ mood : this.moodTracker.getMood(),
1344
+ moodLabel : this.moodTracker.getMoodLabel( neuroticism ),
1345
+ cognitiveStress : this.cognitiveDissonance.getStress(),
1346
+ fatigue : this.decisionFatigue.getLevel(),
1347
+ needs : this.homeostasis.getState(),
1348
+ cortisol : this.cortisolEngine.getLevel(),
1349
+ egoHealth : this.reputationEngine.getEgoHealth(),
1350
+ circadianEnergy : this.circadianRhythm.getEnergyLevel(),
1351
+ dopamineExpectation : this.dopaminergicEngine.getExpectedValue(),
1352
+ sensitization : this.sensitization.level,
1353
+ // Purely internal interoceptive signals — no sensor, no body, no rendering.
1354
+ // See InteroceptiveSignals.js / CALIBRATION.md.
1355
+ interoception : {
1356
+ flush : this.interoceptiveSignals.flushLevel,
1357
+ lastConductance : this.interoceptiveSignals.stressHistory.at( -1 ) ?? null,
1358
+ },
1359
+ }
1360
+
1361
+ }
1362
+
1363
+ }