diff options
| author | Morgan Lunt <morganl@anthropic.com> | 2026-05-12 09:58:41 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-05-12 09:58:41 -0700 |
| commit | 573ecf32cd82a8ec997b0e92acbdd46d17b67bb1 (patch) | |
| tree | 57d692a0580174148ffd8fa8a86214ef556a53ca /plugins/code-modernization/commands | |
| parent | 45896c8f2fe68e68ca2a8e3554d4441f48475431 (diff) | |
| parent | 5e4a45001d608ce34437181d96340faa1f5899c9 (diff) | |
Merge pull request #1820 from anthropics/morganl/code-modernization-plugin
code-modernization: fix pipeline gaps, redesign harden, dry-run hardening
Diffstat (limited to 'plugins/code-modernization/commands')
6 files changed, 149 insertions, 60 deletions
diff --git a/plugins/code-modernization/commands/modernize-assess.md b/plugins/code-modernization/commands/modernize-assess.md index 69df96b1..188c2d43 100644 --- a/plugins/code-modernization/commands/modernize-assess.md +++ b/plugins/code-modernization/commands/modernize-assess.md @@ -23,6 +23,10 @@ cloc --quiet --csv <parent>/<sys> # LOC by language lizard -s cyclomatic_complexity <parent>/<sys> 2>/dev/null | tail -1 ``` +If `cloc`/`lizard` are not installed, fall back to `scc <parent>/<sys>` +(LOC + complexity) or `find` + `wc -l` grouped by extension, and estimate +complexity by counting decision keywords per file. Note which tool you used. + Capture: total SLOC, dominant language, file count, mean & max cyclomatic complexity (CCN). For dependency freshness, locate the manifest (`package.json`, `pom.xml`, `*.csproj`, `requirements*.txt`, @@ -69,6 +73,17 @@ scc legacy/$1 Then run `scc --by-file -s complexity legacy/$1 | head -25` to identify the highest-complexity files. Capture the COCOMO effort/cost estimate scc provides. +If `scc` is not installed, fall back in order: +1. `cloc legacy/$1` for the LOC table, then compute COCOMO-II effort + yourself: `PM = 2.94 × (KSLOC)^1.10` (nominal scale factors). Show the + inputs. +2. If `cloc` is also missing, use `find` + `wc -l` grouped by extension + for LOC, and rank file complexity by counting decision keywords + (`IF`/`EVALUATE`/`WHEN`/`PERFORM` for COBOL; `if`/`for`/`while`/`case`/ + `catch` for C-family). Compute COCOMO from KSLOC as above. + +Note in the assessment which tool was used so the figures are reproducible. + ## Step 2 — Technology fingerprint Identify, with file evidence: @@ -80,12 +95,15 @@ Identify, with file evidence: ## Step 3 — Parallel deep analysis -Spawn three subagents **concurrently** using the Task tool: +Spawn three subagents **in parallel**: 1. **legacy-analyst** — "Build a structural map of legacy/$1: what are the - 5-10 major functional domains, which source files belong to each, and how - do they depend on each other? Return a markdown table + a Mermaid - `graph TD` of domain-level dependencies. Cite file paths." + 5-12 major functional domains (group optional/feature-gated subsystems + under one umbrella), which source files belong to each, and how do they + depend on each other (control flow + shared data)? Return a markdown + table + a Mermaid `graph TD` of domain-level dependencies — use + `subgraph` to cluster and cap at ~40 edges. Cite repo-relative file + paths. Flag dangling references (defined but no source, or unused)." 2. **legacy-analyst** — "Identify technical debt in legacy/$1: dead code, deprecated APIs, copy-paste duplication, god objects/programs, missing @@ -99,20 +117,21 @@ Spawn three subagents **concurrently** using the Task tool: Wait for all three. Synthesize their findings. -## Step 4 — Production runtime overlay (observability) +## Step 4 — Production runtime overlay (optional) -If the system has batch jobs (e.g. JCL members under `app/jcl/`), call the -`observability` MCP tool `get_batch_runtimes` for each business-relevant -job name (interest, posting, statement, reporting). Use the returned -p50/p95/p99 and 90-day series to: +If production telemetry is available — an observability/APM MCP server, batch +job logs, or runtime exports the user can supply — gather p50/p95/p99 +wall-clock for the system's key jobs/transactions (e.g. JCL members under +`legacy/$1/jcl/`, scheduled batches, top API routes). Use it to: - Tag each functional domain from Step 3 with its production wall-clock cost and **p99 variance** (p99/p50 ratio). - Flag the highest-variance domain as the highest operational risk — this is telemetry-grounded, not a static-analysis opinion. -Include a small **Batch Runtime** table (Job · Domain · p50 · p95 · p99 · -p99/p50) in the assessment. +Include a small **Runtime Profile** table (Job/Route · Domain · p50 · p95 · +p99 · p99/p50) in the assessment. If no telemetry is available, skip this +step and note the gap in the assessment. ## Step 5 — Documentation gap analysis @@ -126,7 +145,7 @@ Create `analysis/$1/ASSESSMENT.md` with these sections: - **Executive Summary** (3-4 sentences: what it is, how big, how risky, headline recommendation) - **System Inventory** (the scc table + tech fingerprint) - **Architecture-at-a-Glance** (the domain table; reference the diagram) -- **Production Runtime Profile** (the batch-runtime table from Step 4, with the highest-variance domain called out) +- **Production Runtime Profile** (the runtime table from Step 4 with the highest-variance domain called out — or "no telemetry available") - **Technical Debt** (top 10, ranked) - **Security Findings** (CWE table) - **Documentation Gaps** (top 5) diff --git a/plugins/code-modernization/commands/modernize-brief.md b/plugins/code-modernization/commands/modernize-brief.md index ec7f1496..28eeb624 100644 --- a/plugins/code-modernization/commands/modernize-brief.md +++ b/plugins/code-modernization/commands/modernize-brief.md @@ -8,8 +8,10 @@ single document a steering committee approves and engineering executes. Target stack: `$2` (if blank, recommend one based on the assessment findings). -Read `analysis/$1/ASSESSMENT.md`, `TOPOLOGY.md`, and `BUSINESS_RULES.md` first. -If any are missing, say so and stop. +Read `analysis/$1/ASSESSMENT.md`, `analysis/$1/TOPOLOGY.html` (and the `.mmd` +files alongside it), and `analysis/$1/BUSINESS_RULES.md` first. If any are +missing, say so and stop — they come from `/modernize-assess`, `/modernize-map`, +and `/modernize-extract-rules` respectively. Run those first. ## The Brief @@ -35,8 +37,11 @@ fewest-dependencies first. For each phase: Render the phases as a Mermaid `gantt` chart. ### 4. Behavior Contract -List the **P0 behaviors** from BUSINESS_RULES.md that MUST be proven -equivalent before any phase ships. These become the regression suite. +List the **P0 rules** from BUSINESS_RULES.md (the ones tagged `Priority: P0` — +money, regulatory, data integrity) that MUST be proven equivalent before any +phase ships. These become the regression suite. Flag any P0 rule with +Confidence < High as a blocker requiring SME confirmation before its phase +starts. ### 5. Validation Strategy State which combination applies: characterization tests, contract tests, diff --git a/plugins/code-modernization/commands/modernize-extract-rules.md b/plugins/code-modernization/commands/modernize-extract-rules.md index 34e62472..1fe7979c 100644 --- a/plugins/code-modernization/commands/modernize-extract-rules.md +++ b/plugins/code-modernization/commands/modernize-extract-rules.md @@ -38,6 +38,7 @@ Merge the three result sets. Deduplicate. For each distinct rule, write a ``` ### RULE-NNN: <plain-English name> **Category:** Calculation | Validation | Lifecycle | Policy +**Priority:** P0 | P1 | P2 **Source:** `path/to/file.ext:line-line` **Plain English:** One sentence a business analyst would recognize. **Specification:** @@ -47,11 +48,18 @@ Merge the three result sets. Deduplicate. For each distinct rule, write a [And <additional outcome>] **Parameters:** <constants, rates, thresholds with their current values> **Edge cases handled:** <list> -**Confidence:** High | Medium | Low — <why> +**Suspected defect:** <optional — legacy behavior that looks wrong; decide preserve-vs-fix during transform> +**Confidence:** High | Medium | Low — <why; if < High, state the exact SME question> ``` +Priority heuristic — default to **P1**. Assign **P0** if the rule moves money, +enforces a regulatory/compliance requirement, or guards data integrity (and +flag P0 rules at <High confidence as SME-required). Assign **P2** for +display/formatting/convenience rules. The downstream `/modernize-brief` +behavior contract is built from the P0 rules, so assign deliberately. + Write all rule cards to `analysis/$1/BUSINESS_RULES.md` with: -- A summary table at top (ID, name, category, source, confidence) +- A summary table at top (ID, name, category, priority, source, confidence) - Rule cards grouped by category - A final **"Rules requiring SME confirmation"** section listing every Medium/Low confidence rule with the specific question a human needs to answer diff --git a/plugins/code-modernization/commands/modernize-harden.md b/plugins/code-modernization/commands/modernize-harden.md index 4ef80cf3..b8f7a72c 100644 --- a/plugins/code-modernization/commands/modernize-harden.md +++ b/plugins/code-modernization/commands/modernize-harden.md @@ -1,23 +1,26 @@ --- -description: Security vulnerability scan + remediation — OWASP, CVE, secrets, injection +description: Security vulnerability scan with a reviewable remediation patch — OWASP, CWE, CVE, secrets, injection argument-hint: <system-dir> --- Run a **security hardening pass** on `legacy/$1`: find vulnerabilities, rank -them, and fix the critical ones. +them, and produce a reviewable patch for the critical ones. + +This command never edits `legacy/` — it writes findings and a proposed patch +to `analysis/$1/`. The user reviews and applies (or not). ## Scan Spawn the **security-auditor** subagent: -"Adversarially audit legacy/$1 for security vulnerabilities. Cover: -OWASP Top 10 (injection, broken auth, XSS, SSRF, etc.), hardcoded secrets, -vulnerable dependency versions (check package manifests against known CVEs), -missing input validation, insecure deserialization, path traversal. -For each finding return: CWE ID, severity (Critical/High/Med/Low), file:line, -one-sentence exploit scenario, and recommended fix. Also run any available -SAST tooling (npm audit, pip-audit, OWASP dependency-check) and include -its raw output." +"Adversarially audit legacy/$1 for security vulnerabilities. Cover what's +relevant to the stack: injection (SQL/NoSQL/OS command/template), broken +auth, sensitive data exposure, access control gaps, insecure deserialization, +hardcoded secrets, vulnerable dependency versions, missing input validation, +path traversal. For each finding return: CWE ID, severity +(Critical/High/Med/Low), file:line, one-sentence exploit scenario, and +recommended fix. Run any available SAST tooling (npm audit, pip-audit, +OWASP dependency-check) and include its raw output." ## Triage @@ -28,19 +31,34 @@ Write `analysis/$1/SECURITY_FINDINGS.md`: ## Remediate -For each **Critical** and **High** finding, fix it directly in the source. -Make minimal, targeted changes. After each fix, add a one-line entry under -"Remediation Log" in SECURITY_FINDINGS.md: finding ID → commit-style summary -of what changed. +For each **Critical** and **High** finding, draft a minimal, targeted fix. +Do **not** edit `legacy/` — write all fixes as a single unified diff to +`analysis/$1/security_remediation.patch`, with a comment line above each +hunk citing the finding ID it addresses (`# SEC-001: parameterize the query`). -Show the cumulative diff: -```bash -git -C legacy/$1 diff -``` +Add a **Remediation Log** section to SECURITY_FINDINGS.md mapping each +finding ID → one-line summary of the proposed fix and the patch hunk that +implements it. ## Verify -Re-run the security-auditor against the patched code to confirm the -Critical/High findings are resolved. Update the scorecard with before/after. +Spawn the **security-auditor** again to **review the patch** against the +original code: + +"Review analysis/$1/security_remediation.patch against legacy/$1. For each +hunk: does it fully remediate the cited finding? Does it introduce new +vulnerabilities or change behavior beyond the fix? Return one verdict per +hunk: RESOLVES / PARTIAL / INTRODUCES-RISK, with a one-line reason." + +Add a **Patch Review** section to SECURITY_FINDINGS.md with the verdicts. +If any hunk is PARTIAL or INTRODUCES-RISK, revise the patch and re-review. + +## Present + +Tell the user the artifacts are ready: +- `analysis/$1/SECURITY_FINDINGS.md` — findings, remediation log, patch review +- `analysis/$1/security_remediation.patch` — review, then apply if appropriate + with `git -C legacy/$1 apply ../../analysis/$1/security_remediation.patch` +- Re-run `/modernize-harden $1` after applying to confirm resolution Suggest: `glow -p analysis/$1/SECURITY_FINDINGS.md` diff --git a/plugins/code-modernization/commands/modernize-map.md b/plugins/code-modernization/commands/modernize-map.md index bd149cb5..406b74c0 100644 --- a/plugins/code-modernization/commands/modernize-map.md +++ b/plugins/code-modernization/commands/modernize-map.md @@ -11,31 +11,69 @@ connect? This is the map an engineer needs before touching anything. ## What to produce Write a one-off analysis script (Python or shell — your choice) that parses -the source under `legacy/$1` and extracts: - -- **Program/module call graph** — who calls whom (for COBOL: `CALL` statements - and CICS `LINK`/`XCTL`; for Java: class-level imports/invocations; for Node: - `require`/`import`) -- **Data dependency graph** — which programs read/write which data stores - (COBOL: copybooks + VSAM/DB2 in JCL DD statements; Java: JPA entities/tables; - Node: model files) -- **Entry points** — batch jobs, transaction IDs, HTTP routes, CLI commands -- **Dead-end candidates** — modules with no inbound edges (potential dead code) +the source under `legacy/$1` and extracts the four datasets below. Three +principles apply across stacks; getting them wrong produces a misleading map: + +1. **Edges live in two places** — direct calls in source, *and* dispatcher/ + router calls whose targets are variables (config tables, route maps, + dependency injection, dynamic dispatch). Resolve variables against config + before declaring an edge unresolvable. +2. **The code↔storage join is usually external configuration**, not source — + job/deployment descriptors map logical names to physical stores. +3. **Entry points usually live in deployment config**, not source — without + parsing it, every top-level module looks unreachable. + +Extract: + +- **Program/module call graph** — direct calls (`CALL`, method invocations, + `import`/`require`) *and* dispatcher calls (`EXEC CICS LINK/XCTL`, DI + container wiring, framework routing, reflection/factory). Resolve variable + call targets against route tables, copybooks, config, or constant pools. +- **Data dependency graph** — which modules read/write which data stores, + joined through the relevant config: `SELECT…ASSIGN TO` ↔ JCL `DD` (batch + COBOL), `EXEC CICS READ/WRITE…FILE()` ↔ CSD `DEFINE FILE` (CICS online), + `EXEC SQL` table refs (embedded SQL), ORM annotations/mappings (Java/.NET), + model files (Node/Python/Ruby). Include UI/screen bindings (BMS maps, JSPs, + templates) — they're dependencies too. +- **Entry points** — whatever the stack's outermost invoker is, read from + where it's defined: JCL `EXEC PGM=` and CICS CSD `DEFINE TRANSACTION` + (mainframe), `web.xml`/route annotations/route files (web), `main()`/argv + parsing (CLI), queue/scheduler subscriptions (event-driven). +- **Dead-end candidates** — modules with no inbound edges. **Only meaningful + once all the entry-point and call-edge types above are in the graph.** + Suppress the dead claim for anything that could be the target of an + unresolved dynamic call. A grep-only graph will mark most dispatcher-driven + modules (CICS programs, Spring controllers, ORM-bound DAOs) dead when they + aren't. + +If the source is fixed-column (COBOL columns 8–72, RPG, etc.), slice the +code area and strip comment lines before regex matching, or you'll match +sequence numbers and commented-out code. Save the script as `analysis/$1/extract_topology.py` (or `.sh`) so it can be -re-run and audited. Run it. Show the raw output. +re-run and audited. Have it write a machine-readable +`analysis/$1/topology.json` and print a human summary. Run it; show the +summary (cap at ~200 lines for very large estates). ## Render From the extracted data, generate **three Mermaid diagrams** and write them -to `analysis/$1/TOPOLOGY.html` so the artifact pane renders them live. +to `analysis/$1/TOPOLOGY.html` as a self-contained page that renders in any +browser. The HTML page must use: dark `#1e1e1e` background, `#d4d4d4` text, `#cc785c` for `<h2>`/accents, `system-ui` font, all CSS **inline** (no -external stylesheets). Each diagram goes in a -`<pre class="mermaid">...</pre>` block — the artifact server loads -mermaid.js and renders client-side. Do **not** wrap diagrams in -markdown ` ``` ` fences inside the HTML. +external stylesheets). Load Mermaid from a CDN in `<head>`: + +```html +<script type="module"> + import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs'; + mermaid.initialize({ startOnLoad: true, theme: 'dark' }); +</script> +``` + +Each diagram goes in a `<pre class="mermaid">...</pre>` block. Do **not** +wrap diagrams in markdown ` ``` ` fences inside the HTML. 1. **`graph TD` — Module call graph.** Cluster by domain (use `subgraph`). Highlight entry points in a distinct style. Cap at ~40 nodes — if larger, @@ -46,9 +84,9 @@ markdown ` ``` ` fences inside the HTML. 3. **`flowchart TD` — Critical path.** Trace ONE end-to-end business flow (e.g., "monthly billing run" or "process payment") through every program - and data store it touches, in execution order. If the `observability` - MCP server is connected, annotate each batch step with its p50/p99 - wall-clock from `get_batch_runtimes`. + and data store it touches, in execution order. If production telemetry is + available (see `/modernize-assess` Step 4), annotate each step with its + p50/p99 wall-clock. Also export the three diagrams as standalone `.mmd` files for re-use: `analysis/$1/call-graph.mmd`, `analysis/$1/data-lineage.mmd`, @@ -63,4 +101,4 @@ touched by too many writers. ## Present -Tell the user to open `analysis/$1/TOPOLOGY.html` in the artifact pane. +Tell the user to open `analysis/$1/TOPOLOGY.html` in a browser. diff --git a/plugins/code-modernization/commands/modernize-reimagine.md b/plugins/code-modernization/commands/modernize-reimagine.md index c676601f..c16523ab 100644 --- a/plugins/code-modernization/commands/modernize-reimagine.md +++ b/plugins/code-modernization/commands/modernize-reimagine.md @@ -57,8 +57,9 @@ Enter plan mode. Present the architecture. Wait for approval. ## Phase E — Parallel scaffolding -For each service in the approved architecture (cap at 3 for the demo), spawn -a **general-purpose agent in parallel**: +For each service in the approved architecture (cap at 3 to keep the run +tractable; tell the user which you deferred), spawn a **general-purpose agent +in parallel**: "Scaffold the <service-name> service per analysis/$1/REIMAGINED_ARCHITECTURE.md and AI_NATIVE_SPEC.md. Create: project skeleton, domain model, API stubs |
