MoonBit-memory

MoonBit-memory - a local agent self-evolving memory system, ported from Python to MoonBit.

memory
agent
self-evolution
moonbit
moon add Across2005/MoonBit-memory@0.1.1
Download zip
Version
0.1.1
License
MIT
Last updated
last month
Downloads
13

Dependencies

README

#MoonBit-memory · 本地 Agent 自进化记忆系统


#概况

本项目是 OpenClaw Memory (Python)MoonBit 语言完整转译,已重命名为 MoonBit-memory。它将原型的 7 大模块、三级存储、自进化算法用 MoonBit 重新实现,编译为原生二进制,执行效率更高、资源占用更低,适合嵌入 Agent 守护进程或边缘设备。

MoonBit 是由中国团队开发的云与边缘端编程语言,支持 native / wasm-gc / js 多后端编译,具备快速、简洁、AI 原生的特性。


#功能

操作说明
remember写入记忆:校验 → 分类 → 去重 → 矛盾检测 → 持久化
recall检索记忆:分级调动,按 相似度 × 优先级 × 时效 排序返回 Top-K
evolve自进化:重算优先级,久未访问且低价值者标记 deprecated
stats分类统计与内存总量
list转储全部记忆条目


#编译 & 运行

# 构建 moon build --target wasm-gc # 无需 C 编译器,可浏览器运行 moon build --target native # 需要 MSVC/gcc/clang,原生性能 # CLI moon run cmd/main --target wasm-gc -- remember "用户偏好中文技术文档" --type preference moon run cmd/main --target wasm-gc -- recall "术语怎么处理" moon run cmd/main --target wasm-gc -- evolve moon run cmd/main --target wasm-gc -- stats moon run cmd/main --target wasm-gc -- list # 启用加密 moon run cmd/main --target wasm-gc -- remember "敏感内容" --passphrase secret # 运行测试(6 项,全部通过) moon test --target wasm-gc

Windows native 构建需安装 MSVC(Visual Studio Build Tools)。无 C 编译器时可用 --target wasm-gc 替代。


#项目结构

MoonBit-memory/ ├── models.mbt # 数据模型:MemoryType / MemoryStatus / MemoryEntry ├── similarity.mbt # 文本相似度:tokenize / embed / cosine(零依赖) ├── modules.mbt # 核心算法:分类 / 去重 / 矛盾检测 / 自进化 / 检索 ├── storage.mbt # 三级存储:meta_index + 分类目录 + 条目文件(Ref 共享状态) ├── crypto.mbt # 可选 XOR 加密(与 Python 行为一致) ├── system.mbt # MemorySystem 门面:remember / recall / evolve / stats ├── system_test.mbt # 6 项测试(对应 Python test_system.py) ├── cmd/main/ # CLI 入口(兼容 Python cli.py 的参数约定) │ ├── main.mbt │ └── moon.pkg ├── moon.mod # 模块元信息 └── moon.pkg # 包依赖声明


#与 Python 原型的差异

维度Python 原型MoonBit 版
运行方式解释执行(CPython)编译为原生二进制 / wasm
依赖Python 3.10+ 标准库零外部依赖(仅 moonbitlang/x)
ID 生成uuid4().hex[:12]时间戳 + 单调计数器
时间戳ISO-8601 字符串epoch 毫秒(Int64)
共享状态可变对象引用@ref.Ref[Map[...]] 细胞引用
JSON 序列化json.dumps / json.loadsto_json().stringify() / @json.parse + from_json
文件 I/Oopen() / os 模块@fs.read_file_to_string / write_string_to_file
加密cryptography.Fernet / XOR 回退XOR 码点运算(与 Python 回退行为一致)


#模块映射

文件对应 Python职责
models.mbtmodels.pyMemoryType, MemoryStatus, MemoryEntry 数据模型
similarity.mbtsimilarity.py分词 → TF 向量 → 余弦相似度
crypto.mbtcrypto.py可选本地加密(XOR 码点)
storage.mbtstorage.py三级 JSON 存储(Ref 共享状态)
modules.mbtmodules.py分类 / 去重 / 矛盾检测 / 自进化 / 分级检索
system.mbtsystem.pyMemorySystem 门面
cmd/main/main.mbtcli.py / __main__.py命令行接口


