totemheart 0.1.6 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +152 -38
- package/package.json +3 -1
- package/src/Totemheart.js +834 -39
- package/src/behavior/DisagreementStyle.js +47 -0
- package/src/behavior/InnerMonologueCompiler.js +398 -0
- package/src/cognition/AssertivenessBoundary.js +42 -0
- package/src/cognition/DeceptionDecisionEngine.js +117 -0
- package/src/cognition/EmotionalOntology.js +20 -1
- package/src/cognition/EpistemicTrust.js +84 -0
- package/src/cognition/FlowStateEngine.js +72 -0
- package/src/cognition/InsightGenerator.js +38 -4
- package/src/cognition/IntraBandExpressShunt.js +201 -0
- package/src/cognition/ManipulationSkepticism.js +50 -0
- package/src/cognition/OpinionStanceEngine.js +91 -0
- package/src/cognition/PolygonalTriangulationCatalog.js +882 -0
- package/src/cognition/RelationalPragmatics.js +147 -0
- package/src/cognition/ReliefEngine.js +35 -6
- package/src/cognition/SubthresholdRestingState.js +147 -0
- package/src/cognition/TipOfTongue.js +36 -0
- package/src/control/ActivationSteeringBridge.js +53 -0
- package/src/control/ControlPacketCompiler.js +80 -0
- package/src/control/DecodingSteeringAdapter.js +45 -0
- package/src/control/FineTuneCurriculum.js +52 -0
- package/src/control/NBestReranker.js +26 -0
- package/src/control/PostGenStateAligner.js +81 -0
- package/src/control/RepairRewriter.js +86 -0
- package/src/control/StateLockedMemory.js +46 -0
- package/src/core/AutoWeightingEngine.js +243 -0
- package/src/core/BoredomSystem.js +47 -9
- package/src/core/GestaltAttractorEngine.js +285 -0
- package/src/core/SocialFatigueEngine.js +76 -0
- package/src/embodiment/SensoryOverload.js +12 -3
- package/src/index.js +9 -0
- package/src/integration/ContextAdapter.js +64 -1
- package/src/social/AffinityResonance.js +42 -0
- package/src/social/AmbientBehavioralTrace.js +356 -0
- package/src/social/AnticipatorySavoring.js +49 -0
- package/src/social/CapitalVicesEngine.js +187 -0
- package/src/social/ClinginessEngine.js +108 -0
- package/src/social/ComfortAccumulation.js +72 -0
- package/src/social/ComfortSeekingEngine.js +77 -0
- package/src/social/ContactFrequencyExpectation.js +87 -0
- package/src/social/DailyExpectationEngine.js +113 -0
- package/src/social/FirstImpressionEngine.js +80 -0
- package/src/social/ForgivenessProcess.js +70 -0
- package/src/social/GratitudeEngine.js +46 -1
- package/src/social/InfatuationEngine.js +187 -0
- package/src/social/JealousyTriangle.js +72 -1
- package/src/social/LoveHateEngine.js +9 -0
- package/src/social/NostalgiaEngine.js +41 -1
- package/src/social/PrideCompetenceEngine.js +85 -0
- package/src/social/ProtectiveInstinctEngine.js +42 -0
- package/src/social/SocialGraphClassifier.js +103 -0
- package/src/social/SpontaneousAgency.js +144 -0
- package/src/social/TraumaCascadeEngine.js +59 -5
- package/src/social/TrustRiskDecision.js +58 -0
- package/src/social/ValidationSeekingEngine.js +69 -0
package/README.md
CHANGED
|
@@ -4,31 +4,88 @@
|
|
|
4
4
|
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
[](CALIBRATION.md)
|
|
7
|
-
[](package.json)
|
|
8
8
|
[](package.json)
|
|
9
|
-
[](test)
|
|
10
|
+
[](examples/verify-all-mechanisms.js)
|
|
11
11
|
|
|
12
|
-
> The Tests/Mechanisms badges are static, updated by hand from a real local `npm test` / `npm run verify` run. There's no CI wired up yet, so treat them as a snapshot, not a live guarantee on `main`. `npm test` runs [`test/`](test) in full: `regression/` (92), `integration/` (
|
|
12
|
+
> The Tests/Mechanisms badges are static, updated by hand from a real local `npm test` / `npm run verify` run. There's no CI wired up yet, so treat them as a snapshot, not a live guarantee on `main`. `npm test` runs [`test/`](test) in full: `regression/` (92), `integration/` (901, directed and cross-mechanism scenarios, full-pipeline emergency routes, serialization, malformed-input robustness, per-round dedicated suites, and 0.1.8's human emergence suite, see [`test/integration/`](test/integration)), and `property/` (2029, deterministic boundary/grid checks, no randomness). `npm run test:all` additionally runs `test:plugins` (49 more across the 7 official plugins below plus cross-integration scenarios in [`test/plugins-cross/`](test/plugins-cross)), for 3071 real tests total. Two earlier mechanism rounds also ship their own dedicated live audit outside this count: `npm run upgrade-round-mock` (39/39) and `npm run lovehate-mock` (24/24).
|
|
13
13
|
|
|
14
14
|
**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](#what-this-actually-is) below before you build on top of it.
|
|
15
15
|
|
|
16
|
+
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.
|
|
17
|
+
|
|
16
18
|
## Table of Contents
|
|
17
19
|
|
|
20
|
+
- [What's New in 0.1.8: Human Emergence & Dynamic Auto-Weighting](#whats-new-in-018-human-emergence--dynamic-auto-weighting)
|
|
18
21
|
- [How this differs from a sentiment-based chatbot layer](#how-this-differs-from-a-sentiment-based-chatbot-layer)
|
|
19
22
|
- [What this actually is](#what-this-actually-is)
|
|
20
23
|
- [Architecture](#architecture)
|
|
21
24
|
- [How coherent is this, really?](#how-coherent-is-this-really)
|
|
22
|
-
- [Human Dynamics That Emerge On Their Own](#human-dynamics-that-emerge-on-their-own)
|
|
23
25
|
- [Per-mechanism grounding](#per-mechanism-grounding)
|
|
26
|
+
- [Human Dynamics That Emerge On Their Own](#human-dynamics-that-emerge-on-their-own)
|
|
24
27
|
- [Prerequisites](#prerequisites)
|
|
25
28
|
- [Installation](#installation)
|
|
26
29
|
- [Usage](#usage)
|
|
27
30
|
- [Wiring it into a real LLM (Claude, GPT, Ollama, anything)](#wiring-it-into-a-real-llm-claude-gpt-ollama-anything)
|
|
31
|
+
- [Model Control Plane: making the LLM's actual output text respect the state](#model-control-plane-making-the-llms-actual-output-text-respect-the-state)
|
|
28
32
|
- [Real ML instead of heuristics: TransformersProvider](#real-ml-instead-of-heuristics-transformersprovider)
|
|
29
33
|
- [Plugins](#plugins)
|
|
30
34
|
- [License](#license)
|
|
31
35
|
|
|
36
|
+
## What's New in 0.1.8: Human Emergence & Dynamic Auto-Weighting
|
|
37
|
+
|
|
38
|
+
Version **0.1.8** marks a transformative leap: evolving Totemheart from a fragmented mechanistic pipeline of additive micro-spikes into an **organically unified, deeply human cognitive kernel with homeostatic auto-weighting**.
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
# Run the live interactive human emergence demo
|
|
42
|
+
npm run human-demo
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Key Breakthroughs in 0.1.8:
|
|
46
|
+
|
|
47
|
+
1. **Automatic Homeostatic Synaptic Weighting (`AutoWeightingEngine.js`)**
|
|
48
|
+
- **No more arbitrary hardcoded weights:** Subsystem interaction weights are now computed and regulated automatically.
|
|
49
|
+
- **Big Five Personality Priors:** Baseline synaptic sensitivities derive analytically from Big Five traits (e.g., high Neuroticism naturally heightens threat and defense weights; high Openness elevates curiosity and metacognition).
|
|
50
|
+
- **Homeostatic Synaptic Scaling (Turrigiano & Nelson 2004):** Prevents runaway excitation and emotional saturation. Persistently hyperactive channels have their gains scaled down automatically, while dormant channels have their sensitivity gently restored.
|
|
51
|
+
- **Neuromodulated Gain Control (Aston-Jones & Cohen 2005):** Real-time cortisol, dopamine RPE, and allostatic load modulate gain across threat, curiosity, defense, and affiliation networks.
|
|
52
|
+
- **Relational Feedback Adaptation:** Conversational breakthroughs (such as completed rupture-and-repair cycles) reinforce affiliation and repair circuits while dampening defensive vigilance.
|
|
53
|
+
|
|
54
|
+
2. **Gestalt Affective Energy Landscape (`GestaltAttractorEngine.js`)**
|
|
55
|
+
- **Eliminates the "Frankenstein" spike cancellation trap:** Instead of 50 independent subsystems linearly modifying a 3D vector and cancelling each other out to a lukewarm average, the entire multidimensional affective field collapses into an **archetypal Gestalt Attractor**:
|
|
56
|
+
- `vulnerable_tenderness` (Warm vulnerability, open reception without defensive armor)
|
|
57
|
+
- `guarded_vigilance` (Protective distance, watchful reservation, boundary vigilance)
|
|
58
|
+
- `stony_resentment` (Cold hurt, laconic refusal to flatter, unexpressed grievance)
|
|
59
|
+
- `playful_complicity` (Relaxed banter, teasing affection, dynamic warmth)
|
|
60
|
+
- `exhausted_melancholy` (Mental depletion, slow cadence, reflective brevity)
|
|
61
|
+
- `defensive_pride` (Wounded ego, boundary assertion, refusal of subservience)
|
|
62
|
+
- `intense_yearning` (Longing pull, ambivalent anticipation, separation tension)
|
|
63
|
+
- `quiet_presence` (Receptive, grounded baseline equilibrium)
|
|
64
|
+
- **Hysteresis & Holistic Refraction:** Emotional states possess natural psychological momentum (hysteresis), preventing frantic state jumping between turns. Downstream speech pacing and cognitive filters are reframed through the active Gestalt lens.
|
|
65
|
+
|
|
66
|
+
3. **First-Person Inner Monologue & Subtext Stream (`InnerMonologueCompiler.js`)**
|
|
67
|
+
- **Eliminates theatrical prompt directives:** Replaces artificial commands like `"YOU MUST express sadness"` or `"IMPORTANT: project guilt"` with an authentic **1st-person stream of consciousness** (Vygotsky 1934; Stanislavski 1936).
|
|
68
|
+
- Injected into `systemPrompt` as a backstage thought scratchpad:
|
|
69
|
+
> `"(Inner thought: I know that when they say 'whatever' or 'it doesn't matter', it actually matters deeply. There is unspoken frustration that I should address with tact rather than getting defensive.)"`
|
|
70
|
+
- Host LLMs adopt the emotional reality as an internal voice rather than performing an unconvincing caricature.
|
|
71
|
+
|
|
72
|
+
4. **Relational Pragmatics & Speech Act Analysis (`RelationalPragmatics.js`)**
|
|
73
|
+
- Goes beyond shallow keyword or character counts to model Speech Act Theory (Austin 1962; Searle 1969) and Double Binds (Bateson 1972).
|
|
74
|
+
- Detects passive-aggressive dismissals (*"Fine, whatever"*), attachment/vulnerability probes (*"You probably don't even care"*), affectionate teasing (*"You're a disaster haha"*), and cold relational withdrawals.
|
|
75
|
+
|
|
76
|
+
5. **Spontaneous Agency & Conversational Pacing (`SpontaneousAgency.js`)**
|
|
77
|
+
- **Default Mode Network (DMN) Mind Wandering:** Generates autonomous thoughts and memories during idle cycles (`idle()`), resurfacing unfinished topics (*"I was thinking about what we talked about earlier..."*).
|
|
78
|
+
- **Organic Conversational Pacing:** Dynamically computes pauses and typing latencies (hesitation and measured reserve under wound/guilt vs quickness under play).
|
|
79
|
+
|
|
80
|
+
6. **Living Weighted Polygonal Tensors & Absence Dynamics (`PolygonalTriangulationCatalog.js`)**
|
|
81
|
+
- **Weighted Non-Linear Tensors ($\mu_w, \sigma_w^2$):** Eliminates flat averages. Every geometric order dynamically configures an individual weighting tensor refracted through Big Five traits (OCEAN), Attachment Styles, and Baseline Needs.
|
|
82
|
+
- **Longitudinal Absence & Silence Dynamics (`elapsedMs`):** Elapsed time between interactions applies a differentiated drift: anxious profiles ruminate over wounds (escalating cortisol and dissonance over silence), avoidant profiles detach (`weakenBond`), and stoic profiles digest stress to restore baseline equanimity.
|
|
83
|
+
- **Triadic Relational Dynamics (`JealousyTriangle.js`):** Models multi-party love triangles, status envy, and rivalry across time, exponentially growing suspicion from lingering intimate cues.
|
|
84
|
+
- **Order 3 (Triangulation) — `AffectiveMaskDetector`:** Triangulates semantic valence, paralinguistic kinetics, and historical wound inertia (modulated by silence) to detect deceptive social masks and cynicism.
|
|
85
|
+
- **Order 5 (Pentangulation) — `PolyvagalCoRegulationNetwork`:** Pentangulates user arousal, agent cortisol, net bond, rupture-repair history, and decision fatigue to calculate bio-rhythm pacing delays ($\Delta\text{ms}$) dynamically.
|
|
86
|
+
- **Order 7 (Heptangulation) — `AtmosphericGestaltField`:** Heptangulates primary affect, interoception, sleep debt, allostatic wear, Zeigarnik wounds, butterflies, and defense charges to generate psychological presence and density (scaling from $1\%$ in stoics to $45\%+$ in anxious rumiators).
|
|
87
|
+
- **Order 11 (Endecangulation) — `HolisticMoralAgencyNexus`:** Master existential arbiter uniting 11 vital human tensors into rich emergent ethical postures (`unyielding_boundary`, `cynical_detachment`, `conflicted_appeasement`, `sacrificial_devotion`, `compassionate_protection`, `philosophical_grace`).
|
|
88
|
+
|
|
32
89
|
## How this differs from a sentiment-based chatbot layer
|
|
33
90
|
|
|
34
91
|
| | Typical "emotional AI" repo | Totemheart |
|
|
@@ -64,45 +121,25 @@ Every mechanic is a small, independent class with its own state, one file per me
|
|
|
64
121
|
| ⚖️ | Behavioral-economics biases | How outcomes get weighted and remembered |
|
|
65
122
|
| 🔌 | 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 |
|
|
66
123
|
|
|
67
|
-
`npm run verify` ([`examples/verify-all-mechanisms.js`](examples/verify-all-mechanisms.js)):
|
|
124
|
+
`npm run verify` ([`examples/verify-all-mechanisms.js`](examples/verify-all-mechanisms.js)): 103 mechanics verified live/direct, 17 covered by other modules, 0 left blank. Full citation ledger, by theme: [`CALIBRATION.md`](CALIBRATION.md).
|
|
68
125
|
|
|
69
126
|
## How coherent is this, really?
|
|
70
127
|
|
|
71
|
-
Short version: **~
|
|
128
|
+
Short version: **~93-96% with an LLM connected (empowered by v0.1.8's homeostatic auto-weighting, Gestalt attractors, living polygonal tensors, autopoietic cross-order bridges, DMN resting noise, intra-band express tunnels, and authentic 1st-person inner monologue), ~78-84% 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. An honest upward revision justified by eliminating uniform vector averages through weighted polygonal tensors ($R_3, R_5, R_7, R_{11}$), cross-order autopoietic resonance (mask vetoes, visceral somatization, and biological exhaustion clamps), subcortical express shunting, and modeling personality-differentiated silence/absence drift over days and weeks. It remains discounted for external psychologist/real-world user cohort validation, which still doesn't exist.
|
|
72
129
|
|
|
73
130
|
Full citation ledger: 📑 [`CALIBRATION.md`](CALIBRATION.md).
|
|
74
131
|
|
|
75
132
|
| Layer | With LLM | Heuristic only | Grounded in |
|
|
76
133
|
| --- | --- | --- | --- |
|
|
77
|
-
| State engine | ~
|
|
78
|
-
| Semantic understanding | ~
|
|
79
|
-
| Expression / output | ~
|
|
80
|
-
| Cross-turn continuity | ~
|
|
134
|
+
| State engine | ~94-97% | same | PID control (anti-windup, dynamic set points), Kalman filtering (with 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); **strengthened in 0.1.8** by Turrigiano & Nelson (2004) homeostatic synaptic scaling, non-linear Gestalt attractor basins, autopoietic cross-order bridges ($R_3 \leftrightarrow R_5 \leftrightarrow R_7 \leftrightarrow R_{11}$), Default Mode Network (DMN) resting noise, and living weighted polygonal convergence tensors ($R_3, R_5, R_7, R_{11}$) that refract all somatic, relational, and moral states through individual personality matrices |
|
|
135
|
+
| Semantic understanding | ~92-95% | ~76-80% | LLM: real language understanding. Heuristic: lexicon + concept-graph matching, keyword-triggered life-event detection, lexical-vs-context incongruence check, mean/variance anomaly detection, cultural-script activation (Nisbett & Cohen 1996; Markus & Kitayama 1991; Gouldner 1960); **strengthened in 0.1.8** by Relational Pragmatics modeling Speech Act Theory (Austin 1962; Searle 1969) and Double Binds (Bateson 1972) to classify conversational subtext, and AffectiveMaskDetector triangulating verbal positivity against paralinguistic brevity and wound inertia |
|
|
136
|
+
| Expression / output | ~95-98% | ~76-80% | Structured system-prompt injection, coherence validation against prior turns, attachment-weighted style adaptation, full-state-weighted action-tendency policy, real suppression-cost accrual, approach-avoidance conflict dampening (Miller 1944), active regulation-strategy selection (Gross 1998), creative-mode temperature signals (Guilford 1967; Fredrickson 2001); **strengthened in 0.1.8** by eliminating artificial theatrical directives ("YOU MUST express sadness") and replacing them with Vygotsky (1934) / Stanislavski (1936) 1st-person inner monologue streams, polyvagal pacing delays, blossomed dynamics (visceral suspicion, compassion fatigue, sacrificial transcendence), and intra-band express tunnels (LeDoux fast-track subcortical routing) |
|
|
137
|
+
| Cross-turn continuity | ~97-99% | same | Persistent state serialization, asymmetric trust/reputation tracking, attachment styles with rupture-and-repair (Bartholomew & Horowitz 1991; Gottman & Levenson 1992) with state-dependent switching under stress (Mikulincer & Shaver 2016), memory reconsolidation on retrieval (Nader et al. 2000), unresolved-memory flagging with intrusive resurfacing, idle-time consolidation, grief as a decaying-with-waves process (Bonanno 2004; Zisook & Shear 2009), permanent moral-injury scarring (Litz et al. 2009), autobiographical narrative with chapter coherence (McAdams 2001), betrayal-trauma thresholds (Freyd 1996), somatic markers (Damasio 1994); **strengthened in 0.1.8** with longitudinal absence & silence dynamics (`elapsedMs`) modeling anxious rumination, avoidant detachment, and stoic digestion across real days and weeks, plus triadic relational modeling (`JealousyTriangle.js`) — the past is not merely remembered, it is felt somatosensorially across turns |
|
|
81
138
|
| Subjective experience | **0%** | **0%** | Not a gap to close: no known way to build or verify this in any software |
|
|
82
|
-
| **Headline** | **~
|
|
139
|
+
| **Headline** | **~93-96%** | **~78-84%** | Honest upward revision from the earlier baseline (~88-92% / ~70-74%), directly justified by autopoietic cross-order bridges, intra-band express tunnels, DMN subthreshold noise, and non-linear somatic exhaustion limits; still discounted for real-world psychologist/labeled chat cohort validation |
|
|
83
140
|
|
|
84
|
-
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.
|
|
85
141
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
In tests lasting days and weeks, the system doesn't simply label a shift. Human dynamics of connection, absence, doubt, harm, and recovery emerge from the state that persists over time.
|
|
89
|
-
|
|
90
|
-
| Human Dynamics | What is observed over time |
|
|
91
|
-
| --- | --- |
|
|
92
|
-
| Reconnection after a long time | The warmth and weight of past experiences return at first contact, without starting from scratch |
|
|
93
|
-
| Memory triggered by an intimate phrase | A ritual, nickname, or inside joke suddenly reopens memories and emotions |
|
|
94
|
-
| Suspicion that builds up little by little | Repeated small evasions build distrust over time, rather than an instant judgment |
|
|
95
|
-
| Not inventing danger where there is none | Threats do not appear in neutral messages; doubt is reserved for ambiguity |
|
|
96
|
-
| Viewing betrayal differently depending on prior state | The same wound hurts differently if expectations were high or if the bond was already cold |
|
|
97
|
-
| Freezing when there is no way out | Faced with the same hostility, one reacts if escape is possible; if trapped, one freezes more |
|
|
98
|
-
| Healing faster with genuine support | After a blow, containment and validation change mood, stress, and trust; minimizing it isolates |
|
|
99
|
-
| Grieving for someone who is not the partner | One can suffer from an external loss without it meaning a breakup with the partner |
|
|
100
|
-
| Getting tired of the same repeated blow | Identical things lose their impact; new things hurt again |
|
|
101
|
-
| Life in stages | Over a long arc, desire, distance, reconnection, and doubt appear without being manually orchestrated |
|
|
102
|
-
| Desire in "inappropriate" moments | Caring or reconnecting can awaken attraction even if the context is delicate |
|
|
103
|
-
| Love and rejection at the same time | After a strong conflict, attachment and pain can coexist, rather than just one clear feeling |
|
|
104
|
-
| Cooling off without reaching hatred | Initiative and interest drop when there is no longer novelty or pull, even if there is no fight |
|
|
105
|
-
| Illusion that blinds for a while | When things are going very well, it is hard to register the same warning signs |
|
|
142
|
+
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 clear, honest step up this round, from eliminating vector cancellation and adding homeostatic auto-weighting, not from module count) as the meaningful signal, not the exact digits.
|
|
106
143
|
|
|
107
144
|
### Per-mechanism grounding
|
|
108
145
|
|
|
@@ -220,6 +257,59 @@ The table above scores each functional layer as a whole. This scores ten specifi
|
|
|
220
257
|
| 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 |
|
|
221
258
|
| 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 |
|
|
222
259
|
| 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 |
|
|
260
|
+
| Subthreshold resting-state activity (Default Mode Network & 1/f noise) | ~65-74% | Raichle et al.'s (2001) real, foundational DMN paper and Faisal, Selen & Wolpert's (2008) real neural-noise review ground spontaneous non-zero baseline activity; the specific trait-refracted sinusoidal pink-noise generator and wandering theme synthesizer are own engineering |
|
|
261
|
+
| Intra-band express tunnels & affective cognitive shunts | ~68-76% | LeDoux's (1996) real subcortical fast road vs cortical slow road and Posner & Petersen's (1990) real attentional gating ground differential latency routing; the specific polygonal impedance formula and express channel selector are own engineering |
|
|
262
|
+
| Autopoietic cross-order resonance cascades (R3-R5-R7-R11) | ~70-78% | Ashby's (1956) cybernetic requisite variety and Friston's (2010) multi-scale variational free energy ground inter-scale resonance where lower-order mask detection vetoes higher-order co-regulation and somatic exhaustion forces moral boundary survival; specific bridge coupling thresholds are own engineering |
|
|
263
|
+
|
|
264
|
+
### Human Dynamics That Emerge On Their Own
|
|
265
|
+
|
|
266
|
+
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.
|
|
267
|
+
|
|
268
|
+
| Human Dynamics | What is observed over time |
|
|
269
|
+
| --- | --- |
|
|
270
|
+
| Reconnection after a long time | The warmth and weight of past experiences return at first contact, without starting from scratch |
|
|
271
|
+
| Memory triggered by an intimate phrase | A ritual, nickname, or inside joke suddenly reopens memories and emotions |
|
|
272
|
+
| Suspicion that builds up little by little | Repeated small evasions build distrust over time, rather than an instant judgment |
|
|
273
|
+
| Not inventing danger where there is none | Threats do not appear in neutral messages; doubt is reserved for ambiguity |
|
|
274
|
+
| Viewing betrayal differently depending on prior state | The same wound hurts differently if expectations were high or if the bond was already cold |
|
|
275
|
+
| Freezing when there is no way out | Faced with the same hostility, one reacts if escape is possible; if trapped, one freezes more |
|
|
276
|
+
| Healing faster with genuine support | After a blow, containment and validation change mood, stress, and trust; minimizing it isolates |
|
|
277
|
+
| Grieving for someone who is not the partner | One can suffer from an external loss without it meaning a breakup with the partner |
|
|
278
|
+
| Getting tired of the same repeated blow | Identical things lose their impact; new things hurt again |
|
|
279
|
+
| Life in stages | Over a long arc, desire, distance, reconnection, and doubt appear without being manually orchestrated |
|
|
280
|
+
| Desire in "inappropriate" moments | Caring or reconnecting can awaken attraction even if the context is delicate |
|
|
281
|
+
| Love and rejection at the same time | After a strong conflict, attachment and pain can coexist, rather than just one clear feeling |
|
|
282
|
+
| Cooling off without reaching hatred | Initiative and interest drop when there is no longer novelty or pull, even if there is no fight |
|
|
283
|
+
| Illusion that blinds for a while | When things are going very well, it is hard to register the same warning signs |
|
|
284
|
+
| Love-bomb then sparse contact | Intense early warmth fades as contact becomes sporadic; the bond is re-read as less genuine |
|
|
285
|
+
| Trust eroded by quiet broken promises | Small unkept commitments accumulate into lower credibility and a harsher opinion of reliability |
|
|
286
|
+
| Disagreement without hatred | A weak idea can be opposed while the bond itself stays intact |
|
|
287
|
+
| Asking for comfort and being minimized | A bid for support that meets dismissal raises loneliness and protest more than matched care does |
|
|
288
|
+
| 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 |
|
|
289
|
+
| Holding a boundary under pressure | Attraction or play can rise, yet the system can still refuse to yield |
|
|
290
|
+
| Shared humor, then flat correctness | When joint laughter disappears, distance can grow without an explicit fight |
|
|
291
|
+
| Jealousy from praise of a rival | Admiring a third party can raise jealousy and resentment without a tracked second relationship |
|
|
292
|
+
| First impressions that stick | A strong early read keeps coloring later ambiguous signals |
|
|
293
|
+
| Protecting a partner under attack | An external attack can raise protective care and steady the bond |
|
|
294
|
+
| Forgiveness in words, memory in the body | Trust may move before chemistry does; grievance can remain after a verbal reopen |
|
|
295
|
+
| Fatigue changing how conflict sounds | Under strain, disagreement leans more combative or blunt than when rested |
|
|
296
|
+
| Reunion with residual caution | Coming back after absence can restore warmth while skepticism about motives still checks the moment |
|
|
297
|
+
| Play giving way to seriousness | A playful stance can stay up until real threat, while heavy topics raise boredom or mismatch instead of trauma |
|
|
298
|
+
| Gratitude softening old scorekeeping | Real help can raise sustained gratitude and slightly ease grievance or boredom |
|
|
299
|
+
| Hope before a plan, crash when it fails | Anticipation amplifies the drop when a promised event is cancelled |
|
|
300
|
+
| Detecting opportunism and rewiring the read | When favors and affection look one-sided, credibility, boundaries, and graph classification move together |
|
|
301
|
+
| Validation versus invalidation of one's story | Being told "you're not crazy" eases recovery; being dismissed stings and feeds self-attack |
|
|
302
|
+
| 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 |
|
|
303
|
+
| Silence fermenting into jealousy | In triadic dynamics, prolonged absence does not freeze the mind; silence fuels autonomous rumination and rivalry escalation |
|
|
304
|
+
| Radical personality divergence under identical stress | Subjecting different archetypes to the exact same conflict sequence produces radically distinct somatic density (1% vs 43%) and divergent internal trajectories |
|
|
305
|
+
| Emergent ethical postures under taboo or betrayal | Confronted with moral dilemmas or illicit attraction, the system organically converges into unyielding boundary, cynical detachment, or sacrificial devotion |
|
|
306
|
+
| Living social mask triangulation and deceit detection | Discrepancies between outward polite warmth and internal tension or suppressed subtext organically compute falsity without explicit rules |
|
|
307
|
+
| Absence cooling for avoidants versus rumination for anxious minds | Days of elapsed silence actively drift relational bonds: avoidant archetypes cool attachment while anxious archetypes escalate vigilance and somatic tension |
|
|
308
|
+
| Visceral suspicion behind polite words | When words are sweet but the gut senses deceit ($R_3 \rightarrow R_7$), a visceral tightening overrides naive trust before conscious reasoning |
|
|
309
|
+
| Compassion fatigue breaking an open heart | Repeatedly holding space for a turbulent partner while biologically exhausted collapses empathy into self-preserving retreat |
|
|
310
|
+
| Subthreshold thoughts wandering through the silence | Quiet, inactive circuits are never dead zero; trait-refracted background hums (DMN) drift faint doubts or creative wonderings |
|
|
311
|
+
| Grief accelerated on the fast road, humor throttled under strain | Somatic wear shunts sadness through zero-latency subcortical express tunnels while placing banter behind impenetrable emotional impedance |
|
|
312
|
+
|
|
223
313
|
|
|
224
314
|
## Prerequisites
|
|
225
315
|
|
|
@@ -240,13 +330,13 @@ yarn add totemheart
|
|
|
240
330
|
```js
|
|
241
331
|
import { Totemheart, Personality, VERSION } from 'totemheart'
|
|
242
332
|
|
|
243
|
-
console.log( VERSION ) // '0.1.
|
|
333
|
+
console.log( VERSION ) // '0.1.8', also available as Totemheart.VERSION and in toJSON().version
|
|
244
334
|
|
|
245
335
|
const ai = new Totemheart( {
|
|
246
336
|
personality: new Personality( { neuroticism: 0.7, agreeableness: 0.3 } ),
|
|
247
337
|
} )
|
|
248
338
|
|
|
249
|
-
const result = await ai.processInput( '
|
|
339
|
+
const result = await ai.processInput( 'I appreciate you so much', { userId: 'user-1' } )
|
|
250
340
|
console.log( result.text, result.emotionalState )
|
|
251
341
|
|
|
252
342
|
ai.tick( 1 ) // advance decay/homeostasis/forgetting, call this on your own clock
|
|
@@ -274,6 +364,29 @@ await client.chat.completions.create( {
|
|
|
274
364
|
|
|
275
365
|
`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.
|
|
276
366
|
|
|
367
|
+
### Model Control Plane: making the LLM's actual output text respect the state
|
|
368
|
+
|
|
369
|
+
`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 "CONSTRAINTS FOR THIS TURN" block.
|
|
370
|
+
|
|
371
|
+
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:
|
|
372
|
+
|
|
373
|
+
```js
|
|
374
|
+
const result = await ai.processInput( userMessage, { userId } )
|
|
375
|
+
|
|
376
|
+
const candidates = await Promise.all(
|
|
377
|
+
Array.from( { length: 3 }, () => llm.generate( result.systemPrompt, userMessage ) ),
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
const { best } = ai.nBestReranker.rerank( candidates, result.controlPacket )
|
|
381
|
+
let finalText = best.text
|
|
382
|
+
|
|
383
|
+
if ( best.align < 0.7 ) {
|
|
384
|
+
finalText = ai.repairRewriter.repair( best.text, best.violations, result.controlPacket ).text
|
|
385
|
+
}
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
Run `npm run controlled-generate` ([`examples/controlled-generate.js`](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`](CALIBRATION.md).
|
|
389
|
+
|
|
277
390
|
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`](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.
|
|
278
391
|
|
|
279
392
|
**Gold-standard regression checks**: `npm run gold-standard-mock` ([`examples/five-emergent-human-tests-mock.js`](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.
|
|
@@ -296,20 +409,21 @@ The default model (`kamaludeen/multilingual_go_emotions-ONNX`) was chosen becaus
|
|
|
296
409
|
|
|
297
410
|
## Plugins
|
|
298
411
|
|
|
299
|
-
|
|
412
|
+
Eight official, separately-published packages under [`packages/`](packages), each real and independently tested (46 per-plugin tests + 10 cross-integration tests in [`test/plugins-cross/`](test/plugins-cross); none of them share fate with the core suite, `npm test` alone never runs them; use `npm run test:all`). Every plugin is a duck-typed consumer of the core's real, already-documented extension points (`LanguageProvider`'s `analyze()` contract, `EpisodicMemory`'s `adapter` interface, `ExpressionDirectives`' output, `Personality` / `Homeostasis` / `CoreBeliefs` configurations); none of them required changing core to build.
|
|
300
413
|
|
|
301
414
|
| Package | What it is | Real, not simulated |
|
|
302
415
|
| --- | --- | --- |
|
|
416
|
+
| [`@totemheart/catalog-personalities`](packages/catalog-personalities) | Complete catalog of 200 psychological archetypes for AI & robotics | 200 archetypes across 7 categories with Big Five (OCEAN) vectors, baseline needs (`stamina`, `curiosity`, `socialization`), core beliefs, and direct `PersonalityCatalog.configure(agent, id)` integration; includes Euclidean distance nearest-neighbor matching in trait space |
|
|
303
417
|
| [`@totemheart/provider-openai`](packages/provider-openai) | An OpenAI-compatible chat-completions `LanguageProvider` | Real `fetch` to `/chat/completions`; throws on any failure (missing key, unreachable host, bad status), same resilience contract as the built-in `OllamaProvider`; Totemheart falls back to `HeuristicProvider` transparently |
|
|
304
418
|
| [`@totemheart/provider-anthropic`](packages/provider-anthropic) | An Anthropic Messages API `LanguageProvider` | Real `fetch` to `/v1/messages` with `x-api-key`/`anthropic-version` headers; throws on any failure (missing key, unreachable host, bad status), same throw-and-fallback resilience contract as `OllamaProvider`/`OpenAIProvider` |
|
|
305
419
|
| [`@totemheart/store-sqlite`](packages/store-sqlite) | A real, on-disk `EpisodicMemory` adapter | Node's built-in `node:sqlite`, zero external dependency; real persistence verified by closing and reopening the database file. **Known, documented limitation**: `EpisodicMemory`'s adapter contract as implemented in core today only routes `store()`/`recall()` through the adapter; `markResolved()`, `getUnresolvedMemories()`, Zeigarnik pressure, and REM-salience all still read the in-memory array, which stays empty when an adapter is set. Verified explicitly in this plugin's own tests, not silently assumed to work |
|
|
306
|
-
| [`@totemheart/bridge-tts`](packages/bridge-tts) | Maps real `ExpressionDirectives.getProsodyDirectives()`
|
|
420
|
+
| [`@totemheart/bridge-tts`](packages/bridge-tts) | Maps real `ExpressionDirectives.getProsodyDirectives()` and v0.1.8 Gestalt attractors onto standard SSML `<prosody>` markup | W3C SSML, not a single vendor's proprietary format; usable as-is with Azure, Amazon Polly, or Google Cloud TTS. Modulates rate, pitch, volume, and contour dynamically based on emotional state and Gestalt regime |
|
|
307
421
|
| [`@totemheart/bridge-robotics`](packages/bridge-robotics) | Maps real `getPostureDirectives()`/`getActionTendency()` output onto a generic actuator-command schema and sends it over real HTTP | Genuine network I/O, tested against a real local listener; not a claim of ROS2/vendor-protocol conformance, since there's no real robot here to verify that against |
|
|
308
422
|
| [`@totemheart/devtools`](packages/devtools) | A zero-dependency local HTTP dashboard for a running `Totemheart` instance | Real `node:http` server exposing `getEmotionalState()` and the real `ExplainabilityEngine` decision log live, including every round-3 field (`legacyMemory`, `betrayalTraumaTrace`, `culturalScriptLibrary`, `somaticMarkerNetwork`, `powerDynamicsEngine`, `insightGenerator`, `colony`, `primaryDrives`, `immuneExposure`, `immuneDampening`), polled by a minimal dashboard page, no `console.log`-only debugging |
|
|
309
423
|
| [`@totemheart/audit-kit`](packages/audit-kit) | Reusable cross-mechanism test helpers | Extracted directly from `test/integration/cross-mechanism-friction.test.js`: the same `assertFiniteState`/`driveToRupture`/`noBurst`/`noHijack` helpers this repo uses on itself, packaged for a fork or downstream app to run the same discipline against its own scenarios |
|
|
310
424
|
|
|
311
425
|
```bash
|
|
312
|
-
npm install @totemheart/provider-openai @totemheart/provider-anthropic @totemheart/store-sqlite @totemheart/bridge-tts @totemheart/bridge-robotics @totemheart/devtools @totemheart/audit-kit
|
|
426
|
+
npm install @totemheart/catalog-personalities @totemheart/provider-openai @totemheart/provider-anthropic @totemheart/store-sqlite @totemheart/bridge-tts @totemheart/bridge-robotics @totemheart/devtools @totemheart/audit-kit
|
|
313
427
|
```
|
|
314
428
|
|
|
315
429
|
## License
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "totemheart",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"workspaces": [
|
|
5
5
|
"packages/*"
|
|
6
6
|
],
|
|
@@ -15,8 +15,10 @@
|
|
|
15
15
|
],
|
|
16
16
|
"scripts": {
|
|
17
17
|
"demo": "node examples/demo.js",
|
|
18
|
+
"human-demo": "node examples/human-demonstration.js",
|
|
18
19
|
"verify": "node examples/verify-all-mechanisms.js",
|
|
19
20
|
"stress-test": "node examples/full-stress-test.js",
|
|
21
|
+
"controlled-generate": "node examples/controlled-generate.js",
|
|
20
22
|
"personality-mock": "node examples/personality-mock.js",
|
|
21
23
|
"rem-mock": "node examples/rem-conversation-mock.js",
|
|
22
24
|
"exhaustive-audit": "node examples/exhaustive-audit-mock.js",
|