totemheart
v0.1.7
Published
Totemheart is a modular emotional-simulation engine for AI: personality, mood, neurochemical dynamics, cognitive biases and social mechanics wired into a single pipeline that drives emotionally coherent, stateful behavior over a conversation.
Downloads
1,614
Maintainers
Readme
Totemheart

The Tests/Mechanisms badges are static, updated by hand from a real local
npm test/npm run verifyrun. There's no CI wired up yet, so treat them as a snapshot, not a live guarantee onmain.npm testrunstest/in full:regression/(92),integration/(893, directed and cross-mechanism scenarios, full-pipeline emergency routes, serialization, malformed-input robustness, and per-round dedicated suites, seetest/integration/), andproperty/(2029, deterministic boundary/grid checks, no randomness).npm run test:alladditionally runstest:plugins(49 more across the 7 official plugins below plus cross-integration scenarios intest/plugins-cross/), for 3063 real tests total. Two earlier mechanism rounds also ship their own dedicated live audit outside this count:npm run upgrade-round-mock(39/39) andnpm run lovehate-mock(24/24).
Totemheart is a deterministic control kernel for persistent cognition and relational behavior, not a sentiment classifier and not a prompt-engineering trick. It gives an agent a consistent, inspectable inner state across a conversation and across days: personality, mood, memory, stress, attachment, desire, and social inference that evolve through control-theory and neuroscience-derived dynamics, instead of recomputing each reply from a mood label. Mechanisms interact in chains (bond, residual chemistry, grief, secrecy, intuition) under sparse activation; subjective experience remains 0% by design. See What this actually is below before you build on top of it.
Totemheart is an unusually dense, test-heavy, inspectable kernel for persistent relational and affective dynamics—built to make human-like behavioral continuity computable and controllable, without claiming sentience.
Table of Contents
- How this differs from a sentiment-based chatbot layer
- What this actually is
- Architecture
- How coherent is this, really?
- Prerequisites
- Installation
- Usage
- Plugins
- License
How this differs from a sentiment-based chatbot layer
| | Typical "emotional AI" repo | Totemheart |
| --- | --- | --- |
| Core mechanism | Prompt engineering + emotion classifier | Dynamic system: every spike, decay, homeostatic pull and circadian phase interacts in real time and feeds the next turn |
| Emotion → output | Rule of thumb (if arousal > 0.7, add exclamation marks) | State-driven directives derived from the actual PAD vector and its recent trajectory |
| State | None, or a mood string overwritten each turn | Persistent, inspectable state object updated by real dynamics every turn |
| Signal processing | Raw score in, raw score out | Kalman filtering on arousal, PID with anti-windup on basic needs (stamina, hunger), cubic non-linear decay (a bigger offset from baseline is restored proportionally harder) |
| Memory | "Remembers everything" or nothing at all | REM-style consolidation on idle-time triggers, latent-weight decay toward a non-zero floor (not to zero), token-overlap reactivation instead of blind recall |
| Reward signal | Positive/negative sentiment score | Temporal-difference prediction error, RPE = R_t + γ·V(S_t+1) − V(S_t), the same formulation used in reinforcement-learning neuroscience, with per-relationship eligibility traces |
| Relational memory | One bipolar "liked me / didn't" score | Affinity and Aversion tracked as two separate accumulators (LoveHateEngine), so real ambivalence is representable instead of averaging out to neutral |
| Stress response | A static "angry" threshold | Allostatic load raises reactivity to negative input the longer stress goes unaddressed, a real chronic-stress coupling, not a fixed multiplier |
| Persistence | "Save the mood to a database and hope" | toJSON() / rehydrate with round-trip verification in tests |
What this actually is
Totemheart gives an AI behavioral continuity: the same insult lands differently depending on prior context, repeated affection produces diminishing reactions, unresolved stress lowers the threshold for an outburst, a wounded ego can make it deflect blame instead of apologizing. All of that is real, computed, inspectable state, not decoration.
What it is not: subjective experience. There is no known way to build or verify that in software, and Totemheart doesn't claim to. Every "emotion" here is a point in a valence/arousal vector space plus a pile of interacting numeric modules, legible by design (call getEmotionalState() any time and see exactly why it reacted the way it did). Treat the output as a behavioral simulation with psychological grounding, useful for building characters, companions, or agents that feel coherent over time, not as a claim about machine sentience.
Architecture
Every mechanic is a small, independent class with its own state, one file per mechanic under src/, organized by what kind of psychological work it does.
| | Category | What it covers | | --- | --- | --- | | 🧠 | State engine | Personality, homeostatic needs, and the core emotional vector everything else reads from and writes to | | 🧩 | Appraisal and interpretation | How an input gets read, doubted, reframed, or filtered before it becomes a felt reaction | | 🤝 | Modeling the other person | Trust, reputation, theory of mind, relationship memory, and group dynamics | | 🎭 | Expression | How the felt state actually gets turned into language, suppression, attention, and output-shaping signals for a host LLM | | 🧪 | Reward, stress, and circadian dynamics | Arousal and motivation driven by reward learning, chronic stress, and time of day | | 🫀 | Interoception | Real math on internal signals standing in for a body this system doesn't have, fed back into cognition only, never rendered | | ⚖️ | Behavioral-economics biases | How outcomes get weighted and remembered | | 🔌 | Language backends | Pluggable, from a zero-dependency lexicon to a real transformer model, so the same kernel runs identically whether or not a host wires in a real LLM |
npm run verify (examples/verify-all-mechanisms.js): 91 mechanics verified live/direct, 17 covered by other modules, 0 left blank. Full citation ledger, by theme: CALIBRATION.md.
How coherent is this, really?
Short version: ~81-85% with an LLM connected (especially when the host uses the control plane: packet compilation, N-best reranking, post-gen alignment), ~63-67% running standalone on the zero-dependency heuristic path, 0% subjective experience, by design and permanently. Self-assessed, qualitative estimates of how much of each layer is grounded in real theory/technique vs. own engineering judgment. This is not an average of the row values below. A small upward revision after multi-day chain batteries and a same-turn control plane that compiles internal state into enforceable generation constraints, not from module count alone, and still without external psychologist/user validation; the per-layer scores below remain qualitative and citation-weighted, not a claim of sentience, clinical fidelity, or validation against psychologist judges/real labeled chat data, which still don't exist.
Full citation ledger: 📑 CALIBRATION.md.
| Layer | With LLM | Heuristic only | Grounded in |
| --- | --- | --- | --- |
| State engine | ~82-85% | same | PID control (anti-windup, dynamic set points), Kalman filtering (now with real interoception-informed measurement noise), allostatic load (McEwen & Stellar 1993), prospect-theory loss aversion, TD reward-prediction-error with eligibility traces (Sutton & Barto), wanting/liking dissociation (Berridge & Robinson 1998) with allostatic-load-driven anhedonia, circumplex/PAD affect space with momentum/hysteresis, Holmes & Rahe life-event severity, the two-process sleep-pressure model (Borbély 1982), the opponent-process a/b dynamic (Solomon & Corbit 1974), a real general attentional-effort budget (Kahneman 1973) distinct from the self-regulation-specific one, plus 0.1.6's hyperbolic discounting (Ainslie 1975) and inhibitory control pool (Hofmann et al. 2012) pulling this row down slightly, and its own-design-heavy "butterflies"/global-mood-abatement additions pulling it down further; HappinessEngine, TraumaCascadeEngine, and YearningEngine/BoredomSystem's new per-user engagement now add real, verified dynamics on top, a small honest nudge upward, though much of the specific combining math there is still own engineering, not literal published constants |
| Semantic understanding | ~85-88% | ~68-73% | LLM: real language understanding. Heuristic: lexicon + concept-graph matching, keyword-triggered life-event detection, lexical-vs-context incongruence check, mean/variance anomaly detection, confidence-weighted routing between logical and affective reads, cultural-script activation (honor culture: Nisbett & Cohen 1996; self-construal: Markus & Kitayama 1991; reciprocity: Gouldner 1960); 0.1.6's metacognitive-confidence and source-monitoring additions land close to this row's existing average, no meaningful shift |
| Expression / output | ~88-92% | ~63-69% | Structured system-prompt injection, coherence validation against prior turns, attachment-weighted style adaptation, a full-state-weighted action-tendency policy, real suppression-cost accrual, cognitive-load-derived output metadata, a real approach-avoidance conflict dampening expression confidence (Miller 1944), an active real regulation-strategy selection (Gross 1998) replacing a single fixed suppression pipeline, a real divergent/convergent creative-mode temperature signal (Guilford 1967; Fredrickson 2001); pulled down by 0.1.6's own-design-heavy BlushSlipEngine (~28-35%) and HumanDiscourseShaper/PercentageOfAssets (~40-52%), each real and cited but scoring well below this row's prior average; ChildlikeMode genuinely widens the directive space (real suppression/boost signals for tone, discourse, chills); the round-61 control plane (ControlPacketCompiler, NBestReranker, PostGenStateAligner) closes a real chunk of the old state→text wiring gap by compiling this turn's own state into enforceable bans/must constraints and scoring candidates against them, so the "with LLM" figure moves up; the heuristic-only figure moves up only slightly, since the gain is concentrated in hosts that actually wire the control plane into generation |
| Cross-turn continuity | ~91-95% | same | Persistent state serialization, asymmetric trust/reputation tracking, attachment styles with rupture-and-repair (Bartholomew & Horowitz 1991; Gottman & Levenson 1992) now with state-dependent style switching under stress (Mikulincer & Shaver 2016), memory reconsolidation on retrieval (Nader et al. 2000), unresolved-memory flagging with intrusive resurfacing, idle-time-based consolidation, long-horizon memory decay with similarity-triggered reactivation and bittersweet nostalgic reconsolidation (Walker, Skowronski & Thompson 2003), grief as a real decaying-with-waves process (Bonanno 2004; Zisook & Shear 2009), permanent moral-injury scarring distinct from ordinary dissonance (Litz et al. 2009) now with a real, effortful redemption arc, a real autobiographical narrative with chapter coherence (McAdams 2001), permanent betrayal-trauma trust thresholds (Freyd 1996), and real cumulative somatic-marker decision bias (Damasio 1994); pulled down by 0.1.6's RelationalMemoryCatalog/GrudgeSystem/GhostingDetector/FrikiEngine (~35-50% each) diluting an otherwise very high-scoring row; this is the row the multi-day/multi-round system tests actually exercise (reunion reactivation, ritual/inside-joke reactivation, cumulative suspicion, cross-relationship arcs, co-regulation vs. isolation recovery); the 20-test long-chain battery and the round-58/59 relational-essentials set (reciprocity ledgers, affiliation set point, source monitoring, prospective memory) add further real, verified cross-turn dynamics on top, genuinely the strongest, most-validated row now |
| Subjective experience | 0% | 0% | Not a gap to close: no known way to build or verify this in any software |
| Headline | ~81-85% | ~63-67% | Small, honest upward revision from the previous baseline (~79-83% / ~62-66%), justified by the multi-day chain batteries plus the round-61 control plane compiling this turn's own state into enforceable generation constraints, not by row count or module count alone; still not an average of the rows above, still discounted for the real integrated-system validation (psychologist judges, labeled chat data, real-user testing) that still doesn't exist |
The headline stays below the row average because none of these numbers include validation against psychologist judges, regression against real labeled chat data, or real-user testing of whether the integrated pipeline reads as coherent. See CALIBRATION.md for what hasn't been empirically validated. These are still self-assessed qualitative estimates, not a computed weighted average over the per-mechanism table: treat the direction (a small, honest step up this round, from real multi-day system-test validation, not from module count) as the meaningful signal, not the exact digits.
Per-mechanism grounding
The table above scores each functional layer as a whole. This scores ten specific, individually-audited mechanisms instead: how much of that one technique is real citable theory vs. own engineering, independent of which layer it feeds.
| Mechanism | Grounded | Basis |
| --- | --- | --- |
| Hebbian co-activation plasticity | ~78-84% | Direct algorithmic reproduction of Hebb (1949): same update rule, applied to conversational mechanisms instead of neurons |
| Habituation / hedonic adaptation / decision fatigue | ~65-72% | Thompson & Spencer 1966 (habituation), Brickman & Campbell 1971 (hedonic treadmill) are solid; decision-fatigue/ego-depletion literature has known replication issues, cited for its shape, not as settled science |
| Forgetting curve + latent-memory reactivation | ~55-60% | Ebbinghaus (1885) grounds the general decay-over-time shape; the non-zero floor and keyword-triggered "spark" are its own design, not a reproduction of the classic curve (which decays to zero) |
| REM-style consolidation | ~50-58% | Sleep-dependent memory consolidation is real (Diekelmann & Born 2010; McClelland et al. 1995) as a general phenomenon; the specific cooling formula and idle-time threshold are engineering estimates |
| Expression debt / sensory-overload friction | ~35-42% | Cognitive load theory (Sweller 1988) motivates the general concept; the debt-accumulation-and-payback mechanic itself has no named psychological construct behind it, own design end to end |
| Dopaminergic wanting/liking split + TD(λ) eligibility traces | ~70-78% | Berridge & Robinson (1998) is a real, well-cited dissociation; Sutton & Barto's TD(λ) is a literal, standard reinforcement-learning algorithm applied to a per-relationship expectation store |
| Allostatic load / chronic-stress reactivity | ~58-66% | McEwen & Stellar (1993) and McEwen (1998) are real, well-cited theory; translating "wear from chronic stress" into a dynamic PID set point and a reactivity multiplier is its own control-systems engineering, not a reproduction of any measured allostatic-load curve |
| Attachment styles + rupture-and-repair | ~50-58% | Bartholomew & Horowitz's (1991) four-category model and the Gottman/Levenson rupture-and-repair literature are real; mapping OCEAN traits onto attachment-style buckets is our own engineering choice, explicitly not a validated psychometric equivalence |
| Vaillant defense hierarchy | ~55-63% | Vaillant's (1977) mature/neurotic/immature taxonomy is real, established clinical theory; the ego-health/cortisol-weighted tier-shifting mechanism that picks among them each turn is own design |
| Dual-valence relational bond field | ~38-46% | The individual pieces it reuses (diminishing-returns accumulation, kindling, asymmetric decay, rupture-and-repair) each draw on real cited work; the specific coupled two-accumulator update equations are our own engineering design end to end, not a reproduction of any published relational model |
| Approach-avoidance conflict | ~68-75% | Miller's (1944) real gradient-conflict model, implemented close to literally (two exponential gradients, steeper avoidance decay, a real crossover/vacillation zone); the specific decay constants and the expression-confidence dampening it feeds are own tuning |
| Two-process sleep pressure | ~72-80% | Borbély's (1982) Process S equation implemented directly (saturating exponential rise, exponential fall during a real "sleep" event); the specific rise/fall time constants are own engineering estimates, not measured circadian data |
| Opponent-process after-effect | ~65-72% | Solomon & Corbit's (1974) a-process/b-process structure (habituating peak, growing-and-lengthening undershoot with repetition) implemented as its literal qualitative shape; the specific growth-rate constants are own tuning |
| Grief as a decaying-with-waves process | ~45-52% | The general shape (long-tailed, non-monotonic, punctuated by real intrusive waves) draws on real bereavement research (Bonanno 2004; Zisook & Shear 2009) that explicitly rejects a fixed-stage model, deliberately NOT modeling Kübler-Ross stages, since that theory lacks the empirical support the shape below draws on instead; the power-law exponent and wave-rate constants are own design |
| Shame/guilt split | ~60-68% | Tangney & Dearing's (2002) real, well-established distinction (identity-level vs. behavior-level, differing persistence); which real internal signals feed each accumulator and the specific decay-rate ratio are own engineering |
| Moral injury / identity threat | ~55-63% | Litz et al.'s (2009) actual coinage and definition of "moral injury" as distinct from ordinary guilt, and Steele's (1988) self-affirmation/identity-threat theory, both real and well-matched to what's built; the permanence mechanism and severity-threshold/cascade-multiplier math are own design |
| Dynamic value conflict | ~50-58% | Schwartz's (1992) real, cross-culturally validated basic-values structure supplies the value set and the general "competing values create real tension" framing; the specific EMA nudge rule and conflict-scoring formula are own engineering, not a computational model Schwartz specified |
| Narrative self / chapter coherence | ~48-55% | McAdams' (2001; McAdams & McLean 2013) real narrative-identity framework motivates treating the self as a real, evolving story rather than pure accumulated state; the chapter-theme EMA, coherence formula, and crisis threshold are own engineering, not a computational reproduction of that framework |
| Developmental staging | ~30-38% | Piaget (1952) and Vygotsky (1978) motivate development as qualitative, experience-driven stage change rather than a clock, an explicit engineering borrowing of that SHAPE; the stage boundaries and per-stage trait modifiers are own tuning, not a claim of literal human-child-development equivalence |
| Betrayal trauma trace | ~58-65% | Freyd's (1996) actual coinage of "betrayal trauma" as a distinct wound from a trusted source is a real, exact match to this mechanic's trigger condition; the permanence-above-threshold decay shape and trust-threshold formula are own design |
| Somatic markers | ~55-62% | Damasio's (1994) real somatic-marker hypothesis motivates accumulative gut-feeling bias from past outcomes; the real token-overlap similarity and exponential-decay marker formula are own engineering, not a reproduction of any specific computational somatic-marker model |
| Regulation strategy selection | ~62-70% | Gross's (1998; Gross & John 2003) real reappraisal-vs-suppression cost/effectiveness taxonomy is well-established; the real argmax cost-benefit selection formula and specific base-cost constants are own engineering |
| Meta-emotion | ~52-60% | Gottman, Katz & Hooven's (1996) actual coinage of "meta-emotion" (real evaluative beliefs about one's own emotions) is a well-matched real citation; the specific standard-deviation valence formula and Neuroticism-bias multiplier are own design |
| Cultural scripts | ~40-48% | Real, distinct citations for each script (honor: Nisbett & Cohen 1996; self-construal: Markus & Kitayama 1991; reciprocity: Gouldner 1960), but the token-overlap activation mechanic and the specific weighting constants are own engineering, not a computational model any of those authors specified |
| Social network graph | ~35-42% | Real, standard social-network-analysis vocabulary (edge weight, coalition: Wasserman & Faust 1994); the specific weighting formula is own engineering end to end, not a reproduction of any published relational-network model |
| Group emotional contagion | ~50-58% | Barsade's (2002) real "ripple effect" finding (emotion spreads through a GROUP, not just dyadically, and group coherence is itself real and measurable) is a well-matched citation; the specific weighted-average contagion formula and coherence metric are own design |
| Global workspace competition | ~40-48% | Baars (1988; 2005) and Dehaene & Naccache (2001) are real, foundational consciousness-science theory; a real softmax over candidate saliences is a genuine, literal competition, but it's a deliberately narrow, explicitly-scoped-down engineering analog of "access to the workspace," not a claim of modeling ignition/broadcast dynamics or consciousness itself |
| Primary-process drives | ~55-63% | Panksepp (1998; Panksepp & Biven 2012) is real, cross-species-evidenced neuroscience for exactly these four systems (SEEKING/CARE/PLAY/PANIC-GRIEF) as distinct; the specific bounded-activation-plus-exponential-decay update rule and which existing internal signals feed each drive are own engineering |
| Sustained-negativity numbing | ~46-54% | Gilbert (1989; 2009) is real, well-cited theory for defensive numbing under sustained unresolved negative affect; the specific exposure accumulator and saturating dampening curve are own design, and the phenomenon is real but broader in Gilbert's own work than this one narrow accumulator captures |
| Hyperbolic temporal discounting | ~72-80% | V=R/(1+kd) is the literal, standard hyperbolic-discounting formula from the intertemporal-choice literature (Ainslie 1975; Mazur 1987); which internal signals feed the discount rate k per turn is own engineering |
| Inhibitory control pool | ~48-56% | A depletable inhibition resource distinct from ego-depletion/decision-fatigue is a real, debated construct in self-regulation research (Hofmann, Schmeichel & Baddeley 2012); the specific replenishment-vs-cost update rule and failure-probability sigmoid are own design, not measured data |
| Inequity aversion (fairness) | ~68-75% | U=x_i-α·max(x_j-x_i,0)-β·max(x_i-x_j,0) is a literal reproduction of Fehr & Schmidt's (1999) inequity-aversion model, one of the most cited formal models in behavioral economics; wiring it to conversational offers/turns is own integration |
| Ostracism pain detection | ~55-63% | Williams' (2007, 2009) real "need-threat" ostracism research (exclusion registering as a genuine distinct pain signal) motivates the mechanism; the specific ignore/exclude/inclusion weighting formula is own design |
| Metacognitive confidence | ~50-58% | Confidence as a function of evidence strength minus conflict is a real, established metacognition construct (Fleming & Lau 2014); the specific sigmoid and which internal signals count as "evidence" vs "conflict" are own engineering |
| Relational memory catalog (milestones/details/themes, recency/rupture-capped reunion tone, breakup habituation/initiator asymmetry) | ~47-55% | Grounded in real autobiographical-memory research on person-specific, affectively-tagged episodic detail (Conway & Pleydell-Pearce 2000) plus Berntsen & Rubin's (2002) real emotionally-significant-memory-reactivation finding, extended here to a real long-absence reunion, not just a calendar anniversary; Frederick & Loewenstein's (1999) real hedonic-adaptation finding (stronger for pleasant than unpleasant recurring events) grounds why an ordinary positive moment records with less NEW weight once a relationship is established; Sprecher, Felmlee, Metts, Lin & Christopher (1998) and Perilloux & Buss (2008) are real, published findings that a breakup's non-initiator reports more distress than its initiator, whose own reduced projection is grounded in Festinger's (1957) cognitive-dissonance account; a genuinely recent or unrepaired hurt now caps how warm a reunion's tone can read regardless of the lifetime warmth/hurt sum, own engineering closing a real gap the user's own 20-test battery found; the milestone-detection pattern matching, weight formula, decay floor, and specific habituation/rupture-factor constants are own design end to end |
| Friki Engine (taste, geek intensity, obsession, reveal-gate) | ~35-43% | Interest/hobby intensity as a graded, practiced construct draws loosely on flow and intrinsic-motivation research (Csikszentmihalyi 1990); the geek-level sigmoid, fandom-link propagation, and especially the confidence-gated reveal mechanism have no direct named psychological model behind them, own design |
| Somatic Activation System ("butterflies") | ~30-38% | The desire/uncertainty coupling driving anticipatory arousal is a real, plausible synthesis of appraisal theory (uncertainty appraisals: Smith & Ellsworth 1985) and approach-motivation literature, but S=I·A·U^κ and the ODE dB/dt=ρS(1-B)-λB are own formalization with no published equivalent — the phenomenon is real and well-known colloquially, the equations are engineering |
| Grudge/forgiveness system | ~40-48% | Grudge accumulation and multi-mode forgiveness (transactional/normative/temporal) loosely echoes real forgiveness-psychology typologies (McCullough, Worthington & Rachal 1997); the specific decay/weighting formulas and the never-auto-enacted retribution design are own engineering choices |
| Human discourse shaper (anti-AI narrative shape) | ~45-52% | Directly operationalizes real, measured findings from Hancock/StoryScope-style corpus comparisons of AI vs human narrative structure (over-explicit theming, high plot tidiness, monotone escalation); which text-generation directives counteract each axis, and by how much, are own engineering with no validated causal test yet that they work |
| Blush/slip engine (micro text slips) | ~28-35% | Motivated by real disfluency research showing genuine speech errors correlate with anxiety/arousal (Goldman-Eisler 1968); injecting typed micro-slips as a stand-in for that vocal phenomenon, the slip-type taxonomy, and the repair-probability formula are own design with no direct textual-disfluency literature this maps onto |
| Percentage of Assets / sparse layer-family introspection | ~40-48% | The Herfindahl-style concentration math is a real, standard economics tool (Herfindahl 1950; Hirschman 1945) applied honestly to which mechanism families were salient a given turn; it is explicitly introspection only, not a gating layer — the full pipeline still runs unconditionally every turn, so this row scores the honesty of that framing as much as the math itself |
| Affect alignment monitor (Δ-comparator, bounded correction) | ~45-52% | The Δ-and-bounded-online-correction pattern is a standard, real control-theory technique (proportional error correction); this is deliberately the only piece built from the originally-requested "Model Control Plane" spec — real hidden-state reading and activation steering were declined outright because no available backend exposes model internals, and faking that would be exactly the theater this ledger exists to catch |
| Contempt detection (status + disrespect, dual-gated) | ~62-70% | Gottman & Levenson's (1992) real, well-cited finding that contempt is the strongest single predictor of relational breakdown, plus Ekman & Friesen's (1986) real cross-cultural contempt expression, both a close match to what's built; the dual-gate requiring both status superiority AND accumulated disrespect is own design |
| Demand-withdraw loop | ~60-68% | Christensen & Heavey's (1990) real, well-replicated demand-withdraw pattern; the specific pressure-accumulation and threshold-crossing formulas are own engineering, not measured couple-conflict data |
| Face-threat sensitivity (positive/negative face) | ~65-73% | Brown & Levinson's (1987) real, foundational, extensively-cited politeness theory maps closely onto what's built; the specific warmth/autonomy-slack buffering terms are own tuning |
| Self-presentation management | ~55-63% | Goffman's (1959) real, foundational impression-management framework, plus Jones & Pittman's (1982) real strategy taxonomy; the felt-vs-presented gap formula and its maintenance-cost accrual are own design |
| Ego calibration (hubris/impostor, one shared axis) | ~68-76% | Kruger & Dunning (1999) and Clance & Imes (1978) are both real, extensively-cited, well-matched findings for the two directions this models; treating them as one shared track-record-vs-self-assessment axis rather than two separate constructs is own engineering |
| Reactance engine | ~68-75% | Brehm's (1966) psychological reactance theory is real, foundational, and extensively replicated; the specific boomerang-appeal formula is own tuning |
| Construal-level / psychological distance scaler | ~65-72% | Trope & Liberman's (2010) Construal Level Theory is real, well-established, and directly matches what's built (distance across temporal/spatial/social/hypothetical axes shifting abstraction); combining all four into one scalar distance is own simplification |
| Moral licensing | ~60-68% | Merritt, Effron & Monin's (2010) real, well-cited moral-licensing finding; the specific credit-accrual-and-partial-spend-down formula is own design |
| Self-handicapping | ~58-65% | Berglas & Jones' (1978) real, foundational self-handicapping finding; the specific ego-relevance × failure-risk × (1-confidence) product is own formalization |
| Relational afterglow | ~50-58% | Meltzer et al.'s (2017) real, empirically-measured "sexual afterglow" persistence is the closest real citation, generalized here beyond its original scope to any strong positive relational peak — that generalization itself is own engineering, not the study's own claim |
| Felt-obligation urgency decay | ~62-70% | Gouldner's (1960) real, foundational norm-of-reciprocity paper explicitly distinguishes debt size from felt urgency, a close match; the specific urgency half-life decay curve is own design |
| Betrayal reappraisal window | ~55-63% | Finkel et al.'s (2002) real, well-cited finding that a commitment-scaled window exists during which a betrayal's appraisal can still be revised; the specific window-duration formula and in-window trace-reduction magnitude are own tuning |
| Amusement (incongruity-resolution + benign violation) | ~65-72% | Suls' (1972) real, foundational incongruity-resolution account and McGraw & Warren's (2010) real, well-cited benign-violation theory both directly match what's built — requiring all three of incongruity, resolution, AND benignity; the specific product-of-three formula and repetition-habituation curve are own engineering |
| Moral disgust (CAD triad, purity leg) | ~65-73% | Rozin, Haidt & McCauley's (1999) real disgust-as-purity-violation account and Haidt's (2003) real, well-established CAD triad hypothesis are a close match to what's built — the previously-missing third leg alongside the codebase's existing contempt/anger coverage; the tolerance-floor and exposure-accumulation formulas are own design |
| Embarrassment (distinct from shame) | ~62-70% | Miller's (1996) real, foundational embarrassment account and Keltner & Buswell's (1997) real, well-cited appeasement-function finding both directly match what's built (audience-dependent, low-identity-stakes); the specific saturating-audience-size formula and identity-stakes suppression term are own engineering |
| Mortality salience (Terror Management Theory) | ~68-76% | Greenberg, Pyszczynski & Solomon's (1986) real, extensively-replicated Terror Management Theory is one of the best-validated findings cited anywhere in this table — the real two-phase proximal-suppression/distal-defense SHAPE is the cited finding; the specific delay/fade time constants are own tuning, not measured TMT experimental data |
| Relief (threat-must-precede-it positive spike) | ~48-56% | Frijda's (1986) real relational-theme taxonomy explicitly names "distress abating" as relief's real, distinct trigger, but the citation is thinner than the other rows here (relief gets one line in Frijda's broader taxonomy, not its own elaborated theory); the requires-prior-real-threat gating and the specific short-spike decay shape are own design end to end |
| RAGE/FEAR/LUST (3 remaining Panksepp primary-process systems) | ~65-73% | Panksepp (1998) and Panksepp & Biven (2012), already cited for SEEKING/CARE/PLAY/PANIC-GRIEF, are equally real and well-matched for these 3 — this project's own citation ledger had left them explicitly disclosed as missing for several rounds; the specific thwarted-goal/threat/attraction trigger formulas and decay are own engineering, same as the other 4 systems |
| Prestige (status via freely-conferred respect) | ~63-71% | Cheng, Tracy & Henrich's (2010) real, well-cited finding that dominance and prestige are two distinct real status pathways is a close match to what's built; the specific competence-demonstration-plus-recognition formula and its decay are own design |
| Framing effects | ~68-76% | Tversky & Kahneman's (1981) real, classic, extensively-replicated framing-effects finding is one of the best-established results in this entire table; deliberately kept introspection-only (does not feed back into emotional state, same discipline PercentageOfAssets follows) since auto-detecting real linguistic framing from arbitrary text has no reliable heuristic here — the specific frame-shift magnitude and ambiguity-scaling are own tuning |
| Ideal-self discrepancy | ~58-66% | Higgins' (1987) real self-discrepancy theory explicitly names this second, dejection-family gap as distinct from the already-modeled ought-self one — a close, direct match; the specific openness-linked aspiration bar and dejection-pressure formula are own engineering |
| Comparison Level for Alternatives | ~60-68% | Rusbult's (1980) real Investment Model of Commitment is a well-cited, foundational relationship-science finding extending the interdependence theory already cited elsewhere; the specific alternative-quality EMA and commitment-weighting formula are own design |
| Reflected glory (BIRGing/CORFing) | ~62-70% | Cialdini et al.'s (1976) real, classic, well-replicated field studies are a close match to what's built; the specific dampened-CORFing-relative-to-BIRGing asymmetry (own tuning, not measured from Cialdini's own data) and the publicness-scaling term are own engineering |
| Dream synthesis | ~50-58% | Domhoff's (2003) real continuity hypothesis and Hobson & McCarley's (1977) real activation-synthesis account are a well-matched, real grounding for "dreams synthesize real stored material, continuous with waking concerns"; the specific deep-sleep threshold, the topic/valence synthesis formula, and especially the unprompted-mention gate (own design end to end, no citation for that part specifically) are own engineering |
| Subconscious processing | ~60-68% | Kihlstrom's (1987) real cognitive-unconscious framework, Zajonc's (1968) real mere-exposure effect, and Wegner's (1994) real ironic-process theory are all well-established, well-cited, and closely matched to their respective sub-mechanisms; the losing-coalition-residue extension of GlobalWorkspace is a direct, real corollary of Dehaene & Naccache's own theory rather than a separate citation; the specific accrual/decay formulas for all three are own engineering |
| Bereavement grief (third-party loss) | ~65-73% | Shear & Shair's (2005) real attachment-based bereavement-grief account is a close, direct match for the real gap it fills: grief for someone other than the conversational partner, distinct from GriefEngine.triggerLoss()'s own relational-rupture-only trigger; the composite-key storage and shared power-law decay are own engineering, not new theory |
| Ambiguous loss (present but changed) | ~55-63% | Boss's (1999) real, well-cited ambiguous-loss concept is a close match for the real structural claim modeled: no clean boundary means no clean closure; the specific permanent-floor fraction (0.35 of peak) is own tuning, not measured from Boss's own qualitative work |
| Disenfranchised grief (socially unvalidated loss) | ~55-63% | Doka's (1989) real, coined disenfranchised-grief concept is a close match for the real claim modeled: unwitnessed loss decays slower; the specific social-validation-to-decay-constant scaling is own engineering, not derived from a measured dataset |
| Conservation-withdrawal (overwhelm-driven shutdown) | ~60-68% | Engel & Schmale's (1972) real, biologically-grounded conservation-withdrawal theory is a well-matched, real citation for sustained-overwhelm passive shutdown and solitude-pull, genuinely distinct from EmotionalImmuneSystem's numbing and BoredomSystem's understimulation; the specific threshold/recovery-rate formula is own tuning |
| Denial, repression, reaction formation (ego defenses) | ~65-73% | Anna Freud's (1936) real, foundational triad and Vaillant's (1977) real hierarchy, both already grounding the existing rationalization/projection/evasion rows, are equally close matches for these 3; the specific trait-to-weight mappings are own design, not measured from either source |
| Self-distancing speech (illeism) | ~62-70% | Kross et al.'s (2014) real, foundational finding and Moser et al.'s (2017) real, distinct fMRI/ERP evidence that third-person self-talk regulates emotion without the usual cognitive-control cost are both close, direct matches; the specific gate threshold and boost magnitude are own tuning |
| Anticipatory grief and prolonged grief disorder | ~62-70% | Rando's (1986) real anticipatory-grief account and Prigerson et al.'s (2021) real, current DSM-5-TR/ICD-11 diagnostic criterion are both well-established, closely-matched citations; the specific dampening fraction and the 6-month default window are own tuning, not measured from either source |
| Bereavement overload | ~60-68% | Kastenbaum's (1969) real, coined "bereavement overload" concept is a close, direct match for the real 2-part condition modeled (2+ genuinely concurrent griefs past a combined threshold, not one large grief alone); the specific threshold and minimum-concurrent-count are own tuning, not measured from his own clinical writing |
| Drift Diffusion Model (ambiguous-appraisal deliberation) | ~68-76% | Ratcliff's (1978) real, extensively-replicated Drift Diffusion Model is one of the best-validated sequential-sampling accounts in cognitive psychology; the literal formula (dx = A·dt + c·dW) is implemented directly, only the boundary/noise/step-to-ms conversion constants are own tuning |
| Signal-detection self-calibration (sarcasm detection) | ~65-73% | Green & Swets' (1966) real, foundational d'/criterion framework and Hautus' (1995) real correction for extreme proportions are both closely matched, standard formulas implemented directly; the specific 2-turn-deferred ground-truth proxy for what counts as a "hit" is own engineering |
| Hick-Hyman Law (workspace-complexity latency) | ~70-78% | Hick's (1952) and Hyman's (1953) real, classic, well-replicated logarithmic reaction-time law is implemented as its literal formula against GlobalWorkspace's own real coalition count; only the a/b constants (kept in the empirically observed range) are own tuning |
| Stevens' Power Law (per-kind sensory habituation) | ~65-73% | Stevens' (1957) real, foundational psychophysical law is implemented as its literal formula; the specific exponent-decay rate and floor are own tuning, not measured from Stevens' own data |
| Weber-Fechner Law (perceived-change-vs-baseline) | ~65-73% | Weber's (1834) and Fechner's (1860) real, classic, foundational psychophysics law is implemented as its literal log-ratio formula against the real pre-turn arousal baseline; the specific floor epsilon and output-scaling bounds are own engineering |
| Free energy estimate (Gaussian/Laplace closed form) | ~62-70% | Friston, Kilner & Harrison's (2006) real closed-form Gaussian approximation of variational free energy is implemented directly as F ≈ ½·precision·error² on top of the already-existing, already-cited PredictiveProcessingCore.js; this is the literal formula, not an approximation of an approximation |
| Nightmares (REM affect-regulation failure) | ~62-70% | Levin & Nielsen's (2007) real, well-established review frames a nightmare exactly as this module treats it: a real FAILURE mode, not a separate generator; the 4 real sub-signals it combines (amygdala/PFC ratio, unresolved fear, physiological panic, REM-rebound pressure) each reuse an already-existing, already-cited real module rather than re-deriving anything; the specific combining weights and threshold are own design |
| Oxytocin/vasopressin bonding chemistry | ~62-70% | Carter's (1998) real, foundational neuroendocrine account of attachment is a close, direct match for the real generalized felt-safety/idealization-suppression signal modeled; the specific build/decay rates and the 0.3/0.4 coupling coefficients into hijack threshold and appraisal are own tuning, not measured neurochemical concentrations |
| Endogenous opioid social-bonding analgesia | ~62-70% | Panksepp's (1998) own real opioid theory of separation distress (already cited for PANIC/GRIEF) and Machin & Dunbar's (2011) real review are both close, direct matches for the real pain-buffering-then-lost mechanism modeled; the specific buffer build/decay rates and the allostatic-load discount are own engineering |
| Symbolic/conversational jealousy | ~63-71% | White & Mullen's (1989) real jealousy theory, already grounding evaluate()'s own trend-comparison pathway, equally supports computeJealousy()'s own direct formula (already built, only newly wired); the specific real signal fed into it (max of this turn's own negative desirability and socialReference's relativeUtility) is own engineering |
| Delayed bereavement drive suppression | ~62-70% | Shear & Shair's (2005) real bereavement account, already cited, supports the real observation that acute grief's incapacitating effects build over days rather than landing instantly; the specific 36h rise constant is own tuning, not measured from a published onset-latency dataset |
| Composite "current concerns" dream | ~60-68% | Domhoff's (2003) own real repertoire-of-concerns account, already cited, is explicit that dreaming draws on multiple waking threads at once; the real weighted-blend formula and the specific per-source weighting are own engineering, not a reproduction of any published dream-content model |
| Real loyalty-conflict guilt | ~63-71% | Tangney & Dearing's (2002) real shame/guilt distinction, already cited for ShameGuiltSplit.js, is a close, direct match for genuine divided-loyalty guilt; the specific opposing-signs framing fed into getConflict() is own engineering, caught and fixed after an empirical test showed the naive same-sign reading under-detected real conflict |
| Accumulating desire (incentive-salience wanting) | ~63-71% | Berridge & Robinson's (1998) real, foundational incentive-salience account, already cited for DopaminergicEngine's own wanting/liking split, is a close, direct match; the specific saturating-exponential build/satiation formula is own engineering |
| Temptation under conflict | ~62-70% | Mischel's (1996) real hot/cool systems distinction is a close match for desire-becomes-temptation-under-constraint; reuses already-built real forbiddenness signals rather than inventing new ones, but the specific T=D·P·O combining formula is own design |
| Craving residual after resisting desire | ~62-70% | Wegner's (1994) real ironic-process theory, already cited for SubconsciousEngine's own topic rebound, is a close match applied to a distinct, desire-scoped real residual; the specific kindling/decay constants are own tuning |
| Resisting vs. yielding to temptation | ~63-71% | Baumeister et al.'s (1998) real ego-depletion account, already cited for EgoDepletionBudget/InhibitoryControlPool (reused directly here, not duplicated), is a close, direct match; the specific logistic weighting is own engineering |
| Chills ("escalofrío") peak response | ~62-70% | Maruskin, Thrash & Elliot's (2012) real, foundational chills construct is a close match for a genuinely distinct fast-rise/fast-decay resonance response; the specific 6-channel combining formula and per-cue habituation constants are own engineering |
| Secret-keeping cost and leak risk | ~63-71% | Slepian, Chun & Mason's (2017) real mind-wandering-cost finding and DePaulo & Kashy's (1998) real white-lie-frequency account are both close, direct matches; the specific cost-accrual and leak-probability logistics are own engineering |
| Shared relationship idioculture (inside jokes/rituals) | ~60-68% | Bell, Buerkel-Rothfuss & Gore's (1987) real, coined idioculture concept is a close match for jointly-built inside jokes/nicknames/rituals; the specific reinforcement/reactivation formulas are own design |
| Loneliness (connection-quality deficit) | ~62-70% | Cacioppo & Patrick's (2008) real, foundational loneliness account is a close, direct match for a felt-quality gap genuinely distinct from AffiliationThermostat's own contact-frequency tracking; the specific target/update formula is own engineering |
| Anticipated regret | ~60-68% | Zeelenberg's (1999) real anticipated-regret account is a close match, genuinely distinct in framing from the already-existing retrospective CounterfactualComparison; the specific yield-dampening formula is own design |
| Hope and its disappointment crash | ~62-70% | Snyder's (2002) real, well-established componential hope theory is a close match; the crash-scales-with-prior-hope claim is a real, distinct mechanism from ordinary RPE, and the specific evidence/crash formulas are own engineering |
| Self-compassion vs. self-attack | ~60-68% | Neff's (2003) real self-compassion account is a close match for genuinely different post-failure recovery trajectories; reuses ShameGuiltSplit's own real shame reading, and the specific recovery-multiplier formula is own design |
| Empathic accuracy (bias vs. accuracy split) | ~58-66% | Ickes' (1997) real empathic-accuracy paradigm is a close match; reuses MonteCarloToM's own real estimate as the biased read, and the specific bias/accuracy formulas are own engineering |
| Consolation fit (matching support type to need) | ~58-66% | Cutrona & Russell's (1990) real optimal-matching theory of social support is a close match; reuses EmpathyCompassion, and the specific fit/efficacy formula is own design |
| Sleep-quality coupling to next-day self-control | ~62-70% | Barber & Munz's (2011) real sleep-consistency/self-control finding is a close, direct match; applied to InhibitoryControlPool's own real level right after a real REM sweep, and the specific fragmentation/multiplier formulas are own engineering |
| Conversational misunderstanding repair | ~63-71% | Schegloff, Jefferson & Sacks' (1977) real, foundational conversation-analysis account of repair is a close, direct match, genuinely scoped narrower than the existing RepairProtocol's rupture-and-apology track; the specific classification thresholds are own tuning |
| Meaningful silence typing | ~58-66% | Jaworski's (1993) real account that silence carries distinct communicative types is a close match; the specific 4-type argmax classifier over already-computed bond/cooling/contempt/valence/arousal signals is own engineering |
| Typed intuition / gut-feeling layer, hypervigilance-biased reading | ~56-64% | Kahneman's (2011) real dual-process account and Mischel's (1996) hot/cool systems distinction are close, well-matched grounding for the general fast-hunch-vs-slow-override shape; reuses the already-built real k-NN+entropy hunch (Intuition.js) directly; Ozer et al.'s (2003) real hypervigilance-after-trauma finding now biases how an already-real ambiguous cue gets READ (strength, corroboration bar), not only whether the gate opens; the specific lexical-cue-to-prototype matching, bias-delta formulas, threshold-ramp constants, and Beta-style overconfidence tracker are own engineering, not a learned classifier |
| Threat cascade: entrapment, freeze, fragmented memory, persistence-adjusted lasting trace | ~60-68% | Porges' (1995, 2011) neuroception, Cannon's (1932) mobilization, Nijenhuis & van der Hart's (2011) real entrapment/tonic-immobility distinction, van der Kolk & Fisler's (1995) real fragmented-memory finding, and Herman's (1992) / Ozer et al.'s (2003) real post-event-safety and dissociation-predicts-chronicity findings together closely match what's built, now extended to real decay speed (slower without co-regulation, slower still for high peak severity) and a real scar floor for a poorly-consolidated event; the gate now also opens on a severe ontology concept match (betrayal/threat/humiliation) or real high stakes alone, closing a real gap where a genuinely severe event's own blended appraisal could read less extreme than the matched concept's own severity; reduced to 6 states by explicit design (not the full clinical taxonomy), deliberately gated on genuine extremity; the specific combining formulas, novelty-decay, and threshold constants are own engineering |
| Subjective well-being and its downstream leverage, soft-ceiling read | ~66-74% | Rutledge et al.'s (2014, PNAS) real, published well-being equation is implemented directly as its literal recursive-EMA equivalent; standard ligand-receptor mass-action kinetics are a real, established pharmacology formula reused honestly as a distinct satiation gate; Fredrickson's (2001) real broaden-and-build theory grounds the forward-feeding into gratitude, prosocial reputation, and stress recovery; the normalized 0..1 read is a real logistic squash (own tuning, Weber-Fechner-consistent diminishing-marginal-sensitivity shape already used elsewhere in this codebase) instead of a hard clamp, so it asymptotes without ever fully pinning at the ceiling; which specific mechanisms receive that leverage is own engineering |
| Yearning (anhelo) for someone genuinely absent, breakup-initiator-adjusted, real ambient pull during real absence | ~57-66% | Reuses Schultz, Dayan & Montague's (1997) real TD-learning reward-prediction-error formula directly (via the already-built DopaminergicEngine.computeRPE(), not a reimplementation) for the anticipation/reality-check cycle; Schacter & Addis's (2007) real constructive-episodic-simulation finding grounds treating an imagined future as a real reward signal; Mikulincer & Shaver's (2007) real attachment-strategy account motivates the anxious/avoidant γ split; Sprecher et al. (1998)/Perilloux & Buss (2008) ground why being left amplifies real pain while Festinger (1957) grounds why having left dampens the real fantasy itself; a real accumulated yearning trace now also measurably amplifies the separate reunion-reactivation mechanism's own boom on actual reunion; the idealization weighting, kindling-trace formula, ambient-absence ramp, and conservative real-lexical-cue-only trigger condition for the message-driven path are own engineering |
| ChildlikeMode: a real playful stance, not baby-talk | ~54-63% | Panksepp's (1998) real PLAY primary-process account (already cited for PrimaryDrives.js); Bowlby (1988)/Ainsworth (1978) real secure-base finding that felt security enables exploratory/playful behavior; Fredrickson's (2001) real broaden-and-build theory (already cited for HappinessEngine.js) grounds why positive affect broadens toward play; a real smoothed, persistent per-user activation gates real (never-zeroing) suppression of adult-serious weight, a real play/friki-share boost, and a real hard abort on genuine threat/shame/precisionMode; the specific weight constants, gate threshold, and smoothing/decay rates are own engineering |
| Per-user engagement/boredom, extending the pre-existing BoredomSystem | ~55-64% | Eastwood, Frischen, Fenske & Smilek's (2012) real boredom-as-unengaged-attention account (the same real citation the pre-existing global BoredomSystem already used); Berlyne's (1960) real inverted-U arousal/interest account grounds understimulation; real PartnerPull composes already-tracked bond/desire/yearning/oxytocin/aversion/cooling/betrayal-trace signals into one real "does this person still pull attention" read, with a real hard override so genuine threat is never misread as boredom; the specific weight constants and the non-deterministic novelty-seeking probability are own engineering |
Human Dynamics That Emerge On Their Own
In tests lasting days and weeks, the system doesn't simply label a shift. Human dynamics of connection, absence, doubt, judgment, harm, and recovery emerge from the state that persists over time.
| Human Dynamics | What is observed over time | | --- | --- | | Reconnection after a long time | The warmth and weight of past experiences return at first contact, without starting from scratch | | Memory triggered by an intimate phrase | A ritual, nickname, or inside joke suddenly reopens memories and emotions | | Suspicion that builds up little by little | Repeated small evasions build distrust over time, rather than an instant judgment | | Not inventing danger where there is none | Threats do not appear in neutral messages; doubt is reserved for ambiguity | | Viewing betrayal differently depending on prior state | The same wound hurts differently if expectations were high or if the bond was already cold | | Freezing when there is no way out | Faced with the same hostility, one reacts if escape is possible; if trapped, one freezes more | | Healing faster with genuine support | After a blow, containment and validation change mood, stress, and trust; minimizing it isolates | | Grieving for someone who is not the partner | One can suffer from an external loss without it meaning a breakup with the partner | | Getting tired of the same repeated blow | Identical things lose their impact; new things hurt again | | Life in stages | Over a long arc, desire, distance, reconnection, and doubt appear without being manually orchestrated | | Desire in "inappropriate" moments | Caring or reconnecting can awaken attraction even if the context is delicate | | Love and rejection at the same time | After a strong conflict, attachment and pain can coexist, rather than just one clear feeling | | Cooling off without reaching hatred | Initiative and interest drop when there is no longer novelty or pull, even if there is no fight | | Illusion that blinds for a while | When things are going very well, it is hard to register the same warning signs | | Love-bomb then sparse contact | Intense early warmth fades as contact becomes sporadic; the bond is re-read as less genuine | | Trust eroded by quiet broken promises | Small unkept commitments accumulate into lower credibility and a harsher opinion of reliability | | Disagreement without hatred | A weak idea can be opposed while the bond itself stays intact | | Asking for comfort and being minimized | A bid for support that meets dismissal raises loneliness and protest more than matched care does | | Social fatigue after an intense stretch | After a dense period of contact, the pull to withdraw can rise even if the person is still valued | | Holding a boundary under pressure | Attraction or play can rise, yet the system can still refuse to yield | | Shared humor, then flat correctness | When joint laughter disappears, distance can grow without an explicit fight | | Jealousy from praise of a rival | Admiring a third party can raise jealousy and resentment without a tracked second relationship | | First impressions that stick | A strong early read keeps coloring later ambiguous signals | | Protecting a partner under attack | An external attack can raise protective care and steady the bond | | Forgiveness in words, memory in the body | Trust may move before chemistry does; grievance can remain after a verbal reopen | | Fatigue changing how conflict sounds | Under strain, disagreement leans more combative or blunt than when rested | | Reunion with residual caution | Coming back after absence can restore warmth while skepticism about motives still checks the moment | | Play giving way to seriousness | A playful stance can stay up until real threat, while heavy topics raise boredom or mismatch instead of trauma | | Gratitude softening old scorekeeping | Real help can raise sustained gratitude and slightly ease grievance or boredom | | Hope before a plan, crash when it fails | Anticipation amplifies the drop when a promised event is cancelled | | Detecting opportunism and rewiring the read | When favors and affection look one-sided, credibility, boundaries, and graph classification move together | | Validation versus invalidation of one's story | Being told "you're not crazy" eases recovery; being dismissed stings and feeds self-attack | | Long arcs that reorganize several systems at once | Over weeks, flirt, reliability, comfort-seeking, boundaries, and repair can shift as one life, not as isolated flags |
Prerequisites
None required. HeuristicProvider runs standalone with zero npm dependencies. Optionally, install Ollama if you want OllamaProvider to give the semantic modules (dissonance, theory of mind, appraisal) real language understanding instead of keyword heuristics.
Installation
npm install totemheart
# or
pnpm install totemheart
# or
yarn add totemheartUsage
import { Totemheart, Personality, VERSION } from 'totemheart'
console.log( VERSION ) // '0.1.5', also available as Totemheart.VERSION and in toJSON().version
const ai = new Totemheart( {
personality: new Personality( { neuroticism: 0.7, agreeableness: 0.3 } ),
} )
const result = await ai.processInput( 'te quiero mucho', { userId: 'user-1' } )
console.log( result.text, result.emotionalState )
ai.tick( 1 ) // advance decay/homeostasis/forgetting, call this on your own clockWiring it into a real LLM (Claude, GPT, Ollama, anything)
processInput() includes a systemPrompt: a provider-agnostic block of text describing the current emotional state (dominant emotion, valence/arousal, cognitive stress, cortisol, fatigue, active defense mechanism...) with instructions for an LLM to let it shape tone and content. Prepend it to whatever system message field your provider uses:
const result = await ai.processInput( userMessage, { userId } )
// Anthropic
await anthropic.messages.create( {
model : 'claude-...',
system : result.systemPrompt,
messages : [ { role: 'user', content: userMessage } ],
} )
// OpenAI-compatible / Ollama chat
await client.chat.completions.create( {
messages: [ { role: 'system', content: result.systemPrompt }, { role: 'user', content: userMessage } ],
} )result.structuredContext gives you the same information as plain JSON if you'd rather build your own prompt formatting. Call ai.getSystemPrompt() on its own (no new turn) to seed the very first message of a conversation, or to refresh context after ai.idle()/ai.tick() shifts the mood between turns.
Model Control Plane: making the LLM's actual output text respect the state
systemPrompt alone is a real, honest best-effort: nothing verifies the model actually followed it. processInput() also returns a real controlPacket (structured, machine-readable state, with bans/must and a softmax priority for when directives conflict), stateLockedMemory (a short digest to re-inject every turn so the model's own context window is never the source of truth for the affective state), and decodingSteering (a real temperature and bannedPhrases list for a host's own decoding parameters). systemPrompt itself already carries this SAME turn's own hardened bans/must as an explicit "RESTRICCIONES DE ESTE TURNO" block.
For a host that wants an actual guarantee, not just a well-worded prompt, src/control/ also ships PostGenStateAligner (scores a candidate reply against the control packet), NBestReranker (picks the best of K real candidates), and RepairRewriter (local, deterministic fixes for a mostly-good candidate). The full loop:
const result = await ai.processInput( userMessage, { userId } )
const candidates = await Promise.all(
Array.from( { length: 3 }, () => llm.generate( result.systemPrompt, userMessage ) ),
)
const { best } = ai.nBestReranker.rerank( candidates, result.controlPacket )
let finalText = best.text
if ( best.align < 0.7 ) {
finalText = ai.repairRewriter.repair( best.text, best.violations, result.controlPacket ).text
}Run npm run controlled-generate (examples/controlled-generate.js) to see this end to end against a deterministic mock LLM (no network access needed). Honest limits, not glossed over: Totemheart never calls an LLM itself, so this is real infrastructure a host wires their own model into, not something that runs on its own; ActivationSteeringBridge's own per-axis coefficients only do anything with real model-weight access (a local open-weight checkpoint), never with a closed API; FineTuneCurriculum only accumulates and exports a real (controlPacket, user, assistant) dataset, it doesn't run training itself. Full write-up and citations in CALIBRATION.md.
Run npm run demo for a full scripted conversation showing decay, hedonic adaptation, dopaminergic surprise, sensory overload, and a generated system prompt in action. Run npm test for the mechanic-level test suite. Run npm run stress-test (examples/full-stress-test.js) for a before/after weight trace across a battery of positive/negative/severe shocks, repeated hostility, idle time passing, hardware latency, worn-path caching, and a group/bystander turn. Run npm run upgrade-round-mock for the momentum/hysteresis, allostatic-load, wanting/liking, reconsolidation, attachment-style, graded-hijack, Vaillant-defense, expression-policy, resource-allocation, and circadian-coupling round, or npm run lovehate-mock for LoveHateEngine's ambivalence, kindling, and rupture-and-repair cycle end to end.
Gold-standard regression checks: npm run gold-standard-mock (examples/five-emergent-human-tests-mock.js) runs 5 real, multi-week emergent-behavior scenarios end to end (verbal-vs-chemical forgiveness lag, symbolic jealousy from comparison alone, third-party bereavement vs. relational cooling, blush/micro-slips under romantic tension with a strict factual mask, and ex-partner reentry competing against a newer bond). Tests 1 and 5 (forgiveness lag, ex reentry) are the two with the cleanest, most reproducible emergent signal and are the ones worth re-running as a qualitative gold standard before every release, on top of the automated suite above: real bondNet/trust recovering days before oxytocin/opioid do, and a real loyalty conflict with no automatic reset to whichever bond has the higher instantaneous oxytocin reading.
Real ML instead of heuristics: TransformersProvider
HeuristicProvider is a hand-written lexicon; TransformersProvider runs an actual model trained on GoEmotions (28 emot
