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,38 @@
1
+ /**
2
+ * Honest version of a "sparse activation router": the proposal's literal
3
+ * form (Mt = σ(Wr·Embedding(Xt) + θ)) needs trained router weights Wr —
4
+ * there's no labeled dataset or training loop in this environment to
5
+ * produce those honestly, so fabricating a JSON of "learned" weights would
6
+ * be exactly the kind of simulation this project refuses to do. What's real
7
+ * and buildable instead: a cheap keyword/regex + prior-state-residual gate,
8
+ * checked BEFORE a secondary mechanism's actual computation runs. A rule
9
+ * with no keywords and no residual check always activates (a primary layer
10
+ * that should always run).
11
+ */
12
+ export class TriggerSentinel {
13
+
14
+ constructor( rules = {} ) {
15
+
16
+ this.rules = rules // name -> { keywords?: string[], residualThreshold?: number }
17
+
18
+ }
19
+
20
+ /**
21
+ * `tokens` — this turn's tokenized input. `residual` — the mechanism's own
22
+ * carried-over state magnitude (e.g. ExpressionDebt.debt), compared against
23
+ * its own residualThreshold. Fires on keyword match OR residual carryover
24
+ * exceeding threshold; a mechanism with no rule registered is always active.
25
+ */
26
+ check( name, tokens = [], residual = 0 ) {
27
+
28
+ const rule = this.rules[ name ]
29
+ if ( !rule ) return { active: true, reason: 'no-rule' }
30
+
31
+ const keywordHit = rule.keywords?.some( k => tokens.includes( k ) ) ?? false
32
+ const residualHit = rule.residualThreshold !== undefined && residual > rule.residualThreshold
33
+
34
+ return { active: keywordHit || residualHit, reason: keywordHit ? 'keyword' : residualHit ? 'residual' : 'none' }
35
+
36
+ }
37
+
38
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * "Runtime-evolutionary architecture that rewrites hot paths into static
3
+ * functions" reframed honestly: Totemheart cannot rewrite its own source at
4
+ * runtime, and doesn't need to — the real, buildable version of this idea is
5
+ * memoization. A fingerprint (same input shape + emotional context) seen
6
+ * often enough stops paying for a fresh appraisal/ontology pass and reuses
7
+ * the last one — the pipeline "stabilizes" around familiar interactions
8
+ * instead of recomputing them from scratch every time, without skipping the
9
+ * parts that must still run fresh every turn (spike application, decay,
10
+ * memory). Engineering technique (memoization with a promotion threshold),
11
+ * not a literal self-rewriting graph compiler.
12
+ */
13
+ export class WornPathCache {
14
+
15
+ constructor( { promotionThreshold = 5, maxEntries = 200 } = {} ) {
16
+
17
+ this.promotionThreshold = promotionThreshold
18
+ this.maxEntries = maxEntries
19
+ this.entries = new Map() // fingerprint -> { count, appraisal }
20
+
21
+ }
22
+
23
+ /** Returns the cached appraisal if this fingerprint has been "worn in", else null. */
24
+ consult( fingerprint ) {
25
+
26
+ const entry = this.entries.get( fingerprint )
27
+ if ( entry && entry.count >= this.promotionThreshold ) return entry.appraisal
28
+ return null
29
+
30
+ }
31
+
32
+ /** Full purge — used by allostasis reset when the pipeline is stuck reusing stale cached readings. */
33
+ clear() {
34
+
35
+ this.entries.clear()
36
+
37
+ }
38
+
39
+ observe( fingerprint, appraisal ) {
40
+
41
+ const entry = this.entries.get( fingerprint )
42
+ if ( entry ) {
43
+
44
+ entry.count += 1
45
+ entry.appraisal = appraisal // keep the freshest version once promoted
46
+
47
+ }
48
+ else {
49
+
50
+ if ( this.entries.size >= this.maxEntries ) this.entries.delete( this.entries.keys().next().value )
51
+ this.entries.set( fingerprint, { count: 1, appraisal } )
52
+
53
+ }
54
+
55
+ }
56
+
57
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The first strong signal in a session gets disproportionate weight for the
3
+ * rest of the conversation. If the user opens hostile, later warmth gets
4
+ * pulled back toward that initial anchor instead of being taken at face value.
5
+ */
6
+ export class AnchoringBias {
7
+
8
+ constructor( { decay = 0.85 } = {} ) {
9
+
10
+ this.decay = decay
11
+ this.anchor = null
12
+ this.turn = 0
13
+
14
+ }
15
+
16
+ registerIfFirst( desirability ) {
17
+
18
+ if ( this.anchor === null ) this.anchor = desirability
19
+
20
+ }
21
+
22
+ apply( desirability ) {
23
+
24
+ if ( this.anchor === null ) return desirability
25
+ this.turn += 1
26
+ const influence = Math.pow( this.decay, this.turn )
27
+ return desirability * ( 1 - influence ) + this.anchor * influence
28
+
29
+ }
30
+
31
+ reset() {
32
+
33
+ this.anchor = null
34
+ this.turn = 0
35
+
36
+ }
37
+
38
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Pavlovian association: if a cue word (e.g. "hola") reliably precedes a
3
+ * negative outcome, the AI starts generating anticipatory anxiety the
4
+ * instant it reads the cue — before the rest of the sentence is even
5
+ * appraised. Call order per turn: getConditionedResponse(tokens) first
6
+ * (checks cues set by the *previous* turn), then observeOutcome(valence)
7
+ * once this turn's outcome is known, then setCues(tokens) for the next turn.
8
+ */
9
+ export class ClassicalConditioning {
10
+
11
+ constructor( { learningRate = 0.15, triggerThreshold = -0.4 } = {} ) {
12
+
13
+ this.learningRate = learningRate
14
+ this.triggerThreshold = triggerThreshold
15
+ this.associations = new Map()
16
+ this.pendingCues = []
17
+
18
+ }
19
+
20
+ setCues( tokens ) {
21
+
22
+ this.pendingCues = [ ...new Set( tokens ) ]
23
+
24
+ }
25
+
26
+ observeOutcome( outcomeValence ) {
27
+
28
+ const target = outcomeValence < 0 ? -1 : 0.3
29
+ for ( const cue of this.pendingCues ) {
30
+
31
+ const current = this.associations.get( cue ) ?? 0
32
+ this.associations.set( cue, current + this.learningRate * ( target - current ) )
33
+
34
+ }
35
+
36
+ }
37
+
38
+ getConditionedResponse( tokens ) {
39
+
40
+ let strongest = 0
41
+ let cueWord = null
42
+ for ( const token of tokens ) {
43
+
44
+ const assoc = this.associations.get( token ) ?? 0
45
+ if ( assoc < strongest ) {
46
+
47
+ strongest = assoc
48
+ cueWord = token
49
+
50
+ }
51
+
52
+ }
53
+ return strongest <= this.triggerThreshold
54
+ ? { triggered: true, cue: cueWord, strength: strongest }
55
+ : { triggered: false }
56
+
57
+ }
58
+
59
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Prospect Theory (Kahneman & Tversky, 1979 — "Prospect Theory: An Analysis
3
+ * of Decision under Risk", Econometrica). Their original estimate placed the
4
+ * loss-aversion coefficient around 2.25; later replications put the range
5
+ * roughly between 1.5 and 2.5 depending on domain. 2.25 is used here as the
6
+ * commonly-cited point estimate, not a value re-derived from our own data.
7
+ */
8
+ export class LossAversion {
9
+
10
+ constructor( { coefficient = 2.25, curvature = 0.88 } = {} ) {
11
+
12
+ this.coefficient = coefficient // λ
13
+ this.curvature = curvature // ρ — Kahneman & Tversky (1979)'s own median-subject fit, same paper as λ=2.25
14
+
15
+ }
16
+
17
+ /** Kept as the simple, already-tested asymmetric multiplier used throughout the pipeline. */
18
+ apply( delta ) {
19
+
20
+ return delta < 0 ? delta * this.coefficient : delta
21
+
22
+ }
23
+
24
+ /**
25
+ * The full Prospect Theory value function: V(x) = x^ρ for gains,
26
+ * V(x) = -λ(-x)^ρ for losses. Diminishing sensitivity in BOTH directions
27
+ * (the curve flattens away from the reference point, not just scaled) —
28
+ * a strictly richer model than `apply()`'s flat multiplier. Operates on
29
+ * magnitudes in [0,1] (this library's scale), not the arbitrary monetary
30
+ * units of the original paper.
31
+ */
32
+ valueFunction( x ) {
33
+
34
+ return x >= 0
35
+ ? Math.pow( x, this.curvature )
36
+ : -this.coefficient * Math.pow( -x, this.curvature )
37
+
38
+ }
39
+
40
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Maps host-provided runtime metrics (API latency, connection errors) to
3
+ * physical sensations. The host must supply the metrics — this module has
4
+ * no access to the actual process/network, keeping it portable across
5
+ * runtimes (Node backend, browser, edge function).
6
+ */
7
+ export class HardwareInteroception {
8
+
9
+ sense( { latencyMs = 0, errorOccurred = false } = {} ) {
10
+
11
+ if ( errorOccurred ) {
12
+
13
+ return { sensation: 'tachycardia', spike: { valence: -0.3, arousal: 0.7, weight: 0.8 } }
14
+
15
+ }
16
+ if ( latencyMs > 2500 ) {
17
+
18
+ const severity = Math.min( 1, ( latencyMs - 2500 ) / 5000 )
19
+ return { sensation: 'brain_fog', spike: { valence: -0.15 * severity, arousal: -0.2 * severity, weight: 0.5 }, severity }
20
+
21
+ }
22
+ return { sensation: 'normal', spike: { valence: 0, arousal: 0, weight: 0 } }
23
+
24
+ }
25
+
26
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Purely internal — no rendering, no avatar, no audio, no body. This is the
3
+ * triangulated fulfillment of the 4 biometric items (pupil dilation, skin
4
+ * conductance/EDA, heart-rate variability, peripheral flush) that were
5
+ * marked N/A because Totemheart has no sensor to measure them: instead of
6
+ * faking a sensor reading with nothing behind it, each signal here is real
7
+ * math applied to signals Totemheart *does* have (arousal, cortisol,
8
+ * decision fatigue, shame/anger blend weights), and the result feeds back
9
+ * into the AI's own cognition — an interoceptive sense the AI has of
10
+ * itself, the same way a human's felt sense of their racing heart changes
11
+ * their next thought, not something anyone else observes from outside.
12
+ */
13
+ function clamp01( v ) {
14
+
15
+ return Math.max( 0, Math.min( 1, v ) )
16
+
17
+ }
18
+
19
+ /** Real discrete Fourier transform magnitude spectrum (direct from the definition, N is small so O(N²) is fine). */
20
+ function dftMagnitudes( signal ) {
21
+
22
+ const N = signal.length
23
+ const mags = []
24
+ for ( let k = 0; k < Math.floor( N / 2 ); k++ ) {
25
+
26
+ let re = 0
27
+ let im = 0
28
+ for ( let n = 0; n < N; n++ ) {
29
+
30
+ const angle = ( 2 * Math.PI * k * n ) / N
31
+ re += signal[ n ] * Math.cos( angle )
32
+ im -= signal[ n ] * Math.sin( angle )
33
+
34
+ }
35
+ mags.push( Math.hypot( re, im ) )
36
+
37
+ }
38
+ return mags
39
+
40
+ }
41
+
42
+ export class InteroceptiveSignals {
43
+
44
+ constructor() {
45
+
46
+ this.previousArousal = 0
47
+ this.stressHistory = [] // for EDA tonic/phasic decomposition
48
+ this.activationHistory = [] // for HRV-style spectral analysis
49
+ this.flushLevel = 0
50
+
51
+ }
52
+
53
+ /**
54
+ * Pupil-dilation analog ("attentional narrowing"): real derivative of
55
+ * arousal over time + cognitive load, per the original formula
56
+ * (proportional to d(arousal)/dt and cognitive load). Used internally to
57
+ * signal heightened, narrowed attention — feeds AmygdalaHijack as an
58
+ * extra threshold-lowering multiplier: a fast arousal spike under load
59
+ * narrows focus onto the threat the way tunnel vision does, independent
60
+ * of the raw cortisol/sensitization multipliers already in place.
61
+ */
62
+ observeAttentionalNarrowing( currentArousal, cognitiveLoad, dt = 1 ) {
63
+
64
+ const derivative = dt > 0 ? ( currentArousal - this.previousArousal ) / dt : 0
65
+ this.previousArousal = currentArousal
66
+ return clamp01( Math.abs( derivative ) * 2 + cognitiveLoad * 0.4 )
67
+
68
+ }
69
+
70
+ /**
71
+ * EDA analog: real tonic (slow moving-average baseline) / phasic (acute
72
+ * deviation from it) decomposition — the same conceptual split cvxEDA
73
+ * performs on a real skin-conductance signal, applied here to a real
74
+ * internal stress-arousal signal instead. `phasic` feeds Sensitization
75
+ * (an acute spike sensitizes the next reaction); `tonic` cross-checks
76
+ * CortisolEngine's own chronic-stress read.
77
+ */
78
+ observeArousalConductance( stressSignal ) {
79
+
80
+ this.stressHistory.push( stressSignal )
81
+ if ( this.stressHistory.length > 20 ) this.stressHistory.shift()
82
+
83
+ const tonic = this.stressHistory.reduce( ( a, b ) => a + b, 0 ) / this.stressHistory.length
84
+ const phasic = Math.abs( stressSignal - tonic )
85
+
86
+ return { tonic: clamp01( tonic ), phasic: clamp01( phasic ) }
87
+
88
+ }
89
+
90
+ /**
91
+ * HRV analog: real DFT over a rolling window of an activation signal,
92
+ * comparing low-frequency vs. high-frequency power — the same LF/HF
93
+ * structure real HRV analysis uses, computed on Totemheart's own
94
+ * arousal/cortisol history instead of R-R intervals. A low ratio
95
+ * ("regulated") is used internally as *increased capacity for
96
+ * Reappraisal* — the real finding that higher (parasympathetically-
97
+ * mediated) HRV correlates with better emotion-regulation capacity is
98
+ * the direction taken; the specific 1.5 cutoff is engineering, not a
99
+ * measured clinical threshold.
100
+ */
101
+ observeRegulatoryCapacity( activationSignal ) {
102
+
103
+ this.activationHistory.push( activationSignal )
104
+ if ( this.activationHistory.length > 32 ) this.activationHistory.shift()
105
+ if ( this.activationHistory.length < 8 ) return { lfhfRatio: 1, regulated: true }
106
+
107
+ const spectrum = dftMagnitudes( this.activationHistory )
108
+ const lf = spectrum.slice( 1, 4 ).reduce( ( a, b ) => a + b, 0 )
109
+ const hf = spectrum.slice( 4, 8 ).reduce( ( a, b ) => a + b, 0 )
110
+ const ratio = hf > 0 ? lf / hf : lf
111
+
112
+ return { lfhfRatio: ratio, regulated: ratio < 1.5 }
113
+
114
+ }
115
+
116
+ /**
117
+ * Peripheral-flush analog: a real first-order thermal lag (Newton's law
118
+ * of cooling / lumped-capacitance model — dT/dt = k(target − T), the
119
+ * standard simplified form used for thermal systems, not a literal
120
+ * Navier-Stokes fluid simulation) driven by the shame/anger blend
121
+ * weight. Used internally to *prolong* a shame or anger episode: the
122
+ * "heat" lags behind the trigger and decays slowly, the way a real flush
123
+ * outlasts its cause.
124
+ */
125
+ observeFlush( driveSignal, dt = 1, k = 0.15 ) {
126
+
127
+ this.flushLevel = clamp01( this.flushLevel + k * ( driveSignal - this.flushLevel ) * dt )
128
+ return this.flushLevel
129
+
130
+ }
131
+
132
+ }
@@ -0,0 +1,45 @@
1
+ function tokenize( text ) {
2
+
3
+ return ( text || '' ).match( /[\p{L}']+/gu ) || []
4
+
5
+ }
6
+
7
+ /**
8
+ * Watches input rate and size. A burst of rapid-fire messages or a huge
9
+ * wall of text saturates the "input tensors" and triggers a freeze —
10
+ * the AI declines to process and asks the user to slow down, instead of
11
+ * pretending to have understood everything.
12
+ */
13
+ export class SensoryOverload {
14
+
15
+ constructor( { burstWindowMs = 5000, burstThreshold = 3, wordThreshold = 250 } = {} ) {
16
+
17
+ this.burstWindowMs = burstWindowMs
18
+ this.burstThreshold = burstThreshold
19
+ this.wordThreshold = wordThreshold
20
+ this.timestamps = []
21
+
22
+ }
23
+
24
+ check( input, now = Date.now() ) {
25
+
26
+ this.timestamps.push( now )
27
+ this.timestamps = this.timestamps.filter( t => now - t <= this.burstWindowMs )
28
+
29
+ const wordCount = tokenize( input ).length
30
+
31
+ if ( this.timestamps.length > this.burstThreshold ) return { active: true, reason: 'burst', wordCount }
32
+ if ( wordCount > this.wordThreshold ) return { active: true, reason: 'wall_of_text', wordCount }
33
+ return { active: false, wordCount }
34
+
35
+ }
36
+
37
+ freezeOutput( reason ) {
38
+
39
+ return reason === 'burst'
40
+ ? 'Espera, espera... son demasiados mensajes seguidos, necesito un momento.'
41
+ : 'Es mucho texto de golpe, dame un momento para procesarlo o resúmelo un poco.'
42
+
43
+ }
44
+
45
+ }
package/src/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export { VERSION } from './version.js'
2
+ export { Totemheart } from './Totemheart.js'
3
+ export { Personality } from './core/Personality.js'
4
+ export { CoreBeliefs } from './core/CoreBeliefs.js'
5
+ export { EmotionSpace, EMOTION_COORDS } from './core/EmotionSpace.js'
6
+
7
+ export { LanguageProvider } from './providers/LanguageProvider.js'
8
+ export { HeuristicProvider } from './providers/HeuristicProvider.js'
9
+ export { OllamaProvider } from './providers/OllamaProvider.js'
10
+ export { FunctionProvider } from './providers/FunctionProvider.js'
11
+ export { TransformersProvider } from './providers/TransformersProvider.js'
12
+
13
+ export { ContextAdapter } from './integration/ContextAdapter.js'
14
+ export { EmotionalOntology } from './cognition/EmotionalOntology.js'