Orma Memory

io.github.wizardwithcodehazard由 GitHub 账号 wizardwithcodehazard 发布v0.1.13更新于 Nov 1, 2026

Episode-first, zero-latency long-term memory for local LLMs and AI coding assistants.

发布方自己的服务:Memory.fit

已验证STDIO仅桌面知识与记忆AI 与机器学习

概览

AI 生成的概览

Orma Memory 通过 stdio 为编程助手提供本地 SQLite 长期记忆,让事实、决策和禁用规则跨会话保留。

可以做什么
  • 按查询召回受 token 预算限制的当前事实、过往决策与禁用规则
  • 记录项目决策、架构规则和用户约束,包括反模式
  • 登记硬性禁止项,并将其提升到注入记忆块的顶部
  • 查看全部当前有效事实,可选择包含已过时历史
  • 按状态 ID 关闭已过时或被取代的约束
  • 按用户或会话隔离不同的记忆空间
适用场景
适合编程助手在会话之间反复丢失上下文,需要快速召回项目决策、用户约束和“绝不要这样做”规则,且不希望依赖云服务的场景。面向笔记本上的本地开源模型。
运行要求
以本地进程方式通过 stdio 运行,从 orma-ai 的 PyPI 包安装(Python)。后台整合需要本地模型端点,例如 Ollama 或 llama.cpp。记忆保存在本地 SQLite 文件中。未声明任何 API 密钥或环境变量。
安装前请注意
remember、forbid 和 forget 工具会写入并关闭持久化本地记忆中的条目,错误会一直保留直到被修正。记忆内容会被注入发送给所配置本地模型的提示中。后台整合依赖本地模型抽取事实,README 称有确定性校验加以约束。

安装

在 SourceWeft 中

  1. 打开 控制台中的 Orma Memory,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

Orma (ഓർമ്മ)

Orma (Dravidian / Malayalam for "memory" or "recollection") is an episode-first, zero-latency long-term memory layer built specifically for local, open-weight LLMs (3B–8B models on consumer 8–16 GB laptops).

[PyPI Version] [License] [Python 3.10+] [Tests]

Orma can be used in two ways:

  1. As a native Python SDK (from orma import Memory) for direct integration into your agents, chatbots, and apps (like Mem0 and Cognee).
  2. As an OpenAI-compatible proxy (orma proxy or orma up) that transparently adds long-term memory to any LLM tool, client, or framework with zero code changes.

Everything runs locally in SQLite with sqlite-vec and fast on-device embeddings—no external servers, no cloud API keys, and zero data loss.


Quick Navigation


Why Orma vs. Mem0 & Cognee?

Most agent memory frameworks (like Mem0 or Cognee) were designed for massive cloud models (GPT-4o, Claude 3.5 Sonnet) and enterprise graph databases:

  1. They freeze chat turns: Calling an LLM synchronously on every add() causes 5–15 second freezes on local machines.
  2. They hallucinate graphs: 3B models struggle with complex entity-relation extraction and emit malformed JSON or inverted relations.
  3. They permanently corrupt facts: Prompting small models with destructive DELETE / UPDATE instructions leads to accidental data loss.

The Orma Approach

  • Episodes are the memory: Every conversation turn, document, or tool log is kept in full in an append-only log and indexed into sentences immediately.
  • Zero LLM calls on recall: Recall runs in < 25ms using hybrid vector search (sqlite-vec) + BM25 full-text search (FTS5) with bounded recency boosting (ACT-R).
  • Sleep consolidates state asynchronously: While the machine is idle, a background worker uses the local model to extract single-valued current states (now true) and dated events citing exact line numbers.
  • Deterministic code guards: Time resolution, pronoun carry-over (anuvṛtti), and contradiction resolution are handled in verified Python code, not by trusting small model arithmetic.
