totemheart 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -0
  3. package/package.json +62 -0
  4. package/src/Totemheart.js +1363 -0
  5. package/src/behavior/AttentionFocus.js +69 -0
  6. package/src/behavior/ExpressionDebt.js +48 -0
  7. package/src/behavior/ExpressionDirectives.js +95 -0
  8. package/src/behavior/ExpressiveSuppression.js +45 -0
  9. package/src/behavior/IdleProcessing.js +64 -0
  10. package/src/behavior/LinguisticModulation.js +62 -0
  11. package/src/behavior/LogitBiasBuilder.js +31 -0
  12. package/src/behavior/RuminationChain.js +93 -0
  13. package/src/behavior/StyleMimicry.js +72 -0
  14. package/src/cognition/AmygdalaHijack.js +40 -0
  15. package/src/cognition/AppraisalAgreement.js +39 -0
  16. package/src/cognition/BayesianExpectation.js +59 -0
  17. package/src/cognition/CognitiveDissonance.js +71 -0
  18. package/src/cognition/ControllabilityEstimate.js +56 -0
  19. package/src/cognition/DecisionFatigue.js +44 -0
  20. package/src/cognition/DefenseMechanisms.js +32 -0
  21. package/src/cognition/EmotionalOntology.js +134 -0
  22. package/src/cognition/FuzzyNormativeCheck.js +60 -0
  23. package/src/cognition/Intuition.js +71 -0
  24. package/src/cognition/LifeEventCatalog.js +98 -0
  25. package/src/cognition/LoadScheduler.js +41 -0
  26. package/src/cognition/LogicEngine.js +69 -0
  27. package/src/cognition/NoveltyDetector.js +59 -0
  28. package/src/cognition/Reappraisal.js +34 -0
  29. package/src/cognition/RefractoryPeriod.js +38 -0
  30. package/src/cognition/RemConsolidation.js +79 -0
  31. package/src/cognition/SarcasmDetector.js +38 -0
  32. package/src/cognition/SemanticSimilarity.js +75 -0
  33. package/src/cognition/Sensitization.js +45 -0
  34. package/src/cognition/SituationalContext.js +48 -0
  35. package/src/cognition/TopicSatiation.js +54 -0
  36. package/src/cognition/VisualProsody.js +48 -0
  37. package/src/core/AffectEMA.js +26 -0
  38. package/src/core/CoreBeliefs.js +58 -0
  39. package/src/core/DecayEngine.js +56 -0
  40. package/src/core/EmotionSpace.js +146 -0
  41. package/src/core/HebbianPlasticity.js +59 -0
  42. package/src/core/HedonicAdaptation.js +62 -0
  43. package/src/core/Homeostasis.js +119 -0
  44. package/src/core/MicroEmotions.js +25 -0
  45. package/src/core/MoodTracker.js +53 -0
  46. package/src/core/Personality.js +84 -0
  47. package/src/core/PipelineResilience.js +24 -0
  48. package/src/core/TriggerSentinel.js +38 -0
  49. package/src/core/WornPathCache.js +57 -0
  50. package/src/economics/AnchoringBias.js +38 -0
  51. package/src/economics/ClassicalConditioning.js +59 -0
  52. package/src/economics/LossAversion.js +40 -0
  53. package/src/embodiment/HardwareInteroception.js +26 -0
  54. package/src/embodiment/InteroceptiveSignals.js +132 -0
  55. package/src/embodiment/SensoryOverload.js +45 -0
  56. package/src/index.js +14 -0
  57. package/src/integration/ContextAdapter.js +247 -0
  58. package/src/neurochemistry/ArousalKalmanFilter.js +39 -0
  59. package/src/neurochemistry/CircadianRhythm.js +29 -0
  60. package/src/neurochemistry/CortisolEngine.js +54 -0
  61. package/src/neurochemistry/DopaminergicEngine.js +42 -0
  62. package/src/providers/FunctionProvider.js +26 -0
  63. package/src/providers/HeuristicProvider.js +156 -0
  64. package/src/providers/LanguageProvider.js +13 -0
  65. package/src/providers/OllamaProvider.js +63 -0
  66. package/src/providers/TransformersProvider.js +154 -0
  67. package/src/social/Attachment.js +81 -0
  68. package/src/social/BystanderEffect.js +17 -0
  69. package/src/social/ChronicContagion.js +48 -0
  70. package/src/social/CounterfactualComparison.js +34 -0
  71. package/src/social/EgoConfidence.js +34 -0
  72. package/src/social/EgoProjection.js +20 -0
  73. package/src/social/EmotionalContagion.js +52 -0
  74. package/src/social/EpisodicMemory.js +266 -0
  75. package/src/social/FairnessMonitor.js +34 -0
  76. package/src/social/ForgettingCurve.js +28 -0
  77. package/src/social/GratitudeEngine.js +32 -0
  78. package/src/social/GuiltEngine.js +43 -0
  79. package/src/social/MonteCarloToM.js +49 -0
  80. package/src/social/ReputationEngine.js +45 -0
  81. package/src/social/SelfModel.js +50 -0
  82. package/src/social/StatusEnvy.js +34 -0
  83. package/src/social/TheoryOfMind.js +53 -0
  84. package/src/social/TribalCategorization.js +24 -0
  85. package/src/social/UncannyValleyDetector.js +59 -0
  86. package/src/text/EmotionalCorpus.js +70 -0
  87. package/src/text/EmotionalTextGenerator.js +56 -0
  88. package/src/text/ExplainabilityEngine.js +30 -0
  89. package/src/text/TemplateComposer.js +114 -0
  90. package/src/version.js +1 -0
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Real Bayes' rule: P(event|evidence) = P(evidence|event)·P(event) / P(evidence).
3
+ * Tracks a belief "will interacting with this user go well?" as a Beta-like
4
+ * running estimate updated on each observed outcome, and reports the
5
+ * posterior probability of a positive outcome — used as the anxiety/hope
6
+ * signal (low posterior + this input reads ambiguous = anxious anticipation;
7
+ * high posterior = hope). Real formula; the discretization into "positive
8
+ * outcome" as a binary event (rather than modeling the full continuous
9
+ * likelihood) is an engineering simplification for a conversational context.
10
+ */
11
+ function clamp01( v ) {
12
+
13
+ return Math.max( 0, Math.min( 1, v ) )
14
+
15
+ }
16
+
17
+ export class BayesianExpectation {
18
+
19
+ constructor() {
20
+
21
+ this.beliefs = new Map() // userId -> { positiveOutcomes, totalOutcomes }
22
+
23
+ }
24
+
25
+ #entry( userId ) {
26
+
27
+ if ( !this.beliefs.has( userId ) ) this.beliefs.set( userId, { positiveOutcomes: 1, totalOutcomes: 2 } ) // uniform Beta(1,1) prior
28
+ return this.beliefs.get( userId )
29
+
30
+ }
31
+
32
+ /** P(positive outcome | evidence so far) — the prior for this turn, BEFORE observing it. */
33
+ getExpectation( userId ) {
34
+
35
+ const belief = this.#entry( userId )
36
+ return belief.positiveOutcomes / belief.totalOutcomes
37
+
38
+ }
39
+
40
+ /** Bayesian update: fold this turn's actual outcome into the posterior for next time. */
41
+ update( userId, wasPositive ) {
42
+
43
+ const belief = this.#entry( userId )
44
+ belief.totalOutcomes += 1
45
+ if ( wasPositive ) belief.positiveOutcomes += 1
46
+
47
+ }
48
+
49
+ /** Anxiety = how far below 0.5 the expectation sits, weighted by how confident (much data) that estimate is. */
50
+ getAnxiety( userId ) {
51
+
52
+ const belief = this.#entry( userId )
53
+ const p = this.getExpectation( userId )
54
+ const confidence = clamp01( ( belief.totalOutcomes - 2 ) / 10 ) // ramps up over ~10 observations
55
+ return clamp01( ( 0.5 - p ) * 2 * confidence )
56
+
57
+ }
58
+
59
+ }
@@ -0,0 +1,71 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Tracks "cognitive stress" — a stat of its own (not an emotion) that
9
+ * spikes when input conflicts with a CoreBelief and decays independently.
10
+ * DefenseMechanisms watches this stat to decide when to react.
11
+ *
12
+ * Named after Festinger, L. (1957), "A Theory of Cognitive Dissonance" — the
13
+ * name and the general idea (conflicting cognitions produce tension the
14
+ * system tries to resolve) come from there. The stress accumulation formula,
15
+ * threshold, and the behavioral-inconsistency check below are our own
16
+ * engineering, not something Festinger specified computationally.
17
+ * See CALIBRATION.md.
18
+ */
19
+ export class CognitiveDissonance {
20
+
21
+ constructor() {
22
+
23
+ this.stress = 0
24
+
25
+ }
26
+
27
+ /** conflictScore comes from LanguageProvider.analyze('beliefConflict', ...) */
28
+ registerConflict( conflictScore, personality ) {
29
+
30
+ const threshold = personality.getDissonanceThreshold()
31
+ if ( conflictScore <= threshold ) return { triggered: false, conflictScore }
32
+
33
+ this.stress = clamp01( this.stress + conflictScore * 0.5 )
34
+ return { triggered: true, conflictScore }
35
+
36
+ }
37
+
38
+ /**
39
+ * Dissonance isn't only "does this text contradict a static belief" —
40
+ * it's also "does this text contradict the *pattern* this specific user
41
+ * has established". A user who has been consistently cold suddenly
42
+ * saying "te quiero" is inconsistent with the learned relationship,
43
+ * even though nothing in it contradicts a CoreBelief.
44
+ */
45
+ registerBehavioralInconsistency( appraisal, relation, personality ) {
46
+
47
+ const suddenWarmthFromColdUser = relation.affinity < 0.3 && ( appraisal.desirability ?? 0 ) > 0.5 && appraisal.agency === 'user'
48
+ if ( !suddenWarmthFromColdUser ) return { triggered: false, score: 0 }
49
+
50
+ const score = ( 0.5 - relation.affinity ) + ( appraisal.desirability - 0.5 )
51
+ const threshold = personality.getDissonanceThreshold()
52
+ if ( score <= threshold ) return { triggered: false, score }
53
+
54
+ this.stress = clamp01( this.stress + score * 0.35 )
55
+ return { triggered: true, score }
56
+
57
+ }
58
+
59
+ decay( dt, lambda = 0.15 ) {
60
+
61
+ this.stress = Math.max( 0, this.stress - lambda * dt )
62
+
63
+ }
64
+
65
+ getStress() {
66
+
67
+ return this.stress
68
+
69
+ }
70
+
71
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Lightweight MDP-flavored controllability estimate: tracks, per situation
3
+ * type (a coarse bucket, not a full state space), how often "doing
4
+ * something" (any response at all) was followed by an improved emotional
5
+ * vector on the next tick. A literal Markov Decision Process would need a
6
+ * defined action set and full transition matrix Totemheart doesn't have —
7
+ * this keeps the real idea (estimate P(transition to a better state | own
8
+ * action)) at the scale actually supported: a running success rate per
9
+ * bucket, not a solved MDP.
10
+ */
11
+ function clamp01( v ) {
12
+
13
+ return Math.max( 0, Math.min( 1, v ) )
14
+
15
+ }
16
+
17
+ export class ControllabilityEstimate {
18
+
19
+ constructor() {
20
+
21
+ this.buckets = new Map() // bucketKey -> { improved, total }
22
+
23
+ }
24
+
25
+ #entry( bucketKey ) {
26
+
27
+ if ( !this.buckets.has( bucketKey ) ) this.buckets.set( bucketKey, { improved: 1, total: 2 } ) // weak uniform prior
28
+ return this.buckets.get( bucketKey )
29
+
30
+ }
31
+
32
+ /** P(the situation improves after we respond) for this bucket — high = "I can handle this". */
33
+ getControllability( bucketKey ) {
34
+
35
+ const entry = this.#entry( bucketKey )
36
+ return entry.improved / entry.total
37
+
38
+ }
39
+
40
+ /** Call after a tick/response: did the vector's magnitude actually shrink toward baseline? */
41
+ observeOutcome( bucketKey, valenceBefore, valenceAfter ) {
42
+
43
+ const entry = this.#entry( bucketKey )
44
+ entry.total += 1
45
+ if ( Math.abs( valenceAfter ) < Math.abs( valenceBefore ) ) entry.improved += 1
46
+
47
+ }
48
+
49
+ /** High controllability dampens panic — a multiplier for fear/arousal spikes. */
50
+ getPanicDampener( bucketKey ) {
51
+
52
+ return clamp01( 1 - this.getControllability( bucketKey ) * 0.6 )
53
+
54
+ }
55
+
56
+ }
@@ -0,0 +1,44 @@
1
+ function clamp01( v ) {
2
+
3
+ return Math.max( 0, Math.min( 1, v ) )
4
+
5
+ }
6
+
7
+ /**
8
+ * Counts processed decisions/tokens. Above the threshold the orchestrator
9
+ * enters "shallowMode": deep provider calls (appraisal, ToM, dissonance)
10
+ * are skipped in favor of cheap heuristics and generic responses.
11
+ */
12
+ export class DecisionFatigue {
13
+
14
+ constructor() {
15
+
16
+ this.load = 0
17
+
18
+ }
19
+
20
+ recordDecision( complexity = 1 ) {
21
+
22
+ this.load = clamp01( this.load + 0.05 * complexity )
23
+
24
+ }
25
+
26
+ decay( dt, lambda = 0.02 ) {
27
+
28
+ this.load = Math.max( 0, this.load - lambda * dt )
29
+
30
+ }
31
+
32
+ getLevel() {
33
+
34
+ return this.load
35
+
36
+ }
37
+
38
+ isShallow( threshold = 0.7 ) {
39
+
40
+ return this.load > threshold
41
+
42
+ }
43
+
44
+ }
@@ -0,0 +1,32 @@
1
+ function weightedPick( weights ) {
2
+
3
+ const entries = Object.entries( weights )
4
+ const roll = Math.random() * entries.reduce( ( sum, [ , w ] ) => sum + w, 0 )
5
+ let acc = 0
6
+ for ( const [ name, w ] of entries ) {
7
+
8
+ acc += w
9
+ if ( roll <= acc ) return name
10
+
11
+ }
12
+ return entries[ 0 ][ 0 ]
13
+
14
+ }
15
+
16
+ /**
17
+ * Fires when cognitive stress crosses a critical threshold. Returns a
18
+ * behaviorDirective the text generator / linguistic modulation layer must
19
+ * act on: evasion (change subject), projection (blame the user), sarcasm.
20
+ */
21
+ export class DefenseMechanisms {
22
+
23
+ check( stress, personality, threshold = 0.6 ) {
24
+
25
+ if ( stress < threshold ) return { active: false }
26
+
27
+ const mechanism = weightedPick( personality.getDefenseWeights() )
28
+ return { active: true, mechanism, stress }
29
+
30
+ }
31
+
32
+ }
@@ -0,0 +1,134 @@
1
+ function tokenize( text ) {
2
+
3
+ return ( text || '' ).toLowerCase().match( /[\p{L}']+/gu ) || []
4
+
5
+ }
6
+
7
+ /**
8
+ * A small, hand-built concept graph (not learned, not sourced from a
9
+ * dataset) mapping higher-level psychological concepts to reaction
10
+ * profiles. Loosely inspired by common appraisal-theory/CBT categories, but
11
+ * this is NOT a reproduction of Ekman's basic emotions, Russell's circumplex,
12
+ * or any other published taxonomy — it's our own 6-concept starting point.
13
+ * See CALIBRATION.md. This runs independently of any LanguageProvider, so it
14
+ * raises the floor for the no-LLM heuristic path instead of only ever
15
+ * depending on an external model for anything beyond raw polarity.
16
+ */
17
+ const CONCEPTS = {
18
+ criticism : {
19
+ keywords : [ 'inútil', 'estúpido', 'estúpida', 'malo', 'mala', 'incompetente', 'torpe', 'useless', 'stupid', 'incompetent' ],
20
+ profile : { desirability: -0.6, moralWeight: 0.7, arousal: 0.3, tendency: 'defense' },
21
+ },
22
+ rejection : {
23
+ keywords : [ 'vete', 'no te quiero', 'rechazo', 'aléjate', 'go away', 'reject', 'leave me' ],
24
+ profile : { desirability: -0.8, moralWeight: 0.5, arousal: 0.2, tendency: 'sadness' },
25
+ },
26
+ threat : {
27
+ keywords : [ 'amenaza', 'te voy a', 'cuidado', 'peligro', 'threat', 'danger', 'warning' ],
28
+ profile : { desirability: -0.5, moralWeight: 0.3, arousal: 0.8, tendency: 'fear' },
29
+ },
30
+ betrayal : {
31
+ keywords : [ 'traicion', 'traición', 'mentiste', 'engañaste', 'betray', 'lied', 'deceived' ],
32
+ profile : { desirability: -0.9, moralWeight: 0.9, arousal: 0.6, tendency: 'anger' },
33
+ },
34
+ affection : {
35
+ keywords : [ 'quiero', 'encanta', 'adoro', 'cariño', 'love', 'adore', 'care about you' ],
36
+ profile : { desirability: 0.7, moralWeight: 0.1, arousal: 0.3, tendency: 'warmth' },
37
+ },
38
+ achievement : {
39
+ keywords : [ 'lograste', 'conseguiste', 'genial trabajo', 'bien hecho', 'well done', 'great job', 'achieved' ],
40
+ profile : { desirability: 0.6, moralWeight: 0.2, arousal: 0.4, tendency: 'pride' },
41
+ },
42
+ }
43
+
44
+ export class EmotionalOntology {
45
+
46
+ /** Which concepts, if any, the text matches. */
47
+ interpret( text ) {
48
+
49
+ const tokenSet = new Set( tokenize( text ) )
50
+ const lower = ( text || '' ).toLowerCase()
51
+ const matches = []
52
+
53
+ for ( const [ concept, def ] of Object.entries( CONCEPTS ) ) {
54
+
55
+ const hit = def.keywords.some( kw => kw.includes( ' ' ) ? lower.includes( kw ) : tokenSet.has( kw ) )
56
+ if ( hit ) matches.push( { concept, profile: def.profile } )
57
+
58
+ }
59
+
60
+ return matches
61
+
62
+ }
63
+
64
+ /**
65
+ * Blends ontology matches into an existing appraisal. When the provider
66
+ * (LLM or heuristic) already produced a signal, this nudges it rather
67
+ * than overriding it — the ontology is a cross-check, not a replacement.
68
+ *
69
+ * `relation` (optional, from Attachment.get(userId)) contextualizes the
70
+ * match: criticism/rejection/threat from someone already trusted reads
71
+ * as milder than the same words from someone untrusted; betrayal reads
72
+ * as *worse* coming from someone trusted ("et tu, Brute" — betrayal by
73
+ * a stranger barely registers, betrayal by someone trusted cuts deeper).
74
+ * This direction is a reasonable engineering interpretation, not a
75
+ * citation of any specific study — see CALIBRATION.md.
76
+ *
77
+ * `msSinceLastBetrayal` (optional, from EpisodicMemory.msSinceLastConcept)
78
+ * further amplifies criticism/rejection/threat within a week of a
79
+ * betrayal-tagged memory — a period of hypervigilance where the same
80
+ * words read as more threatening. The general phenomenon (recent
81
+ * negative experiences raising sensitivity to related cues) is a
82
+ * well-documented pattern in the trauma/PTSD literature; the specific
83
+ * "1 week, x1.3" parameters here are our own, not measured — see
84
+ * CALIBRATION.md.
85
+ */
86
+ adjustAppraisal( appraisal, matches, relation = null, msSinceLastBetrayal = null ) {
87
+
88
+ if ( !matches.length ) return appraisal
89
+
90
+ const trust = relation?.trust ?? 0.5
91
+ const ONE_WEEK_MS = 7 * 24 * 60 * 60 * 1000
92
+ const hypervigilant = msSinceLastBetrayal !== null && msSinceLastBetrayal < ONE_WEEK_MS
93
+
94
+ const weighted = matches.map( m => {
95
+
96
+ let factor = 1
97
+ if ( [ 'criticism', 'rejection', 'threat' ].includes( m.concept ) ) {
98
+
99
+ factor = 1.4 - trust * 0.8
100
+ if ( hypervigilant ) factor *= 1.3
101
+
102
+ }
103
+ else if ( m.concept === 'betrayal' ) factor = 0.7 + trust * 0.6
104
+
105
+ return {
106
+ ...m,
107
+ profile : {
108
+ ...m.profile,
109
+ desirability : m.profile.desirability * factor,
110
+ moralWeight : m.profile.moralWeight * factor,
111
+ arousal : m.profile.arousal * factor,
112
+ },
113
+ }
114
+
115
+ } )
116
+
117
+ const avg = weighted.reduce( ( acc, m ) => ( {
118
+ desirability : acc.desirability + m.profile.desirability,
119
+ moralWeight : acc.moralWeight + m.profile.moralWeight,
120
+ arousal : acc.arousal + m.profile.arousal,
121
+ } ), { desirability: 0, moralWeight: 0, arousal: 0 } )
122
+
123
+ const n = weighted.length
124
+ return {
125
+ ...appraisal,
126
+ desirability : ( appraisal.desirability + avg.desirability / n ) / 2,
127
+ moralWeight : Math.max( appraisal.moralWeight ?? 0, avg.moralWeight / n ),
128
+ ontologyArousalBoost : avg.arousal / n,
129
+ concepts : matches.map( m => m.concept ),
130
+ }
131
+
132
+ }
133
+
134
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Real Mamdani-style fuzzy inference (triangular membership functions +
3
+ * min/max rule aggregation), not just a threshold. Where CognitiveDissonance
4
+ * gives a single continuous conflict score, this asks a fuzzier question:
5
+ * "given how much this conflicts AND how much I trust the source, how
6
+ * acceptable is it?" — degrees of membership in [0,1], not a crisp cutoff.
7
+ */
8
+ function triangular( x, a, b, c ) {
9
+
10
+ if ( x <= a || x >= c ) return 0
11
+ if ( x === b ) return 1
12
+ return x < b ? ( x - a ) / ( b - a ) : ( c - x ) / ( c - b )
13
+
14
+ }
15
+
16
+ const CONFLICT_SETS = {
17
+ low : x => triangular( x, -0.1, 0, 0.4 ),
18
+ medium : x => triangular( x, 0.2, 0.5, 0.8 ),
19
+ high : x => triangular( x, 0.6, 1, 1.1 ),
20
+ }
21
+
22
+ const TRUST_SETS = {
23
+ low : x => triangular( x, -0.1, 0, 0.4 ),
24
+ medium : x => triangular( x, 0.2, 0.5, 0.8 ),
25
+ high : x => triangular( x, 0.6, 1, 1.1 ),
26
+ }
27
+
28
+ /**
29
+ * Rules (Mamdani, min for AND, max for aggregation):
30
+ * IF conflict=low THEN acceptable=high
31
+ * IF conflict=medium AND trust=high THEN acceptable=medium
32
+ * IF conflict=medium AND trust=low THEN acceptable=low
33
+ * IF conflict=high THEN acceptable=low
34
+ * Own rule base — a defensible small set for this domain, not a reproduction
35
+ * of a published rule set.
36
+ */
37
+ export class FuzzyNormativeCheck {
38
+
39
+ /** Returns a 0..1 "acceptability" degree via centroid defuzzification over 3 output singletons. */
40
+ evaluate( conflictScore, trust ) {
41
+
42
+ const conflict = { low: CONFLICT_SETS.low( conflictScore ), medium: CONFLICT_SETS.medium( conflictScore ), high: CONFLICT_SETS.high( conflictScore ) }
43
+ const trustDeg = { low: TRUST_SETS.low( trust ), medium: TRUST_SETS.medium( trust ), high: TRUST_SETS.high( trust ) }
44
+
45
+ const ruleStrength = {
46
+ high : conflict.low,
47
+ medium : Math.min( conflict.medium, trustDeg.high ),
48
+ low : Math.max( Math.min( conflict.medium, trustDeg.low ), conflict.high ),
49
+ }
50
+
51
+ // Centroid of singletons at 0 (low), 0.5 (medium), 1 (high), weighted by rule strength.
52
+ const weights = [ [ 0, ruleStrength.low ], [ 0.5, ruleStrength.medium ], [ 1, ruleStrength.high ] ]
53
+ const totalWeight = weights.reduce( ( sum, [ , w ] ) => sum + w, 0 )
54
+ if ( totalWeight === 0 ) return 0.5 // no rule fired meaningfully — neutral default
55
+
56
+ return weights.reduce( ( sum, [ v, w ] ) => sum + v * w, 0 ) / totalWeight
57
+
58
+ }
59
+
60
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Fast-path heuristic, real k-NN (Jaccard similarity over token sets — a
3
+ * real, zero-dependency distance metric; pass an `embedProvider` for a
4
+ * proper vector k-NN via SemanticSimilarity-style embeddings instead) over
5
+ * a rolling log of past inputs tagged with whether they preceded a
6
+ * conflict/dissonance event. When the current input's nearest neighbors
7
+ * disagree about whether that kind of input goes well or badly, that
8
+ * disagreement IS uncertainty — quantified with real Shannon entropy:
9
+ * H(X) = -Σ P(x) log2(P(x))
10
+ * over the binary {conflict, no-conflict} outcome distribution of the
11
+ * neighbors found. High entropy (neighbors split ~50/50) = high hunch
12
+ * penalty; neighbors that agree (all fine or all conflictual) produce low
13
+ * entropy — a confident prediction either way, not an uncertain one.
14
+ */
15
+ export function shannonEntropy( probabilities ) {
16
+
17
+ let h = 0
18
+ for ( const p of probabilities ) if ( p > 0 ) h -= p * Math.log2( p )
19
+ return h
20
+
21
+ }
22
+
23
+ function jaccard( a, b ) {
24
+
25
+ const intersection = [ ...a ].filter( x => b.has( x ) ).length
26
+ const union = new Set( [ ...a, ...b ] ).size
27
+ return union > 0 ? intersection / union : 0
28
+
29
+ }
30
+
31
+ export class Intuition {
32
+
33
+ constructor( { k = 3, maxHistory = 200 } = {} ) {
34
+
35
+ this.k = k
36
+ this.maxHistory = maxHistory
37
+ this.history = [] // { tokens: Set<string>, wasConflict: boolean }
38
+
39
+ }
40
+
41
+ /** Real k-NN + Shannon entropy over the outcome distribution of the nearest matches. */
42
+ sense( tokens ) {
43
+
44
+ const tokenSet = new Set( tokens )
45
+ if ( !this.history.length ) return { entropy: 0, hunchPenalty: 0, neighborsFound: 0 }
46
+
47
+ const scored = this.history
48
+ .map( entry => ( { ...entry, similarity: jaccard( tokenSet, entry.tokens ) } ) )
49
+ .filter( entry => entry.similarity > 0.1 )
50
+ .sort( ( a, b ) => b.similarity - a.similarity )
51
+ .slice( 0, this.k )
52
+
53
+ if ( !scored.length ) return { entropy: 0, hunchPenalty: 0, neighborsFound: 0 }
54
+
55
+ const conflictCount = scored.filter( n => n.wasConflict ).length
56
+ const p = conflictCount / scored.length
57
+ const entropy = shannonEntropy( [ p, 1 - p ] )
58
+ const hunchPenalty = entropy * ( conflictCount > 0 ? 1 : 0.3 )
59
+
60
+ return { entropy, hunchPenalty, neighborsFound: scored.length, conflictRatio: p }
61
+
62
+ }
63
+
64
+ observe( tokens, wasConflict ) {
65
+
66
+ this.history.push( { tokens: new Set( tokens ), wasConflict } )
67
+ if ( this.history.length > this.maxHistory ) this.history.shift()
68
+
69
+ }
70
+
71
+ }
@@ -0,0 +1,98 @@
1
+ export const LIFE_EVENTS = [
2
+
3
+ { id: 'death_spouse', label: 'Death of spouse', sourced: true, impact: 100, valence: -1.0, dominance: -0.9, area: [ 'Engram', 'Affect' ], keywords: [ 'murio mi esposo', 'murio mi esposa', 'murio mi conyuge', 'viudo', 'viuda', 'fallecio mi pareja' ] },
4
+ { id: 'divorce', label: 'Divorce', sourced: true, impact: 73, valence: -0.8, dominance: -0.5, area: [ 'Ego', 'Echo' ], keywords: [ 'divorcio', 'me divorcio', 'nos divorciamos', 'divorciandome' ] },
5
+ { id: 'marital_separation', label: 'Marital separation', sourced: true, impact: 65, valence: -0.7, dominance: -0.4, area: [ 'Ego', 'Echo' ], keywords: [ 'nos separamos', 'me separe de mi pareja', 'separacion matrimonial' ] },
6
+ { id: 'jail_term', label: 'Jail term', sourced: true, impact: 63, valence: -0.9, dominance: -0.9, area: [ 'Ego', 'Restraint' ], keywords: [ 'carcel', 'prision', 'condena', 'me encerraron' ] },
7
+ { id: 'death_close_family', label: 'Death of close family member', sourced: true, impact: 63, valence: -0.9, dominance: -0.7, area: [ 'Engram', 'Affect' ], keywords: [ 'murio mi padre', 'murio mi madre', 'murio mi hermano', 'fallecio mi familiar', 'perdi a mi' ] },
8
+ { id: 'personal_injury_illness', label: 'Personal injury or illness', sourced: true, impact: 53, valence: -0.7, dominance: -0.6, area: [ 'Drive', 'Affect' ], keywords: [ 'me diagnosticaron', 'enfermedad grave', 'estoy muy enfermo', 'lesion grave' ] },
9
+ { id: 'marriage', label: 'Marriage', sourced: true, impact: 50, valence: 0.8, dominance: 0.2, area: [ 'Appraisal', 'Affect' ], keywords: [ 'me caso', 'nos casamos', 'mi boda' ] },
10
+ { id: 'fired_at_work', label: 'Fired at work', sourced: true, impact: 47, valence: -0.7, dominance: -0.6, area: [ 'Ego', 'Drive' ], keywords: [ 'me despidieron', 'perdi mi trabajo', 'me echaron del trabajo' ] },
11
+ { id: 'marital_reconciliation', label: 'Marital reconciliation', sourced: true, impact: 45, valence: 0.5, dominance: 0.2, area: [ 'Ego', 'Affect' ], keywords: [ 'nos reconciliamos', 'volvimos con mi pareja' ] },
12
+ { id: 'retirement', label: 'Retirement', sourced: true, impact: 45, valence: 0.1, dominance: -0.2, area: [ 'Drive', 'Ego' ], keywords: [ 'me jubile', 'mi jubilacion' ] },
13
+ { id: 'family_member_health_change', label: 'Change in health of family member', sourced: true, impact: 44, valence: -0.5, dominance: -0.3, area: [ 'Empathy', 'Affect' ], keywords: [ 'mi familiar esta enfermo', 'la salud de mi madre', 'la salud de mi padre' ] },
14
+ { id: 'pregnancy', label: 'Pregnancy', sourced: true, impact: 40, valence: 0.6, dominance: -0.2, area: [ 'Empathy', 'Drive' ], keywords: [ 'estoy embarazada', 'vamos a tener un bebe', 'mi pareja esta embarazada' ] },
15
+ { id: 'sex_difficulties', label: 'Sex difficulties', sourced: true, impact: 39, valence: -0.4, dominance: -0.3, area: [ 'Ego', 'Affect' ], keywords: [ 'problemas sexuales', 'problemas en la intimidad' ] },
16
+ { id: 'new_family_member', label: 'Gain of new family member', sourced: true, impact: 39, valence: 0.7, dominance: -0.3, area: [ 'Empathy', 'Drive' ], keywords: [ 'nacio mi hijo', 'nacio mi hija', 'tuvimos un bebe', 'adoptamos' ] },
17
+ { id: 'business_readjustment', label: 'Business readjustment', sourced: true, impact: 39, valence: -0.3, dominance: -0.4, area: [ 'Logic', 'Drive' ], keywords: [ 'reestructuracion en el trabajo', 'cambios en la empresa' ] },
18
+ { id: 'financial_state_change', label: 'Change in financial state', sourced: true, impact: 38, valence: -0.3, dominance: -0.4, area: [ 'Logic', 'Affect' ], keywords: [ 'cambio mi situacion economica', 'problemas financieros' ] },
19
+ { id: 'death_close_friend', label: 'Death of close friend', sourced: true, impact: 37, valence: -0.7, dominance: -0.3, area: [ 'Engram', 'Affect' ], keywords: [ 'murio mi amigo', 'fallecio mi amiga' ] },
20
+ { id: 'change_line_of_work', label: 'Change to different line of work', sourced: true, impact: 36, valence: -0.1, dominance: -0.2, area: [ 'Logic', 'Drive' ], keywords: [ 'cambie de trabajo', 'nueva carrera profesional' ] },
21
+ { id: 'arguments_with_spouse_change', label: 'Change in number of arguments with spouse', sourced: true, impact: 35, valence: -0.4, dominance: -0.2, area: [ 'Restraint', 'Affect' ], keywords: [ 'discutimos mas', 'peleamos mucho con mi pareja' ] },
22
+ { id: 'major_purchase_mortgage', label: 'Mortgage or major purchase', sourced: true, impact: 31, valence: -0.2, dominance: -0.3, area: [ 'Logic', 'Ego' ], keywords: [ 'pedi una hipoteca', 'compre una casa' ] },
23
+ { id: 'foreclosure', label: 'Foreclosure of mortgage or loan', sourced: true, impact: 30, valence: -0.6, dominance: -0.7, area: [ 'Logic', 'Affect' ], keywords: [ 'me embargaron', 'no pude pagar la hipoteca' ] },
24
+ { id: 'responsibilities_change_work', label: 'Change in responsibilities at work', sourced: true, impact: 29, valence: -0.1, dominance: 0.1, area: [ 'Drive', 'Logic' ], keywords: [ 'nuevas responsabilidades en el trabajo' ] },
25
+ { id: 'child_leaving_home', label: 'Son or daughter leaving home', sourced: true, impact: 29, valence: -0.3, dominance: -0.2, area: [ 'Empathy', 'Echo' ], keywords: [ 'mi hijo se fue de casa', 'el nido vacio' ] },
26
+ { id: 'trouble_with_in_laws', label: 'Trouble with in-laws', sourced: true, impact: 29, valence: -0.4, dominance: -0.2, area: [ 'Restraint', 'Affect' ], keywords: [ 'problemas con mis suegros' ] },
27
+ { id: 'outstanding_achievement', label: 'Outstanding personal achievement', sourced: true, impact: 28, valence: 0.8, dominance: 0.6, area: [ 'Ego', 'Drive' ], keywords: [ 'logre algo importante', 'consegui un premio', 'gane una competencia' ] },
28
+ { id: 'spouse_work_change', label: 'Spouse begins or stops work', sourced: true, impact: 26, valence: -0.1, dominance: -0.1, area: [ 'Logic', 'Affect' ], keywords: [ 'mi pareja empezo a trabajar', 'mi pareja dejo su trabajo' ] },
29
+ { id: 'school_begin_end', label: 'Begin or end school', sourced: true, impact: 26, valence: 0.2, dominance: 0.1, area: [ 'Drive', 'Logic' ], keywords: [ 'empiezo la universidad', 'me gradue', 'termine mis estudios' ] },
30
+ { id: 'living_conditions_change', label: 'Change in living conditions', sourced: true, impact: 25, valence: -0.2, dominance: -0.2, area: [ 'Affect', 'Restraint' ], keywords: [ 'cambio en mi casa', 'estamos remodelando' ] },
31
+ { id: 'personal_habits_revision', label: 'Revision of personal habits', sourced: true, impact: 24, valence: -0.1, dominance: 0.1, area: [ 'Drive', 'Restraint' ], keywords: [ 'cambie mis habitos', 'dejando un vicio' ] },
32
+ { id: 'trouble_with_boss', label: 'Trouble with boss', sourced: true, impact: 23, valence: -0.5, dominance: -0.4, area: [ 'Restraint', 'Ego' ], keywords: [ 'problemas con mi jefe', 'mi jefe me grito', 'discusion con mi jefe' ] },
33
+ { id: 'work_hours_change', label: 'Change in work hours or conditions', sourced: true, impact: 20, valence: -0.1, dominance: -0.2, area: [ 'Logic', 'Restraint' ], keywords: [ 'cambio de horario de trabajo', 'turno nuevo' ] },
34
+ { id: 'residence_change', label: 'Change in residence', sourced: true, impact: 20, valence: -0.1, dominance: -0.1, area: [ 'Affect', 'Logic' ], keywords: [ 'me mude de casa', 'cambio de residencia' ] },
35
+ { id: 'school_change', label: 'Change in schools', sourced: true, impact: 20, valence: -0.1, dominance: -0.2, area: [ 'Empathy', 'Echo' ], keywords: [ 'cambio de escuela', 'nuevo colegio' ] },
36
+ { id: 'recreation_change', label: 'Change in recreation', sourced: true, impact: 19, valence: 0.1, dominance: 0.0, area: [ 'Affect' ], keywords: [ 'empece un nuevo hobby', 'deje de hacer deporte' ] },
37
+ { id: 'church_activities_change', label: 'Change in church activities', sourced: true, impact: 19, valence: 0.0, dominance: 0.0, area: [ 'Affect' ], keywords: [ 'cambio en mi fe', 'deje de ir a la iglesia' ] },
38
+ { id: 'social_activities_change', label: 'Change in social activities', sourced: true, impact: 18, valence: 0.0, dominance: 0.0, area: [ 'Empathy', 'Affect' ], keywords: [ 'cambio en mi vida social' ] },
39
+ { id: 'minor_mortgage_loan', label: 'Minor mortgage or loan', sourced: true, impact: 17, valence: -0.1, dominance: -0.2, area: [ 'Logic' ], keywords: [ 'pedi un prestamo pequeno' ] },
40
+ { id: 'sleeping_habits_change', label: 'Change in sleeping habits', sourced: true, impact: 16, valence: -0.1, dominance: -0.1, area: [ 'Affect', 'Restraint' ], keywords: [ 'duermo mal ultimamente', 'cambie mis horarios de sueno' ] },
41
+ { id: 'family_gettogethers_change', label: 'Change in number of family get-togethers', sourced: true, impact: 15, valence: 0.1, dominance: 0.0, area: [ 'Empathy' ], keywords: [ 'menos reuniones familiares', 'mas reuniones familiares' ] },
42
+ { id: 'eating_habits_change', label: 'Change in eating habits', sourced: true, impact: 15, valence: -0.1, dominance: 0.0, area: [ 'Affect', 'Restraint' ], keywords: [ 'cambie mi dieta', 'como diferente ahora' ] },
43
+ { id: 'vacation', label: 'Vacation', sourced: true, impact: 13, valence: 0.5, dominance: 0.3, area: [ 'Affect' ], keywords: [ 'me voy de vacaciones', 'estoy de vacaciones' ] },
44
+ { id: 'christmas', label: 'Christmas / holidays', sourced: true, impact: 12, valence: 0.3, dominance: 0.0, area: [ 'Affect', 'Empathy' ], keywords: [ 'es navidad', 'fiestas decembrinas' ] },
45
+ { id: 'minor_law_violation', label: 'Minor violation of the law', sourced: true, impact: 11, valence: -0.3, dominance: -0.3, area: [ 'Ego', 'Logic' ], keywords: [ 'me pusieron una multa', 'infraccion de transito' ] },
46
+
47
+ { id: 'severe_physical_violence_victim', label: 'Victim of severe physical violence', sourced: false, impact: 90, valence: -1.0, dominance: -1.0, area: [ 'Ego', 'Affect', 'Intuition' ], keywords: [ 'me golpearon', 'sufri violencia fisica', 'me atacaron fisicamente' ] },
48
+ { id: 'surviving_severe_accident', label: 'Surviving a severe accident', sourced: false, impact: 85, valence: -0.9, dominance: -1.0, area: [ 'Intuition', 'Restraint' ], keywords: [ 'tuve un accidente grave', 'casi muero en un accidente', 'sobrevivi a un accidente' ] },
49
+ { id: 'witnessing_fatal_accident', label: 'Witnessing a fatal accident', sourced: false, impact: 70, valence: -0.8, dominance: -0.7, area: [ 'Empathy', 'Engram' ], keywords: [ 'vi como alguien moria', 'presencie un accidente fatal' ] },
50
+ { id: 'public_humiliation', label: 'Public humiliation', sourced: false, impact: 55, valence: -0.8, dominance: -0.6, area: [ 'Ego', 'Echo' ], keywords: [ 'me humillaron delante de todos', 'me avergonzaron en publico' ] },
51
+ { id: 'credible_verbal_threat', label: 'Credible direct verbal threat', sourced: false, impact: 50, valence: -0.7, dominance: -0.5, area: [ 'Intuition', 'Focus' ], keywords: [ 'me amenazaron', 'te voy a hacer dano', 'te vas a arrepentir' ] },
52
+ { id: 'discovering_partner_lie', label: 'Discovering a significant lie from a partner', sourced: false, impact: 48, valence: -0.6, dominance: -0.3, area: [ 'Ethos', 'Appraisal' ], keywords: [ 'me mintio mi pareja', 'descubri que me mintio' ] },
53
+ { id: 'minor_physical_fight', label: 'Minor physical fight', sourced: false, impact: 40, valence: -0.6, dominance: -0.1, area: [ 'Intuition', 'Affect' ], keywords: [ 'tuve una pelea', 'nos peleamos fisicamente' ] },
54
+ { id: 'unexpected_love_declaration', label: 'Reciprocated declaration of love', sourced: false, impact: 38, valence: 0.9, dominance: 0.4, area: [ 'Ego', 'Affect' ], keywords: [ 'me dijo que me ama', 'nos declaramos amor' ] },
55
+ { id: 'unexpected_praise', label: 'Unexpected praise from a superior', sourced: false, impact: 35, valence: 0.7, dominance: 0.5, area: [ 'Ego', 'Drive' ], keywords: [ 'mi jefe me elogio', 'recibi un elogio inesperado' ] },
56
+ { id: 'traffic_jam_severe', label: 'Stuck in severe traffic', sourced: false, impact: 20, valence: -0.4, dominance: -0.8, area: [ 'Restraint', 'Affect' ], keywords: [ 'atascado en el trafico', 'llevo una hora en el trafico' ] },
57
+ { id: 'lost_keys_wallet', label: 'Temporarily losing keys or wallet', sourced: false, impact: 15, valence: -0.3, dominance: -0.4, area: [ 'Focus', 'Intuition' ], keywords: [ 'perdi mis llaves', 'perdi mi cartera', 'no encuentro mis llaves' ] },
58
+ { id: 'message_ignored', label: 'Being ignored on a key message', sourced: false, impact: 12, valence: -0.2, dominance: -0.3, area: [ 'Echo', 'Ego' ], keywords: [ 'me dejaste en visto', 'no me respondiste el mensaje' ] },
59
+ { id: 'tech_failure_minor', label: 'Minor technical failure', sourced: false, impact: 10, valence: -0.4, dominance: -0.5, area: [ 'Logic', 'Affect' ], keywords: [ 'se borro el archivo', 'fallo el sistema', 'perdi mi trabajo sin guardar' ] },
60
+
61
+ ]
62
+
63
+ function normalize( text ) {
64
+
65
+ return ( text || '' ).toLowerCase()
66
+
67
+ }
68
+
69
+ export class LifeEventCatalog {
70
+
71
+ detect( text ) {
72
+
73
+ const lower = normalize( text )
74
+ return LIFE_EVENTS.filter( event => event.keywords.some( phrase => lower.includes( phrase ) ) )
75
+
76
+ }
77
+
78
+ triangulate( matches ) {
79
+
80
+ if ( !matches.length ) return null
81
+ if ( matches.length === 1 ) {
82
+
83
+ const [ only ] = matches
84
+ return { impact: only.impact, valence: only.valence, dominance: only.dominance, area: only.area, events: [ only.id ] }
85
+
86
+ }
87
+
88
+ const totalWeight = matches.reduce( ( sum, e ) => sum + e.impact, 0 )
89
+ const valence = matches.reduce( ( sum, e ) => sum + e.valence * e.impact, 0 ) / totalWeight
90
+ const dominance = matches.reduce( ( sum, e ) => sum + e.dominance * e.impact, 0 ) / totalWeight
91
+ const impact = Math.max( ...matches.map( e => e.impact ) )
92
+ const area = [ ...new Set( matches.flatMap( e => e.area ) ) ]
93
+
94
+ return { impact, valence, dominance, area, events: matches.map( e => e.id ) }
95
+
96
+ }
97
+
98
+ }