Predictive memory network — remembers workflows and predicts the most likely next step before the user asks.
White-box explainability — every prediction/explain returns the concrete node/edge/transition path, never a black box.
Semantic recall — given a new source sentence, activates a spreading network to recall the exact bilingual terms/sentences that keep terminology consistent.
Cold-start generalization — role-level abstraction (D8) induces domain-independent process skeletons, so an unseen project still gets a sensible next step.
Deterministic & reproducible — a logical clock replaces wall-clock time; identical call sequences yield byte-identical to_json output (no RNG).
Zero third-party dependencies — pure MoonBit core (json + math only); nothing to install beyond the moon toolchain.
Serializable — full engine state exports/imports as JSON for persistence and cross-session restore.
Fast inference (快) — role inverted-index (role_members) + per-source Top-8 pruning keep the hot path off full-graph scans; a pred_cache (fully invalidated on any engine change, not LRU) short-circuits repeated (context, k) queries.
Accurate (准) — second-order Markov (trans2, P(w3|w1,w2) blended at λ=0.4), multi-granularity role keys (前二/前四/前后各二), elastic forgetting (recency-aware edge decay), adaptive Hebbian LR, per-domain bias ΔW (LoRA-style), online contrastive learning (cl_step), and attention-gated edge weights in recall.
Explainable & bilingual (美) — TermNode (mark_term) boosts terminology recall with a +5.0 activation and a “term hit” flag; explain_card returns a white-box activation_path / prediction_path / value_breakdown JSON; align_diff gives a character-level LCS edit script for bilingual alignment.
β=0.45 dominates — predicted-hit value ranks highest.
D5 Episode sequence
episode log
Records sequences for consolidation replay.
D6 Consolidation
prune + constraint-contract snapshot
Meta-cognitive explore control; contract roll-back via restore.
D7 Uncertainty
distribution entropy
Emits confidence / uncertainty.
D8 Concept abstraction
multi-granularity role transitions (cold-start)
前二 / 前四 / 前后各二 role keys induce cross-topic rules.
Why deterministic: a self.clock (incremented on every remember/observe) substitutes wall-clock time, so results are reproducible and dependency-free. Because REC_TAU ≫ training steps, the recency term is ≈ 1.
Requires the MoonBit toolchain (moon, v0.1.2026+).
Out-of-the-box setup (Windows, AI agents welcome)
Clone the repo, then run the one-shot dev workflow (checks env → builds the native
service → starts it on 127.0.0.1:8787 → seeds sample TM pairs → smoke-tests
all 27 REST endpoints + 25 MCP tools):
Windows native prerequisites: cmd/service requires MSVC (link.native.cc
in cmd/service/moon.pkg and cmd/main/moon.pkg points at cl.exe — update both if
the path differs on your machine); after a MoonBit toolchain upgrade, rebuild the core
native bundle once (cd ~/.moon/lib/core && moon clean --target-dir _build/native && moon bundle --target native --release). AI agents: see AGENTS.md for
the full out-of-the-box guide.
Quick Start
A copy-paste minimal example: train a short workflow, then predict the next need — and (with #22) manage a translation memory + termbase.
pub fn quickstart() -> Unit {
let mut eng = @lib.ProphecyEngine::make()
// 1) observe() records real steps in order; the engine maintains a
// context window and a 1st/2nd-order Markov transition model internally.
let _ = eng.observe("解析源文件结构", "step")
let _ = eng.observe("提取核心术语表并锁定", "step")
let _ = eng.observe("生成双语对照草稿", "step")
// 2) predict Top-3 most likely next steps from current context.
let pred = eng.predict(3)
println(@json.stringify(pred))
// 3) recall: given a query, return related memories (with activation + path).
let hits = eng.recall("术语", 5)
println(@json.stringify(hits))
// 4) persist & restore.
let snap = eng.to_json()
let eng2 = @lib.ProphecyEngine::from_json(snap)
let _ = eng2
// 5) #22 — TM / TermBase: add memory, load a TBX glossary, align & verify.
let _ = eng.add_tm("电池包热管理策略", "Battery pack thermal management strategy")
let tbx =
"<martif><text><body>" +
"<termEntry id=\"1\"><langSet xml:lang=\"en-US\"><ntig><termGrp><term>sensor</term></termGrp></ntig></langSet>" +
"<langSet xml:lang=\"zh-CN\"><ntig><termGrp><term>传感器</term></termGrp></ntig></langSet></termEntry>" +
"</body></text></martif>"
let _ = eng.load_tbx(tbx)
let tmx = eng.fuzzy_match("电池包热管理", 3, 0.70) // Top-K with match_pct
let v = eng.check_terms("install the sensor", "安装设备") // 1 violation (漏译 传感器)
println(@json.stringify(tmx))
println(@json.stringify(v))
}
observe(text, mtype) builds edges/transitions from the current context window and advances the logical clock. To control co-occurrence manually, call remember(text, mtype, ctx) with an explicit ctx array.
Then smoke-test the API (Windows native build requires MSVC — see Service Layer):
curl -X POST localhost:8787/api/add_tm -d '{"src":"电池包热管理策略","tgt":"Battery pack thermal management strategy"}'
curl -X POST localhost:8787/api/fuzzy_match -d '{"query":"电池包热管理方案","k":3,"threshold":0.5}'
curl -X POST localhost:8787/api/check_terms -d '{"source":"install the sensor","target":"安装设备"}'
curl -X POST localhost:8787/api/qe_auto -d '{"source":"a","target":"b","match_rate":0.8}'
curl -X POST localhost:8787/api/predict -d '{"k":3}'
Modern Corpus Evaluation (2025–2026)
The engine is evaluated end-to-end on a cutting-edge, purely English corpus spanning 8 modern domains sourced from real 2025–2026 research trends. All transcripts are fully reproducible via moon test --target wasm-gc --filter Layer* (yimai_prophecy_moonbit_modern_corpus_test.mbt).
Corpus domains (Modern + Extended + Frontier)
#
Domain
Sample training content
1
AI Safety & Alignment
RLHF reward hacking audits, red-teaming frontier models against CBRN knowledge, mechanistic interpretability of superposition in SAE features
2
Climate Modeling & Carbon Capture
CMIP7 AR7 scenario SSP5-8.5 projection, direct air capture with solid amine sorbents, enhanced weathering of olivine for ocean alkalinity enhancement
3
Quantum Computing & Error Correction
Surface code logical error rates at 10⁻⁶ physical error threshold, cat qubit bias-preserving gates with autonomous stabilization, LDPC code benchmarks on IBM ibm_sherbrooke vs Google Willow
4
CRISPR & Gene Therapy
CRISPR-Cas12a multiplexed genome editing with AI-designed gRNA libraries, PCSK9 base editing for durable LDL cholesterol reduction, AAV9 capsid engineering for blood-brain barrier crossing
5
Cybersecurity & Zero Trust
NIST SP 800-207 Zero Trust Architecture deployment, post-quantum TLS 1.3 hybrid key exchange with Kyber-1024 + X25519, AI-driven SOC automation with graph neural network anomaly detection
6
Neuroscience & Brain-Computer Interfaces
High-density 1024-channel ECoG grid for speech decoding, latent diffusion models reconstructing perceived natural images from 7T fMRI BOLD signals
7
Distributed Systems & Cloud Native
Multi-region Spanner-style TrueTime with bounded clock uncertainty, service mesh mTLS with SPIFFE identities, disaggregated memory pooling over CXL 3.0 fabrics
8
NLP & Large Language Models
Llama-4-Maverick MOE routing with 128 experts + top-8 gating, RLAIF vs RLHF head-to-head on MT-Bench and AlpacaEval 2.0, retrieval-augmented generation with late interaction ColBERTv2
9
Robotics & Embodied AI
Diffusion policy for dexterous manipulation with visuotactile feedback, sim-to-real transfer of quadruped locomotion via domain randomization
LLZO garnet-type solid electrolyte ionic conductivity tuning, lithium metal anode dendrite suppression with ALD coatings
14
Space Tech & Satellite Constellations
Starlink V2 laser inter-satellite link mesh routing, lunar surface habitat construction with regolith 3D printing
15
AI Safety (Frontier)
Constitutional AI alignment workflows, mechanistic interpretability of attention head superposition, red-teaming procedures for CBRN knowledge boundary enforcement
16
Science (Frontier)
CRISPR-Cas12a multiplexed editing workflows, stem cell differentiation protocols, protein folding prediction pipelines with AlphaFold3
17
Mathematics (Frontier)
Category theory proof verification, homological algebra computation, topological data analysis with persistent homology
fuzzy_match("RAG chunking vector store optimization") → hits AI/NLP entries with sim_token / sim_tfidf / sim_char / sim_ngram / sim_tokenset breakdowns
fuzzy_match("CRISPR knockout of PCSK9 gene") → hits CRISPR domain entries
fuzzy_match("neural decoding of brain signals") → hits neuroscience content via semantic overlap (threshold 0.15)
Layer 2: Term enforcement & TBX glossary
Loads 8 bilingual term entries from TBX format (en-US ↔ zh-CN), enforces term consistency on input text, and checks source-target alignment — covering retrieval-augmented generation, low-rank adaptation, surface code, enhanced weathering, guide RNA, zero trust, ECoG, and linearizability.
Layer 3: Cross-domain semantic recall
Multi-domain recall activates the correct domains for mixed queries:
"LLM safety benchmarking" → activates AI Safety + NLP domains
Unseen domains like Zero-Day Threat Intelligence Report and Perovskite Solar Cell Efficiency Roadmap correctly trigger D8 role abstraction to predict a sensible next step — confirming the engine generalizes beyond its training distribution.
Layer 5: Deep fuzzy match with white-box scoring
Cross-domain queries receive multi-granularity similarity breakdowns (token / TF-IDF / char / n-gram / token-set), while orthogonal queries (e.g., “Aristotle” against a technical corpus) correctly return zero results.
Two independent engine instances with identical training produce byte-identical to_json() output; to_json → from_json → to_json round-trips are verified; prediction consistency across serialization boundaries is confirmed.
Post-consolidation state is verified: nodes / edges pruning works correctly, WAL log and replay clone produce valid entries, and metrics report memories count and Hit@3 with expected values.
Extended Corpus Evaluation — 6 New Frontier Domains
Beyond the 8 original domains, the engine is additionally validated on 6 emerging research domains sourced from 2025–2026 breakthroughs. All transcripts in yimai_prophecy_moonbit_extended_corpus_test.mbt.
Additional domains
#
Domain
Sample training content
1
Robotics & Embodied AI
Diffusion policy for dexterous manipulation with visuotactile feedback, sim-to-real transfer of quadruped locomotion via domain randomization
LLZO garnet-type solid electrolyte ionic conductivity tuning, lithium metal anode dendrite suppression with ALD coatings
6
Space Tech & Satellite Constellations
Starlink V2 laser inter-satellite link mesh routing, lunar surface habitat construction with regolith 3D printing
Evaluation results — 14 tests, all passing
Tests span the same Layer 0–10 framework, covering workflow prediction, TM fuzzy match across robotics and fusion pairs, extended TBX glossary enforcement (6 new terms), cross-domain recall, cold-start generalization, deterministic serialization, consolidation/WAL, explainability, attention-gated recall, and active learning/federated export/distillation.
Constitutional AI alignment workflows, mechanistic interpretability of attention head superposition, red-teaming procedures for CBRN knowledge boundary enforcement
2
Science (Frontier)
CRISPR-Cas12a multiplexed editing workflows, stem cell differentiation protocols, protein folding prediction pipelines with AlphaFold3
3
Mathematics (Frontier)
Category theory proof verification, homological algebra computation, topological data analysis with persistent homology
Concordance search: returns all TM segments containing the query term, scored by term occurrence count (distinct from the fuzzy_match similarity score).
Parse a TBX (ISO 30042) termbase. Resolves source/target by each langSet‘s xml:lang (default en-US→zh-CN; falls back to document order when absent). Returns the number of concept entries loaded.
enforce_terms
(text : String) -> Json
Term enforcement: scan text for known terms (Latin terms require word boundaries, so log won’t false-match logical), return hits with translation.
check_terms
(source, target : String) -> Json
Term-consistency check: for each source term whose translation is missing from the target, return a violation.
#22 TM/TB — Translation Memory & TermBase
This extension makes translation memory and terminology first-class citizens alongside the predictive core. It reuses the existing yimai_tokenize / tf_vector / cosine / align_diff / clamp01 primitives — no new dependencies, no re-invented wheel.
add_tm(src, tgt) builds a MemoryNode of mtype="tm" carrying text=source, translation=target (and maintains the TM document-frequency index for IDF).
fuzzy_match (S1 upgrade) scores 0.55·idf_dice + 0.20·char-2gram-dice + 0.15·token-set-dice + 0.10·position over mtype=="tm" nodes only. The IDF table (ln((N+1)/(df+1))+1) down-weights frequent words so rare domain terms dominate (R23); char 2-gram catches morphological variants; token-set Dice tolerates word reordering — a Chinese reordered query scores 0.91 with the new formula while the legacy one misses it entirely (R24). The old 0.7·token-cosine + 0.3·char-ratio formula remains as fuzzy_match_legacy for A/B comparison.
concordance counts query-term occurrences per TM segment — concordance % is term occurrence, distinct from the fuzzy similarity score (per the research baseline).
load_tbx parses TBX 2.0 (<ntig><termGrp><term> or simplified <tig><term>), language-aware via xml:lang, into mtype="term" nodes with is_term=true.
enforce_terms / check_terms provide terminology lock-in and missed-term detection, with word-boundary-aware matching for Latin terms.
All six methods are covered by regression tests R16–R22 (see Evaluation).
TM / TermBase nodes add two fields: a TM node carries "type":"tm","translation":"<target>"; a terminology node carries "type":"term","is_term":true,"translation":"<target term>". Both are round-trip preserved through to_json/from_json (covered by R20).
The engine’s Hit@3 is verified across multiple independent evaluation surfaces:
Classic acceptance suite (4 tests): Layer1 batch training → Hit@3=0.8246, determinism, JSON round-trip, consolidation.
Modern corpus suite (11 tests): 8 cutting-edge English domains, 240 training observations, Hit@3=0.7773, cold-start generalization on unseen domains, cross-domain semantic recall, deep fuzzy match, attention-gated recall, WAL event sourcing, federated export/import, and distillation.
Extension suite (E1–E18): QE+MQM, format-fidelity, multimodal-OCR-stub, batch-CI, TMS XLIFF/TMX, observability/drift.
Reproduce:
cd yimai_prophecy_moonbit
moon test --target wasm-gc # all 175 tests (P6 hardened)
moon test --target wasm-gc --filter Layer* # modern + extended + frontier corpus (25 tests)
moon test --target wasm-gc --filter T* # P4 quality/security tests (T30–T51, 22 tests)
moon build --target wasm-gc # library only
cd cmd/main && moon build --target wasm-gc && moon run .
Extension API (#2–#7)
All seven user-scoped extension capabilities are implemented in engine.mbt and regression-tested by yimai_prophecy_moonbit_extension_test.mbt (E1–E18). They are zero-dependency and deterministic — same input ⇒ same output.
#
Capability
Key methods
Notes
2
Quality estimation + MQM
qe_score, mqm_tags, qe_auto
qe_score = 0.55·match_rate + 0.30·term_ok + 0.15·char_ratio (cross-language length penalty dropped — it dragged scores to ~0.7 and distorted QE). mqm_tags emits terminology / accuracy / fluency / omission with major / critical / minor severity.
3
Format-fidelity round-trip
check_format_fidelity, protect_tags
Detects missing (source tag absent in target) / extra (target-only) inline tags & placeholders; protect_tags masks them to __TAG__ so fuzzy token-cosine isn’t polluted.
4
Multimodal / screenshot
ocr_image (stub), align_regions
ocr_image is an external boundary stub (real OCR = Tesseract / vision-LLM, injected by host). Regions flow as JSON {bbox, text}; the engine does region ↔ TM alignment purely.
5
Localization CI / batch
batch_apply
Top-1 TM match + term-gate per segment, threshold-driven → {total, passed, failed, items}. Drop-in for a CI localization gate.
6
TMS interoperability
parse_tmx, parse_xliff, export_tmx
XLIFF 1.2 <trans-unit> and 2.0 <unit> both parsed; TMX 1.4 exported with XML escaping. Round-trip verified (E10).
7
Observability & drift
metrics, drift_report
metrics = tm/term counts + term-coverage; drift_report(before, after) diffs two to_json snapshots by (type|is_term|text|translation) key to surface TM/term add/remove.
Boundary principle. Capabilities #4 (OCR) and any host persistence stay outside the zero-dependency engine. The engine speaks JSON at these boundaries, so the host (Node/Python/Agent) supplies OCR, files, and I/O — the MoonBit core stays 100% pure-stdlib and wasm-gc-testable.
Roadmap & Extension Status
Engine implementation status (内核「快·准·美」)
The “fast / accurate / beautiful” algorithm kernel is fully landed and contract-tested. Remaining items are front-end workbenches (ardot hand-off) or external services, not engine gaps.
Roadmap entry
Engine implementation
Status
Role inverted-index + Top-K pruning + LRU pred cache
This project is not packaged as a WorkBuddy skill yet. The dev loop for these is: research (Deep Research / WebSearch) → review (open-code-review) → verify (browser automation + moon test). MoA is intentionally not embedded inside the skill (kept as an external advisor).
International Standards & Compliance (P4 增量)
2026-08 增补:随着项目演进,本节列出当前已声明对齐 / 仍属 roadmap 的国际/区域标准,
以及对应的本地化合规姿态。yimai 本身是技术构建块(library + local service)而非翻译服务
机构;本节为「adopter 集成指南」,非 ISO 认证声明。
This package delivers a zero-dependency, deterministic “Prophecy Memory Network” to other agents. Integration options (2026-08 更新,修正此前「无 I/O / 仅 IIFE」的过时声明):
AI agent 拆箱即用:克隆后先读 AGENTS.md(项目结构、构建/运行/消费指南、Windows 前置、MoonBit 坑、多 harness 接入),再跑 scripts/dev.ps1 一键起服务——无需人工配置。
Path D — algorithm port (agent has no MoonBit but needs the capability in-process):
engine.mbt is pure-stdlib, zero-I/O, with constants (HEBB_LR, EDGE_DECAY, BETA, …) that map 1:1 to D1–D8. It can be reimplemented in Python / TypeScript / Go by reading the source — the most portable route for cross-language agent loading.
Issues and pull requests are welcome. The repo ships multiple test suites — please keep moon test --target wasm-gc green when you submit a change. For behavioural/evaluation changes, extend yimai_prophecy_moonbit_modern_corpus_test.mbt with real modern corpus so the evaluation stays honest.
Built on the MoonBit language and its core (json, math) packages.
README structure follows conventions of high-star open-source projects (e.g. sharkdp/bat, BurntSushi/ripgrep) and the idiomatic MoonBit library style of moonbit-community/moon_elk.
译脉·先知 2.0 (MoonBit)
Table of Contents
Features
to_jsonoutput (no RNG).json+mathonly); nothing to install beyond themoontoolchain.role_members) + per-source Top-8 pruning keep the hot path off full-graph scans; apred_cache(fully invalidated on any engine change, not LRU) short-circuits repeated(context, k)queries.trans2,P(w3|w1,w2)blended atλ=0.4), multi-granularity role keys (前二/前四/前后各二), elastic forgetting (recency-aware edge decay), adaptive Hebbian LR, per-domain biasΔW(LoRA-style), online contrastive learning (cl_step), and attention-gated edge weights in recall.TermNode(mark_term) boosts terminology recall with a +5.0 activation and a “term hit” flag;explain_cardreturns a white-boxactivation_path/prediction_path/value_breakdownJSON;align_diffgives a character-level LCS edit script for bilingual alignment.#22新增add_tm/fuzzy_match/concordance/load_tbx/enforce_terms/check_terms:真正的 fuzzy match(匹配率 %)、concordance 检索、TBX(ISO 30042)术语库解析、术语强制对齐与一致性校验(见 §#22)。wal_*) for event-sourced replay, active-learning candidates by uncertainty + diversity, and federated increment export/import (fed_*) for cross-agent coordination.cmd/service起本地 HTTP server(127.0.0.1:8787),27 个/api/*端点 +/mcpMCP Server(13 基础 + retrieve_prompt / bleu / chrf / style_check / style_report / back_align / term_conflicts / fed_export / fed_import / distill_inject / active_learning / metrics / health / mqm_re_annotate;MCP 层共 25 tools)全部实测通过,含 BLEU/chrF++ 评测、风格检查、回译对齐、术语冲突、TMPlm、联邦/蒸馏注入、主动学习推荐;TM 状态经 fs 原子写持久化(tmp+rename),重启恢复闭环——引擎到服务零桥接语言。How it works (D1–D8)
The engine is a neuro-inspired memory network. Eight modules map directly to constants in
engine.mbt:w ← w + LR·(1−w)a·w·decaysrc→{dst}/(w1,w2)→{w3}λ·P(w3|w1,w2)(second-order).V = α·U_past + β·U_pred + γ·C_graph + δ·R − ε·Costexplorecontrol; contract roll-back viarestore.confidence/uncertainty.Why deterministic: a
self.clock(incremented on everyremember/observe) substitutes wall-clock time, so results are reproducible and dependency-free. BecauseREC_TAU≫ training steps, the recency term is ≈ 1.Project Structure
三层架构:
engine.mbt+util.mbt—— 零依赖,仅依赖moonbitlang/core/json+core/mathcmd/service/*—— 纯 MoonBit HTTP/MCP 服务,27 个端点,原子写持久化docs/*+AGENTS.md+SKILL.md—— 文档 + 技能编排 + 集成指南测试策略:
core69 /corpus54 /feature52)scripts/dev.ps1+.githooks/pre-commit+.github/workflows/ci.yml—— 构建/提交前自动运行moon test --target wasm-gcInstallation
As a MoonBit library, add the dependency:
Then declare the import in your package’s
moon.pkg(recommended alias@lib):Out-of-the-box setup (Windows, AI agents welcome)
Clone the repo, then run the one-shot dev workflow (checks env → builds the native service → starts it on
127.0.0.1:8787→ seeds sample TM pairs → smoke-tests all 27 REST endpoints + 25 MCP tools):Or step by step:
scripts/setup.ps1(env check) →build.ps1(compile, needs MSVC) →run.ps1(start) →seed.ps1(sample data) →smoke.ps1(verify).Quick Start
A copy-paste minimal example: train a short workflow, then predict the next need — and (with
#22) manage a translation memory + termbase.Build & run the bundled demo:
Start the HTTP service (pure MoonBit,
cmd/service)Then smoke-test the API (Windows native build requires MSVC — see Service Layer):
Modern Corpus Evaluation (2025–2026)
The engine is evaluated end-to-end on a cutting-edge, purely English corpus spanning 8 modern domains sourced from real 2025–2026 research trends. All transcripts are fully reproducible via
moon test --target wasm-gc --filter Layer*(yimai_prophecy_moonbit_modern_corpus_test.mbt).Corpus domains (Modern + Extended + Frontier)
Evaluation results — 25 tests, all passing (Modern + Extended + Frontier)
Layer 0: Workflow prediction (8 domains × 6 steps × 5 rounds = 240 observations)
Layer 1: TM fuzzy match (multi-granularity white-box scoring)
Cross-domain TM recall consistently activates relevant memories:
fuzzy_match("RAG chunking vector store optimization")→ hits AI/NLP entries with sim_token / sim_tfidf / sim_char / sim_ngram / sim_tokenset breakdownsfuzzy_match("CRISPR knockout of PCSK9 gene")→ hits CRISPR domain entriesfuzzy_match("neural decoding of brain signals")→ hits neuroscience content via semantic overlap (threshold 0.15)Layer 2: Term enforcement & TBX glossary
Loads 8 bilingual term entries from TBX format (
en-US↔zh-CN), enforces term consistency on input text, and checks source-target alignment — covering retrieval-augmented generation, low-rank adaptation, surface code, enhanced weathering, guide RNA, zero trust, ECoG, and linearizability.Layer 3: Cross-domain semantic recall
Multi-domain recall activates the correct domains for mixed queries:
"LLM safety benchmarking"→ activates AI Safety + NLP domains"gene editing + neural decoding"→ activates CRISPR + Neuroscience domains"quantum + distributed consensus"→ activates Quantum Computing + Distributed Systems domainsLayer 4: Cold-start generalization
Unseen domains like Zero-Day Threat Intelligence Report and Perovskite Solar Cell Efficiency Roadmap correctly trigger D8 role abstraction to predict a sensible next step — confirming the engine generalizes beyond its training distribution.
Layer 5: Deep fuzzy match with white-box scoring
Cross-domain queries receive multi-granularity similarity breakdowns (token / TF-IDF / char / n-gram / token-set), while orthogonal queries (e.g., “Aristotle” against a technical corpus) correctly return zero results.
Layer 6: Deterministic serialization & JSON round-trip
Two independent engine instances with identical training produce byte-identical
to_json()output;to_json → from_json → to_jsonround-trips are verified; prediction consistency across serialization boundaries is confirmed.Layer 7: Consolidation, metrics & WAL event sourcing
Post-consolidation state is verified: nodes / edges pruning works correctly, WAL log and replay clone produce valid entries, and metrics report memories count and Hit@3 with expected values.
Layer 8: White-box explainability
explain_cardreturns rich JSON withactivation_path(source→target node chain),prediction_path(step-to-step transitions), andvalue_breakdown(α·U + β·U_pred + γ·C_graph + δ·R − ε·Cost decomposition).Layer 9: Attention-gated recall & domain bias modulation
Attention gating (α=0.3, β=0.2) + domain bias (+0.15 on quantum role) shifts recall ranking toward the preferred domain while preserving cross-domain awareness.
Layer 10: Active learning, federated export/import & distillation
Active learning candidates ranked by uncertainty + diversity; federated export produces increment diff; domain bias distilled at +0.25 for targeted roles; federated import merges external memory increments.
Summary
Extended Corpus Evaluation — 6 New Frontier Domains
Beyond the 8 original domains, the engine is additionally validated on 6 emerging research domains sourced from 2025–2026 breakthroughs. All transcripts in
yimai_prophecy_moonbit_extended_corpus_test.mbt.Additional domains
Evaluation results — 14 tests, all passing
Tests span the same Layer 0–10 framework, covering workflow prediction, TM fuzzy match across robotics and fusion pairs, extended TBX glossary enforcement (6 new terms), cross-domain recall, cold-start generalization, deterministic serialization, consolidation/WAL, explainability, attention-gated recall, and active learning/federated export/distillation.
Frontier Corpus Evaluation — 10 Emerging Domains
2026-08 P4 增量新增:前 8 个(Modern + Extended)已覆盖 14 个前沿领域,Frontier Corpus 再增 10 个跨学科前沿领域,重点测试预测记忆引擎在超长上下文(步骤超过 10 步)和复杂事实推理场景下的泛化能力。所有测试在
yimai_prophecy_moonbit_frontier_corpus_test.mbt。Frontier domains
Evaluation results — 14 tests, all passing
核心验证点:
add_tm存储事实,observe学习指令),更贴近真实工作流Service Layer — 纯 MoonBit HTTP API (cmd/service)
cmd/service是纯 MoonBit 双层架构的 Layer 2:用moonbitlang/async(http / fs / socket)起本地 HTTP server,把引擎能力以 REST API 暴露给前端工作台 / Agent / LLM 宿主。引擎到服务零桥接语言——同一门 MoonBit 完成全部。架构演进:旧架构 vs 新架构
本项目从「纯库」演进为「三层架构」。差异如下:
cmd/maindemoasync/fs原子写持久化(tm_store.json,tmp+rename)+ 重启恢复闭环moon add后进程内调用)127.0.0.1:8787Ref[ProphecyEngine]服务内单例 + JSON 边界透出端点矩阵(27 个,全部 curl 实测通过)
/api/ping{"status":"ok"}/api/add_tm{"src","tgt"}{"id","status"}/api/fuzzy_match{"query","k","threshold"}/api/check_terms{"source","target"}/api/concordance{"term","k"}/api/qe_auto{"source","target","match_rate"}{"qe_score","term_ok","mqm"}/api/predict{"k"}{"predictions","confidence","uncertainty"}/api/observe{"text","mtype"}{"mid","status"}/api/recall{"query","k"}Array[{id,text,score,via_edges}]/api/explain{"mid"}value_breakdown/activation_path证据链/api/reward{"mid","score"}{"ok"}/api/consolidate{"prune"}{pruned,nodes,edges,...}/api/retrieve_prompt{"query","k","threshold"}/api/bleu//api/chrf{"ref","hyp"}{bleu}/{chrf}/api/style_check{"text"}/api/style_report{"text"?}{sentence_count,avg_src_len,avg_tgt_len,formal_score,distribution,term_variants,tips}/api/back_align{"source","target"}{align_score,misaligns,ops}/api/term_conflicts/api/fed_export//api/fed_import{"added","updated"}{status}/api/distill_inject{"table":{k:v}}{status,keys}/api/active_learning{"k"}Array[{id,text,uncertainty,role}]/api/tm_count{"tm_count"}/api/metrics/api/health/api/mqm_re_annotate{"source","target","match_rate"}实测(中文 query,白盒分项全透出):
三层关联与记忆闭环
27 个端点不是孤立的——它们把三层连成记忆闭环(完整映射表见架构方案 §11):
两个闭环(实测):
/api/reward{mid,+1}→predictive_value提升 → 下次/api/predict排序更优;/api/observe{text}→ 转移计数 → 落盘 → 重启恢复 → 预测更准(实测:observe 两步 → predict Top1 prob=1.0)。MCP Server(/mcp 端点)—— 供 Claude Desktop / 通用 MCP 客户端消费
cmd/service同时暴露 MCP(Model Context Protocol)Server 变体(spec 2025-11-25,Streamable HTTP):挂/mcp端点,POST 单 JSON-RPC 消息、application/json响应(无需 SSE)。**25 个引擎能力直接映射为 MCP tools(新增 mqm_re_annotate)`:fuzzy_matchadd_tmcheck_termsconcordanceqe_autopredictobserverecallexplainrewardconsolidatetm_count/pingretrieve_promptbleu/chrfstyle_checkstyle_reportback_alignterm_conflictsfed_export/fed_importdistill_injectactive_learningmqm_re_annotate持久化
to_json()→@fs.write_file(tmp, create_mode=CreateOrTruncate)→rename原子落盘到tm_store.json;load_store()→from_json()完整恢复(实测 tm_count 持久化后重启一致);engine_ref : @ref.Ref[@lib.ProphecyEngine](MoonBit 顶层无全局可变变量,Ref是标准方案)。平台要求(Windows)
thread_pool.c: #error "Currently only MSVC is supported on Windows"),mingw gcc 不可用;wasm/js 后端暂不支持 socket server;moon.pkg配置link.native.cc指向cl.exe;cd ~/.moon/lib/core && moon clean --target-dir _build/native && moon bundle --target native --release)。API Reference
All public interfaces are methods of
ProphecyEngine(encoding helpers inutil.mbtare package-private).Core (D1–D8, persistence, feedback)
make() -> ProphecyEngineremember(text, mtype, ctx : Array[String]) -> Stringobserve(text, mtype) -> Stringpredict(k : Int) -> Jsonrecall(query : String, k : Int) -> Array[Json]consolidate(prune : Bool) -> Jsonexplore.restore() -> Jsonreward(mid, score : Double) -> Boolexplain(mid : String) -> Jsonend_episode() -> Unithit_rate() -> Doublestats_view() -> Jsoncontext_texts() -> Array[String]last_context_id() -> Stringto_json() -> Jsonfrom_json(data : Json) -> ProphecyEngineLearning & explanation (准·美)
set_domain_bias(role, delta : Double) -> UnitΔW(LoRA-style).inject_distillation(table : Map[String, Double]) -> Unitcl_step(anchor, positive, negative : String) -> Unitset_attention(alpha, beta : Double) -> Unitmark_term(mid : String) -> Boolexplain_card(mid : String) -> JsonIncremental & collaborative (中/长周期)
active_learning_candidates(k : Int) -> Array[Json]wal_replay() -> ProphecyEnginewal_export/wal_compact/wal_clear/wal_len(…) -> Array[String] / Unit / Intfed_export/fed_import() -> Json/(added, updated : Int) -> Unit#22 TM/TB (检索 + 术语守门)
add_tm(src, tgt : String) -> Stringfuzzy_match(query : String, k : Int, threshold : Double) -> Json0.55·idf_dice + 0.20·char-2gram-dice + 0.15·token-set-dice + 0.10·position(IDF 加权让罕见术语优先、2-gram 捕捉形态变体、token-set Dice 容忍词序重排);returnsmatch_pct/sim_token/sim_tfidf/sim_char/sim_ngram/sim_tokenset. (建议阈值threshold = 0.70;MoonBit 无默认参数,调用方需显式传入。)fuzzy_match_legacy(query : String, k : Int, threshold : Double) -> Json0.7·token-cosine + 0.3·char-ratio,4 处引用(engine.mbt+ 2 test + 本 README)。新代码请用fuzzy_match(S1 公式 + IDF 倒排剪枝)。concordance(term : String, k : Int) -> Jsonfuzzy_matchsimilarity score).load_tbx(xml : String, src_lang~ : String = "en-US", tgt_lang~ : String = "zh-CN") -> IntlangSet‘sxml:lang(default en-US→zh-CN; falls back to document order when absent). Returns the number of concept entries loaded.enforce_terms(text : String) -> Jsonlogwon’t false-matchlogical), return hits with translation.check_terms(source, target : String) -> Json#22 TM/TB — Translation Memory & TermBase
This extension makes translation memory and terminology first-class citizens alongside the predictive core. It reuses the existing
yimai_tokenize/tf_vector/cosine/align_diff/clamp01primitives — no new dependencies, no re-invented wheel.add_tm(src, tgt)builds aMemoryNodeofmtype="tm"carryingtext=source,translation=target(and maintains the TM document-frequency index for IDF).fuzzy_match(S1 upgrade) scores0.55·idf_dice + 0.20·char-2gram-dice + 0.15·token-set-dice + 0.10·positionovermtype=="tm"nodes only. The IDF table (ln((N+1)/(df+1))+1) down-weights frequent words so rare domain terms dominate (R23); char 2-gram catches morphological variants; token-set Dice tolerates word reordering — a Chinese reordered query scores 0.91 with the new formula while the legacy one misses it entirely (R24). The old0.7·token-cosine + 0.3·char-ratioformula remains asfuzzy_match_legacyfor A/B comparison.concordancecounts query-term occurrences per TM segment — concordance % is term occurrence, distinct from the fuzzy similarity score (per the research baseline).load_tbxparsesTBX 2.0(<ntig><termGrp><term>or simplified<tig><term>), language-aware viaxml:lang, intomtype="term"nodes withis_term=true.enforce_terms/check_termsprovide terminology lock-in and missed-term detection, with word-boundary-aware matching for Latin terms.All six methods are covered by regression tests R16–R22 (see Evaluation).
Data Formats
Engine persistence (
to_json/from_json)predict(k)returnsrecall(query, k)returns (array)consolidate(prune)returns#22— TM / TermBase outputsfuzzy_match(query, k, threshold)(array, Top-K byscore):concordance(term, k)(array):load_tbxinput (TBX 2.0 fragment):enforce_terms(text)(array — word-boundary matched):check_terms(source, target)(array — violations only):Evaluation & Test Results
All numbers below are produced by
moon test --target wasm-gcand are reproducible.Summary:
Total tests: 175, passed: 175, failed: 0(3 sub-packages:tests/core/69 +tests/corpus/54 +tests/feature/52; 4 quantitative acceptance + 16 API coverage + 6 benchmark + 7 golden + 12 long-text + 10 TM + 6 v2 + 3 whitebox + 1 main; 11 modern corpus + 11 extended corpus + 14 frontier corpus + 3 business corpus + 15 roadmap regression; 19 extension E1–E19 + 16 P4 quality T1–T37 + 12 routes_meta + 5 mqm_re_annotate).hit_rate = 0.8246over 8 topics × 8 roundsto_jsoncalls are byte-identicalto_json → from_json → to_jsonidentical提取核心术语表并锁定explain_cardreturns concrete activation_path / prediction_path / value_breakdownto_json → from_jsonTop1 unchangedCredibility hardening
The engine’s Hit@3 is verified across multiple independent evaluation surfaces:
log≠logical), 3-languagexml:lang, IDF discrimination, word-order tolerance, empty/short-query boundary.Reproduce:
Extension API (#2–#7)
All seven user-scoped extension capabilities are implemented in
engine.mbtand regression-tested byyimai_prophecy_moonbit_extension_test.mbt(E1–E18). They are zero-dependency and deterministic — same input ⇒ same output.qe_score,mqm_tags,qe_autoqe_score = 0.55·match_rate + 0.30·term_ok + 0.15·char_ratio(cross-language length penalty dropped — it dragged scores to ~0.7 and distorted QE).mqm_tagsemitsterminology / accuracy / fluency / omissionwithmajor / critical / minorseverity.check_format_fidelity,protect_tagsmissing(source tag absent in target) /extra(target-only) inline tags & placeholders;protect_tagsmasks them to__TAG__so fuzzy token-cosine isn’t polluted.ocr_image(stub),align_regionsocr_imageis an external boundary stub (real OCR = Tesseract / vision-LLM, injected by host). Regions flow as JSON{bbox, text}; the engine does region ↔ TM alignment purely.batch_apply{total, passed, failed, items}. Drop-in for a CI localization gate.parse_tmx,parse_xliff,export_tmx<trans-unit>and 2.0<unit>both parsed; TMX 1.4 exported with XML escaping. Round-trip verified (E10).metrics,drift_reportmetrics= tm/term counts + term-coverage;drift_report(before, after)diffs twoto_jsonsnapshots by(type|is_term|text|translation)key to surface TM/term add/remove.Roadmap & Extension Status
Engine implementation status (内核「快·准·美」)
The “fast / accurate / beautiful” algorithm kernel is fully landed and contract-tested. Remaining items are front-end workbenches (ardot hand-off) or external services, not engine gaps.
role_members/ predict Top-K /pred_cachetrans2roles_ofhebb_lr/consolidatedomain_bias/set_domain_bias/inject_distillationcl_stepattn_alpha/beta/set_attentionmark_term/explain_cardwal_*align_diffactive_learning_candidatesfed_export/fed_importinject_distillationadd_tm/fuzzy_match/concordance/load_tbx/enforce_terms/check_termsfuzzy_match(IDF + 2-gram + word-order)/fuzzy_match_legacycmd/service:27 端点 + 记忆闭环 + 原子写持久化 + 重启恢复cmd/service/mcp.mbt:25 引擎能力 → MCP tools(spec 2025-11-25)retrieve_for_prompt+/api/retrieve_prompt(三段式)docs/skill/SKILL.md(agent_created,安装见 For Agents)cmd/service/web(四面板 + 记忆图谱)bleu_score/chrf_score/style_check/back_align/term_conflicts+ 端点style_report(记忆库句长/正式度分布 + 术语变体族 + 偏离建议)+/api/style_report+ MCP + web ⑧ 面板/api/fed_export/api/fed_import/api/distill_injectSeven extension capabilities (user-scoped)
From the “translation-born skill” brainstorm — what’s built vs. pending:
moon test175/175 (P6 hardening 后); reviewed + hardened (word-boundary,xml:lang); S1 fuzzy-match upgrade (IDF + 2-gram + word-order, R23–R25); open-code-review + MoA fixes forparse_tmxcross-language/</tu>split +mqm_tagscross-language false positives + empty-target/language-variant robustness; P0 长文 + 数字守门加固(MAX_TOKENS 截断 / numeric_consistency MQM 维度 / fuzzy_match 长 query 不崩 / L1–L12 长文回归); P4 fuzzy_match 抽公共 helper + drift_report.text_chrf_avg + MQM 严重度数值化; P6 last_body_oversize→Result enum 消 TOCTOU + NaN/Inf API 修正 + validate.mbt 同包。qe_score(0.55·match + 0.30·term + 0.15·char) +mqm_tags(terminology/accuracy/fluency/omission w/ severity). Tested E1–E3.check_format_fidelity(missing/extra tag detection) +protect_tags(mask tags to__TAG__). Tested E4–E5.ocr_image(external boundary) +align_regions(region ↔ TM align). Zero-dep engine speaks JSON at the OCR boundary; real OCR injected by host. Tested E6–E7.batch_apply(Top-1 TM + term-gate, threshold-driven) →{total, passed, failed, items}. Tested E8–E9.parse_tmx/parse_xliff(XLIFF 1.2<trans-unit>& 2.0<unit>) +export_tmx(round-trip). Tested E10–E11; cross-language TMX correctness regression added as E14 (open-code-review fix).metrics(tm/term counts + coverage) +drift_report(before/after snapshot diff). Tested E12–E13.International Standards & Compliance (P4 增量)
已对齐(algorithm / docs 层)
observe/predict+reward反馈闭环;retrieve_prompt注入双语上下文qe_auto(QE+MQM 标签)+bleu/chrf度量load_tbx解析 ISO 30042-compliant<martif>/<termEntry>predict逐步推荐 +consolidate项目收尾复盘qe_auto/mqm_tags/drift_report.text_chrf_avg三层指标覆盖mqm_tags7 维度标签 + 严重度数值(severity_score: None=0 / Minor=1 / Major=5 / Critical=10)protect_tags/mark_term消费 in-text metadata/mcp端点(Streamable HTTP + JSON-RPC 2.0)2026-07-28已发稳定版(无状态核心 / 移除initialize握手 /server/discover),但因纯本地无鉴权、现有 13 harness 均基于2025-11-25握手,yimai 停留在 2025-11-25(迁移 0.2.0 再议);已落实该版本的 Origin 头校验(DNS 重绑定防护)MQM 严重度尺度(与业界三方对齐,P5 增量)
yimai 采用 MQM Core 严重度数值化。业界主流 MQM 评分器使用三套不同的 penalty 数值, 下表给出显式对照(便于跨工具数据交换):
severity_scoreyimai vs Phrase 差异:Critical penalty yimai 用 10 而非 25。理由是 yimai 中 Critical 已自动触发
mqm_re_annotate二次标注流程(Google 2025-10-28 论文对齐), 二次审后再被采纳的 Critical 段会被消费方拦截,因此 penalty 10 已足够震慑。 Phrase 走纯人工 review 路径,故用更重的 25 防止漏审。yimai vs Lokalise 差异:Lokalise 走
100 - sum(penalties)评分模式(满分 100), yimai 走severity_score原始累计 +qe_auto综合公式(0.50·match_rate + 0.25·term_ok + 0.10·char + 0.15·bleu)。 两者数值不可直接比较,需要按公式反推。参考:
Roadmap(未在 0.1.0 落地,0.2.0 候选)
parse_tmx/export_tmx是pub fn但无/api/*入口parse_xliff是pub fn但无入口/api/import_srx合规姿态:EU AI Act + GDPR(2026-08 声明)
127.0.0.1:8787闭环,tm_store.json原子写持久化在本地工作目录。explain_card/activation_path/prediction_path/value_breakdown)+ MQM 严重度尺度作为 可审计凭证。MCP server 集成 Claude Code / Cursor / Gemini CLI
yimai
/mcp是标准 MCP 2025-11-25 server,可被以下 harness 直接消费(同一份配置 schema 对所有 harness 透明;tools 列表一致):~/.claude/mcp.json或项目级.mcp.jsonmcpServers.yimai.{url,type:"http"}~/.cursor/mcp.json~/.gemini/settings.jsonmcpServers.yimai.{url,type:"http"}完整 13 个 harness 配置(Claude Desktop / Claude Code / Gemini CLI / Cursor / Cline / Continue.dev / Roo Code / Windsurf / OpenAI Codex CLI / Aider / Sourcegraph Cody / Zed / GitHub Copilot)见
docs/harness-configs/。For Agents / Integration
This package delivers a zero-dependency, deterministic “Prophecy Memory Network” to other agents. Integration options (2026-08 更新,修正此前「无 I/O / 仅 IIFE」的过时声明):
Path A — build & run (agent has the MoonBit toolchain):
Then
moon add Across2005/yimai_prophecy_moonbitand call any of theProphecyEnginemethods.Path B — wasm-gc exports (engine as a callable module): 新工具链(moonc v0.10.4+)支持在
moon.pkg.json配置link.wasm-gc.exports+use-js-builtin-string: true,让 JS 宿主直接调用ProphecyEngine方法(String 与 JS String 互通);JS 后端亦支持format: esm/cjs(不再只有 IIFE)。详见 Package Configuration。Path C — service layer (纯 MoonBit HTTP server,
cmd/service): ✅ 已实测落地。moonbitlang/async提供http/fs/socket,起本地服务并托管前端工作台;27 个/api/*端点(13 基础 + retrieve_prompt / bleu / chrf / style_check / style_report / back_align / term_conflicts / fed_export / fed_import / distill_inject / active_learning / metrics / health / mqm_re_annotate)全部 curl 通过,含记忆闭环(observe 学习 → predict 预测 → reward 反馈 → consolidate 固化)与原子写持久化 + 重启恢复(详见 Service Layer)。注意:Windows 上 async 的 native 后端仅支持 MSVC 编译(thread_pool.c: #error "Currently only MSVC is supported on Windows");wasm/js 后端暂不支持 socket server(socket/unimplemented.mbt)。Path D — algorithm port (agent has no MoonBit but needs the capability in-process):
engine.mbtis pure-stdlib, zero-I/O, with constants (HEBB_LR,EDGE_DECAY,BETA, …) that map 1:1 to D1–D8. It can be reimplemented in Python / TypeScript / Go by reading the source — the most portable route for cross-language agent loading.Path E — MCP client (Claude Desktop / any MCP host): ✅ 已实测。
cmd/service暴露/mcp端点(MCP spec 2025-11-25 Streamable HTTP),25 个引擎能力映射为 MCP tools(fuzzy_match / add_tm / check_terms / concordance / qe_auto / predict / observe / recall / explain / reward / consolidate / tm_count / ping / retrieve_prompt / bleu / chrf / style_check / style_report / back_align / term_conflicts / fed_export / fed_import / distill_inject / active_learning / mqm_re_annotate)。Claude Desktop 配置:先
moon run cmd/service --target native起服务,MCP 客户端即可经 initialize → tools/list → tools/call 消费全部引擎能力(详见 MCP Server)。Contributing
Issues and pull requests are welcome. The repo ships multiple test suites — please keep
moon test --target wasm-gcgreen when you submit a change. For behavioural/evaluation changes, extendyimai_prophecy_moonbit_modern_corpus_test.mbtwith real modern corpus so the evaluation stays honest.License
MIT — see
LICENSE.Acknowledgements
core(json,math) packages.sharkdp/bat,BurntSushi/ripgrep) and the idiomatic MoonBit library style ofmoonbit-community/moon_elk.译脉·先知2.0_完整架构方案.md(黑客松定位、三层架构、确定性/零依赖/白盒三大卖点、S1 实证、增强路线图 S/M/L → 端点映射)。