FeatureMem0CogneeOrma
Target LLMsCloud (GPT-4o)Cloud (GPT-4o)Local 3B–8B (Ollama / llama.cpp)
Python SDKMemory()cognee.add()from orma import Memory
Zero-Code Proxy ModePaid Cloud / CustomNoYes (orma proxy / orma up)
Write OverheadSynchronous LLM calls (5–15s delay)Multi-stage graph pipelinesInstant (< 5ms SQLite append)
Recall OverheadVector + LLM synthesisGraph traversal + LLMInstant (< 25ms hybrid search, 0 LLM calls)
Data SafetyDestructive DELETE / UPDATELossy graph extractionLossless append-only logs (rebuild anytime)
Storage ArchitectureExternal Vector DBNeo4j / NetworkX + VectorSingle embedded SQLite file (~/.orma/memory.db)
Hallucination ProtectionRelies on LLM accuracyRelies on Pydantic outputLine citations + deterministic Python guards

Empirical Benchmarks: Tokens & Latency

Orma is benchmarked on consumer laptop hardware (Apple Silicon M2 16GB / AMD Ryzen 7) against standard episodic and graph-based memory frameworks.

1. Context Token Overhead (10 Active Memories in Prompt)

Small local LLMs (3B–8B) have limited effective attention windows and generate significantly slower as prompt size increases. Orma's Sutra Dense Packing saves 35% to 45% tokens over standard bulleted memory blocks and up to 68% over verbose narrative prose:

Framework             Tokens Injected per Turn       Compression vs Mem0-------------------------------------------------------------------------Mem0 (Markdown Prose) ████████████████████ 420 tokens   [Baseline: 0%]Cognee (Graph Triples)█████████████████   365 tokens   [-13%]Orma Classic (Bullets)███████████         240 tokens   [-43%]Orma Sutra Packing    ██████              135 tokens   [-68% Token Savings!]
mermaid
xychart-beta    title "Prompt Token Overhead for 10 Active Memories (Lower is Better)"    x-axis ["Mem0 (Prose)", "Cognee (Triples)", "Orma Classic", "Orma Sutra"]    y-axis "Tokens in Prompt" 0 --> 500    bar [420, 365, 240, 135]

2. Recall & Add Latency (2,000 Episodic Records in SQLite)

Tested using scripts/latency_smoke.py over 2,000 realistic conversational turns and notes:

Operation                 Orma Latency      Cloud Graph Alternatives (Mem0/Cognee)---------------------------------------------------------------------------------Memory Add / Ingestion    1.2 ms (median)   5,000 - 15,000 ms (Synchronous LLM freeze)Hybrid Recall Search      16.4 ms (median)  1,800 - 3,500 ms (Multi-hop LLM synthesis)Recall Tail (p95)         21.8 ms           8,200 msNeedle-in-Haystack Acc    100.0% (5/5)      Varies by graph extraction accuracy
mermaid
xychart-beta    title "Recall Latency in Milliseconds (Lower is Better)"    x-axis ["Mem0 (LLM Synthesis)", "Cognee (Graph Traversal)", "Orma (Hybrid SQLite)"]    y-axis "Latency (ms)" 0 --> 3000    bar [2800, 1950, 18]

3. Negative Memory / Anti-Pattern Compliance Rate

Tested on local Qwen 2.5 3B Instruct across developer anti-patterns (e.g., PowerShell semicolon chaining) and strict lifestyle constraints (severe food allergies):

ApproachPrompt StrategyQwen 2.5 3B Compliance RateOutcome
Naive Prompting"Please don't use semicolons"28% (Fails 7/10 times)Attention activates on forbidden keyword
Standard NotesBullet point under "Now true:"45% (Fails 5/10 times)Model treats prohibition as general context
Orma Inhibitory Control[FORBIDDEN: ...] Hoisting + Dynamic Negative Framing100% (10/10 compliant)Absolute negative boundary enforced

Architecture & Data Flow

1. Online Recall & Cognitive Retrieval Pipeline (< 25ms, Zero LLM Calls)

