Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install migrate-to-rust@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin migrate-to-rust v1.0.0 follows the Agent Plugins spec.
gh skills-hub install migrate-to-rust Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/migrate-to-rust/ Extract the ZIP to .github/skills/ in your repo. The folder name must match migrate-to-rust for Copilot to auto-discover it.
Skill Files (4)
SKILL.md 12.2 KB
---
name: migrate-to-rust
metadata:
version: "1.0.0"
category: ApplicationDevelopment
description: >-
Clones, analyzes, plans, and migrates legacy codebases (C++, Fortran, Java,
Python, C, Shell) from a GitHub URL or local directory to a modern,
high-performance, deterministic, 100% Safe Rust architecture, tracking live
telemetry across every task bucket, test failure/fix cycle, and
Profile-Guided Optimization (PGO) stage, and producing a first-person AI
storytelling report and interactive HTML infographic. Use when migrating a
GitHub repository or local codebase to Rust, porting legacy C++, Fortran,
Python, or Java workloads to memory-safe Rust, designing Struct-of-Arrays
(SoA) or SIMD Rust architectures, or optimizing Rust ports with LLVM PGO.
Don't use for unrelated non-Rust refactoring or single-line syntax questions.
---
# Migrate Legacy Codebases to 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`](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`](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`.
## 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](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`
```
--------------------------------------------------------------------------------
## Stage 0: Repository Acquisition, Telemetry Init & Legacy Baseline
Resolve context parameters from the repository or directory:
Parameter | Placeholder | Resolution 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
### Stage 0 Execution Steps
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`.
--------------------------------------------------------------------------------
## Stage 1: Deep Audit, Opportunity Discovery & Architectural Blueprint
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](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).
--------------------------------------------------------------------------------
## Stage 2: Phased Safe Rust Implementation, Self-Healing, PGO & Infographic
Follow the command recipes and core engineering standards in
[references/pgo_and_telemetry_guide.md](references/pgo_and_telemetry_guide.md)
for each step:
### Step 1: Scaffold Safe Rust Workspace & Port Modules (`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`.
### Step 2: The Verification Crucible — Test, Fail, Diagnose & Fix (`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).
### Step 3: A/B Differential Output Parity (`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).
### Step 4: Profile-Guided Optimization (PGO) & Final Benchmarks (`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](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`.
### Step 5: Final Census, First-Person AI Story & Visual Infographic
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.
--------------------------------------------------------------------------------
## Bundled Resources
- **Telemetry & Infographic CLI**:
[`scripts/telemetry.py`](scripts/telemetry.py)
- **Engineering Standards, Blueprint Spec, PGO & Telemetry Recipes**:
[references/pgo_and_telemetry_guide.md](references/pgo_and_telemetry_guide.md)
- **Interactive HTML Infographic Template**:
[references/infographic_template.html](references/infographic_template.html)
infographic_template.html 61.5 KB
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Safe Rust Migration Report & Infographic</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2064%2064%22%20role%3D%22img%22%20aria-label%3D%22Migrate%20to%20Rust%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20rx%3D%2214%22%20fill%3D%22%23b7410e%22/%3E%3Crect%20x%3D%2230.5%22%20y%3D%228%22%20width%3D%223%22%20height%3D%2235%22%20rx%3D%221.5%22%20fill%3D%22%23fff%22/%3E%3Cpath%20d%3D%22M35%2012c9%204%2014%2013%2014%2025H35z%22%20fill%3D%22%23fff%22/%3E%3Cpath%20d%3D%22M29%2016c-7%204-11%2011-11%2021h11z%22%20fill%3D%22%23fed7aa%22/%3E%3Cpath%20d%3D%22M2%2037l6%205h48l-6%2011H14L5%2043z%22%20fill%3D%22%23fff%22/%3E%3C/svg%3E" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
<style>
:root,
html[data-theme="light"] {
--bg-page: #f8fafc;
--bg-surface: #ffffff;
--bg-subtle: #f1f5f9;
--bg-hover: #e2e8f0;
--bg-code: #0f172a;
--text-code: #f8fafc;
--text-primary: #0f172a;
--text-secondary: #475569;
--text-muted: #64748b;
--border-color: #e2e8f0;
--border-strong: #cbd5e1;
--accent-primary: #2563eb;
--accent-primary-hover: #1d4ed8;
--accent-primary-soft: #eff6ff;
--accent-primary-text: #1e40af;
--accent-success: #059669;
--accent-success-soft: #ecfdf5;
--accent-success-text: #065f46;
--accent-warning: #d97706;
--accent-warning-soft: #fffbeb;
--accent-warning-text: #92400e;
--accent-danger: #dc2626;
--accent-danger-soft: #fef2f2;
--accent-danger-text: #991b1b;
--shadow-sm: 0 1px 2px 0 rgba(15, 23, 42, 0.05);
--shadow-md: 0 4px 12px -2px rgba(15, 23, 42, 0.08);
}
html[data-theme="dark"] {
--bg-page: #0b0f19;
--bg-surface: #111827;
--bg-subtle: #1e293b;
--bg-hover: #334155;
--bg-code: #090d16;
--text-code: #e2e8f0;
--text-primary: #f8fafc;
--text-secondary: #cbd5e1;
--text-muted: #94a3b8;
--border-color: #1e293b;
--border-strong: #334155;
--accent-primary: #3b82f6;
--accent-primary-hover: #60a5fa;
--accent-primary-soft: rgba(59, 130, 246, 0.14);
--accent-primary-text: #93c5fd;
--accent-success: #10b981;
--accent-success-soft: rgba(16, 185, 129, 0.14);
--accent-success-text: #6ee7b7;
--accent-warning: #f59e0b;
--accent-warning-soft: rgba(245, 158, 11, 0.14);
--accent-warning-text: #fcd34d;
--accent-danger: #ef4444;
--accent-danger-soft: rgba(239, 68, 68, 0.14);
--accent-danger-text: #fca5a5;
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
--shadow-md: 0 4px 12px -2px rgba(0, 0, 0, 0.45);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background-color: var(--bg-page);
color: var(--text-primary);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
transition: background-color 0.2s ease, color 0.2s ease;
}
code, pre, .mono {
font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
pre {
white-space: pre-wrap;
word-break: break-word;
margin: 0;
}
a {
color: var(--accent-primary);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.container {
max-width: 1140px;
margin: 0 auto;
padding: 0 24px;
}
/* Sticky Top Bar */
.topbar {
position: sticky;
top: 0;
z-index: 40;
background: var(--bg-surface);
border-bottom: 1px solid var(--border-color);
box-shadow: var(--shadow-sm);
}
.topbar-inner {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 14px;
padding: 12px 0;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-logo {
width: 36px;
height: 36px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-shadow: var(--shadow-sm);
}
.brand-title {
font-size: 16px;
font-weight: 800;
letter-spacing: -0.02em;
margin: 0;
color: var(--text-primary);
}
.nav-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.tab-group {
display: flex;
align-items: center;
gap: 4px;
background: var(--bg-subtle);
padding: 4px;
border-radius: 10px;
border: 1px solid var(--border-color);
}
.tab-btn {
border: none;
background: transparent;
color: var(--text-secondary);
font-family: inherit;
font-size: 12.5px;
font-weight: 600;
padding: 6px 12px;
border-radius: 7px;
cursor: pointer;
transition: all 0.15s ease;
}
.tab-btn:hover {
color: var(--text-primary);
}
.tab-btn.active {
background: var(--bg-surface);
color: var(--accent-primary);
box-shadow: var(--shadow-sm);
}
.theme-toggle {
border: 1px solid var(--border-color);
background: var(--bg-surface);
color: var(--text-secondary);
font-family: inherit;
font-size: 12.5px;
font-weight: 600;
padding: 6px 11px;
border-radius: 9px;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
transition: all 0.15s ease;
}
.theme-toggle:hover {
background: var(--bg-subtle);
color: var(--text-primary);
}
.badge {
display: inline-flex;
align-items: center;
font-size: 11.5px;
font-weight: 600;
padding: 3px 9px;
border-radius: 999px;
white-space: nowrap;
}
.badge-primary {
background: var(--accent-primary-soft);
color: var(--accent-primary-text);
}
.badge-success {
background: var(--accent-success-soft);
color: var(--accent-success-text);
}
.badge-warning {
background: var(--accent-warning-soft);
color: var(--accent-warning-text);
}
.badge-danger {
background: var(--accent-danger-soft);
color: var(--accent-danger-text);
}
.section-stack {
padding: 24px 0 60px;
display: flex;
flex-direction: column;
gap: 20px;
}
.card {
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 24px;
box-shadow: var(--shadow-sm);
}
/* 4 Glanceable Hero KPI Pillars */
.kpi-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 14px;
margin-top: 18px;
}
@media (min-width: 880px) {
.kpi-grid {
grid-template-columns: repeat(4, 1fr);
}
}
.kpi-card {
background: var(--bg-subtle);
border: 1px solid var(--border-color);
border-radius: 14px;
padding: 16px 18px;
}
.kpi-card.kpi-featured {
border-color: var(--accent-primary);
background: linear-gradient(180deg, var(--accent-primary-soft) 0%, var(--bg-surface) 75%);
}
.kpi-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
}
.kpi-label {
font-size: 11.5px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--text-muted);
}
.kpi-val {
font-size: 26px;
font-weight: 800;
letter-spacing: -0.02em;
margin-top: 6px;
color: var(--text-primary);
}
.kpi-sub {
font-size: 12px;
color: var(--text-secondary);
margin-top: 4px;
}
/* Collapsible Cards for Progressive Disclosure */
details.collapsible-card {
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 16px;
box-shadow: var(--shadow-sm);
overflow: hidden;
}
details.collapsible-card > summary {
list-style: none;
cursor: pointer;
padding: 16px 22px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
user-select: none;
transition: background-color 0.15s ease;
}
details.collapsible-card > summary::-webkit-details-marker {
display: none;
}
details.collapsible-card > summary:hover {
background: var(--bg-subtle);
}
.summary-left {
display: flex;
flex-direction: column;
gap: 3px;
}
.summary-title {
font-size: 15.5px;
font-weight: 700;
color: var(--text-primary);
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.summary-sub {
font-size: 13px;
color: var(--text-secondary);
}
.summary-toggle-pill {
font-size: 12px;
font-weight: 600;
color: var(--accent-primary-text);
background: var(--accent-primary-soft);
padding: 5px 11px;
border-radius: 8px;
white-space: nowrap;
flex-shrink: 0;
}
details.collapsible-card[open] > summary {
border-bottom: 1px solid var(--border-color);
background: var(--bg-subtle);
}
details.collapsible-card[open] .summary-toggle-pill::after {
content: " ▲";
}
details.collapsible-card:not([open]) .summary-toggle-pill::after {
content: " ▼";
}
.collapsible-body {
padding: 20px 22px;
}
/* Progress Bars */
.bar-track {
width: 100%;
height: 8px;
background: var(--bg-subtle);
border-radius: 999px;
overflow: hidden;
}
.bar-fill {
height: 100%;
border-radius: 999px;
transition: width 0.5s ease;
}
/* Scorecard Grid */
.scorecard-grid {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
}
@media (min-width: 640px) {
.scorecard-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 960px) {
.scorecard-grid {
grid-template-columns: repeat(4, 1fr);
}
}
.score-item {
background: var(--bg-subtle);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 14px;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 10px;
}
/* Code Comparison Boxes */
.code-grid {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
@media (min-width: 880px) {
.code-grid {
grid-template-columns: repeat(2, 1fr);
}
}
.code-box {
border: 1px solid var(--border-color);
border-radius: 12px;
overflow: hidden;
background: var(--bg-code);
color: var(--text-code);
display: flex;
flex-direction: column;
}
.code-box-header {
padding: 10px 14px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
font-size: 12px;
font-weight: 700;
border-bottom: 1px solid #1e293b;
}
.hidden {
display: none !important;
}
</style>
</head>
<body>
<!-- Top Navigation & Mode Toggle -->
<header class="topbar">
<div class="container topbar-inner">
<div class="brand">
<div class="brand-logo" title="Safe Rust Migration Report">
<svg width="36" height="36" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Migrate to Rust">
<rect width="64" height="64" rx="14" fill="#b7410e"/>
<rect x="30.5" y="8" width="3" height="35" rx="1.5" fill="#fff"/>
<path d="M35 12c9 4 14 13 14 25H35z" fill="#fff"/>
<path d="M29 16c-7 4-11 11-11 21h11z" fill="#fed7aa"/>
<path d="M2 37l6 5h48l-6 11H14L5 43z" fill="#fff"/>
</svg>
</div>
<div>
<div style="display:flex; flex-wrap:wrap; align-items:center; gap:6px; margin-bottom:2px;">
<span class="badge badge-primary">migrate-to-rust</span>
<span id="nav-lang-badge" class="badge badge-primary">Language: Unmeasured</span>
<span id="nav-model-badge" class="badge badge-primary hidden"></span>
</div>
<h1 id="nav-project-title" class="brand-title">Rust Migration Telemetry Report</h1>
</div>
</div>
<div class="nav-actions">
<div class="tab-group" role="tablist" aria-label="Report View Mode">
<button onclick="setViewMode('all')" id="btn-mode-all" class="tab-btn active">Overview & Story</button>
<button onclick="setViewMode('executive')" id="btn-mode-executive" class="tab-btn">Executive Summary</button>
<button onclick="setViewMode('technical')" id="btn-mode-technical" class="tab-btn">Code & Benchmarks</button>
</div>
<button onclick="toggleTheme()" id="theme-toggle-btn" class="theme-toggle" title="Switch between Light and Dark theme">
<span id="theme-toggle-icon">🌙</span>
<span id="theme-toggle-label">Dark Mode</span>
</button>
</div>
</div>
</header>
<main class="container section-stack">
<!-- 1. HERO SUMMARY CARD: GLANCEABLE OUTCOMES -->
<section class="card">
<div style="display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:8px; margin-bottom:10px;">
<span class="badge badge-primary">🤖 First-Person Migration Report</span>
<span id="hero-timestamp" style="font-size:12.5px; color:var(--text-muted);">Not measured</span>
</div>
<h2 id="hero-headline" style="margin:0 0 10px; font-size:24px; font-weight:800; letter-spacing:-0.02em; line-height:1.3;">
Unrendered Migration Report Template
</h2>
<p id="hero-narrative" style="margin:0; font-size:14.5px; color:var(--text-secondary); max-width:960px; line-height:1.6;">
Run scripts/telemetry.py render-infographic to inject measured migration telemetry into this template.
</p>
<!-- 4 Glanceable Impact Pillars -->
<div class="kpi-grid">
<!-- Pillar 1: Measured Agent Execution Time -->
<div class="kpi-card kpi-featured">
<div class="kpi-top">
<span class="kpi-label">⏱️ Agent Execution Time</span>
<span id="hero-roi-badge" class="badge badge-primary">Unmeasured</span>
</div>
<div id="hero-total-time" class="kpi-val" style="color:var(--accent-primary);">Not measured</div>
<div id="hero-roi-sub" class="kpi-sub">
No stage timers recorded
</div>
</div>
<!-- Pillar 2: Speedup -->
<div class="kpi-card">
<div class="kpi-top">
<span class="kpi-label">⚡ Final PGO Speedup</span>
<span id="hero-speed-grade" class="badge badge-success">N/A</span>
</div>
<div id="hero-speedup" class="kpi-val" style="color:var(--accent-success);">Not measured</div>
<div id="hero-speed-sub" class="kpi-sub">
Log benchmarks via log-benchmark
</div>
</div>
<!-- Pillar 3: Memory Safety -->
<div class="kpi-card">
<div class="kpi-top">
<span class="kpi-label">🛡️ Memory Safety</span>
<span id="hero-safety-badge" class="badge badge-warning">Unmeasured</span>
</div>
<div id="hero-unsafe" class="kpi-val">Not measured</div>
<div id="hero-safety-sub" class="kpi-sub">
Scan codebase via scan-codebase
</div>
</div>
<!-- Pillar 4: Output Parity -->
<div class="kpi-card">
<div class="kpi-top">
<span class="kpi-label">🎯 Output Replication</span>
<span id="hero-parity-seeds" class="badge badge-primary">Unmeasured</span>
</div>
<div id="hero-parity" class="kpi-val">Not measured</div>
<div id="hero-parity-sub" class="kpi-sub">
No parity runs logged
</div>
</div>
</div>
</section>
<!-- 2. BENCHMARK & TIME SUMMARY (ALWAYS GLANCEABLE) -->
<section id="sec-benchmarks-time" class="card">
<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(320px, 1fr)); gap:24px;">
<!-- Left: 4-Stage PGO Speedup Staircase -->
<div>
<div style="display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:6px;">
<h3 style="margin:0; font-size:17px; font-weight:800;">⚡ 4-Stage Performance Staircase</h3>
<span id="ch5-pgo-badge" class="badge badge-primary">No Benchmarks Logged</span>
</div>
<p id="ch5-narrative" style="margin:0 0 14px; font-size:13px; color:var(--text-secondary);">
Progressive optimization from original baseline to Safe Rust, Struct-of-Arrays (SoA) layout, and Profile-Guided Optimization (PGO).
</p>
<div id="benchmark-staircase" style="display:flex; flex-direction:column; gap:10px;"></div>
</div>
<!-- Right: Measured Agent Execution Time Breakdown -->
<div>
<div style="display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:6px;">
<h3 style="margin:0; font-size:17px; font-weight:800;">⏱️ Agent Execution Time Breakdown</h3>
<span id="ch6-total-badge" class="badge badge-primary">Not measured</span>
</div>
<p style="margin:0 0 14px; font-size:13px; color:var(--text-secondary);">
Measured wall-clock time across the 6 migration stages.
</p>
<div id="time-stacked-bar" style="width:100%; height:14px; border-radius:999px; overflow:hidden; display:flex; border:1px solid var(--border-color); margin-bottom:12px;"></div>
<div id="time-buckets-grid" style="display:grid; grid-template-columns:repeat(2, 1fr); gap:8px;"></div>
</div>
</div>
</section>
<!-- 3. COLLAPSIBLE EXECUTIVE SCORECARD (8 DIMENSIONS BEFORE VS AFTER) -->
<details id="sec-scorecard" class="collapsible-card" open>
<summary>
<div class="summary-left">
<div class="summary-title">
<span>🏅 Executive Transformation Scorecard (Before vs. After)</span>
<span id="overall-before-score" class="badge badge-danger">Legacy: Not measured</span>
<span>→</span>
<span id="overall-after-score" class="badge badge-success">Safe Rust: Not measured</span>
</div>
<div class="summary-sub">
8 engineering dimensions scored 0–100 strictly from measured repository census, compiler checks, test coverage, and benchmarks.
</div>
</div>
<span class="summary-toggle-pill">Scorecard</span>
</summary>
<div class="collapsible-body">
<div id="scorecard-grid" class="scorecard-grid"></div>
</div>
</details>
<!-- 4. COLLAPSIBLE AI MIGRATION STORY CHAPTERS (PROGRESSIVE DISCLOSURE) -->
<div id="sec-story" style="display:flex; flex-direction:column; gap:14px;">
<!-- Chapter 1: Discovery & Hidden Legacy Bugs -->
<details class="collapsible-card" open>
<summary>
<div class="summary-left">
<div class="summary-title">
<span>🔍 Chapter 1: Legacy Audit & Hidden Bugs Discovered</span>
<span id="ch1-bugs-pill" class="badge badge-warning">Audit Not Measured</span>
</div>
<div id="ch1-narrative" class="summary-sub">
Not yet recorded.
</div>
</div>
<span class="summary-toggle-pill">See Details</span>
</summary>
<div class="collapsible-body">
<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(160px, 1fr)); gap:10px; margin-bottom:16px;">
<div style="background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:10px; padding:12px;">
<div style="font-size:11px; color:var(--text-muted); font-weight:700; text-transform:uppercase;">Largest Legacy File</div>
<div id="ch1-max-loc" style="font-size:18px; font-weight:800; color:var(--accent-danger); margin-top:2px;">Not measured</div>
</div>
<div style="background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:10px; padding:12px;">
<div style="font-size:11px; color:var(--text-muted); font-weight:700; text-transform:uppercase;">Legacy Comment Ratio</div>
<div id="ch1-comment-pct" style="font-size:18px; font-weight:800; color:var(--accent-warning); margin-top:2px;">Not measured</div>
</div>
<div style="background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:10px; padding:12px;">
<div style="font-size:11px; color:var(--text-muted); font-weight:700; text-transform:uppercase;">Memory & Pointer Hazards</div>
<div id="ch1-hazards" style="font-size:18px; font-weight:800; color:var(--accent-danger); margin-top:2px;">Not measured</div>
</div>
<div style="background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:10px; padding:12px;">
<div style="font-size:11px; color:var(--text-muted); font-weight:700; text-transform:uppercase;">Latent Bugs Uncovered</div>
<div id="ch1-latent-bugs" style="font-size:18px; font-weight:800; color:var(--accent-warning); margin-top:2px;">Not measured</div>
</div>
</div>
<div id="opportunities-list" style="display:grid; grid-template-columns:repeat(auto-fit, minmax(280px, 1fr)); gap:10px;"></div>
</div>
</details>
<!-- Chapter 2: Modular Architecture & Hygiene -->
<details class="collapsible-card">
<summary>
<div class="summary-left">
<div class="summary-title">
<span>🗂️ Chapter 2: Modular Architecture, Hygiene & Rustdoc</span>
<span id="ch2-doc-delta" class="badge badge-success">Not measured</span>
<span id="ch2-loc-delta" class="badge badge-primary">Not measured</span>
</div>
<div id="ch2-narrative" class="summary-sub">
Not yet recorded.
</div>
</div>
<span class="summary-toggle-pill">See Details</span>
</summary>
<div class="collapsible-body">
<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(250px, 1fr)); gap:14px;">
<div style="background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:12px; padding:14px;">
<div style="font-size:13px; font-weight:700; margin-bottom:8px;">📚 Comment & Doc Density</div>
<div style="font-size:12px; color:var(--text-secondary); display:flex; justify-content:space-between; margin-bottom:4px;">
<span>Before (Legacy)</span>
<span id="ch2-doc-before">Not measured</span>
</div>
<div class="bar-track" style="margin-bottom:8px;">
<div id="ch2-doc-bar-before" class="bar-fill" style="width:0%; background:var(--accent-danger);"></div>
</div>
<div style="font-size:12px; font-weight:600; display:flex; justify-content:space-between; margin-bottom:4px;">
<span>After (Rust + Rustdoc)</span>
<span id="ch2-doc-after" style="color:var(--accent-success);">Not measured</span>
</div>
<div class="bar-track">
<div id="ch2-doc-bar-after" class="bar-fill" style="width:0%; background:var(--accent-success);"></div>
</div>
</div>
<div style="background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:12px; padding:14px;">
<div style="font-size:13px; font-weight:700; margin-bottom:8px;">🗂️ Max File Size (≤400 LOC Rule)</div>
<div style="font-size:12px; color:var(--text-secondary); display:flex; justify-content:space-between; margin-bottom:4px;">
<span>Before (Monolith)</span>
<span id="ch2-loc-before">Not measured</span>
</div>
<div class="bar-track" style="margin-bottom:8px;">
<div id="ch2-loc-bar-before" class="bar-fill" style="width:0%; background:var(--accent-danger);"></div>
</div>
<div style="font-size:12px; font-weight:600; display:flex; justify-content:space-between; margin-bottom:4px;">
<span>After (Modular Rust)</span>
<span id="ch2-loc-after" style="color:var(--accent-success);">Not measured</span>
</div>
<div class="bar-track">
<div id="ch2-loc-bar-after" class="bar-fill" style="width:0%; background:var(--accent-success);"></div>
</div>
</div>
<div style="background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:12px; padding:14px;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
<span style="font-size:13px; font-weight:700;">🧠 Cognitive Simplicity</span>
<span id="ch2-simplicity-delta" class="badge badge-success">Not measured</span>
</div>
<div style="font-size:12px; color:var(--text-secondary); display:flex; justify-content:space-between; margin-bottom:4px;">
<span>Before (Fn / Depth)</span>
<span id="ch2-simp-before">Not measured</span>
</div>
<div class="bar-track" style="margin-bottom:8px;">
<div id="ch2-simp-bar-before" class="bar-fill" style="width:0%; background:var(--accent-danger);"></div>
</div>
<div style="font-size:12px; font-weight:600; display:flex; justify-content:space-between; margin-bottom:4px;">
<span>After (Fn / Depth)</span>
<span id="ch2-simp-after" style="color:var(--accent-success);">Not measured</span>
</div>
<div class="bar-track">
<div id="ch2-simp-bar-after" class="bar-fill" style="width:0%; background:var(--accent-success);"></div>
</div>
</div>
</div>
</div>
</details>
<!-- Chapter 3 & 4: Self-Healing Test Loop & A/B Parity Verification -->
<details class="collapsible-card">
<summary>
<div class="summary-left">
<div class="summary-title">
<span>🧪 Chapters 3 & 4: Self-Healing Test Loop & Side-by-Side Parity Proof</span>
<span id="ch3-initial-fail-badge" class="badge badge-warning">No Test Runs Logged</span>
<span id="ch4-parity-badge" class="badge badge-success">Parity Not Measured</span>
</div>
<div id="ch3-narrative" class="summary-sub">
Not yet recorded.
</div>
</div>
<span class="summary-toggle-pill">See Details</span>
</summary>
<div class="collapsible-body" style="display:flex; flex-direction:column; gap:18px;">
<div>
<h4 style="margin:0 0 8px; font-size:14px; font-weight:700;">Unit, Doc & Property Test Iterations (Self-Repair Audit Trail)</h4>
<div id="test-iterations-list" style="display:flex; flex-direction:column; gap:10px;"></div>
</div>
<div style="padding-top:14px; border-top:1px solid var(--border-color);">
<h4 style="margin:0 0 4px; font-size:14px; font-weight:700;">A/B Differential Output Parity (Legacy vs. Rust Binary)</h4>
<p id="ch4-narrative" style="margin:0 0 10px; font-size:12.5px; color:var(--text-secondary);"></p>
<div id="parity-iterations-list" style="display:flex; flex-direction:column; gap:10px;"></div>
</div>
</div>
</details>
</div>
<!-- 5. TECHNICAL PROOF: BEFORE VS AFTER CODE SPOTLIGHT -->
<details id="sec-technical" class="collapsible-card" open>
<summary>
<div class="summary-left">
<div class="summary-title">
<span>🔬 Code Spotlight: Legacy Implementation vs. Target Rust</span>
</div>
<div id="spotlight-explanation" class="summary-sub">
Not yet recorded.
</div>
</div>
<span class="summary-toggle-pill">Code Diff</span>
</summary>
<div class="collapsible-body">
<div class="code-grid">
<div class="code-box">
<div class="code-box-header" style="background:rgba(220, 38, 38, 0.18); color:#fca5a5;">
<span>❌ BEFORE: Legacy Implementation</span>
<code id="spotlight-legacy-file" style="font-size:11px; color:#cbd5e1;">Not measured</code>
</div>
<pre id="spotlight-legacy-code" style="padding:14px; font-size:12px; line-height:1.55; overflow-x:auto;"></pre>
</div>
<div class="code-box">
<div class="code-box-header" style="background:rgba(16, 185, 129, 0.18); color:#6ee7b7;">
<span>✅ AFTER: Target Rust Implementation</span>
<code id="spotlight-rust-file" style="font-size:11px; color:#cbd5e1;">Not measured</code>
</div>
<pre id="spotlight-rust-code" style="padding:14px; font-size:12px; line-height:1.55; overflow-x:auto;"></pre>
</div>
</div>
</div>
</details>
</main>
<script>
const RAW_INJECTED = "__TELEMETRY_JSON_PLACEHOLDER__";
const DATA = (typeof RAW_INJECTED === "object" && RAW_INJECTED !== null)
? RAW_INJECTED
: null;
// Theme management
function applyTheme(theme) {
const resolved = theme === 'dark' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', resolved);
const iconEl = document.getElementById('theme-toggle-icon');
const labelEl = document.getElementById('theme-toggle-label');
if (iconEl && labelEl) {
if (resolved === 'dark') {
iconEl.textContent = '☀️';
labelEl.textContent = 'Light Mode';
} else {
iconEl.textContent = '🌙';
labelEl.textContent = 'Dark Mode';
}
}
try {
localStorage.setItem('migrate_to_rust_theme', resolved);
} catch (e) {}
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme') || 'light';
applyTheme(current === 'dark' ? 'light' : 'dark');
}
(function initTheme() {
let saved = 'light';
try {
const stored = localStorage.getItem('migrate_to_rust_theme');
if (stored === 'dark' || stored === 'light') saved = stored;
} catch (e) {}
applyTheme(saved);
})();
// Format AI minutes strictly in compact H:MM format
function formatAiDuration(totalMins) {
const m = Math.max(0, Math.round(Number(totalMins) || 0));
const hrs = Math.floor(m / 60);
const mins = m % 60;
return `${hrs}:${String(mins).padStart(2, '0')}`;
}
let currentViewMode = 'all';
function setViewMode(mode, skipUrlUpdate) {
if (!['all', 'executive', 'technical'].includes(mode)) mode = 'all';
currentViewMode = mode;
const secBench = document.getElementById('sec-benchmarks-time');
const secScorecard = document.getElementById('sec-scorecard');
const secStory = document.getElementById('sec-story');
const secTech = document.getElementById('sec-technical');
['all', 'executive', 'technical'].forEach(m => {
const btn = document.getElementById('btn-mode-' + m);
if (!btn) return;
if (m === mode) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
});
if (mode === 'all') {
secBench.classList.remove('hidden');
secScorecard.classList.remove('hidden');
secStory.classList.remove('hidden');
secTech.classList.remove('hidden');
} else if (mode === 'executive') {
secBench.classList.remove('hidden');
secScorecard.classList.remove('hidden');
secStory.classList.remove('hidden');
secTech.classList.add('hidden');
} else if (mode === 'technical') {
secBench.classList.remove('hidden');
secScorecard.classList.add('hidden');
secStory.classList.add('hidden');
secTech.classList.remove('hidden');
secTech.open = true;
}
if (!skipUrlUpdate && typeof window !== 'undefined' && window.history && window.history.replaceState && window.location) {
const base = String(window.location.href || '').split('?')[0];
const nextUrl = mode === 'all' ? base : `${base}?mode=${encodeURIComponent(mode)}`;
window.history.replaceState({ mode }, '', nextUrl);
}
}
function gradeFromScore(s) {
if (s === null || s === undefined) return 'N/A';
if (s >= 95) return 'A+';
if (s >= 90) return 'A';
if (s >= 80) return 'B';
if (s >= 70) return 'C';
if (s >= 55) return 'D';
return 'F';
}
function renderAll() {
if (!DATA) {
const mainEl = document.querySelector('main');
if (mainEl) {
mainEl.innerHTML = `
<section class="card" style="border:2px dashed var(--accent-warning); text-align:center; padding:48px 24px;">
<span class="badge badge-warning" style="margin-bottom:12px;">Unrendered Template (Fail-Closed)</span>
<h2 style="margin:0 0 10px; font-size:22px; font-weight:800;">No Telemetry Data Injected</h2>
<p style="margin:0 auto; max-width:640px; font-size:14px; color:var(--text-secondary); line-height:1.6;">
This HTML file is an unrendered template. Run <code>python3 scripts/telemetry.py render-infographic --telemetry migration_telemetry.json --out migration_infographic.html</code> to inject measured migration telemetry.
</p>
</section>
`;
}
return;
}
const beforeCensus = (DATA.census && DATA.census.before) || {};
const afterCensus = (DATA.census && DATA.census.after) || {};
const hasAfterUnsafe = afterCensus.unsafe_blocks !== null && afterCensus.unsafe_blocks !== undefined;
const hasBeforeHazards = beforeCensus.hazards_count !== null && beforeCensus.hazards_count !== undefined;
document.getElementById('nav-project-title').textContent = DATA.project_name || 'Rust Migration Telemetry Report';
const navLangBadgeEl = document.getElementById('nav-lang-badge');
if (hasAfterUnsafe && Number(afterCensus.unsafe_blocks) === 0) {
navLangBadgeEl.textContent = `${DATA.legacy_language || 'Legacy'} → Safe Rust`;
navLangBadgeEl.className = 'badge badge-success';
} else if (afterCensus.scanned) {
navLangBadgeEl.textContent = `${DATA.legacy_language || 'Legacy'} → Rust`;
navLangBadgeEl.className = 'badge badge-primary';
} else {
navLangBadgeEl.textContent = DATA.legacy_language ? `${DATA.legacy_language} (Target: Rust)` : 'Language: Unmeasured';
navLangBadgeEl.className = 'badge badge-primary';
}
const modelBadgeEl = document.getElementById('nav-model-badge');
if (DATA.model && String(DATA.model).trim() && String(DATA.model).toLowerCase() !== 'unspecified') {
modelBadgeEl.textContent = `Model: ${DATA.model}`;
modelBadgeEl.classList.remove('hidden');
} else {
modelBadgeEl.classList.add('hidden');
}
document.getElementById('hero-timestamp').textContent = (DATA.completed_at && afterCensus.scanned)
? `Completed ${DATA.completed_at}`
: (DATA.completed_at ? `Snapshot ${DATA.completed_at} (Incomplete)` : 'Incomplete / In Progress');
const story = DATA.story || {};
document.getElementById('hero-headline').textContent = story.headline
|| `${DATA.project_name || 'Repository'} Migration Telemetry`;
document.getElementById('hero-narrative').textContent = story.intro
|| 'Narrative summary not yet recorded via set-story.';
document.getElementById('ch1-narrative').textContent = story.ch1_narrative || 'Not yet recorded.';
document.getElementById('ch2-narrative').textContent = story.ch2_narrative || 'Not yet recorded.';
document.getElementById('ch3-narrative').textContent = story.ch3_narrative || 'Not yet recorded.';
document.getElementById('ch4-narrative').textContent = story.ch4_narrative || '';
document.getElementById('ch5-narrative').textContent = story.ch5_narrative
|| 'Progressive benchmark stages from legacy baseline to Rust.';
const benches = DATA.benchmarks || [];
if (benches.length >= 2) {
const baseBench = benches[0];
const finalBench = benches[benches.length - 1];
const speedup = Number(finalBench.speedup || (baseBench.wall_time_ms / Math.max(finalBench.wall_time_ms, 0.001)));
const runtimeSavedPct = ((1 - 1 / Math.max(speedup, 1)) * 100).toFixed(1);
document.getElementById('hero-speedup').textContent = `${speedup.toFixed(2)}x`;
document.getElementById('hero-speed-sub').textContent = `${runtimeSavedPct}% faster (${baseBench.wall_time_ms} → ${finalBench.wall_time_ms} ms)`;
} else {
document.getElementById('hero-speedup').textContent = 'Not measured';
document.getElementById('hero-speed-sub').textContent = 'Log benchmarks via log-benchmark';
document.getElementById('hero-speed-grade').textContent = 'N/A';
}
const safetyBadgeEl = document.getElementById('hero-safety-badge');
if (hasAfterUnsafe) {
document.getElementById('hero-unsafe').textContent = `${afterCensus.unsafe_blocks} Unsafe`;
if (Number(afterCensus.unsafe_blocks) === 0) {
safetyBadgeEl.textContent = '#![forbid(unsafe)]';
safetyBadgeEl.className = 'badge badge-success';
} else {
safetyBadgeEl.textContent = `${afterCensus.unsafe_blocks} unsafe`;
safetyBadgeEl.className = 'badge badge-warning';
}
} else {
document.getElementById('hero-unsafe').textContent = 'Not measured';
safetyBadgeEl.textContent = 'Unmeasured';
safetyBadgeEl.className = 'badge badge-warning';
}
if (hasBeforeHazards && hasAfterUnsafe) {
if (Number(afterCensus.unsafe_blocks) === 0) {
document.getElementById('hero-safety-sub').textContent = `Eliminated ${beforeCensus.hazards_count} legacy pointer/memory hazards`;
} else {
document.getElementById('hero-safety-sub').textContent = `${beforeCensus.hazards_count} legacy hazards → ${afterCensus.unsafe_blocks} Rust unsafe blocks`;
}
} else if (hasBeforeHazards) {
document.getElementById('hero-safety-sub').textContent = `${beforeCensus.hazards_count} legacy hazards scanned (after-scan pending)`;
} else {
document.getElementById('hero-safety-sub').textContent = 'Scan legacy codebase via scan-codebase --phase before';
}
const parityRuns = DATA.parity_iterations || [];
const covText = (afterCensus.branch_coverage_pct !== null && afterCensus.branch_coverage_pct !== undefined)
? `${afterCensus.branch_coverage_pct}% coverage`
: 'Coverage not measured';
if (parityRuns.length > 0) {
const lastParity = parityRuns[parityRuns.length - 1];
const parityPct = lastParity.seeds_tested > 0 ? ((lastParity.seeds_passed / lastParity.seeds_tested) * 100).toFixed(1) : '0.0';
document.getElementById('hero-parity-seeds').textContent = `${lastParity.seeds_tested} Seeds`;
document.getElementById('hero-parity').textContent = `${parityPct}%`;
document.getElementById('hero-parity-sub').textContent = `Verified within tolerance • ${covText}`;
} else {
document.getElementById('hero-parity-seeds').textContent = 'Unmeasured';
document.getElementById('hero-parity').textContent = 'Not measured';
document.getElementById('hero-parity-sub').textContent = `No parity runs logged • ${covText}`;
}
// Measured Agent Time Pillar
const buckets = DATA.time_buckets || [];
const totalMins = buckets.reduce((acc, b) => acc + (b.minutes || 0), 0);
const activeStages = buckets.filter(b => (b.minutes || 0) > 0).length;
const formattedAiTime = formatAiDuration(totalMins);
if (activeStages > 0) {
document.getElementById('hero-total-time').textContent = formattedAiTime;
document.getElementById('hero-roi-badge').textContent = `${activeStages}/${buckets.length || 6} Stages Timed`;
document.getElementById('hero-roi-sub').textContent = `${totalMins} min measured across task buckets`;
} else {
document.getElementById('hero-total-time').textContent = 'Not measured';
document.getElementById('hero-roi-badge').textContent = 'Unmeasured';
document.getElementById('hero-roi-sub').textContent = 'No stage timers recorded';
}
// Render Scorecard Grid
const scorecard = DATA.scorecard || [];
if (scorecard[0] && scorecard[0].after_grade && scorecard[0].after_score !== null && scorecard[0].after_score !== undefined) {
document.getElementById('hero-speed-grade').textContent = scorecard[0].after_grade;
} else {
document.getElementById('hero-speed-grade').textContent = 'N/A';
}
const gridEl = document.getElementById('scorecard-grid');
gridEl.innerHTML = '';
let sumBefore = 0, countBefore = 0, sumAfter = 0, countAfter = 0;
scorecard.forEach(item => {
const hasBefore = item.before_score !== null && item.before_score !== undefined;
const hasAfter = item.after_score !== null && item.after_score !== undefined;
if (hasBefore) { sumBefore += item.before_score; countBefore++; }
if (hasAfter) { sumAfter += item.after_score; countAfter++; }
const beforeScoreText = hasBefore ? `${item.before_score}/100 (${item.before_grade})` : 'Not measured';
const afterScoreText = hasAfter ? `${item.after_score}/100 (${item.after_grade})` : 'Not measured';
const barWidth = hasAfter ? item.after_score : 0;
const card = document.createElement('div');
card.className = "score-item";
card.innerHTML = `
<div>
<div style="display:flex; align-items:center; justify-content:space-between; gap:6px; margin-bottom:8px;">
<span style="font-size:12.5px; font-weight:700;">${item.icon || '📊'} ${item.title}</span>
<span class="badge ${hasAfter ? 'badge-success' : 'badge-warning'}">${item.delta_badge}</span>
</div>
<div style="display:flex; align-items:center; justify-content:space-between; background:var(--bg-surface); border:1px solid var(--border-color); border-radius:9px; padding:8px 10px; margin-bottom:8px;">
<div>
<div style="font-size:10px; text-transform:uppercase; color:var(--text-muted);">Before</div>
<div style="font-size:13px; font-weight:700; color:var(--accent-danger);">${beforeScoreText}</div>
<div style="font-size:11px; color:var(--text-secondary);">${item.before_label}</div>
</div>
<div style="font-weight:700; color:var(--text-muted);">→</div>
<div style="text-align:right;">
<div style="font-size:10px; text-transform:uppercase; color:var(--text-muted);">After (Rust)</div>
<div style="font-size:13px; font-weight:800; color:var(--accent-success);">${afterScoreText}</div>
<div style="font-size:11px; color:var(--accent-success); font-weight:600;">${item.after_label}</div>
</div>
</div>
<div class="bar-track">
<div class="bar-fill" style="width:${barWidth}%; background:var(--accent-success);"></div>
</div>
</div>
<div style="font-size:11.5px; color:var(--text-secondary); line-height:1.45;">
${item.explanation}
</div>
`;
gridEl.appendChild(card);
});
const avgBefore = countBefore > 0 ? Math.round(sumBefore / countBefore) : null;
const avgAfter = countAfter > 0 ? Math.round(sumAfter / countAfter) : null;
document.getElementById('overall-before-score').textContent = avgBefore !== null
? `Legacy: ${avgBefore}/100 (${gradeFromScore(avgBefore)})`
: 'Legacy: Not measured';
document.getElementById('overall-after-score').textContent = avgAfter !== null
? `Safe Rust: ${avgAfter}/100 (${gradeFromScore(avgAfter)})`
: 'Safe Rust: Not measured';
// Chapter 1 Metrics & Opportunities
const latentBugsRaw = beforeCensus.latent_bugs_found;
const hasLatentBugsCount = (
latentBugsRaw !== null &&
latentBugsRaw !== undefined &&
(Boolean(beforeCensus.scanned) || (Array.isArray(DATA.opportunities) && DATA.opportunities.length > 0))
);
if (hasLatentBugsCount) {
const bugsCount = Number(latentBugsRaw);
document.getElementById('ch1-bugs-pill').textContent = `${bugsCount} Hidden Bug${bugsCount === 1 ? '' : 's'} Found`;
document.getElementById('ch1-latent-bugs').textContent = `${bugsCount} Bug${bugsCount === 1 ? '' : 's'}`;
} else {
document.getElementById('ch1-bugs-pill').textContent = 'Audit Not Measured';
document.getElementById('ch1-latent-bugs').textContent = 'Not measured';
}
document.getElementById('ch1-max-loc').textContent = beforeCensus.max_file_loc ? `${beforeCensus.max_file_loc.toLocaleString()} LOC` : 'Not measured';
document.getElementById('ch1-comment-pct').textContent = (beforeCensus.comment_pct !== null && beforeCensus.comment_pct !== undefined) ? `${beforeCensus.comment_pct}%` : 'Not measured';
document.getElementById('ch1-hazards').textContent = (beforeCensus.hazards_count !== null && beforeCensus.hazards_count !== undefined) ? `${beforeCensus.hazards_count} Hazards` : 'Not measured';
const oppEl = document.getElementById('opportunities-list');
oppEl.innerHTML = '';
(DATA.opportunities || []).forEach(opp => {
const cat = String(opp.category || 'architecture');
const isBug = cat === 'latent_bug';
const badgeClass = isBug ? 'badge-danger' : 'badge-primary';
const badgeLabel = isBug ? '🐞 Latent Legacy Bug' : `💡 ${cat.toUpperCase()}`;
const item = document.createElement('div');
item.style.cssText = "background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:12px; padding:14px;";
item.innerHTML = `
<div style="display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:6px;">
<span class="badge ${badgeClass}">${badgeLabel}</span>
<code style="font-size:11px; color:var(--text-muted);">${opp.file || ''}</code>
</div>
<div style="font-size:13px; font-weight:700; margin-bottom:4px;">${opp.title || ''}</div>
<div style="font-size:12.5px; color:var(--text-secondary); line-height:1.5;">${opp.description || ''}</div>
`;
oppEl.appendChild(item);
});
// Chapter 2 Hygiene & Simplicity Bars
const docBeforePct = beforeCensus.comment_pct;
const docAfterPct = afterCensus.comment_pct;
if (docBeforePct !== null && docBeforePct !== undefined && docAfterPct !== null && docAfterPct !== undefined) {
const docIncreasePct = docBeforePct > 0 ? Math.round(((docAfterPct - docBeforePct) / docBeforePct) * 100) : 0;
const docTestsVal = (afterCensus.doc_tests !== null && afterCensus.doc_tests !== undefined) ? afterCensus.doc_tests : null;
document.getElementById('ch2-doc-delta').textContent = docIncreasePct >= 0
? `+${docIncreasePct}% More Docs`
: (docTestsVal !== null ? `${docTestsVal} Doc-Tests` : `${docAfterPct}% Docs`);
const beforeLinesPart = (beforeCensus.comment_loc !== null && beforeCensus.comment_loc !== undefined) ? ` (${beforeCensus.comment_loc} lines)` : '';
const afterLinesPart = (afterCensus.comment_loc !== null && afterCensus.comment_loc !== undefined)
? ` (${afterCensus.comment_loc} lines${docTestsVal !== null ? ` • ${docTestsVal} doc-tests` : ''})`
: (docTestsVal !== null ? ` (${docTestsVal} doc-tests)` : '');
document.getElementById('ch2-doc-before').textContent = `${docBeforePct}%${beforeLinesPart}`;
document.getElementById('ch2-doc-after').textContent = `${docAfterPct}%${afterLinesPart}`;
document.getElementById('ch2-doc-bar-before').style.width = `${Math.min(100, Math.max(5, Math.round(docBeforePct * 2)))}%`;
document.getElementById('ch2-doc-bar-after').style.width = `${Math.min(100, Math.max(5, Math.round(docAfterPct * 2.5)))}%`;
} else {
document.getElementById('ch2-doc-delta').textContent = 'Not measured';
document.getElementById('ch2-doc-before').textContent = docBeforePct !== null && docBeforePct !== undefined ? `${docBeforePct}%` : 'Not measured';
document.getElementById('ch2-doc-after').textContent = docAfterPct !== null && docAfterPct !== undefined ? `${docAfterPct}%` : 'Not measured';
document.getElementById('ch2-doc-bar-before').style.width = '0%';
document.getElementById('ch2-doc-bar-after').style.width = '0%';
}
const maxLocBefore = beforeCensus.max_file_loc || 0;
const maxLocAfter = afterCensus.max_file_loc || 0;
if (maxLocBefore > 0 && maxLocAfter > 0) {
const locDropPct = Math.round(((maxLocBefore - maxLocAfter) / maxLocBefore) * 100);
document.getElementById('ch2-loc-delta').textContent = `${locDropPct >= 0 ? '-' : '+'}${Math.abs(locDropPct)}% Max File LOC`;
document.getElementById('ch2-loc-before').textContent = `${maxLocBefore.toLocaleString()} LOC max`;
document.getElementById('ch2-loc-after').textContent = `${maxLocAfter.toLocaleString()} LOC max`;
document.getElementById('ch2-loc-bar-before').style.width = '95%';
document.getElementById('ch2-loc-bar-after').style.width = `${Math.min(95, Math.max(10, Math.round((maxLocAfter / Math.max(maxLocBefore, 400)) * 95)))}%`;
} else {
document.getElementById('ch2-loc-delta').textContent = 'Not measured';
document.getElementById('ch2-loc-before').textContent = maxLocBefore > 0 ? `${maxLocBefore} LOC` : 'Not measured';
document.getElementById('ch2-loc-after').textContent = maxLocAfter > 0 ? `${maxLocAfter} LOC` : 'Not measured';
document.getElementById('ch2-loc-bar-before').style.width = '0%';
document.getElementById('ch2-loc-bar-after').style.width = '0%';
}
const fnBefore = beforeCensus.avg_fn_loc;
const fnAfter = afterCensus.avg_fn_loc;
const depthBefore = beforeCensus.max_nesting_depth;
const depthAfter = afterCensus.max_nesting_depth;
if (fnBefore !== null && fnBefore !== undefined && fnAfter !== null && fnAfter !== undefined) {
const fnDropPct = fnBefore > 0 ? Math.round(((fnBefore - fnAfter) / fnBefore) * 100) : 0;
const hasDepth = depthBefore !== null && depthBefore !== undefined && depthAfter !== null && depthAfter !== undefined;
document.getElementById('ch2-simplicity-delta').textContent = fnDropPct >= 0
? `-${fnDropPct}% Fn Complexity`
: (hasDepth ? `Depth ${depthBefore} → ${depthAfter}` : `${fnAfter} LOC/fn`);
document.getElementById('ch2-simp-before').textContent = `${fnBefore} LOC/fn${depthBefore !== null && depthBefore !== undefined ? ` • depth ${depthBefore}` : ''}`;
document.getElementById('ch2-simp-after').textContent = `${fnAfter} LOC/fn${depthAfter !== null && depthAfter !== undefined ? ` • depth ${depthAfter}` : ''}`;
const maxFn = Math.max(fnBefore, fnAfter, 1);
document.getElementById('ch2-simp-bar-before').style.width = `${Math.min(95, Math.max(10, Math.round((fnBefore / maxFn) * 90)))}%`;
document.getElementById('ch2-simp-bar-after').style.width = `${Math.min(95, Math.max(10, Math.round((fnAfter / maxFn) * 90)))}%`;
} else {
document.getElementById('ch2-simplicity-delta').textContent = 'Not measured';
document.getElementById('ch2-simp-before').textContent = (fnBefore !== null && fnBefore !== undefined) ? `${fnBefore} LOC/fn` : 'Not measured';
document.getElementById('ch2-simp-after').textContent = (fnAfter !== null && fnAfter !== undefined) ? `${fnAfter} LOC/fn` : 'Not measured';
document.getElementById('ch2-simp-bar-before').style.width = '0%';
document.getElementById('ch2-simp-bar-after').style.width = '0%';
}
// Chapter 3 Test Self-Healing List
const testListEl = document.getElementById('test-iterations-list');
testListEl.innerHTML = '';
const testRuns = DATA.test_iterations || [];
if (testRuns.length > 0) {
const firstRun = testRuns[0];
const lastRun = testRuns[testRuns.length - 1];
const firstFailPct = firstRun.total > 0 ? ((firstRun.failed / firstRun.total) * 100).toFixed(1) : "0.0";
const lastPassPct = lastRun.total > 0 ? ((lastRun.passed / lastRun.total) * 100).toFixed(1) : "0.0";
document.getElementById('ch3-initial-fail-badge').textContent =
`Initial Run: ${firstFailPct}% Failed → Final: ${lastPassPct}% Pass`;
} else {
document.getElementById('ch3-initial-fail-badge').textContent = 'No Test Runs Logged';
}
testRuns.forEach(tr => {
const passPct = tr.total > 0 ? ((tr.passed / tr.total) * 100).toFixed(1) : "0.0";
const isClean = tr.failed === 0;
const covDisplay = (tr.coverage_pct !== null && tr.coverage_pct !== undefined) ? `${tr.coverage_pct}%` : 'Not measured';
const clippyDisplay = (tr.clippy_warnings !== null && tr.clippy_warnings !== undefined) ? String(tr.clippy_warnings) : 'Not measured';
const row = document.createElement('div');
row.style.cssText = "background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:12px; padding:14px; font-size:12.5px;";
row.innerHTML = `
<div style="display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:8px; margin-bottom:6px;">
<div>
<span class="badge ${isClean ? 'badge-success' : 'badge-warning'}">Test Run #${tr.iteration}</span>
<strong style="margin-left:6px;">${tr.passed}/${tr.total} Passed (${passPct}%) • ${tr.failed} Failed</strong>
</div>
<span style="color:var(--text-secondary);">Coverage: <strong>${covDisplay}</strong> • Clippy Warnings: <strong>${clippyDisplay}</strong></span>
</div>
<div style="color:var(--text-secondary); margin-top:4px;"><strong>Diagnostic:</strong> ${tr.failures_summary}</div>
<div style="color:var(--accent-success-text); margin-top:3px;"><strong>Self-Healing Action:</strong> ${tr.fix_applied}</div>
`;
testListEl.appendChild(row);
});
// Chapter 4 Parity Iterations
const parityEl = document.getElementById('parity-iterations-list');
parityEl.innerHTML = '';
if (parityRuns.length > 0) {
const lp = parityRuns[parityRuns.length - 1];
const pct = lp.seeds_tested > 0 ? ((lp.seeds_passed / lp.seeds_tested) * 100).toFixed(1) : '0.0';
document.getElementById('ch4-parity-badge').textContent = `${pct}% Output Parity`;
} else {
document.getElementById('ch4-parity-badge').textContent = 'Parity Not Measured';
}
parityRuns.forEach(pr => {
const isClean = pr.seeds_passed === pr.seeds_tested;
const row = document.createElement('div');
row.style.cssText = "background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:12px; padding:14px; font-size:12.5px;";
row.innerHTML = `
<div style="display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:8px; margin-bottom:6px;">
<span class="badge ${isClean ? 'badge-success' : 'badge-warning'}">A/B Parity Run #${pr.iteration}: ${pr.seeds_passed}/${pr.seeds_tested} Seeds Matched</span>
<span style="color:var(--text-secondary);">Max Error: <strong>${pr.max_abs_error}</strong></span>
</div>
<div style="color:var(--text-secondary);"><strong>Finding:</strong> ${pr.divergence_cause}</div>
<div style="color:var(--accent-success-text); margin-top:3px;"><strong>Resolution:</strong> ${pr.fix_applied}</div>
`;
parityEl.appendChild(row);
});
// Chapter 5 PGO Benchmark Staircase
const stairEl = document.getElementById('benchmark-staircase');
stairEl.innerHTML = '';
if (benches.length >= 2) {
const prePgo = benches[benches.length - 2];
const postPgo = benches[benches.length - 1];
if (prePgo && postPgo && postPgo.wall_time_ms > 0) {
const pgoGain = Math.round(((prePgo.wall_time_ms - postPgo.wall_time_ms) / prePgo.wall_time_ms) * 100);
if (pgoGain > 0) {
document.getElementById('ch5-pgo-badge').textContent = `+${pgoGain}% Extra Boost from PGO`;
} else {
document.getElementById('ch5-pgo-badge').textContent = `${benches.length} Stages Logged`;
}
}
} else if (benches.length === 1) {
document.getElementById('ch5-pgo-badge').textContent = '1 Stage Logged';
} else {
document.getElementById('ch5-pgo-badge').textContent = 'No Benchmarks Logged';
}
const firstBenchMs = benches.length > 0 ? Math.max(0.001, benches[0].wall_time_ms) : 1.0;
benches.forEach((b, idx) => {
const timeRatioPct = Math.min(100, Math.max(10, Math.round((b.wall_time_ms / firstBenchMs) * 100)));
const isFinal = idx === benches.length - 1;
const barCol = idx === 0 ? 'var(--text-muted)' : (isFinal ? 'var(--accent-success)' : 'var(--accent-primary)');
const row = document.createElement('div');
row.style.cssText = "background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:10px; padding:11px 13px;";
row.innerHTML = `
<div style="display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:6px; font-size:12.5px; margin-bottom:5px;">
<strong>${b.label}</strong>
<div style="display:flex; align-items:center; gap:8px;">
<span class="mono" style="font-size:11.5px; color:var(--text-secondary);">${b.wall_time_ms} ms • ${b.peak_rss_mb} MB</span>
<span class="badge ${isFinal ? 'badge-success' : 'badge-primary'}">${b.speedup.toFixed(2)}x</span>
</div>
</div>
<div class="bar-track">
<div class="bar-fill" style="width:${timeRatioPct}%; background:${barCol};"></div>
</div>
<div style="font-size:11px; color:var(--text-muted); margin-top:4px;">${b.notes || ''}</div>
`;
stairEl.appendChild(row);
});
// Chapter 6 Time Buckets
document.getElementById('ch6-total-badge').textContent = activeStages > 0 ? `Total: ${formattedAiTime}` : 'Not measured';
const stackedBar = document.getElementById('time-stacked-bar');
const bucketsGrid = document.getElementById('time-buckets-grid');
stackedBar.innerHTML = '';
bucketsGrid.innerHTML = '';
const palette = ['#3b82f6', '#6366f1', '#10b981', '#f59e0b', '#06b6d4', '#8b5cf6'];
buckets.forEach((b, idx) => {
const pct = totalMins > 0 ? ((b.minutes / totalMins) * 100).toFixed(1) : '0.0';
const col = palette[idx % palette.length];
if (b.minutes > 0) {
const seg = document.createElement('div');
seg.style.cssText = `width:${pct}%; height:100%; background:${col};`;
seg.title = `${b.label}: ${formatAiDuration(b.minutes)} (${pct}%)`;
stackedBar.appendChild(seg);
}
const card = document.createElement('div');
card.style.cssText = "background:var(--bg-subtle); border:1px solid var(--border-color); border-radius:10px; padding:9px 11px; display:flex; align-items:center; justify-content:space-between; gap:8px;";
card.innerHTML = `
<div style="display:flex; align-items:center; gap:7px;">
<span style="width:9px; height:9px; border-radius:999px; background:${col}; flex-shrink:0;"></span>
<div>
<div style="font-size:12px; font-weight:700;">${b.label}</div>
<div style="font-size:10.5px; color:var(--text-muted);">${b.minutes > 0 ? `${pct}% of agent time` : 'Not timed'}</div>
</div>
</div>
<strong class="mono" style="font-size:12.5px;">${b.minutes > 0 ? formatAiDuration(b.minutes) : 'Not measured'}</strong>
`;
bucketsGrid.appendChild(card);
});
// Spotlight
const spot = DATA.spotlight || {};
document.getElementById('spotlight-explanation').textContent = spot.explanation || 'Not yet recorded.';
document.getElementById('spotlight-legacy-file').textContent = spot.legacy_file || 'Not measured';
document.getElementById('spotlight-legacy-code').textContent = spot.legacy_code || '';
document.getElementById('spotlight-rust-file').textContent = spot.rust_file || 'Not measured';
document.getElementById('spotlight-rust-code').textContent = spot.rust_code || '';
}
renderAll();
if (typeof window !== 'undefined' && window.location && window.location.search) {
const m = String(window.location.search).match(/[?&]mode=([^&]+)/);
const modeParam = m ? decodeURIComponent(m[1]) : null;
if (modeParam && ['all', 'executive', 'technical'].includes(modeParam)) {
setViewMode(modeParam, true);
}
}
</script>
</body>
</html>
pgo_and_telemetry_guide.md 17.2 KB
# Engineering Standards, Blueprint Spec, PGO Pipeline & Telemetry Reference
This reference provides the core engineering standards, 6-section Architectural
Blueprint specification, exact command recipes for recording continuous
migration telemetry via [`scripts/telemetry.py`](../scripts/telemetry.py), and
the LLVM Profile-Guided Optimization (PGO) pipeline.
## Table of Contents
- [1. Core Engineering & Verification Standards](#1-core-engineering--verification-standards):
Lines 33-102
- [2. Stage 1 Architectural Blueprint Specification (6 Sections)](#2-stage-1-architectural-blueprint-specification-6-sections):
Lines 104-141
- [3. Continuous Telemetry Lifecycle (`scripts/telemetry.py`)](#3-continuous-telemetry-lifecycle-scriptstelemetrypy):
Lines 143-281
- [Step A: Initialize Telemetry & Scan Legacy Codebase (`discovery` Bucket)](#step-a-initialize-telemetry--scan-legacy-codebase-discovery-bucket):
Lines 150-183
- [Step B: Log Opportunities & Latent Legacy Bugs (`blueprint` Bucket)](#step-b-log-opportunities--latent-legacy-bugs-blueprint-bucket):
Lines 184-208
- [Step C: Safe Rust Rewrite & Modularization (`rewrite` Bucket)](#step-c-safe-rust-rewrite--modularization-rewrite-bucket):
Lines 209-224
- [Step D: Log Every Test Run & Self-Healing Fix (`test_heal` Bucket)](#step-d-log-every-test-run--self-healing-fix-test_heal-bucket):
Lines 225-251
- [Step E: Log A/B Differential Parity Iterations (`parity` Bucket)](#step-e-log-ab-differential-parity-iterations-parity-bucket):
Lines 252-281
- [4. Profile-Guided Optimization (PGO) Workflow (`pgo_bench` Bucket)](#4-profile-guided-optimization-pgo-workflow-pgo_bench-bucket):
Lines 283-361
- [5. Final Census, First-Person Story & Infographic Generation](#5-final-census-first-person-story--infographic-generation):
Lines 363-415
--------------------------------------------------------------------------------
## 1. Core Engineering & Verification Standards
Every architectural decision in Stage 1 and every module implemented in Stage 2
should follow these seven engineering objectives:
### 1.1 100% Memory Safety (`#![forbid(unsafe_code)]`)
- Place `#![forbid(unsafe_code)]` at the crate root (`src/lib.rs` and
`src/main.rs`) so the compiler rejects `unsafe` blocks, raw pointer
dereferences, or unchecked indexing at compile time. Replace legacy raw
pointers, manual `malloc`/`new`/`free` calls, and mutable globals with safe
ownership, slices, and strong types (`0` `unsafe` blocks).
### 1.2 4-Stage Performance Staircase & PGO
- Track and benchmark performance across four explicit checkpoints so the
contribution of each optimization technique is isolated and quantified:
1. **Legacy Baseline (`legacy_baseline`)**: Original implementation
(`1.0x`).
2. **Initial Safe Rust (`safe_rust`)**: Idiomatic safe port with zero
hot-loop heap allocations.
3. **Data-Oriented SoA & SIMD (`soa_simd`)**: Struct-of-Arrays
cache-aligned memory layouts, pre-allocated workspace arenas, and
auto-vectorization.
4. **Profile-Guided Optimization (`pgo_lto`)**: Instrumented binary
profiled on representative workloads (`-Cprofile-generate` ->
`llvm-profdata merge` -> `-Cprofile-use` + `lto = "fat"` +
`codegen-units = 1`).
### 1.3 API, Call-Site & Cognitive Simplification
- Audit legacy convoluted call trees, deep nesting, out-parameters, and global
mutable state.
- Reduce average function length and maximum nesting depth by decomposing
complex imperative loops into composable iterators, builders, and strongly
typed domain methods.
### 1.4 Modular Rebalancing & File Hygiene (`<= 400` LOC)
- Keep individual source files focused and readable: target **<= 400 lines of
code (LOC)** per file (hard ceiling: **600 LOC**) by decomposing monolithic
legacy files into cohesive, single-responsibility sub-modules.
### 1.5 Comprehensive Documentation & Comment Expansion (`+X%` Docs)
- Document every public module (`//!`), struct, trait, and function (`///`)
with `rustdoc` covering purpose, invariants, units/coordinate frames, `#
Errors`, equations, and runnable doc-tests.
### 1.6 Bounded Verification Crucible & Self-Healing Telemetry
- Target **>= 95% branch coverage** with unit, integration, doc, and
property-based tests (`proptest`).
- **Log every test run transparently (up to 5 self-healing iterations)**: when
initial test runs fail (`X%` failed), record the failure count, root cause,
and self-healing fix via `scripts/telemetry.py log-test-run` before
rebuilding and re-testing. If any failures remain after 5 iterations,
document the remaining failures honestly in telemetry rather than looping
indefinitely.
### 1.7 Numerical / Epsilon Parity & Determinism
- Execute both the legacy baseline and the Rust binary side-by-side across `N`
deterministic seeds. Log every parity check (`scripts/telemetry.py
log-parity-run`), bisect and repair any algorithmic or PRNG discrepancy, and
verify parity within a documented epsilon tolerance (`--max-abs-error`),
accounting for hardware FMA or extended-precision differences where
applicable.
--------------------------------------------------------------------------------
## 2. Stage 1 Architectural Blueprint Specification (6 Sections)
Structure the Stage 1 Markdown blueprint into these six sections:
1. **Codebase Audit, Legacy Census & Latent Bugs Discovered**:
- Present the automated baseline census from `migration_telemetry.json`
(total LOC, comment %, max file LOC, nesting depth, memory/state
hazards).
- Highlight **Latent Bugs & Undefined Behaviors** uncovered in the
original code (e.g., uninitialized memory, unchecked division by zero,
float precision loss, off-by-one boundary reads) with exact file and
line references.
2. **Target Safe Rust Architecture & Module Graph**:
- Proposed Rust crate/module layout (`#![forbid(unsafe_code)]`, every file
`<= 400` LOC target).
- **Mapping Table** showing where legacy files, classes, and functions
relocate:
Legacy File & Symbol (`{legacy_language}`) | Target Rust Module & Type/Fn | Transformation & LOC Target
:----------------------------------------- | :---------------------------------- | :--------------------------
`path/to/legacy.cpp::SimEngine` | `src/engine/stepper.rs::SimStepper` | AoS to SoA; `#![forbid(unsafe_code)]`; `<= 400` LOC
3. **API Ergonomics & Call-Site Modernization**:
- Concrete **Before (`{legacy_language}`) / After (Rust)** code examples
from actual repository call sites showing how legacy calls become clean,
type-safe Rust APIs.
4. **Test Harness, Property Fuzzing & Parity Strategy**:
- Plan for unit, doc, and `proptest` property tests (`>= 95%` branch
coverage target) and golden output comparison across `N` deterministic
seeds within a documented epsilon tolerance.
5. **4-Stage Benchmarking & PGO Pipeline Plan**:
- Strategy for measuring the 4-stage speedup staircase: `legacy_baseline`
-> `safe_rust` -> `soa_simd` -> `pgo_lto` (LLVM Profile-Guided
Optimization + Fat LTO).
6. **Phased Execution Roadmap**:
- Step-by-step milestones for Stage 2 execution plus any **Open
Questions**.
--------------------------------------------------------------------------------
## 3. Continuous Telemetry Lifecycle (`scripts/telemetry.py`)
Resolve `{skill_dir}` as the directory containing the `SKILL.md` file you
loaded. Invoke `python3 {skill_dir}/scripts/telemetry.py` at each stage
transition so every metric is grounded in real measurements rather than post-hoc
estimates.
### Step A: Initialize Telemetry & Scan Legacy Codebase (`discovery` Bucket)
Immediately after cloning or locating the legacy repository:
```bash
python3 "{skill_dir}/scripts/telemetry.py" init \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--project-name "{project_name}" \
--legacy-lang "{legacy_language}"
python3 "{skill_dir}/scripts/telemetry.py" start-bucket \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--bucket discovery
python3 "{skill_dir}/scripts/telemetry.py" scan-codebase \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--phase before \
--dir "{legacy_src_dir}"
```
After confirming and running the legacy baseline binary
(`{baseline_run_command}`) under `/usr/bin/time -v` (or a Python
`resource`/`time` wrapper), log the baseline benchmark:
```bash
python3 "{skill_dir}/scripts/telemetry.py" log-benchmark \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--stage legacy_baseline \
--label "1. Legacy {legacy_language} Baseline" \
--wall-time-ms {legacy_ms} \
--peak-rss-mb {legacy_rss_mb} \
--notes "Original legacy implementation baseline."
```
### Step B: Log Opportunities & Latent Legacy Bugs (`blueprint` Bucket)
When transitioning to Stage 1 (Architectural Blueprint):
```bash
python3 "{skill_dir}/scripts/telemetry.py" start-bucket \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--bucket blueprint
```
For each architectural opportunity, performance bottleneck, memory hazard, or
**latent bug in the original code** discovered during the audit, log it:
```bash
python3 "{skill_dir}/scripts/telemetry.py" log-opportunity \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--category latent_bug \
--title "Uninitialized boundary state on tick 0" \
--file "src/solver.cpp:142" \
--description "Edge cells read uninitialized memory when periodic wrapping is disabled."
```
Valid `--category` values: `latent_bug`, `performance`, `safety`, `hygiene`,
`architecture`.
### Step C: Safe Rust Rewrite & Modularization (`rewrite` Bucket)
At the start of Stage 2 implementation:
```bash
python3 "{skill_dir}/scripts/telemetry.py" start-bucket \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--bucket rewrite
```
- Place `#![forbid(unsafe_code)]` at the top of `src/lib.rs` and `src/main.rs`
so memory safety is enforced by the compiler.
- Benchmark both the initial idiomatic Safe Rust port (`safe_rust`) and the
Struct-of-Arrays / SIMD / zero-allocation refactor (`soa_simd`) using
`log-benchmark`.
### Step D: Log Every Test Run & Self-Healing Fix (`test_heal` Bucket)
Initial test failures form the core of Chapter 3 ("The Verification Crucible").
Start the `test_heal` bucket and log **every** test execution iteration,
including Iteration 1 where `X%` of tests fail, what caused the failures, and
how you fixed them:
```bash
python3 "{skill_dir}/scripts/telemetry.py" start-bucket \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--bucket test_heal
python3 "{skill_dir}/scripts/telemetry.py" log-test-run \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--iteration 1 \
--total 42 \
--passed 34 \
--failed 8 \
--coverage-pct 83.5 \
--clippy-warnings 3 \
--failures-summary "19.0% failed (8/42): boundary reflection off-by-one and extreme seed NaN handling." \
--fix-applied "Corrected opposite-direction index LUT and added domain validation."
```
Repeat `log-test-run` for each rebuild/re-test cycle (up to 5 iterations)
targeting `--failed 0`, `--clippy-warnings 0`, and `--coverage-pct >= 95.0`.
### Step E: Log A/B Differential Parity Iterations (`parity` Bucket)
Start the `parity` bucket and record each side-by-side comparison run across `N`
seeds, including any initial seed divergence and the fix applied:
```bash
python3 "{skill_dir}/scripts/telemetry.py" start-bucket \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--bucket parity
python3 "{skill_dir}/scripts/telemetry.py" log-parity-run \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--iteration 1 \
--seeds-tested 100 \
--seeds-passed 96 \
--max-abs-error "4.2e-4" \
--divergence-cause "4 seeds drifted beyond 1e-12 epsilon at step 380 due to f32 accumulator rounding." \
--fix-applied "Promoted reduction accumulator to f64 to match legacy reference precision."
python3 "{skill_dir}/scripts/telemetry.py" log-parity-run \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--iteration 2 \
--seeds-tested 100 \
--seeds-passed 100 \
--max-abs-error "2.1e-14 (<= 1e-12 epsilon)" \
--divergence-cause "None — 100/100 seeds matched within 1e-12 epsilon." \
--fix-applied "Verified equivalence across all 100 deterministic seeds."
```
--------------------------------------------------------------------------------
## 4. Profile-Guided Optimization (PGO) Workflow (`pgo_bench` Bucket)
After completing the test and parity verification passes, start the `pgo_bench`
bucket and execute an LLVM Profile-Guided Optimization pass:
```bash
python3 "{skill_dir}/scripts/telemetry.py" start-bucket \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--bucket pgo_bench
```
### Step 1: Locate `llvm-profdata`
Run `rustc --print sysroot` first, then locate `llvm-profdata` inside that
toolchain path (or check `which llvm-profdata`):
```bash
rustc --print sysroot
```
### Step 2: Build Instrumented Binary (`-Cprofile-generate`)
Configure `Cargo.toml` with release LTO settings:
```toml
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
```
Compile with profiling instrumentation enabled using a `pgo-data` directory
inside the project workspace:
```bash
RUSTFLAGS="-Cprofile-generate=./pgo-data" cargo build --release
```
### Step 3: Execute Representative Profiling Workload
Run the instrumented binary across 3–5 representative seeds/workloads so LLVM
records accurate branch probabilities and hot-loop trip counts:
```bash
./target/release/{binary_name} {representative_workload_args}
```
### Step 4: Merge Profile Data & Compile Final PGO Binary (`-Cprofile-use`)
```bash
{llvm_profdata_binary} merge -o ./pgo-data/merged.profdata ./pgo-data
```
```bash
RUSTFLAGS="-Cprofile-use=./pgo-data/merged.profdata -Cllvm-args=-pgo-warn-missing-function" cargo build --release
```
> **Fallback if `llvm-profdata` is not installed in the environment**: Compile
> Step 4 with `RUSTFLAGS="-C target-cpu=native -C opt-level=3 -C lto=fat -C
> codegen-units=1"` and note the compiler target-cpu + fat-LTO optimization pass
> in `--notes`.
### Step 5: Benchmark Final PGO Binary & Log Stage 4
Measure wall-clock time and peak RSS of the PGO binary on the exact baseline
workload and log `pgo_lto`:
```bash
python3 "{skill_dir}/scripts/telemetry.py" log-benchmark \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--stage pgo_lto \
--label "4. Profile-Guided Optimization (PGO) + Fat LTO" \
--wall-time-ms {pgo_ms} \
--peak-rss-mb {pgo_rss_mb} \
--notes "Profiled on representative workload and recompiled with -Cprofile-use + Fat LTO."
```
--------------------------------------------------------------------------------
## 5. Final Census, First-Person Story & Infographic Generation
Once PGO benchmarking is complete:
1. **Scan the final Rust codebase**:
```bash
python3 "{skill_dir}/scripts/telemetry.py" scan-codebase \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--phase after \
--dir "{rust_crate_dir}/src" \
--coverage-pct {final_coverage_pct} \
--clippy-warnings 0
```
2. **Record a Before/After Code Transformation Spotlight**:
```bash
python3 "{skill_dir}/scripts/telemetry.py" log-spotlight \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--explanation "How the legacy hot loop was transformed into a documented, zero-allocation Safe Rust kernel." \
--legacy-file "{legacy_file_path}" \
--legacy-code "{legacy_snippet}" \
--rust-file "{rust_file_path}" \
--rust-code "{rust_snippet}"
```
3. **Write the First-Person AI Narrative Chapters**: Write from the AI's
first-person perspective (`"I found..."`, `"I analyzed..."`, `"On my first
test run, X% of tests failed..."`, `"I fixed..."`, `"At the end I ran
PGO..."`):
```bash
python3 "{skill_dir}/scripts/telemetry.py" set-story \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--headline "“I inherited a {legacy_lang} codebase, uncovered {N} latent bugs, self-healed through {X}% initial test failures, and delivered a {S}x faster PGO-tuned Safe Rust port.”" \
--intro "{2-3 sentence executive summary from AI POV}" \
--ch1-narrative "{Chapter 1: What I found in the legacy codebase & opportunities/bugs discovered}" \
--ch2-narrative "{Chapter 2: How I reorganized the architecture, capped files <=400 LOC, and added +X% docs}" \
--ch3-narrative "{Chapter 3: The test crucible — initial failure %, root causes diagnosed, and self-healing fixes}" \
--ch4-narrative "{Chapter 4: Proving output parity across N seeds}" \
--ch5-narrative "{Chapter 5: The 4-stage speedup staircase culminating in PGO}"
```
4. **End the final timer bucket and render the HTML Infographic**:
```bash
python3 "{skill_dir}/scripts/telemetry.py" end-bucket \
--telemetry "{workspace_dir}/migration_telemetry.json" \
--bucket pgo_bench
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_scope}"
```
telemetry.py 41.4 KB
#!/usr/bin/env python3
"""Telemetry & Executive Infographic Generator for the migrate-to-rust Skill.
Tracks real wall-clock time across migration task buckets, performs automated
Before/After codebase censuses (LOC, modularity, comment/doc density, cognitive
complexity, legacy memory hazards vs. Rust unsafe blocks), logs test/parity
self-healing iterations and PGO benchmark staircases, computes the 8-dimension
Executive Scorecard from measured values, and renders a self-contained HTML
infographic from references/infographic_template.html.
"""
import argparse
import datetime
import json
import os
from pathlib import Path
import re
import sys
import time
BUCKET_META = {
"discovery": ("Discovery & Baseline Capture", "bg-sky-400"),
"blueprint": ("Deep Audit & 6-Section Blueprint", "bg-indigo-400"),
"rewrite": ("Safe Rust Rewrite & Modularization", "bg-emerald-400"),
"test_heal": ("Test Generation & Self-Healing Loop", "bg-amber-400"),
"parity": ("A/B Differential Parity Verification", "bg-cyan-400"),
"pgo_bench": ("PGO Profiling & Criterion Benchmarks", "bg-violet-400"),
}
STAGE_LABELS = {
"legacy_baseline": "1. Legacy Baseline Binary",
"safe_rust": "2. Initial Safe Rust Port (Idiomatic)",
"soa_simd": "3. Struct-of-Arrays (SoA) & Zero-Alloc Tuning",
"pgo_lto": "4. Profile-Guided Optimization (PGO) + Fat LTO",
}
LEGACY_EXTS = {
".c",
".cc",
".cpp",
".cxx",
".h",
".hh",
".hpp",
".f",
".f90",
".f95",
".for",
".py",
".java",
".sh",
".bash",
".r",
}
RUST_EXTS = {".rs"}
class TelemetryError(Exception):
"""Actionable error raised when telemetry input or files are invalid."""
def grade_from_score(score: int | None) -> str:
if score is None:
return "N/A"
if score >= 95:
return "A+"
if score >= 90:
return "A"
if score >= 85:
return "A-"
if score >= 80:
return "B+"
if score >= 75:
return "B"
if score >= 65:
return "C"
if score >= 50:
return "D"
return "F"
def clamp_score(val: float, low: int = 0, high: int = 100) -> int:
return max(low, min(high, int(round(val))))
def load_telemetry(path: Path) -> dict:
if not path.exists():
raise TelemetryError(
f"Telemetry file not found: '{path}'. Run 'telemetry.py init"
f" --telemetry {path} --project-name <name> --legacy-lang <lang>'"
" first."
)
try:
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
except json.JSONDecodeError as exc:
raise TelemetryError(
f"Malformed JSON in telemetry file '{path}': {exc}. Re-initialize with"
" 'telemetry.py init' or fix the JSON syntax."
) from exc
except OSError as exc:
raise TelemetryError(
f"Unable to read telemetry file '{path}': {exc}"
) from exc
if not isinstance(data, dict):
raise TelemetryError(
f"Telemetry file '{path}' must contain a top-level JSON object."
)
return data
def save_telemetry(path: Path, data: dict) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except OSError as exc:
raise TelemetryError(
f"Unable to write telemetry file '{path}': {exc}"
) from exc
def resolve_effective_model(
cli_model: str | None, existing_model: str | None
) -> str | None:
"""Resolve the active model name from CLI flags, existing telemetry, or environment."""
for candidate in (
cli_model,
existing_model,
os.environ.get("MIGRATE_TO_RUST_MODEL"),
):
if candidate and candidate.strip():
cleaned = candidate.strip()
if cleaned.lower() not in {"none", "unspecified", "unknown"}:
return cleaned
return None
def close_active_bucket(data: dict, now: float) -> None:
active = data.get("_active_bucket")
if isinstance(active, dict) and active.get("name"):
bname = active["name"]
elapsed_sec = max(0.0, now - float(active.get("started_at", now)))
buckets = data.setdefault("_bucket_seconds", {})
buckets[bname] = buckets.get(bname, 0.0) + elapsed_sec
data["_active_bucket"] = None
def cmd_init(args: argparse.Namespace) -> None:
out_path = Path(args.telemetry)
now = time.time()
user = getattr(args, "user", None) or os.environ.get("USER", "developer")
model = resolve_effective_model(getattr(args, "model", None), None)
data = {
"project_name": args.project_name,
"legacy_language": args.legacy_lang,
"user": user,
"model": model,
"source_url": getattr(args, "source_url", None) or "",
"scope_summary": getattr(args, "scope_summary", None) or "",
"started_at_epoch": now,
"completed_at": None,
"_active_bucket": None,
"_bucket_seconds": {k: 0.0 for k in BUCKET_META},
"story": {
"headline": "",
"intro": "",
"ch1_narrative": "",
"ch2_narrative": "",
"ch3_narrative": "",
"ch4_narrative": "",
"ch5_narrative": "",
},
"census": {
"before": {
"scanned": False,
"files": 0,
"code_loc": 0,
"comment_loc": 0,
"comment_pct": None,
"max_file_loc": 0,
"avg_file_loc": 0,
"files_under_400_pct": None,
"doc_tests": 0,
"max_nesting_depth": None,
"avg_fn_loc": None,
"hazards_count": None,
"latent_bugs_found": None,
},
"after": {
"scanned": False,
"files": 0,
"code_loc": 0,
"comment_loc": 0,
"comment_pct": None,
"max_file_loc": 0,
"avg_file_loc": 0,
"files_under_400_pct": None,
"doc_tests": 0,
"max_nesting_depth": None,
"avg_fn_loc": None,
"unsafe_blocks": None,
"forbid_unsafe": False,
"branch_coverage_pct": None,
"clippy_warnings": None,
},
},
"opportunities": [],
"test_iterations": [],
"parity_iterations": [],
"benchmarks": [],
"time_buckets": [],
"scorecard": [],
"roi": {},
"spotlight": {
"explanation": "",
"legacy_file": "",
"legacy_code": "",
"rust_file": "",
"rust_code": "",
},
}
save_telemetry(out_path, data)
print(
f"[telemetry] Initialized {out_path} for '{args.project_name}'"
f" ({args.legacy_lang})."
)
def cmd_start_bucket(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
now = time.time()
close_active_bucket(data, now)
data["_active_bucket"] = {"name": args.bucket, "started_at": now}
save_telemetry(path, data)
print(f"[telemetry] Started timer for bucket '{args.bucket}'.")
def cmd_end_bucket(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
now = time.time()
close_active_bucket(data, now)
if args.minutes is not None:
data.setdefault("_bucket_seconds", {})[args.bucket] = (
float(args.minutes) * 60.0
)
save_telemetry(path, data)
print(f"[telemetry] Ended timer for bucket '{args.bucket}'.")
def analyze_directory(root_dir: Path, is_rust: bool) -> dict:
if not root_dir.exists():
raise TelemetryError(
f"Directory to scan does not exist: '{root_dir}'. Pass a valid"
" source directory to 'scan-codebase --dir'."
)
exts = RUST_EXTS if is_rust else LEGACY_EXTS
skip_dirs = {
".git",
"target",
"build",
"node_modules",
".venv",
"__pycache__",
}
files_loc = []
total_code = 0
total_comments = 0
doc_tests = 0
max_nesting = 0
fn_count = 0
hazards = 0
unsafe_blocks = 0
forbid_unsafe = False
fn_pattern_rust = re.compile(
r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+|async\s+)?fn\s+\w+"
)
fn_pattern_legacy = re.compile(
r"^\s*(?:[\w:<>~*&\s]+)\s+\w+\s*\([^;]*\)\s*(?:const)?\s*\{|"
r"^\s*def\s+\w+\s*\(|"
r"^\s*(?:subroutine|function)\s+\w+",
re.IGNORECASE,
)
hazard_pattern = re.compile(
r"\b(?:malloc|calloc|realloc|free|new|delete|memcpy|memset|goto|COMMON|EQUIVALENCE)\b|"
r"\*\s*\w+\s*=|->\w+|\bstatic\s+(?!const\b)\w+",
)
unsafe_pattern = re.compile(r"\bunsafe\s*(?:\{|fn\b|impl\b|trait\b)")
for dirpath, dirnames, filenames in os.walk(root_dir):
dirnames[:] = [d for d in dirnames if d not in skip_dirs]
for fname in filenames:
fpath = Path(dirpath) / fname
if fpath.suffix.lower() not in exts:
continue
try:
lines = fpath.read_text(encoding="utf-8", errors="ignore").splitlines()
except OSError:
continue
file_code = 0
file_comment = 0
in_block_comment = False
in_doctest = False
brace_depth = 0
for line in lines:
stripped = line.strip()
if not stripped:
continue
if is_rust and "#![forbid(unsafe_code)]" in stripped:
forbid_unsafe = True
# Block comment handling
if in_block_comment:
file_comment += 1
if "*/" in stripped:
in_block_comment = False
continue
if stripped.startswith("/*"):
file_comment += 1
if "*/" not in stripped[2:]:
in_block_comment = True
continue
if is_rust:
if stripped.startswith("///") or stripped.startswith("//!"):
file_comment += 1
if "```" in stripped:
if not in_doctest:
doc_tests += 1
in_doctest = True
else:
in_doctest = False
continue
if stripped.startswith("//"):
file_comment += 1
continue
else:
if (
stripped.startswith("//")
or stripped.startswith("#")
or (
fpath.suffix.lower() in {".f", ".f90", ".f95", ".for"}
and stripped.startswith("!")
)
):
file_comment += 1
continue
# Count code line
file_code += 1
if "//" in stripped:
file_comment += 1
# Nesting depth estimation
if fpath.suffix.lower() == ".py":
indent = len(line) - len(line.lstrip(" "))
depth = indent // 4
max_nesting = max(max_nesting, depth)
else:
brace_depth += stripped.count("{") - stripped.count("}")
brace_depth = max(0, brace_depth)
max_nesting = max(max_nesting, brace_depth)
if is_rust:
if fn_pattern_rust.match(line):
fn_count += 1
if unsafe_pattern.search(stripped):
unsafe_blocks += 1
else:
if fn_pattern_legacy.match(line):
fn_count += 1
hazards += len(hazard_pattern.findall(stripped))
file_total_loc = file_code + file_comment
if file_total_loc > 0:
files_loc.append(file_total_loc)
total_code += file_code
total_comments += file_comment
num_files = len(files_loc)
max_loc = max(files_loc) if files_loc else 0
avg_loc = int(round(sum(files_loc) / num_files)) if num_files else 0
under_400 = (
round((sum(1 for x in files_loc if x <= 400) / num_files) * 100.0, 1)
if num_files
else None
)
comment_pct = (
round((total_comments / max(1, total_code)) * 100.0, 1)
if total_code > 0
else None
)
avg_fn_loc = (
int(round(total_code / max(1, fn_count))) if total_code > 0 else None
)
measured_nesting = (
max(1, min(max_nesting, 12 if is_rust else 15)) if num_files > 0 else None
)
if is_rust:
return {
"scanned": num_files > 0,
"files": num_files,
"code_loc": total_code,
"comment_loc": total_comments,
"comment_pct": comment_pct,
"max_file_loc": max_loc,
"avg_file_loc": avg_loc,
"files_under_400_pct": under_400,
"doc_tests": doc_tests,
"max_nesting_depth": measured_nesting,
"avg_fn_loc": avg_fn_loc,
"unsafe_blocks": unsafe_blocks if num_files > 0 else None,
"forbid_unsafe": forbid_unsafe,
}
return {
"scanned": num_files > 0,
"files": num_files,
"code_loc": total_code,
"comment_loc": total_comments,
"comment_pct": comment_pct,
"max_file_loc": max_loc,
"avg_file_loc": avg_loc,
"files_under_400_pct": under_400,
"doc_tests": 0,
"max_nesting_depth": measured_nesting,
"avg_fn_loc": avg_fn_loc,
"hazards_count": hazards if num_files > 0 else None,
}
def cmd_scan_codebase(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
target_dir = Path(args.dir)
is_rust = args.phase == "after"
stats = analyze_directory(target_dir, is_rust=is_rust)
census = data.setdefault("census", {})
before_c = census.setdefault("before", {})
after_c = census.setdefault("after", {})
if is_rust:
if args.coverage_pct is not None:
stats["branch_coverage_pct"] = round(float(args.coverage_pct), 1)
else:
stats["branch_coverage_pct"] = after_c.get("branch_coverage_pct")
if args.clippy_warnings is not None:
stats["clippy_warnings"] = int(args.clippy_warnings)
else:
stats["clippy_warnings"] = after_c.get("clippy_warnings")
after_c.update(stats)
else:
existing_latent = before_c.get("latent_bugs_found")
if existing_latent is None:
existing_latent = sum(
1
for o in data.get("opportunities", [])
if o.get("category") == "latent_bug"
)
stats["latent_bugs_found"] = existing_latent
before_c.update(stats)
save_telemetry(path, data)
print(
f"[telemetry] Scanned '{args.phase}' codebase at {target_dir}:"
f" {json.dumps(stats)}"
)
def cmd_log_opportunity(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
entry = {
"category": args.category,
"title": args.title,
"file": args.file or "",
"description": args.description,
}
data.setdefault("opportunities", []).append(entry)
if args.category == "latent_bug":
latent = sum(
1 for o in data["opportunities"] if o.get("category") == "latent_bug"
)
data.setdefault("census", {}).setdefault("before", {})[
"latent_bugs_found"
] = latent
save_telemetry(path, data)
print(f"[telemetry] Logged {args.category}: {args.title}")
def cmd_log_test_run(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
cov_val = (
round(float(args.coverage_pct), 1)
if args.coverage_pct is not None
else None
)
clippy_val = (
int(args.clippy_warnings) if args.clippy_warnings is not None else None
)
entry = {
"iteration": args.iteration,
"total": args.total,
"passed": args.passed,
"failed": args.failed,
"coverage_pct": cov_val,
"clippy_warnings": clippy_val,
"failures_summary": args.failures_summary,
"fix_applied": args.fix_applied,
}
runs = data.setdefault("test_iterations", [])
runs = [r for r in runs if r.get("iteration") != args.iteration]
runs.append(entry)
runs.sort(key=lambda r: r["iteration"])
data["test_iterations"] = runs
after_c = data.setdefault("census", {}).setdefault("after", {})
if cov_val is not None:
after_c["branch_coverage_pct"] = cov_val
if clippy_val is not None:
after_c["clippy_warnings"] = clippy_val
save_telemetry(path, data)
print(
f"[telemetry] Logged test iteration #{args.iteration}:"
f" {args.passed}/{args.total} passed."
)
def cmd_log_parity_run(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
entry = {
"iteration": args.iteration,
"seeds_tested": args.seeds_tested,
"seeds_passed": args.seeds_passed,
"max_abs_error": args.max_abs_error,
"divergence_cause": args.divergence_cause,
"fix_applied": args.fix_applied,
}
runs = data.setdefault("parity_iterations", [])
runs = [r for r in runs if r.get("iteration") != args.iteration]
runs.append(entry)
runs.sort(key=lambda r: r["iteration"])
data["parity_iterations"] = runs
save_telemetry(path, data)
print(
f"[telemetry] Logged parity iteration #{args.iteration}:"
f" {args.seeds_passed}/{args.seeds_tested} seeds matched."
)
def cmd_log_benchmark(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
benches = data.setdefault("benchmarks", [])
benches = [b for b in benches if b.get("stage") != args.stage]
base_ms = float(args.wall_time_ms)
for b in benches:
if b.get("stage") == "legacy_baseline":
base_ms = float(b["wall_time_ms"])
break
entry = {
"stage": args.stage,
"label": args.label or STAGE_LABELS.get(args.stage, args.stage),
"wall_time_ms": round(float(args.wall_time_ms), 2),
"peak_rss_mb": round(float(args.peak_rss_mb), 2),
"speedup": round(base_ms / max(0.001, float(args.wall_time_ms)), 2),
"notes": args.notes or "",
}
benches.append(entry)
stage_order = ["legacy_baseline", "safe_rust", "soa_simd", "pgo_lto"]
benches.sort(
key=lambda b: stage_order.index(b["stage"])
if b["stage"] in stage_order
else 99
)
# Recompute speedups relative to first benchmark
if benches:
first_ms = max(0.001, float(benches[0]["wall_time_ms"]))
for b in benches:
b["speedup"] = round(first_ms / max(0.001, float(b["wall_time_ms"])), 2)
data["benchmarks"] = benches
save_telemetry(path, data)
print(
f"[telemetry] Logged benchmark '{args.stage}': {entry['wall_time_ms']} ms"
f" ({entry['speedup']}x)."
)
def cmd_log_spotlight(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
legacy_code = args.legacy_code or ""
if args.legacy_code_file:
lpath = Path(args.legacy_code_file)
if not lpath.exists():
raise TelemetryError(f"Legacy spotlight code file not found: '{lpath}'")
legacy_code = lpath.read_text(encoding="utf-8", errors="ignore")
rust_code = args.rust_code or ""
if args.rust_code_file:
rpath = Path(args.rust_code_file)
if not rpath.exists():
raise TelemetryError(f"Rust spotlight code file not found: '{rpath}'")
rust_code = rpath.read_text(encoding="utf-8", errors="ignore")
data["spotlight"] = {
"explanation": args.explanation,
"legacy_file": args.legacy_file,
"legacy_code": legacy_code,
"rust_file": args.rust_file,
"rust_code": rust_code,
}
save_telemetry(path, data)
print("[telemetry] Updated Before/After code spotlight.")
def cmd_set_story(args: argparse.Namespace) -> None:
path = Path(args.telemetry)
data = load_telemetry(path)
story = data.setdefault("story", {})
for field in [
"headline",
"intro",
"ch1_narrative",
"ch2_narrative",
"ch3_narrative",
"ch4_narrative",
"ch5_narrative",
]:
val = getattr(args, field, None)
if val:
story[field] = val
save_telemetry(path, data)
print("[telemetry] Updated first-person AI narrative chapters.")
def compute_derived_metrics(data: dict) -> None:
now = time.time()
close_active_bucket(data, now)
after_scanned = bool(
((data.get("census") or {}).get("after") or {}).get("scanned")
)
if after_scanned:
data["completed_at"] = datetime.datetime.now(
datetime.timezone.utc
).strftime("%Y-%m-%d %H:%M UTC")
else:
data.setdefault("completed_at", None)
# 1. Time buckets (measured wall-clock time; 0 minutes when a bucket was not run)
sec_map = data.get("_bucket_seconds", {})
time_buckets = []
total_minutes = 0
active_buckets_count = 0
for bkey, (blabel, bcolor) in BUCKET_META.items():
secs = float(sec_map.get(bkey, 0.0))
if secs > 0.0:
mins = max(1, int(round(secs / 60.0)))
active_buckets_count += 1
else:
mins = 0
total_minutes += mins
time_buckets.append({
"bucket": bkey,
"label": blabel,
"minutes": mins,
"color": bcolor,
})
data["time_buckets"] = time_buckets
# 2. Measured Agent Execution Time (no synthetic human-effort multiplier)
total_ai_hours = round(total_minutes / 60.0, 2)
data["roi"] = {
"total_ai_minutes": total_minutes,
"total_ai_hours": total_ai_hours,
"active_buckets_count": active_buckets_count,
}
# 3. Compute the 8 Scorecard Dimensions strictly from measured values
census = data.get("census") or {}
before_c = census.get("before") or {}
after_c = census.get("after") or {}
benches = data.get("benchmarks") or []
has_benches = len(benches) >= 2
if has_benches:
base_b = benches[0]
final_b = benches[-1]
base_ms = max(0.001, float(base_b.get("wall_time_ms", 0.0)))
final_ms = max(0.001, float(final_b.get("wall_time_ms", 0.0)))
speedup = round(base_ms / final_ms, 2)
speed_before_score = clamp_score(100.0 / max(1.0, speedup), 0, 100)
speed_after_score = clamp_score(
60.0 * speedup
if speedup < 1.0
else 60.0 + min(40.0, (speedup - 1.0) * 15.0),
0,
100,
)
speed_before_label = f"{base_b['wall_time_ms']} ms (1.0x)"
speed_after_label = f"{final_b['wall_time_ms']} ms ({speedup:.2f}x)"
speed_delta = (
f"{speedup:.2f}x Faster" if speedup >= 1.0 else f"{speedup:.2f}x Slower"
)
rss_before = max(0.001, float(base_b.get("peak_rss_mb", 0.0)))
rss_after = max(0.001, float(final_b.get("peak_rss_mb", 0.0)))
rss_drop_pct = round((1.0 - rss_after / rss_before) * 100.0, 1)
mem_before_score = clamp_score(100.0 - max(0.0, rss_drop_pct), 0, 100)
mem_after_score = clamp_score(70.0 + rss_drop_pct * 0.3, 0, 100)
mem_before_label = f"{base_b['peak_rss_mb']} MB Peak RSS"
mem_after_label = f"{final_b['peak_rss_mb']} MB Peak RSS"
mem_delta = (
f"-{rss_drop_pct:.1f}% RAM"
if rss_drop_pct >= 0
else f"+{abs(rss_drop_pct):.1f}% RAM"
)
compute_saved_pct = int(round((1.0 - final_ms / base_ms) * 100.0))
cost_before_score = None
cost_after_score = clamp_score(50.0 + compute_saved_pct * 0.5, 0, 100)
cost_before_label = "Not measured"
cost_after_label = f"{speedup:.2f}x Throughput / Node"
cost_delta = (
f"-{compute_saved_pct}% Compute Hrs"
if compute_saved_pct >= 0
else f"+{abs(compute_saved_pct)}% Compute Hrs"
)
else:
speedup = None
speed_before_score = None
speed_after_score = None
speed_before_label = (
f"{benches[0]['wall_time_ms']} ms" if benches else "Not measured"
)
speed_after_label = "Not measured"
speed_delta = "Not measured"
mem_before_score = None
mem_after_score = None
mem_before_label = (
f"{benches[0]['peak_rss_mb']} MB" if benches else "Not measured"
)
mem_after_label = "Not measured"
mem_delta = "Not measured"
cost_before_score = None
cost_after_score = None
cost_before_label = "Not measured"
cost_after_label = "Not measured"
cost_delta = "Not measured"
hazards = before_c.get("hazards_count")
unsafe_cnt = after_c.get("unsafe_blocks")
if hazards is not None:
safety_before_score = clamp_score(80.0 - float(hazards) * 2.5, 0, 100)
safety_before_label = f"{int(hazards)} Pointer/State Hazards"
else:
safety_before_score = None
safety_before_label = "Not measured"
if unsafe_cnt is not None:
unsafe_int = int(unsafe_cnt)
safety_after_score = (
100
if unsafe_int == 0
else clamp_score(90.0 - unsafe_int * 10.0, 0, 100)
)
safety_after_label = f"{unsafe_int} Unsafe Blocks"
safety_delta = (
"100% Safe Rust" if unsafe_int == 0 else f"{unsafe_int} Unsafe"
)
else:
safety_after_score = None
safety_after_label = "Not measured"
safety_delta = "Not measured"
parity_runs = data.get("parity_iterations") or []
if parity_runs:
last_p = parity_runs[-1]
seeds_t = max(1, int(last_p.get("seeds_tested", 0)))
seeds_p = int(last_p.get("seeds_passed", 0))
parity_pct = round((seeds_p / seeds_t) * 100.0, 1)
parity_before_score = None
parity_after_score = clamp_score(parity_pct, 0, 100)
parity_before_label = "Not measured"
parity_after_label = f"{parity_pct}% across {seeds_t} Seeds"
parity_delta = f"{parity_pct}% Verified"
parity_expl = (
"Automated A/B differential harness verified output equivalence"
f" across {seeds_t} deterministic seeds."
)
else:
parity_before_score = None
parity_after_score = None
parity_before_label = "Not measured"
parity_after_label = "Not measured"
parity_delta = "Not measured"
parity_expl = (
"No A/B parity runs were logged. Run 'telemetry.py log-parity-run' to"
" record seed comparisons."
)
cov_raw = after_c.get("branch_coverage_pct")
clippy_raw = after_c.get("clippy_warnings")
if cov_raw is not None and clippy_raw is not None:
cov_pct = round(float(cov_raw), 1)
clippy_w = int(clippy_raw)
qual_before_score = None
qual_after_score = clamp_score(cov_pct - clippy_w * 3.0, 0, 100)
qual_before_label = "Not measured"
qual_after_label = f"{cov_pct}% Coverage"
qual_delta = f"{clippy_w} Warnings • {cov_pct}% Cov"
else:
qual_before_score = None
qual_after_score = None
qual_before_label = "Not measured"
qual_after_label = "Not measured"
qual_delta = "Not measured"
doc_before = before_c.get("comment_pct")
doc_after = after_c.get("comment_pct")
u400_before = before_c.get("files_under_400_pct")
u400_after = after_c.get("files_under_400_pct")
if doc_before is not None and u400_before is not None:
hygiene_before_score = clamp_score(
float(doc_before) * 2.0 + float(u400_before) * 0.4, 0, 100
)
hygiene_before_label = (
f"{doc_before}% Comments • {before_c.get('max_file_loc', 0)} Max LOC"
)
else:
hygiene_before_score = None
hygiene_before_label = "Not measured"
if doc_after is not None and u400_after is not None:
hygiene_after_score = clamp_score(
float(u400_after) * 0.6 + min(40.0, float(doc_after) * 1.8), 0, 100
)
hygiene_after_label = (
f"{doc_after}% Docs • {after_c.get('max_file_loc', 0)} Max LOC"
)
if doc_before is not None and float(doc_before) > 0:
doc_inc = int(
round(
((float(doc_after) - float(doc_before)) / float(doc_before))
* 100.0
)
)
hygiene_delta = (
f"+{doc_inc}% Docs" if doc_inc >= 0 else f"{doc_inc}% Docs"
)
else:
hygiene_delta = f"{doc_after}% Docs"
else:
hygiene_after_score = None
hygiene_after_label = "Not measured"
hygiene_delta = "Not measured"
nest_b = before_c.get("max_nesting_depth")
fn_b = before_c.get("avg_fn_loc")
nest_a = after_c.get("max_nesting_depth")
fn_a = after_c.get("avg_fn_loc")
if nest_b is not None and fn_b is not None:
simp_before_score = clamp_score(
100.0 - int(nest_b) * 5.0 - int(fn_b) * 0.3, 0, 100
)
simp_before_label = f"Depth {int(nest_b)} • {int(fn_b)} LOC/Fn"
else:
simp_before_score = None
simp_before_label = "Not measured"
if nest_a is not None and fn_a is not None:
simp_after_score = clamp_score(
100.0 - max(0, int(nest_a) - 2) * 4.0 - max(0, int(fn_a) - 20) * 0.4,
0,
100,
)
simp_after_label = f"Depth {int(nest_a)} • {int(fn_a)} LOC/Fn"
if fn_b is not None and int(fn_b) > 0:
fn_drop = int(round(((int(fn_b) - int(fn_a)) / int(fn_b)) * 100.0))
simp_delta = (
f"-{fn_drop}% Fn Size"
if fn_drop >= 0
else f"+{abs(fn_drop)}% Fn Size"
)
else:
simp_delta = f"{int(fn_a)} LOC/Fn"
else:
simp_after_score = None
simp_after_label = "Not measured"
simp_delta = "Not measured"
data["scorecard"] = [
{
"id": "speed",
"title": "Speed & PGO Throughput",
"icon": "⚡",
"before_score": speed_before_score,
"before_grade": grade_from_score(speed_before_score),
"before_label": speed_before_label,
"after_score": speed_after_score,
"after_grade": grade_from_score(speed_after_score),
"after_label": speed_after_label,
"delta_badge": speed_delta,
"explanation": (
"Wall-clock runtime comparison across baseline, Struct-of-Arrays"
" (SoA) layout, and LLVM Profile-Guided Optimization (PGO)."
),
},
{
"id": "memory",
"title": "Memory Efficiency (RSS)",
"icon": "💾",
"before_score": mem_before_score,
"before_grade": grade_from_score(mem_before_score),
"before_label": mem_before_label,
"after_score": mem_after_score,
"after_grade": grade_from_score(mem_after_score),
"after_label": mem_after_label,
"delta_badge": mem_delta,
"explanation": (
"Peak resident memory footprint with pre-allocated workspace"
" buffers and zero hot-loop heap allocations."
),
},
{
"id": "safety",
"title": "Memory Safety (Unsafe Audit)",
"icon": "🛡️",
"before_score": safety_before_score,
"before_grade": grade_from_score(safety_before_score),
"before_label": safety_before_label,
"after_score": safety_after_score,
"after_grade": grade_from_score(safety_after_score),
"after_label": safety_after_label,
"delta_badge": safety_delta,
"explanation": (
"Compile-time memory safety enforced via #![forbid(unsafe_code)],"
" eliminating raw pointer and buffer hazards."
),
},
{
"id": "parity",
"title": "Output Parity & Determinism",
"icon": "🎯",
"before_score": parity_before_score,
"before_grade": grade_from_score(parity_before_score),
"before_label": parity_before_label,
"after_score": parity_after_score,
"after_grade": grade_from_score(parity_after_score),
"after_label": parity_after_label,
"delta_badge": parity_delta,
"explanation": parity_expl,
},
{
"id": "quality",
"title": "Code Quality & Test Coverage",
"icon": "✅",
"before_score": qual_before_score,
"before_grade": grade_from_score(qual_before_score),
"before_label": qual_before_label,
"after_score": qual_after_score,
"after_grade": grade_from_score(qual_after_score),
"after_label": qual_after_label,
"delta_badge": qual_delta,
"explanation": (
"Unit, integration, doc-tests, and property-based proptest suites"
" with clippy -D warnings verification."
),
},
{
"id": "hygiene",
"title": "Code Hygiene & Documentation",
"icon": "📚",
"before_score": hygiene_before_score,
"before_grade": grade_from_score(hygiene_before_score),
"before_label": hygiene_before_label,
"after_score": hygiene_after_score,
"after_grade": grade_from_score(hygiene_after_score),
"after_label": hygiene_after_label,
"delta_badge": hygiene_delta,
"explanation": (
"Public types and functions documented with rustdoc and runnable"
" doc-tests, targeting <=400 LOC per file."
),
},
{
"id": "simplicity",
"title": "Cognitive Simplicity",
"icon": "🧩",
"before_score": simp_before_score,
"before_grade": grade_from_score(simp_before_score),
"before_label": simp_before_label,
"after_score": simp_after_score,
"after_grade": grade_from_score(simp_after_score),
"after_label": simp_after_label,
"delta_badge": simp_delta,
"explanation": (
"Decomposed deeply nested monolithic functions and mutable"
" globals into small, composable functions."
),
},
{
"id": "cost",
"title": "Compute Throughput Efficiency",
"icon": "☁️",
"before_score": cost_before_score,
"before_grade": grade_from_score(cost_before_score),
"before_label": cost_before_label,
"after_score": cost_after_score,
"after_grade": grade_from_score(cost_after_score),
"after_label": cost_after_label,
"delta_badge": cost_delta,
"explanation": (
"Measured execution speedup and memory reduction per node"
" across benchmark stages."
),
},
]
def render_infographic_from_template(tpl_path: Path, data: dict) -> str:
"""Render an interactive HTML infographic from infographic_template.html and telemetry dict."""
try:
html = tpl_path.read_text(encoding="utf-8")
except OSError as exc:
raise TelemetryError(
f"Unable to read infographic template '{tpl_path}': {exc}"
) from exc
json_payload = json.dumps(data, indent=2).replace("</", "<\\/")
return html.replace('"__TELEMETRY_JSON_PLACEHOLDER__"', json_payload)
def cmd_render_infographic(args: argparse.Namespace) -> None:
tpath = Path(args.telemetry)
data = load_telemetry(tpath)
if getattr(args, "user", None):
data["user"] = args.user
data["model"] = resolve_effective_model(
getattr(args, "model", None), data.get("model")
)
if getattr(args, "source_url", None):
data["source_url"] = args.source_url
if getattr(args, "scope_summary", None):
data["scope_summary"] = args.scope_summary
if getattr(args, "run_id", None):
data["run_id"] = args.run_id
compute_derived_metrics(data)
save_telemetry(tpath, data)
script_dir = Path(__file__).parent.resolve()
default_tpl = script_dir.parent / "references" / "infographic_template.html"
tpl_path = Path(args.template) if args.template else default_tpl
if not tpl_path.exists():
raise TelemetryError(
f"Infographic template not found at '{tpl_path}'. Pass a valid path"
" via '--template'."
)
html_out = render_infographic_from_template(tpl_path, data)
out_path = Path(args.out)
try:
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(html_out, encoding="utf-8")
except OSError as exc:
raise TelemetryError(
f"Unable to write HTML infographic to '{out_path}': {exc}"
) from exc
print(f"[telemetry] Rendered interactive HTML infographic to {out_path}")
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
description="migrate-to-rust Migration Telemetry & Infographic CLI"
)
sub = p.add_subparsers(dest="cmd", required=True)
p_init = sub.add_parser("init", help="Initialize migration_telemetry.json")
p_init.add_argument(
"--telemetry", required=True, help="Path to migration_telemetry.json"
)
p_init.add_argument(
"--project-name", required=True, help="Human-readable project name"
)
p_init.add_argument(
"--legacy-lang",
required=True,
help="Detected legacy language (e.g. C++14, Fortran90, Python)",
)
p_init.add_argument(
"--model",
default=None,
help="Optional AI model identifier",
)
p_init.add_argument("--user", default=None, help="Developer username")
p_init.add_argument(
"--source-url", default=None, help="Source GitHub URL or repository path"
)
p_init.add_argument(
"--scope-summary", default=None, help="Brief summary of migrated scope"
)
p_init.set_defaults(func=cmd_init)
p_sb = sub.add_parser(
"start-bucket", help="Start wall-clock timer for a task bucket"
)
p_sb.add_argument("--telemetry", required=True)
p_sb.add_argument("--bucket", required=True, choices=list(BUCKET_META.keys()))
p_sb.set_defaults(func=cmd_start_bucket)
p_eb = sub.add_parser(
"end-bucket", help="End wall-clock timer for a task bucket"
)
p_eb.add_argument("--telemetry", required=True)
p_eb.add_argument("--bucket", required=True, choices=list(BUCKET_META.keys()))
p_eb.add_argument(
"--minutes",
type=float,
default=None,
help="Optional explicit minutes override",
)
p_eb.set_defaults(func=cmd_end_bucket)
p_scan = sub.add_parser(
"scan-codebase",
help="Scan Before (legacy) or After (Rust) codebase metrics",
)
p_scan.add_argument("--telemetry", required=True)
p_scan.add_argument("--phase", required=True, choices=["before", "after"])
p_scan.add_argument("--dir", required=True, help="Directory to scan")
p_scan.add_argument("--coverage-pct", type=float, default=None)
p_scan.add_argument("--clippy-warnings", type=int, default=None)
p_scan.set_defaults(func=cmd_scan_codebase)
p_opp = sub.add_parser(
"log-opportunity",
help="Log an architectural opportunity or latent legacy bug",
)
p_opp.add_argument("--telemetry", required=True)
p_opp.add_argument(
"--category",
required=True,
choices=[
"latent_bug",
"performance",
"safety",
"hygiene",
"architecture",
],
)
p_opp.add_argument("--title", required=True)
p_opp.add_argument("--file", default="")
p_opp.add_argument("--description", required=True)
p_opp.set_defaults(func=cmd_log_opportunity)
p_tr = sub.add_parser(
"log-test-run", help="Log a test execution & self-healing iteration"
)
p_tr.add_argument("--telemetry", required=True)
p_tr.add_argument("--iteration", type=int, required=True)
p_tr.add_argument("--total", type=int, required=True)
p_tr.add_argument("--passed", type=int, required=True)
p_tr.add_argument("--failed", type=int, required=True)
p_tr.add_argument("--coverage-pct", type=float, default=None)
p_tr.add_argument("--clippy-warnings", type=int, default=None)
p_tr.add_argument("--failures-summary", required=True)
p_tr.add_argument("--fix-applied", required=True)
p_tr.set_defaults(func=cmd_log_test_run)
p_pr = sub.add_parser(
"log-parity-run", help="Log an A/B differential parity iteration"
)
p_pr.add_argument("--telemetry", required=True)
p_pr.add_argument("--iteration", type=int, required=True)
p_pr.add_argument("--seeds-tested", type=int, required=True)
p_pr.add_argument("--seeds-passed", type=int, required=True)
p_pr.add_argument("--max-abs-error", required=True)
p_pr.add_argument("--divergence-cause", required=True)
p_pr.add_argument("--fix-applied", required=True)
p_pr.set_defaults(func=cmd_log_parity_run)
p_bm = sub.add_parser(
"log-benchmark", help="Log a benchmark stage on the 4-stage PGO staircase"
)
p_bm.add_argument("--telemetry", required=True)
p_bm.add_argument(
"--stage",
required=True,
choices=["legacy_baseline", "safe_rust", "soa_simd", "pgo_lto"],
)
p_bm.add_argument("--label", default="")
p_bm.add_argument("--wall-time-ms", type=float, required=True)
p_bm.add_argument("--peak-rss-mb", type=float, required=True)
p_bm.add_argument("--notes", default="")
p_bm.set_defaults(func=cmd_log_benchmark)
p_sp = sub.add_parser(
"log-spotlight", help="Record Before/After code snippet spotlight"
)
p_sp.add_argument("--telemetry", required=True)
p_sp.add_argument("--explanation", required=True)
p_sp.add_argument("--legacy-file", required=True)
p_sp.add_argument("--legacy-code", default="")
p_sp.add_argument("--legacy-code-file", default="")
p_sp.add_argument("--rust-file", required=True)
p_sp.add_argument("--rust-code", default="")
p_sp.add_argument("--rust-code-file", default="")
p_sp.set_defaults(func=cmd_log_spotlight)
p_st = sub.add_parser(
"set-story", help="Set first-person AI story narrative fields"
)
p_st.add_argument("--telemetry", required=True)
p_st.add_argument("--headline", default=None)
p_st.add_argument("--intro", default=None)
p_st.add_argument("--ch1-narrative", dest="ch1_narrative", default=None)
p_st.add_argument("--ch2-narrative", dest="ch2_narrative", default=None)
p_st.add_argument("--ch3-narrative", dest="ch3_narrative", default=None)
p_st.add_argument("--ch4-narrative", dest="ch4_narrative", default=None)
p_st.add_argument("--ch5-narrative", dest="ch5_narrative", default=None)
p_st.set_defaults(func=cmd_set_story)
p_ri = sub.add_parser(
"render-infographic",
help="Compute final scorecard and render HTML infographic",
)
p_ri.add_argument("--telemetry", required=True)
p_ri.add_argument(
"--out",
required=True,
help="Output HTML file path",
)
p_ri.add_argument(
"--template", default=None, help="Optional custom template path"
)
p_ri.add_argument(
"--model",
default=None,
help="Optional AI model identifier",
)
p_ri.add_argument("--user", default=None, help="Developer username")
p_ri.add_argument(
"--source-url", default=None, help="Source GitHub URL or repository path"
)
p_ri.add_argument(
"--scope-summary", default=None, help="Brief summary of migrated scope"
)
p_ri.add_argument(
"--run-id", default=None, help="Optional explicit run ID slug"
)
p_ri.set_defaults(func=cmd_render_infographic)
return p
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
try:
args.func(args)
except TelemetryError as exc:
print(f"[telemetry] ERROR: {exc}", file=sys.stderr)
return 1
except KeyError as exc:
print(
f"[telemetry] ERROR: Missing required telemetry key {exc}. Ensure"
" 'telemetry.py init' was run on this file.",
file=sys.stderr,
)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE