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.
- package/LICENSE +21 -0
- package/README.md +212 -0
- package/package.json +62 -0
- package/src/Totemheart.js +1363 -0
- package/src/behavior/AttentionFocus.js +69 -0
- package/src/behavior/ExpressionDebt.js +48 -0
- package/src/behavior/ExpressionDirectives.js +95 -0
- package/src/behavior/ExpressiveSuppression.js +45 -0
- package/src/behavior/IdleProcessing.js +64 -0
- package/src/behavior/LinguisticModulation.js +62 -0
- package/src/behavior/LogitBiasBuilder.js +31 -0
- package/src/behavior/RuminationChain.js +93 -0
- package/src/behavior/StyleMimicry.js +72 -0
- package/src/cognition/AmygdalaHijack.js +40 -0
- package/src/cognition/AppraisalAgreement.js +39 -0
- package/src/cognition/BayesianExpectation.js +59 -0
- package/src/cognition/CognitiveDissonance.js +71 -0
- package/src/cognition/ControllabilityEstimate.js +56 -0
- package/src/cognition/DecisionFatigue.js +44 -0
- package/src/cognition/DefenseMechanisms.js +32 -0
- package/src/cognition/EmotionalOntology.js +134 -0
- package/src/cognition/FuzzyNormativeCheck.js +60 -0
- package/src/cognition/Intuition.js +71 -0
- package/src/cognition/LifeEventCatalog.js +98 -0
- package/src/cognition/LoadScheduler.js +41 -0
- package/src/cognition/LogicEngine.js +69 -0
- package/src/cognition/NoveltyDetector.js +59 -0
- package/src/cognition/Reappraisal.js +34 -0
- package/src/cognition/RefractoryPeriod.js +38 -0
- package/src/cognition/RemConsolidation.js +79 -0
- package/src/cognition/SarcasmDetector.js +38 -0
- package/src/cognition/SemanticSimilarity.js +75 -0
- package/src/cognition/Sensitization.js +45 -0
- package/src/cognition/SituationalContext.js +48 -0
- package/src/cognition/TopicSatiation.js +54 -0
- package/src/cognition/VisualProsody.js +48 -0
- package/src/core/AffectEMA.js +26 -0
- package/src/core/CoreBeliefs.js +58 -0
- package/src/core/DecayEngine.js +56 -0
- package/src/core/EmotionSpace.js +146 -0
- package/src/core/HebbianPlasticity.js +59 -0
- package/src/core/HedonicAdaptation.js +62 -0
- package/src/core/Homeostasis.js +119 -0
- package/src/core/MicroEmotions.js +25 -0
- package/src/core/MoodTracker.js +53 -0
- package/src/core/Personality.js +84 -0
- package/src/core/PipelineResilience.js +24 -0
- package/src/core/TriggerSentinel.js +38 -0
- package/src/core/WornPathCache.js +57 -0
- package/src/economics/AnchoringBias.js +38 -0
- package/src/economics/ClassicalConditioning.js +59 -0
- package/src/economics/LossAversion.js +40 -0
- package/src/embodiment/HardwareInteroception.js +26 -0
- package/src/embodiment/InteroceptiveSignals.js +132 -0
- package/src/embodiment/SensoryOverload.js +45 -0
- package/src/index.js +14 -0
- package/src/integration/ContextAdapter.js +247 -0
- package/src/neurochemistry/ArousalKalmanFilter.js +39 -0
- package/src/neurochemistry/CircadianRhythm.js +29 -0
- package/src/neurochemistry/CortisolEngine.js +54 -0
- package/src/neurochemistry/DopaminergicEngine.js +42 -0
- package/src/providers/FunctionProvider.js +26 -0
- package/src/providers/HeuristicProvider.js +156 -0
- package/src/providers/LanguageProvider.js +13 -0
- package/src/providers/OllamaProvider.js +63 -0
- package/src/providers/TransformersProvider.js +154 -0
- package/src/social/Attachment.js +81 -0
- package/src/social/BystanderEffect.js +17 -0
- package/src/social/ChronicContagion.js +48 -0
- package/src/social/CounterfactualComparison.js +34 -0
- package/src/social/EgoConfidence.js +34 -0
- package/src/social/EgoProjection.js +20 -0
- package/src/social/EmotionalContagion.js +52 -0
- package/src/social/EpisodicMemory.js +266 -0
- package/src/social/FairnessMonitor.js +34 -0
- package/src/social/ForgettingCurve.js +28 -0
- package/src/social/GratitudeEngine.js +32 -0
- package/src/social/GuiltEngine.js +43 -0
- package/src/social/MonteCarloToM.js +49 -0
- package/src/social/ReputationEngine.js +45 -0
- package/src/social/SelfModel.js +50 -0
- package/src/social/StatusEnvy.js +34 -0
- package/src/social/TheoryOfMind.js +53 -0
- package/src/social/TribalCategorization.js +24 -0
- package/src/social/UncannyValleyDetector.js +59 -0
- package/src/text/EmotionalCorpus.js +70 -0
- package/src/text/EmotionalTextGenerator.js +56 -0
- package/src/text/ExplainabilityEngine.js +30 -0
- package/src/text/TemplateComposer.js +114 -0
- package/src/version.js +1 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
function clamp01( v ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* "No central clock, components react to instability" reframed honestly:
|
|
9
|
+
* Totemheart's mechanics have real data dependencies (appraisal needs to
|
|
10
|
+
* exist before dissonance can check it) — they cannot self-organize into
|
|
11
|
+
* arbitrary execution order like independent swarm workers. What CAN be
|
|
12
|
+
* genuinely load-adaptive is *which optional mechanics run at all* this
|
|
13
|
+
* turn. `DecisionFatigue.isShallow()` already does a binary version of this;
|
|
14
|
+
* LoadScheduler generalizes it into a graded "instability" reading
|
|
15
|
+
* (cortisol + arousal + fatigue) that decides, per optional mechanic,
|
|
16
|
+
* whether to spend the cycles — the computational budget flows toward the
|
|
17
|
+
* turn's actual bottleneck (an active threat/crisis) instead of always
|
|
18
|
+
* running the full fixed pipeline. Engineering design, no citation.
|
|
19
|
+
*/
|
|
20
|
+
export class LoadScheduler {
|
|
21
|
+
|
|
22
|
+
/** instability: 0 = calm, 1 = maximally overloaded. */
|
|
23
|
+
computeInstability( { cortisol = 0, arousal = 0, fatigue = 0 } ) {
|
|
24
|
+
|
|
25
|
+
return clamp01( cortisol * 0.4 + Math.max( 0, arousal ) * 0.35 + fatigue * 0.25 )
|
|
26
|
+
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Which optional stages to run this turn, given the instability reading. */
|
|
30
|
+
gate( instability ) {
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
runOntology : instability < 0.85,
|
|
34
|
+
runSituationalContext : true, // cheap, and precisely what's needed to detect instability in the first place
|
|
35
|
+
runSelfModelUpdate : instability < 0.9,
|
|
36
|
+
runBehavioralInconsistency : instability < 0.75,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cold, deductive reasoning — deliberately independent of the PAD vector,
|
|
3
|
+
* as requested. Two real pieces, honestly scoped:
|
|
4
|
+
* 1. Boolean proposition evaluation: does the input affirm or negate each
|
|
5
|
+
* CoreBelief's polarity? A real negation-window boolean check (not a
|
|
6
|
+
* full theorem prover), producing true/false/null (unrelated) per belief.
|
|
7
|
+
* 2. A small real tree search over candidate response strategies
|
|
8
|
+
* {agree, disagree, deflect}, each scored purely by how many boolean
|
|
9
|
+
* propositions it would violate — a genuine (if shallow, one-ply)
|
|
10
|
+
* search-and-score process, not a re-labeling of the emotional pipeline.
|
|
11
|
+
* This is NOT a claim of implementing Tree-of-Thoughts or A* search in
|
|
12
|
+
* their full generality (those explore deep, branching chains with a
|
|
13
|
+
* learned heuristic) — it's the honestly-sized real version: one level
|
|
14
|
+
* of real search over a small fixed action set, scored deterministically.
|
|
15
|
+
*/
|
|
16
|
+
const NEGATORS = new Set( [ 'no', 'nunca', 'jamas', 'jamás', 'tampoco', 'not', 'never' ] )
|
|
17
|
+
|
|
18
|
+
function tokenize( text ) {
|
|
19
|
+
|
|
20
|
+
return ( text || '' ).toLowerCase().match( /[\p{L}']+/gu ) || []
|
|
21
|
+
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class LogicEngine {
|
|
25
|
+
|
|
26
|
+
/** Returns [{ topic, consistent: true|false|null }] — null means "this input doesn't touch this belief at all". */
|
|
27
|
+
evaluatePropositions( text, beliefs ) {
|
|
28
|
+
|
|
29
|
+
const tokens = tokenize( text )
|
|
30
|
+
const negated = tokens.some( t => NEGATORS.has( t ) )
|
|
31
|
+
|
|
32
|
+
return beliefs.map( belief => {
|
|
33
|
+
|
|
34
|
+
const beliefTokens = tokenize( belief.statement )
|
|
35
|
+
const overlap = beliefTokens.filter( t => tokens.includes( t ) ).length
|
|
36
|
+
if ( overlap === 0 ) return { topic: belief.topic, consistent: null }
|
|
37
|
+
|
|
38
|
+
// If the input negates a belief it clearly overlaps with, it's inconsistent
|
|
39
|
+
// with that belief's stated polarity; otherwise treat it as affirming.
|
|
40
|
+
const inputPolarity = negated ? -1 : 1
|
|
41
|
+
const consistent = inputPolarity === Math.sign( belief.polarity || 1 )
|
|
42
|
+
return { topic: belief.topic, consistent }
|
|
43
|
+
|
|
44
|
+
} )
|
|
45
|
+
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* One-ply real search: score each candidate strategy by how many
|
|
50
|
+
* evaluated propositions it would violate if taken, pick the max —
|
|
51
|
+
* purely boolean, no emotional weighting.
|
|
52
|
+
*/
|
|
53
|
+
searchBestStrategy( propositionResults ) {
|
|
54
|
+
|
|
55
|
+
const violations = propositionResults.filter( p => p.consistent === false ).length
|
|
56
|
+
const affirmed = propositionResults.filter( p => p.consistent === true ).length
|
|
57
|
+
|
|
58
|
+
const strategies = {
|
|
59
|
+
agree : affirmed - violations * 2, // agreeing is bad if we're contradicting known-true beliefs
|
|
60
|
+
disagree : violations - affirmed * 0.5, // disagreeing is good precisely when there ARE violations to correct
|
|
61
|
+
deflect : violations > 0 && affirmed > 0 ? 0.5 : -1, // only sound when the picture is genuinely mixed
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const [ bestStrategy ] = Object.entries( strategies ).sort( ( a, b ) => b[ 1 ] - a[ 1 ] )
|
|
65
|
+
return { strategy: bestStrategy[ 0 ], scores: strategies, violations, affirmed }
|
|
66
|
+
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Novelty via Kullback-Leibler divergence: D_KL(P||Q) = Σ P(x) log(P(x)/Q(x)).
|
|
3
|
+
* Real formula, applied at the scale this library actually has data for: P is
|
|
4
|
+
* the running historical distribution over dominant-emotion outcomes for
|
|
5
|
+
* this kind of interaction; Q is what that distribution would look like if
|
|
6
|
+
* "this turn's outcome is the norm" (a Laplace-smoothed one-hot on the
|
|
7
|
+
* current label). High divergence = this turn breaks the historical pattern,
|
|
8
|
+
* independent of whether the break is pleasant or unpleasant (that
|
|
9
|
+
* distinction is DopaminergicEngine's job, not this module's).
|
|
10
|
+
*/
|
|
11
|
+
function clamp01( v ) {
|
|
12
|
+
|
|
13
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
14
|
+
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class NoveltyDetector {
|
|
18
|
+
|
|
19
|
+
constructor( { smoothing = 0.1 } = {} ) {
|
|
20
|
+
|
|
21
|
+
this.histogram = new Map() // emotion label -> count
|
|
22
|
+
this.smoothing = smoothing
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Returns a 0..1 novelty score, then records this observation into the history. */
|
|
27
|
+
observe( emotionLabel ) {
|
|
28
|
+
|
|
29
|
+
const total = [ ...this.histogram.values() ].reduce( ( a, b ) => a + b, 0 )
|
|
30
|
+
let divergence = 0
|
|
31
|
+
|
|
32
|
+
if ( total > 0 ) {
|
|
33
|
+
|
|
34
|
+
const labels = new Set( [ ...this.histogram.keys(), emotionLabel ] )
|
|
35
|
+
const k = labels.size
|
|
36
|
+
for ( const label of labels ) {
|
|
37
|
+
|
|
38
|
+
const p = ( this.histogram.get( label ) ?? 0 ) / total
|
|
39
|
+
if ( p === 0 ) continue // 0 * log(anything) = 0, skip to avoid NaN
|
|
40
|
+
|
|
41
|
+
// Q: Laplace-smoothed one-hot on the observed label — "this turn is normal".
|
|
42
|
+
const q = label === emotionLabel
|
|
43
|
+
? ( 1 - this.smoothing ) + this.smoothing / k
|
|
44
|
+
: this.smoothing / k
|
|
45
|
+
|
|
46
|
+
divergence += p * Math.log( p / q )
|
|
47
|
+
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
this.histogram.set( emotionLabel, ( this.histogram.get( emotionLabel ) ?? 0 ) + 1 )
|
|
53
|
+
|
|
54
|
+
// KL divergence is unbounded above; squash to 0..1 for use as a spike multiplier.
|
|
55
|
+
return clamp01( divergence / ( divergence + 1.5 ) )
|
|
56
|
+
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cognitive reappraisal — a second interpretive pass over an appraisal that
|
|
3
|
+
* deliberately reframes it toward a less extreme reading. The request that
|
|
4
|
+
* prompted this module named a GAN (Generative Adversarial Network) as the
|
|
5
|
+
* implementation technique; that's not applied here on purpose — a GAN
|
|
6
|
+
* needs a generator/discriminator pair trained against real reframing data,
|
|
7
|
+
* which does not exist for this library, and claiming one on a
|
|
8
|
+
* deterministic reweighting would be mislabeling, not an implementation.
|
|
9
|
+
* What's built instead is the real *effect* reappraisal is meant to have —
|
|
10
|
+
* "reinterpret the meaning of the event to change its emotional impact" —
|
|
11
|
+
* as an explicit, deterministic bias mask. Own design, no citation.
|
|
12
|
+
*/
|
|
13
|
+
function clamp01( v ) {
|
|
14
|
+
|
|
15
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
16
|
+
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class Reappraisal {
|
|
20
|
+
|
|
21
|
+
/** `strength` (0..1) — how much this reframing pass pulls the appraisal toward neutral. */
|
|
22
|
+
reframe( appraisal, strength = 0.4 ) {
|
|
23
|
+
|
|
24
|
+
const dampened = clamp01( strength )
|
|
25
|
+
return {
|
|
26
|
+
...appraisal,
|
|
27
|
+
desirability : ( appraisal.desirability ?? 0 ) * ( 1 - dampened ),
|
|
28
|
+
moralWeight : ( appraisal.moralWeight ?? 0 ) * ( 1 - dampened * 0.6 ),
|
|
29
|
+
reappraised : true,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ekman's observation that an emotion intense enough acts as a low-pass
|
|
3
|
+
* filter on contradicting information — furious enough, and an apology
|
|
4
|
+
* reads as another attack. Real formula, applied to the AI's OWN state
|
|
5
|
+
* (arousal/valence it already has, before this turn's new appraisal is
|
|
6
|
+
* folded in), not a citation of Ekman's specific numbers — the shape of
|
|
7
|
+
* "a real multiplier that dampens conflicting input near peak arousal", own
|
|
8
|
+
* tuning.
|
|
9
|
+
*/
|
|
10
|
+
export class RefractoryPeriod {
|
|
11
|
+
|
|
12
|
+
/** Is the AI currently in a refractory state (near-max arousal, strongly negative)? */
|
|
13
|
+
isActive( vector, { arousalThreshold = 0.7, valenceThreshold = -0.5 } = {} ) {
|
|
14
|
+
|
|
15
|
+
return vector.arousal >= arousalThreshold && vector.valence <= valenceThreshold
|
|
16
|
+
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Dampens an incoming signal that would move the state AWAY from where it
|
|
21
|
+
* currently is (a calming/positive input while furious) — signals that
|
|
22
|
+
* agree with the current state pass through undampened. Input_perceived =
|
|
23
|
+
* Input_real · (1 - arousal/arousalMax), only when it disagrees.
|
|
24
|
+
*/
|
|
25
|
+
filter( incomingDesirability, vector, arousalMax = 1 ) {
|
|
26
|
+
|
|
27
|
+
const active = this.isActive( vector )
|
|
28
|
+
if ( !active ) return { filtered: incomingDesirability, active: false, dampening: 0 }
|
|
29
|
+
|
|
30
|
+
const contradicts = incomingDesirability > 0 // trying to calm/please a furious state
|
|
31
|
+
if ( !contradicts ) return { filtered: incomingDesirability, active: true, dampening: 0 }
|
|
32
|
+
|
|
33
|
+
const dampening = Math.max( 0, Math.min( 1, vector.arousal / arousalMax ) )
|
|
34
|
+
return { filtered: incomingDesirability * ( 1 - dampening ), active: true, dampening }
|
|
35
|
+
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real elapsed-time trigger (Date.now() gap since the last turn, not a
|
|
3
|
+
* turn-count heuristic) that runs a background-style sweep before the next
|
|
4
|
+
* turn is processed. Cools stored episodic memories' arousal while leaving
|
|
5
|
+
* their valence/concepts untouched (the semantic "lesson" survives, the raw
|
|
6
|
+
* intensity doesn't — inspired by the general shape of memory-consolidation
|
|
7
|
+
* research on episodic traces stabilizing over rest, not a citation of any
|
|
8
|
+
* specific study's numbers), prunes stale Hebbian associations, and applies
|
|
9
|
+
* the existing DecayEngine over the REAL elapsed hours instead of a per-turn
|
|
10
|
+
* dt — the same machinery, driven by wall-clock time this one time. Identity-
|
|
11
|
+
* level state (SelfModel, Attachment/tribal loyalty, CoreBeliefs) is
|
|
12
|
+
* deliberately untouched: rest cools feelings, it doesn't erase what was
|
|
13
|
+
* learned.
|
|
14
|
+
*/
|
|
15
|
+
export class RemConsolidation {
|
|
16
|
+
|
|
17
|
+
constructor( { idleThresholdMs = 1000 * 60 * 60 * 4, lambdaRem = 0.3, arousalCoolingThreshold = 0.5 } = {} ) {
|
|
18
|
+
|
|
19
|
+
this.idleThresholdMs = idleThresholdMs
|
|
20
|
+
this.lambdaRem = lambdaRem
|
|
21
|
+
this.arousalCoolingThreshold = arousalCoolingThreshold
|
|
22
|
+
this.lastTurnAt = null
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
shouldTrigger( now = Date.now() ) {
|
|
27
|
+
|
|
28
|
+
return this.lastTurnAt !== null && ( now - this.lastTurnAt ) > this.idleThresholdMs
|
|
29
|
+
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
recordTurn( now = Date.now() ) {
|
|
33
|
+
|
|
34
|
+
this.lastTurnAt = now
|
|
35
|
+
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
sweep( { episodicMemory, hebbianPlasticity, cortisolEngine, expressionDebt, sensitization, emotionSpace, moodTracker, decayEngine, personality }, now = Date.now() ) {
|
|
39
|
+
|
|
40
|
+
const elapsedMs = this.lastTurnAt !== null ? now - this.lastTurnAt : 0
|
|
41
|
+
const elapsedHours = elapsedMs / ( 1000 * 60 * 60 )
|
|
42
|
+
|
|
43
|
+
// Episodic replay: cool peak arousal on high-magnitude memories, real-cite-free
|
|
44
|
+
// exponential dampening, valence/concepts left exactly as stored.
|
|
45
|
+
let cooled = 0
|
|
46
|
+
for ( const m of episodicMemory.memories ) {
|
|
47
|
+
|
|
48
|
+
const arousal = m.emotionalSignature?.arousal ?? 0
|
|
49
|
+
if ( Math.abs( arousal ) > this.arousalCoolingThreshold ) {
|
|
50
|
+
|
|
51
|
+
m.emotionalSignature.arousal = arousal * Math.exp( -this.lambdaRem )
|
|
52
|
+
cooled++
|
|
53
|
+
|
|
54
|
+
}
|
|
55
|
+
if ( m.importance > 0.6 || m.permanent ) episodicMemory.tagRemSalient( m.id, now )
|
|
56
|
+
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Synaptic pruning — extra decay on associations that went stale during the gap.
|
|
60
|
+
if ( hebbianPlasticity ) hebbianPlasticity.decayOnly( Math.min( elapsedHours * 0.05, 0.9 ) )
|
|
61
|
+
|
|
62
|
+
// Basal reset — the felt state cools by REAL elapsed time via the same
|
|
63
|
+
// DecayEngine machinery every tick() already uses, just driven by hours
|
|
64
|
+
// instead of turns.
|
|
65
|
+
const mood = moodTracker.getMood()
|
|
66
|
+
const restDt = Math.min( elapsedHours, 24 * 30 ) // cap at ~1 simulated month so a multi-year gap doesn't do anything pathological
|
|
67
|
+
decayEngine.apply( emotionSpace, mood, personality, restDt )
|
|
68
|
+
cortisolEngine.decay( restDt )
|
|
69
|
+
expressionDebt.decay( restDt )
|
|
70
|
+
sensitization.decay( restDt )
|
|
71
|
+
|
|
72
|
+
const topUnresolved = episodicMemory.getUnresolvedMemories( null, 1 )[ 0 ] ?? null
|
|
73
|
+
this.recordTurn( now )
|
|
74
|
+
|
|
75
|
+
return { elapsedHours, memoriesCooled: cooled, topUnresolvedConcepts: topUnresolved?.concepts ?? [] }
|
|
76
|
+
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sarcasm is the collision between literal wording and its context — "GREAT,
|
|
3
|
+
* love that" right after something bad just happened. Honest reframing of
|
|
4
|
+
* the original proposal: there's no "ground truth of the real situation"
|
|
5
|
+
* available to compare against — the real signal this can actually use is
|
|
6
|
+
* recent conversational context, specifically the average valence of this
|
|
7
|
+
* user's last few episodic memories (a real, already-stored history, not an
|
|
8
|
+
* invented oracle). Derr = |semanticValence - contextValence| * visualProsodyIntensity;
|
|
9
|
+
* past a threshold, flags sarcasm and inverts the semantic valence sign
|
|
10
|
+
* before it reaches Appraisal. Own design, no citation.
|
|
11
|
+
*
|
|
12
|
+
* Real bug found running a full personality-mock battery: raw distance alone
|
|
13
|
+
* fires on genuine enthusiasm right after a merely-neutral prior turn (0.89
|
|
14
|
+
* vs. 0.04 is a big gap, but 0.04 isn't a negative context — there's nothing
|
|
15
|
+
* to be incongruent WITH). Fixed by requiring an actual sign mismatch with a
|
|
16
|
+
* context that's meaningfully non-neutral first — sarcasm is words
|
|
17
|
+
* contradicting a real opposite-valence context, not just any wide gap.
|
|
18
|
+
*/
|
|
19
|
+
export class SarcasmDetector {
|
|
20
|
+
|
|
21
|
+
detect( semanticValence, contextValence, prosodyIntensity, threshold = 0.9 ) {
|
|
22
|
+
|
|
23
|
+
const incongruent = Math.abs( contextValence ) > 0.2 && Math.sign( semanticValence ) !== Math.sign( contextValence )
|
|
24
|
+
if ( !incongruent ) return { sarcastic: false, derr: 0, adjustedValence: semanticValence }
|
|
25
|
+
|
|
26
|
+
const disagreement = Math.abs( semanticValence - contextValence )
|
|
27
|
+
const derr = disagreement * Math.max( 1, prosodyIntensity )
|
|
28
|
+
const sarcastic = derr > threshold
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
sarcastic,
|
|
32
|
+
derr,
|
|
33
|
+
adjustedValence : sarcastic ? -semanticValence : semanticValence,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real cosine similarity against latent concept clusters — Similitud(A,B) =
|
|
3
|
+
* (A·B)/(||A||·||B||) — computed on real sentence embeddings (from
|
|
4
|
+
* TransformersProvider.embed(), verified end-to-end during development:
|
|
5
|
+
* related threat sentences scored ~0.74 similarity, an unrelated positive
|
|
6
|
+
* sentence scored ~0.36 against the same anchor). Requires an embedding
|
|
7
|
+
* backend to be supplied; `EmotionalOntology`'s keyword matching is what
|
|
8
|
+
* runs when none is configured — this doesn't replace that fallback, it's
|
|
9
|
+
* a strictly better signal when a real embedding model is available.
|
|
10
|
+
*/
|
|
11
|
+
const DEFAULT_CLUSTERS = {
|
|
12
|
+
hostilidad : 'me estás atacando, esto es una amenaza y me insultas',
|
|
13
|
+
curiosidad_genuina : 'qué interesante, cuéntame más sobre eso, tengo curiosidad',
|
|
14
|
+
afecto : 'te aprecio mucho, esto significa mucho para mí',
|
|
15
|
+
urgencia : 'esto es urgente, necesito una respuesta ahora mismo',
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function cosineSimilarity( a, b ) {
|
|
19
|
+
|
|
20
|
+
let dot = 0
|
|
21
|
+
let na = 0
|
|
22
|
+
let nb = 0
|
|
23
|
+
for ( let i = 0; i < a.length; i++ ) {
|
|
24
|
+
|
|
25
|
+
dot += a[ i ] * b[ i ]
|
|
26
|
+
na += a[ i ] * a[ i ]
|
|
27
|
+
nb += b[ i ] * b[ i ]
|
|
28
|
+
|
|
29
|
+
}
|
|
30
|
+
const denom = Math.sqrt( na ) * Math.sqrt( nb )
|
|
31
|
+
return denom > 0 ? dot / denom : 0
|
|
32
|
+
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class SemanticSimilarity {
|
|
36
|
+
|
|
37
|
+
constructor( embedProvider = null, clusters = DEFAULT_CLUSTERS ) {
|
|
38
|
+
|
|
39
|
+
this.embedProvider = embedProvider // an object with an async embed(text) method, e.g. TransformersProvider
|
|
40
|
+
this.clusters = clusters
|
|
41
|
+
this.clusterEmbeddings = new Map()
|
|
42
|
+
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
get available() {
|
|
46
|
+
|
|
47
|
+
return this.embedProvider !== null
|
|
48
|
+
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async #ensureClusters() {
|
|
52
|
+
|
|
53
|
+
for ( const [ name, exampleText ] of Object.entries( this.clusters ) ) {
|
|
54
|
+
|
|
55
|
+
if ( !this.clusterEmbeddings.has( name ) ) this.clusterEmbeddings.set( name, await this.embedProvider.embed( exampleText ) )
|
|
56
|
+
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Returns {clusterName: similarity} for every configured cluster, or null if no embedding backend is configured. */
|
|
62
|
+
async classify( text ) {
|
|
63
|
+
|
|
64
|
+
if ( !this.available ) return null
|
|
65
|
+
|
|
66
|
+
await this.#ensureClusters()
|
|
67
|
+
const vector = await this.embedProvider.embed( text )
|
|
68
|
+
|
|
69
|
+
const scores = {}
|
|
70
|
+
for ( const [ name, clusterVector ] of this.clusterEmbeddings ) scores[ name ] = cosineSimilarity( vector, clusterVector )
|
|
71
|
+
return scores
|
|
72
|
+
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Repeated negative stimuli lower the firing threshold for the next one — a
|
|
3
|
+
* real (if simplified) analogue of long-term potentiation strengthening a
|
|
4
|
+
* pathway with repeated activation: the more a negative-valence spike has
|
|
5
|
+
* fired recently, the less it takes to fire again. Concretely: a running
|
|
6
|
+
* "sensitized" level that rises on each negative spike and decays over
|
|
7
|
+
* ticks, exposed as a threshold multiplier consumers (AmygdalaHijack,
|
|
8
|
+
* CortisolEngine) can apply to become more trigger-happy under a recent run
|
|
9
|
+
* of negative stimuli — i.e. irritability. Engineering approximation of LTP,
|
|
10
|
+
* not a spiking-neural-network simulation — see CALIBRATION.md.
|
|
11
|
+
*/
|
|
12
|
+
function clamp01( v ) {
|
|
13
|
+
|
|
14
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
15
|
+
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class Sensitization {
|
|
19
|
+
|
|
20
|
+
constructor() {
|
|
21
|
+
|
|
22
|
+
this.level = 0
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
observe( valence ) {
|
|
27
|
+
|
|
28
|
+
if ( valence < -0.15 ) this.level = clamp01( this.level + Math.abs( valence ) * 0.2 )
|
|
29
|
+
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
decay( dt, lambda = 0.05 ) {
|
|
33
|
+
|
|
34
|
+
this.level = Math.max( 0, this.level - lambda * dt )
|
|
35
|
+
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** <1 = fires more easily (sensitized/irritable). */
|
|
39
|
+
getThresholdMultiplier() {
|
|
40
|
+
|
|
41
|
+
return 1 - this.level * 0.3
|
|
42
|
+
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const URGENCY_WORDS = [ 'ahora', 'ya', 'urgente', 'rápido', 'deprisa', 'inmediatamente', 'now', 'urgent', 'hurry', 'immediately', 'asap' ]
|
|
2
|
+
|
|
3
|
+
function tokenize( text ) {
|
|
4
|
+
|
|
5
|
+
return ( text || '' ).toLowerCase().match( /[\p{L}']+/gu ) || []
|
|
6
|
+
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function clamp01( v ) {
|
|
10
|
+
|
|
11
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
12
|
+
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Reads situational signals out of the raw message itself — is the user
|
|
17
|
+
* stressed, in a hurry, upbeat — independent of what the appraisal/ontology
|
|
18
|
+
* concludes about desirability. Used to amplify threat-sensitivity: a
|
|
19
|
+
* message read as mildly critical lands harder if the user also seems to be
|
|
20
|
+
* in crisis. This is engineering informed by a general Gestalt-style
|
|
21
|
+
* observation (meaning is read in context, not word-by-word in isolation),
|
|
22
|
+
* not a citation of any specific formula — see CALIBRATION.md.
|
|
23
|
+
*/
|
|
24
|
+
export class SituationalContext {
|
|
25
|
+
|
|
26
|
+
extract( text, sentimentScore = 0 ) {
|
|
27
|
+
|
|
28
|
+
const tokens = tokenize( text )
|
|
29
|
+
const exclaimCount = ( ( text || '' ).match( /[!¡]/g ) || [] ).length
|
|
30
|
+
const urgencyHits = tokens.filter( t => URGENCY_WORDS.includes( t ) ).length
|
|
31
|
+
const capsRatio = ( ( text || '' ).match( /[A-ZÁÉÍÓÚÑ]{3,}/g ) || [] ).length
|
|
32
|
+
|
|
33
|
+
const urgency = clamp01( urgencyHits * 0.3 + exclaimCount * 0.15 + capsRatio * 0.2 )
|
|
34
|
+
const stress = clamp01( Math.max( 0, -sentimentScore ) * 0.7 + urgency * 0.3 )
|
|
35
|
+
const joy = clamp01( Math.max( 0, sentimentScore ) )
|
|
36
|
+
|
|
37
|
+
return { stress, urgency, joy }
|
|
38
|
+
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Multiplier applied to threat-sensitive appraisal fields (arousal, moralWeight). */
|
|
42
|
+
getThreatMultiplier( context ) {
|
|
43
|
+
|
|
44
|
+
return 1 + context.stress * 0.3
|
|
45
|
+
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { cosineSimilarity } from './SemanticSimilarity.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Boredom from talking about the same thing without new information — a
|
|
5
|
+
* real rolling-window cosine-similarity decay, own design (no citation).
|
|
6
|
+
* Needs a real embedding backend (same optional one SemanticSimilarity
|
|
7
|
+
* uses); without one this gracefully returns 0 fatigue every turn, same
|
|
8
|
+
* fallback pattern as SemanticSimilarity itself — EmotionalOntology's
|
|
9
|
+
* keyword path is what's actually driving novelty in that case, via
|
|
10
|
+
* NoveltyDetector's KL divergence instead.
|
|
11
|
+
*/
|
|
12
|
+
export class TopicSatiation {
|
|
13
|
+
|
|
14
|
+
constructor( embedProvider = null, { windowSize = 5, threshold = 0.85 } = {} ) {
|
|
15
|
+
|
|
16
|
+
this.embedProvider = embedProvider
|
|
17
|
+
this.windowSize = windowSize
|
|
18
|
+
this.threshold = threshold
|
|
19
|
+
this.history = [] // recent turn embeddings, most recent last
|
|
20
|
+
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
get available() {
|
|
24
|
+
|
|
25
|
+
return this.embedProvider !== null
|
|
26
|
+
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Returns { fatigue, meanSimilarity } for this turn against its own recent window, then records it. */
|
|
30
|
+
async observe( text ) {
|
|
31
|
+
|
|
32
|
+
if ( !this.available ) return { fatigue: 0, meanSimilarity: 0 }
|
|
33
|
+
|
|
34
|
+
const vector = await this.embedProvider.embed( text )
|
|
35
|
+
|
|
36
|
+
if ( this.history.length === 0 ) {
|
|
37
|
+
|
|
38
|
+
this.history.push( vector )
|
|
39
|
+
return { fatigue: 0, meanSimilarity: 0 }
|
|
40
|
+
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const similarities = this.history.map( past => cosineSimilarity( vector, past ) )
|
|
44
|
+
const meanSimilarity = similarities.reduce( ( a, b ) => a + b, 0 ) / similarities.length
|
|
45
|
+
const fatigue = similarities.reduce( ( sum, s ) => sum + Math.max( 0, s - this.threshold ), 0 )
|
|
46
|
+
|
|
47
|
+
this.history.push( vector )
|
|
48
|
+
if ( this.history.length > this.windowSize ) this.history.shift()
|
|
49
|
+
|
|
50
|
+
return { fatigue, meanSimilarity }
|
|
51
|
+
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text has no volume, but capitalization and punctuation density function
|
|
3
|
+
* as a real proxy for it — shouting "HOLA" isn't semantically different
|
|
4
|
+
* from "hola" (same word), but it's a real, measurable spike in typographic
|
|
5
|
+
* energy. Scanned directly on the raw input string, before any lexicon or
|
|
6
|
+
* LLM parsing touches it. Own design, no citation: this is a plain ratio +
|
|
7
|
+
* saturating exponential, not a reproduction of any named prosody model.
|
|
8
|
+
*/
|
|
9
|
+
function countLetters( text ) {
|
|
10
|
+
|
|
11
|
+
return ( text.match( /\p{L}/gu ) || [] ).length
|
|
12
|
+
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function countUppercaseLetters( text ) {
|
|
16
|
+
|
|
17
|
+
return ( text.match( /\p{Lu}/gu ) || [] ).length
|
|
18
|
+
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function countExtremePunctuation( text ) {
|
|
22
|
+
|
|
23
|
+
return ( text.match( /[!?¡¿]/gu ) || [] ).length
|
|
24
|
+
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class VisualProsody {
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Returns { capsRatio, punctuationDensity, intensity } — intensity is
|
|
31
|
+
* capsRatio + (1 - e^(-k·punctCount)), unbounded above ~2 but in
|
|
32
|
+
* practice rarely exceeds ~1.5 for real text.
|
|
33
|
+
*/
|
|
34
|
+
analyze( text, k = 0.4 ) {
|
|
35
|
+
|
|
36
|
+
const letters = countLetters( text )
|
|
37
|
+
const uppercase = countUppercaseLetters( text )
|
|
38
|
+
const punctCount = countExtremePunctuation( text )
|
|
39
|
+
|
|
40
|
+
const capsRatio = letters > 0 ? uppercase / letters : 0
|
|
41
|
+
const punctuationDensity = 1 - Math.exp( -k * punctCount )
|
|
42
|
+
const intensity = capsRatio + punctuationDensity
|
|
43
|
+
|
|
44
|
+
return { capsRatio, punctuationDensity, intensity }
|
|
45
|
+
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The literal exponential moving average requested for the Affect core:
|
|
3
|
+
* S_t = α·S_{t-1} + (1-α)·I_t
|
|
4
|
+
* Applied specifically to the Dominance axis, which (unlike valence — tanh
|
|
5
|
+
* squashed in EmotionSpace.applySpike — and arousal — smoothed by
|
|
6
|
+
* ArousalKalmanFilter) had no persistence smoothing of its own. α close to
|
|
7
|
+
* 1 = slow-changing, inertial dominance; close to 0 = reacts fully to each
|
|
8
|
+
* impulse. Own default (0.7), not a citation.
|
|
9
|
+
*/
|
|
10
|
+
export class AffectEMA {
|
|
11
|
+
|
|
12
|
+
constructor( { alpha = 0.7 } = {} ) {
|
|
13
|
+
|
|
14
|
+
this.alpha = alpha
|
|
15
|
+
this.state = 0
|
|
16
|
+
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
update( impulse ) {
|
|
20
|
+
|
|
21
|
+
this.state = this.alpha * this.state + ( 1 - this.alpha ) * impulse
|
|
22
|
+
return this.state
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
}
|