mermaid
flowchart TD    User["User / App / Chatbot"] -->|"1a. Chat Request"| Proxy["Orma Proxy / SDK"]    CodingAgent["Coding Agent (Claude Code / Cursor / Windsurf)"] -->|"1b. MCP Tool Call (orma_recall)"| MCPServer["Orma MCP Server"]    MCPServer --> Proxy        subgraph MultiSearch ["Multi-Channel Hybrid Search (SQLite)"]        Proxy -->|"2a. BM25 Query"| FTS["FTS5 BM25 Exact Text Index"]        Proxy -->|"2b. Vector Query"| Vec["sqlite-vec (bge-small-en-v1.5)"]        FTS --> RRF["Reciprocal Rank Fusion (RRF)"]        Vec --> RRF        RRF --> NoiseFloor["Adaptive Space Noise Floor Calibration"]    end
    subgraph SpreadingGraph ["ACT-R Spreading Activation (SQLite Entity Graph)"]        NoiseFloor --> ExtractEntities["Extract Seed Entities from Query & States"]        ExtractEntities --> Adjacency["Traverse Bi-directional Entity Links"]        Adjacency --> FanEffect["Anderson's Fan Effect: Weight / Fan(Entity)"]        FanEffect --> AssociateStates["Boost Associated Context (Dr. Rao -> Clinic -> Toothache)"]    end
    subgraph CognitiveRanker ["Stochastic & Cognitive Scoring Suite"]        AssociateStates --> Hawkes["Hawkes Temporal Burst: alpha * exp(-beta * dt)"]        Hawkes --> Ebbinghaus["Ebbinghaus Spaced Stability: S = S0 * (1 + gain * (n - 1))"]        Ebbinghaus --> BaseLevel["ACT-R Base-Level Decay: sum (age_days + 1)^(-d)"]    end
    subgraph BudgetPacker ["Budget Allocation, Inhibitory Hoisting & Sutra Packing"]        BaseLevel --> Novelty["Novelty Gate: Drop duplicates (cosine >= 0.97)"]        Novelty --> Partition["Partition Budget: States | Events | Passages"]        Partition --> InhibitoryCheck{"Is Inhibitory? (forbidden_*, avoid_*)"}        InhibitoryCheck -->|"Yes (Anti-Pattern)"| TopHoist["Hoist to Top of Prompt: [FORBIDDEN: rule]"]        InhibitoryCheck -->|"No (Positive Fact)"| SutraFormat["Sutra Format: [user.attr: val] (-45% tokens)"]        TopHoist --> DynamicFraming["Inject Dynamic Negative Framing Semantics"]        SutraFormat --> DynamicFraming        DynamicFraming --> MemoryBlock["Construct Prioritized System Memory Block"]    end
    MemoryBlock -->|"3. Injected Prompt"| Upstream["Local LLM (Ollama / llama.cpp / vLLM)"]    Upstream -->|"4. Streaming Response"| Proxy    Proxy -->|"5. Return to User / Agent"| User    Proxy -.->|"6. Async Non-Blocking Append"| EpisodicLog[("SQLite Append-Only Episodes")]

2. Background Sleep Consolidation & Defeasible Epistemic Logic

mermaid
flowchart TD    EpisodicLog[("Pending SQLite Episodes")] -->|"Idle (120s) or Batch Threshold"| Batcher["Episode Batcher (Line IDs [s1, s2, ...])"]    Batcher --> SleepLLM["Local Sleep Model (Qwen2.5-3B / Llama-3.2-3B)"]    SleepLLM -->|"Constrained JSON Schema Output"| RawExtraction["Raw States & Events with Line Citations"]
    subgraph DeterministicVerification ["Deterministic Neuro-Symbolic Verification"]        RawExtraction --> V1["Line Citation Check (Cited sentence exists?)"]        V1 --> V2["Grounding Engine (Value matches / paraphrases line?)"]        V2 --> V3["Pronoun & Anaphora Resolution (Anuvṛtti tracking)"]        V3 --> V4["Calendar & Timezone Anchoring (clock.py)"]    end
    subgraph InhibitoryAndDefeasibleGate ["Inhibitory & Defeasible Logic Gate"]        V4 --> ProhibCheck{"Declared Prohibited? (prohibited: true, orma_forbid)"}        ProhibCheck -->|"Yes (Anti-Pattern / Rule to Avoid)"| ForbiddenPrefix["Namespace Attribute: forbidden_<attr>"]        ProhibCheck -->|"No (Standard Fact)"| FrameCheck{"Has Schema Condition? (item.condition non-empty)"}        FrameCheck -->|"No (Categorical Fact)"| Categorical["Supersedes Contradictory Prior State"]        Categorical --> CloseOld["Mark Old State: active = 0, superseded_by_id = new_id"]        FrameCheck -->|"Yes (Defeasible Exception)"| Defeasible["Preserve Baseline Truth + Record Conditional Override"]    end
    CloseOld --> Store[("SQLite State Store & Entity Adjacency Graph")]    Defeasible --> Store    ForbiddenPrefix --> Store