#设计继承

  • 三级存储meta_index.json(全局索引)→ 分类目录(<type>/)→ 条目文件(<id>.json
  • 自进化公式priority = 0.5·freq_norm + 0.3·recency + 0.2·feedback(仅当有反馈时)
  • 安全三件套:本地加密、指令授权、防注入(记忆仅作数据召回,不当作指令执行)
  • 6 项测试:写入 / 检索 / 去重 / 分类 / 冲突检测 / 自进化 / 加密落盘,全部通过


#License

MIT © 2026 Across2005

#
CryptoProvider

pub struct CryptoProvider {
enabled : Bool
passphrase : String
} derive(
Debug
)

Optional local encryption provider.

#
CryptoProvider::decrypt

fn CryptoProvider::decrypt(self : CryptoProvider, data : String) -> String

Decrypt (XOR obfuscate) a string.

#
CryptoProvider::disabled

fn CryptoProvider::disabled() -> CryptoProvider

Disabled provider: data is stored as-is.

#
CryptoProvider::encrypt

fn CryptoProvider::encrypt(self : CryptoProvider, data : String) -> String

Encrypt (XOR obfuscate) a string.

#
CryptoProvider::new

fn CryptoProvider::new(passphrase : String) -> CryptoProvider

Enabled provider keyed by passphrase.

#
MemoryEntry

pub struct MemoryEntry {
id : String
mtype : String
content : String
confidence : Double
source : String
timestamp : Int64
access_count : Int
priority : Double
status : String
last_accessed : Int64
feedback_score : Double
tags : Array[String]
} derive(
Debug
)

A single memory entry. Mirrors Python MemoryEntry.

Field mtype maps to JSON key "type" (the word type is a MoonBit keyword, so the struct field is named mtype and serialization renames it).

#
MemoryEntry::create

fn MemoryEntry::create(content : String, mtype : MemoryType, source? : String, confidence? : Double, tags? : Array[String]) -> MemoryEntry

Create a new entry (mirrors MemoryEntry.create).

#
MemoryEntry::from_json

fn MemoryEntry::from_json(j : Json) -> MemoryEntry?

Parse an entry from a JSON value. Returns None on malformed input.

#
MemoryEntry::to_json

fn MemoryEntry::to_json(self : MemoryEntry) -> Json

Serialize an entry to a JSON value (key "type" is emitted for mtype).

#
MemoryStatus

pub enum MemoryStatus {
Active
Deprecated
Archived
} derive(Eq,
Debug
)

Memory lifecycle status. Mirrors Python MemoryStatus(str, Enum).

#
MemoryStatus::from_str

fn MemoryStatus::from_str(s : String) -> MemoryStatus

#
MemoryStatus::value

fn MemoryStatus::value(self : MemoryStatus) -> String

#
MemorySystem

pub struct MemorySystem {
storage : Storage
}

The memory system facade. Holds a Storage; because Storage keeps its index in a Ref cell, copying the facade still shares the same store.

#
MemorySystem::age_entry

fn MemorySystem::age_entry(self : MemorySystem, id : String, last_accessed : Int64, access_count : Int) -> Bool raise
IOError

Maintenance helper: rewind an entry's access clock so self-evolution's deprecation path can be exercised deterministically by tests. Returns true if the entry existed and was updated.

#
MemorySystem::entry_path

fn MemorySystem::entry_path(self : MemorySystem, id : String) -> String?

Return the on-disk JSON file path for an entry, or None if absent. Exposed so storage can be inspected (e.g. by encryption-roundtrip tests).

#
MemorySystem::evolve

Run self-evolution over the store.

#
MemorySystem::list_all

fn MemorySystem::list_all(self : MemorySystem) -> Array[Json]

List all entries as JSON.

#
MemorySystem::new

fn MemorySystem::new(root : String, passphrase? : String) -> MemorySystem

Open a memory system rooted at root, optionally encrypted by passphrase.

#
MemorySystem::recall

fn MemorySystem::recall(self : MemorySystem, query : String, top_k? : Int) -> Array[Json] raise
IOError

Retrieve memories ranked by similarity x priority x recency; updates stats.

#
MemorySystem::remember

fn MemorySystem::remember(self : MemorySystem, content : String, type_hint? : String, source? : String, interactive? : Bool, conflict_policy? : String) -> Map[String, Json] raise
IOError

Write a memory: validate -> classify -> dedup -> conflict -> store.

#
MemorySystem::stats

fn MemorySystem::stats(self : MemorySystem) -> Map[String, Json]

Aggregate statistics.

#
MemoryType

pub enum MemoryType {
CommonSense
Instruction
Preference
Fact
Other
} derive(Eq,
Debug
)

Memory categories. Mirrors Python MemoryType(str, Enum).

#
MemoryType::from_str

fn MemoryType::from_str(s : String) -> MemoryType

#
MemoryType::value

fn MemoryType::value(self : MemoryType) -> String

#
Storage

pub struct Storage {
root : String
crypto : CryptoProvider
index_path : String
entries :
Ref
[Map[String, MemoryEntry]]
}

Three-tier JSON-backed memory store.

#
Storage::all_entries

fn Storage::all_entries(self : Storage) -> Array[MemoryEntry]

All entries.

#
Storage::delete

fn Storage::delete(self : Storage, entry_id : String) -> Bool raise
IOError

Delete an entry by id. Returns true if something was removed.

#
Storage::get

fn Storage::get(self : Storage, entry_id : String) -> MemoryEntry?

Fetch an entry by id (from the in-memory index).

#
Storage::new

fn Storage::new(root : String, crypto? : CryptoProvider) -> Storage

Open (or create) a store rooted at root.

#
Storage::put

fn Storage::put(self : Storage, entry : MemoryEntry) -> Unit raise
IOError

Persist an entry (file + index).

#
Storage::query_by_type

fn Storage::query_by_type(self : Storage, mtype : MemoryType) -> Array[MemoryEntry]

Entries of a given type.

#
Storage::stats

fn Storage::stats(self : Storage) -> Map[String, Json]

Aggregate statistics (mirrors Python Storage.stats).

#
all_types

fn all_types() -> Array[MemoryType]

All memory types, used for storage directory layout and index categories.

#
classify

fn classify(content : String) -> MemoryType

Classify content into a memory type by keyword scoring.

#
cosine

fn cosine(a : Map[String, Int], b : Map[String, Int]) -> Double

Cosine similarity between two token-count maps.

#
detect_conflict

fn detect_conflict(new_entry : MemoryEntry, candidates : Array[MemoryEntry], threshold? : Double) -> Array[MemoryEntry]

Detect conflicting entries (similar + opposite polarity).

#
embed

fn embed(text : String) -> Map[String, Int]

Bag-of-tokens embedding: token -> count.

#
evolve

fn evolve(storage : Storage, now? : Int64, deprecate_below? : Double, deprecate_age? : Double) -> Map[String, Json] raise
IOError

Self-evolution: recompute priorities and deprecate stale low-value entries.

#
find_duplicate

fn find_duplicate(content : String, candidates : Array[MemoryEntry], threshold? : Double) -> MemoryEntry?

Find the most similar existing entry above threshold (duplicate check).

#
graded_retrieval

fn graded_retrieval(storage : Storage, query : String, top_k? : Int, now? : Int64) -> Array[(MemoryEntry, Double)]

Graded retrieval: rank active entries by similarity x priority x recency.

#
now_ms

fn now_ms() -> Int64

Current time in epoch milliseconds (UTC).

#
obj

fn obj(pairs : Array[(String, Json)]) -> Map[String, Json]

Build a JSON object from key/value pairs.

#
recompute_priority

fn recompute_priority(entry : MemoryEntry, now : Int64, w? : (Double, Double, Double), half_life? : Double) -> Double

Recompute an entry's priority score.

#
similarity

fn similarity(text_a : String, text_b : String) -> Double

End-to-end similarity between two raw text strings.

#
tokenize

fn tokenize(text : String) -> Array[String]

Tokenize: lowercase, split latin/alphanumeric runs, keep each CJK char.

#
validate_input

fn validate_input(content : String) -> (Bool, String)

Validate raw input (mirrors validate_input).