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,266 @@
1
+ let nextId = 1
2
+
3
+ // Common function words — excluded from token-overlap matching so two unrelated
4
+ // sentences don't "match" just because both happen to contain "el"/"que"/"the".
5
+ // Real bug found via a two-personality REM conversation mock: an unrelated control
6
+ // message ("¿qué tal el tiempo hoy?") reactivated a months-old memory purely because
7
+ // both sentences contained "el", which isn't a topical match by any real measure.
8
+ const STOPWORDS = new Set( [
9
+ 'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas', 'de', 'del', 'a', 'al', 'en', 'y', 'o', 'que',
10
+ 'es', 'son', 'ser', 'esta', 'está', 'estan', 'están', 'con', 'por', 'para', 'se', 'su', 'sus', 'lo',
11
+ 'me', 'te', 'le', 'les', 'mi', 'tu', 'yo', 'no', 'si', 'sí', 'como', 'mas', 'más', 'pero', 'muy',
12
+ 'the', 'a', 'an', 'of', 'to', 'in', 'is', 'are', 'was', 'were', 'and', 'or', 'but', 'for', 'with',
13
+ 'this', 'that', 'it', 'i', 'you', 'he', 'she', 'we', 'they',
14
+ ] )
15
+
16
+ function tokenize( text ) {
17
+
18
+ return ( text || '' ).toLowerCase().match( /[\p{L}']+/gu ) || []
19
+
20
+ }
21
+
22
+ function significantTokens( text ) {
23
+
24
+ return tokenize( text ).filter( t => !STOPWORDS.has( t ) )
25
+
26
+ }
27
+
28
+ function clamp01( v ) {
29
+
30
+ return Math.max( 0, Math.min( 1, v ) )
31
+
32
+ }
33
+
34
+ /**
35
+ * Memories tagged with a full emotional signature (vector + label blend).
36
+ * Uses a simple in-memory keyword-overlap store by default. Pass an
37
+ * `adapter` ({ upsert(entry), query(text, topK) }) to back this with an
38
+ * external vector DB (Pinecone, Weaviate, ...) instead.
39
+ */
40
+ export class EpisodicMemory {
41
+
42
+ constructor( { adapter = null } = {} ) {
43
+
44
+ this.adapter = adapter
45
+ this.memories = []
46
+
47
+ }
48
+
49
+ async store( { text, userId, emotionalSignature, importance, concepts = [], turnIndex = null, surprise = 0, lifeEvent = null } ) {
50
+
51
+ const magnitude = Math.hypot( emotionalSignature?.valence ?? 0, emotionalSignature?.arousal ?? 0 ) / Math.SQRT2
52
+ const valence = emotionalSignature?.valence ?? 0
53
+ // Trauma consolidation: a surprising event (high |RPE|, from DopaminergicEngine)
54
+ // needs less raw magnitude to get permanently consolidated — a mundane strong
55
+ // emotion still requires real intensity, but a shocking one gets remembered
56
+ // more readily. Threshold shifts by up to 0.3 at full surprise; own tuning,
57
+ // not a reproduction of any specific consolidation/learning-rate schedule.
58
+ const permanenceThreshold = 0.9 - clamp01( surprise ) * 0.3
59
+ const entry = {
60
+ id : nextId++,
61
+ text,
62
+ userId,
63
+ concepts,
64
+ turnIndex,
65
+ emotionalSignature,
66
+ lifeEvent,
67
+ importance : importance ?? magnitude,
68
+ retention : 1,
69
+ permanent : magnitude > permanenceThreshold,
70
+ // A strongly negative, high-magnitude memory doesn't just decay away like
71
+ // a trivial one — it stays "unresolved" until something explicitly heals it
72
+ // (see Totemheart's guardedness handling and markResolved()). This is an
73
+ // engineering take on the everyday observation that unresolved negative
74
+ // experiences keep affecting behavior — not a citation of any specific
75
+ // trauma-processing formula. See CALIBRATION.md.
76
+ resolution : magnitude > 0.6 && valence < -0.2 ? 'unresolved' : 'resolved',
77
+ timestamp : Date.now(),
78
+ }
79
+
80
+ if ( this.adapter ) await this.adapter.upsert( entry )
81
+ else this.memories.push( entry )
82
+
83
+ return entry
84
+
85
+ }
86
+
87
+ markResolved( id ) {
88
+
89
+ const entry = this.memories.find( m => m.id === id )
90
+ if ( entry ) entry.resolution = 'resolved'
91
+
92
+ }
93
+
94
+ getUnresolvedMemories( userId = null, topK = 10 ) {
95
+
96
+ return this.memories
97
+ .filter( m => m.resolution === 'unresolved' && ( !userId || m.userId === userId ) )
98
+ .slice( 0, topK )
99
+
100
+ }
101
+
102
+ /**
103
+ * The Zeigarnik effect: an interrupted/unresolved thread doesn't fade
104
+ * with time the way an ordinary memory does — it keeps nagging, and if
105
+ * anything gets MORE prominent the longer it goes unaddressed, up to an
106
+ * asymptotic ceiling (own design, no citation — a bounded-growth curve
107
+ * with the right qualitative shape, not a reproduction of Zeigarnik's
108
+ * original experimental measurements). `k` is tuned so the curve is
109
+ * roughly two-thirds of the way to its ceiling after ~30 real minutes,
110
+ * the same real-world timescale HedonicAdaptation's cooldown uses.
111
+ */
112
+ getZeigarnikPriority( entry, now = Date.now(), k = 1 / ( 1000 * 60 * 27 ) ) {
113
+
114
+ const interruptedMs = Math.max( 0, now - entry.timestamp )
115
+ return entry.importance * ( 2 - Math.exp( -k * interruptedMs ) )
116
+
117
+ }
118
+
119
+ /** Total ambient pressure from every unresolved thread (optionally for one user) — feeds CortisolEngine. */
120
+ getZeigarnikPressure( userId = null, now = Date.now() ) {
121
+
122
+ return this.getUnresolvedMemories( userId, Infinity )
123
+ .reduce( ( sum, entry ) => sum + this.getZeigarnikPriority( entry, now ), 0 )
124
+
125
+ }
126
+
127
+ /** Milliseconds since the most recent memory tagged with `concept` for this user, or null if none. */
128
+ msSinceLastConcept( userId, concept, now = Date.now() ) {
129
+
130
+ const matches = this.memories.filter( m => m.userId === userId && m.concepts?.includes( concept ) )
131
+ if ( !matches.length ) return null
132
+
133
+ const mostRecent = matches.reduce( ( a, b ) => ( a.timestamp > b.timestamp ? a : b ) )
134
+ return now - mostRecent.timestamp
135
+
136
+ }
137
+
138
+ async recall( queryText, topK = 5 ) {
139
+
140
+ if ( this.adapter ) return await this.adapter.query( queryText, topK )
141
+
142
+ const queryTokens = new Set( tokenize( queryText ) )
143
+ return this.memories
144
+ .map( entry => {
145
+
146
+ const overlap = tokenize( entry.text ).filter( t => queryTokens.has( t ) ).length
147
+ const score = overlap * ( 0.5 + entry.retention ) * ( 0.5 + entry.importance )
148
+ return { entry, score }
149
+
150
+ } )
151
+ .filter( ( { score } ) => score > 0 )
152
+ .sort( ( a, b ) => b.score - a.score )
153
+ .slice( 0, topK )
154
+ .map( ( { entry } ) => entry )
155
+
156
+ }
157
+
158
+ /**
159
+ * Mood-congruent recall: real k-nearest-neighbors in emotional-signature
160
+ * space (not text). The state-dependent-memory effect (recalling sad
161
+ * things more readily while sad) falls out naturally from weighting
162
+ * distance in this space rather than needing a special-cased rule.
163
+ */
164
+ recallMoodCongruent( currentVector, topK = 5 ) {
165
+
166
+ const pool = this.adapter ? [] : this.memories // adapter-backed stores don't expose raw vectors to sort here
167
+ return pool
168
+ .map( entry => {
169
+
170
+ const sig = entry.emotionalSignature ?? { valence: 0, arousal: 0 }
171
+ const d = Math.hypot(
172
+ ( sig.valence ?? 0 ) - ( currentVector.valence ?? 0 ),
173
+ ( sig.arousal ?? 0 ) - ( currentVector.arousal ?? 0 ),
174
+ )
175
+ return { entry, score: 1 / ( 0.1 + d ) }
176
+
177
+ } )
178
+ .sort( ( a, b ) => b.score - a.score )
179
+ .slice( 0, topK )
180
+ .map( ( { entry } ) => entry )
181
+
182
+ }
183
+
184
+ /** Average valence of this user's `topK` most recent memories — the real "recent context" SarcasmDetector compares against. */
185
+ getRecentValence( userId, topK = 3 ) {
186
+
187
+ const recent = this.memories
188
+ .filter( m => m.userId === userId )
189
+ .slice( -topK )
190
+
191
+ if ( !recent.length ) return 0
192
+ return recent.reduce( ( sum, m ) => sum + ( m.emotionalSignature?.valence ?? 0 ), 0 ) / recent.length
193
+
194
+ }
195
+
196
+ /**
197
+ * Marks a memory as REM-consolidated "standout" — the raw material for a latent,
198
+ * slow-decaying salience distinct from `importance` (which never changes) and from
199
+ * `resolution` (which is binary). Only a REM sweep calls this, not every turn.
200
+ */
201
+ tagRemSalient( id, now = Date.now() ) {
202
+
203
+ const entry = this.memories.find( m => m.id === id )
204
+ if ( entry ) { entry.remSalient = true; entry.remTaggedAt = now }
205
+
206
+ }
207
+
208
+ /**
209
+ * Asymptotic decay toward a non-zero latent floor — an important REM-tagged memory
210
+ * never fully vanishes from relevance, it just goes quiet, real wall-clock time
211
+ * (not turns/ticks) since it was tagged. `lambda` default: ~45 real days to
212
+ * approach the floor. Own design, no citation (inspired by the general shape of
213
+ * memory-consolidation research — episodic traces stabilizing into more durable,
214
+ * lower-amplitude traces over time — not a reproduction of any specific model's
215
+ * numbers).
216
+ */
217
+ getLatentWeight( entry, now = Date.now(), lambda = 1 / ( 1000 * 60 * 60 * 24 * 45 ), floor = 0.05 ) {
218
+
219
+ if ( !entry.remSalient ) return 0
220
+ const elapsed = Math.max( 0, now - ( entry.remTaggedAt ?? entry.timestamp ) )
221
+ return entry.importance * Math.exp( -lambda * elapsed ) + floor
222
+
223
+ }
224
+
225
+ /**
226
+ * The "spark": real keyword-token overlap between this turn and a latent memory's
227
+ * text (same overlap technique `recall()` already uses, not embeddings unless a
228
+ * caller separately supplies one) multiplies the latent weight back up — a memory
229
+ * that's gone quiet for months can still resurface at real strength the instant a
230
+ * matching topic comes up again.
231
+ */
232
+ getReactivation( entry, tokens ) {
233
+
234
+ const entryTokens = new Set( significantTokens( entry.text ) )
235
+ const overlap = tokens.filter( t => !STOPWORDS.has( t ) && entryTokens.has( t ) ).length
236
+ if ( overlap === 0 ) return 0
237
+
238
+ return this.getLatentWeight( entry ) * ( 1 + overlap * 0.5 )
239
+
240
+ }
241
+
242
+ /** The single most-reactivated REM-salient memory for this turn's tokens, or null. */
243
+ getBestReactivation( tokens, now = Date.now() ) {
244
+
245
+ let best = null
246
+ let bestScore = 0
247
+ for ( const entry of this.memories ) {
248
+
249
+ if ( !entry.remSalient ) continue
250
+ const score = this.getReactivation( entry, tokens, now )
251
+ if ( score > bestScore ) { bestScore = score; best = entry }
252
+
253
+ }
254
+ return best ? { entry: best, score: bestScore } : null
255
+
256
+ }
257
+
258
+ getInfluentialMemories( topK = 5 ) {
259
+
260
+ return [ ...this.memories ]
261
+ .sort( ( a, b ) => b.importance - a.importance )
262
+ .slice( 0, topK )
263
+
264
+ }
265
+
266
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Fehr-Schmidt inequity aversion (Fehr, E. & Schmidt, K. M., 1999, "A Theory
3
+ * of Fairness, Competition, and Cooperation", Quarterly Journal of
4
+ * Economics): U_i(x) = x_i − α·max(x_j − x_i, 0) − β·max(x_i − x_j, 0).
5
+ * α (envy term) and β (guilt term) are the paper's own parameters; the
6
+ * typical fitted range (α > β, both ≥ 0) is used here as a default, not
7
+ * re-derived from data. Applied to how "treatment" (Attachment.affinity) is
8
+ * distributed across known users, instead of monetary payoffs — the
9
+ * mechanism is the same math, the domain is Totemheart's, not the paper's.
10
+ */
11
+ export class FairnessMonitor {
12
+
13
+ constructor( { alpha = 1.0, beta = 0.6 } = {} ) {
14
+
15
+ this.alpha = alpha // envy coefficient — pain from others having more
16
+ this.beta = beta // guilt coefficient — discomfort from having more than others
17
+
18
+ }
19
+
20
+ /** `ownTreatment` and `othersTreatment` (array) are affinity-like values in [0,1]. */
21
+ evaluate( ownTreatment, othersTreatment ) {
22
+
23
+ if ( !othersTreatment.length ) return { utility: ownTreatment, envy: 0, guilt: 0 }
24
+
25
+ const avgOther = othersTreatment.reduce( ( a, b ) => a + b, 0 ) / othersTreatment.length
26
+ const envy = this.alpha * Math.max( avgOther - ownTreatment, 0 )
27
+ const guilt = this.beta * Math.max( ownTreatment - avgOther, 0 )
28
+ const utility = ownTreatment - envy - guilt
29
+
30
+ return { utility, envy, guilt }
31
+
32
+ }
33
+
34
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Ebbinghaus (1885) forgetting curve: retention decays exponentially with
3
+ * time since encoding, and decays slower the more "stable" (rehearsed /
4
+ * salient) the memory is — R(t) = e^(-t/S). Ebbinghaus's original nonlinear
5
+ * curve was fit to his own memorized-syllable data, not to conversational
6
+ * emotional memory, so `stability` here is an engineering parameter tuned
7
+ * for this system's timescale, not a reproduction of his measured constants.
8
+ * Entries flagged `permanent` (emotional peak > 0.9, set by
9
+ * EpisodicMemory.store) bypass the curve entirely and never get pruned.
10
+ */
11
+ export class ForgettingCurve {
12
+
13
+ tick( episodicMemory, dt, { pruneBelow = 0.05, stability = 8 } = {} ) {
14
+
15
+ if ( episodicMemory.adapter ) return // external store manages its own retention
16
+
17
+ episodicMemory.memories = episodicMemory.memories.filter( entry => {
18
+
19
+ if ( entry.permanent ) return true
20
+
21
+ entry.retention *= Math.exp( -dt / ( stability * ( 1 + entry.importance ) ) )
22
+ return entry.retention > pruneBelow
23
+
24
+ } )
25
+
26
+ }
27
+
28
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Gratitude via credit assignment: when an unexpectedly positive outcome
3
+ * (high dopaminergic RPE) is attributed to a specific user (appraisal.agency
4
+ * === 'user'), that user's contribution gets an explicit credit signal —
5
+ * the real idea behind "solving the credit assignment problem" for a
6
+ * positive surprise, at the scale this library actually operates: crediting
7
+ * one attributed source, not backpropagating through a multi-step causal
8
+ * chain.
9
+ */
10
+ function clamp01( v ) {
11
+
12
+ return Math.max( 0, Math.min( 1, v ) )
13
+
14
+ }
15
+
16
+ export class GratitudeEngine {
17
+
18
+ /** Returns a gratitude spike + an extra Attachment credit boost, or null if this turn doesn't qualify. */
19
+ evaluate( { rpe, agency, desirability } ) {
20
+
21
+ const qualifies = agency === 'user' && rpe > 0.4 && desirability > 0.3
22
+ if ( !qualifies ) return null
23
+
24
+ const intensity = clamp01( rpe )
25
+ return {
26
+ spike : { valence: intensity * 0.4, arousal: intensity * 0.2, weight: 0.6 },
27
+ creditBoost : intensity * 0.1, // extra Attachment.affinity nudge, on top of the normal valence-driven update
28
+ }
29
+
30
+ }
31
+
32
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Retrospective self-evaluation. If the AI's own output was harsh while it
3
+ * was in a negative/high-arousal state, this raises a guilt signal that
4
+ * biases the *next* turn toward an apology.
5
+ */
6
+ export class GuiltEngine {
7
+
8
+ constructor() {
9
+
10
+ this.pendingApology = false
11
+
12
+ }
13
+
14
+ /**
15
+ * `loyaltyMultiplier` (default 1, own tuning up to 2 for a fully in-group
16
+ * user): failing someone the AI is close to costs more than failing a
17
+ * stranger — the tribal-loyalty asymmetry applies to the AI's own guilt,
18
+ * not just how it reads the user's behavior.
19
+ */
20
+ evaluate( emotionVector, selfCritiqueScore, threshold = 0.4, loyaltyMultiplier = 1 ) {
21
+
22
+ const wasNegativeAndAroused = emotionVector.valence < -0.2 && emotionVector.arousal > 0.3
23
+ const violated = selfCritiqueScore > threshold
24
+
25
+ if ( wasNegativeAndAroused && violated ) {
26
+
27
+ this.pendingApology = true
28
+ return { guiltTriggered: true, spike: { valence: -0.4 * loyaltyMultiplier, arousal: -0.1, weight: 0.6 * loyaltyMultiplier } }
29
+
30
+ }
31
+ return { guiltTriggered: false }
32
+
33
+ }
34
+
35
+ consumeApologyFlag() {
36
+
37
+ const flag = this.pendingApology
38
+ this.pendingApology = false
39
+ return flag
40
+
41
+ }
42
+
43
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Real Monte Carlo simulation (small N, appropriate to the scale of a
3
+ * conversational turn, not a large statistical study): to estimate what the
4
+ * other party might be feeling, run the AI's own appraisal-shaped evaluation
5
+ * N times with small random perturbations standing in for "I don't know
6
+ * their exact personality/mood, only a rough sense of it", and average the
7
+ * results — a real sampling-based estimate of empathic inference, not just a
8
+ * single point guess.
9
+ */
10
+ function clamp01( v ) {
11
+
12
+ return Math.max( 0, Math.min( 1, v ) )
13
+
14
+ }
15
+
16
+ export class MonteCarloToM {
17
+
18
+ constructor( { samples = 12 } = {} ) {
19
+
20
+ this.samples = samples
21
+
22
+ }
23
+
24
+ /**
25
+ * `baseValence` — the AI's own read of the event's valence (from its appraisal).
26
+ * `uncertainty` (0..1) — how little the AI knows about this specific person;
27
+ * higher uncertainty widens the perturbation spread across samples.
28
+ */
29
+ simulate( baseValence, uncertainty = 0.4 ) {
30
+
31
+ const draws = []
32
+ for ( let i = 0; i < this.samples; i++ ) {
33
+
34
+ const noise = ( Math.random() * 2 - 1 ) * uncertainty
35
+ draws.push( Math.max( -1, Math.min( 1, baseValence + noise ) ) )
36
+
37
+ }
38
+
39
+ const mean = draws.reduce( ( a, b ) => a + b, 0 ) / draws.length
40
+ const variance = draws.reduce( ( sum, v ) => sum + ( v - mean ) ** 2, 0 ) / draws.length
41
+
42
+ return {
43
+ estimatedValence : mean,
44
+ confidence : clamp01( 1 - Math.sqrt( variance ) ), // low spread across samples = more confident read
45
+ }
46
+
47
+ }
48
+
49
+ }
@@ -0,0 +1,45 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Tracks how the AI believes it is being perceived. A hit to perceived
9
+ * competence damages "ego health"; the reaction to that damage depends on
10
+ * personality — agreeable minds fold into shame (submission), the rest
11
+ * double down into wounded pride (which EgoProjection can turn into blame).
12
+ */
13
+ export class ReputationEngine {
14
+
15
+ constructor() {
16
+
17
+ this.egoHealth = 0.7
18
+
19
+ }
20
+
21
+ evaluate( appraisal, personality ) {
22
+
23
+ if ( appraisal.agency !== 'self' || appraisal.desirability >= -0.1 ) return { damaged: false }
24
+
25
+ const damage = Math.abs( appraisal.desirability ) * 0.3
26
+ this.egoHealth = clamp01( this.egoHealth - damage )
27
+
28
+ const reaction = personality.get( 'agreeableness' ) > 0.5 ? 'shame' : 'wounded_pride'
29
+ return { damaged: true, damage, reaction, egoHealth: this.egoHealth }
30
+
31
+ }
32
+
33
+ regenerate( dt, lambda = 0.02 ) {
34
+
35
+ this.egoHealth = clamp01( this.egoHealth + lambda * dt )
36
+
37
+ }
38
+
39
+ getEgoHealth() {
40
+
41
+ return this.egoHealth
42
+
43
+ }
44
+
45
+ }
@@ -0,0 +1,50 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Emergent self-awareness: instead of batch-analyzing history every N turns,
9
+ * each pattern's confidence is nudged toward 1 every time it's observed and
10
+ * decays slowly otherwise (an EMA, computed incrementally — no scheduled
11
+ * "reflection" step needed). "soy defensivo con crítica" becomes something
12
+ * the system can report on because it actually tracked it, not because an
13
+ * LLM was asked to guess. Pure engineering — no citation, see CALIBRATION.md.
14
+ */
15
+ export class SelfModel {
16
+
17
+ constructor() {
18
+
19
+ this.patterns = new Map()
20
+
21
+ }
22
+
23
+ reinforce( name, amount = 0.15 ) {
24
+
25
+ const current = this.patterns.get( name ) ?? 0
26
+ this.patterns.set( name, clamp01( current + amount * ( 1 - current ) ) )
27
+
28
+ }
29
+
30
+ decay( dt, lambda = 0.01 ) {
31
+
32
+ for ( const [ name, value ] of this.patterns ) this.patterns.set( name, Math.max( 0, value - lambda * dt ) )
33
+
34
+ }
35
+
36
+ get( name ) {
37
+
38
+ return this.patterns.get( name ) ?? 0
39
+
40
+ }
41
+
42
+ getDominant( threshold = 0.6 ) {
43
+
44
+ return [ ...this.patterns.entries() ]
45
+ .filter( ( [ , v ] ) => v >= threshold )
46
+ .sort( ( a, b ) => b[ 1 ] - a[ 1 ] )
47
+
48
+ }
49
+
50
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Envy/jealousy triggered by the *sign of the derivative* of relative
3
+ * status, not the absolute level — matching the real phenomenon that envy
4
+ * spikes when your standing is falling while a comparison target's is
5
+ * rising, not just from someone else generally having more. Status here is
6
+ * approximated by Attachment.powerDynamic (already tracked per user); this
7
+ * module only adds the trend comparison across two users' status.
8
+ */
9
+ export class StatusEnvy {
10
+
11
+ constructor() {
12
+
13
+ this.history = new Map() // userId -> last observed status
14
+
15
+ }
16
+
17
+ /** Call once per turn per known user with their current status (e.g. relation.powerDynamic). */
18
+ observe( userId, status ) {
19
+
20
+ const previous = this.history.get( userId )
21
+ this.history.set( userId, status )
22
+ return previous === undefined ? 0 : status - previous
23
+
24
+ }
25
+
26
+ /** Compares self's status trend against a rival's — positive envyTrigger = classic "falling while they rise". */
27
+ checkEnvy( selfTrend, rivalTrend ) {
28
+
29
+ const triggered = selfTrend < 0 && rivalTrend > 0
30
+ return { triggered, intensity: triggered ? Math.min( 1, Math.abs( selfTrend ) + rivalTrend ) : 0 }
31
+
32
+ }
33
+
34
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Per-user model of what the AI believes the user knows, feels and intends.
3
+ * Fed by LanguageProvider's 'mentalState' task (or the heuristic fallback),
4
+ * so the AI can react to inferred intent rather than just literal text.
5
+ */
6
+ export class TheoryOfMind {
7
+
8
+ constructor() {
9
+
10
+ this.models = new Map()
11
+
12
+ }
13
+
14
+ #entry( userId ) {
15
+
16
+ if ( !this.models.has( userId ) ) {
17
+
18
+ this.models.set( userId, { beliefs: new Map(), inferredEmotion: 'neutral', inferredIntent: null, valence: 0 } )
19
+
20
+ }
21
+ return this.models.get( userId )
22
+
23
+ }
24
+
25
+ update( userId, mentalState ) {
26
+
27
+ const entry = this.#entry( userId )
28
+ entry.inferredEmotion = mentalState.inferredEmotion ?? entry.inferredEmotion
29
+ entry.inferredIntent = mentalState.inferredIntent ?? entry.inferredIntent
30
+ entry.valence = mentalState.valence ?? entry.valence
31
+ return entry
32
+
33
+ }
34
+
35
+ updateBelief( userId, topic, belief ) {
36
+
37
+ this.#entry( userId ).beliefs.set( topic, belief )
38
+
39
+ }
40
+
41
+ getBeliefAbout( userId, topic ) {
42
+
43
+ return this.#entry( userId ).beliefs.get( topic ) ?? 'No information'
44
+
45
+ }
46
+
47
+ getModel( userId ) {
48
+
49
+ return this.#entry( userId )
50
+
51
+ }
52
+
53
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Buckets a user into in-group/out-group based on accrued Attachment
3
+ * affinity. In-group gets the benefit of the doubt (confirmation bias
4
+ * toward the positive); out-group gets systemic skepticism.
5
+ */
6
+ export class TribalCategorization {
7
+
8
+ classify( relation, { inThreshold = 0.65, outThreshold = 0.35 } = {} ) {
9
+
10
+ if ( relation.affinity >= inThreshold ) return 'ingroup'
11
+ if ( relation.affinity <= outThreshold ) return 'outgroup'
12
+ return 'neutral'
13
+
14
+ }
15
+
16
+ biasMultiplier( group, desirability ) {
17
+
18
+ if ( group === 'ingroup' ) return desirability >= 0 ? 1.3 : 0.6
19
+ if ( group === 'outgroup' ) return desirability >= 0 ? 0.6 : 1.3
20
+ return 1
21
+
22
+ }
23
+
24
+ }