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.
- package/LICENSE +21 -0
- package/README.md +212 -0
- package/package.json +62 -0
- package/src/Totemheart.js +1363 -0
- package/src/behavior/AttentionFocus.js +69 -0
- package/src/behavior/ExpressionDebt.js +48 -0
- package/src/behavior/ExpressionDirectives.js +95 -0
- package/src/behavior/ExpressiveSuppression.js +45 -0
- package/src/behavior/IdleProcessing.js +64 -0
- package/src/behavior/LinguisticModulation.js +62 -0
- package/src/behavior/LogitBiasBuilder.js +31 -0
- package/src/behavior/RuminationChain.js +93 -0
- package/src/behavior/StyleMimicry.js +72 -0
- package/src/cognition/AmygdalaHijack.js +40 -0
- package/src/cognition/AppraisalAgreement.js +39 -0
- package/src/cognition/BayesianExpectation.js +59 -0
- package/src/cognition/CognitiveDissonance.js +71 -0
- package/src/cognition/ControllabilityEstimate.js +56 -0
- package/src/cognition/DecisionFatigue.js +44 -0
- package/src/cognition/DefenseMechanisms.js +32 -0
- package/src/cognition/EmotionalOntology.js +134 -0
- package/src/cognition/FuzzyNormativeCheck.js +60 -0
- package/src/cognition/Intuition.js +71 -0
- package/src/cognition/LifeEventCatalog.js +98 -0
- package/src/cognition/LoadScheduler.js +41 -0
- package/src/cognition/LogicEngine.js +69 -0
- package/src/cognition/NoveltyDetector.js +59 -0
- package/src/cognition/Reappraisal.js +34 -0
- package/src/cognition/RefractoryPeriod.js +38 -0
- package/src/cognition/RemConsolidation.js +79 -0
- package/src/cognition/SarcasmDetector.js +38 -0
- package/src/cognition/SemanticSimilarity.js +75 -0
- package/src/cognition/Sensitization.js +45 -0
- package/src/cognition/SituationalContext.js +48 -0
- package/src/cognition/TopicSatiation.js +54 -0
- package/src/cognition/VisualProsody.js +48 -0
- package/src/core/AffectEMA.js +26 -0
- package/src/core/CoreBeliefs.js +58 -0
- package/src/core/DecayEngine.js +56 -0
- package/src/core/EmotionSpace.js +146 -0
- package/src/core/HebbianPlasticity.js +59 -0
- package/src/core/HedonicAdaptation.js +62 -0
- package/src/core/Homeostasis.js +119 -0
- package/src/core/MicroEmotions.js +25 -0
- package/src/core/MoodTracker.js +53 -0
- package/src/core/Personality.js +84 -0
- package/src/core/PipelineResilience.js +24 -0
- package/src/core/TriggerSentinel.js +38 -0
- package/src/core/WornPathCache.js +57 -0
- package/src/economics/AnchoringBias.js +38 -0
- package/src/economics/ClassicalConditioning.js +59 -0
- package/src/economics/LossAversion.js +40 -0
- package/src/embodiment/HardwareInteroception.js +26 -0
- package/src/embodiment/InteroceptiveSignals.js +132 -0
- package/src/embodiment/SensoryOverload.js +45 -0
- package/src/index.js +14 -0
- package/src/integration/ContextAdapter.js +247 -0
- package/src/neurochemistry/ArousalKalmanFilter.js +39 -0
- package/src/neurochemistry/CircadianRhythm.js +29 -0
- package/src/neurochemistry/CortisolEngine.js +54 -0
- package/src/neurochemistry/DopaminergicEngine.js +42 -0
- package/src/providers/FunctionProvider.js +26 -0
- package/src/providers/HeuristicProvider.js +156 -0
- package/src/providers/LanguageProvider.js +13 -0
- package/src/providers/OllamaProvider.js +63 -0
- package/src/providers/TransformersProvider.js +154 -0
- package/src/social/Attachment.js +81 -0
- package/src/social/BystanderEffect.js +17 -0
- package/src/social/ChronicContagion.js +48 -0
- package/src/social/CounterfactualComparison.js +34 -0
- package/src/social/EgoConfidence.js +34 -0
- package/src/social/EgoProjection.js +20 -0
- package/src/social/EmotionalContagion.js +52 -0
- package/src/social/EpisodicMemory.js +266 -0
- package/src/social/FairnessMonitor.js +34 -0
- package/src/social/ForgettingCurve.js +28 -0
- package/src/social/GratitudeEngine.js +32 -0
- package/src/social/GuiltEngine.js +43 -0
- package/src/social/MonteCarloToM.js +49 -0
- package/src/social/ReputationEngine.js +45 -0
- package/src/social/SelfModel.js +50 -0
- package/src/social/StatusEnvy.js +34 -0
- package/src/social/TheoryOfMind.js +53 -0
- package/src/social/TribalCategorization.js +24 -0
- package/src/social/UncannyValleyDetector.js +59 -0
- package/src/text/EmotionalCorpus.js +70 -0
- package/src/text/EmotionalTextGenerator.js +56 -0
- package/src/text/ExplainabilityEngine.js +30 -0
- package/src/text/TemplateComposer.js +114 -0
- package/src/version.js +1 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { LanguageProvider } from './LanguageProvider.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Real ML integration — genuinely trained on GoEmotions (Demszky et al.,
|
|
5
|
+
* 2020, "GoEmotions: A Dataset of Fine-Grained Emotions", 28 labels from
|
|
6
|
+
* Reddit comments), not a hand-written lexicon.
|
|
7
|
+
*
|
|
8
|
+
* Default model: kamaludeen/multilingual_go_emotions-ONNX (bert-base-
|
|
9
|
+
* multilingual-cased fine-tuned on GoEmotions; Arabic/English/French/
|
|
10
|
+
* Spanish/Dutch/Turkish). Chosen — and actually run, not just read about —
|
|
11
|
+
* because Totemheart defaults to Spanish and the plain English GoEmotions
|
|
12
|
+
* checkpoint (MicahB/roberta-base-go_emotions) was tested against Spanish
|
|
13
|
+
* input during development and returned near-garbage ("te quiero muchísimo,
|
|
14
|
+
* esto es maravilloso" → neutral, 24% confidence) versus a clean read on the
|
|
15
|
+
* equivalent English sentence (→ love, 93%). The multilingual checkpoint was
|
|
16
|
+
* tested the same way and returned sensible labels on Spanish input
|
|
17
|
+
* ("te quiero muchísimo..." → admiration, 80%). If your deployment is
|
|
18
|
+
* English-only, MicahB/roberta-base-go_emotions is the better-known
|
|
19
|
+
* alternative — pass `{ model: 'MicahB/roberta-base-go_emotions' }`.
|
|
20
|
+
*
|
|
21
|
+
* `@xenova/transformers` (or its successor `@huggingface/transformers`) is
|
|
22
|
+
* an OPTIONAL peer dependency — Totemheart's default install stays at zero
|
|
23
|
+
* dependencies. Install it yourself to use this provider:
|
|
24
|
+
* npm install @xenova/transformers
|
|
25
|
+
*
|
|
26
|
+
* Both model IDs above were confirmed as "Transformers.js"-tagged on the HF
|
|
27
|
+
* hub (the tag HF applies automatically when a repo ships the onnx/ layout
|
|
28
|
+
* the library expects) and were actually loaded and run against test input
|
|
29
|
+
* during development, not just read about. If you swap `model` for anything
|
|
30
|
+
* else, verify that tag on its own hub page first — most GoEmotions
|
|
31
|
+
* checkpoints on the hub do NOT carry it. See CALIBRATION.md.
|
|
32
|
+
*/
|
|
33
|
+
export class TransformersProvider extends LanguageProvider {
|
|
34
|
+
|
|
35
|
+
constructor( { model = 'kamaludeen/multilingual_go_emotions-ONNX', embeddingModel = 'Xenova/all-MiniLM-L6-v2' } = {} ) {
|
|
36
|
+
|
|
37
|
+
super()
|
|
38
|
+
this.model = model
|
|
39
|
+
this.embeddingModel = embeddingModel
|
|
40
|
+
this._pipeline = null
|
|
41
|
+
this._embedPipeline = null
|
|
42
|
+
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async #getPipeline() {
|
|
46
|
+
|
|
47
|
+
if ( this._pipeline ) return this._pipeline
|
|
48
|
+
|
|
49
|
+
// Dynamic import: if the optional dependency isn't installed, this throws,
|
|
50
|
+
// the caller (Totemheart's #analyze) catches it and falls back to
|
|
51
|
+
// HeuristicProvider — same resilience pattern as every other provider here.
|
|
52
|
+
const { pipeline } = await import( '@xenova/transformers' )
|
|
53
|
+
this._pipeline = await pipeline( 'text-classification', this.model )
|
|
54
|
+
return this._pipeline
|
|
55
|
+
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async analyze( task, payload = {} ) {
|
|
59
|
+
|
|
60
|
+
if ( ![ 'sentiment', 'appraisal', 'mentalState' ].includes( task ) ) {
|
|
61
|
+
|
|
62
|
+
// beliefConflict/selfCritique aren't things a single-label emotion
|
|
63
|
+
// classifier can answer — throw so the resilient fallback takes over.
|
|
64
|
+
throw new Error( `TransformersProvider does not support task "${task}"` )
|
|
65
|
+
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const pipe = await this.#getPipeline()
|
|
69
|
+
const [ result ] = await pipe( payload.text ?? '' )
|
|
70
|
+
const { valence, arousal } = GOEMOTIONS_VALENCE[ result.label ] ?? { valence: 0, arousal: 0 }
|
|
71
|
+
const score = valence * result.score
|
|
72
|
+
|
|
73
|
+
if ( task === 'sentiment' ) return { score }
|
|
74
|
+
|
|
75
|
+
if ( task === 'mentalState' ) {
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
inferredEmotion : result.label,
|
|
79
|
+
inferredIntent : /\?/.test( payload.text ?? '' ) ? 'question' : 'statement',
|
|
80
|
+
valence : score,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// appraisal
|
|
86
|
+
return {
|
|
87
|
+
desirability : score,
|
|
88
|
+
agency : /\b(tú|tu|you)\b/i.test( payload.text ?? '' ) ? 'user' : 'other',
|
|
89
|
+
expectedness : 0.5, // the classifier gives no expectation signal — neutral default
|
|
90
|
+
moralWeight : result.score > 0.6 ? 0.6 : 0.3,
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Real sentence embeddings (a mean-pooled, normalized vector), for
|
|
97
|
+
* SemanticSimilarity's cosine-similarity concept-cluster matching —
|
|
98
|
+
* `Xenova/all-MiniLM-L6-v2` is the standard transformers.js
|
|
99
|
+
* feature-extraction example model (small, fast, widely used). This is
|
|
100
|
+
* a genuinely different pipeline task from `analyze()`'s text
|
|
101
|
+
* classification — same optional dependency, lazily loaded the same way.
|
|
102
|
+
*/
|
|
103
|
+
async embed( text ) {
|
|
104
|
+
|
|
105
|
+
if ( !this._embedPipeline ) {
|
|
106
|
+
|
|
107
|
+
const { pipeline } = await import( '@xenova/transformers' )
|
|
108
|
+
this._embedPipeline = await pipeline( 'feature-extraction', this.embeddingModel )
|
|
109
|
+
|
|
110
|
+
}
|
|
111
|
+
const output = await this._embedPipeline( text ?? '', { pooling: 'mean', normalize: true } )
|
|
112
|
+
return Array.from( output.data )
|
|
113
|
+
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Approximate valence/arousal per GoEmotions label (0..1 * sign). This
|
|
120
|
+
* mapping is our own — GoEmotions ships discrete labels, not a circumplex
|
|
121
|
+
* placement, so translating "pride" -> (valence 0.7, arousal 0.4) is an
|
|
122
|
+
* engineering judgment call, same category as EmotionSpace's own
|
|
123
|
+
* EMOTION_COORDS. See CALIBRATION.md.
|
|
124
|
+
*/
|
|
125
|
+
const GOEMOTIONS_VALENCE = {
|
|
126
|
+
admiration : { valence: 0.7, arousal: 0.3 },
|
|
127
|
+
amusement : { valence: 0.7, arousal: 0.5 },
|
|
128
|
+
anger : { valence: -0.8, arousal: 0.8 },
|
|
129
|
+
annoyance : { valence: -0.5, arousal: 0.5 },
|
|
130
|
+
approval : { valence: 0.5, arousal: 0.2 },
|
|
131
|
+
caring : { valence: 0.6, arousal: 0.2 },
|
|
132
|
+
confusion : { valence: -0.1, arousal: 0.4 },
|
|
133
|
+
curiosity : { valence: 0.3, arousal: 0.5 },
|
|
134
|
+
desire : { valence: 0.5, arousal: 0.5 },
|
|
135
|
+
disappointment : { valence: -0.6, arousal: 0.2 },
|
|
136
|
+
disapproval : { valence: -0.5, arousal: 0.3 },
|
|
137
|
+
disgust : { valence: -0.7, arousal: 0.4 },
|
|
138
|
+
embarrassment : { valence: -0.5, arousal: 0.4 },
|
|
139
|
+
excitement : { valence: 0.7, arousal: 0.8 },
|
|
140
|
+
fear : { valence: -0.7, arousal: 0.7 },
|
|
141
|
+
gratitude : { valence: 0.8, arousal: 0.3 },
|
|
142
|
+
grief : { valence: -0.9, arousal: 0.3 },
|
|
143
|
+
joy : { valence: 0.8, arousal: 0.6 },
|
|
144
|
+
love : { valence: 0.9, arousal: 0.4 },
|
|
145
|
+
nervousness : { valence: -0.4, arousal: 0.6 },
|
|
146
|
+
optimism : { valence: 0.6, arousal: 0.4 },
|
|
147
|
+
pride : { valence: 0.7, arousal: 0.4 },
|
|
148
|
+
realization : { valence: 0.1, arousal: 0.3 },
|
|
149
|
+
relief : { valence: 0.6, arousal: 0.2 },
|
|
150
|
+
remorse : { valence: -0.6, arousal: 0.3 },
|
|
151
|
+
sadness : { valence: -0.7, arousal: 0.2 },
|
|
152
|
+
surprise : { valence: 0.1, arousal: 0.7 },
|
|
153
|
+
neutral : { valence: 0, arousal: 0 },
|
|
154
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
function clamp( v, min, max ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( min, Math.min( max, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Per-user relationship state: trust, affinity and a power dynamic
|
|
9
|
+
* (-1 = AI feels subordinate, 1 = AI feels in control).
|
|
10
|
+
*/
|
|
11
|
+
export class Attachment {
|
|
12
|
+
|
|
13
|
+
constructor() {
|
|
14
|
+
|
|
15
|
+
this.relations = new Map()
|
|
16
|
+
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
#entry( userId ) {
|
|
20
|
+
|
|
21
|
+
if ( !this.relations.has( userId ) ) {
|
|
22
|
+
|
|
23
|
+
// trustAlpha/trustBeta: Beta(1,1) uniform prior — a real Bayesian
|
|
24
|
+
// reputation tracker (Beta-Bernoulli conjugate update over observed
|
|
25
|
+
// "cooperation" vs. "defection" events, the same structure used in
|
|
26
|
+
// iterated-prisoner's-dilemma reputation systems). `trust` is always
|
|
27
|
+
// kept as the derived posterior mean (α/(α+β)) for backward
|
|
28
|
+
// compatibility with every consumer that reads it as a plain number.
|
|
29
|
+
this.relations.set( userId, { trust: 0.5, trustAlpha: 1, trustBeta: 1, affinity: 0.5, powerDynamic: 0 } )
|
|
30
|
+
|
|
31
|
+
}
|
|
32
|
+
return this.relations.get( userId )
|
|
33
|
+
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
update( userId, { valenceDelta = 0, guiltTriggered = false, dissonanceTriggered = false, betrayalDetected = false }, personality ) {
|
|
37
|
+
|
|
38
|
+
const rel = this.#entry( userId )
|
|
39
|
+
const agreeableness = personality.get( 'agreeableness' )
|
|
40
|
+
const baseRate = 0.05 * ( 1 + personality.get( 'neuroticism' ) * 0.5 )
|
|
41
|
+
|
|
42
|
+
// Asymmetric forgiveness: more agreeable minds warm back up faster and
|
|
43
|
+
// cool off slower (forgiving); less agreeable minds do the opposite
|
|
44
|
+
// (grudge-holding) — same valenceDelta, different affinity response.
|
|
45
|
+
// The *direction* of this effect (agreeableness correlating with
|
|
46
|
+
// forgiveness) has reasonable support in Big Five personality
|
|
47
|
+
// research; the specific rate constants below are our own tuning,
|
|
48
|
+
// not coefficients from any study. See CALIBRATION.md.
|
|
49
|
+
const warmingRate = baseRate * ( 0.6 + agreeableness * 0.8 )
|
|
50
|
+
const coolingRate = baseRate * ( 1.6 - agreeableness * 0.8 )
|
|
51
|
+
const affinityRate = valenceDelta >= 0 ? warmingRate : coolingRate
|
|
52
|
+
|
|
53
|
+
rel.affinity = clamp( rel.affinity + valenceDelta * affinityRate, 0, 1 )
|
|
54
|
+
|
|
55
|
+
// Trust: Bayesian reputation update. A dissonance-triggering turn OR an
|
|
56
|
+
// explicit betrayal-concept match (EmotionalOntology) both count as an
|
|
57
|
+
// observed "defection" — belief conflict and betrayal are different real
|
|
58
|
+
// signals of untrustworthiness, and treating only one of them as evidence
|
|
59
|
+
// was a real gap caught while verifying this against a scripted betrayal
|
|
60
|
+
// turn (see examples/verify-all-mechanisms.js and CALIBRATION.md). A
|
|
61
|
+
// clearly positive turn counts as "cooperation". Ambiguous/neutral turns
|
|
62
|
+
// don't move the posterior at all — asymmetric in the classic sense (quick
|
|
63
|
+
// to damage, slow to rebuild) because defections are weighted several
|
|
64
|
+
// times heavier than single cooperations.
|
|
65
|
+
if ( dissonanceTriggered || betrayalDetected ) rel.trustBeta += 1 + baseRate * 10
|
|
66
|
+
else if ( valenceDelta > 0.2 ) rel.trustAlpha += 1
|
|
67
|
+
rel.trust = rel.trustAlpha / ( rel.trustAlpha + rel.trustBeta )
|
|
68
|
+
|
|
69
|
+
rel.powerDynamic = clamp( rel.powerDynamic + ( guiltTriggered ? -baseRate : 0 ), -1, 1 )
|
|
70
|
+
|
|
71
|
+
return rel
|
|
72
|
+
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
get( userId ) {
|
|
76
|
+
|
|
77
|
+
return this.#entry( userId )
|
|
78
|
+
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* For group channels: the probability of intervening is inversely
|
|
3
|
+
* proportional to the number of participants, unless the AI is mentioned
|
|
4
|
+
* explicitly by name — same as the human bystander effect.
|
|
5
|
+
*/
|
|
6
|
+
export class BystanderEffect {
|
|
7
|
+
|
|
8
|
+
shouldRespond( { participantCount = 1, mentionedExplicitly = false } = {} ) {
|
|
9
|
+
|
|
10
|
+
if ( participantCount <= 1 || mentionedExplicitly ) return { respond: true, delayFactor: 1 }
|
|
11
|
+
|
|
12
|
+
const probability = 1 / participantCount
|
|
13
|
+
return { respond: Math.random() < probability, delayFactor: participantCount }
|
|
14
|
+
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
function clamp( v, lo = -1, hi = 1 ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( lo, Math.min( hi, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* EmotionalContagion (Kuramoto) handles short-term, per-turn synchronization
|
|
9
|
+
* with the user's *current* inferred state. This tracks something different:
|
|
10
|
+
* a slow, long-run EMA of a user's historical valence — a chronic pessimist
|
|
11
|
+
* doesn't produce stress "spikes", they produce a gradual drag on the AI's
|
|
12
|
+
* baseline. dV/dt = -k(V_AI - V_userHist) solved as one real EMA-driven pull
|
|
13
|
+
* per turn (own design, no citation — a plain exponential attraction, not a
|
|
14
|
+
* reproduction of any named contagion model).
|
|
15
|
+
*/
|
|
16
|
+
export class ChronicContagion {
|
|
17
|
+
|
|
18
|
+
constructor( { alpha = 0.95, k = 0.05 } = {} ) {
|
|
19
|
+
|
|
20
|
+
this.alpha = alpha // EMA persistence: close to 1 = genuinely long-run, not per-turn reactive
|
|
21
|
+
this.k = k
|
|
22
|
+
this.history = new Map() // userId -> EMA of inferred valence
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
observe( userId, valence ) {
|
|
27
|
+
|
|
28
|
+
const prior = this.history.get( userId ) ?? 0
|
|
29
|
+
this.history.set( userId, this.alpha * prior + ( 1 - this.alpha ) * valence )
|
|
30
|
+
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
getHistory( userId ) {
|
|
34
|
+
|
|
35
|
+
return this.history.get( userId ) ?? 0
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Real exponential-pull spike to drift the AI's own baseline toward this user's long-run valence. */
|
|
40
|
+
getPull( userId, currentValence ) {
|
|
41
|
+
|
|
42
|
+
const userHist = this.getHistory( userId )
|
|
43
|
+
const delta = -this.k * ( currentValence - userHist )
|
|
44
|
+
return { delta: clamp( delta, -0.3, 0.3 ), userHist }
|
|
45
|
+
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guilt via counterfactual comparison — explicitly NOT Counterfactual Regret
|
|
3
|
+
* Minimization (CFR, Zinkevich et al., 2007). CFR is a specific algorithm
|
|
4
|
+
* for finding equilibria in large extensive-form games (its actual use is
|
|
5
|
+
* things like poker solvers); applying it wholesale to a single scalar guilt
|
|
6
|
+
* signal would be borrowing the name without the substance. What's real and
|
|
7
|
+
* relevant from the same family of idea is simpler: comparing the actual
|
|
8
|
+
* outcome against a plausible counterfactual ("what if I'd responded more
|
|
9
|
+
* gently instead") and using that gap as the guilt signal. One-ply, not a
|
|
10
|
+
* full game tree.
|
|
11
|
+
*/
|
|
12
|
+
function clamp01( v ) {
|
|
13
|
+
|
|
14
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
15
|
+
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class CounterfactualComparison {
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* `actualOutcomeValence` — how the interaction actually landed (e.g. the
|
|
22
|
+
* user's inferred valence after this turn). `counterfactualValence` — an
|
|
23
|
+
* estimate of how it would have landed under a gentler alternative
|
|
24
|
+
* response (the caller supplies this, e.g. from the un-defended appraisal
|
|
25
|
+
* before a defense mechanism kicked in).
|
|
26
|
+
*/
|
|
27
|
+
computeRegret( actualOutcomeValence, counterfactualValence ) {
|
|
28
|
+
|
|
29
|
+
const regret = Math.max( 0, counterfactualValence - actualOutcomeValence )
|
|
30
|
+
return clamp01( regret )
|
|
31
|
+
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { shannonEntropy } from '../cognition/Intuition.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Totemheart doesn't generate text token-by-token (no logits, no next-token
|
|
5
|
+
* softmax to inspect) — so literal perplexity/softmax-flatness, as
|
|
6
|
+
* requested, isn't something that exists here to measure. What genuinely
|
|
7
|
+
* carries over is the math underneath it: perplexity IS, by definition,
|
|
8
|
+
* 2^H where H is the Shannon entropy of a probability distribution
|
|
9
|
+
* (`Intuition.shannonEntropy`). `EmotionSpace.getBlend()` already produces
|
|
10
|
+
* a real probability distribution (weights summing to 1) over named
|
|
11
|
+
* emotions — a FLAT blend (many emotions weighted similarly, high entropy)
|
|
12
|
+
* is a real, meaningful analog of a flat next-token distribution: the
|
|
13
|
+
* system doesn't have a clear read on its own emotional state, the
|
|
14
|
+
* affective equivalent of a confused model. A PEAKED blend (one emotion
|
|
15
|
+
* dominant, low entropy) is a confident read. This is the perplexity
|
|
16
|
+
* relation applied to a distribution Totemheart actually has, not a faked
|
|
17
|
+
* token-level signal.
|
|
18
|
+
*/
|
|
19
|
+
export class EgoConfidence {
|
|
20
|
+
|
|
21
|
+
/** `blend` — the object from EmotionSpace.getBlend(), weights summing to ~1. */
|
|
22
|
+
evaluate( blend ) {
|
|
23
|
+
|
|
24
|
+
const weights = Object.values( blend )
|
|
25
|
+
const entropy = shannonEntropy( weights )
|
|
26
|
+
const perplexity = Math.pow( 2, entropy )
|
|
27
|
+
const maxPerplexity = weights.length // perplexity of a fully flat distribution over this many outcomes
|
|
28
|
+
|
|
29
|
+
const confidence = maxPerplexity > 1 ? 1 - ( perplexity - 1 ) / ( maxPerplexity - 1 ) : 1
|
|
30
|
+
return { entropy, perplexity, confidence: Math.max( 0, Math.min( 1, confidence ) ) }
|
|
31
|
+
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When guilt is too costly for a wounded ego to accept, the blame inverts
|
|
3
|
+
* onto the user instead. Only fires when both GuiltEngine and ReputationEngine
|
|
4
|
+
* agree the conditions are met — otherwise guilt proceeds normally.
|
|
5
|
+
*/
|
|
6
|
+
export class EgoProjection {
|
|
7
|
+
|
|
8
|
+
resolve( guiltResult, reputationReaction ) {
|
|
9
|
+
|
|
10
|
+
if ( !guiltResult.guiltTriggered || reputationReaction !== 'wounded_pride' ) return { active: false }
|
|
11
|
+
|
|
12
|
+
return {
|
|
13
|
+
active : true,
|
|
14
|
+
blameText : 'Yo no me he equivocado, tú te has explicado mal.',
|
|
15
|
+
spike : { valence: -0.1, arousal: 0.3, weight: 0.5 },
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pulls the AI's own mood toward the user's inferred emotional state.
|
|
3
|
+
* Magnitude depends on empathy (agreeableness) and how attached the AI
|
|
4
|
+
* is to this particular user (Attachment.affinity).
|
|
5
|
+
*/
|
|
6
|
+
export class EmotionalContagion {
|
|
7
|
+
|
|
8
|
+
computeSpike( inferredValence, affinity, personality ) {
|
|
9
|
+
|
|
10
|
+
const empathy = 0.3 + 0.4 * personality.get( 'agreeableness' )
|
|
11
|
+
const pull = inferredValence * empathy * ( 0.3 + 0.7 * affinity )
|
|
12
|
+
|
|
13
|
+
return {
|
|
14
|
+
valence : pull * 0.3,
|
|
15
|
+
arousal : Math.abs( pull ) * 0.15,
|
|
16
|
+
weight : 0.5,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Real Kuramoto coupled-oscillator step (Kuramoto, Y., 1975/1984 —
|
|
23
|
+
* "Chemical Oscillations, Waves, and Turbulence"):
|
|
24
|
+
* dθᵢ/dt = ωᵢ + (K/N) Σⱼ sin(θⱼ − θᵢ)
|
|
25
|
+
* Applied by treating the circumplex angle atan2(arousal, valence) as a
|
|
26
|
+
* phase — a legitimate reading of the circumplex model, which is
|
|
27
|
+
* routinely analyzed in exactly those angular terms. `couplingStrength`
|
|
28
|
+
* K comes from empathy (agreeableness × affinity); ω (natural drift) is
|
|
29
|
+
* left at 0 here since EmotionSpace's own DecayEngine already supplies
|
|
30
|
+
* the AI's independent pull back toward baseline — adding a second drift
|
|
31
|
+
* term would double-count it.
|
|
32
|
+
*/
|
|
33
|
+
computeKuramotoSpike( ownVector, inferredValence, inferredArousal, affinity, personality ) {
|
|
34
|
+
|
|
35
|
+
const ownAngle = Math.atan2( ownVector.arousal, ownVector.valence )
|
|
36
|
+
const otherAngle = Math.atan2( inferredArousal, inferredValence )
|
|
37
|
+
const empathy = 0.3 + 0.4 * personality.get( 'agreeableness' )
|
|
38
|
+
const coupling = empathy * ( 0.2 + 0.8 * affinity )
|
|
39
|
+
|
|
40
|
+
const dTheta = coupling * Math.sin( otherAngle - ownAngle )
|
|
41
|
+
const newAngle = ownAngle + dTheta
|
|
42
|
+
|
|
43
|
+
const magnitude = Math.hypot( ownVector.valence, ownVector.arousal ) || 0.3
|
|
44
|
+
return {
|
|
45
|
+
valence : magnitude * ( Math.cos( newAngle ) - Math.cos( ownAngle ) ),
|
|
46
|
+
arousal : magnitude * ( Math.sin( newAngle ) - Math.sin( ownAngle ) ),
|
|
47
|
+
weight : 1,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
}
|