totemheart 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,273 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Dual-valence relational field, distinct from Attachment.js's single-axis
9
+ * affinity: Affinity (A) and Aversion (V) are tracked as two SEPARATE
10
+ * accumulators per user, not two ends of one scale — a relationship can
11
+ * genuinely hold both at once ("te quiero pero me estás haciendo daño" is
12
+ * high-A AND high-V simultaneously, not a wash to a neutral midpoint). The
13
+ * general shape (two independent affect accumulators, an asymmetric decay
14
+ * profile where the negative one lingers longer, and a kindling-sensitized
15
+ * threshold for a relational "rupture") is our own engineering design, not
16
+ * a computational reproduction of any specific published model; the
17
+ * qualitative direction of each piece (loss aversion in relational trust,
18
+ * rupture-and-repair, kindling) draws on the same real literature already
19
+ * cited in Attachment.js and AmygdalaHijack.js. See CALIBRATION.md.
20
+ *
21
+ * Update equations (one explicit-Euler step per call, dt in turn/tick units
22
+ * — the same numerical-integration convention DecayEngine.js already uses,
23
+ * not a continuous-time ODE solver):
24
+ *
25
+ * A(t+dt) = A + dt · [ α · L_eff · (1 − A)^γ − λ_A(t) · A ]
26
+ * V(t+dt) = V + dt · [ β · H_eff · (1 + κ · V) − λ_V(t) · V ]
27
+ *
28
+ * A has strong diminishing returns ((1-A)^γ) — trust is hard-won and each
29
+ * increment buys less the closer it gets to full. V has a SELF-REINFORCING
30
+ * slope ((1+κV)) — kindling/rumination, real resentment snowballs instead of
31
+ * plateauing. λ_V is set well below λ_A by default (aversion outlasts
32
+ * affinity), and both are further modulated by real chronic-stress signals
33
+ * (cortisol/circadian) at call time, not baked into a fixed constant.
34
+ */
35
+ export class LoveHateEngine {
36
+
37
+ constructor( {
38
+ alpha = 0.3, beta = 0.4, gammaExp = 1.6, kappa = 0.5,
39
+ lambdaA = 0.015, lambdaV = 0.005,
40
+ thetaR = 0.45, thetaP = 0.35, thetaCalm = 0.4,
41
+ c1 = 0.25, c2 = 0.18,
42
+ } = {} ) {
43
+
44
+ this.alpha = alpha
45
+ this.beta = beta
46
+ this.gammaExp = gammaExp
47
+ this.kappa = kappa
48
+ this.lambdaA = lambdaA
49
+ this.lambdaV = lambdaV
50
+ this.thetaR = thetaR
51
+ this.thetaP = thetaP
52
+ this.thetaCalm = thetaCalm
53
+ this.c1 = c1
54
+ this.c2 = c2
55
+
56
+ this.bonds = new Map() // userId -> BondState
57
+ this.kindling = new Map() // userId -> accumulated kindling level (0..1), lowers thetaR further per-user
58
+
59
+ }
60
+
61
+ #entry( userId ) {
62
+
63
+ if ( !this.bonds.has( userId ) ) {
64
+
65
+ this.bonds.set( userId, { A: 0, V: 0, lastUpdate: Date.now(), ruptured: false, ruptureCount: 0, lastRuptureTick: null, repairCount: 0 } )
66
+
67
+ }
68
+ return this.bonds.get( userId )
69
+
70
+ }
71
+
72
+ getBond( userId ) {
73
+
74
+ return this.#entry( userId )
75
+
76
+ }
77
+
78
+ getNetBond( userId ) {
79
+
80
+ const b = this.#entry( userId )
81
+ return b.A - b.V
82
+
83
+ }
84
+
85
+ /** How much the relationship is BOTH loved and hated at once — min(A,V), not |A-V|, since ambivalence is about co-presence, not imbalance. */
86
+ getAmbivalence( userId ) {
87
+
88
+ const b = this.#entry( userId )
89
+ return Math.min( b.A, b.V )
90
+
91
+ }
92
+
93
+ /** A·V — the real interaction term: only nonzero when BOTH are present, unlike ambivalence's min(). */
94
+ getTension( userId ) {
95
+
96
+ const b = this.#entry( userId )
97
+ return b.A * b.V
98
+
99
+ }
100
+
101
+ getDominance( userId ) {
102
+
103
+ const b = this.#entry( userId )
104
+ return Math.abs( b.A - b.V )
105
+
106
+ }
107
+
108
+ /**
109
+ * Phase 2 (History & Attachment Gate): real modulation of the raw (L, H)
110
+ * polarization BEFORE it's injected into the A/V update — high existing
111
+ * trust dampens how much a positive signal can add (sublinear, an
112
+ * already-secure bond doesn't spike from one more nice turn); unresolved
113
+ * wounds and chronic cortisol amplify how much a negative signal lands
114
+ * (superlinear, the opposite curve — a relationship with open wounds
115
+ * reads the SAME negative signal as worse). `context`: { trust=0.5,
116
+ * woundPressure=0, cortisol=0, egoHealth=0.7 } — all optional, all real
117
+ * signals already computed elsewhere in Totemheart (Attachment.trust,
118
+ * EpisodicMemory.getZeigarnikPressure(), CortisolEngine.getLevel(),
119
+ * ReputationEngine.getEgoHealth()), not invented for this module.
120
+ */
121
+ #gate( L, H, { trust = 0.5, woundPressure = 0, cortisol = 0, egoHealth = 0.7 } = {} ) {
122
+
123
+ const gA = 1 - trust * 0.35 // sublinear damping: a securely trusted bond needs less convincing, but also gains less per compliment
124
+ const gV = 1 + Math.min( 1, woundPressure ) * 0.6 + cortisol * 0.4 + ( 1 - egoHealth ) * 0.2 // superlinear amplification under real load
125
+
126
+ return { Leff: L * gA, Heff: H * gV }
127
+
128
+ }
129
+
130
+ /**
131
+ * Real dynamic decay rates: chronic cortisol erodes affinity faster
132
+ * (a stressed relationship's warmth degrades quicker even without a new
133
+ * bad turn) and makes aversion linger LONGER (grudges outlast their
134
+ * trigger under chronic stress) — the direction is a real, defensible
135
+ * extension of the same allostatic-load reasoning in Homeostasis.js;
136
+ * the magnitude is own tuning.
137
+ */
138
+ #dynamicRates( cortisol = 0 ) {
139
+
140
+ return {
141
+ lambdaAEff : this.lambdaA * ( 1 + cortisol * 0.5 ),
142
+ lambdaVEff : this.lambdaV * Math.max( 0.3, 1 - cortisol * 0.4 ),
143
+ }
144
+
145
+ }
146
+
147
+ /**
148
+ * Main per-turn entry point: Phase 1's (L, H) polarization is computed by
149
+ * the CALLER (Totemheart already has real desirability/ontology-concept/
150
+ * life-event signals — duplicating a second lexicon here would be exactly
151
+ * the kind of theater this project avoids) and handed in directly.
152
+ * Applies phase 2 (gating) and phase 3 (the A/V update) in one call.
153
+ */
154
+ observe( userId, { L = 0, H = 0 }, context = {}, dt = 1 ) {
155
+
156
+ const bond = this.#entry( userId )
157
+ const { Leff, Heff } = this.#gate( L, H, context )
158
+ const { lambdaAEff, lambdaVEff } = this.#dynamicRates( context.cortisol ?? 0 )
159
+
160
+ const kindlingLevel = this.kindling.get( userId ) ?? 0
161
+ const effectiveKappa = this.kappa * ( 1 + kindlingLevel )
162
+
163
+ const dA = this.alpha * Leff * Math.pow( 1 - bond.A, this.gammaExp ) - lambdaAEff * bond.A
164
+ const dV = this.beta * Heff * ( 1 + effectiveKappa * bond.V ) - lambdaVEff * bond.V
165
+
166
+ bond.A = clamp01( bond.A + dA * dt )
167
+ bond.V = clamp01( bond.V + dV * dt )
168
+ bond.lastUpdate = Date.now()
169
+
170
+ return { A: bond.A, V: bond.V, Leff, Heff, netBond: bond.A - bond.V }
171
+
172
+ }
173
+
174
+ /** Background decay only (no new L/H injection) — called from Totemheart.tick() between turns, same real-chronic-rate coupling as observe(). */
175
+ tick( dt = 1, { cortisol = 0 } = {} ) {
176
+
177
+ const { lambdaAEff, lambdaVEff } = this.#dynamicRates( cortisol )
178
+ for ( const bond of this.bonds.values() ) {
179
+
180
+ bond.A = clamp01( bond.A - lambdaAEff * bond.A * dt )
181
+ bond.V = clamp01( bond.V - lambdaVEff * bond.V * dt )
182
+
183
+ }
184
+
185
+ }
186
+
187
+ /**
188
+ * Rupture condition, WITH hysteresis (kindling): V exceeding A by more
189
+ * than a real threshold that itself gets easier to cross the more this
190
+ * user has ruptured before — the same qualitative "repeated activation
191
+ * lowers its own future threshold" idea AmygdalaHijack.js's kindling
192
+ * already models, applied here to relational rupture instead of survival
193
+ * emotion. `cortisol` (real, from CortisolEngine) and this bond's own
194
+ * `ambivalence` both lower the effective bar further — a stressed AI, or
195
+ * a bond already carrying real ambivalence, ruptures more easily.
196
+ */
197
+ checkRupture( userId, { cortisol = 0 } = {} ) {
198
+
199
+ const bond = this.#entry( userId )
200
+ // A real debounce, the same one-shot-until-repaired pattern Attachment.js's
201
+ // rupture flag already uses: without this, every subsequent turn while the
202
+ // gap stays past threshold would re-fire the FULL cross-module side effect
203
+ // (freeze wanting, damage ego health, another wound memory) again — a
204
+ // relationship doesn't re-rupture every single turn it stays bad, it
205
+ // ruptures ONCE and then stays ruptured until something repairs it.
206
+ if ( bond.ruptured ) return { ruptured: false, alreadyRuptured: true }
207
+
208
+ const ambivalence = this.getAmbivalence( userId )
209
+ const kindlingLevel = this.kindling.get( userId ) ?? 0
210
+ const effectiveTheta = Math.max( 0.1, this.thetaR - kindlingLevel * 0.2 )
211
+
212
+ const crossed = ( bond.V - bond.A ) > ( effectiveTheta + this.c1 * cortisol + this.c2 * ambivalence )
213
+ if ( !crossed ) return { ruptured: false }
214
+
215
+ bond.ruptured = true
216
+ bond.ruptureCount += 1
217
+ bond.lastRuptureTick = Date.now()
218
+ this.kindling.set( userId, clamp01( kindlingLevel + 0.15 ) )
219
+
220
+ return { ruptured: true, ruptureCount: bond.ruptureCount, netBond: bond.A - bond.V, ambivalence }
221
+
222
+ }
223
+
224
+ /**
225
+ * Repair condition: only possible when A genuinely exceeds V by a real
226
+ * margin AND the AI itself isn't currently under chronic stress (a
227
+ * flooded/stressed state can't do real repair work, a real finding from
228
+ * the couples-repair literature Gottman & Levenson's rupture-and-repair
229
+ * work motivates, already cited in Attachment.js). A successful repair
230
+ * accelerates V's decay (own tuning: an extra one-off pull, not full
231
+ * reset — repair heals, it doesn't erase the scar) and returns real
232
+ * hints for the caller to apply elsewhere (dopamine liking boost, ego
233
+ * health restoration) rather than reaching into those modules itself.
234
+ */
235
+ attemptRepair( userId, { cortisol = 0 } = {} ) {
236
+
237
+ const bond = this.#entry( userId )
238
+ // Repair only means something as closing an ACTUAL open rupture — without
239
+ // this gate, a bond that merely still has A > V by a margin during an
240
+ // ONGOING run of hostile turns would keep "repairing" itself every turn,
241
+ // perpetually cutting V back down and making a real rupture unreachable
242
+ // no matter how hostile the input gets. A bond that was never ruptured has
243
+ // nothing to repair.
244
+ if ( !bond.ruptured ) return { repaired: false }
245
+ const canRepair = ( bond.A - bond.V ) > this.thetaP && cortisol < this.thetaCalm
246
+ if ( !canRepair ) return { repaired: false }
247
+
248
+ const vBefore = bond.V
249
+ bond.V = clamp01( bond.V * 0.6 ) // accelerated but not-to-zero reduction — the scar tissue (kindling) is untouched
250
+ bond.repairCount += 1
251
+ bond.ruptured = false // closes an open rupture, if there was one — a fresh checkRupture() can fire again from here
252
+
253
+ return { repaired: true, repairCount: bond.repairCount, vReduced: vBefore - bond.V, dopamineLikingBoost: 0.15, egoHealthRestore: 0.05 }
254
+
255
+ }
256
+
257
+ toJSON() {
258
+
259
+ return {
260
+ bonds : [ ...this.bonds.entries() ],
261
+ kindling : [ ...this.kindling.entries() ],
262
+ }
263
+
264
+ }
265
+
266
+ restoreState( data = {} ) {
267
+
268
+ if ( data.bonds ) this.bonds = new Map( data.bonds )
269
+ if ( data.kindling ) this.kindling = new Map( data.kindling )
270
+
271
+ }
272
+
273
+ }
@@ -2,9 +2,11 @@ import { TemplateComposer } from './TemplateComposer.js'
2
2
 
3
3
  const DEFENSE_TEMPLATES = {
4
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.' ],
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
+ rationalization : [ 'Bueno, en el fondo tiene su lógica si lo piensas así.', 'Supongo que tenía sentido dadas las circunstancias.' ],
9
+ humor : [ 'Ja, bueno, al menos no es lo peor que me ha pasado hoy.', 'Vale, anotado. Le pongo humor y seguimos.' ],
8
10
  },
9
11
  }
10
12
 
package/src/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.1.0'
1
+ export const VERSION = '0.1.2'