migrate-to-rust

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Migrate 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.py
记录实测遥测数据和第一人称工程叙事。

Execution Contract & Portability

执行约定与可移植性

When migrating a repository or local directory (
{github_url}
or
{codebase_path}
), follow these execution rules across agentic harnesses:
  1. 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.)
  2. 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.
  3. Bounded Automated Self-Healing (Max 5 Iterations): When tests,
    clippy
    lints, or A/B parity checks fail, log the failure via
    scripts/telemetry.py
    , 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 in
    migration_telemetry.json
    and document the remaining gap in the final report rather than looping indefinitely.
  4. Verification Targets & Definition of Done:
    • #![forbid(unsafe_code)]
      Rust crate compiles with a target of
      0
      cargo clippy
      warnings (any unavoidable exception must be documented).
    • Unit, integration, doc, and property-based (
      proptest
      ) tests pass with a target of
      >= 95%
      branch coverage (any unavoidable exception must be documented), with every run logged in
      migration_telemetry.json
      .
    • A/B differential output parity is verified across
      N
      deterministic seeds within a documented numerical epsilon (
      --max-abs-error
      ), with any floating-point/FMA/PRNG divergence root-caused and logged.
    • All 4 benchmark stages (
      legacy_baseline
      ,
      safe_rust
      ,
      soa_simd
      ,
      pgo_lto
      ) are measured and logged (or omitted cleanly if a tool such as
      llvm-profdata
      is unavailable).
    • The interactive HTML infographic (
      migration_infographic.html
      ) is rendered via
      scripts/telemetry.py render-infographic
      .
