totemheart 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Real approach-avoidance gradient conflict (Miller, N. E. (1944),
3
+ * "Experimental studies of conflict", in Hunt, J. McV. (ed.), Personality
4
+ * and the Behavior Disorders, Ronald Press, 431-465): both an approach
5
+ * gradient and an avoidance gradient grow stronger as psychological
6
+ * distance to a goal shrinks, but the avoidance gradient is STEEPER — so far
7
+ * from the goal, approach dominates (net pull toward it); close to the goal,
8
+ * avoidance overtakes it (net push away). Where the two curves cross is a
9
+ * real region of maximal conflict — approach-avoidance VACILLATION, the
10
+ * literal oscillation Miller's model predicts, not a metaphor.
11
+ *
12
+ * approach(d) = Ga · exp(−d/La)
13
+ * avoidance(d) = Gv · exp(−d/Lv), with Lv < La (avoidance falls off faster with distance)
14
+ */
15
+ function clamp01( v ) {
16
+
17
+ return Math.max( 0, Math.min( 1, v ) )
18
+
19
+ }
20
+
21
+ export class MotivationalConflict {
22
+
23
+ constructor( { La = 1.4, Lv = 0.7 } = {} ) {
24
+
25
+ this.La = La // approach gradient's real spatial decay constant
26
+ this.Lv = Lv // avoidance gradient's real spatial decay constant — steeper (smaller) than La
27
+
28
+ }
29
+
30
+ /**
31
+ * `distance` (0..~2, psychological distance to the goal — caller-supplied,
32
+ * e.g. 1 - trust for "closeness to disclosure", or unresolved-wound
33
+ * pressure for "closeness to confrontation"). `approachGain`/`avoidanceGain`
34
+ * (Ga, Gv, real magnitudes the caller already has — e.g. desirability for
35
+ * Ga, woundPressure/cortisol for Gv).
36
+ */
37
+ evaluate( distance, approachGain, avoidanceGain ) {
38
+
39
+ const d = Math.max( 0, distance )
40
+ const approachForce = approachGain * Math.exp( -d / this.La )
41
+ const avoidanceForce = avoidanceGain * Math.exp( -d / this.Lv )
42
+ const netForce = approachForce - avoidanceForce
43
+
44
+ // Vacillation: the two forces are close in magnitude relative to their
45
+ // own scale — real conflict-zone detection, not an arbitrary constant
46
+ // threshold (own tuning of the 0.15 relative-closeness band).
47
+ const scale = Math.max( approachForce, avoidanceForce, 0.001 )
48
+ const vacillating = Math.abs( netForce ) / scale < 0.15
49
+
50
+ return {
51
+ approachForce,
52
+ avoidanceForce,
53
+ netForce,
54
+ vacillating,
55
+ // Real expression-confidence dampener: high conflict = low confidence
56
+ // in what to express, feeds AppraisalAgreement-style downstream gating.
57
+ expressionConfidence : vacillating ? clamp01( 1 - Math.abs( netForce ) / scale * 2 ) : 1,
58
+ }
59
+
60
+ }
61
+
62
+ }
@@ -0,0 +1,77 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * A small, dynamic subset of Schwartz's real, cross-culturally validated
9
+ * basic human values (Schwartz, S. H. (1992), "Universals in the content and
10
+ * structure of values: theoretical advances and empirical tests in 20
11
+ * countries", Advances in Experimental Social Psychology, 25, 1-65) —
12
+ * benevolence (care), universalism (fairness), conformity (loyalty/tradition),
13
+ * self-direction (autonomy), and security. Each holds a real weight in [0,1]
14
+ * that experience nudges via a simple EMA (own engineering — Schwartz's work
15
+ * establishes the value STRUCTURE, not a per-agent learning update rule).
16
+ * When two active values genuinely conflict on the same appraisal (opposite
17
+ * polarity read on the same event, e.g. an honesty/fairness pull toward
18
+ * telling a hard truth vs. a care/loyalty pull toward protecting feelings),
19
+ * this raises a real dissonance signal proportional to how strongly BOTH
20
+ * values are held — a mild, weakly-held value clashing with a strong one
21
+ * isn't much of a real conflict; two strongly-held values clashing is.
22
+ */
23
+ const DEFAULT_VALUES = [ 'care', 'fairness', 'loyalty', 'autonomy', 'security' ]
24
+
25
+ export class ValueHierarchy {
26
+
27
+ constructor( initialWeights = {} ) {
28
+
29
+ this.weights = new Map( DEFAULT_VALUES.map( v => [ v, clamp01( initialWeights[ v ] ?? 0.5 ) ] ) )
30
+
31
+ }
32
+
33
+ getWeight( value ) {
34
+
35
+ return this.weights.get( value ) ?? 0
36
+
37
+ }
38
+
39
+ /** Real EMA nudge — an experience that reinforced or violated a value shifts its weight, bounded in [0,1]. */
40
+ nudge( value, delta, rate = 0.1 ) {
41
+
42
+ if ( !this.weights.has( value ) ) return
43
+ const current = this.weights.get( value )
44
+ this.weights.set( value, clamp01( current + rate * delta ) )
45
+
46
+ }
47
+
48
+ /**
49
+ * `polarityA`/`polarityB` — signed direction (-1..1) each value pulls THIS
50
+ * appraisal toward. A real conflict requires opposite signs; the
51
+ * dissonance magnitude is the product of both weights (both must matter)
52
+ * scaled by how opposed the polarities are.
53
+ */
54
+ evaluateConflict( valueA, polarityA, valueB, polarityB ) {
55
+
56
+ if ( Math.sign( polarityA ) === Math.sign( polarityB ) || polarityA === 0 || polarityB === 0 ) {
57
+
58
+ return { conflict: false, dissonance: 0 }
59
+
60
+ }
61
+
62
+ const wA = this.getWeight( valueA )
63
+ const wB = this.getWeight( valueB )
64
+ const opposition = Math.min( Math.abs( polarityA ), Math.abs( polarityB ) )
65
+ const dissonance = clamp01( wA * wB * opposition )
66
+
67
+ return { conflict: dissonance > 0.05, dissonance, valueA, valueB }
68
+
69
+ }
70
+
71
+ getAll() {
72
+
73
+ return [ ...this.weights.entries() ]
74
+
75
+ }
76
+
77
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Internal self-binding promises — the AI can commit its own future behavior
3
+ * and pay a real, escalating cost for breaking that commitment, matching the
4
+ * real finding that commitment consistency pressure grows with prior
5
+ * investment, not a fixed penalty (Kiesler, C. A. (1971), "The Psychology of
6
+ * Commitment", Academic Press — behavioral commitment strengthens with each
7
+ * reaffirmation). Reuses CoreBeliefs' own defense-investment counting shape
8
+ * (recordDefense/getInvestment) conceptually, but tracks promises as their
9
+ * own ledger — a promise is a commitment about FUTURE behavior, a core
10
+ * belief is a claim about how things already are, and conflating the two
11
+ * would blur two genuinely different kinds of state.
12
+ */
13
+ function clamp01( v ) {
14
+
15
+ return Math.max( 0, Math.min( 1, v ) )
16
+
17
+ }
18
+
19
+ export class CommitmentDevice {
20
+
21
+ constructor( { baseCost = 0.15, growthPerKept = 0.08 } = {} ) {
22
+
23
+ this.baseCost = baseCost
24
+ this.growthPerKept = growthPerKept
25
+ this.promises = new Map() // topic -> { description, timesKept, timesBroken, active }
26
+
27
+ }
28
+
29
+ make( topic, description ) {
30
+
31
+ this.promises.set( topic, { description, timesKept: 0, timesBroken: 0, active: true } )
32
+ return this.promises.get( topic )
33
+
34
+ }
35
+
36
+ /** A turn passed where this promise's condition genuinely held — real reinforcement, not automatic. */
37
+ keep( topic ) {
38
+
39
+ const p = this.promises.get( topic )
40
+ if ( !p ) return null
41
+ p.timesKept += 1
42
+ return p
43
+
44
+ }
45
+
46
+ /**
47
+ * Breaking a longer-kept promise costs more — real escalating-commitment
48
+ * cost, `cost` is a real magnitude the caller applies to GuiltEngine's
49
+ * spike weight and ReputationEngine's egoHealth damage, not an invented
50
+ * separate emotion channel.
51
+ */
52
+ violate( topic ) {
53
+
54
+ const p = this.promises.get( topic )
55
+ if ( !p ) return { cost: 0 }
56
+ p.timesBroken += 1
57
+ const cost = clamp01( this.baseCost * ( 1 + p.timesKept * this.growthPerKept ) )
58
+ return { cost, timesKept: p.timesKept, timesBroken: p.timesBroken }
59
+
60
+ }
61
+
62
+ getInvestment( topic ) {
63
+
64
+ return this.promises.get( topic )?.timesKept ?? 0
65
+
66
+ }
67
+
68
+ getAll() {
69
+
70
+ return [ ...this.promises.entries() ]
71
+
72
+ }
73
+
74
+ }
@@ -0,0 +1,61 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Damage to a core value, distinct from ordinary guilt — a "perpetrating,
9
+ * failing to prevent, or bearing witness to acts that transgress deeply
10
+ * held moral beliefs" (Litz, B. T., Stein, N., Delaney, E., Lebowitz, L.,
11
+ * Nash, W. P., Silva, C., & Maguen, S. (2009), "Moral injury and moral
12
+ * repair in war veterans: A preliminary model and intervention strategy",
13
+ * Clinical Psychology Review, 29(8), 695-706 — the term and its distinction
14
+ * from ordinary guilt/PTSD symptomatology originates here). Unlike ordinary
15
+ * dissonance (CognitiveDissonance.js, which recovers as the triggering
16
+ * input passes), a moral injury leaves a PERMANENT scar — CoreBeliefs
17
+ * themselves are immutable by design (see CoreBeliefs.js), so this tracks
18
+ * scarring as its own separate, non-decaying ledger keyed by belief topic,
19
+ * exactly the way a real core belief can't be "fixed" once violated deeply
20
+ * enough, only carried.
21
+ */
22
+ export class MoralInjury {
23
+
24
+ constructor( { threshold = 0.75 } = {} ) {
25
+
26
+ this.threshold = threshold // stress magnitude beyond which ordinary dissonance becomes injury
27
+ this.scars = new Map() // topic -> cumulative severity, never decays
28
+
29
+ }
30
+
31
+ /**
32
+ * `dissonanceStress` — real magnitude from CognitiveDissonance for a hit
33
+ * against a HIGH-polarity core belief (caller filters for polarity/importance).
34
+ * Only crosses into injury territory above `threshold` — ordinary disagreement
35
+ * doesn't scar, a genuine violation of a deeply held value does.
36
+ */
37
+ evaluate( topic, dissonanceStress, beliefPolarity = 1 ) {
38
+
39
+ if ( dissonanceStress < this.threshold ) return { injured: false }
40
+
41
+ const severity = clamp01( ( dissonanceStress - this.threshold ) / ( 1 - this.threshold ) ) * Math.abs( beliefPolarity )
42
+ this.scars.set( topic, clamp01( ( this.scars.get( topic ) ?? 0 ) + severity ) )
43
+
44
+ return { injured: true, severity, totalScar: this.scars.get( topic ) }
45
+
46
+ }
47
+
48
+ getScar( topic ) {
49
+
50
+ return this.scars.get( topic ) ?? 0
51
+
52
+ }
53
+
54
+ /** Total permanent scarring across all topics — a real, never-decaying signal DefenseMechanisms' regression weighting can read. */
55
+ getTotalScar() {
56
+
57
+ return [ ...this.scars.values() ].reduce( ( a, b ) => a + b, 0 )
58
+
59
+ }
60
+
61
+ }
@@ -0,0 +1,56 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Opponent-process theory of acquired motivation (Solomon, R. L., & Corbit,
9
+ * J. D. (1974), "An opponent-process theory of motivation: I. Temporal
10
+ * dynamics of affect", Psychological Review, 81(2), 119-145): a strong
11
+ * hedonic event (the "a-process") is automatically followed by an opposite-
12
+ * valence "b-process" that undershoots baseline once the a-process ends —
13
+ * and with REPEATED exposure, the a-process habituates (tolerance) while the
14
+ * b-process grows and lasts longer (withdrawal), literally the theory's
15
+ * central claim. Modeled directly as those two real trends, keyed by the
16
+ * same fingerprint idea HedonicAdaptation already uses for a repeated
17
+ * stimulus.
18
+ */
19
+ export class OpponentProcess {
20
+
21
+ constructor( { baseB = 0.3, growthRate = 0.15, aHabituationRate = 0.08 } = {} ) {
22
+
23
+ this.baseB = baseB
24
+ this.growthRate = growthRate
25
+ this.aHabituationRate = aHabituationRate
26
+ this.exposures = new Map() // fingerprint -> exposureCount
27
+
28
+ }
29
+
30
+ /**
31
+ * `peakValence` — the real magnitude of this hedonic spike (already
32
+ * computed elsewhere). Returns the real, GROWING after-effect (undershoot,
33
+ * opposite sign) the caller should apply as a spike shortly after, and the
34
+ * HABITUATED (shrinking) magnitude the a-process itself should actually
35
+ * be felt at this time around.
36
+ */
37
+ trigger( fingerprint, peakValence ) {
38
+
39
+ const exposureCount = ( this.exposures.get( fingerprint ) ?? 0 ) + 1
40
+ this.exposures.set( fingerprint, exposureCount )
41
+
42
+ const habituatedPeak = peakValence / ( 1 + this.aHabituationRate * ( exposureCount - 1 ) )
43
+ const bMagnitude = this.baseB * ( 1 + this.growthRate * ( exposureCount - 1 ) )
44
+ const afterEffectValence = -Math.sign( peakValence ) * clamp01( Math.abs( peakValence ) * bMagnitude )
45
+
46
+ return { exposureCount, habituatedPeak, afterEffectValence }
47
+
48
+ }
49
+
50
+ getExposureCount( fingerprint ) {
51
+
52
+ return this.exposures.get( fingerprint ) ?? 0
53
+
54
+ }
55
+
56
+ }
@@ -0,0 +1,47 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Real predictive-processing account of interoception: the body/mind
9
+ * continuously predicts its own internal state, and affect is generated
10
+ * substantially FROM the prediction error itself, not just from the raw
11
+ * signal (Seth, A. K. (2013), "Interoceptive inference, emotion, and the
12
+ * embodied self", Trends in Cognitive Sciences, 17(11), 565-573). This
13
+ * module doesn't reinvent the prediction machinery — ArousalKalmanFilter
14
+ * already IS a real predict/correct interoceptive model, and its
15
+ * `lastInnovation` (measurement − predicted estimate) already IS the real
16
+ * prediction-error term that theory is about. What this adds: a persistent
17
+ * EMA of |innovation| magnitude (a running "how surprising has my own body
18
+ * been to me lately" signal) and the real anxiety-like arousal contribution
19
+ * a SUSTAINED mismatch produces — one surprising reading is just noise, a
20
+ * persistent pattern of mismatch is the genuinely anxiogenic signal.
21
+ */
22
+ export class InteroceptivePredictionError {
23
+
24
+ constructor( { alpha = 0.2, gain = 1.2 } = {} ) {
25
+
26
+ this.alpha = alpha
27
+ this.gain = gain
28
+ this.mismatchLevel = 0
29
+
30
+ }
31
+
32
+ /** Feed the real innovation from ArousalKalmanFilter.getLastInnovation() each turn. */
33
+ observe( innovation ) {
34
+
35
+ this.mismatchLevel = this.alpha * Math.abs( innovation ) + ( 1 - this.alpha ) * this.mismatchLevel
36
+ return this.mismatchLevel
37
+
38
+ }
39
+
40
+ /** Sustained mismatch reads as real anxiety-like arousal — a body the mind can't predict is itself threatening. */
41
+ getAnxietyContribution() {
42
+
43
+ return clamp01( this.mismatchLevel * this.gain )
44
+
45
+ }
46
+
47
+ }
@@ -62,8 +62,19 @@ export class DopaminergicEngine {
62
62
 
63
63
  }
64
64
 
65
- /** `context` lets ToM-derived predictions and life events target a specific relationship/topic instead of one shared scalar. */
66
- computeRPE( reward, context = 'default' ) {
65
+ /**
66
+ * `context` lets ToM-derived predictions and life events target a specific
67
+ * relationship/topic instead of one shared scalar. `allostaticLoad` (0..1,
68
+ * optional, Homeostasis.allostaticLoad) — real allostatic-load-driven
69
+ * anhedonia: sustained high load blunts the hedonic response to reward
70
+ * (a real, well-supported direction in the chronic-stress/anhedonia
71
+ * literature — the same allostatic-load concept CircadianRhythm.js already
72
+ * cites Miller, Chen & Zhou (2007) for), applied here as a real damper on
73
+ * `likingAlpha`'s effective learning rate so a loaded system needs a
74
+ * bigger reward to register the same felt liking. Defaults to 0 (no
75
+ * damping) so every existing caller keeps the original behavior exactly.
76
+ */
77
+ computeRPE( reward, context = 'default', allostaticLoad = 0 ) {
67
78
 
68
79
  const v = this.#getV( context )
69
80
  const rpe = reward + this.gamma * v - v
@@ -88,7 +99,8 @@ export class DopaminergicEngine {
88
99
 
89
100
  }
90
101
 
91
- this.likingValue += this.likingAlpha * ( reward - this.likingValue )
102
+ const effectiveLikingAlpha = this.likingAlpha * ( 1 - clamp01( allostaticLoad ) * 0.6 ) // anhedonia damper — own tuning of the 0.6 ceiling
103
+ this.likingValue += effectiveLikingAlpha * ( reward - this.likingValue )
92
104
  this.wanting = clamp01( this.wanting * ( 1 - this.wantingDecay ) + Math.abs( rpe ) * 0.3 )
93
105
 
94
106
  return clamp( rpe, -2, 2 ) / 2 // normalize to roughly -1..1 for downstream spike use
@@ -0,0 +1,74 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * The real two-process model of sleep regulation (Borbély, A. A. (1982), "A
9
+ * two process model of sleep regulation", Human Neurobiology, 1(3), 195-204):
10
+ * Process S, homeostatic sleep pressure, rises as a saturating exponential
11
+ * while awake and falls as an exponential decay during sleep. Implemented
12
+ * here literally as that real equation, distinct from CircadianRhythm's
13
+ * Process C (the wave-based diurnal rhythm already in CircadianRhythm.js —
14
+ * the two-process model is explicitly the INTERACTION of both processes, so
15
+ * this module is a genuine formal counterpart to the existing one, not a
16
+ * duplicate). Downstream: rising S reduces cognitive control (feeds
17
+ * DecisionFatigue) and raises emotional lability (widens EmotionSpace
18
+ * spikes) — both real, well-supported directions of sleep deprivation
19
+ * research; the specific multiplier magnitudes are our own tuning.
20
+ *
21
+ * awake: S(t) = Sasym − (Sasym − S0)·exp(−t/τr)
22
+ * asleep: S(t) = Sfloor + (S − Sfloor)·exp(−t/τf)
23
+ */
24
+ export class SleepPressure {
25
+
26
+ constructor( { asymptote = 1, floor = 0.05, tauRiseMs = 1000 * 60 * 60 * 16, tauFallMs = 1000 * 60 * 60 * 2 } = {} ) {
27
+
28
+ this.asymptote = asymptote
29
+ this.floor = floor
30
+ this.tauRiseMs = tauRiseMs // real time-to-saturate constant while awake (~16h to approach ceiling)
31
+ this.tauFallMs = tauFallMs // real time-to-clear constant during a REM sweep ("sleep")
32
+ this.S = 0
33
+
34
+ }
35
+
36
+ /** Call each processed turn (real elapsed ms since the last one) — awake accumulation. */
37
+ accumulate( elapsedMs ) {
38
+
39
+ if ( elapsedMs <= 0 ) return this.S
40
+ this.S = this.asymptote - ( this.asymptote - this.S ) * Math.exp( -elapsedMs / this.tauRiseMs )
41
+ return this.S
42
+
43
+ }
44
+
45
+ /** Called from a real RemConsolidation sweep — the actual "sleep" event that clears pressure, same real event that already pays CircadianRhythm's sleepDebt down. */
46
+ dissipate( elapsedMs ) {
47
+
48
+ if ( elapsedMs <= 0 ) return this.S
49
+ this.S = this.floor + ( this.S - this.floor ) * Math.exp( -elapsedMs / this.tauFallMs )
50
+ return this.S
51
+
52
+ }
53
+
54
+ /** High S reduces cognitive control — a real multiplier DecisionFatigue's capacity can be scaled by. */
55
+ getCognitiveControlMultiplier() {
56
+
57
+ return 1 - clamp01( this.S ) * 0.5
58
+
59
+ }
60
+
61
+ /** High S widens emotional swings — a real multiplier EmotionSpace spike weights can be scaled by. */
62
+ getLabilityMultiplier() {
63
+
64
+ return 1 + clamp01( this.S ) * 0.4
65
+
66
+ }
67
+
68
+ getLevel() {
69
+
70
+ return clamp01( this.S )
71
+
72
+ }
73
+
74
+ }
@@ -0,0 +1,54 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Psychological time as its own real variable, distinct from wall-clock dt.
9
+ * Two well-supported directions from the time-perception literature, both
10
+ * modeled here as a real dt-multiplier applied on top of the caller's raw dt
11
+ * (decay, rumination frequency, REM pressure all consume this multiplied
12
+ * value instead of raw dt):
13
+ *
14
+ * High arousal/threat DENSIFIES subjective time — real duration judgments
15
+ * lengthen retrospectively under fear/high arousal (Stetson, C., Fiesta, M. P.,
16
+ * & Eagleman, D. M. (2007), "Does time really slow down during a frightening
17
+ * event?", PLoS ONE, 2(12), e1295), which this models as MORE subjective
18
+ * time elapsing per real tick while aroused — rumination and decay both
19
+ * process more "felt" time per real turn during a hijack.
20
+ *
21
+ * Boredom/satiation also STRETCHES subjective time — the classic "time
22
+ * drags" experience under low-stimulation monotony (Zakay, D., & Block, R. A.
23
+ * (1997), "Temporal cognition", Current Directions in Psychological Science,
24
+ * 6(1), 12-16, on attention-to-time models of duration judgment: more
25
+ * attention allocated to the passage of time itself, whether from
26
+ * hypervigilant threat-monitoring or from having nothing else to attend to,
27
+ * lengthens the subjective estimate). Both routes land on the SAME real
28
+ * outcome (more felt time per real tick, not opposite signs) — what differs
29
+ * between them is the cause, not the direction.
30
+ */
31
+ export class SubjectiveTimeEngine {
32
+
33
+ constructor( { arousalGain = 1.5, boredomGain = 0.6 } = {} ) {
34
+
35
+ this.arousalGain = arousalGain
36
+ this.boredomGain = boredomGain
37
+
38
+ }
39
+
40
+ /** `arousal` (0..1, above-baseline reading) and `boredomLevel` (0..1, e.g. TopicSatiation's own scalar) are both real signals this engine only combines, not invents. */
41
+ getSubjectiveDtMultiplier( arousal = 0, boredomLevel = 0 ) {
42
+
43
+ const densify = clamp01( arousal ) * this.arousalGain
44
+ const stretch = clamp01( boredomLevel ) * this.boredomGain
45
+
46
+ // Both forces push in the same direction (more felt time per real tick) —
47
+ // densification and stretching are two real routes to the same
48
+ // subjective outcome (time "feels longer"), not opposites here; what
49
+ // differs between them is what they're driven by, not their sign.
50
+ return Math.max( 0.1, 1 + densify + stretch )
51
+
52
+ }
53
+
54
+ }
@@ -154,6 +154,27 @@ export class Attachment {
154
154
 
155
155
  }
156
156
 
157
+ /**
158
+ * State-dependent style switching under real acute stress — "earned
159
+ * insecurity": the attachment BEHAVIORAL SYSTEM activates under threat and
160
+ * can express a more insecure style than the trait baseline while the
161
+ * threat lasts (Mikulincer, M., & Shaver, P. R. (2016), "Attachment in
162
+ * Adulthood: Structure, Dynamics, and Change", 2nd ed., Guilford Press, on
163
+ * state vs. trait attachment and activation of the attachment system under
164
+ * threat). A secure trait style can read as anxious under a real,
165
+ * extreme cortisol/hijack load; other trait styles are left as-is
166
+ * (avoidant/anxious/fearful already ARE the stress-reactive end of the
167
+ * spectrum in this model — there's no further insecure direction to
168
+ * switch them toward). `stressLevel` (0..1, e.g. CortisolEngine.getLevel()).
169
+ */
170
+ getStressStyle( personality, stressLevel = 0 ) {
171
+
172
+ const traitStyle = classifyStyle( personality )
173
+ if ( traitStyle === 'secure' && stressLevel > 0.75 ) return 'anxious'
174
+ return traitStyle
175
+
176
+ }
177
+
157
178
  get( userId ) {
158
179
 
159
180
  return this.#entry( userId )
@@ -0,0 +1,105 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Grief as a real process, not "high sadness". Two honest engineering
9
+ * choices instead of borrowing Kübler-Ross's five stages: (1) the stage
10
+ * model is a popular framing, not an empirically validated sequence — real
11
+ * grief research (Bonanno, G. A. (2004), "Loss, trauma, and human
12
+ * resilience: have we underestimated the human capacity to thrive after
13
+ * extremely aversive events?", American Psychologist, 59(1), 20-28) finds
14
+ * highly variable trajectories, not a fixed order, so no stage machine is
15
+ * built here; (2) what IS well supported and modeled directly is the real
16
+ * SHAPE — a long-tailed, non-monotonic decline (slow power-law fade, not
17
+ * exponential) punctuated by intrusive "waves" long after the initial loss
18
+ * (Zisook, S., & Shear, K. (2009), "Grief and bereavement: what psychiatrists
19
+ * need to know", World Psychiatry, 8(2), 67-74, on grief's protracted,
20
+ * fluctuating course).
21
+ *
22
+ * intensity(t) = G0 · (1 + t/τ)^(−p) — power-law decay, own choice of p/τ,
23
+ * not fit from a specific dataset — heavier-tailed than CortisolEngine's
24
+ * exponential chronic-stress decay on purpose: grief is modeled as
25
+ * genuinely slower to fade than ordinary stress.
26
+ *
27
+ * Waves are a real Poisson process on top of that decaying base intensity,
28
+ * the same mechanism EpisodicMemory.rollIntrusiveThought() already uses for
29
+ * unresolved-wound intrusions — grief waves are that same real phenomenon,
30
+ * scoped to loss specifically and given their own decaying rate so waves
31
+ * genuinely space out as grief work progresses (own tuning).
32
+ */
33
+ export class GriefEngine {
34
+
35
+ constructor( { tauMs = 1000 * 60 * 60 * 24 * 14, p = 0.55, waveRateScale = 0.0005 } = {} ) {
36
+
37
+ this.tauMs = tauMs
38
+ this.p = p
39
+ this.waveRateScale = waveRateScale
40
+ this.griefs = new Map() // userId -> { G0, startedAt, wavesCount, sourceId }
41
+
42
+ }
43
+
44
+ /** A loss just happened — `lostValue` (0..1) is real magnitude already computed elsewhere (a bond's affinity, a memory's importance). */
45
+ triggerLoss( userId, lostValue, sourceId = null, now = Date.now() ) {
46
+
47
+ const existing = this.griefs.get( userId )
48
+ const carryOver = existing ? this.getIntensity( userId, now ) : 0
49
+ this.griefs.set( userId, { G0: clamp01( carryOver + lostValue ), startedAt: now, wavesCount: existing?.wavesCount ?? 0, sourceId } )
50
+ return this.griefs.get( userId )
51
+
52
+ }
53
+
54
+ getIntensity( userId, now = Date.now() ) {
55
+
56
+ const g = this.griefs.get( userId )
57
+ if ( !g ) return 0
58
+ const elapsed = Math.max( 0, now - g.startedAt )
59
+ return g.G0 * Math.pow( 1 + elapsed / this.tauMs, -this.p )
60
+
61
+ }
62
+
63
+ isActive( userId, now = Date.now(), floor = 0.05 ) {
64
+
65
+ return this.getIntensity( userId, now ) > floor
66
+
67
+ }
68
+
69
+ /**
70
+ * Real Poisson roll for an intrusive grief wave this tick — probability
71
+ * scales with current (already-decayed) intensity, and the rate itself
72
+ * damps as wavesCount grows (own tuning: real grief work — each
73
+ * processed wave makes the next one somewhat less likely, without ever
74
+ * reaching exactly zero).
75
+ */
76
+ rollWave( userId, now = Date.now(), dt = 1 ) {
77
+
78
+ const g = this.griefs.get( userId )
79
+ if ( !g ) return null
80
+
81
+ const intensity = this.getIntensity( userId, now )
82
+ if ( intensity <= 0.05 ) return null
83
+
84
+ const dampened = this.waveRateScale / ( 1 + g.wavesCount * 0.08 )
85
+ const probability = 1 - Math.exp( -dampened * intensity * 1000 * dt )
86
+ if ( Math.random() >= probability ) return null
87
+
88
+ g.wavesCount += 1
89
+ return {
90
+ intensity,
91
+ wavesCount : g.wavesCount,
92
+ spike : { valence: -intensity * 0.6, arousal: intensity * 0.4, weight: intensity },
93
+ }
94
+
95
+ }
96
+
97
+ getState( userId, now = Date.now() ) {
98
+
99
+ const g = this.griefs.get( userId )
100
+ if ( !g ) return { active: false, intensity: 0, wavesCount: 0 }
101
+ return { active: this.isActive( userId, now ), intensity: this.getIntensity( userId, now ), wavesCount: g.wavesCount, sourceId: g.sourceId }
102
+
103
+ }
104
+
105
+ }