⚠️ This is the static README. The canonical, always-up-to-date README is
README.mbt.md, which runs as executable tests
via moon test README.mbt.md — every code example is verified on every CI run.
本文件仅为静态副本,最新权威版本请查看 README.mbt.md(可执行文档,示例即测试)。
A MoonBit-native pathfinding and graph algorithms library built for rigorous engineering.
A production-grade pathfinding and graph algorithms library for MoonBit,
built to compete with Rust’s pathfinding crate on the axes that matter:
executable proof predicates, executable Markdown documentation,
multi-backend consistency (wasm-gc / native / js), and
reproducible validation scripts.
Why this project (three stories)
Filling an ecosystem gap — a production-grade pathfinding / graph
algorithms library for MoonBit: 38+ algorithms (BFS → A* → JPS → ALT →
CH → Hub Labels → PHAST) plus 20 infra directions, published on
mooncakes.io
with a live in-browser playground.
An engineering benchmark for the ecosystem — 3339 tests across four
backends (wasm-gc / native / js / wasm), executable proof predicates,
executable README (moon test README.mbt.md), DST + differential PBT,
zero-warning --deny-warn CI gates, and a published
head-to-head vs Rust’s pathfinding crate
(≈2.7× median same-algorithm speedup; bidirectional variants reported
separately).
Real data, end to end — real OSM road networks (Beijing / Xiamen)
drive the point-to-point hierarchy (bidirectional Dijkstra → ALT → CH →
HL, up to 13279×) with full cross-validation, all reproducible from
checked-in scripts and artifacts.
Downstream usage: two independent repositories consume the published
mooncakes.io package (moon add Suquster/moonbit-pathfinding) as a regular
dependency, each with its own tests and CI:
Suquster/moonbit-pathfinding-demo
(a warehouse robot route planner) and
Suquster/moonbit-maze
(a perfect-maze generator + A* solver CLI with a Dijkstra cross-check
oracle).
Ported from
本库 API 哲学 参考自 Rust 社区的
pathfinding crate(v4.15.0,
双许可 MIT OR Apache-2.0)。核心借鉴:
AI-agent-friendly successor-function APIs and graph input guides that
keep callers free from a forced graph data structure.
See docs/ECOSYSTEM_COMPARISON.md for a
per-domain comparison with existing MoonBit ecosystem packages (pathfinding,
hash, compress, TOML, diff, etc.) and the tradeoffs behind each choice, and
docs/STRATEGY_CLOSURE.md for the project’s
six-layer closure positioning (pathfinding ⊂ graph algorithms ⊂ verification
infra ⊂ general infra ⊂ language tooling ⊂ AI-native software factory).
moon build --target wasm-gc --release links the src/playground export
layer into a ≤ 100 KBplayground.wasm (enforced by
scripts/wasm_size_guard.ps1 in CI)
Paint walls with the mouse, drag start/goal, and watch BFS / DFS /
Dijkstra / A* / JPS expand frame-by-frame at 60 fps with a live FPS meter
Three-tier fallback (wasm-gc → JS glue → pure-JS) so the demo runs in any
environment, including fully offline (python -m http.server from
playground/web/ + the built .wasm)
Bridge correctness is test-gated: playground/solver_test.mbt and
src/playground/*_test.mbt assert the playground answers are identical to
the library’s
状态: executable runtime predicates exist today; src/proofs is
proof-enabled, and scripts/proof_evidence.ps1 records the current
moon prove result or the exact local toolchain blocker.
The src/proofs/ package encodes post-condition predicates as ordinary
MoonBit functions and tests them in CI. These predicates are the contract
vocabulary that moon prove annotations can reference as the verifier surface
settles. Official MoonBit documentation currently describes moon prove as
experimental, backed by Why3 and SMT solvers.
算法
证明性质
状态
bfs
start/end/edge-validity/minimality/None-witness post-conditions, including bad-witness rejection
✅ runtime-checked
dijkstra
non-negative outputs, weighted path-validity, cost consistency, including bad-witness rejection
Latest local evidence is stored in
docs/verification/latest-proof-evidence.md.
On this machine, runtime proof predicates passed, moon prove --help is
available, and static discharge is blocked because Why3 is not on PATH.
对标 Rust pathfinding crate(✅ published head-to-head)
A reproducible head-to-head comparison against Rust’s pathfinding crate
(v4.11.0, cargo --release) is published in
benches/results/latest-rust-comparison.md
(run via pwsh scripts/rust_comparison.ps1; native backend, bit-identical
xorshift64 workloads with a golden element-wise cross-check, per-query result
signatures verified equal on both sides):
Same-algorithm tier (unidirectional BFS / Dijkstra / A* on both sides,
18/18 cases included, up to 100k nodes / 1.6M edges): median speedup
≈2.7× over Rust (range 2.1–3.6×).
Library-capability bonus tier: this library’s bidirectional variants
(no counterpart API in the Rust crate) reach 8–68× over its own
unidirectional baseline on the same workloads, with signatures
cross-checked element-wise — reported separately and excluded from the
same-algorithm speedup, so no unsupported claims.
Beyond the Rust comparison, checked-in benches/results/*.json artifacts are
local regression evidence. Native artifacts record moon bench statistics from
@bench.T blocks; smoke artifacts record end-to-end package timing. Both
include machine, backend, input size, command output, and methodology so
regressions can be discussed with concrete data.
The native guard defaults to a 25% regression tolerance. The smoke guard remains
available with a deliberately loose 50% default because it times end-to-end
moon test -p ... package execution.
This library is built to compile and run identically on all four MoonBit
backends: wasm-gc, js, native, and pure wasm (linear memory). Every
push to main and every PR triggers the ci workflow’s 4-backend matrix,
which executes the full test suite (2683 cases) on each backend, plus a
WASI delivery gate (scripts/wasi_gate.sh) that runs the release wasm
artifacts under wasmtime and byte-diffs the output against the js backend, and
a component model gate (scripts/component_gate.sh) that componentizes the
core wasm modules via the wasi_snapshot_preview1 command adapter
(wasm-tools component new), validates the component-model binaries, and runs
them under wasmtime with the same byte-level diff against the js backend. Any
output divergence — including snapshot mismatches from inspect(..., content=...)
— fails the entire build, giving us a differential test of algorithmic
behaviour across backends for free.
Current benchmark tests are smoke gates, not a published backend comparison.
The repository now includes reproducible smoke artifacts under
benches/results/ with:
Required field
Why it matters
MoonBit version and target backend
Toolchain performance changes over time
Machine / OS / CPU
Makes local numbers interpretable
Input generator and seed
Allows exact reruns
Algorithm, graph size, edge count, query count
Prevents vague benchmark claims
Raw timing and summary statistics
Keeps release notes auditable
Native and smoke regression guards are available through
scripts/benchmark_native_guard.ps1, scripts/benchmark_guard.ps1, and optional
local acceptance:
The native guard is the lower-noise gate; the smoke guard remains useful for
package-level harness regressions.
Target restrictions
Currently no algorithm is backend-restricted. Future additions that rely
on backend-specific features (e.g. SIMD intrinsics on native) will declare
supported_targets in their moon.pkg.json. Template follows design.md §15.1.
Acknowledgements · 致谢
This project stands on the shoulders of three communities:
MoonBit Team & Community — for the toolchain, Discourse feedback, and
the hard work behind moon prove, Markdown-oriented programming, and the
three-backend ecosystem that makes this library possible.
Rust pathfinding crate authors (evenfurther & contributors) — for
the minimalist “successor function” API philosophy that we ported into
MoonBit. Thank you for a decade of principled design in open source.
OSC 2026 mentors & reviewers — for the spec-driven methodology and
continuous, candid feedback during Milestones 0–3.
External code reviewers and discussion participants who shaped this library
(alphabetical, by GitHub handle) are recorded in docs/community/ as the
project grows. Pull requests are warmly welcomed — see
CONTRIBUTING.md.
For the full development story — design tradeoffs, the road-network SOTA
climb (Dijkstra → ALT → CH → Hub Labeling), falsified experiments, and the
human–AI collaboration record — see the development article (Chinese):
docs/zh/development-article.md.
moonbit-pathfinding
Why this project (three stories)
moon test README.mbt.md), DST + differential PBT, zero-warning--deny-warnCI gates, and a published head-to-head vs Rust’spathfindingcrate (≈2.7× median same-algorithm speedup; bidirectional variants reported separately).Downstream usage: two independent repositories consume the published mooncakes.io package (
moon add Suquster/moonbit-pathfinding) as a regular dependency, each with its own tests and CI:Suquster/moonbit-pathfinding-demo(a warehouse robot route planner) andSuquster/moonbit-maze(a perfect-maze generator + A* solver CLI with a Dijkstra cross-check oracle).Ported from
本库 API 哲学 参考自 Rust 社区的
pathfindingcrate(v4.15.0, 双许可 MIT OR Apache-2.0)。核心借鉴:fn(N) -> Array[N]或fn(N) -> Array[(N, W)]定义邻居关系。N : Eq + Hash足够,无需Ord约束。Option[(Array[N], W)]表示”可能无解的带权最短路”。但所有算法实现均独立派生自原始论文,不是逐行移植。本库在此基础上原 创贡献:
moon proveupgrade path.moon test README.mbt.md, so examples are compiled and snapshot-checked instead of drifting.See docs/ECOSYSTEM_COMPARISON.md for a per-domain comparison with existing MoonBit ecosystem packages (pathfinding, hash, compress, TOML, diff, etc.) and the tradeoffs behind each choice, and docs/STRATEGY_CLOSURE.md for the project’s six-layer closure positioning (pathfinding ⊂ graph algorithms ⊂ verification infra ⊂ general infra ⊂ language tooling ⊂ AI-native software factory).
Quick Start
1. 安装依赖
在你的 MoonBit 项目根目录执行:
在需要调用算法的包的
moon.pkg里声明导入:2. Dijkstra 最短路 · 5 节点小图
考虑下面的有向带权图 (节点
A..E对应索引0..4):三条候选路径:
1 + 2 + 14 + 11 + 3 + 2完整可运行示例 (
cmd/main/main.mbt):运行:
预期输出:
即最短路径为
A → B → C → D, 总代价4,与上方表格第 1 行结果吻合。Example Workflows
The repository ships runnable workflows that exercise different user stories instead of isolated snippets — pathfinding and INFRA directions alike:
moon run examples/maze_solvermoon run examples/network_routingmoon run examples/eight_puzzlemoon run examples/mini_compiler_pipelinemoon run examples/regex_toolkitmoon run examples/log_pipelinemoon run examples/actor_worker_poolmoon run examples/build_pipelinemoon run examples/serialization_studiomoon run examples/dst_explorermoon run examples/config_diff_opsmoon run examples/hash_integritysha256sum), HMAC tamper detection, HKDF/PBKDF2 key derivation, streaming == one-shot, xxHash shardingmoon run examples/compress_workbenchmoon run examples/time_schedulermoon run examples/resilience_gatewaymoon run examples/cli_devtoolmoon run examples/observability_kitmoon run examples/text_editor_coremoon run examples/parser_playgroundmoon run examples/pbt_fuzz_labVerify all example outputs with checked markers:
Latest evidence:
docs/examples/latest-examples-run.mdanddocs/examples/latest-examples-run.json.Hands-on tutorials for every direction (key APIs + minimal snippets + the demo that exercises them):
docs/tutorials/README.md(中文版:docs/zh/tutorials.md).Release Readiness
Package metadata is checked against mooncakes.io publishing expectations: SemVer version, SPDX license, repository, homepage, keywords, README, changelog, and package artifact generation.
Latest evidence:
docs/release/latest-release-readiness.mdanddocs/release/latest-release-readiness.json. The current local guard passes with one environment warning:moon publish --dry-runneeds mooncakes credentials frommoon loginor CI secrets.Algorithm Catalog
当前已落地 30 种经典图/路径算法 与 8 种前沿算法。 CH / ALT / Hub Labeling 已有生产级稠密快路径变体(
src/directed/); ALT 的 farthest-first 地标选择会优先为尚未覆盖的非连通分量播种, 避免重复地标削弱启发式;三者均附真实 OSM 路网基准证据(北京驾车网: CH 相对双向 Dijkstra 46.7×,HL 距离查询 0.47 µs(13279×),PHAST 一到全 SSSP 相对全量 Dijkstra 6.27×,many-to-many 64×64 距离表相对逐对 CH 16–27×,RPHAST 目标子集限定再提 7.2–9.4×,见benches/results/osm-real-networks-ch-native-2026-07-08.md、benches/results/osm-alt-hl-native-2026-07-08.md; 2026-07-12 异机复测同量级可复现,见benches/results/osm-suite-native-2026-07-12.md)。HL 支持路径还原 (query_via/query_path)。src/unweighted/bfs.mbtsrc/directed/dfs.mbtsrc/directed/dijkstra.mbtsrc/directed/astar.mbtsrc/directed/bellman_ford.mbtsrc/directed/floyd_warshall.mbtsrc/undirected/kruskal.mbtsrc/undirected/connected_components.mbtsrc/directed/bidirectional_bfs.mbtsrc/directed/topo_sort.mbtsrc/directed/tarjan_scc.mbtsrc/directed/edmonds_karp.mbtsrc/directed/ida_star.mbtsrc/directed/yen.mbtsrc/undirected/kuhn_munkres.mbtsrc/undirected/prim.mbtsrc/directed/dag_shortest_path.mbtsrc/undirected/bridges.mbtsrc/directed/bidirectional_dijkstra.mbtsrc/directed/dijkstra_all.mbtsrc/unweighted/bfs_all.mbtsrc/directed/bellman_ford_paths.mbtsrc/directed/floyd_warshall_paths.mbtsrc/directed/johnson.mbtsrc/directed/dinic.mbtsrc/directed/min_cut.mbtsrc/directed/min_cost_flow.mbtsrc/undirected/hopcroft_karp.mbtsrc/directed/eulerian.mbtsrc/directed/condensation.mbtsrc/advanced/ch.mbt· 生产级src/directed/ch.mbtsrc/advanced/jps.mbtsrc/advanced/alt.mbt· 生产级src/directed/alt.mbtsrc/directed/hub_labels.mbtsrc/directed/phast.mbtsrc/directed/many_to_many.mbtsrc/directed/rphast.mbtsrc/directed/cch.mbtPlayground
Interactive grid pathfinding visualiser, powered by the very library in
src/compiled to wasm-gc:moon build --target wasm-gc --releaselinks thesrc/playgroundexport layer into a ≤ 100 KBplayground.wasm(enforced byscripts/wasm_size_guard.ps1in CI)python -m http.serverfromplayground/web/+ the built.wasm)playground/solver_test.mbtandsrc/playground/*_test.mbtassert the playground answers are identical to the library’spg_osm_*graph export layer; click any two points to snap to the nearest road nodes and run unidirectional vs. bidirectional Dijkstra with live settled-node and timing comparison (identical costs cross-checked on every query). The network artifact is reproducible viapython3 scripts/build_playground_osm.py对应需求: R16 (WASM Playground) · R26 (实时 JPS Playground 杀手锏)。
Formal verification
The
src/proofs/package encodes post-condition predicates as ordinary MoonBit functions and tests them in CI. These predicates are the contract vocabulary thatmoon proveannotations can reference as the verifier surface settles. Official MoonBit documentation currently describesmoon proveas experimental, backed by Why3 and SMT solvers.bfsdijkstramoon provestatic dischargeRun the current evidence chain with:
Latest local evidence is stored in
docs/verification/latest-proof-evidence.md. On this machine, runtime proof predicates passed,moon prove --helpis available, and static discharge is blocked because Why3 is not onPATH.对应需求: R8 (形式化证明撒手锏) · R25 (答辩故事张力)。
Benchmarks
moonbit-pathfinding以benches/目录承载可复现、可 CI 回归的性能证据:moon testsmoke guards 验证工作负载正确性,moon bench原生@bench.T块记录更低噪声的算法级时间。当前基准覆盖 4 个 MVP 算法:benches/bfs_bench/bfs_bench.mbtbenches/dijkstra_bench/dijkstra_bench.mbtbenches/astar_bench/astar_bench.mbtbenches/kruskal_bench/kruskal_bench.mbt运行
每个基准文件都有
test "smoke: ..."和test "bench: ..." (b : @bench.T)两层入口:前者进入普通测试,后者由moon bench采样。scripts/benchmark_native.ps1会生成算法级结果:benches/results/latest-native.md与benches/results/latest-native.json。scripts/benchmark_native_guard.ps1会把当前 native run 写入_build/native-benchmark-guard/临时目录,并和 checked-in baseline 比较 medianmoon benchmean timing,生成benches/results/latest-native-guard.md与benches/results/latest-native-guard.json。scripts/benchmark_smoke.ps1会额外生成可审计结果:benches/results/latest-smoke.md与benches/results/latest-smoke.json。scripts/benchmark_guard.ps1会把当前 smoke run 写入_build/benchmark-guard/临时目录,并和 checked-in baseline 比较 median,生成benches/results/latest-guard.md与benches/results/latest-guard.json。对标 Rust
pathfindingcrate(✅ published head-to-head)A reproducible head-to-head comparison against Rust’s
pathfindingcrate (v4.11.0,cargo --release) is published inbenches/results/latest-rust-comparison.md(run viapwsh scripts/rust_comparison.ps1; native backend, bit-identical xorshift64 workloads with a golden element-wise cross-check, per-query result signatures verified equal on both sides):Beyond the Rust comparison, checked-in
benches/results/*.jsonartifacts are local regression evidence. Native artifacts recordmoon benchstatistics from@bench.Tblocks; smoke artifacts record end-to-end package timing. Both include machine, backend, input size, command output, and methodology so regressions can be discussed with concrete data.The native guard defaults to a 25% regression tolerance. The smoke guard remains available with a deliberately loose 50% default because it times end-to-end
moon test -p ...package execution.OSM 真实路网(✅ landed · Tier-3)
真实 OSM 路网基准已落地(
benches/advanced_bench/osm_alt_bench.mbt, 厦门/北京驾车网):单向/双向 Dijkstra、ALT 双向 A*、CH 四档同批 查询对拍 + 计时,证据归档于benches/results/osm-alt-hl-native-2026-07-08.md与benches/results/osm-real-networks-ch-native-2026-07-08.md(历史:alt-indexed-osm-20260705.md、ch-osm-20260705.md)。任何加速比都必须来自benches/results/中记录的机器、backend、输入和原始计时。Multi-backend consistency · 四后端一致性
This library is built to compile and run identically on all four MoonBit backends:
wasm-gc,js,native, and purewasm(linear memory). Every push tomainand every PR triggers theciworkflow’s 4-backend matrix, which executes the full test suite (2683 cases) on each backend, plus a WASI delivery gate (scripts/wasi_gate.sh) that runs the release wasm artifacts underwasmtimeand byte-diffs the output against the js backend, and a component model gate (scripts/component_gate.sh) that componentizes the core wasm modules via thewasi_snapshot_preview1command adapter (wasm-tools component new), validates the component-model binaries, and runs them underwasmtimewith the same byte-level diff against the js backend. Any output divergence — including snapshot mismatches frominspect(..., content=...)— fails the entire build, giving us a differential test of algorithmic behaviour across backends for free.Backend × Algorithm matrix
Performance evidence
Current benchmark tests are smoke gates, not a published backend comparison. The repository now includes reproducible smoke artifacts under
benches/results/with:Native and smoke regression guards are available through
scripts/benchmark_native_guard.ps1,scripts/benchmark_guard.ps1, and optional local acceptance:The native guard is the lower-noise gate; the smoke guard remains useful for package-level harness regressions.
Target restrictions
Currently no algorithm is backend-restricted. Future additions that rely on backend-specific features (e.g. SIMD intrinsics on native) will declare
supported_targetsin theirmoon.pkg.json. Template follows design.md §15.1.Acknowledgements · 致谢
This project stands on the shoulders of three communities:
moon prove, Markdown-oriented programming, and the three-backend ecosystem that makes this library possible.pathfindingcrate authors (evenfurther & contributors) — for the minimalist “successor function” API philosophy that we ported into MoonBit. Thank you for a decade of principled design in open source.External code reviewers and discussion participants who shaped this library (alphabetical, by GitHub handle) are recorded in
docs/community/as the project grows. Pull requests are warmly welcomed — see CONTRIBUTING.md.For code agents and scripted integrations, see AI_AGENT_USAGE.md.
For the full development story — design tradeoffs, the road-network SOTA climb (Dijkstra → ALT → CH → Hub Labeling), falsified experiments, and the human–AI collaboration record — see the development article (Chinese): docs/zh/development-article.md.
License
Apache-2.0 © 2026 Suquster. See LICENSE.
Benchmark fixtures under
cache/contain map data © OpenStreetMap contributors, retrieved via the Overpass API and redistributed under the ODbL 1.0 license.