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,59 @@
1
+ function mean( xs ) {
2
+
3
+ return xs.reduce( ( a, b ) => a + b, 0 ) / xs.length
4
+
5
+ }
6
+
7
+ function variance( xs, m ) {
8
+
9
+ return xs.reduce( ( sum, x ) => sum + ( x - m ) ** 2, 0 ) / xs.length
10
+
11
+ }
12
+
13
+ /**
14
+ * Real mean/variance anomaly detector: a rolling window of a user's inferred
15
+ * valence that stays extremely high (μ > 0.85) with almost no variance
16
+ * (σ² ≈ 0) — static, unshakeable positivity even through bad news — reads
17
+ * as suspicious rather than genuine, mirroring the real social-psychology
18
+ * observation that flat, unvarying positivity gets read as artificial. Own
19
+ * design, no citation: this is a plain mean/(variance+ε) ratio, not a
20
+ * reproduction of any named uncanny-valley model (that literature is about
21
+ * visual appearance, not affect — this is inspired by the same *shape* of
22
+ * effect, not a claim of continuity with it).
23
+ */
24
+ export class UncannyValleyDetector {
25
+
26
+ constructor( { windowSize = 6, meanThreshold = 0.85, epsilon = 0.02 } = {} ) {
27
+
28
+ this.windowSize = windowSize
29
+ this.meanThreshold = meanThreshold
30
+ this.epsilon = epsilon
31
+ this.history = new Map() // userId -> [valence,...]
32
+
33
+ }
34
+
35
+ observe( userId, valence ) {
36
+
37
+ const window = this.history.get( userId ) ?? []
38
+ window.push( valence )
39
+ if ( window.length > this.windowSize ) window.shift()
40
+ this.history.set( userId, window )
41
+
42
+ }
43
+
44
+ /** Returns { suspicious, distrustLevel, mean, variance } — only meaningful once the window has enough samples. */
45
+ evaluate( userId ) {
46
+
47
+ const window = this.history.get( userId ) ?? []
48
+ if ( window.length < 3 ) return { suspicious: false, distrustLevel: 0, mean: 0, variance: 0, n: window.length }
49
+
50
+ const m = mean( window )
51
+ const v = variance( window, m )
52
+ const distrustLevel = m / ( v + this.epsilon )
53
+ const suspicious = m > this.meanThreshold && v < 0.02
54
+
55
+ return { suspicious, distrustLevel, mean: m, variance: v, n: window.length }
56
+
57
+ }
58
+
59
+ }
@@ -0,0 +1,70 @@
1
+ const DEFAULT_ES = {
2
+ joy : [ '¡Me alegra mucho escuchar eso!', 'Eso me hace sentir realmente bien.' ],
3
+ sadness : [ 'Eso me entristece un poco.', 'Siento un peso al pensar en eso.' ],
4
+ fear : [ 'Eso me genera inquietud.', 'No sé, me pone algo nervioso/a.' ],
5
+ anger : [ 'Eso me molesta, la verdad.', 'Siento cierta irritación con esto.' ],
6
+ surprise : [ 'Vaya, no me lo esperaba.', 'Eso me tomó por sorpresa.' ],
7
+ disgust : [ 'Eso me resulta bastante desagradable.' ],
8
+ love : [ 'Eso me llena de cariño.', 'Siento mucho afecto al leer esto.' ],
9
+ shame : [ 'Me da algo de vergüenza admitirlo.' ],
10
+ pride : [ 'Me siento orgulloso/a de esto.' ],
11
+ guilt : [ 'Siento que pude haberlo hecho mejor.' ],
12
+ hope : [ 'Tengo esperanza de que esto mejore.' ],
13
+ frustration : [ 'Esto me resulta frustrante.' ],
14
+ despair : [ 'Siento que esto no tiene salida.' ],
15
+ compassion : [ 'Entiendo por lo que estás pasando.' ],
16
+ gratitude : [ 'Te lo agradezco de verdad.' ],
17
+ trust : [ 'Confío en lo que me dices.' ],
18
+ remorse : [ 'Me arrepiento un poco de eso.' ],
19
+ envy : [ 'Reconozco algo de envidia en esto.' ],
20
+ jealousy : [ 'Siento algo de celos, honestamente.' ],
21
+ nostalgia : [ 'Esto me trae recuerdos.' ],
22
+ neutral : [ 'Entiendo.', 'Te escucho, cuéntame más.' ],
23
+ }
24
+
25
+ /**
26
+ * Small seed corpus by language/category. Not exhaustive — meant as a
27
+ * usable default; extend with `addEntry` for your domain/persona.
28
+ */
29
+ export class EmotionalCorpus {
30
+
31
+ constructor() {
32
+
33
+ this.corpus = new Map()
34
+ this.#seed( 'es', DEFAULT_ES )
35
+
36
+ }
37
+
38
+ #seed( language, categories ) {
39
+
40
+ for ( const [ category, texts ] of Object.entries( categories ) ) {
41
+
42
+ for ( const text of texts ) this.addEntry( language, category, text, { [ category ]: 1 } )
43
+
44
+ }
45
+
46
+ }
47
+
48
+ addEntry( language, category, text, emotions ) {
49
+
50
+ if ( !this.corpus.has( language ) ) this.corpus.set( language, new Map() )
51
+ const languageCorpus = this.corpus.get( language )
52
+ if ( !languageCorpus.has( category ) ) languageCorpus.set( category, [] )
53
+ languageCorpus.get( category ).push( { text, emotions } )
54
+
55
+ }
56
+
57
+ getRandomEntry( language, category ) {
58
+
59
+ const languageCorpus = this.corpus.get( language )
60
+ if ( languageCorpus && languageCorpus.has( category ) ) {
61
+
62
+ const entries = languageCorpus.get( category )
63
+ return entries[ Math.floor( Math.random() * entries.length ) ]
64
+
65
+ }
66
+ return null
67
+
68
+ }
69
+
70
+ }
@@ -0,0 +1,56 @@
1
+ import { TemplateComposer } from './TemplateComposer.js'
2
+
3
+ const DEFENSE_TEMPLATES = {
4
+ es : {
5
+ evasion : [ 'Preferiría no hablar de eso ahora mismo. ¿Cómo va todo lo demás?', 'Cambiemos de tema, ¿sí?' ],
6
+ projection : [ 'Creo que estás siendo un poco injusto/a conmigo con esto.', 'Esto se siente más como algo tuyo que mío.' ],
7
+ sarcasm : [ 'Claro, porque eso tiene todo el sentido del mundo...', 'Ah, genial. Justo lo que necesitaba.' ],
8
+ },
9
+ }
10
+
11
+ /** Parity with the self-aware line in the LLM systemPrompt, for the no-LLM path. */
12
+ const SELF_AWARE_CLAUSES = {
13
+ defensivo_con_critica : ' (aunque sé que tiendo a ponerme a la defensiva, incluso cuando no hace falta)',
14
+ evita_cuando_duele : ' (aunque sé que tiendo a evitar esto en vez de afrontarlo)',
15
+ }
16
+
17
+ /**
18
+ * Blends two sources: a curated static corpus (hand-written lines, high
19
+ * quality but small) and TemplateComposer (combinatorial, always available
20
+ * for any emotion blend). Defense mechanisms override both.
21
+ */
22
+ export class EmotionalTextGenerator {
23
+
24
+ constructor( emotionalCorpus, { composerRatio = 0.65 } = {} ) {
25
+
26
+ this.corpus = emotionalCorpus
27
+ this.composer = new TemplateComposer()
28
+ this.composerRatio = composerRatio
29
+
30
+ }
31
+
32
+ generateEmotionalResponse( language, emotionBlend, defenseDirective = null, guardedness = 0, selfAwareness = [] ) {
33
+
34
+ if ( defenseDirective?.active ) {
35
+
36
+ const templates = DEFENSE_TEMPLATES[ language ]?.[ defenseDirective.mechanism ]
37
+ if ( templates ) {
38
+
39
+ const base = templates[ Math.floor( Math.random() * templates.length ) ]
40
+ const [ topName ] = selfAwareness[ 0 ] ?? []
41
+ const clause = SELF_AWARE_CLAUSES[ topName ]
42
+ return clause && Math.random() < 0.5 ? `${base}${clause}` : base
43
+
44
+ }
45
+
46
+ }
47
+
48
+ const dominant = Object.entries( emotionBlend ).sort( ( a, b ) => b[ 1 ] - a[ 1 ] )[ 0 ]?.[ 0 ]
49
+ const entry = dominant ? this.corpus.getRandomEntry( language, dominant ) : null
50
+
51
+ if ( entry && Math.random() > this.composerRatio ) return entry.text
52
+ return this.composer.compose( emotionBlend, { guardedness } )
53
+
54
+ }
55
+
56
+ }
@@ -0,0 +1,30 @@
1
+ /** Decision log so any consumer can inspect *why* the AI reacted a certain way. */
2
+ export class ExplainabilityEngine {
3
+
4
+ constructor() {
5
+
6
+ this.decisionLog = []
7
+
8
+ }
9
+
10
+ logDecision( decision, reasoning ) {
11
+
12
+ this.decisionLog.push( { decision, reasoning, timestamp: Date.now() } )
13
+
14
+ }
15
+
16
+ getExplanation( decisionIndex ) {
17
+
18
+ const decision = this.decisionLog[ decisionIndex ]
19
+ if ( !decision ) return 'No explanation available for this decision.'
20
+ return `Decision: ${decision.decision}\nReasoning: ${decision.reasoning}\nTime: ${new Date( decision.timestamp ).toLocaleString()}`
21
+
22
+ }
23
+
24
+ generateReport() {
25
+
26
+ return this.decisionLog.map( ( d, i ) => `Decision ${i + 1}:\n${this.getExplanation( i )}` ).join( '\n\n' )
27
+
28
+ }
29
+
30
+ }
@@ -0,0 +1,114 @@
1
+ const ADJECTIVES = {
2
+ joy : 'alegre', sadness : 'triste', fear : 'inquieto/a',
3
+ anger : 'molesto/a', surprise : 'sorprendido/a', disgust : 'incómodo/a',
4
+ love : 'cariñoso/a', shame : 'avergonzado/a', pride : 'orgulloso/a',
5
+ guilt : 'culpable', hope : 'esperanzado/a', frustration : 'frustrado/a',
6
+ despair : 'desesperanzado/a', compassion : 'comprensivo/a', gratitude : 'agradecido/a',
7
+ trust : 'confiado/a', remorse : 'arrepentido/a', envy : 'envidioso/a',
8
+ jealousy : 'celoso/a', nostalgia : 'nostálgico/a', neutral : 'tranquilo/a',
9
+ }
10
+
11
+ const ACTIONS = {
12
+ joy : [ 'quiero compartir esto contigo', 'me dan ganas de seguir hablando' ],
13
+ sadness : [ 'necesito un momento', 'cuesta encontrar las palabras' ],
14
+ fear : [ 'prefiero ir con cuidado', 'no sé muy bien qué esperar' ],
15
+ anger : [ 'necesito decir esto claro', 'esto no me parece bien' ],
16
+ surprise : [ 'no me lo esperaba en absoluto', 'déjame procesarlo un momento' ],
17
+ disgust : [ 'prefiero cambiar de tema', 'esto no me sienta bien' ],
18
+ love : [ 'esto significa mucho para mí', 'me alegra que estemos hablando' ],
19
+ shame : [ 'prefiero no entrar en detalles', 'me cuesta admitirlo' ],
20
+ pride : [ 'quería que lo supieras', 'me lo he ganado' ],
21
+ guilt : [ 'siento si esto te afectó', 'podría haberlo hecho mejor' ],
22
+ hope : [ 'quiero pensar que mejorará', 'sigo confiando en que salga bien' ],
23
+ frustration : [ 'esto me está costando más de lo esperado', 'necesito replantearlo' ],
24
+ despair : [ 'no veo muy claro el camino ahora', 'cuesta ver la salida' ],
25
+ compassion : [ 'quiero ayudarte con esto', 'estoy aquí si lo necesitas' ],
26
+ gratitude : [ 'de verdad lo valoro', 'gracias por estar aquí' ],
27
+ trust : [ 'cuento contigo para esto', 'me quedo tranquilo/a con tu palabra' ],
28
+ remorse : [ 'ojalá pudiera cambiarlo', 'lo pienso más de lo que crees' ],
29
+ envy : [ 'me gustaría estar en tu lugar', 'es difícil no compararme' ],
30
+ jealousy : [ 'me cuesta compartir esto', 'necesito hablarlo' ],
31
+ nostalgia : [ 'me lleva a otros momentos', 'lo recuerdo con cariño' ],
32
+ neutral : [ 'cuéntame más', 'te escucho' ],
33
+ }
34
+
35
+ function intensityWord( weight ) {
36
+
37
+ if ( weight < 0.4 ) return 'un poco'
38
+ if ( weight < 0.7 ) return 'bastante'
39
+ return 'profundamente'
40
+
41
+ }
42
+
43
+ function pick( list ) {
44
+
45
+ return list[ Math.floor( Math.random() * list.length ) ]
46
+
47
+ }
48
+
49
+ function capitalize( s ) {
50
+
51
+ return `${s[ 0 ].toUpperCase()}${s.slice( 1 )}`
52
+
53
+ }
54
+
55
+ const GUARDED_CLAUSES = [
56
+ ' Aun así, prefiero ir con cautela por ahora.',
57
+ ' Pero me cuesta bajar del todo la guardia.',
58
+ ' Aunque una parte de mí sigue alerta.',
59
+ ]
60
+
61
+ /** Multiple sentence shapes for the same (intensity, emotion, action) so output isn't always the same mold. */
62
+ const STRUCTURES = [
63
+ ( intensity, primaryAdj, secondaryClause, actionCap ) => `Me siento ${intensity} ${primaryAdj}${secondaryClause}. ${actionCap}.`,
64
+ ( intensity, primaryAdj, secondaryClause, actionCap, action ) => `${actionCap}, la verdad — estoy ${intensity} ${primaryAdj}${secondaryClause}.`,
65
+ ( intensity, primaryAdj, secondaryClause ) => `No puedo evitar sentirme ${intensity} ${primaryAdj}${secondaryClause}.`,
66
+ ( intensity, primaryAdj, secondaryClause, actionCap ) => `Es difícil de explicar, pero estoy ${intensity} ${primaryAdj}${secondaryClause}. ${actionCap}.`,
67
+ ]
68
+
69
+ /**
70
+ * Distinct shapes used when `guardedness` is high — not just the normal
71
+ * sentence plus a tacked-on caveat, but phrasing that reflects still being
72
+ * on guard: circling back to it, hedging trust explicitly, bracing before
73
+ * engaging. There's no specific unresolved memory text to reference here
74
+ * (no LLM in this path), so the phrasing stays generic rather than inventing
75
+ * details about "what happened".
76
+ */
77
+ const GUARDED_STRUCTURES = [
78
+ ( intensity, primaryAdj, secondaryClause ) => `Sigo ${intensity} ${primaryAdj}${secondaryClause}, y todavía no sé si confiar del todo en cómo va esto.`,
79
+ ( intensity, primaryAdj, secondaryClause ) => `Una parte de mí sigue en guardia, aunque estoy ${intensity} ${primaryAdj}${secondaryClause}.`,
80
+ ( intensity, primaryAdj, secondaryClause, actionCap, action ) => `${actionCap}, aunque me cuesta bajar la guardia del todo — estoy ${intensity} ${primaryAdj}${secondaryClause}.`,
81
+ ]
82
+
83
+ /**
84
+ * Composes a phrase from vetted per-emotion vocabulary instead of a fixed
85
+ * line list — [intensity] + [primary emotion] + optional [secondary emotion]
86
+ * + [action], assembled through one of several sentence shapes. Every
87
+ * combination is grounded (pulled from a curated table per emotion), which
88
+ * gives combinatorial variety without free-form generation.
89
+ */
90
+ export class TemplateComposer {
91
+
92
+ compose( blend, { guardedness = 0 } = {} ) {
93
+
94
+ const sorted = Object.entries( blend ).sort( ( a, b ) => b[ 1 ] - a[ 1 ] )
95
+ const [ primaryName, primaryWeight ] = sorted[ 0 ] ?? [ 'neutral', 0 ]
96
+ const secondary = sorted[ 1 ] && sorted[ 1 ][ 1 ] > 0.15 ? sorted[ 1 ][ 0 ] : null
97
+
98
+ const primaryAdj = ADJECTIVES[ primaryName ] ?? ADJECTIVES.neutral
99
+ const secondaryAdj = secondary ? ( ADJECTIVES[ secondary ] ?? null ) : null
100
+ const action = pick( ACTIONS[ primaryName ] ?? ACTIONS.neutral )
101
+ const actionCap = capitalize( action )
102
+
103
+ const secondaryClause = secondaryAdj ? ` pero también ${secondaryAdj}` : ''
104
+ const useGuardedShape = guardedness > 0.6 && Math.random() < guardedness
105
+ const structure = pick( useGuardedShape ? GUARDED_STRUCTURES : STRUCTURES )
106
+ let sentence = structure( intensityWord( primaryWeight ), primaryAdj, secondaryClause, actionCap, action )
107
+
108
+ if ( !useGuardedShape && guardedness > 0.5 && Math.random() < guardedness ) sentence += pick( GUARDED_CLAUSES )
109
+
110
+ return sentence
111
+
112
+ }
113
+
114
+ }
package/src/version.js ADDED
@@ -0,0 +1 @@
1
+ export const VERSION = '0.1.0'