Installation

bash
pip install orma-ai

Or install from source for development:

bash
git clone https://github.com/wizardwithcodehazard/orma.gitcd ormapip install -e ".[dev]"python -m pytest -q  # 213 tests pass locally

Usage Option 1: Python SDK (Direct In-Code Integration)

Use the Python SDK to embed Orma directly into your agents, pipelines, or web applications:

python
from orma import Memory
# 1. Initialize memory (defaults to ~/.orma/memory.db)mem = Memory(    upstream="http://localhost:11434/v1",  # Ollama or llama.cpp endpoint    model="llama3.2:3b"                     # Model for background sleep consolidation)
# 2. Add memories, documents, or ongoing chat turnsmem.add("I work as a backend engineer and I live in Pune.")mem.add_file("project_notes.md")
# Record chat interactionsmem.observe(role="user", text="I moved from Pune to Bangalore last week.")mem.observe(role="assistant", text="Congratulations on the move to Bangalore!")
# 3. Retrieve formatted context for prompt injectionmessages = [{"role": "user", "content": "Where do I currently live?"}]prompt_messages = mem.build_context(messages)# prompt_messages contains a system prompt with current facts, outdated facts marked, and relevant quotes!
# 4. Search memory directlyresults = mem.search("Where is my home?")for state in results.states:    print(state.text)  # "user · home city: Bangalore"
# 5. Background consolidation (extracts facts and closes outdated ones)report = mem.sleep()print(report)
mem.close()

Usage Option 2: Zero-Code Proxy (OpenAI SDK, LangChain, Cursor, Open WebUI)

Start Orma as a local proxy:

bash
# With Ollamaorma proxy --model llama3.2:3b
# Or with llama.cpporma proxy --upstream http://127.0.0.1:9931 --model "Qwen/Qwen2.5-3B-Instruct-GGUF:Q4_K_M"

Then point any client to http://localhost:8080/v1:

With the Official OpenAI Python Client:

python
from openai import OpenAI
client = OpenAI(    base_url="http://localhost:8080/v1",    api_key="none")
response = client.chat.completions.create(    model="llama3.2:3b",    messages=[{"role": "user", "content": "What is my job and where do I live?"}])print(response.choices[0].message.content)

With LangChain:

python
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(    base_url="http://localhost:8080/v1",    api_key="none",    model="llama3.2:3b")

With Open WebUI, AnythingLLM, or Cursor:

  • Set OpenAI Base URL to: http://localhost:8080/v1
  • Set API Key to: none

Usage Option 3: One-Command Web UI (orma up)

If you are using llama.cpp or Ollama with a browser web UI, run:

bash
orma up --upstream http://127.0.0.1:9931 --model "Qwen/Qwen2.5-3B-Instruct-GGUF:Q4_K_M"

This immediately:

  1. Starts the Orma memory proxy on port 8080.
  2. Automatically opens your default web browser to http://127.0.0.1:8080/#/.
  3. Passes through the web UI frontend while transparently routing all chat completions through Orma's memory layer.

Usage Option 4: Model Context Protocol (MCP) Server for Coding Assistants

Orma natively speaks the Model Context Protocol (MCP) over standard stdio. This gives coding agents (Claude Code, Cursor, Antigravity IDE, Windsurf, Roo Code, Hermes) persistent, zero-latency memory across editing sessions without session amnesia.

