New:Microsoft Teams Notifications Are Now Available in Socket.Learn more →
Get Started

@zensation/algorithms

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@zensation/algorithms

Agent memory for LLM agents: FSRS spaced repetition, Hebbian learning, Ebbinghaus forgetting curves, emotional tagging, sleep consolidation and 15 more. ZenBrain's algorithm core — 20 modules, zero-dependency TypeScript library.

latest
Source
npmnpm
Version
0.4.5
Version published
Weekly downloads
226
53.74%
Maintainers
1
Weekly downloads
 
Created
Source

@zensation/algorithms

Neuroscience-inspired memory algorithms for AI agents. Pure TypeScript. Zero dependencies.

npm License TypeScript Zero Dependencies

What's Inside

20 algorithm modules (10 core + 10 advanced), extracted from a production AI platform and published as standalone, dependency-free modules. Pure TypeScript, zero runtime dependencies, tree-shakeable subpath exports, 429 tests.

ZenBrain's full architecture is 15 neuroscience-inspired mechanisms (9 foundational + 6 PMA) (paper). The 6 PMA components are proprietary; this open-source package ships the algorithm library described below.

Core (10 algorithms — since v0.2.x)

AlgorithmInspired ByWhat It Does
FSRSFree Spaced Repetition SchedulerOptimal review scheduling — your AI never forgets what matters
EbbinghausEbbinghaus (1885)Exponential forgetting curves with personalized decay profiles
EmotionalAmygdala modulation (Cahill & McGaugh, 1998)Arousal/valence/significance tagging — emotional memories decay 3× slower
HebbianHebb's Rule (1949)Co-activation strengthening with homeostatic normalization
BayesianBayesian belief propagationConfidence propagation through knowledge graphs
Context RetrievalEncoding Specificity (Tulving, 1973)Context-dependent retrieval boost when contexts match
SimilarityNLP heuristicsNegation detection (EN/DE), Jaccard similarity, text analysis
Sleep ConsolidationStickgold & Walker (2013)Replay simulation — strengthens emotional/recent memories, prunes weak edges
IntervalsStatistics95 % confidence intervals on retrievability and propagation
Visualization—Export retention curves and FSRS schedules for charting
(plus shared types)—Logger interface, common typedefs

Advanced algorithms (10 algorithms — new in v0.3.0)

Each is a separate sub-path import. Grounded in recent neuroscience and ML literature:

AlgorithmSub-pathInspired by
Prediction-Error coupled FSRS./fsrs-vmPFCZou et al. 2025, vmPFC re-encoding
Two-Factor Synaptic Hebbian./hebbian-two-factorZenke et al. 2025, two-factor consolidation
Simulation-Selection Sleep Loop./sleep-simulation-selectionFrontiers Comp. Neurosci. 2025, RL replay
Spectral KG Health (Fiedler value)./spectral-healthAlgebraic graph theory
Information-Bottleneck Budget./ib-budgetMemFly 2026, IB-based retention
Dopamine-Modulated Routing./dopamine-routingReward-modulated retrieval routing
Hopfield Short-Term Memory./hopfield-stmModern Hopfield networks
Personalized PageRank./personalized-pagerankGraph propagation
Surprise-Gradient (Variational FE) Memory./surprise-gradient-memoryFree-energy principle
Temporal Multi-Route Retrieval./temporal-multi-routeDecomposed temporal queries

Quick Start

npm install @zensation/algorithms
import {
  // FSRS Spaced Repetition
  initFromDecayClass,
  getRetrievability,
  updateAfterRecall,
  scheduleNextReview,

  // Emotional Memory
  tagEmotion,
  computeEmotionalWeight,

  // Hebbian Learning
  computeHebbianStrengthening,
  computeHebbianDecay,

  // Bayesian Confidence
  propagateForRelation,
} from '@zensation/algorithms';

// 1. Create a memory with FSRS scheduling
const memory = initFromDecayClass('normal_decay');
console.log(memory);
// { difficulty: 5, stability: 7, nextReview: Date }

// 2. A week later, check recall probability (Ebbinghaus decay)
const aWeekLater = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const retention = getRetrievability(memory, aWeekLater);
console.log(`Recall probability: ${(retention * 100).toFixed(1)}%`);
// ~36.8% — retrievability has decayed over the week

// 3. User recalled it anyway with grade 4 (good)
const updated = updateAfterRecall(memory, 4, retention, aWeekLater);
console.log(`Stability: ${memory.stability} -> ${updated.stability.toFixed(2)}`);
// 7 -> 8.19 — recalling at low retrievability gives a bigger boost (desirable difficulty)

// 4. Tag emotional significance
const emotion = tagEmotion('I am absolutely thrilled — I got the promotion!');
console.log(emotion);
// { sentiment: 0.55, arousal: 0.35, valence: 0.78, significance: 0.85 }

const weight = computeEmotionalWeight(emotion);
console.log(`Decay multiplier: ${weight.decayMultiplier}x`);
// 2.7x — this memory will decay nearly 3x slower

// 5. Strengthen knowledge graph edges via Hebbian learning
const newWeight = computeHebbianStrengthening(1.0);
// 1.09 — asymptotic growth toward MAX_WEIGHT (10.0)

// 6. Propagate confidence through relations
const newConfidence = propagateForRelation(
  0.5,   // base confidence
  0.8,   // source confidence
  1.0,   // edge weight
  'supports'
);
// 0.9 — supporting evidence increases confidence

Tree-Shakeable Imports

Import only what you need:

