LoomDB: a local shared task-memory box for agents, written in MoonBit.
本地优先 · 事件溯源 · 确定性强
# 安装 MoonBit
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
# 编译 & 跑测试
git clone <repo-url> moonbitLoomDB && cd moonbitLoomDB
moon test -p loomdb # 281 单元测试全过
bash scripts/build_wasm.sh # → dist/loomdb.wasm
bash scripts/build_bridge.sh # → dist/loombox-bridge
python3 scripts/platform_smoke.py # CLI + Python SDK 端到端
python3 scripts/multi_agent_demo.py # 3 场景 23 断言(跨 taskId merge + fork 幂等)
python3 scripts/two_agent_test.py # 两个 Agent 并发操作(9 断言 · pytest 友好)
python3 scripts/benchmark.py # 性能 benchmark(200 facts · 12-57× 提升)
bash scripts/loombridge.sh start # 后台 daemon 化 bridge(可选,Python SDK 已内置 persistent)
# CLI 速览
python3 platform/cli/loombox.py create issue-42
python3 platform/cli/loombox.py fact issue-42 repo tool pnpm
python3 platform/cli/loombox.py observe issue-42 pytest passed "64/64 ok"
python3 platform/cli/loombox.py context issue-42 # 取上下文包
python3 platform/cli/loombox.py why issue-42 repo # 问来由
python3 platform/cli/loombox.py next issue-42 # 看下一步动作
python3 platform/cli/loombox.py check issue-42 # CI 检查(有矛盾则退出码非零)┌─────────────────────────────────────────────────────────────┐
│ Platform Layer │
│ ┌──────────┐ ┌───────┐ ┌────┐ ┌────┐ ┌──────┐ ┌───────┐ │
│ │ JS/TS SDK │ │ CLI │ │MCP │ │ CI │ │ Git │ │ IndexedDB│ │
│ └────┬─────┘ └───┬───┘ └─┬──┘ └─┬──┘ └──┬───┘ └───┬───┘ │
│ │ │ │ │ │ │ │
│ ┌────▼───────────▼───────▼──────▼────────▼─────────▼───┐ │
│ │ MoonBit Core │ │
│ │ ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌────────┐ │ │
│ │ │ 事件模型 │ │ 状态归约 │ │ 合并 / │ │ 检索 / │ │ │
│ │ │ Lamport │ │stateHash │ │ CRDT │ │ 安全 │ │ │
│ │ └─────────┘ └──────────┘ └──────────┘ └────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
│ 一份源码 · 编译为 Native / Wasm / JS │
└─────────────────────────────────────────────────────────────┘| 层 | 说明 |
|---|---|
| 事件模型 | 每类写入生成确定性事件:FactSet、TaskFieldSet、DecisionAdded、ObservationAdded、ArtifactAdded 等。事件含 id/type/actor/lamport/payload/refs。 |
| 状态归约 | stateHash = sha256(replay(events))——相同事件序列必然得到相同哈希。LWW 冲突裁决按 Lamport 时钟。 |
| 合并 / CRDT | 版本向量 + 三路合并 + 可插拔策略(LWW / OR-Set / Counter)。merge(A, B) 后双方哈希一致。跨 taskId 合并:fork-base-fork 场景下,merge(a_task, b_task) 自动把 B 事件里的 task kind(TaskFieldSet / ObservationAdded / DependencyAdded / DependencyRemoved / PolicySet(scope))rewrite 归 A 的 task_id,fact/decision/artifact 零副作用。核心函数 rewrite_event_for_task,在 import / merge_to_box / merge_three_way 三层统一生效。 |
| 检索 / 安全 | 全文 / 字段 / 聚合 / 分页 / 流式 / 跨任务 / 递归规则 / 确定性向量检索;盒子级 + 字段级权限;敏感字段脱敏;完整性校验。 |
import { LoomBox } from "./bindings/loomdb-sdk.mjs";
const box = LoomBox.create("issue-42", { agent: "planner" });
box.fact("repo", "tool", "pnpm"); // 写事实
box.observe("pytest", "fail", "64/64 ok"); // 记观测
box.decide("build tool?", "pnpm", "fast install"); // 记决策
box.artifact("lockfile", "pnpm-lock.yaml", "sha256:abc"); // 记产物
box.context(); // 上下文包(状态 / 事实 / 决策 / 观测 / 产物)
box.why("repo#tool");// 问来由 → 依赖链
box.next(); // 下一步动作
box.health(); // 健康度(矛盾事实 / 过期决策 / 未关联观测)
box.check(); // CI 检查(有矛盾则退出码非零)
box.merge(other); // 与另一盒合并(同 taskId → CRDT 收敛;跨 taskId → 自动 rewrite task kind)
box.timeline(); // 事件时间线
box.causal(); // 因果图(DAG,无环、无悬挂边)
box.audit(); // 审计导出 JSON
box.fork("new-task");// fork 自当前盒,所有事件 task kind 自动 rewritebox.fork("new-task") # → 新 LoomBox 实例,自动写 box.json + events.jsonl
box.merge(other) # 自动传 otherTaskId,跨 taskId 时 rewrite task kind| 命令 | 说明 |
|---|---|
| create <task> | 建盒(默认 agent=planner) |
| list | 列出所有盒子 |
| fact <task> <subj> <pred> <obj> [--source] | 写事实 |
| observe <task> <tool> <status> <summary> | 记观测 |
| decide <task> <q> <choice> <rationale> | 记决策 |
| artifact <task> <name> <uri> <hash> | 记产物 |
| set/policy/permission | 任务字段 / 策略 / 权限 |
| events <task> | 原始事件 JSONL |
| context/why/next | 取上下文 / 问来由 / 看下一步 |
| timeline/causal/audit | 时间线 / 因果图 / 审计导出 |
| check <task> | 矛盾检测(退出码非零 = 有问题) |
| merge <taskA> <taskB> | 合并两盒(同 taskId CRDT 收敛 / 跨 taskId 自动 rewrite task kind 归 taskA) |
| MCP Tool | 说明 |
|---|---|
| loombox_context | 取 ContextPack(字段、事实、决策、观测、策略) |
| loombox_next | 当前可执行动作(含目标、依据、优先级) |
| loombox_why | 问来由 → 源头事件依赖链 |
| loombox_check | 盒子健康检查 |
| loombox_list | 列出所有盒子 |
相同事件序列 = 相同状态哈希
stateHash = sha256( canonical( replay( events ) ) )| 层 | 优化 | 作用 |
|---|---|---|
| Python events 缓存 | LoomBox.events() 带 mtime 检测,同文件未变复用内存字符串 | 避免每次读磁盘 + 序列化 |
| Bridge stdin 长驻 | async fn main + @stdio.stdin.text.read_until("\n"),Python 用 Popen 常驻 + stdin/stdout JSON RPC | 消除 subprocess spawn 开销(~15ms/op) |
| Bridge BoxCache + state_hash | 按 task_id 缓存 Box;rebuild() 结束预计算 state_hash 写入 state_hash_cache;invalidate_caches() / incremental_update_caches() 全路径自动失效 | 同一 task_id 读操作零 rebuild |
指标 one-shot persistent 提升
─────────────────────────────────────────────────────────
append 200 facts 3600ms 284ms 12.6×
context() 18ms 0.65ms 27.7×
timeline() 18ms 0.61ms 29.5×
health() 16ms 0.28ms 57×
state_hash() 20ms 1.53ms 13×
causal() 17ms 0.22ms 77×
merge(200+200) 28ms 10.9ms 2.6×python3 scripts/benchmark.py # 跑自己的 benchmarkPython Bridge (LoomBox)
│ subprocess.Popen([bridge.exe]) ← 只 spawn 一次
│ stdin.write(json + "\n") ← 每 op 发一行
│ stdout.readline() ← 收一行响应
│ "exit\n" → 优雅退出
▼
bridge.exe (async fn main + BoxCache)
│ cached_open_box(task_id)
│ ├─ 命中 → 直接返回内存 Box(零 rebuild)
│ └─ 未命中 → import_events_jsonl → rebuild → 缓存
│ reload=true → 强制从 data 重建
▼
LoomDB kernel (Box with state_hash_cache)@stdio.stdin.text.read_until("\n")
→ Some(line) → 处理 JSON → 继续
→ None (EOF) → @async.sleep(1000) → 下一轮重试bash scripts/install_systemd.sh install # 自动检测 MoonBit、编译 bridge、装 service、启动
bash scripts/install_systemd.sh status # 状态
bash scripts/install_systemd.sh logs # tail -f journalctl
bash scripts/install_systemd.sh restart # 重启
bash scripts/install_systemd.sh stop # 停止
bash scripts/install_systemd.sh uninstall # 卸载
# 可选:让登出后继续跑
sudo loginctl enable-linger $USERmkdir -p ~/.config/systemd/user
cp systemd/loombridge.service ~/.config/systemd/user/
sed -i "s|%h|$HOME|g; s|__REPO__|$PWD|g" ~/.config/systemd/user/loombridge.service
systemctl --user daemon-reload
systemctl --user enable --now loombridge
# 管理
systemctl --user status loombridge
systemctl --user restart loombridge
journalctl --user -u loombridge -f # 实时日志loombridge.service: Failed to set up standard output: No such file or directory
loombridge.service: Main process exited, code=exited, status=209/STDOUT
loombridge.service: Scheduled restart job, restart counter is at 9.// None(EOF) 不 break,而是短暂 sleep 后重试
let mut slept_forever = false
while true {
match @stdio.stdin.text.read_until("\n") {
Some(line) => { slept_forever = false; /* 处理 JSON */ }
None => { slept_forever = true } // 不 break
}
if slept_forever {
@async.sleep(1000) // 1s 轮询,零 CPU 开销
slept_forever = false
}
}let mut served_any = false // 是否成功处理过至少一条 request
let max_idle_eof = 5 // 前 5 次 EOF(≈5s)还没收到任何请求就退出
while true {
match @stdio.stdin.text.read_until("\n") {
Some(line) => { served_any = true; /* 处理 JSON */ }
None => {
eof_count = eof_count + 1
// 还没服务过任何 request,且 EOF 次数超阈值 → 没人理它,自己退出
if !served_any && eof_count >= max_idle_eof { break }
// 已服务过 request(systemd / Python persistent 模式)→ 永久 polling
@async.sleep(1000)
}
}
}| 调用场景 | 第一次 EOF | 第二次 EOF | ... | 第 5 次 EOF | 第 6 次 EOF |
|---|---|---|---|---|---|
| 裸调 bridge | served_any=false, eof=1 sleep | eof=2 sleep | ... | eof=5 → break exit 0 | — |
| systemd /dev/null | served_any=false, eof=1 sleep | ... | — | — | 收到 request 后 served_any=true → 永久 polling |
| Python persistent | 不会 EOF(Python 持续写) | — | — | — | — |
● loombridge.service - LoomDB Bridge (async stdin long驻)
Loaded: loaded (.../loombridge.service; enabled; preset: enabled)
Active: active (running) since Tue 2026-12-01 10:29:24 CST; 5min ago
Main PID: 900821 (loombox-bridge)
Tasks: 3 (limit: 24595)
Memory: 416.0K (peak: 920.0K)
CPU: 36ms
CGroup: /user.slice/user-0.slice/user@0.service/app.slice/loombridge.service| 检查项 | 结果 |
|---|---|
| install_systemd.sh install(自动编译 + enable --now) | ✅ |
| systemctl is-active | ✅ active |
| 5+ 分钟稳定运行(RestartCount=0) | ✅ 零 crash |
| Memory(RSS 2756KB / 峰值 920KB) | ✅ 低开销 |
| CPU(5 分钟只消耗 36ms) | ✅ EOF polling 几乎零开销 |
| Python one-shot(state_hash + context + reopen) | ✅ 落盘一致 |
| Python persistent(10 facts + 15 reads) | ✅ hash 稳定 |
| Restart=on-failure(手动 systemctl restart) | ✅ 1s 后 active |
| 优雅 stop(journald Stopped loombridge.service) | ✅ |
| 281 单元测试 | ✅ |
| multi_agent_demo.py(23 断言) | ✅ |
| two_agent_test.py(9 断言) | ✅ |
修复前(StandardOutput=append:/path 目录不存在):
loombridge.service: Failed to set up standard output: No such file or directory
loombridge.service: Main process exited, status=209/STDOUT
loombridge.service: Scheduled restart job, restart counter is at 9 ← crash loop
修复后(StandardOutput=journal + EOF polling loop):
Dec 01 10:29:24 Started loombridge.service - LoomDB Bridge (async stdin long驻).
Dec 01 10:34:24 is-active → active, 0 crash, CPU 36ms, RSS 2756KBPython SDK persistent(Popen 长驻) → context 0.67ms / health 0.30ms / 12-57×
Python SDK one-shot(argv spawn 每次) → state_hash 15-20ms,bridge BoxCache 热
systemd daemon + bridge stdin 长驻 → 进程 2756KB / 36ms CPU·5min / EOF polling 零开销bash scripts/loombridge.sh start # 后台 daemon 化(pid + log + setsid)
bash scripts/loombridge.sh status # 看状态
bash scripts/loombridge.sh ping # 健康检查
bash scripts/loombridge.sh stop # SIGTERM → 等 3s → SIGKILL| # | 问题 | 影响 | 根因 |
|---|---|---|---|
| 1 | 裸调 bridge 永不退出 | ./dist/loombox-bridge(无 argv 无 pipe stdin)进入 EOF polling loop 永远挂着,自己锁自己的 task 文件 | slept_forever 第一代只管 systemd /dev/null 场景,没覆盖"没人理它"的裸调 |
| 2 | Python SDK 缺 fork() API | 内核有 Box::fork(new_task_id)(agent_id 加 task_id 后缀天然隔离),TypeScript SDK 已暴露,但 Python SDK 没实现,用户 fork 只能手动 save_events + merge | 遗漏 |
| 3 | merge op 丢 other 的 task kind 事件 | fork → 演化 a → fork → 演化 b → merge(b→a),b 端 set 的 status/priority 等 task kind 字段全部丢失 | bridge merge op 用 a.task_id 调 load_box 加载 other → import_events_jsonl 把 b 的 task kind rewrite 成 a.task_id,但 merge_to_box 里 a.task_id == b.task_id → 不走 rewrite 分支 |
def fork(self, new_task_id: str) -> "LoomBox":
result = self.bridge.call({
"op": "fork", "taskId": self.task, "agentId": self.agent,
"data": self.events(), "newTaskId": new_task_id,
})
fork_dir = self.store.task_dir(new_task_id)
fork_dir.mkdir(parents=True, exist_ok=True)
(fork_dir / "box.json").write_text(json.dumps({"task": new_task_id, "agent": self.agent}) + "\n")
self.store.save_events(new_task_id, result["events"])
return LoomBox(self.store, new_task_id, self.agent, self.bridge)event.id == event.author + "#" + event.clock.to_string()let agent = agent_id.unwrap_or(self.agent_id + "-" + new_task_id)| 检查项 | 结果 |
|---|---|
| moon test -p loomdb(281 单测) | 281/281 ✅ |
| native bridge 构建 | ✅ |
| wasm / js 构建 | ✅ |
| wasm-gc 构建 | moonc v1.0.0-rc1 release 路径触发 link-core ICE(编译器 bug) → CI 走 debug 构建(功能等价),等上游修完加回 --release |
| python3 scripts/multi_agent_demo.py(3 场景 23 断言) | 全部通过 ✅ |
| python3 scripts/two_agent_test.py(9 断言) | 9/9 ✅ |
| bash scripts/install_systemd.sh install + is-active | ✅ active |
| systemd 5+ 分钟稳定运行 | ✅ 零 crash / 36ms CPU / RSS 2756KB |
| benchmark(200 facts · persistent vs one-shot) | context 0.69ms/loop / merge 11.10ms / 12-57× 提升 |
| Target | 命令 | 产物 | 用途 | CI 状态 |
|---|---|---|---|---|
| Native | moon build cmd/bridge --target native --release | _build/native/.../bridge.exe | CLI、Node 文件系统后端 | ✅ release |
| Wasm | moon build --target wasm --release | _build/wasm/.../bridge.wasm | 浏览器 IndexedDB / OPFS | ✅ release |
| Wasm-GC | moon build --target wasm-gc(debug) | _build/wasm-gc/.../bridge.wasm | 浏览器 GC proposal,体积更小 | ⚠️ 见下 |
| JS | moon build --target js --release | _build/js/.../bridge.js | Node.js 纯 JS,MCP Server 宿主 | ✅ release |
Error: File "moonc.ml", line 470030, characters 14-20: Assertion failedif [ target = "wasm-gc" ]; then
moon build --target wasm-gc # debug → 通过 ✅
else
moon build --target $target --release # release → 通过 ✅
fi| 适配 | 位置 | 说明 |
|---|---|---|
| 文件系统 | MoonBit core 内置 | Node / Native runner 写 events.jsonl |
| IndexedDB | platform/storage/indexeddb.mjs | Wasm 宿主持久化 |
| Git | platform/git/pre-commit + gitattributes.snippet + loombox-history.sh | 事件文件纳入版本控制,git diff 即记忆变化 |
| CI 检查 | platform/ci/check.sh + loombox.py check | 矛盾事实 / 过期决策 → 非零退出码 |
moon test -p loomdb # 281 tests · 全过(含 7 个跨 taskId merge 集成测试)
python3 scripts/platform_smoke.py # CLI + Python SDK + bridge
python3 scripts/multi_agent_demo.py # Planner / Executor 协作链 · Lamport 冲突 · 三路合并
python3 scripts/two_agent_test.py # 两个最小 Agent 并发操作 · 9 断言 · pytest 友好
python3 -m pytest scripts/two_agent_test.py -v -s # 也能用 pytest 跑
python3 scripts/benchmark.py # 200 facts · persistent vs one-shot 性能对比(12-57× 提升)
bash scripts/build_wasm.sh # wasm 编译 + selftest + gzip ≤ 500KB| 项 | 重评条件 |
|---|---|
| 存储加密 encryptBox | M4 验收后 |
| VS Code 侧边栏插件 | M3 + M4 验收后 |
| Web DevTools 可视化 | M2 验收后 |
| 多语言 SDK(Rust / Go) | M1 验收后 |
| 分布式跨机器同步服务 | 产品形态明确后 |
moonbitLoomDB/
├── loomdb/ # MoonBit 核心(事件模型 / 状态归约 / 合并 / 检索)
├── cmd/
│ ├── bridge/ # Native 可执行(CLI 宿主)
│ └── ffi/ # Wasm / JS FFI 接口
├── bindings/ # TypeScript 类型声明 + JS 绑定
├── platform/
│ ├── cli/ # Python CLI(调用 native bridge)
│ ├── mcp/server.mjs # MCP Server
│ ├── sdk/python/ # Python SDK(CLI 内部用)
│ ├── storage/indexeddb.mjs # 浏览器 IndexedDB 适配
│ ├── git/ # Git 集成钩子
│ └── ci/check.sh # CI 检查脚本
├── scripts/ # 构建 & 冒烟 & 演示 & 集成测试 & benchmark
│ ├── build_wasm.sh
│ ├── build_bridge.sh
│ ├── platform_smoke.py
│ ├── multi_agent_demo.py # Planner + Executor 跨 taskId merge 演示
│ ├── two_agent_test.py # 两 Agent 并发集成测试(threading + 9 断言)
│ ├── benchmark.py # 200 facts box 性能基准(bridge persistent vs one-shot)
│ ├── profile_bridge.py # bridge 内部耗时分解
│ ├── loombridge.sh # Bridge 长驻进程管理(start/stop/restart/status/ping/logs/run)
│ └── install_systemd.sh # systemd 用户服务一键安装脚本
├── systemd/
│ └── loombridge.service # systemd user service(StandardInput=null + Restart=on-failure)
├── .github/workflows/ci.yml
└── moon.mod / moon.pkg TaskFieldSet(_, field, value)
→ TaskFieldSet(new, field, value)
ObservationAdded(id, tool, status, summary, _, out)
→ ObservationAdded(id, tool, status, summary, new, out)
DependencyAdded(_, dep)
→ DependencyAdded(new, dep)
DependencyRemoved(_, dep)
→ DependencyRemoved(new, dep)
PolicySet(scope, key, val, enabled) // 仅 scope=="task:"+old 时
→ PolicySet("task:"+new, key, val, enabled)
FactSet / FactRetracted / DecisionAdded / ArtifactAdded / ...
→ 原样(无 task kind,零副作用)| 入口 | 文件 | 触发时机 |
|---|---|---|
| Box::fork(new_task_id) | box.mbt:1782 | fork 时立即把所有旧事件的 task kind 重写成新 task_id |
| merge_to_box(a, b) / merge_boxes(a, b) | box.mbt:1706 / api.mbt:969 | a.task_id != b.task_id 时对 b.events 做 map rewrite |
| merge_three_way(base, a, b) | sync.mbt:279 | 同上,对 b.events rewrite 后再 merge |
| import_events_jsonl(data, task_id) | import_events.mbt:412 | bridge 入口,构造目标 task 盒时自动 rewrite(防 replay 炸) |
| Python SDK | platform/sdk/python/loomdb.py:314 | 已去掉 if other.task != self.task → raise 这一层硬挡 |
# 直接跑(打印漂亮日志 + 9 断言)
python3 scripts/two_agent_test.py
# pytest 风格
python3 -m pytest scripts/two_agent_test.py -v -sbase 盒(status=pending, repo.name=loombot)
├── thread=Planner task_id=...-planner
│ set status=analyzing → claim owner → fact build.tool=npm
│ fact build.fail_reason=.npmrc → decide fix → set status=blocked
│
└── thread=Executor task_id=...-executor
observe ci fail → observe install pass → artifact .npmrc
fact env.node_path → set status=in_progress → set status=done
↓ merge executor → planner(跨 taskId,自动 rewrite)
最终 Planner 盒:
├── status = "done" ← Lamport LWW,Executor 最后一次写胜
├── decisions = 1 ← Planner 写的
├── observations = 2 ← Executor 写的(task_id 已 rewrite)
├── artifacts = 1 ← Executor 写的
├── facts: 4 条全部合入 ← Planner 的 build.* + Executor 的 env.node_path
├── timeline: 14 事件 ← Lamport 严格递增
└── contradictions = 0| # | 断言 | 验证 |
|---|---|---|
| 1 | Planner/Executor state_hash 不同 | 各自演化独立 |
| 2 | merge 落盘后再 open,hash 一致 | merge + rewrite 真正落地 |
| 3 | 最终 status == "done" | Lamport LWW 冲突裁决正确 |
| 4 | decisions ≥ 1, observations ≥ 2 | 两边内容都在 |
| 5 | build.tool="npm" + env.node_path | fact 合并正确 |
| 6 | artifacts ≥ 1 | Executor 产物进来了 |
| 7 | timeline Lamport 严格递增 | 时间线有序 |
| 8 | rewrite 无泄漏 | 遍历 merge 后事件 JSONL,所有 kind ∈ {task, observation, dep, undep} 的 taskId 都等于 Planner task_id;所有 policy.scope 不以 task: 开头或等于 task:planner_task_id |
| 9 | merge 幂等 | 同一 Executor box 再 merge 一次 → state_hash 不变 |
┌─ 结果 ─────────────────────────────────────────────────────
│ base_hash = sha256:261154e5f
│ planner(before) = sha256:77c57bc70 ← 各自演化,不同
│ executor(before) = sha256:9b328798c ← 各自演化,不同
│ merged_hash = sha256:2715e616f ← 跨 taskId merge 收敛
│ final_hash = sha256:2715e616f ← 落盘后打开,一致
│ timeline events = 14 ← Lamport 有序
│ contradictions = 0 ← merge 后无矛盾
│ decisions = 1
│ observations = 2
│ artifacts = 1
└─────────────────────────────────────────────────────────────
✅ 全部 9 个断言通过!两 Agent 操作 + 跨 taskId merge 收敛正确。| 维度 | 选择 | 理由 |
|---|---|---|
| Agent 实现 | 规则引擎(deterministic) | 不依赖任何外部 LLM API,纯离线可复现 |
| 并发模型 | threading.Thread × 2,每 thread 独持一份 LoomBox + native bridge 子进程 | 真实模拟多 Agent 并发,而不是伪顺序 |
| task_id 隔离 | Planner/Executor 各持独立 task_id | 故意触发 rewrite_event_for_task 路径 |
| merge 方向 | executor → planner(跨 taskId) | Planner 主导,Executor 的 task kind 自动 rewrite |
| 两层入口 | main() 直接打印 + pytest test_two_agents_concurrent_merge() | 既可以单独跑也能进 CI |
Install
Download zipLoomDB: a local shared task-memory box for agents, written in MoonBit.