mermaid
flowchart LR    subgraph Clients ["AI Coding Assistants & IDEs"]        ClaudeCode["Claude Code"]        Cursor["Cursor IDE"]        Windsurf["Windsurf"]        Antigravity["Antigravity / Roo / Hermes"]    end
    subgraph Transport ["Standard stdio JSON-RPC 2.0"]        RPC["JSON-RPC Channel (orma mcp)"]    end
    subgraph MCPServer ["Orma MCP Server Layer"]        RecallTool["orma_recall"]        RememberTool["orma_remember"]        ForbidTool["orma_forbid"]        FactsTool["orma_facts"]        ForgetTool["orma_forget"]    end
    subgraph OrmaEngine ["Orma Local Cognitive Engine"]        Hybrid["Hybrid BM25 + sqlite-vec Search"]        InhibitoryEngine["Inhibitory Hoisting & Sutra Packing"]        SleepDaemon["Background Sleep Consolidation Worker"]        DB[("Embedded SQLite: ~/.orma/memory.db")]    end
    Clients <-->|"stdio"| RPC    RPC --> MCPServer    MCPServer <--> OrmaEngine    OrmaEngine <--> DB

In Claude Code:

bash
claude mcp add orma -- orma mcp

In Cursor (.cursor/mcp.json or Settings > MCP):

json
{  "mcpServers": {    "orma": {      "command": "orma",      "args": ["mcp"]    }  }}

In Windsurf / Antigravity IDE / Roo Code (mcp.json):

json
{  "mcpServers": {    "orma": {      "command": "orma",      "args": ["mcp"]    }  }}

One-Click Install via Smithery.ai:

bash
npx -y @smithery/cli install orma-ai --client cursor

Tools Exposed to Agents:

  • orma_recall(query, space): Returns token-budgeted, Sutra-packed active facts, anti-patterns, and past decisions (< 20ms).
  • orma_remember(text, kind, role, space): Permanently records a project decision, architecture rule, or user constraint. Set kind="anti_pattern" to mark a forbidden mistake to avoid.
  • orma_forbid(rule, space): Directly registers a hard anti-pattern or prohibited behavior (e.g., "Never chain PowerShell commands with semicolons").
  • orma_facts(space, include_history): Inspects all active canonical truths without running a search.
  • orma_forget(state_id, space): Closes an obsolete or superseded constraint.

Inhibitory Control & Anti-Pattern Prevention (Negative Memory)

A pervasive failure mode in AI coding assistants and small LLMs is forbidden mistake recurrence: when a user says "Stop using semicolons to chain terminal commands in PowerShell", standard autoregressive models place high attention weight on the word semicolon and continue repeating the exact same error.

mermaid
flowchart TD    subgraph Problem ["Traditional LLM Attention Failure"]        UserWarning["User: 'Never use semicolon to chain commands in PowerShell'"] --> StandardLLM["Standard LLM Attention Mechanism"]        StandardLLM --> AttentionBias["Attention Activates on Forbidden Token: 'semicolon'"]        AttentionBias --> RecurrenceError["Forbidden Mistake Repeated: git add . ; git commit"]    end
    subgraph Solution ["Orma Inhibitory Control Architecture"]        ForbidRule["Inhibitory Rule: orma_forbid / sleep extraction"] --> SchemaAttr["Schema Attribution (prohibited: true)"]        SchemaAttr --> NamespaceAttr["Attribute Namespacing (forbidden_powershell_chain)"]        NamespaceAttr --> HoistTop["Top-of-Prompt Hoisting: [FORBIDDEN: never use semicolon]"]        HoistTop --> DynamicFraming["Dynamic Negative Framing Semantics"]        DynamicFraming --> CleanOutput["Strict Negative Compliance: git add . \n git commit"]    end

