totemheart 0.1.2 → 0.1.3

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,58 @@
1
+ function clamp( v, min = -1, max = 1 ) {
2
+
3
+ return Math.max( min, Math.min( max, v ) )
4
+
5
+ }
6
+
7
+ function clamp01( v ) {
8
+
9
+ return Math.max( 0, Math.min( 1, v ) )
10
+
11
+ }
12
+
13
+ /**
14
+ * Affective forecasting: emotion generated by what the AI EXPECTS to happen,
15
+ * not only by what already happened (Wilson, T. D., & Gilbert, D. T. (2003),
16
+ * "Affective forecasting", Advances in Experimental Social Psychology, 35,
17
+ * 345-411). Reuses BayesianExpectation's real posterior (already a genuine
18
+ * P(positive outcome) estimate per user) as the forecast's valence sign and
19
+ * confidence, converts it into a concrete expected-valence/arousal pair, and
20
+ * — the real mechanic — computes the forecast ERROR once the actual outcome
21
+ * is known, which is exactly the same real signal DopaminergicEngine's RPE
22
+ * already consumes, so a wrong anticipation genuinely corrects future
23
+ * anticipation the way TD learning does, not just the reward-prediction
24
+ * system alone.
25
+ */
26
+ export class AnticipatoryAffect {
27
+
28
+ /** BayesianExpectation posterior -> a concrete forecast the AI can feel BEFORE the turn's real outcome is known. */
29
+ forecast( bayesianExpectation, userId ) {
30
+
31
+ const p = bayesianExpectation.getExpectation( userId )
32
+ const anxiety = bayesianExpectation.getAnxiety( userId )
33
+ const expectedValence = clamp( ( p - 0.5 ) * 2 )
34
+ const expectedArousal = clamp01( anxiety ) // anticipating a bad outcome is itself arousing
35
+
36
+ // Confidence: how far the posterior sits from an uninformative 0.5 —
37
+ // a forecast near neutral is a weak forecast regardless of arousal.
38
+ const confidence = clamp01( Math.abs( p - 0.5 ) * 2 )
39
+
40
+ return { expectedValence, expectedArousal, confidence, posterior: p }
41
+
42
+ }
43
+
44
+ /** Real forecast error — the gap between what was anticipated and what actually happened, signed (positive = better than feared/hoped). */
45
+ getForecastError( forecastResult, actualValence ) {
46
+
47
+ return clamp( actualValence - forecastResult.expectedValence )
48
+
49
+ }
50
+
51
+ /** Feeds the forecast error into DopaminergicEngine as a direct expectation nudge — a wrong anticipation updates the NEXT forecast, real backward correction. */
52
+ applyCorrection( dopaminergicEngine, context, forecastError, weight = 0.25 ) {
53
+
54
+ dopaminergicEngine.updateExpectationFromBelief( context, forecastError, weight )
55
+
56
+ }
57
+
58
+ }
@@ -0,0 +1,81 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * A stronger, explicitly-budgeted self-regulation resource, distinct from
9
+ * DecisionFatigue's plain accumulate-and-decay load and from ExpressionDebt's
10
+ * suppression-cost reservoir: this is a real daily-scale BUDGET that
11
+ * regulation acts spend down, checked against a hard floor that changes
12
+ * downstream behavior (raised hijack probability, style collapse) once
13
+ * crossed — not just a smoothly degrading number.
14
+ *
15
+ * Modeled on the strength/resource metaphor of ego depletion (Baumeister,
16
+ * R. F., Bratslavsky, E., Muraven, M., & Tice, D. M. (1998), "Ego depletion:
17
+ * Is the active self a limited resource?", Journal of Personality and Social
18
+ * Psychology, 74(5), 1252-1265) — with an explicit, honest caveat: that
19
+ * theory's specific glucose/resource-depletion mechanism largely failed to
20
+ * replicate in a large registered replication effort (Hagger, M. S., et al.
21
+ * (2016), "A multilab preregistered replication of the ego-depletion
22
+ * effect", Perspectives on Psychological Science, 11(4), 546-573). What's
23
+ * kept here is the qualitatively useful ENGINEERING pattern (a bounded
24
+ * resource that regulation spends and rest restores, with real downstream
25
+ * consequences once low) — not a claim that this models a settled
26
+ * neuroscientific mechanism. See CALIBRATION.md.
27
+ */
28
+ export class EgoDepletionBudget {
29
+
30
+ constructor( { capacity = 1, regenRate = 0.02, lowThreshold = 0.25 } = {} ) {
31
+
32
+ this.capacity = capacity
33
+ this.regenRate = regenRate
34
+ this.lowThreshold = lowThreshold
35
+ this.budget = capacity
36
+
37
+ }
38
+
39
+ /** Any act of self-regulation (suppression, reappraisal, overriding an immature defense) spends real budget. */
40
+ spend( amount ) {
41
+
42
+ this.budget = Math.max( 0, this.budget - Math.max( 0, amount ) )
43
+ return this.budget
44
+
45
+ }
46
+
47
+ /** Rest/idle time and REM sweeps regenerate the budget — real bounded recovery, never above capacity. */
48
+ regenerate( dt = 1 ) {
49
+
50
+ this.budget = Math.min( this.capacity, this.budget + this.regenRate * dt )
51
+ return this.budget
52
+
53
+ }
54
+
55
+ isDepleted() {
56
+
57
+ return this.budget <= this.lowThreshold
58
+
59
+ }
60
+
61
+ getLevel() {
62
+
63
+ return clamp01( this.budget / this.capacity )
64
+
65
+ }
66
+
67
+ /** Multiplies AmygdalaHijack's effective threshold DOWN as budget runs low — depleted regulation capacity makes a hijack easier to trigger. */
68
+ getHijackThresholdMultiplier() {
69
+
70
+ return this.isDepleted() ? 1 - ( 1 - this.getLevel() ) * 0.4 : 1
71
+
72
+ }
73
+
74
+ /** Reappraisal/mature-defense capacity scales down with depletion — a real gate other modules can multiply their own capacity by. */
75
+ getRegulationCapacity() {
76
+
77
+ return this.getLevel()
78
+
79
+ }
80
+
81
+ }
@@ -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
+ }