// Just FSRS
import { updateAfterRecall, getRetrievability } from '@zensation/algorithms/fsrs';

// Just emotional tagging
import { tagEmotion } from '@zensation/algorithms/emotional';

// Just Hebbian dynamics
import { computeHebbianStrengthening } from '@zensation/algorithms/hebbian';

Why These Algorithms?

FSRS vs SM-2

SM-2 (SuperMemo 2, 1990) uses fixed multipliers. FSRS uses the desirable difficulty principle: reviewing when retention is low gives a bigger stability boost. The result? 30% fewer reviews for the same retention.

Emotional Memory

Human brains consolidate emotional memories more strongly (flashbulb memory effect). This module gives your AI the same capability: memories tagged with high arousal + significance get up to 3x longer decay half-life.

Hebbian Learning

Knowledge graph edges that are frequently co-activated grow stronger. Edges that are never used decay and get pruned. The result is a self-organizing knowledge structure that reflects actual usage patterns.

Context-Dependent Retrieval

Tulving showed that memory recall improves when the retrieval context matches the encoding context. This module captures temporal + task context at encoding time and provides up to a 30% retrieval boost when contexts match.

API Reference

FSRS (@zensation/algorithms/fsrs)

FunctionDescription
initFromDecayClass(class, emotionalWeight?)Create initial state from decay class
initFromSM2(stability)Convert SM-2 stability to FSRS state
getRetrievability(state, now?)Calculate current recall probability
scheduleNextReview(state, targetRetention?, now?)Schedule next optimal review
updateAfterRecall(state, grade, retrievability, now?)Update after successful recall (grade 1-5)
updateAfterForgot(state, retrievability, now?)Update after failed recall
updateStabilityCompat(stability, success, multiplier?)Drop-in SM-2 replacement
getRetentionProbabilityCompat(lastAccess, stability, multiplier?)Drop-in Ebbinghaus replacement

Ebbinghaus (@zensation/algorithms/ebbinghaus)

FunctionDescription
calculateRetention(lastAccess, stability, emotionalMultiplier?)Full retention analysis
updateStability(stability, success)SM-2 stability update
getRepetitionCandidates(facts, threshold?)Find facts due for review
calculateOptimalInterval(stability, targetRetention?)Optimal review interval
batchCalculateRetention(facts)Efficient batch retention
learnDecayProfile(history)Personalized decay curves
calculatePersonalizedRetention(lastAccess, stability, profile)User-specific retention

Emotional (@zensation/algorithms/emotional)

FunctionDescription
tagEmotion(text, contextDomain?)Multi-dimensional emotion analysis
computeEmotionalWeight(tag)Consolidation weight + decay multiplier
isEmotionallySignificant(text, threshold?)Quick significance check
computeContextualValence(text, domain)Domain-adjusted valence

Hebbian (@zensation/algorithms/hebbian)

FunctionDescription
computeHebbianStrengthening(weight)Asymptotic edge strengthening
computeHebbianDecay(weight)Exponential decay with pruning
computeHomeostaticNormalization(weights, targetSum)Normalize weight distribution
generatePairs(items)Generate C(n,2) co-activation pairs

Bayesian (@zensation/algorithms/bayesian)

FunctionDescription
propagateForRelation(base, source, weight, type)Single-edge confidence propagation
applyDamping(newValue, previousValue)Blend with previous for stability
isSignificantChange(newValue, previousValue)Check if update is worth persisting

Context Retrieval (@zensation/algorithms/context-retrieval)

FunctionDescription
captureEncodingContext(taskType?)Snapshot current context
calculateContextSimilarity(encoding, current?)Context match score + boost
serializeContext(ctx) / deserializeContext(data)Storage helpers

Similarity (@zensation/algorithms/similarity)

FunctionDescription
detectNegation(text)Detect negation with target extraction (EN/DE)
computeStringSimilarity(a, b)Jaccard word overlap similarity
stripNegation(text)Remove negation words
safeJsonParse(json, fallback)Safe JSON parsing with fallback

Logging

All functions accept an optional Logger parameter. Pass console, your favorite logger, or nothing (silent by default):

import { updateAfterRecall } from '@zensation/algorithms';

// Silent (default)
updateAfterRecall(state, 4, 0.9);

// With logging
updateAfterRecall(state, 4, 0.9, new Date(), console);

Research

These algorithms are documented in an open-access technical disclosure: ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture (Zenodo). See also: HuggingFace Model Card.

Part of ZenBrain

This package is part of the ZenBrain monorepo — the neuroscience-inspired memory system for AI agents.

PackageDescription
@zensation/algorithmsPure algorithms (this package)
@zensation/coreMemory layers + coordinator
@zensation/adapter-postgresPostgreSQL + pgvector storage
@zensation/adapter-sqliteSQLite + sqlite-vec storage

License

Apache 2.0 — see LICENSE.

About ZenBrain

ZenBrain is a seven-layer, neuroscience-derived memory architecture for LLM agents, built as zero-dependency TypeScript and published under Apache-2.0. On LongMemEval-500 three of nine head-to-head answer-quality comparisons hold against Letta, Mem0 and A-Mem — all three against A-Mem, the remaining six are ties, none lost (three competitors x three LLM judges, Bonferroni-corrected, version-matched) — reaching 91.3% of a full-context oracle's binary-judge accuracy at 1/109.6 of the per-query token cost.

License: Apache-2.0

Keywords

ai-memory

FAQs

Package last updated on 21 Sep 2026

Related posts