Orma introduces Inhibitory Control:

  1. Schema-Level Attribution: Negative rules are identified during sleep extraction with prohibited: true or directly registered via orma_forbid(rule).
  2. Sutra Inhibitory Hoisting: Prohibited states are rendered as [FORBIDDEN: <rule>] and hoisted to the very top of the system prompt (above all positive facts and conversation history).
  3. Dynamic Negative Framing: Orma dynamically injects explicit negative constraint semantics into the system prompt whenever anti-patterns are present:
    text
    ## Memory... Lines marked [FORBIDDEN: ...] or under Forbidden are strict negative constraints: you must NEVER suggest, mention, or take what is forbidden.[FORBIDDEN: chaining terminal commands using semicolons or commas][user.editor: neovim]
  4. Universal Applicability: Works identically for developer pain points (terminal syntax, forbidden dependencies, deprecated API calls) and personal constraints (severe allergies, tone boundaries, forbidden buzzwords).

Multi-User & Multi-Tenant Isolation

Orma supports isolated memory spaces out of the box so multiple users or agent sessions don't contaminate each other's memories:

  • In Python SDK:
    python
    mem.add("Alice likes green tea.", space="user_alice")context = mem.build_context(messages, space="user_alice")
  • In HTTP Requests / Proxies: Pass the x-orma-space header or "user" field:
    bash
    curl http://localhost:8080/v1/chat/completions \  -H "x-orma-space: user_123" \  -H "Content-Type: application/json" \  -d '{"messages": [{"role": "user", "content": "Who am I?"}]}'

CLI Reference

Orma provides a command-line tool for managing your memory:

bash
# Add a note or documentorma add "My dentist is Dr. Rao in Kothrud."orma add docs/handbook.md
# Search memoryorma search "dentist"
# Inspect active facts and outdated historyorma facts --history
# Preview the exact prompt block that would be injectedorma recall "Who is my dentist?"
# Manually trigger sleep consolidationorma sleep --model llama3.2:3b
# Forget a specific factorma forget 12
# Database statisticsorma stats
# Run as an MCP server for Claude Code / Cursor / Windsurforma mcp

Memory Prompt Output Format (Sutra Dense Packing)

When Orma recalls memories, it packs them into an unambiguous, high-density symbolic bracket representation (saving 35–45% context tokens over conversational prose):

