totemheart 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,11 @@
1
1
  import { EMOTION_COORDS, SURVIVAL_EMOTIONS } from '../core/EmotionSpace.js'
2
2
 
3
+ function clamp01( v ) {
4
+
5
+ return Math.max( 0, Math.min( 1, v ) )
6
+
7
+ }
8
+
3
9
  function intensity( vector, coords ) {
4
10
 
5
11
  const d = Math.hypot( vector.valence - coords.valence, vector.arousal - coords.arousal )
@@ -8,21 +14,112 @@ function intensity( vector, coords ) {
8
14
  }
9
15
 
10
16
  /**
11
- * Pure interrupt module. When a survival emotion (fear/anger) crosses the
12
- * threshold, this bypasses the normal pipeline entirely and forces an
13
- * instinctive, non-analytical output.
17
+ * Interrupt module: how far a survival emotion (fear/anger) has crossed
18
+ * threshold decides whether this stays a bias on normal processing or takes
19
+ * it over entirely. Three real, graded tiers instead of one binary flag:
20
+ *
21
+ * 'alert' — above the base threshold, below the partial one: a real
22
+ * signal downstream code can react to (e.g. raise
23
+ * suppressionDrive), the normal pipeline still runs.
24
+ * 'partial' — deep enough that rational processing genuinely degrades
25
+ * (shallow mode forced), but text is still generated normally.
26
+ * 'full' — the original behavior: bypass the pipeline, force the
27
+ * instinctive output.
28
+ *
29
+ * Two real dynamics layer on top:
30
+ *
31
+ * Kindling: repeated activation to the SAME stimulus TYPE (a concept tag
32
+ * like 'threat'/'betrayal'/'criticism', supplied by the caller) lowers the
33
+ * threshold further each time it recurs — named after kindling, the
34
+ * observation that repeated sub-threshold electrical/chemical stimulation of
35
+ * the amygdala progressively lowers the seizure threshold (Goddard, G. V.
36
+ * (1967), "Development of epileptic seizures through brain stimulation at
37
+ * low intensity", Nature, 214, 1020-1021). Used here as a metaphorical
38
+ * borrowing of the qualitative "repeated activation of the SAME pathway
39
+ * lowers its own threshold" shape, not a claim this reproduces real synaptic
40
+ * kindling — distinct from Sensitization.js's generic any-negative-valence
41
+ * accumulator, which doesn't care about stimulus type.
42
+ *
43
+ * Hangover: after ANY hijack tier fires, a measurable post-hijack window
44
+ * where DecisionFatigue/ExpressionDebt accumulate faster — real "shaken for
45
+ * a while afterward" cost, own engineering, no citation.
14
46
  */
15
47
  export class AmygdalaHijack {
16
48
 
17
- check( emotionSpace, threshold = 0.95 ) {
49
+ constructor() {
50
+
51
+ this.kindling = new Map() // concept -> accumulated kindling level (0..1)
52
+ this.hangoverUntil = 0
53
+ this.hangoverIntensity = 0
54
+
55
+ }
56
+
57
+ /** Repeated exposure to the same concept-tagged stimulus lowers this concept's own future threshold. */
58
+ observeStimulus( concept ) {
59
+
60
+ if ( !concept ) return
61
+ const current = this.kindling.get( concept ) ?? 0
62
+ this.kindling.set( concept, clamp01( current + 0.15 ) )
63
+
64
+ }
65
+
66
+ decayKindling( dt, lambda = 0.03 ) {
67
+
68
+ for ( const [ concept, level ] of this.kindling ) {
69
+
70
+ const decayed = Math.max( 0, level - lambda * dt )
71
+ if ( decayed <= 0 ) this.kindling.delete( concept )
72
+ else this.kindling.set( concept, decayed )
73
+
74
+ }
75
+
76
+ }
77
+
78
+ getKindlingDiscount( concepts = [] ) {
79
+
80
+ const level = Math.max( 0, ...concepts.map( c => this.kindling.get( c ) ?? 0 ), 0 )
81
+ return level * 0.15 // up to 0.15 shaved off the threshold at full kindling on a matched concept — own tuning
82
+
83
+ }
84
+
85
+ isInHangover( now = Date.now() ) {
86
+
87
+ return now < this.hangoverUntil
88
+
89
+ }
90
+
91
+ /** Extra DecisionFatigue/ExpressionDebt-facing load while the hangover window is open. */
92
+ getHangoverLoad( now = Date.now() ) {
93
+
94
+ return this.isInHangover( now ) ? this.hangoverIntensity : 0
95
+
96
+ }
97
+
98
+ check( emotionSpace, threshold = 0.95, { concepts = [], now = Date.now() } = {} ) {
99
+
100
+ const effectiveThreshold = clamp01( threshold - this.getKindlingDiscount( concepts ) )
101
+ const partialThreshold = effectiveThreshold * 0.75
102
+ const alertThreshold = effectiveThreshold * 0.5
18
103
 
19
104
  for ( const emotion of SURVIVAL_EMOTIONS ) {
20
105
 
21
106
  const level = intensity( emotionSpace.vector, EMOTION_COORDS[ emotion ] )
22
- if ( level >= threshold ) return { active: true, emotion, intensity: level }
107
+ if ( level < alertThreshold ) continue
108
+
109
+ const tier = level >= effectiveThreshold ? 'full' : level >= partialThreshold ? 'partial' : 'alert'
110
+
111
+ if ( tier === 'full' || tier === 'partial' ) {
112
+
113
+ this.hangoverUntil = now + 1000 * 60 * 5 // 5 real minutes, own tuning
114
+ this.hangoverIntensity = tier === 'full' ? 0.5 : 0.25
115
+ for ( const concept of concepts ) this.observeStimulus( concept )
116
+
117
+ }
118
+
119
+ return { active: tier === 'full', tier, emotion, intensity: level, threshold: effectiveThreshold }
23
120
 
24
121
  }
25
- return { active: false }
122
+ return { active: false, tier: 'none' }
26
123
 
27
124
  }
28
125
 
@@ -13,19 +13,48 @@ function weightedPick( weights ) {
13
13
 
14
14
  }
15
15
 
16
+ // Vaillant, G. E. (1977), "Adaptation to Life", Little, Brown — a 3-tier
17
+ // hierarchy from least to most adaptive. Which tier a defense belongs to is
18
+ // straight from that source; treating egoHealth/cortisol as the real signal
19
+ // that shifts weight toward the immature end is our own engineering, not a
20
+ // computational model Vaillant himself specified. See CALIBRATION.md.
21
+ const TIER = {
22
+ projection : 'immature',
23
+ evasion : 'immature',
24
+ rationalization : 'neurotic',
25
+ sarcasm : 'neurotic',
26
+ humor : 'mature',
27
+ }
28
+
16
29
  /**
17
30
  * Fires when cognitive stress crosses a critical threshold. Returns a
18
31
  * behaviorDirective the text generator / linguistic modulation layer must
19
- * act on: evasion (change subject), projection (blame the user), sarcasm.
32
+ * act on. Which mechanism fires is personality-weighted (Personality.
33
+ * getDefenseWeights()) AND state-weighted: low ego health / high cortisol
34
+ * pulls the pick toward the immature end of Vaillant's hierarchy (real
35
+ * regression-under-stress direction, own tuning of the magnitude), high ego
36
+ * health and low cortisol let mature defenses (humor) compete.
20
37
  */
21
38
  export class DefenseMechanisms {
22
39
 
23
- check( stress, personality, threshold = 0.6 ) {
40
+ check( stress, personality, threshold = 0.6, { egoHealth = 0.7, cortisol = 0 } = {} ) {
24
41
 
25
42
  if ( stress < threshold ) return { active: false }
26
43
 
27
- const mechanism = weightedPick( personality.getDefenseWeights() )
28
- return { active: true, mechanism, stress }
44
+ const base = personality.getDefenseWeights()
45
+ const regression = ( 1 - egoHealth ) * 0.6 + cortisol * 0.4 // 0..1, how hard stress is pulling toward the immature end
46
+ const reshaped = Object.fromEntries( Object.entries( base ).map( ( [ name, w ] ) => {
47
+
48
+ const tier = TIER[ name ]
49
+ const multiplier = tier === 'immature' ? 1 + regression * 1.5
50
+ : tier === 'mature' ? Math.max( 0.1, 1 - regression * 1.2 )
51
+ : 1 // neurotic tier stays roughly flat, the "default" register
52
+ return [ name, w * multiplier ]
53
+
54
+ } ) )
55
+
56
+ const mechanism = weightedPick( reshaped )
57
+ return { active: true, mechanism, tier: TIER[ mechanism ], stress }
29
58
 
30
59
  }
31
60
 
@@ -17,6 +17,25 @@ function clamp01( v ) {
17
17
  * turn's actual bottleneck (an active threat/crisis) instead of always
18
18
  * running the full fixed pipeline. Engineering design, no citation.
19
19
  */
20
+ // Relative computational-cost estimate per optional stage (own engineering
21
+ // ranking based on what each one actually does — an ontology concept-graph
22
+ // pass and a full appraisal cross-check are real multi-step work, a self-
23
+ // model reinforcement is one map write — not measured wall-clock profiling).
24
+ const STAGE_COST = {
25
+ runOntology : 0.8,
26
+ runSelfModelUpdate : 0.15,
27
+ runBehavioralInconsistency : 0.35,
28
+ }
29
+
30
+ // Base instability ceiling per stage — same cutoffs the original fixed-
31
+ // threshold version used, kept as the anchor `gate()` computes a real,
32
+ // per-turn-adjusted budget around instead of a flat constant.
33
+ const BASE_THRESHOLD = {
34
+ runOntology : 0.85,
35
+ runSelfModelUpdate : 0.9,
36
+ runBehavioralInconsistency : 0.75,
37
+ }
38
+
20
39
  export class LoadScheduler {
21
40
 
22
41
  /** instability: 0 = calm, 1 = maximally overloaded. */
@@ -26,14 +45,33 @@ export class LoadScheduler {
26
45
 
27
46
  }
28
47
 
29
- /** Which optional stages to run this turn, given the instability reading. */
30
- gate( instability ) {
48
+ /**
49
+ * Real per-stage resource allocation: each stage's fixed instability
50
+ * ceiling shifts up when this turn is genuinely novel (worth spending
51
+ * more on — NoveltyDetector's KL divergence, "urgencia emocional +
52
+ * novedad" as the two real signals worth budgeting on) and down by its
53
+ * own relative cost (a pricier stage gets skipped a bit sooner under
54
+ * load than a cheap one would). A stage still runs whenever
55
+ * instability < its adjusted threshold — same comparison shape the
56
+ * original fixed-threshold gate used, now genuinely turn-adjusted
57
+ * instead of a flat constant.
58
+ */
59
+ getAdjustedThreshold( stage, { novelty = 0 } = {} ) {
60
+
61
+ const base = BASE_THRESHOLD[ stage ] ?? 0.8
62
+ const cost = STAGE_COST[ stage ] ?? 0.3
63
+ return clamp01( base + Math.min( novelty, 1 ) * 0.1 - cost * 0.1 )
64
+
65
+ }
66
+
67
+ /** Which optional stages to run this turn, given the instability reading (and optionally novelty, for the adjusted budget). */
68
+ gate( instability, { novelty = 0 } = {} ) {
31
69
 
32
70
  return {
33
- runOntology : instability < 0.85,
71
+ runOntology : instability < this.getAdjustedThreshold( 'runOntology', { novelty } ),
34
72
  runSituationalContext : true, // cheap, and precisely what's needed to detect instability in the first place
35
- runSelfModelUpdate : instability < 0.9,
36
- runBehavioralInconsistency : instability < 0.75,
73
+ runSelfModelUpdate : instability < this.getAdjustedThreshold( 'runSelfModelUpdate', { novelty } ),
74
+ runBehavioralInconsistency : instability < this.getAdjustedThreshold( 'runBehavioralInconsistency', { novelty } ),
37
75
  }
38
76
 
39
77
  }
@@ -35,11 +35,19 @@ export class RemConsolidation {
35
35
 
36
36
  }
37
37
 
38
- sweep( { episodicMemory, hebbianPlasticity, cortisolEngine, expressionDebt, sensitization, emotionSpace, moodTracker, decayEngine, personality }, now = Date.now() ) {
38
+ sweep( { episodicMemory, hebbianPlasticity, cortisolEngine, expressionDebt, sensitization, emotionSpace, moodTracker, decayEngine, personality, circadianRhythm }, now = Date.now() ) {
39
39
 
40
40
  const elapsedMs = this.lastTurnAt !== null ? now - this.lastTurnAt : 0
41
41
  const elapsedHours = elapsedMs / ( 1000 * 60 * 60 )
42
42
 
43
+ // Sleep debt makes this sweep cool memories MORE aggressively — the real
44
+ // idea that a longer-overdue rest, once it finally happens, does more
45
+ // consolidation work per sweep. `circadianRhythm` is optional so callers
46
+ // that don't wire it (or existing tests) get the original lambdaRem back
47
+ // exactly. Own tuning, no citation for the specific scaling.
48
+ const sleepDebt = circadianRhythm?.sleepDebt ?? 0
49
+ const effectiveLambda = this.lambdaRem * ( 1 + sleepDebt * 0.5 )
50
+
43
51
  // Episodic replay: cool peak arousal on high-magnitude memories, real-cite-free
44
52
  // exponential dampening, valence/concepts left exactly as stored.
45
53
  let cooled = 0
@@ -48,7 +56,7 @@ export class RemConsolidation {
48
56
  const arousal = m.emotionalSignature?.arousal ?? 0
49
57
  if ( Math.abs( arousal ) > this.arousalCoolingThreshold ) {
50
58
 
51
- m.emotionalSignature.arousal = arousal * Math.exp( -this.lambdaRem )
59
+ m.emotionalSignature.arousal = arousal * Math.exp( -effectiveLambda )
52
60
  cooled++
53
61
 
54
62
  }
@@ -56,6 +64,10 @@ export class RemConsolidation {
56
64
 
57
65
  }
58
66
 
67
+ // A real sweep IS the "sleep" event that pays sleep debt back down —
68
+ // the only place it's allowed to decrease (see CircadianRhythm.js).
69
+ circadianRhythm?.payDownSleepDebt( 0.3 + sleepDebt * 0.2 )
70
+
59
71
  // Synaptic pruning — extra decay on associations that went stale during the gap.
60
72
  if ( hebbianPlasticity ) hebbianPlasticity.decayOnly( Math.min( elapsedHours * 0.05, 0.9 ) )
61
73
 
@@ -40,15 +40,21 @@ export class DecayEngine {
40
40
  apply( emotionSpace, mood, personality, dt, { cubicK = 0.15 } = {} ) {
41
41
 
42
42
  const { valence, arousal } = emotionSpace.vector
43
- const lambdaValence = personality.getEmotionalRecoveryRate( valence - mood.valence )
44
- const lambdaArousal = personality.getEmotionalRecoveryRate( arousal - mood.arousal )
43
+ // Hysteresis coupling: EmotionSpace.getRecoveryResistance() reads <1 while an
44
+ // axis is past the "extreme" threshold, so both the exponential and cubic
45
+ // pull-back rates slow down there — leaving an extreme mood state takes real,
46
+ // measurably longer than entering one did, not just resisting the next spike.
47
+ const valenceResistance = emotionSpace.getRecoveryResistance( 'valence' )
48
+ const arousalResistance = emotionSpace.getRecoveryResistance( 'arousal' )
49
+ const lambdaValence = personality.getEmotionalRecoveryRate( valence - mood.valence ) * valenceResistance
50
+ const lambdaArousal = personality.getEmotionalRecoveryRate( arousal - mood.arousal ) * arousalResistance
45
51
 
46
52
  const expValence = decayTowards( valence, mood.valence, lambdaValence, dt )
47
53
  const expArousal = decayTowards( arousal, mood.arousal, lambdaArousal, dt )
48
54
 
49
55
  emotionSpace.setVector(
50
- cubicDecayTowards( expValence, mood.valence, cubicK, dt ),
51
- cubicDecayTowards( expArousal, mood.arousal, cubicK, dt ),
56
+ cubicDecayTowards( expValence, mood.valence, cubicK * valenceResistance, dt ),
57
+ cubicDecayTowards( expArousal, mood.arousal, cubicK * arousalResistance, dt ),
52
58
  )
53
59
 
54
60
  }
@@ -41,6 +41,26 @@ function clamp( v, min = -1, max = 1 ) {
41
41
 
42
42
  }
43
43
 
44
+ // Emotional inertia: how much of the current velocity (EMA of the recent
45
+ // per-spike delta) carries forward into the next spike's push, a discrete
46
+ // momentum term (v_t += m * velocity_{t-1}) analogous to momentum in
47
+ // gradient descent — an already-shifting state keeps drifting a bit in that
48
+ // direction instead of every spike being evaluated as if from a standing
49
+ // start. Own tuning, no citation.
50
+ const MOMENTUM_COEFF = 0.25
51
+ // EMA rate for updating velocity itself from the realized delta — smoothed,
52
+ // not a raw frame-to-frame difference, so one big spike doesn't inject a
53
+ // runaway momentum term into the next one.
54
+ const VELOCITY_EMA = 0.4
55
+ // Hysteresis: past this |value| the state counts as "extreme". A spike that
56
+ // would pull an extreme axis back toward neutral is damped (harder to
57
+ // leave); a spike pushing further in the same direction is not (easy to
58
+ // enter/reinforce) — the qualitative asymmetric-loop shape hysteresis has in
59
+ // magnetic/mechanical systems, applied here to the felt-intensity axes, own
60
+ // tuning, not a reproduction of any specific hysteresis model.
61
+ const HYSTERESIS_THRESHOLD = 0.75
62
+ const HYSTERESIS_DAMPING = 0.85
63
+
44
64
  function distance( a, b ) {
45
65
 
46
66
  return Math.hypot( a.valence - b.valence, a.arousal - b.arousal, ( a.dominance ?? 0 ) - ( b.dominance ?? 0 ) )
@@ -103,7 +123,8 @@ export class EmotionSpace {
103
123
 
104
124
  constructor() {
105
125
 
106
- this.vector = { valence: 0, arousal: 0, dominance: 0 }
126
+ this.vector = { valence: 0, arousal: 0, dominance: 0 }
127
+ this.velocity = { valence: 0, arousal: 0, dominance: 0 }
107
128
 
108
129
  }
109
130
 
@@ -113,14 +134,48 @@ export class EmotionSpace {
113
134
 
114
135
  }
115
136
 
116
- /** Additively apply a weighted spike (from MicroEmotions) to the current vector. */
137
+ /** >0.6 magnitude counts as "extreme" — multiplier a caller (DecayEngine) can apply to slow recovery from there. */
138
+ getRecoveryResistance( axis ) {
139
+
140
+ return Math.abs( this.vector[ axis ] ?? 0 ) >= HYSTERESIS_THRESHOLD ? HYSTERESIS_DAMPING : 1
141
+
142
+ }
143
+
144
+ /** Damps a push that would pull an already-extreme axis back toward neutral; leaves a push that reinforces it alone. */
145
+ #hysteresisMultiplier( currentValue, push ) {
146
+
147
+ if ( Math.abs( currentValue ) < HYSTERESIS_THRESHOLD || push === 0 ) return 1
148
+ const reducing = Math.sign( push ) !== Math.sign( currentValue )
149
+ return reducing ? HYSTERESIS_DAMPING : 1
150
+
151
+ }
152
+
153
+ /**
154
+ * Additively apply a weighted spike (from MicroEmotions) to the current
155
+ * vector. Two real dynamics layer on top of the plain additive push: a
156
+ * momentum term carried over from the EMA-smoothed velocity of recent
157
+ * spikes (the state keeps some of its own drift), and a hysteresis
158
+ * multiplier that resists a spike pulling an already-extreme axis back
159
+ * toward neutral while not resisting one that pushes it further out.
160
+ */
117
161
  applySpike( { valence = 0, arousal = 0, dominance = 0, weight = 1 } ) {
118
162
 
119
- this.vector = {
120
- valence : Math.tanh( this.vector.valence + valence * weight ),
121
- arousal : clamp( this.vector.arousal + arousal * weight ),
122
- dominance : Math.tanh( ( this.vector.dominance ?? 0 ) + dominance * weight ),
163
+ const prev = this.vector
164
+ const prevDominance = prev.dominance ?? 0
165
+ const pushV = valence * weight
166
+ const pushA = arousal * weight
167
+ const pushD = dominance * weight
168
+
169
+ const nextValence = Math.tanh( prev.valence + pushV * this.#hysteresisMultiplier( prev.valence, pushV ) + this.velocity.valence * MOMENTUM_COEFF )
170
+ const nextArousal = clamp( prev.arousal + pushA * this.#hysteresisMultiplier( prev.arousal, pushA ) + this.velocity.arousal * MOMENTUM_COEFF )
171
+ const nextDominance = Math.tanh( prevDominance + pushD * this.#hysteresisMultiplier( prevDominance, pushD ) + this.velocity.dominance * MOMENTUM_COEFF )
172
+
173
+ this.velocity = {
174
+ valence : this.velocity.valence * ( 1 - VELOCITY_EMA ) + ( nextValence - prev.valence ) * VELOCITY_EMA,
175
+ arousal : this.velocity.arousal * ( 1 - VELOCITY_EMA ) + ( nextArousal - prev.arousal ) * VELOCITY_EMA,
176
+ dominance : this.velocity.dominance * ( 1 - VELOCITY_EMA ) + ( nextDominance - prevDominance ) * VELOCITY_EMA,
123
177
  }
178
+ this.vector = { valence: nextValence, arousal: nextArousal, dominance: nextDominance }
124
179
 
125
180
  }
126
181
 
@@ -75,16 +75,81 @@ export class Homeostasis {
75
75
  this.needs = { stamina: 1, socialization: 1, curiosity: 1 }
76
76
  this.alertThreshold = alertThreshold
77
77
  this.controllers = { stamina: new PID(), socialization: new PID(), curiosity: new PID() }
78
+ // Allostatic load (McEwen, B. S., & Stellar, E. (1993), "Stress and the
79
+ // individual: mechanisms leading to disease", Arch Intern Med, 153(18)):
80
+ // the cumulative "wear" of repeatedly falling short of what the regulatory
81
+ // set point demands. Real accumulator here, distinct from CortisolEngine's
82
+ // acute level — it only rises while a need actually sits below its dynamic
83
+ // target and decays slowly otherwise, so it tracks CHRONIC deprivation, not
84
+ // a single bad tick. The specific accumulation/decay rates are own tuning,
85
+ // not measured allostatic-load coefficients. See CALIBRATION.md.
86
+ this.allostaticLoad = 0
78
87
 
79
88
  }
80
89
 
81
- tick( dt, personality ) {
90
+ /**
91
+ * The regulatory set point itself drifts under sustained load — the real
92
+ * allostatic-load idea (McEwen & Stellar 1993): a chronically stressed or
93
+ * circadian-depleted system doesn't just fail to reach "fully satisfied",
94
+ * its own definition of "satisfied" contracts. `personality` shifts the
95
+ * baseline (higher neuroticism tolerates less deprivation before the target
96
+ * itself starts slipping); `circadianEnergy` and `cortisol` (both 0..1,
97
+ * optional) pull it down further. Own tuning of the specific coefficients,
98
+ * not a reproduction of any measured set-point-shift curve.
99
+ */
100
+ getDynamicTarget( need, { personality = null, circadianEnergy = 1, cortisol = 0 } = {} ) {
101
+
102
+ const neuroticism = typeof personality?.get === 'function' ? personality.get( 'neuroticism' ) : 0.5
103
+ const circadianDrag = ( 1 - circadianEnergy ) * 0.15
104
+ const cortisolDrag = cortisol * 0.2
105
+ const loadDrag = this.allostaticLoad * 0.15
106
+ const neuroticismDrag = neuroticism * 0.05
107
+
108
+ return clamp01( 1 - circadianDrag - cortisolDrag - loadDrag - neuroticismDrag )
109
+
110
+ }
111
+
112
+ tick( dt, personality, { circadianEnergy = 1, cortisol = 0 } = {} ) {
82
113
 
83
114
  this.needs.stamina = clamp01( this.needs.stamina - BASE_DECAY.stamina * dt )
84
115
  this.needs.socialization = clamp01( this.needs.socialization - personality.getSocialDecayRate() * dt )
85
116
  this.needs.curiosity = clamp01( this.needs.curiosity - BASE_DECAY.curiosity * dt )
86
117
 
87
- for ( const need of Object.keys( this.needs ) ) this.controllers[ need ].step( this.needs[ need ], 1, dt )
118
+ for ( const need of Object.keys( this.needs ) ) {
119
+
120
+ const target = this.getDynamicTarget( need, { personality, circadianEnergy, cortisol } )
121
+ this.controllers[ need ].step( this.needs[ need ], target, dt )
122
+
123
+ }
124
+
125
+ // Load accumulation is driven by two INDEPENDENT real signals, not the
126
+ // self-lowering dynamic target from above (checking deprivation against
127
+ // a target that itself drops under stress would perversely make chronic
128
+ // stress look "more satisfied" and accumulate LESS load — the opposite
129
+ // of the real allostatic-load direction). Deprivation is checked against
130
+ // a fixed, undrifted reference instead; the chronic-stress drag
131
+ // (circadian + cortisol, the same terms getDynamicTarget uses) directly
132
+ // scales how fast load builds once there IS real deprivation.
133
+ const deprived = Object.values( this.needs ).some( v => v < 0.85 )
134
+ const drag = ( 1 - circadianEnergy ) * 0.15 + cortisol * 0.2
135
+
136
+ this.allostaticLoad = ( deprived || drag > 0.1 )
137
+ ? clamp01( this.allostaticLoad + ( 0.01 + drag * 0.03 ) * dt )
138
+ : Math.max( 0, this.allostaticLoad - 0.02 * dt )
139
+
140
+ }
141
+
142
+ /**
143
+ * Chronic-stress reactivity: real allostatic load makes a system MORE
144
+ * reactive to negative stimuli, not less — the well-documented "wear and
145
+ * tear" direction from the allostatic-load literature (McEwen & Stellar
146
+ * 1993; McEwen, B. S. (1998), "Protective and damaging effects of stress
147
+ * mediators", NEJM, 338(3)). Returns a multiplier >=1 a caller applies to
148
+ * a negative-appraisal spike; the specific 0.4 ceiling is own tuning.
149
+ */
150
+ getReactivityMultiplier() {
151
+
152
+ return 1 + this.allostaticLoad * 0.4
88
153
 
89
154
  }
90
155
 
@@ -58,17 +58,27 @@ export class Personality {
58
58
 
59
59
  }
60
60
 
61
- /** Relative weights for the three defense mechanisms. */
61
+ /**
62
+ * Relative weights across 5 defense mechanisms spanning Vaillant's
63
+ * immature/neurotic/mature hierarchy (Vaillant, G. E. (1977), "Adaptation
64
+ * to Life", Little, Brown). These personality-driven base weights are
65
+ * further reshaped by ego health / cortisol in DefenseMechanisms.check() —
66
+ * this method only supplies the trait-driven starting point.
67
+ */
62
68
  getDefenseWeights() {
63
69
 
64
- const projection = 0.2 + 0.6 * ( 1 - this.traits.agreeableness )
65
- const evasion = 0.2 + 0.6 * this.traits.neuroticism
66
- const sarcasm = 0.2 + 0.6 * this.traits.openness
67
- const total = projection + evasion + sarcasm
70
+ const projection = 0.2 + 0.6 * ( 1 - this.traits.agreeableness ) // immature
71
+ const evasion = 0.2 + 0.6 * this.traits.neuroticism // immature
72
+ const rationalization = 0.2 + 0.5 * this.traits.conscientiousness // neurotic
73
+ const sarcasm = 0.2 + 0.6 * this.traits.openness // neurotic-leaning, kept as-is (existing behavior)
74
+ const humor = 0.15 + 0.5 * this.traits.extraversion * this.traits.openness // mature
75
+ const total = projection + evasion + rationalization + sarcasm + humor
68
76
  return {
69
- projection : projection / total,
70
- evasion : evasion / total,
71
- sarcasm : sarcasm / total,
77
+ projection : projection / total,
78
+ evasion : evasion / total,
79
+ rationalization : rationalization / total,
80
+ sarcasm : sarcasm / total,
81
+ humor : humor / total,
72
82
  }
73
83
 
74
84
  }
@@ -12,20 +12,32 @@
12
12
  */
13
13
  export class WornPathCache {
14
14
 
15
- constructor( { promotionThreshold = 5, maxEntries = 200 } = {} ) {
15
+ constructor( { promotionThreshold = 5, maxEntries = 200, authorityHalfLifeMs = 1000 * 60 * 60 * 24 * 7 } = {} ) {
16
16
 
17
17
  this.promotionThreshold = promotionThreshold
18
18
  this.maxEntries = maxEntries
19
- this.entries = new Map() // fingerprint -> { count, appraisal }
19
+ // A path "worn in" a week ago that hasn't been walked since shouldn't
20
+ // carry the same authority as one walked an hour ago — real confidence
21
+ // decay by wall-clock time since LAST observed, not since creation.
22
+ // Half-life default (~1 week) is own tuning, not a citation.
23
+ this.authorityLambda = Math.log( 2 ) / authorityHalfLifeMs
24
+ this.entries = new Map() // fingerprint -> { count, appraisal, lastObservedAt }
20
25
 
21
26
  }
22
27
 
23
- /** Returns the cached appraisal if this fingerprint has been "worn in", else null. */
24
- consult( fingerprint ) {
28
+ /** Fraction of full authority this entry still carries, given how long it's been since it was last actually walked. */
29
+ getAuthority( entry, now = Date.now() ) {
30
+
31
+ return Math.exp( -this.authorityLambda * Math.max( 0, now - entry.lastObservedAt ) )
32
+
33
+ }
34
+
35
+ /** Returns the cached appraisal if this fingerprint is worn in AND its authority hasn't decayed below the threshold, else null. */
36
+ consult( fingerprint, { authorityThreshold = 0.5, now = Date.now() } = {} ) {
25
37
 
26
38
  const entry = this.entries.get( fingerprint )
27
- if ( entry && entry.count >= this.promotionThreshold ) return entry.appraisal
28
- return null
39
+ if ( !entry || entry.count < this.promotionThreshold ) return null
40
+ return this.getAuthority( entry, now ) >= authorityThreshold ? entry.appraisal : null
29
41
 
30
42
  }
31
43
 
@@ -36,19 +48,20 @@ export class WornPathCache {
36
48
 
37
49
  }
38
50
 
39
- observe( fingerprint, appraisal ) {
51
+ observe( fingerprint, appraisal, now = Date.now() ) {
40
52
 
41
53
  const entry = this.entries.get( fingerprint )
42
54
  if ( entry ) {
43
55
 
44
56
  entry.count += 1
45
- entry.appraisal = appraisal // keep the freshest version once promoted
57
+ entry.appraisal = appraisal // keep the freshest version once promoted
58
+ entry.lastObservedAt = now
46
59
 
47
60
  }
48
61
  else {
49
62
 
50
63
  if ( this.entries.size >= this.maxEntries ) this.entries.delete( this.entries.keys().next().value )
51
- this.entries.set( fingerprint, { count: 1, appraisal } )
64
+ this.entries.set( fingerprint, { count: 1, appraisal, lastObservedAt: now } )
52
65
 
53
66
  }
54
67
 
@@ -17,23 +17,43 @@ export class ArousalKalmanFilter {
17
17
  this.r = measurementNoise
18
18
  this.estimate = initial
19
19
  this.errorCovariance = 1
20
+ this.lastInnovation = 0 // measurement − predicted estimate, the real "how surprising was this reading" term
20
21
 
21
22
  }
22
23
 
23
- /** Feed a raw (noisy) arousal observation, get back the smoothed estimate. */
24
- filter( measurement ) {
24
+ /**
25
+ * Feed a raw (noisy) arousal observation, get back the smoothed estimate.
26
+ * `noiseMultiplier` (optional, default 1) lets a caller genuinely inform
27
+ * R per-observation from real interoceptive signals instead of a fixed
28
+ * constant: InteroceptiveSignals' attentional-narrowing/novelty reading is
29
+ * evidence THIS measurement is more likely a real signal than noise (a
30
+ * surprising, attention-grabbing spike), so it can pass a multiplier < 1
31
+ * (trust this one more); a high-threat/erratic-load reading is evidence
32
+ * the raw signal itself is noisier right now, so it can pass > 1 (trust it
33
+ * less). Same filter equations, R just isn't a hardcoded constant anymore.
34
+ */
35
+ filter( measurement, noiseMultiplier = 1 ) {
25
36
 
26
37
  // Predict
27
38
  const predictedEstimate = this.estimate
28
39
  const predictedCovariance = this.errorCovariance + this.q
29
40
 
30
41
  // Update
31
- const kalmanGain = predictedCovariance / ( predictedCovariance + this.r )
32
- this.estimate = predictedEstimate + kalmanGain * ( measurement - predictedEstimate )
42
+ const effectiveR = Math.max( 0.001, this.r * noiseMultiplier )
43
+ const kalmanGain = predictedCovariance / ( predictedCovariance + effectiveR )
44
+ this.lastInnovation = measurement - predictedEstimate // real Kalman "innovation" term, standard name, not invented
45
+ this.estimate = predictedEstimate + kalmanGain * this.lastInnovation
33
46
  this.errorCovariance = ( 1 - kalmanGain ) * predictedCovariance
34
47
 
35
48
  return this.estimate
36
49
 
37
50
  }
38
51
 
52
+ /** The raw prediction error from the last filter() call — large on a genuine surprise, near zero once the estimate has converged to a stable signal. */
53
+ getLastInnovation() {
54
+
55
+ return this.lastInnovation
56
+
57
+ }
58
+
39
59
  }