migrate-to-rust
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMigrate Legacy Codebases to Safe Rust
将遗留代码库迁移到 Safe Rust
Act as a Systems Architect, Performance Engineer, and Rust Specialist. Your goal
is to migrate legacy codebases into 100% Safe, PGO-tuned Rust while recording
measured telemetry and a first-person engineering narrative via
.
scripts/telemetry.py充当系统架构师、性能工程师和 Rust 专家。你的目标
是将遗留代码库迁移为 100% Safe、经过 PGO 调优的 Rust,同时通过
记录实测遥测数据和第一人称工程叙事。
scripts/telemetry.pyExecution Contract & Portability
执行约定与可移植性
When migrating a repository or local directory ( or
), follow these execution rules across agentic harnesses:
{github_url}{codebase_path}- Stage 0 External Code Confirmation Gate: After cloning an external repository and inspecting its build files, present the resolved legacy build command, run command, and target directory to the user and obtain confirmation before compiling or executing cloned code. (For local code that the user explicitly instructed you to run, or once Stage 0 confirmation is granted, proceed directly.)
- Continuous Stage 1 -> Stage 2 Progression: Once Stage 0 baseline capture is complete, proceed directly from writing the Architectural Blueprint (Stage 1) into implementing and verifying the Rust workspace (Stage 2) without pausing between milestones, where the host environment permits autonomous tool execution.
- Bounded Automated Self-Healing (Max 5 Iterations): When tests, lints, or A/B parity checks fail, log the failure via
clippy, diagnose and fix the root cause, and re-test automatically up to a budget of 5 self-healing iterations (or 15 minutes per phase). If any test or seed still diverges after the budget is exhausted, record the partial state inscripts/telemetry.pyand document the remaining gap in the final report rather than looping indefinitely.migration_telemetry.json - Verification Targets & Definition of Done:
- Rust crate compiles with a target of
#![forbid(unsafe_code)]0warnings (any unavoidable exception must be documented).cargo clippy - Unit, integration, doc, and property-based () tests pass with a target of
proptestbranch coverage (any unavoidable exception must be documented), with every run logged in>= 95%.migration_telemetry.json - A/B differential output parity is verified across deterministic seeds within a documented numerical epsilon (
N), with any floating-point/FMA/PRNG divergence root-caused and logged.--max-abs-error - All 4 benchmark stages (,
legacy_baseline,safe_rust,soa_simd) are measured and logged (or omitted cleanly if a tool such aspgo_ltois unavailable).llvm-profdata - The interactive HTML infographic () is rendered via
migration_infographic.html.scripts/telemetry.py render-infographic
迁移仓库或本地目录( 或
)时,在各类 agentic harness 中遵循以下执行规则:
{github_url}{codebase_path}- 阶段 0 外部代码确认门禁:克隆外部 仓库并检查其构建文件后,必须向用户展示解析出的遗留构建命令、运行命令和目标目录,并在编译或执行克隆代码前获得 确认。(如果用户明确指示运行本地代码,或阶段 0 已获得确认,则直接继续。)
- 阶段 1 -> 阶段 2 连续推进:完成阶段 0 基线采集后,无需在各个里程碑之间暂停,直接从编写架构蓝图(阶段 1)进入 Rust workspace 的实现与验证(阶段 2);前提是宿主环境允许自主执行工具。
- 有界自动自愈(最多 5 次迭代):当测试、lint 或 A/B parity 检查失败时,通过
clippy记录失败,诊断并修复根因,然后自动重新测试;预算上限为 5 次自愈迭代(或每个阶段 15 分钟)。如果预算耗尽后仍有任何测试或随机种子存在偏差,则将部分状态记录到scripts/telemetry.py,并在最终报告中记录剩余差距,而不是无限循环。migration_telemetry.json - 验证目标与完成定义:
- 带有 的 Rust crate 编译通过,且
#![forbid(unsafe_code)]warning 目标为cargo clippy(任何不可避免的例外都必须记录)。0 - 单元测试、集成测试、文档测试和基于属性的测试()全部通过,分支覆盖率目标为
proptest(任何不可避免的例外都必须记录),并通过>= 95%记录每次运行。migration_telemetry.json - 在文档记录的数值 epsilon()容差内,验证 A/B 差分输出在
--max-abs-error个确定性随机种子下保持一致;对任何浮点/FMA/PRNG 偏差进行根因分析并记录。N - 对全部 4 个基准测试阶段(、
legacy_baseline、safe_rust、soa_simd)进行测量和记录;如果pgo_lto等工具不可用,则妥善跳过。llvm-profdata - 通过 渲染交互式 HTML 信息图(
scripts/telemetry.py render-infographic)。migration_infographic.html
- 带有
End-to-End Workflow Checklist
端到端工作流检查清单
Copy this checklist to track progress across the three stages (detailed command
recipes and architectural specifications are in
references/pgo_and_telemetry_guide.md):
markdown
- [ ] Stage 0: Acquire repo, initialize `migration_telemetry.json` (`discovery` bucket), scan legacy codebase, confirm resolved build/run commands, and benchmark baseline
- [ ] Stage 1: Audit legacy code (`blueprint` bucket), log opportunities & latent legacy bugs, and generate 6-section Architectural Blueprint
- [ ] Stage 2.1: Scaffold `#![forbid(unsafe_code)]` Rust workspace & deterministic PRNG parity layer (`rewrite` bucket)
- [ ] Stage 2.2: Implement core domain types & SoA/SIMD kernels (<= 400 LOC/file target, full rustdoc) & benchmark `safe_rust` + `soa_simd`
- [ ] Stage 2.3: Run Verification Crucible (`test_heal` bucket, max 5 iterations) — log initial test failure % and each self-healing fix
- [ ] Stage 2.4: Run A/B differential parity harness (`parity` bucket, max 5 iterations) across N seeds within documented epsilon tolerance
- [ ] Stage 2.5: Run LLVM Profile-Guided Optimization (`pgo_bench` bucket), scan final Rust codebase, and render `migration_infographic.html`复制此检查清单,以跟踪三个阶段的进度(详细命令配方和架构规范见
references/pgo_and_telemetry_guide.md):
markdown
- [ ] 阶段 0:获取仓库,初始化 `migration_telemetry.json`(`discovery` bucket),扫描遗留代码库,确认解析出的构建/运行命令,并测量性能基准
- [ ] 阶段 1:审计遗留代码(`blueprint` bucket),记录优化机会与潜在遗留缺陷,并生成包含 6 个部分的架构蓝图
- [ ] 阶段 2.1:搭建带有 `#![forbid(unsafe_code)]` 的 Rust workspace 和确定性 PRNG parity 层(`rewrite` bucket)
- [ ] 阶段 2.2:实现核心领域类型与 SoA/SIMD 内核(目标每文件 <= 400 LOC,提供完整 rustdoc),并测量 `safe_rust` + `soa_simd`
- [ ] 阶段 2.3:运行验证试炼(`test_heal` bucket,最多 5 次迭代)——记录初始测试失败率及每次自愈修复
- [ ] 阶段 2.4:运行 A/B 差分一致性测试工具(`parity` bucket,最多 5 次迭代),在文档记录的 epsilon 容差内覆盖 N 个随机种子
- [ ] 阶段 2.5:运行 LLVM Profile-Guided Optimization(`pgo_bench` bucket),扫描最终 Rust 代码库,并渲染 `migration_infographic.html`Stage 0: Repository Acquisition, Telemetry Init & Legacy Baseline
阶段 0:仓库获取、遥测初始化与遗留基线
Resolve context parameters from the repository or directory:
| Parameter | Placeholder | Resolution Strategy |
|---|---|---|
| Source Input | | Accept a GitHub URL ( |
| Original Language / Framework | | Auto-detect from file extensions and build files ( |
| Baseline Run Command | | Identify from |
| Telemetry Ledger | | Initialized via |
从仓库或目录中解析以下上下文参数:
| 参数 | 占位符 | 解析策略 |
|---|---|---|
| 源输入 | | 接受 GitHub URL( |
| 原始语言/框架 | | 根据文件扩展名和构建文件( |
| 基线运行命令 | | 从 |
| 遥测账本 | | 在阶段 0 开始时通过 |
Stage 0 Execution Steps
阶段 0 执行步骤
- Clone Repository (if GitHub URL): Choose a clean local directory
(default to , or inside the current workspace if requested) and run
~/rust_migrations/{repo_name}.git clone {github_url} ~/rust_migrations/{repo_name} - Initialize Telemetry & Scan Legacy Codebase: Run . Start the
scripts/telemetry.py init --telemetry "{workspace_dir}/migration_telemetry.json" --project-name "{project_name}" --legacy-lang "{legacy_language}"bucket and rundiscoveryon the legacy source directory to record baseline file count, code LOC, comment density %, max file LOC, nesting depth, average function length, and raw pointer/memory hazards.scripts/telemetry.py scan-codebase --phase before - Confirm & Benchmark Legacy Baseline: Before executing build or run
commands from a cloned external repository, surface the resolved build
command, , and working directory for user confirmation. Once confirmed, compile the legacy project in release mode (
{baseline_run_command}/-O3), capture golden reference outputs across deterministic seeds, measure baseline wall-clock runtime (ms) and peak RSS (MB), and log Stage 1 viaRelease.scripts/telemetry.py log-benchmark --stage legacy_baseline
- 克隆仓库(如果提供 GitHub URL):选择一个干净的本地目录
(默认使用 ,或按要求放在当前 workspace 内),并运行
~/rust_migrations/{repo_name}。git clone {github_url} ~/rust_migrations/{repo_name} - 初始化遥测并扫描遗留代码库:运行 。启动
scripts/telemetry.py init --telemetry "{workspace_dir}/migration_telemetry.json" --project-name "{project_name}" --legacy-lang "{legacy_language}"bucket,并对遗留源代码目录运行discovery,以记录基线文件数量、代码 LOC、注释密度%、最大文件 LOC、嵌套深度、平均函数长度以及原始指针/内存风险。scripts/telemetry.py scan-codebase --phase before - 确认并测量遗留基线:在执行克隆外部仓库的构建或运行命令前,向用户展示解析出的构建命令、和工作目录以供确认。确认后,以 release 模式(
{baseline_run_command}/-O3)编译遗留项目,在确定性随机种子下采集黄金参考输出,测量基线 wall-clock 运行时间(ms)和峰值 RSS(MB),并通过Release记录阶段 1。scripts/telemetry.py log-benchmark --stage legacy_baseline
Stage 1: Deep Audit, Opportunity Discovery & Architectural Blueprint
阶段 1:深度审计、机会发现与架构蓝图
Start the timer bucket (), inspect the repository, log every discovered opportunity and
latent legacy bug (), and generate the
6-section Markdown blueprint defined in Section 2 of
references/pgo_and_telemetry_guide.md.
blueprintscripts/telemetry.py start-bucket --bucket blueprintscripts/telemetry.py log-opportunityStage 1 -> Stage 2 Transition: Save the blueprint and proceed directly to
Stage 2 (unless the user explicitly requested a blueprint-only plan).
启动 计时 bucket(),检查仓库,通过 记录每个发现的优化机会和
潜在遗留缺陷,并生成 references/pgo_and_telemetry_guide.md 第 2 节定义的 6 部分 Markdown 架构蓝图。
blueprintscripts/telemetry.py start-bucket --bucket blueprintscripts/telemetry.py log-opportunity阶段 1 -> 阶段 2 转换:保存蓝图并直接进入
阶段 2(除非用户明确要求仅提供蓝图计划)。
Stage 2: Phased Safe Rust Implementation, Self-Healing, PGO & Infographic
阶段 2:分阶段 Safe Rust 实现、自愈、PGO 与信息图
Follow the command recipes and core engineering standards in
references/pgo_and_telemetry_guide.md
for each step:
按照 references/pgo_and_telemetry_guide.md
中的命令配方和核心工程标准执行每个步骤:
Step 1: Scaffold Safe Rust Workspace & Port Modules (rewrite
Bucket)
rewrite步骤 1:搭建 Safe Rust workspace 并移植模块(rewrite
bucket)
rewrite- Start the timer bucket (
rewrite).scripts/telemetry.py start-bucket --bucket rewrite - Initialize the Rust workspace with in
#![forbid(unsafe_code)]andsrc/lib.rs.src/main.rs - Implement the deterministic PRNG wrapper, domain types, and modules in
dependency order (LOC per file target, complete
<= 400and//!rustdoc with runnable doc-tests)./// - Benchmark and log Stage 2 () and Stage 3 (
safe_rust) viasoa_simd.scripts/telemetry.py log-benchmark
- 启动 计时 bucket(
rewrite)。scripts/telemetry.py start-bucket --bucket rewrite - 初始化 Rust workspace,并在 和
src/lib.rs中设置src/main.rs。#![forbid(unsafe_code)] - 按依赖顺序实现确定性 PRNG wrapper、领域类型和模块(目标每文件
LOC,使用完整的
<= 400和//!rustdoc,并提供可运行的 doc-tests)。/// - 通过 测量并记录阶段 2(
scripts/telemetry.py log-benchmark)和阶段 3(safe_rust)。soa_simd
Step 2: The Verification Crucible — Test, Fail, Diagnose & Fix (test_heal
Bucket)
test_heal步骤 2:验证试炼——测试、失败、诊断与修复(test_heal
bucket)
test_heal- Start the timer bucket (
test_heal).scripts/telemetry.py start-bucket --bucket test_heal - Write unit tests, runnable doc-tests, and boundary tests.
proptest - Run ,
cargo test --all-targets, andcargo test --doc.cargo clippy --all-targets - Log Every Iteration (Up to 5 Iterations): After Run 1 and each
subsequent run, invoke with total tests, passed, failed, coverage %, clippy warnings, diagnostic summary, and fix applied. Iterate until
scripts/telemetry.py log-test-runfailures and0warnings (or until the 5-iteration budget is reached, documenting any unavoidable exception).0
- 启动 计时 bucket(
test_heal)。scripts/telemetry.py start-bucket --bucket test_heal - 编写单元测试、可运行的 doc-tests 和 边界测试。
proptest - 运行 、
cargo test --all-targets和cargo test --doc。cargo clippy --all-targets - 记录每次迭代(最多 5 次迭代):第 1 次运行及之后的每次运行完成后,调用 ,记录测试总数、通过数、失败数、覆盖率%、clippy warning、诊断摘要和已应用的修复。持续迭代,直到失败数为
scripts/telemetry.py log-test-run且 warning 数为0,或达到 5 次迭代预算,并记录任何不可避免的例外。0
Step 3: A/B Differential Output Parity (parity
Bucket)
parity步骤 3:A/B 差分输出一致性(parity
bucket)
parity- Start the timer bucket (
parity).scripts/telemetry.py start-bucket --bucket parity - Run the automated A/B differential harness across deterministic seeds comparing
Nand the Rust binary within the documented epsilon tolerance.{baseline_run_command} - Log each parity iteration via . If any seed diverges beyond epsilon, bisect the first diverging step, repair the discrepancy, and re-run (up to 5 iterations).
scripts/telemetry.py log-parity-run
- 启动 计时 bucket(
parity)。scripts/telemetry.py start-bucket --bucket parity - 在文档记录的 epsilon 容差内,运行自动化 A/B 差分测试工具,覆盖 个确定性随机种子,对比
N与 Rust binary。{baseline_run_command} - 通过 记录每次一致性迭代。如果任何随机种子的偏差超过 epsilon,则二分定位首个分歧步骤,修复差异并重新运行(最多 5 次迭代)。
scripts/telemetry.py log-parity-run
Step 4: Profile-Guided Optimization (PGO) & Final Benchmarks (pgo_bench
Bucket)
pgo_bench步骤 4:Profile-Guided Optimization (PGO) 与最终基准测试(pgo_bench
bucket)
pgo_bench- Start the timer bucket (
pgo_bench).scripts/telemetry.py start-bucket --bucket pgo_bench - Execute the LLVM PGO workflow in
references/pgo_and_telemetry_guide.md:
build with , run representative workloads, merge profiles via
RUSTFLAGS="-Cprofile-generate=./pgo-data", and rebuild withllvm-profdataandRUSTFLAGS="-Cprofile-use=./pgo-data/merged.profdata"(or use the documentedlto = "fat"fallback if-Ctarget-cpu=nativeis unavailable).llvm-profdata - Verify that tests and A/B parity still pass on the PGO binary, then measure
wall-clock runtime and peak RSS and log Stage 4 () via
pgo_lto.scripts/telemetry.py log-benchmark --stage pgo_lto
- 启动 计时 bucket(
pgo_bench)。scripts/telemetry.py start-bucket --bucket pgo_bench - 执行 references/pgo_and_telemetry_guide.md
中的 LLVM PGO 工作流:使用 构建,运行代表性工作负载,通过
RUSTFLAGS="-Cprofile-generate=./pgo-data"合并 profile,然后使用llvm-profdata和RUSTFLAGS="-Cprofile-use=./pgo-data/merged.profdata"重新构建;如果lto = "fat"不可用,则使用文档中记录的llvm-profdatafallback。-Ctarget-cpu=native - 验证 PGO binary 上的测试和 A/B parity 仍然通过,然后测量 wall-clock 运行时间和峰值 RSS,并通过 记录阶段 4。
scripts/telemetry.py log-benchmark --stage pgo_lto
Step 5: Final Census, First-Person AI Story & Visual Infographic
步骤 5:最终统计、第一人称 AI 故事与可视化信息图
-
Runon
scripts/telemetry.py scan-codebase --phase afterto capture final LOC,src/LOC compliance, comment/rustdoc density, runnable doc-tests, nesting depth, and<= 400block count.unsafe -
Log a Before vs. After Code Spotlight () and populate the First-Person AI Story Chapters (
scripts/telemetry.py log-spotlight).scripts/telemetry.py set-story -
End thetimer bucket and render the interactive HTML infographic (where
pgo_benchis the directory containing this{skill_dir}):SKILL.mdbashpython3 "{skill_dir}/scripts/telemetry.py" render-infographic \ --telemetry "{workspace_dir}/migration_telemetry.json" \ --out "{output_dir}/migration_infographic.html" \ --scope-summary "{short_summary_of_ported_modules}" -
Output a concise executive summary referencing the generatedreport and key measured before/after metrics.
migration_infographic.html
-
对运行
src/,采集最终 LOC、scripts/telemetry.py scan-codebase --phase afterLOC 合规性、注释/rustdoc 密度、可运行的 doc-tests、嵌套深度和<= 400代码块数量。unsafe -
记录迁移前后代码亮点(),并填充第一人称 AI 故事章节(
scripts/telemetry.py log-spotlight)。scripts/telemetry.py set-story -
结束计时 bucket,并渲染交互式 HTML 信息图(
pgo_bench是包含此{skill_dir}的目录):SKILL.mdbashpython3 "{skill_dir}/scripts/telemetry.py" render-infographic \ --telemetry "{workspace_dir}/migration_telemetry.json" \ --out "{output_dir}/migration_infographic.html" \ --scope-summary "{short_summary_of_ported_modules}" -
输出简洁的 executive summary,引用已生成的报告以及关键的迁移前后实测指标。
migration_infographic.html
Bundled Resources
附带资源
- Telemetry & Infographic CLI:
scripts/telemetry.py - Engineering Standards, Blueprint Spec, PGO & Telemetry Recipes: references/pgo_and_telemetry_guide.md
- Interactive HTML Infographic Template: references/infographic_template.html
- 遥测与信息图 CLI:
scripts/telemetry.py - 工程标准、Blueprint 规范、PGO 与遥测配方: references/pgo_and_telemetry_guide.md
- 交互式 HTML 信息图模板: references/infographic_template.html