迁移仓库或本地目录(
{github_url}
或
{codebase_path}
)时,在各类 agentic harness 中遵循以下执行规则:
  1. 阶段 0 外部代码确认门禁:克隆外部 仓库并检查其构建文件后,必须向用户展示解析出的遗留构建命令、运行命令和目标目录,并在编译或执行克隆代码前获得 确认。(如果用户明确指示运行本地代码,或阶段 0 已获得确认,则直接继续。)
  2. 阶段 1 -> 阶段 2 连续推进:完成阶段 0 基线采集后,无需在各个里程碑之间暂停,直接从编写架构蓝图(阶段 1)进入 Rust workspace 的实现与验证(阶段 2);前提是宿主环境允许自主执行工具。
  3. 有界自动自愈(最多 5 次迭代):当测试、
    clippy
    lint 或 A/B parity 检查失败时,通过
    scripts/telemetry.py
    记录失败,诊断并修复根因,然后自动重新测试;预算上限为 5 次自愈迭代(或每个阶段 15 分钟)。如果预算耗尽后仍有任何测试或随机种子存在偏差,则将部分状态记录到
    migration_telemetry.json
    ,并在最终报告中记录剩余差距,而不是无限循环。
  4. 验证目标与完成定义:
    • 带有
      #![forbid(unsafe_code)]
      的 Rust crate 编译通过,且
      cargo clippy
      warning 目标为
      0
      (任何不可避免的例外都必须记录)。
    • 单元测试、集成测试、文档测试和基于属性的测试(
      proptest
      )全部通过,分支覆盖率目标为
      >= 95%
      (任何不可避免的例外都必须记录),并通过
      migration_telemetry.json
      记录每次运行。
    • 在文档记录的数值 epsilon(
      --max-abs-error
      )容差内,验证 A/B 差分输出在
      N
      个确定性随机种子下保持一致;对任何浮点/FMA/PRNG 偏差进行根因分析并记录。
    • 对全部 4 个基准测试阶段(
      legacy_baseline
      、
      safe_rust
      、
      soa_simd
      、
      pgo_lto
      )进行测量和记录;如果
      llvm-profdata
      等工具不可用,则妥善跳过。
    • 通过
      scripts/telemetry.py render-infographic
      渲染交互式 HTML 信息图(
      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:
ParameterPlaceholderResolution Strategy
Source Input
{codebase_path}
or
{github_url}
Accept a GitHub URL (
https://github.com/...
) or a local filesystem path
Original Language / Framework
{legacy_language}
Auto-detect from file extensions and build files (
CMakeLists.txt
,
Makefile
,
meson.build
,
pyproject.toml
,
pom.xml
,
*.f90
,
*.cpp
)
Baseline Run Command
{baseline_run_command}
Identify from
README.md
, CI workflows (
.github/workflows/*.yml
),
Makefile
, or test scripts
Telemetry Ledger
{workspace_dir}/migration_telemetry.json
Initialized via
scripts/telemetry.py init
at the start of Stage 0
从仓库或目录中解析以下上下文参数:
参数占位符解析策略
源输入
{codebase_path}
或
{github_url}
接受 GitHub URL(
https://github.com/...
)或本地文件系统路径
原始语言/框架
{legacy_language}
根据文件扩展名和构建文件(
CMakeLists.txt
、
Makefile
、
meson.build
、
pyproject.toml
、
pom.xml
、
*.f90
、
*.cpp
)自动检测
基线运行命令
{baseline_run_command}
从
README.md
、CI workflow(
.github/workflows/*.yml
)、
Makefile
或测试脚本中识别
遥测账本
{workspace_dir}/migration_telemetry.json
在阶段 0 开始时通过
scripts/telemetry.py init
初始化

Stage 0 Execution Steps

阶段 0 执行步骤

  1. Clone Repository (if GitHub URL): Choose a clean local directory (default to
    ~/rust_migrations/{repo_name}
    , or inside the current workspace if requested) and run
    git clone {github_url} ~/rust_migrations/{repo_name}
    .
  2. Initialize Telemetry & Scan Legacy Codebase: Run
    scripts/telemetry.py init --telemetry "{workspace_dir}/migration_telemetry.json" --project-name "{project_name}" --legacy-lang "{legacy_language}"
    . Start the
    discovery
    bucket and run
    scripts/telemetry.py scan-codebase --phase before
    on 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.
  3. Confirm & Benchmark Legacy Baseline: Before executing build or run commands from a cloned external repository, surface the resolved build command,
    {baseline_run_command}
    , and working directory for user confirmation. Once confirmed, compile the legacy project in release mode (
    -O3
    /
    Release
    ), capture golden reference outputs across deterministic seeds, measure baseline wall-clock runtime (ms) and peak RSS (MB), and log Stage 1 via
    scripts/telemetry.py log-benchmark --stage legacy_baseline
    .

  1. 克隆仓库(如果提供 GitHub URL):选择一个干净的本地目录 (默认使用
    ~/rust_migrations/{repo_name}
    ,或按要求放在当前 workspace 内),并运行
    git clone {github_url} ~/rust_migrations/{repo_name}
    。
  2. 初始化遥测并扫描遗留代码库:运行
    scripts/telemetry.py init --telemetry "{workspace_dir}/migration_telemetry.json" --project-name "{project_name}" --legacy-lang "{legacy_language}"
    。启动
    discovery
    bucket,并对遗留源代码目录运行
    scripts/telemetry.py scan-codebase --phase before
    ,以记录基线文件数量、代码 LOC、注释密度%、最大文件 LOC、嵌套深度、平均函数长度以及原始指针/内存风险。
  3. 确认并测量遗留基线:在执行克隆外部仓库的构建或运行命令前,向用户展示解析出的构建命令、
    {baseline_run_command}
    和工作目录以供确认。确认后,以 release 模式(
    -O3
    /
    Release
    )编译遗留项目,在确定性随机种子下采集黄金参考输出,测量基线 wall-clock 运行时间(ms)和峰值 RSS(MB),并通过
    scripts/telemetry.py log-benchmark --stage legacy_baseline
    记录阶段 1。

Stage 1: Deep Audit, Opportunity Discovery & Architectural Blueprint

阶段 1:深度审计、机会发现与架构蓝图

Start the
blueprint
timer bucket (
scripts/telemetry.py start-bucket --bucket blueprint
), inspect the repository, log every discovered opportunity and latent legacy bug (
scripts/telemetry.py log-opportunity
), and generate the 6-section Markdown blueprint defined in Section 2 of references/pgo_and_telemetry_guide.md.
Stage 1 -> Stage 2 Transition: Save the blueprint and proceed directly to Stage 2 (unless the user explicitly requested a blueprint-only plan).

启动
blueprint
计时 bucket(
scripts/telemetry.py start-bucket --bucket blueprint
),检查仓库,通过
scripts/telemetry.py log-opportunity
记录每个发现的优化机会和 潜在遗留缺陷,并生成 references/pgo_and_telemetry_guide.md 第 2 节定义的 6 部分 Markdown 架构蓝图。
阶段 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)

步骤 1:搭建 Safe Rust workspace 并移植模块(
rewrite
bucket)

  1. Start the
    rewrite
    timer bucket (
    scripts/telemetry.py start-bucket --bucket rewrite
    ).
  2. Initialize the Rust workspace with
    #![forbid(unsafe_code)]
    in
    src/lib.rs
    and
    src/main.rs
    .
  3. Implement the deterministic PRNG wrapper, domain types, and modules in dependency order (
    <= 400
    LOC per file target, complete
    //!
    and
    ///
    rustdoc with runnable doc-tests).
  4. Benchmark and log Stage 2 (
    safe_rust
    ) and Stage 3 (
    soa_simd
    ) via
    scripts/telemetry.py log-benchmark
    .
  1. 启动
    rewrite
    计时 bucket(
    scripts/telemetry.py start-bucket --bucket rewrite
    )。
  2. 初始化 Rust workspace,并在
    src/lib.rs
    和
    src/main.rs
    中设置
    #![forbid(unsafe_code)]
    。
  3. 按依赖顺序实现确定性 PRNG wrapper、领域类型和模块(目标每文件
    <= 400
    LOC,使用完整的
    //!
    和
    ///
    rustdoc,并提供可运行的 doc-tests)。
  4. 通过
    scripts/telemetry.py log-benchmark
    测量并记录阶段 2(
    safe_rust
    )和阶段 3(
    soa_simd
    )。

Step 2: The Verification Crucible — Test, Fail, Diagnose & Fix (
test_heal
Bucket)

步骤 2:验证试炼——测试、失败、诊断与修复(
test_heal
bucket)

  1. Start the
    test_heal
    timer bucket (
    scripts/telemetry.py start-bucket --bucket test_heal
    ).
  2. Write unit tests, runnable doc-tests, and
    proptest
    boundary tests.
  3. Run
    cargo test --all-targets
    ,
    cargo test --doc
    , and
    cargo clippy --all-targets
    .
  4. Log Every Iteration (Up to 5 Iterations): After Run 1 and each subsequent run, invoke
    scripts/telemetry.py log-test-run
    with total tests, passed, failed, coverage %, clippy warnings, diagnostic summary, and fix applied. Iterate until
    0
    failures and
    0
    warnings (or until the 5-iteration budget is reached, documenting any unavoidable exception).
  1. 启动
    test_heal
    计时 bucket(
    scripts/telemetry.py start-bucket --bucket test_heal
    )。
  2. 编写单元测试、可运行的 doc-tests 和
    proptest
    边界测试。
  3. 运行
    cargo test --all-targets
    、
    cargo test --doc
    和
    cargo clippy --all-targets
    。
  4. 记录每次迭代(最多 5 次迭代):第 1 次运行及之后的每次运行完成后,调用
    scripts/telemetry.py log-test-run
    ,记录测试总数、通过数、失败数、覆盖率%、clippy warning、诊断摘要和已应用的修复。持续迭代,直到失败数为
    0
    且 warning 数为
    0
    ,或达到 5 次迭代预算,并记录任何不可避免的例外。

Step 3: A/B Differential Output Parity (
parity
Bucket)

步骤 3:A/B 差分输出一致性(
parity
bucket)

  1. Start the
    parity
    timer bucket (
    scripts/telemetry.py start-bucket --bucket parity
    ).
  2. Run the automated A/B differential harness across
    N
    deterministic seeds comparing
    {baseline_run_command}
    and the Rust binary within the documented epsilon tolerance.
  3. Log each parity iteration via
    scripts/telemetry.py log-parity-run
    . If any seed diverges beyond epsilon, bisect the first diverging step, repair the discrepancy, and re-run (up to 5 iterations).
  1. 启动
    parity
    计时 bucket(
    scripts/telemetry.py start-bucket --bucket parity
    )。
  2. 在文档记录的 epsilon 容差内,运行自动化 A/B 差分测试工具,覆盖
    N
    个确定性随机种子,对比
    {baseline_run_command}
    与 Rust binary。
  3. 通过
    scripts/telemetry.py log-parity-run
    记录每次一致性迭代。如果任何随机种子的偏差超过 epsilon,则二分定位首个分歧步骤,修复差异并重新运行(最多 5 次迭代)。

Step 4: Profile-Guided Optimization (PGO) & Final Benchmarks (
pgo_bench
Bucket)

步骤 4:Profile-Guided Optimization (PGO) 与最终基准测试(
pgo_bench
bucket)

  1. Start the
    pgo_bench
    timer bucket (
    scripts/telemetry.py start-bucket --bucket pgo_bench
    ).
  2. Execute the LLVM PGO workflow in references/pgo_and_telemetry_guide.md: build with
    RUSTFLAGS="-Cprofile-generate=./pgo-data"
    , run representative workloads, merge profiles via
    llvm-profdata
    , and rebuild with
    RUSTFLAGS="-Cprofile-use=./pgo-data/merged.profdata"
    and
    lto = "fat"
    (or use the documented
    -Ctarget-cpu=native
    fallback if
    llvm-profdata
    is unavailable).
  3. 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 (
    pgo_lto
    ) via
    scripts/telemetry.py log-benchmark --stage pgo_lto
    .
  1. 启动
    pgo_bench
    计时 bucket(
    scripts/telemetry.py start-bucket --bucket pgo_bench
    )。
  2. 执行 references/pgo_and_telemetry_guide.md 中的 LLVM PGO 工作流:使用
    RUSTFLAGS="-Cprofile-generate=./pgo-data"
    构建,运行代表性工作负载,通过
    llvm-profdata
    合并 profile,然后使用
    RUSTFLAGS="-Cprofile-use=./pgo-data/merged.profdata"
    和
    lto = "fat"
    重新构建;如果
    llvm-profdata
    不可用,则使用文档中记录的
    -Ctarget-cpu=native
    fallback。
  3. 验证 PGO binary 上的测试和 A/B parity 仍然通过,然后测量 wall-clock 运行时间和峰值 RSS,并通过
    scripts/telemetry.py log-benchmark --stage pgo_lto
    记录阶段 4。

Step 5: Final Census, First-Person AI Story & Visual Infographic

步骤 5:最终统计、第一人称 AI 故事与可视化信息图

  1. Run
    scripts/telemetry.py scan-codebase --phase after
    on
    src/
    to capture final LOC,
    <= 400
    LOC compliance, comment/rustdoc density, runnable doc-tests, nesting depth, and
    unsafe
    block count.
  2. Log a Before vs. After Code Spotlight (
    scripts/telemetry.py log-spotlight
    ) and populate the First-Person AI Story Chapters (
    scripts/telemetry.py set-story
    ).
  3. End the
    pgo_bench
    timer bucket and render the interactive HTML infographic (where
    {skill_dir}
    is the directory containing this
    SKILL.md
    ):
    bash
    python3 "{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}"
  4. Output a concise executive summary referencing the generated
    migration_infographic.html
    report and key measured before/after metrics.

  1. 对
    src/
    运行
    scripts/telemetry.py scan-codebase --phase after
    ,采集最终 LOC、
    <= 400
    LOC 合规性、注释/rustdoc 密度、可运行的 doc-tests、嵌套深度和
    unsafe
    代码块数量。
  2. 记录迁移前后代码亮点(
    scripts/telemetry.py log-spotlight
    ),并填充第一人称 AI 故事章节(
    scripts/telemetry.py set-story
    )。
  3. 结束
    pgo_bench
    计时 bucket,并渲染交互式 HTML 信息图(
    {skill_dir}
    是包含此
    SKILL.md
    的目录):
    bash
    python3 "{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}"
  4. 输出简洁的 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