1. Orienting Your modernization journey
This comprehensive codelab is the practical companion lab derived directly from the architectural deep-dive article, How to automate modernization with Antigravity and multi-agent orchestration. While we use a classic Node.js framework swap as our tangible demonstration vehicle, the core design patterns, directory structures, and agentic orchestration processes you will champion here are completely language-agnostic and universally applicable to any legacy modernization project at scale.
Unlike standard coding assistants that merely autocomplete lines in a single file, you will learn how to leverage the agent-first capabilities of Google Antigravity to orchestrate autonomous teams of specialized AI subagents. These agents can independently reverse-engineer legacy codebases, write rigorous test suites, scaffold modern architectures, and self-correct their own compiler errors using Reflexion loops, all while you maintain absolute control as the high-level architect.
What you'll learn
- Mapping the workflow: How to correctly classify and separate deterministic setup tasks from complex heuristic refactoring challenges.
- Skills architecture: How to structure an extensible Agent Skills Pack using progressive disclosure and YAML routing metadata.
- Orchestrating design patterns: How to drive large-scale refactoring by chaining the Router, Plan-and-Execute, and Reflexion design patterns.
- Rigid input/output contracts: How to enforce clear input/skill/output boundaries across multi-phase reverse-engineering and target scaffolding pipelines.
- Parity verification: How to leverage Antigravity's Browser Subagent to perform side-by-side parity testing within the Chrome a web browser.
What you'll build
You will orchestrate a completely automated Greenfield Refactoring Pipeline that takes the iconic, outdated legacy Express and Mongoose CRUD monolith (the "madhums demo") and autonomously rebuilds it from scratch into a strictly typed Next.js App Router application backed by MongoDB, strict Zod validation, and accessible ShadCN UI components.
What you'll need
- Google Antigravity IDE installed locally (available at antigravity.google).
- Node.js (v18+) installed locally.
- Chrome browser for automated UI verification.
- A clone of the open-source modernizing-expressjs demonstration monorepo.
2. Set up the modernization environment
Before letting autonomous agents loose on an aging legacy codebase, we must establish a clean, highly stable monorepo environment. Giving an AI assistant a clean baseline ensures it focuses entirely on generating high-quality modern code rather than wasting tokens fighting decade-old package vulnerabilities or compiler mismatches.
Legacy Express versus modern Next.js architecture mapping
Component | Legacy Stack | Modern Replacement | The Rationale |
Architecture | Express Monolith | Next.js App Router | Decoupling logic into Server Components for optimized rendering and React Server Components (RSC) performance. |
Data Logic | Mongoose (ODM) | MongoDB + Zod | Swapping implicit ORM hooks for explicit, type-safe Zod schemas and raw driver performance. |
Language | CommonJS / JavaScript | TypeScript (ESM) | Enforcing compile-time safety and moving to modern module standards. |
Frontend | Pug/EJS (Server View) | ShadCN UI + Tailwind | Shifting from rigid templates to a composable, accessible, and utility-first design system. |
Auth | Passport.js | NextAuth | Modernizing session management with built-in support for Edge and contemporary providers. |
Safety | Manual Middleware | Zod (Strict Validation) | Implementing a "Single Source of Truth" for data validation across the entire stack. |
Initialize the modernization hub
Our first deterministic action is to clone the isolated monorepo structure. This separates the read-only legacy code from our new greenfield target repository, ensuring zero accidental mutations to the original application.
Open your Antigravity terminal and run the following setup commands:
git clone https://github.com/GoogleCloudPlatform/devrel-demos.git cd devrel-demos/other/modernizing-expressjs
Once cloned, open the modernizing-expressjs folder directly in the Antigravity IDE explorer. You will observe the following isolated layout:
/modernizing-expressjs/ ├── .agents/ # Skills metadata and checklists │ └── skills/ ├── docs/ # Target directory for reverse-engineered markdown artifacts ├── legacy-app/ # Read-only root of the legacy Express monolith ├── modern-app/ # Greenfield target repository for the Next.js rewrite ├── GEMINI.md # Project-wide agent constitution └── README.md # Companion documentation
Watch this brief video walkthrough demonstrating how to prepare and isolate your monorepo environment deterministically:
3. Architect AI agent skills packs & patterns
Authoring a robust Agent Skill is fundamentally different from writing a standard chat prompt. When you author a Skill Pack, you are designing a modular piece of software that an underlying LLM will execute autonomously. To prevent the agent from hallucinating or experiencing "context window tax", we introduce the open-source Greenfield Orchestration Skill Pack as an extensible authoring template driven by two non-negotiable principles: conciseness and progressive disclosure.
Progressive disclosure using YAML metadata routing
Rather than dumping all target rules into a single monolithic system prompt, we distribute instructions across directories. Every Skill directory contains a SKILL.md entrypoint wrapped in a YAML routing frontmatter block.
Open .agents/skills/orchestrating-greenfield-migration/SKILL.md and inspect the router metadata:
---
name: orchestrating-greenfield-migration
description: >
Manages the end-to-end modernization of legacy Express
monoliths into Next.js architectures. Orchestrates subagents
for auditing, scaffolding, and verification. Use when starting
or managing a greenfield rewrite project.
---
Hardcoding the plan-and-execute pattern
To prevent an autonomous agent from drifting, getting distracted by interesting legacy middleware, or attempting unauthorized database swaps, we override standard open-ended planning by hardcoding the Plan-and-Execute pattern directly into the instructions.
Inspect the literal Markdown checklist embedded inside the main orchestrator:
### Phase 1: The AI audit (reverse engineering)
Dispatch subagents to produce specifications while identifying project-specific test scenarios.
* [ ] Init `docs/verification/Verification_Plan.md` to create baseline template.
* [ ] Run `auditing-data-models` -> Append Data Integrity Stress-Tests.
* [ ] Run `auditing-api-contracts` -> Append API Parity & Edge Case Probes.
* [ ] Run `auditing-business-logic` -> Append Logic & Authorization Stress-Tests.
* [ ] Run `auditing-ui-archeology` -> Append Interaction & Layout Targets.
By formatting the workflow as an explicit checklist with inline skill references, the agent copies this exact roadmap into its task plan, locking it into an "execute-only" mode that systematically checks off boxes and invokes highly specialized subagents exactly when needed.
4. Phase 1 — Reverse-engineer the legacy monolith (audit)
We are ready to trigger our main orchestration sequence! Our first major phase extracts the business rules, data schemas, and API payloads from the legacy monolith, storing them as clean Markdown artifacts while leaving a decade of imperative technical debt behind.
Trigger the autonomous refactoring sequence
In the Antigravity Agent Manager chat panel, type the following custom slash command and press Enter:
/orchestrating-greenfield-migration
Now, observe your terminal console. You will watch the main agent read its system prompt, match your request to the Orchestrator's metadata, output the 5-Phase checklist, and immediately begin dispatching specialized "Auditor" subagents in parallel.
The input/skill/output instructional contract
During Phase 1, the agent executes a strict reverse-engineering pipeline bound by the following instructional contract:
Inputs consumed: Read-only legacy source code files located inside legacy-app/.
Skills invoked:
Skill | Description |
| Traces legacy routes to document exact JSON response envelopes. |
| Deconstructs Mongoose schemas to extract relations, required fields, and defaults. |
| Documents implicit side-effects, Passport auth flows, and middleware rules. |
| Scans legacy Pug templates to map high-level "UI Intent" (navbars, forms). |
Artifacts produced: Highly structured Markdown specifications generated directly into your docs/ folder
Artifact | Description |
| This document details the reverse-engineered API surface area of the legacy Express application. Use this catalog to ensure strict parity when rebuilding routes in the modernized Next.js application. |
| This document logs the verified behaviors, configurations, and strict rules of the legacy Express application concerning authentication (AuthN), authorization (AuthZ), global middlewares, session management, and side-effects. |
| This document provides a comprehensive analysis of the legacy Mongoose schemas from |
| This document provides a detailed analysis of the legacy Pug-based user interface in |
Watch this live terminal capture demonstrating the autonomous reverse-engineering audit in action:
5. Phase 2 & 3 — TDD harness & greenfield backend scaffolding
With the legacy application fully audited and documented, the main orchestrator advances to scaffolding the modern target backend. This phase introduces the most powerful agentic design pattern in our toolkit: closed-loop Reflexion (self-reflection) driven by strict Test-Driven Development (TDD).
Driving self-healing code using Reflexion loops
Writing modern code is straightforward; ensuring it compiles perfectly and passes strict validation constraints requires closed-loop evaluation. The orchestrator handles this autonomously by piping test output directly back into the subagent's context window:
- Phase 2 (TDD setup): The orchestrator invokes the
generating-api-testssubagent, which readsdocs/API_Contracts.mdand writes exhaustive Vitest integration test suites asserting the exact required HTTP status codes and JSON payloads. As expected in TDD, these tests fail initially. - Phase 3 (Backend scaffolding): Scaffolding subagents begin writing modern Next.js Route Handlers and strict Zod validation schemas.
- Self-correction loop: When the deterministic Vitest harness evaluates the new code and returns a failure (e.g., an expected
422validation error returned a500), the agent does not crash. It reflects on the objective error output, reopens the target route handler, fixes the Zod schema payload structure, and runs the tests again. It iterates autonomously until achieving an exit code of0.
The input/skill/output instructional contract
Inputs consumed: Reverse-engineered specification artifacts (docs/API_Contracts.md, docs/Data_Models.md).
Skills invoked:
Skill | Description |
| Generates failing Vitest integration suites. |
| Initializes the base Next.js App Router layout. |
| Configures the local Vitest test runner environment. |
| Translates old Mongoose models into MongoDB + Zod schemas. |
| Rebuilds Express routes into Next.js Route Handlers and modular Route Guards. |
Outputs produced: Initial failing Vitest suites, fully typed Zod schemas, functional Next.js route handlers, and clean, passing test suite executions.
Observe the automated generation of the TDD test harness:
Observe the real-time execution of the self-correcting Reflexion loop scaffolding the target backend:
6. Phase 4 — Scaffold the modern frontend (UI components)
With the backend validation layer fully hardened and passing integration tests, the main orchestrator shifts context to modernize the visual presentation. Imperative server-rendered templates are discarded in favor of a highly accessible, utility-first component design system.
Translating UI intent to composable views
Rather than attempting a line-by-line CSS translation, the frontend subagent reads the extracted "UI Intent" inventory and maps structural elements directly to high-fidelity modern equivalents.
The input/skill/output instructional contract
Inputs consumed: The reverse-engineered frontend inventory artifact (docs/UI_Inventory.md).
Skills invoked:
Skill | Description |
| Translates a |
Outputs produced: Production-ready Next.js frontend pages constructed using highly accessible ShadCN UI components and Tailwind CSS utility layouts.
Watch the autonomous generation of the modernized frontend view layer:
7. Phase 5 — Verification & adversarial auditing
Our refactoring pipeline concludes with a rigorous quality sweep. The main orchestrator transitions from static code analysis to active runtime environment testing, actively attempting to break the new target application to prove absolute functional parity with the legacy baseline.
Executing the two-tab test and browser actuation
The verification phase leverages Antigravity's integrated visual and DOM capabilities to prove success autonomously without requiring you to manually click through forms:
- Side-by-side parity: The
auditing-paritysubagent instructs the local runner to start both the legacy Express monolith and the modernized Next.js application concurrently, verifying identical visual presentation and data rendering. - Adversarial security probing: The orchestrator invokes the
adversarial-verificationsubagent, which launches the Antigravity Browser Subagent. This specialized agent actuates the browser directly—typing into inputs, submitting forms, and probing for security regressions, broken session cookies, or unhandled edge cases. - Audit trail generation: The browser subagent automatically records WebP video captures of its session actuations, attaching them directly to the final migration report as verifiable "proof of work".
The input/skill/output instructional contract
Inputs consumed: Both legacy and modern applications running side-by-side in local runtime environments.
Skills invoked:
Skill | Description |
| Executes runtime side-by-side verification checks. |
| Probes for logic flaws and functional regressions using automated browser actuation. |
Outputs produced: A comprehensive functional parity audit trail paired with recorded browser session videos confirming complete success.
Observe the automated browser subagent actively verifying the modernized application:
8. Post-Migration production readiness & next steps
Congratulations! You have successfully orchestrated a highly advanced, autonomous agentic refactoring pipeline to modernize a legacy monolith from scratch, learning universal, highly transferable skills like progressive disclosure, Plan-and-Execute checklists, and self-healing Reflexion loops.
Preparing for production deployment
With your Next.js application fully verified and audited, you are ready to advance to production integration. Consider implementing these industry-standard next steps:
- Incremental routing: Deploy a reverse proxy (e.g., the Strangler Fig Pattern) to route traffic incrementally from the legacy Express app to the modern target.
- SEO Preservation: Map legacy Express routes to Next.js permanent redirects (
_redirects.yaml) to retain existing domain authority. - Data Streaming: Move from static database seeding to live production data streaming validated securely at runtime using strict Zod schemas.
- Observability: Replace imperative logging utilities with structured OpenTelemetry frameworks.
Deepen your modernization expertise
To explore the complete underlying codebases, custom skill instructions, and exhaustive theoretical rationale driving this pipeline, be sure to read the full parent article:
Join the Agentic Builder community
I hope you found these universal refactoring patterns and agentic pipelines valuable. Stay updated on future open-source skill packs, deep-dive technical content, and upcoming conference speaking engagements by following me across professional channels:
- Follow on LinkedIn: linkedin.com/in/jamesor
- Follow on X (Twitter): x.com/JamesOR
Tell us what you think
What excites you most about agentic orchestration?
Thank you for building with Google Antigravity!