markdown
## MemoryWhat you remember about the person you are talking to, from earlier conversations, notes and documents. Answer directly using these facts and statements without asking the user to re-confirm details already provided here; do not mention this list. A line marked [outdated] was true when it was said and has changed since. Today is 2026-11-01.
[user.home city: Bangalore (since 2026-10-17)][user.morning drink: black coffee][user.morning drink | cond: sore throat -> warm ginger tea with raw honey][user.role: systems engineer @ Zerodha][EVENT: 2026-11-01: user received a gift from manager: Swiss knife][LOG: 2026-10-10 user: I'm Sahil and I live in Pune. [outdated: now Bangalore]]

(Note: Can be toggled back to classic natural language section blocks via enable_sutra_packing = False)


Cognitive & Mathematical Architecture

Orma integrates established principles from cognitive science, stochastic point processes, and non-monotonic logic directly into its zero-latency retrieval engine:

+---------------------------------------------------------------------------------------------------+|                                 ORMA COGNITIVE RETRIEVAL PIPELINE                                 |+------------------------------------+--------------------------------------------------------------+| Hybrid Search (BM25 + sqlite-vec)  | Multi-channel fusion calibrated against dynamic noise floor  || Spreading Activation (ACT-R)       | Associative entity graph traversal with Fan Effect damping   || Hawkes Temporal Burst Process      | Self-exciting exponential kernel for conversational momentum || Ebbinghaus Retention & Stability   | Dynamic stability scaling per spaced repetition & rehearsal  || Defeasible Epistemic Logic         | Conditional exception handling preventing false overwrites   || Sutra Context Packing              | Dense declarative bracket encoding saving 35-45% tokens      |+------------------------------------+--------------------------------------------------------------+

1. Hawkes Self-Exciting Temporal Process (enable_hawkes)

Cognitive Rationale: Human dialogues exhibit natural clustering and temporal burstiness (Hawkes 1971, Kleinberg 2002). When a user brings up a topic (e.g., an ongoing project or medical symptom), subsequent exchanges revolve around that cluster. Standard recency decay either forgets past topics too fast or keeps them active too long.

Mathematical Formulation:

Intensity(t) = alpha * exp(-beta * dt)beta = ln(2) / half_life_seconds
  • Burst Amplitude (alpha = 0.4): Boosts items accessed in active conversational bursts.
  • Decay Constant (beta = ln(2) / 1800): A 30-minute half-life ensures topics discussed earlier in a session maintain strong conversational momentum without lingering indefinitely into future days.
  • Bounded Ranking: Implemented in orma/recall/rank.py as a bounded additive boost so temporal bursts never override exact factual matches.

2. Ebbinghaus Spaced Repetition Stability (enable_ebbinghaus)

Cognitive Rationale: The human forgetting curve (Ebbinghaus 1885, Cepeda et al. 2008) demonstrates that memory retention decays exponentially, but each spaced retrieval increases the memory's underlying stability (half-life). A fact stated once in passing should gracefully fade, whereas a fact confirmed across 4 different days should remain permanently accessible.

Mathematical Formulation:

Retention R(dt) = exp(-dt / S)Stability S(n)  = S0 * (1 + gain * (n - 1))
  • Baseline Stability (S0 = 2.0 days): Initial stability for a single mention.
  • Rehearsal Gain (gain = 0.5): For every subsequent citation or spaced rehearsal n, memory stability expands linearly, lengthening the half-life before decay.
  • Dual Protection: Single-pass noise drops out of recall candidate pools, while repeated preferences resist decay for months.

3. ACT-R Spreading Activation & Anderson's Fan Effect (enable_spreading_activation)

Cognitive Rationale: Human memory recalls information associatively (Anderson 1983). When asked "Where should I go for my toothache?", the query may not contain the doctor's name, but the concept of toothache is associatively linked to dentist and Dr. Rao. Traditional graph databases (e.g. Neo4j) add 50–150ms of network overhead. Orma executes associative graph traversal directly within SQLite using indexed adjacency tables.

Mathematical Formulation:

Activation A_i = B_i + sum_j (W_j * S_ji)Association S_ji = Base_Weight / Fan(Entity_j)
  • Source Seed Extraction: Seed entities are identified from hybrid text matches and active states.
  • The Fan Effect: John R. Anderson's Fan Effect proves that associative activation spreading from a concept is inversely proportional to the number of facts associated with it:
    • A specific entity (e.g., "Dr. Rao" with Fan = 2) channels 50% of its associative energy directly to the target clinic state.
    • A general hub (e.g., "Pune" with Fan = 60) dissipates its energy across dozens of states, preventing generic concepts from hijacking the recall budget.

4. Defeasible Epistemic Logic (enable_defeasible_logic)

Cognitive Rationale: Real-world beliefs are non-monotonic. When a user states:

"I drink black coffee every morning." followed later by: "When I have a sore throat, I drink ginger tea with honey."

Naive memory systems (like Mem0 or basic graph extraction) detect a contradiction on the entity-attribute (user, drink) and destructively overwrite the baseline habit.

Epistemic Rule Engine:

  • Orma inspects assertions via schema attribution (item.condition extracted by the model during sleep) rather than brittle keyword matching.
  • Categorical Assertions (condition: "" e.g., "I moved to Bangalore"): Trigger state supersession (active = 0, superseded_by_id = new_state_id).
  • Defeasible Overrides (condition: "sore throat" e.g., "When sick, drink tea"): Registered as conditional exceptions without closing or corrupting the baseline categorical truth. Both facts are preserved in context.

5. Adaptive Noise Floor Calibration & Reciprocal Rank Fusion

Algorithmic Rationale: Small embedding models (e.g., 384-dimensional bge-small-en-v1.5) suffer from geometric concentration on high-dimensional unit hyperspheres—unrelated sentences frequently score 0.45–0.55 cosine similarity by pure random chance.

  • Noise Floor Estimation: Orma dynamically samples pairwise distances to compute the 50th-percentile noise floor of the embedding space.
  • Similarity Floor Truncation: Scores below the space noise floor carry zero evidential weight.
  • Reciprocal Rank Fusion (RRF):
    RRF Score = (1 / (60 + Rank_BM25)) + (1 / (60 + Rank_Vector))
    Fuses exact keyword recall (FTS5 BM25) with semantic vector search (sqlite-vec) with zero hyperparameter tuning.

6. Sutra Context Encoding (enable_sutra_packing)

Cognitive & LLM Rationale: Small 3B models are heavily trained on code and structured JSON. Natural language narrative memory blocks ("Now true:", "Things said before:") waste precious context budget on formatting boilerplate and can cause models to ask redundant clarifying questions.

  • Dense Declarative Syntax: Packs states, conditions, events, and outdated lineages into atomic bracketed forms ([user.attribute: value (metadata)]).
  • Token Savings: Reduces prompt memory overhead by 35% to 45%, providing faster generation speeds and more room for user instructions.
  • Zero Syntax Bleed: Formatted to ensure instruction-tuned models absorb the knowledge as background system facts without outputting brackets to the user.

7. Inhibitory Control & Attention Hoisting

Cognitive & Neuro-Symbolic Rationale: In human cognitive neuroscience, executive inhibitory control (prefrontal cortex) suppresses prepotent motor or verbal impulses. In autoregressive Transformers, negative phrasing ("do not use X") paradoxically increases the probability of generating X because token attention activates on the semantic representations of the mentioned words.

  • Hoisting Precedence: Rather than interweaving negative rules inside narrative facts, Orma isolates negative boundaries into [FORBIDDEN: <rule>] tokens and places them at the very beginning of the system prompt.
  • Instruction-Tuning Alignment: Modern instruction-tuned models (e.g. Qwen 2.5, Llama 3.2, Claude 3.5) treat top-level boundaries as hard system constraints when defined prior to task context.
  • Dual Channel Registration:
    • Declarative Extraction: Asynchronous sleep maps "never use semicolon in terminal" to prohibited = True and namespaced attribute forbidden_<name>.
    • Immediate MCP Tool: Coding assistants directly call orma_forbid(rule) to establish an instant guardrail without waiting for background consolidation.

Storage & Data Durability (100% Local & Persistent)

  • Single File SQLite Storage: All memories reside in ~/.orma/memory.db with Write-Ahead Logging (WAL) enabled.
  • Survives Restarts & Power Cycles: You can shut down orma up, restart your machine, or close your terminal at any time; your complete memory state, episodic history, and consolidated facts remain permanently stored.
  • Lossless Append-Only: Episodes are never destructively overwritten or pruned by hallucinating models. You can inspect or re-consolidate your history anytime with orma facts --history.

Configuration & Ablation Switches

Every mechanism in Orma can be independently configured or ablated in orma/config.py or passed via OrmaConfig:

ParameterDefaultDescription
enable_semanticTrueBackground consolidation into states & events (off = pure episodic sentence search baseline)
enable_novelty_gateTrueDrops duplicate sentences (cosine similarity >= 0.97)
enable_similarity_weightingTrueCalibrates vector similarity against adaptive space noise floor
enable_base_levelTrueACT-R recency and frequency power-law decay
enable_hawkesTrueHawkes self-exciting temporal process for conversational bursts
enable_ebbinghausTrueEbbinghaus spaced repetition stability scaling
enable_spreading_activationTrueAssociative spreading activation with Fan Effect
enable_defeasible_logicTrueNon-monotonic conditional exception protection
enable_sutra_packingFalseDense declarative bracket encoding (-40% token usage; default False, toggle to True)
budget_tokens4096Token budget ceiling for injected memory blocks
search_k30Top-k candidates pulled per hybrid search channel
rrf_k60Reciprocal Rank Fusion constant for combining BM25 and vector scores

License

Distributed under the Apache-2.0 License. See LICENSE for more information.

来源:README.md,提交 1583d04

工具

0
SourceWeft 曾在隔离沙箱中以无凭据方式启动该软件包一次,以列出其工具,但未能完成:该软件包类型无法在沙箱中运行。

版本历史

1
  1. v0.1.13最新Nov 1, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分

其他 Memory 集成