Documentation & Modernization
Two complementary workflows for a repository the user already has checked out
locally, bundled as one skill:
- Documentation mode — produce one definitive, cited architecture document
from the code on disk. Ideal for onboarding, system-design maps, or as the
evidence base for a modernization effort.
- Modernization mode — turn that architecture into a phased, safety-laddered
plan to upgrade, migrate, or rewrite a legacy system.
Mode selection
- If the user wants to understand, document, map, research, or onboard onto a
codebase, run Documentation mode.
- If the user wants to modernize, migrate, upgrade, or rewrite a system, run
Modernization mode. Modernization mode is self-sufficient: if no
architecture document exists yet, it runs the Documentation mode workflow
first (in the same pass), then continues straight through to the plan.
When in doubt, produce the architecture document first — it is the audited
evidence base both modes rely on.
Documentation mode
Generate one definitive, cited architecture document for a repository the user
already has checked out locally. The goal is a writeup someone could hand to a
new engineer as their onboarding reference — broad enough to cover the whole
system, deep enough on the hard parts to be useful, and trustworthy because
every claim traces back to a file on disk.
Why local-first
Reading from the local checkout (not the GitHub API or the web) is the deliberate
default. It is faster, free, avoids rate limits, and — most importantly — it
describes the exact code in front of you rather than whatever main happens
to look like remotely. The one tradeoff is that remote-only facts (star counts,
full CI run history, sibling repos) aren't visible. That's fine: state those as
out-of-scope or mark them [UNVERIFIED] rather than guessing.
Local-first is not local-never-remote: a web/API lookup is a deliberate
last-resort fallback, reserved for a fact that genuinely cannot be determined
from disk and that materially matters to the document. When you do reach for it,
flag the result clearly (e.g. [UNVERIFIED] / sourced-remotely) so the reader
knows it didn't come from the checkout, and never let it become the easy path
that displaces reading the code on disk.
Workflow
- Establish identity first. Run
git remote -v, git branch --show-current,
and git log -1 so the document is anchored to a specific remote, branch, and
commit. A reader must be able to tell which snapshot this describes. Remote
URLs can contain embedded credentials (e.g. https://<token>@github.com/...)
— redact any credentials/tokens from the URL before recording it in the
document.
- Detect, don't assume. Read the real manifests (
go.mod, package.json,
Cargo.toml, pyproject.toml, pom.xml, etc.), the Makefile/task runner,
CI config, and any repo-specific agent or contributor docs (AGENTS.md,
CONTRIBUTING, README, docs/). These are the source of truth for the tech
stack and commands — prefer them over your prior knowledge of the framework.
- Map breadth, then drill into depth. First build the whole-repo map (the
three lenses below), then pick the 2-3 hardest subsystems and go deep on them.
- Verify as you go. Open the files you cite. If you reference a line number,
you should have actually read that line. Unsupported claims are worse than
omissions here — the whole value of this document is that it can be trusted.
Output structure
Produce a single Markdown file with the sections below, in this order. Adapt
the headings to the actual project (a CLI tool has no "frontend" lens — fold that
slot into whatever matters for that repo), but keep the three-lens shape and the
verification discipline.
Part 1 — Whole-repo technical deep-dive
- What the repository is (one paragraph, cited to README).
- Tech-stack detection table: layer | technology | evidence (file+line).
- Entry points (backend, frontend, CLI — whatever applies).
- Commands & Verification Inventory — a table of the canonical project
commands (
command | purpose | evidence), verified against the task runner /
manifests / CI config, not guessed. Cover build, run/serve, test (and how to
run a single test), lint, format, and — where they exist — typecheck,
end-to-end/smoke, contract, and any other gate commands, plus the CI
workflow(s) that run them and on what trigger. Also record whether CI is
enforced — i.e. whether any workflow is a required status check /
branch-protection rule that actually blocks merges, versus one that merely
runs — since that distinction is a manual, human-configured setting that
Modernization mode must surface, not assume. Enforcement usually cannot be
determined from the local checkout alone: ask the user, or mark it
[UNVERIFIED] unless confirmed from an authoritative source (any remote
lookup is a flagged last resort, per the local-first rule above). This
inventory is the source of
truth that downstream planning (Modernization mode) cites so its exit
criteria are runnable, not aspirational. Detect these per-ecosystem (npm/yarn/
pnpm, make, just, cargo, go, poetry/tox/nox, gradle/maven,
etc.) — do not assume a stack. Mark any command you could not verify
[UNVERIFIED].
- Directory layout for each major area, with a one-line purpose per directory.
- Deployment & Runtime Surface — a table of every place the language/runtime
and backing-service versions are pinned for running the system (not just
building it): container base images (
Dockerfile/Containerfile,
docker-compose* build contexts), CI runner images / setup-* versions,
engines/.nvmrc/.tool-versions/runtime.txt, serverless/lambda runtimes,
and stateful data-store image tags (DB/cache/broker/search). Cite each with
file+line. This surface is what a later platform/runtime bump must move in
lockstep — flag any drift between build-runtime and run-runtime here so it's
visible before a modernization plan is written.
- EOL / dead-dependency scan — call out frameworks, runtimes, base images,
and libraries that are end-of-life, unmaintained, or removed in a likely target
major (e.g. a framework whose next major renames namespaces or drops a
component family). Mark each
[INFERRED]/[UNVERIFIED] as appropriate. This is
the raw material Modernization mode's feasibility spike and hazard red-team
build on.
- Data/storage layers, APIs, plugins/extensions, background jobs, CI/CD, testing.
Part 2 — Context & ecosystem
- Local checkout identity table (remote, branch, HEAD commit, version, license).
- Repo-specific agent/contributor docs present, and what rules they encode.
- Developer gotchas (test watch-mode defaults, slow builds, codegen-must-commit,
pre-commit hooks) — each cited.
- How this project relates to its broader ecosystem or sibling services, as
visible from disk (build tags, optional linked repos, separately-deployable
components). Don't import remote ecosystem trivia.
Part 3 — Architectural blueprint
- Tech-stack summary (can reference the Part 1 table).
- C4-style diagrams as Mermaid: Level 1 system context, Level 2 containers,
Level 3 a representative request/component lifecycle.
- Layering and dependency rules (what may depend on what, and what enforces it).
- Cross-cutting concerns table: auth, config, logging, metrics/tracing, secrets,
error handling, feature flags — each with its location and evidence.
- Inferred Architectural Decision Records (reconstructed from code + docs).
- Governance & enforcement mechanisms (CI gates, codegen verification,
CODEOWNERS, review gates, compatibility rules).
- "How to add a feature" guide plus common pitfalls.
Subsystem deep-dives
Identify the 2-3 most complex or architecturally significant subsystems — the
parts a new engineer would most struggle with, such as an evaluation/scheduling
engine, a plugin loader pipeline, a state machine, or a rendering/migration
framework. For each, add a dedicated subsection covering its internal structure,
lifecycle or state machine, key types, and data flow, with local file+line
citations and a small Mermaid diagram where it clarifies the flow. This is what
separates a useful onboarding doc from a directory listing — spend real effort
here.
Confidence assessment
A table of the major claim areas rated High / Inferred / Unverified, so a
reader knows exactly which parts to trust outright and which to double-check.
Footnotes — local file citations
A list of the key local files the document relies on, each with a one-line note
on what it establishes.
Conventions that make the document trustworthy
These are the habits that distinguish this skill's output from a generic
overview. They matter because the document's entire value is that a reader can
rely on it without re-deriving everything.
- Cite every non-obvious claim to a local path, with a line number where it
pins something specific (
pkg/server/server.go#L39-L41). Relative paths from
the repo root keep links clickable.
- Mark uncertainty honestly. Use
[INFERRED] for something you reasoned to
but didn't see stated, and [UNVERIFIED] for something you're repeating but
didn't confirm (e.g. a build-timing claim from a doc you didn't re-measure).
Honest gaps are more useful than false confidence.
- Resolve contradictions, don't restate them. If two sources disagree (say a
version literal in code vs. the manifest), go read the code, decide the real
answer, and label it
[Resolved contradiction] with the explanation. Leaving
a reader to puzzle over a conflict is a failure mode.
- Note compatibility and deploy-cadence rules the repo enforces — separate
FE/BE PRs, bidirectional storage compatibility, additive-only protobuf changes
— because these are the rules a newcomer most easily breaks.
- Prefer precise counts over vague ones. "73 service packages", "89 workflow
files" (from a directory listing) reads as verified; "many services" reads as a
guess.
Scope control
Keep the document grounded in the checkout. It's easy to drift outward into the
project's wider ecosystem (related products, README marketing, satellite repos)
— resist that unless it's visible on disk, and clearly label anything that comes
from outside the local tree. The reader asked for this codebase, documented
faithfully.
Modernization mode
Generate a complete, actionable modernization plan for a legacy codebase. This
skill focuses on the forward-looking work — what to modernize, why, in what
order, and how — but it is self-sufficient: it ensures an architecture
document exists first, producing one via Documentation mode when needed.
Assume dead-by-default. People reach for modernization precisely because the
old stack is hard or impossible to upgrade — EOL runtimes, uncompilable native
modules, retired package mirrors, abandoned frameworks. So this skill does not
assume you can resurrect the legacy toolchain and stand up a fully-green CI gate
before touching anything. That "freeze-then-lift" approach is the lucky case,
not the default. Instead the skill runs a time-boxed feasibility spike, then
picks a migration strategy and a safety strategy matched to how alive the
system actually is. On a truly dead app, building a green legacy gate is itself
a modernization project — a circular trap this skill is designed to avoid.
Three ideas drive the whole plan and are introduced below: the Testability
Milestone (when — per component — the system can actually build, run, and pass
a test again), the safety ladder (the highest rung of regression safety
you can actually reach, with a downgrade treated as a blessed outcome, not a
failure), and the CI Milestone (which phase first stands up CI — and the
reminder that enforcing CI as a required check is a manual human step, not
something the agent can do).
Prerequisites
This skill needs an understanding of the system's architecture before it can
plan. Resolve that as follows:
- If an architecture document already exists — produced by Documentation mode
above, or a README / ARCHITECTURE.md the user points to, or enough
prior conversation context — use it and skip to the workflow below.
- If none exists, run the Documentation mode workflow above first to
generate a cited architecture document, then continue straight through
to Phase 1 below in the same pass. Do not stop to ask the user to run it
separately, and do not pause for review between the two documents.
The result is two artifacts: the architecture document (the audited evidence
base) and this modernization plan (the forward-looking action set).
Before planning, confirm a Commands & Verification Inventory exists. Exit
criteria are only worth anything if they are runnable, so the plan must be able
to cite the project's canonical build / run / test / lint / typecheck / e2e /
contract commands and CI gate(s). Documentation mode produces this
inventory in Part 1; if you're working from a README or prior context that lacks
it, detect and record those commands yourself (per-ecosystem — npm/yarn/pnpm,
make, just, cargo, go, poetry/tox/nox, gradle/mvn, etc.) before
writing exit criteria. Never invent a command you haven't verified against the
task runner / manifests / CI config.
Workflow
Phase 1: Assess Current State (from existing docs)
Read the architecture document and extract:
- Tech stack inventory — languages, frameworks, runtimes, dependencies with
versions where visible
- Feature/domain map — the major functional areas of the system
- Pain points already identified — tech debt, concerns, deprecated deps,
architectural violations noted in the existing docs
- Deployment and infrastructure — how it runs today
Do NOT re-read every source file. Trust the architecture doc. Only open specific
files if a modernization question requires verifying a detail (e.g., "is this
dependency actually used or just declared?").
Phase 2: Feasibility Spike, Strategy Fork & Safety Ladder
This is the pivot of the whole plan. Do it before recommending a target
architecture or writing any phases. Its job is to answer, quickly and honestly:
how alive is this system, what migration shape fits, and how much regression
safety can we actually achieve?
2a. Run a time-boxed feasibility spike
Put a hard time box on it (e.g. one day). The spike's question is NOT "can
we make CI green?" — it is "can we get this to run even once to capture its
behavior?" Probe, per component / deployable unit:
- Does it install its dependencies today (ideally from a committed
lockfile without hand-patching)?
- Do native/build steps succeed on a currently supported toolchain?
- Does it boot / start?
- Can the test runner execute at all, and does ≥1 meaningful test pass?
Record what you actually observed — including partial success (common in
monorepos: one service installs and tests green while another can't compile). Do
not sink two sprints resurrecting a corpse to discover it's unresurrectable.
When the time box expires, decide with the evidence you have.
2b. Locate the Testability Milestone (per component)
"Testable" is not a precondition you can satisfy on a dead app — for a dead app
it is an output of modernization, not an input. So every plan must name, up
front, its Testability Milestone: the specific phase at which the system
(or a given component) first satisfies all four conditions at once:
- Runs on a supported (non-EOL) runtime.
- Dependencies install from a lockfile without hand-patching.
- Native / build steps succeed on the current toolchain.
- The test runner executes and ≥1 meaningful test passes in CI.
Assess this per component — as the reference Nylas run showed, a near-modern
cloud service can cross the line immediately while a legacy Electron client
doesn't cross it until several phases later. This milestone is the single most
important marker in the plan. State where it lands for each component, out loud.
2c. Label every phase pre- or post-testability
The Testability Milestone splits the effort into two regimes with different
safety rules:
- Pre-testability ("dark") regime: the component can't be trusted to run.
Safety comes from non-test sources (see the safety ladder below).
Requiring a CI test gate here is a category error — you're demanding green
tests from something that isn't alive yet.
- Post-testability ("lit") regime: it builds and runs on a live, supported
stack. Now real CI, characterization, and e2e are achievable and worth the
investment. The classic green-gate belongs here.
Rule: never require an automated test gate on a component before that component
crosses its own testability line.
2d. Choose the migration strategy — the A/B fork
The spike decides which of two shapes fits (this is a per-component call in a
monorepo):
- (A) Freeze-then-lift. Net the old app as-is, then upgrade under the net.
Requires the old app to be resurrectable at acceptable cost — i.e. it
almost runs. This is the traditional "characterization tests before you
change anything" path. Opt-in, not the default.
- (B) Beachhead-then-expand (walking skeleton). Don't net the corpse. Drive
the thinnest possible end-to-end slice onto the modern stack until it
builds, boots, and tests; then strangle the rest in, writing tests on the new
stack as you go. This is the default for dead apps. In strategy B, the
first phase is "reach the Testability Milestone with the smallest slice," not
"freeze the whole legacy toolchain."
If a component can't be built or run at all, characterization tests on the
old stack are impossible by definition — invert the approach: stop trying to
net the corpse and build the net on the target stack incrementally, using the
old code/output as the reference oracle.
2e. Pick the highest achievable rung on the safety ladder
Regression safety is a ladder, not a binary. Choose the highest rung you can
actually reach per component; a downgrade to a lower rung is a blessed,
first-class outcome — not a failure — provided the residual risk is named.
- L4 — Full automated gate: green lint + unit + characterization + e2e in CI.
- L3 — Partial gate: some suites green + lockfile + CI on the achievable
subset; the rest quarantined with a named list.
- L2 — Characterization / golden-master only: can't run in CI, but capture
I/O snapshots / behavioral diffs (manual is acceptable).
- L1 — Reversibility-based: no runnable tests; safety comes from small
reversible steps, strangler / parallel-run, a smoke checklist, and review.
- L0 — No net possible: treat as a spec-driven rewrite (old code = the spec)
or archive.
Safety is not only tests. There are at least five sources, and on dead apps
2–4 often outweigh 1:
- Tests (characterization / unit / e2e) — strongest, often unachievable on
dead apps.
- Reversibility — tiny commits, branch-per-change, trivial rollback.
- Isolation — feature flags, strangler-fig, run old + new in parallel and
diff outputs.
- The running old system as an oracle — record/replay real I/O to
characterize behavior without a test harness.
- Human review + domain knowledge.
Anchor safety at the behavioral seams, not the unit. The durable,
stack-agnostic contracts of any app are its externally observable behaviors:
HTTP endpoints, DB schema/queries, file/wire formats, CLI output, protocols. Pin
those as golden-master / approval snapshots — they survive the rewrite; unit
tests on dead legacy code get deleted the moment you replace the module. Get an
oracle, ranked by what's available:
- Best — it runs somewhere (prod, a VM, an old container, even read-only),
and you're allowed to use it: record real I/O and replay it against the new
code. One successful capture beats a permanent green legacy CI. (Do not assume
this rung is always available — a faithful third-party reimplementation or a
resurrected legacy binary may be off-limits by policy, licensing, or an
explicit decision to build "with only what we have." If so, skip to the
self-frozen rung.)
- Fallback — it doesn't run at all: the old source is the spec;
supplement with prod logs, DB dumps, docs, tickets, and accept that
characterization tests get written against the new implementation to lock
it once verified correct.
- Self-frozen golden master — no external reference exists or is permitted:
when nothing trustworthy runs and you may not borrow an external oracle, the
modernized component records its own golden master the moment it first runs
(at its Testability Milestone), and every later phase diffs against that frozen
snapshot. This is a real, usable rung — but name its residual risk out loud:
it guarantees the self-consistency of later refactors, not the correctness
of the first boot (the snapshot is only as correct as the run that produced it).
Pair it with human review / spec cross-checks to bless that first run.
2f. Feed an economic/oracle triage into the choice
Weigh regression cost when picking a rung: Is the app in production? Does
it have real users? Is the old system still runnable as a reference? An
abandoned app with zero users has near-zero regression cost — an expensive gate
there is over-engineering. A production system with users justifies a higher
rung and a real oracle.
2g. Locate the CI Milestone (name the phase that stands up CI)
Just as the Testability Milestone names when a component can first run and be
tested, the CI Milestone names when continuous integration is first stood
up — and it must be stated out loud in the roadmap, not buried in a phase
body. A common failure of modernization plans is leaving the reader unable to
tell which phase introduces CI; name it explicitly.
Rule: CI is stood up in the first lit phase — at or immediately after the
component crosses its Testability Milestone — never before. CI cannot be green
on a component that cannot yet build/run, so wiring a CI gate during the dark
regime is the same category error as demanding a test gate there. (Trivial
scaffolding — a lint-only or build-only workflow — may appear earlier, but the
authoritative test gate lands at the CI Milestone.)
CI is two distinct steps, and the second is human-only — call both out:
- Author the CI workflow file (e.g.
.github/workflows/*.yml, .gitlab-ci.yml,
Azure Pipelines) that runs the gate. An agent can do this.
- Make that workflow an enforced gate — a required status check /
branch-protection rule / merge-request approval rule. This is a manual
platform-UI / admin step (GitHub → Settings → Branches; GitLab protected
branches + MR settings; etc.) that an agent cannot perform. Until a human
configures it, CI runs on PRs but does not block merges.
Because step 2 is outside the agent's reach, every plan that stands up CI must
emit it as an explicit user action item (in the phase's exit criteria and in
§9 Open questions / decisions needed from stakeholders), so the reader knows the
gate is not self-enforcing until they turn it on.
Output of Phase 2: for each component — the spike result, the chosen strategy
(A or B), the located Testability Milestone, the pre/post label, and the target
safety-ladder rung with any residual risk named — plus the plan-wide CI
Milestone (which phase stands up CI) and the reminder that enforcing it is a
manual human step. Everything downstream depends on these.
Phase 2.5: Red-team every phase against the hazard catalog (mandatory)
The strategic scaffolding above (testability, safety ladder, CI milestone) is
necessary but not sufficient. Modernization plans also fail on tactical,
ecosystem-predictable hazards — an incomplete quarantine set, a forgotten
namespace codemod, a runtime bump that leaves the base images behind, a stateful
data-store major treated as an image bump, an edge rewrite that drops the
anonymous route class. These are so recurring that they have their own catalog:
references/migration-hazards.md (H1–H8).
Rule: before any phase is implemented, red-team its plan against every hazard
in references/migration-hazards.md. For each hazard, ask "does this phase
trigger it?", run the hazard's detection probe against the real repo, and fold
its plan action into the phase's tasks/exit criteria before writing code. A
hazard caught in planning is a task; caught in review it's rework; caught in prod
it's an incident. Record hazards you checked and cleared, not just the ones
that fired — a silent skip is indistinguishable from a miss.
This is the institutionalized form of an independent-critic pass. Do it yourself
by walking the catalog, and — where an independent second opinion is available
(e.g. a rubber-duck / critique agent) — use it: on the reference PiggyMetrics run
such a pass caught a blocking plan gap in every single phase, and each gap
was an instance of an H1–H8 class. Bake the outcome into each phase's
"Decisions made" and exit criteria so the executing agent inherits the cleared
checklist rather than re-discovering the hazard.
Phase 3: Recommend Target Architecture
Decision framework — always evaluate in this order:
For each component/dependency, work through these levels from least-disruptive to
most-disruptive. Stop at the first level that solves the problem:
Upgrade in place — Can you bump the major version and fix breakages?
(e.g., Node 14→22, Python 2→3, React 16→19, Rails 5→7). This is the default
answer. Only reject it if the upgrade path is officially unsupported, the
breaking changes are so extensive they exceed rewrite cost, or the framework
itself is abandoned/EOL.
Swap the dependency — If the specific library is dead but the pattern is
fine, can you swap to a maintained alternative with the same interface shape?
(e.g., Moment.js → date-fns, Request → got/fetch, CoffeeScript → TypeScript
with decaffeinate). Prefer drop-in or mechanical migration tools when they
exist.
Wrap/adapt (Strangler Fig) — If the component's interface is sound but
internals are unmaintainable, can you put a clean interface in front and
incrementally replace internals behind it? This works when coupling is
manageable and the system can run with old and new coexisting.
Rewrite — Only when: the framework is abandoned with no upgrade path, the
architecture fundamentally cannot support required new capabilities (e.g.,
synchronous-only design that must become real-time), or honest estimation shows
upgrade cost exceeds rewrite cost. Require explicit justification for every
rewrite recommendation — "it's old" is not sufficient.
Remove — Dead code, features with zero usage, deprecated capabilities
superseded by other systems. Verify usage claims before recommending removal.
Bias toward conservatism. The cheapest migration is the one you don't do.
Every level of disruption adds risk, timeline, and cost. A working system on an
older framework is better than a half-finished rewrite on a new one.
Mechanical-migration riders (apply whenever a recommendation is an upgrade,
swap, or removal). These are the parts of a target-architecture decision that
first-draft plans routinely drop; each maps to a hazard class in
references/migration-hazards.md:
- Transitive-quarantine completeness (H1). When removing/cutting over a whole
dependency family, grep the dead artifact across all manifests and list the
full set of dependents that must move or be quarantined — not the subset you
first thought of. State the post-cutover build target explicitly.
- Framework-major codemods (H2). A major bump carries mechanical breaking
changes independent of your logic — namespace renames, removed deprecated APIs,
a changed test engine, changed config keys. Enumerate each as its own task
and prefer the ecosystem's automated recipe/codemod tool (OpenRewrite,
jscodeshift/react-codemod,
2to3/pyupgrade, etc.) over hand-editing on large
trees. Don't forget the test-framework migration — it is the most-forgotten one.
- Runtime↔deployment lockstep (H3). If a recommendation bumps the
language/runtime major, every place the runtime is pinned for running the
app — base images,
docker-compose build contexts, CI runner images,
engines/.nvmrc/.tool-versions, serverless runtimes — must move in the
same phase. Build-runtime and run-runtime must never drift across a phase
boundary, or the app builds green and then fails to run.
Produce a Target Architecture section that includes:
- Recommended tech stack with rationale for each choice (framework, language,
runtime, database, infrastructure)
- Architectural pattern recommendation (monolith → modular monolith →
services, event-driven, serverless, etc.) with justification
- What stays vs. what goes — explicitly categorize each major component using
the decision framework above:
- ✅ Keep as-is (still modern/adequate)
- ⬆️ Upgrade in place (bump version, fix breakages)
- 🔀 Swap dependency (replace dead library with maintained equivalent)
- 🔄 Wrap/adapt (add an interface layer, incrementally replace internals)
- 🔁 Rewrite (fundamentally incompatible — justification required)
- 🗑️ Remove (dead code, deprecated features, superseded)
For each recommendation, write an inline ADR:
#### ADR: [Decision Title]
- **Context:** [Why this decision is needed]
- **Decision:** [What we chose and which decision framework level it falls under]
- **Alternatives considered:** [What else was evaluated and why it lost]
- **Consequences:** [Tradeoffs accepted]
Phase 4: Per-Feature Migration Analysis
For each major feature/domain identified in the architecture doc, produce a
section covering:
- Current implementation — one paragraph summary with file references
- Migration strategy — the A/B choice from Phase 2 for this component
(Freeze-then-lift vs. Beachhead/walking-skeleton), plus the tactic: Strangler
Fig, Big Bang rewrite, Lift & Shift, Incremental Refactor, or Leave In Place
- Testability status — where this component's Testability Milestone
lands, and its safety-ladder rung (L0–L4) with residual risk named
- Dependencies and coupling — what else breaks or must move with it
- Effort estimate — T-shirt size (XS/S/M/L/XL) with justification
- Risk assessment — what can go wrong, data migration concerns, user impact
- Acceptance criteria — how you know the migration succeeded (expressed
against the chosen oracle/seam contracts, not against a not-yet-alive test
suite)
Phase 5: Phased Implementation Plan
Produce an ordered, phased plan. Each phase should be independently deployable
(no half-migrated states that can't run in production).
Phase gating is regime-aware (applies to every phase). State this rule at the
top of the phased plan and honor it in every phase's exit criteria. A phase is
not complete until its Verification & Exit Criteria pass. Those criteria must
be (a) objectively verifiable; (b) actually executed and recorded before
the next phase starts; and (c) gated — do not advance to phase N+1 until
phase N's criteria are demonstrably met. But which criteria are valid depends
on the component's regime (Phase 2c):
- Post-testability ("lit") phases: exit criteria are runnable commands / green
CI — green CI on the phase's branch/PR is the authoritative signal.
- Pre-testability ("dark") phases: the component isn't alive yet, so a green
CI test gate is a category error. Exit criteria come from the achievable
safety-ladder rung instead — captured seam/oracle snapshots, reversibility
scaffolding proven present, a passed smoke checklist, recorded review. Do not
block a dark-regime phase on a test suite that can't run yet.
Report to the user any phase whose pass/fail is unknown rather than assuming it
passed.
The first phase establishes maximum achievable safety — not a fixed "green
legacy gate." Do not hard-code "resurrect everything and make CI green." Shape
the first phase from the Phase 2 outputs, per component:
- Strategy A (Freeze-then-lift), component is resurrectable: the first phase
is the classic Safety Net & Baseline — purely additive, no behavior change:
- Characterization / golden / contract tests at the seams that pin
current observable behavior (protocol traces, API snapshots, output goldens).
- CI + lint + formatter wired up and green (an authoritative gate for later
lit-regime phases).
- Pinned dependencies / committed lockfile and a recorded known-good
baseline (versions, toolchain, how it builds and runs today).
- "Net proven to fail." Deliberately mutate the code (e.g., change one
protocol code or return value), confirm the new tests go red, then
revert. A safety net that never fails is proof of nothing — prove it has
teeth.
- Strategy B (Beachhead/walking-skeleton), component is dead: the first phase
is "reach the Testability Milestone with the smallest slice" — drive the
thinnest end-to-end path onto the modern stack until it builds, boots, and runs
≥1 real test green, capturing seam/oracle contracts from the old system to
validate against. Do not try to net the corpse. Its exit criterion is the
achievable safety-ladder rung with residual risk named — a blessed downgrade
is not a failure.
Only after the first phase's criteria are met (at whatever rung) do the
subsequent infrastructure and feature phases begin.
Structure each phase as:
### Phase N: [Name] (T-shirt size: M)
**Goal:** [One sentence]
**Regime:** [pre-testability ("dark") | post-testability ("lit")] — per component
**Safety rung:** [L0–L4, with residual risk named if below L4]
**Prerequisites:** [Which phases must complete first]
**Duration estimate:** [Relative, not calendar — e.g., "2-4 sprints"]
#### Tasks
| ID | Task | Component | Blocked by |
|----|------|-----------|------------|
| N.1 | ... | ... | — |
| N.2 | ... | ... | N.1 |
#### Risks & Mitigations
- **Risk:** ... → **Mitigation:** ...
#### Decisions made
- [Every sub-decision this phase depends on, resolved and documented here so the
phase can be implemented without further user input. State "dropped" vs
"deferred" explicitly for anything cut.]
#### Verification & Exit Criteria (Definition of Done)
- [ ] [Regime-appropriate criterion. For LIT phases: a runnable command / green
CI check, citing the actual command from the Commands & Verification
Inventory. For DARK phases: the achievable safety-ladder rung's evidence —
captured seam/oracle snapshots, reversibility proven, smoke checklist
passed — NOT a green test suite the component can't yet run.]
- [ ] [Include a parity/characterization check against the chosen oracle whenever
the change is meant to preserve behavior.]
- [ ] [If purely additive, assert it: "no behavior/dependency/logic changed."]
- [ ] [If exiting below L4, state the residual risk and which later phase closes
it (e.g., "client test gate deferred to the client-migration phase").]
Ordering principles:
- Locate the Testability Milestone first, per component — schedule the
smallest slice that reaches it early rather than deferring "testable" to the end
while demanding a gate at the start.
- Never require a component's automated test gate before it crosses its own
testability line.
- Name the CI Milestone in the roadmap. State explicitly which phase stands
up CI (the first lit phase, at/after the Testability Milestone) so the reader
never has to guess when CI arrives — and flag that enforcing it (required
status check / branch protection) is a manual human step, not an agent task.
- First-phase safety before behavior change — establish the highest
achievable rung (not necessarily a full green gate) before modifying behavior.
- Infrastructure and cross-cutting concerns next (auth, config, logging, CI/CD)
- Highest-risk or highest-value features next (prove the pattern early)
- Low-risk, low-coupling features last (easy wins to parallelize)
- Data migrations get their own phase with rollback plans
Phase 6: Execution Governance
Modernization plans fail in execution, not on paper. Bake in the governance that
keeps each phase honest and reversible (generic across any ecosystem):
- Branch per phase. Never commit phase work to the default branch. Open one
PR per phase; let CI on the PR be the authoritative green signal before merge
for lit-regime phases. For dark-regime phases, the PR still carries the
rung's evidence (captured contracts, smoke results, reversibility scaffolding).
- Merge to trunk before the next phase; never stack (H7). Each phase branch
is cut from trunk, and its PR is merged to trunk before the next phase
starts. Never base a phase branch or its PR on a sibling phase branch — that
is how PRs get merged into each other, the trunk silently stalls several phases
behind, and later phases are forced into the exact bind where the no-stacking
rule has to be broken. Before starting a phase, verify the previous phase is
merged to trunk and
git log origin/<trunk>..HEAD is empty at branch creation.
If controlled stacking is genuinely unavoidable, it is allowed only with a
required reconciliation PR that lands the stack onto trunk and an explicit
residual-risk note — never as a silent default.
- Confirm the trunk name; retire legacy defaults. Pin the repo's real trunk
(e.g.
main) and, if a second default-ish branch exists (master), mark it
"history only — do not target" so phase work never lands on the wrong branch.
- The gate matches the regime. Lit phases advance on green CI; dark phases
advance on the achievable safety-ladder rung with residual risk named — not on
a "looks done" judgement, and not on a test suite that can't run yet.
- Stand up CI at the CI Milestone, and hand off enforcement to a human.
Name the phase that introduces CI (the first lit phase). Distinguish the two
steps: authoring the workflow file is agent-doable; making it an enforced
required status check / branch-protection (or MR-approval) rule is a manual
platform-UI step the agent cannot perform. Until a human configures it, CI
runs but does not block merges — so record "enable branch protection /
required checks" as an explicit user action item (in the CI phase's exit
criteria and in §9 stakeholder decisions), never as a completed agent task.
- Interface-preserving & independently deployable. Each phase leaves the
system runnable, so rollback = redeploy the previous version. Prefer
interface-preserving rewrites (wrap internals behind a stable interface) and
prove equivalence with the seam/oracle contracts (golden/characterization
tests where they exist).
- Living plan. Update
MODERNIZATION_PLAN.md status markers as each phase's
exit criteria are met — ✅ complete / ⏭️ descoped / 🗑️ dropped — record the
decisions made during implementation, and **update the safety-ladder rung /
…(truncated)
1---
2name: doc-and-modernize
3description: ">- Two related workflows for a locally-cloned codebase, in one skill. Documentation mode produces a single, comprehensive, verifiable architecture document primarily by reading files on disk (local-first) — use it whenever the user wants to understand, map, document, research, or onboard onto a codebase (\"research this repo\", \"write up the architecture\", \"do an architecture deep dive\", \"document how this codebase works\", \"map the system design\", \"create an onboarding doc\"). Modernization mode generates a phased plan to modernize, migrate, upgrade, or rewrite a legacy system (\"modernize this\", \"plan the migration\", \"how would we rewrite this\", \"how do we get off this legacy stack\"); if no architecture document exists yet it first runs Documentation mode, then continues straight through to the plan. It assumes the legacy stack may be dead, runs a time-boxed feasibility spike, and picks..."
4category: engineering-core
5source_repo: github/awesome-copilot
6source_path: "skills/doc-and-modernize/SKILL.md"
7source_url: https://github.com/github/awesome-copilot/blob/HEAD/skills/doc-and-modernize/SKILL.md
8metadata:
9 source: https://skillmd.com/skills/thedixitjain/doc-and-modernize
10---
11# Documentation & Modernization
12
13Two complementary workflows for a repository the user already has checked out
14locally, bundled as one skill:
15
16- **Documentation mode** — produce one definitive, cited architecture document
17 from the code on disk. Ideal for onboarding, system-design maps, or as the
18 evidence base for a modernization effort.
19- **Modernization mode** — turn that architecture into a phased, safety-laddered
20 plan to upgrade, migrate, or rewrite a legacy system.
21
22## Mode selection
23
24- If the user wants to **understand, document, map, research, or onboard onto** a
25 codebase, run **Documentation mode**.
26- If the user wants to **modernize, migrate, upgrade, or rewrite** a system, run
27 **Modernization mode**. Modernization mode is self-sufficient: if no
28 architecture document exists yet, it runs the **Documentation mode** workflow
29 first (in the same pass), then continues straight through to the plan.
30
31When in doubt, produce the architecture document first — it is the audited
32evidence base both modes rely on.
33
34## Documentation mode
35
36Generate one definitive, cited architecture document for a repository the user
37already has checked out locally. The goal is a writeup someone could hand to a
38new engineer as their onboarding reference — broad enough to cover the whole
39system, deep enough on the hard parts to be useful, and trustworthy because
40every claim traces back to a file on disk.
41
42### Why local-first
43
44Reading from the local checkout (not the GitHub API or the web) is the deliberate
45**default**. It is faster, free, avoids rate limits, and — most importantly — it
46describes *the exact code in front of you* rather than whatever `main` happens
47to look like remotely. The one tradeoff is that remote-only facts (star counts,
48full CI run history, sibling repos) aren't visible. That's fine: state those as
49out-of-scope or mark them `[UNVERIFIED]` rather than guessing.
50
51Local-first is not local-*never*-remote: a web/API lookup is a deliberate
52**last-resort fallback**, reserved for a fact that genuinely cannot be determined
53from disk and that materially matters to the document. When you do reach for it,
54flag the result clearly (e.g. `[UNVERIFIED]` / sourced-remotely) so the reader
55knows it didn't come from the checkout, and never let it become the easy path
56that displaces reading the code on disk.
57
58### Workflow
59
601. **Establish identity first.** Run `git remote -v`, `git branch --show-current`,
61 and `git log -1` so the document is anchored to a specific remote, branch, and
62 commit. A reader must be able to tell which snapshot this describes. Remote
63 URLs can contain embedded credentials (e.g. `https://<token>@github.com/...`)
64 — **redact any credentials/tokens** from the URL before recording it in the
65 document.
662. **Detect, don't assume.** Read the real manifests (`go.mod`, `package.json`,
67 `Cargo.toml`, `pyproject.toml`, `pom.xml`, etc.), the `Makefile`/task runner,
68 CI config, and any repo-specific agent or contributor docs (`AGENTS.md`,
69 `CONTRIBUTING`, `README`, `docs/`). These are the source of truth for the tech
70 stack and commands — prefer them over your prior knowledge of the framework.
713. **Map breadth, then drill into depth.** First build the whole-repo map (the
72 three lenses below), then pick the 2-3 hardest subsystems and go deep on them.
734. **Verify as you go.** Open the files you cite. If you reference a line number,
74 you should have actually read that line. Unsupported claims are worse than
75 omissions here — the whole value of this document is that it can be trusted.
76
77### Output structure
78
79Produce a **single Markdown file** with the sections below, in this order. Adapt
80the headings to the actual project (a CLI tool has no "frontend" lens — fold that
81slot into whatever matters for that repo), but keep the three-lens shape and the
82verification discipline.
83
84#### Part 1 — Whole-repo technical deep-dive
85- What the repository is (one paragraph, cited to README).
86- Tech-stack detection table: layer | technology | evidence (file+line).
87- Entry points (backend, frontend, CLI — whatever applies).
88- **Commands & Verification Inventory** — a table of the canonical project
89 commands (`command | purpose | evidence`), verified against the task runner /
90 manifests / CI config, not guessed. Cover build, run/serve, test (and how to
91 run a single test), lint, format, and — where they exist — typecheck,
92 end-to-end/smoke, contract, and any other gate commands, plus the CI
93 workflow(s) that run them and on what trigger. **Also record whether CI is
94 *enforced*** — i.e. whether any workflow is a **required status check /
95 branch-protection rule** that actually blocks merges, versus one that merely
96 runs — since that distinction is a manual, human-configured setting that
97 Modernization mode must surface, not assume. Enforcement usually cannot be
98 determined from the local checkout alone: ask the user, or mark it
99 `[UNVERIFIED]` unless confirmed from an authoritative source (any remote
100 lookup is a flagged last resort, per the local-first rule above). This
101 inventory is the source of
102 truth that downstream planning (Modernization mode) cites so its exit
103 criteria are runnable, not aspirational. Detect these per-ecosystem (npm/yarn/
104 pnpm, `make`, `just`, `cargo`, `go`, `poetry`/`tox`/`nox`, `gradle`/`maven`,
105 etc.) — do not assume a stack. Mark any command you could not verify
106 `[UNVERIFIED]`.
107- Directory layout for each major area, with a one-line purpose per directory.
108- **Deployment & Runtime Surface** — a table of every place the language/runtime
109 and backing-service versions are pinned *for running* the system (not just
110 building it): container base images (`Dockerfile`/`Containerfile`,
111 `docker-compose*` build contexts), CI runner images / `setup-*` versions,
112 `engines`/`.nvmrc`/`.tool-versions`/`runtime.txt`, serverless/lambda runtimes,
113 and stateful data-store image tags (DB/cache/broker/search). Cite each with
114 file+line. This surface is what a later platform/runtime bump must move in
115 lockstep — flag any drift between build-runtime and run-runtime here so it's
116 visible before a modernization plan is written.
117- **EOL / dead-dependency scan** — call out frameworks, runtimes, base images,
118 and libraries that are end-of-life, unmaintained, or removed in a likely target
119 major (e.g. a framework whose next major renames namespaces or drops a
120 component family). Mark each `[INFERRED]`/`[UNVERIFIED]` as appropriate. This is
121 the raw material Modernization mode's feasibility spike and hazard red-team
122 build on.
123- Data/storage layers, APIs, plugins/extensions, background jobs, CI/CD, testing.
124
125#### Part 2 — Context & ecosystem
126- Local checkout identity table (remote, branch, HEAD commit, version, license).
127- Repo-specific agent/contributor docs present, and what rules they encode.
128- Developer gotchas (test watch-mode defaults, slow builds, codegen-must-commit,
129 pre-commit hooks) — each cited.
130- How this project relates to its broader ecosystem or sibling services, *as
131 visible from disk* (build tags, optional linked repos, separately-deployable
132 components). Don't import remote ecosystem trivia.
133
134#### Part 3 — Architectural blueprint
135- Tech-stack summary (can reference the Part 1 table).
136- C4-style diagrams as Mermaid: Level 1 system context, Level 2 containers,
137 Level 3 a representative request/component lifecycle.
138- Layering and dependency rules (what may depend on what, and what enforces it).
139- Cross-cutting concerns table: auth, config, logging, metrics/tracing, secrets,
140 error handling, feature flags — each with its location and evidence.
141- Inferred Architectural Decision Records (reconstructed from code + docs).
142- Governance & enforcement mechanisms (CI gates, codegen verification,
143 CODEOWNERS, review gates, compatibility rules).
144- "How to add a feature" guide plus common pitfalls.
145
146#### Subsystem deep-dives
147Identify the 2-3 most complex or architecturally significant subsystems — the
148parts a new engineer would most struggle with, such as an evaluation/scheduling
149engine, a plugin loader pipeline, a state machine, or a rendering/migration
150framework. For each, add a dedicated subsection covering its internal structure,
151lifecycle or state machine, key types, and data flow, with local file+line
152citations and a small Mermaid diagram where it clarifies the flow. This is what
153separates a useful onboarding doc from a directory listing — spend real effort
154here.
155
156#### Confidence assessment
157A table of the major claim areas rated **High / Inferred / Unverified**, so a
158reader knows exactly which parts to trust outright and which to double-check.
159
160#### Footnotes — local file citations
161A list of the key local files the document relies on, each with a one-line note
162on what it establishes.
163
164### Conventions that make the document trustworthy
165
166These are the habits that distinguish this skill's output from a generic
167overview. They matter because the document's entire value is that a reader can
168rely on it without re-deriving everything.
169
170- **Cite every non-obvious claim** to a local path, with a line number where it
171 pins something specific (`pkg/server/server.go#L39-L41`). Relative paths from
172 the repo root keep links clickable.
173- **Mark uncertainty honestly.** Use `[INFERRED]` for something you reasoned to
174 but didn't see stated, and `[UNVERIFIED]` for something you're repeating but
175 didn't confirm (e.g. a build-timing claim from a doc you didn't re-measure).
176 Honest gaps are more useful than false confidence.
177- **Resolve contradictions, don't restate them.** If two sources disagree (say a
178 version literal in code vs. the manifest), go read the code, decide the real
179 answer, and label it `[Resolved contradiction]` with the explanation. Leaving
180 a reader to puzzle over a conflict is a failure mode.
181- **Note compatibility and deploy-cadence rules** the repo enforces — separate
182 FE/BE PRs, bidirectional storage compatibility, additive-only protobuf changes
183 — because these are the rules a newcomer most easily breaks.
184- **Prefer precise counts over vague ones.** "73 service packages", "89 workflow
185 files" (from a directory listing) reads as verified; "many services" reads as a
186 guess.
187
188### Scope control
189
190Keep the document grounded in the checkout. It's easy to drift outward into the
191project's wider ecosystem (related products, README marketing, satellite repos)
192— resist that unless it's visible on disk, and clearly label anything that comes
193from outside the local tree. The reader asked for *this codebase*, documented
194faithfully.
195
196## Modernization mode
197
198Generate a complete, actionable modernization plan for a legacy codebase. This
199skill focuses on the forward-looking work — what to modernize, why, in what
200order, and how — but it is **self-sufficient**: it ensures an architecture
201document exists first, producing one via Documentation mode when needed.
202
203**Assume dead-by-default.** People reach for modernization precisely because the
204old stack is hard or impossible to upgrade — EOL runtimes, uncompilable native
205modules, retired package mirrors, abandoned frameworks. So this skill does **not**
206assume you can resurrect the legacy toolchain and stand up a fully-green CI gate
207before touching anything. That "freeze-then-lift" approach is the *lucky* case,
208not the default. Instead the skill runs a **time-boxed feasibility spike**, then
209picks a migration strategy and a **safety strategy** matched to how alive the
210system actually is. On a truly dead app, building a green legacy gate *is itself
211a modernization project* — a circular trap this skill is designed to avoid.
212
213Three ideas drive the whole plan and are introduced below: the **Testability
214Milestone** (when — per component — the system can actually build, run, and pass
215a test again), the **safety ladder** (the highest rung of regression safety
216you can actually reach, with a downgrade treated as a blessed outcome, not a
217failure), and the **CI Milestone** (which phase first stands up CI — and the
218reminder that *enforcing* CI as a required check is a manual human step, not
219something the agent can do).
220
221### Prerequisites
222
223This skill needs an understanding of the system's architecture before it can
224plan. Resolve that as follows:
225
2261. If an architecture document already exists — produced by **Documentation mode**
227 above, or a README / ARCHITECTURE.md the user points to, or enough
228 prior conversation context — use it and skip to the workflow below.
2292. **If none exists, run the Documentation mode workflow above first** to
230 generate a cited architecture document, then continue **straight through**
231 to Phase 1 below in the same pass. Do not stop to ask the user to run it
232 separately, and do not pause for review between the two documents.
233
234The result is two artifacts: the architecture document (the audited evidence
235base) and this modernization plan (the forward-looking action set).
236
237**Before planning, confirm a Commands & Verification Inventory exists.** Exit
238criteria are only worth anything if they are *runnable*, so the plan must be able
239to cite the project's canonical build / run / test / lint / typecheck / e2e /
240contract commands and CI gate(s). Documentation mode produces this
241inventory in Part 1; if you're working from a README or prior context that lacks
242it, detect and record those commands yourself (per-ecosystem — npm/yarn/pnpm,
243`make`, `just`, `cargo`, `go`, `poetry`/`tox`/`nox`, `gradle`/`mvn`, etc.) before
244writing exit criteria. Never invent a command you haven't verified against the
245task runner / manifests / CI config.
246
247### Workflow
248
249#### Phase 1: Assess Current State (from existing docs)
250
251Read the architecture document and extract:
252
2531. **Tech stack inventory** — languages, frameworks, runtimes, dependencies with
254 versions where visible
2552. **Feature/domain map** — the major functional areas of the system
2563. **Pain points already identified** — tech debt, concerns, deprecated deps,
257 architectural violations noted in the existing docs
2584. **Deployment and infrastructure** — how it runs today
259
260Do NOT re-read every source file. Trust the architecture doc. Only open specific
261files if a modernization question requires verifying a detail (e.g., "is this
262dependency actually used or just declared?").
263
264#### Phase 2: Feasibility Spike, Strategy Fork & Safety Ladder
265
266This is the pivot of the whole plan. **Do it before recommending a target
267architecture or writing any phases.** Its job is to answer, quickly and honestly:
268*how alive is this system, what migration shape fits, and how much regression
269safety can we actually achieve?*
270
271##### 2a. Run a time-boxed feasibility spike
272
273Put a **hard time box** on it (e.g. one day). The spike's question is **NOT "can
274we make CI green?"** — it is **"can we get this to run even *once* to capture its
275behavior?"** Probe, per component / deployable unit:
276
277- Does it **install** its dependencies today (ideally **from a committed
278 lockfile without hand-patching**)?
279- Do **native/build steps** succeed on a **currently supported** toolchain?
280- Does it **boot / start**?
281- Can the **test runner execute at all**, and does **≥1 meaningful test pass**?
282
283Record what you actually observed — including partial success (common in
284monorepos: one service installs and tests green while another can't compile). Do
285**not** sink two sprints resurrecting a corpse to discover it's unresurrectable.
286When the time box expires, decide with the evidence you have.
287
288##### 2b. Locate the Testability Milestone (per component)
289
290**"Testable" is not a precondition you can satisfy on a dead app — for a dead app
291it is an *output* of modernization, not an input.** So every plan must name, up
292front, its **Testability Milestone**: the specific phase at which the system
293(or a given component) first satisfies **all four** conditions at once:
294
2951. Runs on a **supported** (non-EOL) runtime.
2962. Dependencies install **from a lockfile without hand-patching**.
2973. Native / build steps **succeed on the current toolchain**.
2984. The **test runner executes and ≥1 meaningful test passes in CI**.
299
300Assess this **per component** — as the reference Nylas run showed, a near-modern
301cloud service can cross the line immediately while a legacy Electron client
302doesn't cross it until several phases later. **This milestone is the single most
303important marker in the plan.** State where it lands for each component, out loud.
304
305##### 2c. Label every phase pre- or post-testability
306
307The Testability Milestone splits the effort into two regimes with **different
308safety rules**:
309
310- **Pre-testability ("dark") regime:** the component can't be trusted to run.
311 Safety comes from **non-test** sources (see the safety ladder below).
312 **Requiring a CI test gate here is a category error** — you're demanding green
313 tests from something that isn't alive yet.
314- **Post-testability ("lit") regime:** it builds and runs on a live, supported
315 stack. *Now* real CI, characterization, and e2e are achievable and worth the
316 investment. The classic green-gate belongs **here**.
317
318**Rule: never require an automated test gate on a component before that component
319crosses its own testability line.**
320
321##### 2d. Choose the migration strategy — the A/B fork
322
323The spike decides which of two shapes fits (this is a per-component call in a
324monorepo):
325
326- **(A) Freeze-then-lift.** Net the old app *as-is*, then upgrade under the net.
327 Requires the old app to be **resurrectable at acceptable cost** — i.e. it
328 *almost* runs. This is the traditional "characterization tests before you
329 change anything" path. **Opt-in, not the default.**
330- **(B) Beachhead-then-expand (walking skeleton).** Don't net the corpse. Drive
331 the **thinnest possible end-to-end slice onto the modern stack** until it
332 builds, boots, and tests; then strangle the rest in, writing tests **on the new
333 stack** as you go. **This is the default for dead apps.** In strategy B, the
334 first phase is *"reach the Testability Milestone with the smallest slice,"* not
335 *"freeze the whole legacy toolchain."*
336
337If a component **can't be built or run at all**, characterization tests on the
338*old* stack are impossible by definition — invert the approach: **stop trying to
339net the corpse and build the net on the *target* stack incrementally**, using the
340old code/output as the reference oracle.
341
342##### 2e. Pick the highest achievable rung on the safety ladder
343
344Regression safety is a ladder, not a binary. Choose the **highest rung you can
345actually reach** per component; **a downgrade to a lower rung is a blessed,
346first-class outcome — not a failure — provided the residual risk is named.**
347
348- **L4 — Full automated gate:** green lint + unit + characterization + e2e in CI.
349- **L3 — Partial gate:** some suites green + lockfile + CI on the achievable
350 subset; the rest **quarantined** with a named list.
351- **L2 — Characterization / golden-master only:** can't run in CI, but capture
352 I/O snapshots / behavioral diffs (manual is acceptable).
353- **L1 — Reversibility-based:** no runnable tests; safety comes from small
354 reversible steps, strangler / parallel-run, a smoke checklist, and review.
355- **L0 — No net possible:** treat as a spec-driven rewrite (old code = the spec)
356 or archive.
357
358**Safety is not only tests.** There are at least five sources, and on dead apps
3592–4 often outweigh 1:
360
3611. **Tests** (characterization / unit / e2e) — strongest, often unachievable on
362 dead apps.
3632. **Reversibility** — tiny commits, branch-per-change, trivial rollback.
3643. **Isolation** — feature flags, strangler-fig, run old + new in parallel and
365 **diff outputs**.
3664. **The running old system as an oracle** — record/replay real I/O to
367 characterize behavior without a test harness.
3685. **Human review + domain knowledge.**
369
370**Anchor safety at the behavioral *seams*, not the unit.** The durable,
371stack-agnostic contracts of any app are its externally observable behaviors:
372HTTP endpoints, DB schema/queries, file/wire formats, CLI output, protocols. Pin
373*those* as golden-master / approval snapshots — **they survive the rewrite; unit
374tests on dead legacy code get deleted the moment you replace the module.** Get an
375**oracle**, ranked by what's available:
376
377- **Best — it runs *somewhere*** (prod, a VM, an old container, even read-only),
378 **and you're allowed to use it**: record real I/O and replay it against the new
379 code. One successful capture beats a permanent green legacy CI. *(Do not assume
380 this rung is always available — a faithful third-party reimplementation or a
381 resurrected legacy binary may be off-limits by policy, licensing, or an
382 explicit decision to build "with only what we have." If so, skip to the
383 self-frozen rung.)*
384- **Fallback — it doesn't run at all:** the old **source is the spec**;
385 supplement with prod logs, DB dumps, docs, tickets, and accept that
386 characterization tests get written **against the new implementation** to lock
387 it once verified correct.
388- **Self-frozen golden master — no external reference exists or is permitted:**
389 when nothing trustworthy runs *and* you may not borrow an external oracle, the
390 **modernized component records its *own* golden master the moment it first runs**
391 (at its Testability Milestone), and every later phase diffs against that frozen
392 snapshot. This is a real, usable rung — but **name its residual risk out loud**:
393 it guarantees the *self-consistency of later refactors*, **not** the correctness
394 of the first boot (the snapshot is only as correct as the run that produced it).
395 Pair it with human review / spec cross-checks to bless that first run.
396
397##### 2f. Feed an economic/oracle triage into the choice
398
399Weigh **regression cost** when picking a rung: Is the app **in production**? Does
400it have **real users**? Is the **old system still runnable** as a reference? An
401abandoned app with zero users has near-zero regression cost — an expensive gate
402there is **over-engineering**. A production system with users justifies a higher
403rung and a real oracle.
404
405##### 2g. Locate the CI Milestone (name the phase that stands up CI)
406
407Just as the Testability Milestone names *when a component can first run and be
408tested*, the **CI Milestone** names *when continuous integration is first stood
409up* — and it must be **stated out loud in the roadmap, not buried in a phase
410body.** A common failure of modernization plans is leaving the reader unable to
411tell which phase introduces CI; name it explicitly.
412
413**Rule: CI is stood up in the *first lit phase* — at or immediately after the
414component crosses its Testability Milestone — never before.** CI cannot be green
415on a component that cannot yet build/run, so wiring a CI *gate* during the dark
416regime is the same category error as demanding a test gate there. (Trivial
417scaffolding — a lint-only or build-only workflow — may appear earlier, but the
418authoritative test gate lands at the CI Milestone.)
419
420**CI is two distinct steps, and the second is human-only** — call both out:
4211. **Author the CI workflow file** (e.g. `.github/workflows/*.yml`, `.gitlab-ci.yml`,
422 Azure Pipelines) that runs the gate. **An agent can do this.**
4232. **Make that workflow an *enforced* gate** — a **required status check /
424 branch-protection rule / merge-request approval rule**. This is a manual
425 platform-UI / admin step (GitHub → Settings → Branches; GitLab protected
426 branches + MR settings; etc.) that **an agent cannot perform.** Until a human
427 configures it, CI *runs* on PRs but does **not** *block* merges.
428
429Because step 2 is outside the agent's reach, **every plan that stands up CI must
430emit it as an explicit user action item** (in the phase's exit criteria and in
431§9 Open questions / decisions needed from stakeholders), so the reader knows the
432gate is not self-enforcing until they turn it on.
433
434**Output of Phase 2:** for each component — the spike result, the chosen strategy
435(A or B), the located Testability Milestone, the pre/post label, and the target
436safety-ladder rung with any residual risk named — **plus the plan-wide CI
437Milestone** (which phase stands up CI) and the reminder that enforcing it is a
438manual human step. Everything downstream depends on these.
439
440#### Phase 2.5: Red-team every phase against the hazard catalog (mandatory)
441
442The strategic scaffolding above (testability, safety ladder, CI milestone) is
443necessary but **not sufficient**. Modernization plans also fail on *tactical,
444ecosystem-predictable* hazards — an incomplete quarantine set, a forgotten
445namespace codemod, a runtime bump that leaves the base images behind, a stateful
446data-store major treated as an image bump, an edge rewrite that drops the
447anonymous route class. These are so recurring that they have their own catalog:
448**`references/migration-hazards.md`** (H1–H8).
449
450**Rule: before any phase is implemented, red-team its plan against every hazard
451in `references/migration-hazards.md`.** For each hazard, ask "does this phase
452trigger it?", run the hazard's detection probe against the real repo, and fold
453its plan action into the phase's tasks/exit criteria **before** writing code. A
454hazard caught in planning is a task; caught in review it's rework; caught in prod
455it's an incident. Record hazards you checked and **cleared**, not just the ones
456that fired — a silent skip is indistinguishable from a miss.
457
458This is the institutionalized form of an independent-critic pass. Do it yourself
459by walking the catalog, and — where an independent second opinion is available
460(e.g. a rubber-duck / critique agent) — use it: on the reference PiggyMetrics run
461such a pass caught a **blocking plan gap in every single phase**, and each gap
462was an instance of an H1–H8 class. Bake the outcome into each phase's
463"Decisions made" and exit criteria so the executing agent inherits the cleared
464checklist rather than re-discovering the hazard.
465
466#### Phase 3: Recommend Target Architecture
467
468**Decision framework — always evaluate in this order:**
469
470For each component/dependency, work through these levels from least-disruptive to
471most-disruptive. Stop at the first level that solves the problem:
472
4731. **Upgrade in place** — Can you bump the major version and fix breakages?
474 (e.g., Node 14→22, Python 2→3, React 16→19, Rails 5→7). This is the default
475 answer. Only reject it if the upgrade path is officially unsupported, the
476 breaking changes are so extensive they exceed rewrite cost, or the framework
477 itself is abandoned/EOL.
478
4792. **Swap the dependency** — If the specific library is dead but the pattern is
480 fine, can you swap to a maintained alternative with the same interface shape?
481 (e.g., Moment.js → date-fns, Request → got/fetch, CoffeeScript → TypeScript
482 with decaffeinate). Prefer drop-in or mechanical migration tools when they
483 exist.
484
4853. **Wrap/adapt (Strangler Fig)** — If the component's interface is sound but
486 internals are unmaintainable, can you put a clean interface in front and
487 incrementally replace internals behind it? This works when coupling is
488 manageable and the system can run with old and new coexisting.
489
4904. **Rewrite** — Only when: the framework is abandoned with no upgrade path, the
491 architecture fundamentally cannot support required new capabilities (e.g.,
492 synchronous-only design that must become real-time), or honest estimation shows
493 upgrade cost exceeds rewrite cost. Require explicit justification for every
494 rewrite recommendation — "it's old" is not sufficient.
495
4965. **Remove** — Dead code, features with zero usage, deprecated capabilities
497 superseded by other systems. Verify usage claims before recommending removal.
498
499**Bias toward conservatism.** The cheapest migration is the one you don't do.
500Every level of disruption adds risk, timeline, and cost. A working system on an
501older framework is better than a half-finished rewrite on a new one.
502
503**Mechanical-migration riders (apply whenever a recommendation is an upgrade,
504swap, or removal).** These are the parts of a target-architecture decision that
505first-draft plans routinely drop; each maps to a hazard class in
506`references/migration-hazards.md`:
507
508- **Transitive-quarantine completeness (H1).** When removing/cutting over a whole
509 dependency family, grep the dead artifact across **all** manifests and list the
510 *full* set of dependents that must move or be quarantined — not the subset you
511 first thought of. State the post-cutover build target explicitly.
512- **Framework-major codemods (H2).** A **major** bump carries mechanical breaking
513 changes independent of your logic — namespace renames, removed deprecated APIs,
514 a changed **test engine**, changed config keys. Enumerate each as its own task
515 and prefer the ecosystem's automated **recipe/codemod tool** (OpenRewrite,
516 jscodeshift/react-codemod, `2to3`/`pyupgrade`, etc.) over hand-editing on large
517 trees. Don't forget the test-framework migration — it is the most-forgotten one.
518- **Runtime↔deployment lockstep (H3).** If a recommendation bumps the
519 language/runtime **major**, every place the runtime is pinned for *running* the
520 app — base images, `docker-compose` build contexts, CI runner images,
521 `engines`/`.nvmrc`/`.tool-versions`, serverless runtimes — must move in the
522 **same phase**. Build-runtime and run-runtime must never drift across a phase
523 boundary, or the app builds green and then fails to run.
524
525Produce a **Target Architecture** section that includes:
526
527- **Recommended tech stack** with rationale for each choice (framework, language,
528 runtime, database, infrastructure)
529- **Architectural pattern** recommendation (monolith → modular monolith →
530 services, event-driven, serverless, etc.) with justification
531- **What stays vs. what goes** — explicitly categorize each major component using
532 the decision framework above:
533 - ✅ Keep as-is (still modern/adequate)
534 - ⬆️ Upgrade in place (bump version, fix breakages)
535 - 🔀 Swap dependency (replace dead library with maintained equivalent)
536 - 🔄 Wrap/adapt (add an interface layer, incrementally replace internals)
537 - 🔁 Rewrite (fundamentally incompatible — justification required)
538 - 🗑️ Remove (dead code, deprecated features, superseded)
539
540For each recommendation, write an inline ADR:
541
542```markdown
543#### ADR: [Decision Title]
544- **Context:** [Why this decision is needed]
545- **Decision:** [What we chose and which decision framework level it falls under]
546- **Alternatives considered:** [What else was evaluated and why it lost]
547- **Consequences:** [Tradeoffs accepted]
548```
549
550#### Phase 4: Per-Feature Migration Analysis
551
552For each major feature/domain identified in the architecture doc, produce a
553section covering:
554
5551. **Current implementation** — one paragraph summary with file references
5562. **Migration strategy** — the A/B choice from Phase 2 for this component
557 (Freeze-then-lift vs. Beachhead/walking-skeleton), plus the tactic: Strangler
558 Fig, Big Bang rewrite, Lift & Shift, Incremental Refactor, or Leave In Place
5593. **Testability status** — where this component's **Testability Milestone**
560 lands, and its **safety-ladder rung** (L0–L4) with residual risk named
5614. **Dependencies and coupling** — what else breaks or must move with it
5625. **Effort estimate** — T-shirt size (XS/S/M/L/XL) with justification
5636. **Risk assessment** — what can go wrong, data migration concerns, user impact
5647. **Acceptance criteria** — how you know the migration succeeded (expressed
565 against the chosen oracle/seam contracts, not against a not-yet-alive test
566 suite)
567
568#### Phase 5: Phased Implementation Plan
569
570Produce an ordered, phased plan. Each phase should be independently deployable
571(no half-migrated states that can't run in production).
572
573**Phase gating is regime-aware (applies to every phase).** State this rule at the
574top of the phased plan and honor it in every phase's exit criteria. A phase is
575**not complete** until its Verification & Exit Criteria pass. Those criteria must
576be (a) **objectively verifiable**; (b) **actually executed and recorded** before
577the next phase starts; and (c) **gated** — do not advance to phase N+1 until
578phase N's criteria are demonstrably met. **But which criteria are valid depends
579on the component's regime (Phase 2c):**
580
581- **Post-testability ("lit") phases:** exit criteria are runnable commands / green
582 CI — **green CI on the phase's branch/PR is the authoritative signal.**
583- **Pre-testability ("dark") phases:** the component isn't alive yet, so a green
584 CI test gate is a **category error**. Exit criteria come from the achievable
585 safety-ladder rung instead — captured seam/oracle snapshots, reversibility
586 scaffolding proven present, a passed smoke checklist, recorded review. Do **not**
587 block a dark-regime phase on a test suite that can't run yet.
588
589Report to the user any phase whose pass/fail is unknown rather than assuming it
590passed.
591
592**The first phase establishes maximum *achievable* safety — not a fixed "green
593legacy gate."** Do not hard-code "resurrect everything and make CI green." Shape
594the first phase from the Phase 2 outputs, per component:
595
596- **Strategy A (Freeze-then-lift), component is resurrectable:** the first phase
597 *is* the classic Safety Net & Baseline — purely additive, no behavior change:
598 - **Characterization / golden / contract tests** at the **seams** that pin
599 current observable behavior (protocol traces, API snapshots, output goldens).
600 - **CI + lint + formatter** wired up and green (an authoritative gate for later
601 lit-regime phases).
602 - **Pinned dependencies / committed lockfile** and a recorded known-good
603 baseline (versions, toolchain, how it builds and runs today).
604 - **"Net proven to fail."** Deliberately mutate the code (e.g., change one
605 protocol code or return value), confirm the new tests go **red**, then
606 revert. A safety net that never fails is proof of nothing — prove it has
607 teeth.
608- **Strategy B (Beachhead/walking-skeleton), component is dead:** the first phase
609 is **"reach the Testability Milestone with the smallest slice"** — drive the
610 thinnest end-to-end path onto the modern stack until it builds, boots, and runs
611 ≥1 real test green, capturing seam/oracle contracts from the old system to
612 validate against. **Do not try to net the corpse.** Its exit criterion is the
613 achievable safety-ladder rung with residual risk named — a **blessed downgrade
614 is not a failure.**
615
616Only after the first phase's criteria are met (at whatever rung) do the
617subsequent infrastructure and feature phases begin.
618
619Structure each phase as:
620
621```markdown
622### Phase N: [Name] (T-shirt size: M)
623
624**Goal:** [One sentence]
625**Regime:** [pre-testability ("dark") | post-testability ("lit")] — per component
626**Safety rung:** [L0–L4, with residual risk named if below L4]
627**Prerequisites:** [Which phases must complete first]
628**Duration estimate:** [Relative, not calendar — e.g., "2-4 sprints"]
629
630#### Tasks
631| ID | Task | Component | Blocked by |
632|----|------|-----------|------------|
633| N.1 | ... | ... | — |
634| N.2 | ... | ... | N.1 |
635
636#### Risks & Mitigations
637- **Risk:** ... → **Mitigation:** ...
638
639#### Decisions made
640- [Every sub-decision this phase depends on, resolved and documented here so the
641 phase can be implemented without further user input. State "dropped" vs
642 "deferred" explicitly for anything cut.]
643
644#### Verification & Exit Criteria (Definition of Done)
645- [ ] [Regime-appropriate criterion. For LIT phases: a runnable command / green
646 CI check, citing the actual command from the Commands & Verification
647 Inventory. For DARK phases: the achievable safety-ladder rung's evidence —
648 captured seam/oracle snapshots, reversibility proven, smoke checklist
649 passed — NOT a green test suite the component can't yet run.]
650- [ ] [Include a parity/characterization check against the chosen oracle whenever
651 the change is meant to preserve behavior.]
652- [ ] [If purely additive, assert it: "no behavior/dependency/logic changed."]
653- [ ] [If exiting below L4, state the residual risk and which later phase closes
654 it (e.g., "client test gate deferred to the client-migration phase").]
655```
656
657**Ordering principles:**
658- **Locate the Testability Milestone first**, per component — schedule the
659 smallest slice that reaches it early rather than deferring "testable" to the end
660 while demanding a gate at the start.
661- **Never require a component's automated test gate before it crosses its own
662 testability line.**
663- **Name the CI Milestone in the roadmap.** State explicitly which phase stands
664 up CI (the first *lit* phase, at/after the Testability Milestone) so the reader
665 never has to guess when CI arrives — and flag that *enforcing* it (required
666 status check / branch protection) is a manual human step, not an agent task.
667- **First-phase safety before behavior change** — establish the highest
668 achievable rung (not necessarily a full green gate) before modifying behavior.
669- Infrastructure and cross-cutting concerns next (auth, config, logging, CI/CD)
670- Highest-risk or highest-value features next (prove the pattern early)
671- Low-risk, low-coupling features last (easy wins to parallelize)
672- Data migrations get their own phase with rollback plans
673
674#### Phase 6: Execution Governance
675
676Modernization plans fail in execution, not on paper. Bake in the governance that
677keeps each phase honest and reversible (generic across any ecosystem):
678
679- **Branch per phase.** Never commit phase work to the default branch. Open one
680 PR per phase; let CI on the PR be the authoritative green signal before merge
681 **for lit-regime phases**. For dark-regime phases, the PR still carries the
682 rung's evidence (captured contracts, smoke results, reversibility scaffolding).
683- **Merge to trunk before the next phase; never stack (H7).** Each phase branch
684 is cut **from trunk**, and its PR is **merged to trunk before the next phase
685 starts**. Never base a phase branch or its PR on a *sibling* phase branch — that
686 is how PRs get merged into each other, the trunk silently stalls several phases
687 behind, and later phases are forced into the exact bind where the no-stacking
688 rule has to be broken. Before starting a phase, verify the previous phase is
689 merged to trunk and `git log origin/<trunk>..HEAD` is empty at branch creation.
690 **If controlled stacking is genuinely unavoidable, it is allowed only with a
691 required reconciliation PR** that lands the stack onto trunk **and an explicit
692 residual-risk note** — never as a silent default.
693- **Confirm the trunk name; retire legacy defaults.** Pin the repo's real trunk
694 (e.g. `main`) and, if a second default-ish branch exists (`master`), mark it
695 "history only — do not target" so phase work never lands on the wrong branch.
696- **The gate matches the regime.** Lit phases advance on green CI; dark phases
697 advance on the achievable safety-ladder rung with residual risk named — not on
698 a "looks done" judgement, and not on a test suite that can't run yet.
699- **Stand up CI at the CI Milestone, and hand off enforcement to a human.**
700 Name the phase that introduces CI (the first lit phase). Distinguish the two
701 steps: authoring the workflow file is agent-doable; making it an **enforced
702 required status check / branch-protection (or MR-approval) rule is a manual
703 platform-UI step the agent cannot perform.** Until a human configures it, CI
704 *runs* but does not *block* merges — so record "enable branch protection /
705 required checks" as an explicit user action item (in the CI phase's exit
706 criteria and in §9 stakeholder decisions), never as a completed agent task.
707- **Interface-preserving & independently deployable.** Each phase leaves the
708 system runnable, so rollback = redeploy the previous version. Prefer
709 interface-preserving rewrites (wrap internals behind a stable interface) and
710 prove equivalence with the seam/oracle contracts (golden/characterization
711 tests where they exist).
712- **Living plan.** Update `MODERNIZATION_PLAN.md` status markers as each phase's
713 exit criteria are met — ✅ complete / ⏭️ descoped / 🗑️ dropped — record the
714 decisions made during implementation, and **update the safety-ladder rung /
715 residual-risk register** as components cross their testability lines.
716- **Keep the executable docs alive too (H8).** The living-plan discipline is not
717 only the plan file. Any phase that changes **topology** — module/reactor
718 membership, removed services, renamed branches, changed commands, new/removed
719 endpoints — must update `.github/copilot-instructions.md`, the `README`, and any
720 module/topology list **in the same PR**. Treat those doc updates as part of the
721 phase's Definition of Done, not a follow-up — a stale "quarantined module" list
722 or a hard-coded old-branch link actively misleads the next agent/human.
723- **Red-team each phase before implementing it (Phase 2.5).** Walk the phase plan
724 against `references/migration-hazards.md` (H1–H8) and fold the fixes into tasks
725 and exit criteria before writing code. Record the cleared checklist in the
726 phase's "Decisions made".
727- **Emit editable instructions.** Produce a `.github/copilot-instructions.md`
728 (create the `.github/` directory if needed) from the template at
729 `references/copilot-instructions.template.md` — a commands table plus the
730 regime-aware phase-gate and branch/PR rules — so the executing agent/human has
731 the canonical commands and gates in the location GitHub Copilot auto-loads. The
732 user edits it to their own gates. If a `.github/copilot-instructions.md` already
733 exists, do not overwrite it — merge the commands/gating/branch sections in, or
734 write the generated file alongside as
735 `.github/copilot-instructions.modernization.md` and tell the user to merge.
736
737#### Phase 7: Migration Safety Net
738
739Document the operational guardrails needed:
740
741- **Feature flags** — what gets flagged and how old/new coexist
742- **Data migration strategy** — schema changes, backfills, dual-write periods.
743 For a **stateful data-store major upgrade** with persisted volumes (H5), an
744 engine image/tag bump is **not** a migration: pick and document one path —
745 a sequential/feature-compatibility-version upgrade with steps + rollback, **or**
746 an explicit **destructive reset** (drop volumes, re-seed) when the data is
747 ephemeral/demo — stated as a deliberate decision, with the prior-major image
748 retained for rollback. (e.g. Mongo 3→7 over an existing `/data/db` volume needs
749 `down -v` + re-seed for a demo, or a staged FCV upgrade for real data.)
750- **Rollback plan** — per phase, how to revert if something fails
751- **Transitional-insecure-state register (H6)** — every deliberately-weak state
752 introduced to keep the system runnable mid-migration (permit-all shims, CSRF
753 disabled, an open endpoint, a placeholder secret) listed with: why it's needed,
754 the phase that **closes** it, the residual risk, and a by-design-until-phase-N
755 note for reviewers. Scope each weakening as tightly as possible (e.g. a
756 permit-all chain should still explicitly disable form-login/HTTP-Basic).
757 Pre-declaring these converts recurring scanner/reviewer churn into a tracked
758 decision.
759- **Oracle & seam contracts** — which running instance / recorded I/O / golden
760 snapshots (or a **self-frozen golden master**, when no external reference is
761 available or permitted) serve as the behavioral reference, and how new work is
762 diffed against them
763- **Testing strategy** — what new test coverage is needed (built on the *target*
764 stack as components cross their testability line), and what stays quarantined
765- **Observability** — metrics/alerts that prove the new system matches the old
766
767### Output Structure
768
769Produce a primary Markdown file named `MODERNIZATION_PLAN.md` with:
770
7711. Executive summary (one paragraph: what, why, rough scope)
7722. Current state assessment (from architecture doc)
7733. **Feasibility spike result & strategy** — per component: spike findings, the
774 A/B migration strategy, the located **Testability Milestone**, the target
775 **safety-ladder rung**, and a **residual-risk register** for anything below L4;
776 plus the plan-wide **CI Milestone** (which phase stands up CI) with a note that
777 *enforcing* it is a manual human step
7784. Target architecture with ADRs
7795. Per-feature migration analysis (with testability status + safety rung)
7806. Phased implementation plan — first phase establishes the highest *achievable*
781 safety rung (not a fixed green legacy gate); every phase is labeled
782 pre/post-testability and carries regime-appropriate, gated exit criteria; the
783 **CI Milestone phase is named explicitly** and lists "enable branch protection
784 / required status checks" as a manual user action
7857. Execution governance (branch-per-phase, regime-aware gate, living-plan status)
7868. Migration safety net (oracle & seam contracts, flags, rollback, observability)
7879. Open questions / decisions needed from stakeholders — including any manual
788 platform-configuration handoffs the agent cannot perform (e.g. enabling
789 required status checks / branch protection to make CI an enforced gate)
790
791Also emit a companion **`.github/copilot-instructions.md`** (the path GitHub
792Copilot auto-loads; create `.github/` if absent) from
793`references/copilot-instructions.template.md`, populated with the project's
794canonical commands and phase-gating / branch rules, for whoever executes the
795plan to edit and adopt. Never overwrite an existing
796`.github/copilot-instructions.md` — merge into it or write a sibling
797`.github/copilot-instructions.modernization.md` and flag it for the user.
798
799### Conventions
800
801- **Cite the architecture doc** when referencing current state rather than
802 restating everything. Keep this document forward-looking.
803- **Be opinionated.** Make concrete recommendations, not "you could do A or B."
804 State what you'd pick and why. The user can override.
805- **Scope realistically.** A modernization plan that tries to change everything at
806 once is fiction. Identify what's phase 1 vs. "future consideration."
807- **Resolve every in-phase decision during planning.** A phase plan must carry
808 all the sub-decisions its implementation depends on, already decided and
809 documented (the "Decisions made" block), so the phase can be executed without
810 going back to the user. State **"dropped" vs "deferred"** explicitly for
811 anything cut — they are not the same. Reserve `[DECISION NEEDED]` for genuine
812 *stakeholder/business* choices (budget, team size, product direction, timeline
813 pressure) that block a phase; drive those to resolution with the user during
814 planning rather than leaving them open in an implementable phase.
815- **Don't gold-plate.** If a component works fine on the old stack and has no
816 maintenance burden, "leave it alone" is a valid recommendation.
817- **Assume dead-by-default; make safety adaptive.** Don't demand a fully-green
818 legacy CI gate up front. Run the feasibility spike, pick the highest achievable
819 safety-ladder rung, and treat a **downgrade as a blessed outcome** with residual
820 risk named — never a failure.
821- **Locate testability in time.** Every plan must name its **Testability
822 Milestone** per component and never require a component's automated test gate
823 before that component crosses its own testability line.
824- **Name the CI Milestone, hand enforcement to a human.** State which phase
825 stands up CI (the first lit phase), and make explicit that turning CI into an
826 *enforced* required check / branch-protection rule is a manual platform step
827 the agent cannot do — surface it as a user action item, not a done task.
828- **Net the seams, not the corpse.** Anchor safety at externally observable
829 contracts (protocols, schemas, wire/file formats, endpoints) with a ranked
830 oracle (running instance → recorded I/O → code-as-spec → **self-frozen golden
831 master** when no external reference exists or is permitted). Don't sink sprints
832 resurrecting a dead toolchain just to run a test that gets deleted at rewrite.
833- **Keep it generic.** Express commands and gates in terms of *the project's*
834 package manager / test runner / CI — never assume a specific stack.
835- **Red-team every phase before implementing (H1–H8).** Walk each phase plan
836 against `references/migration-hazards.md` and fold the fixes into tasks/exit
837 criteria first — a hazard caught in planning is a task; in review, rework; in
838 prod, an incident. These tactical hazards (incomplete quarantine, framework
839 codemods, runtime/base-image lockstep, route-class enumeration, data-store
840 upgrade paths, transitional-insecure-state noise, stacked-PR/trunk drift,
841 living-doc drift) are what strategic scaffolding alone keeps missing.
842
843---
844
845**Source:** [`github/awesome-copilot`](https://github.com/github/awesome-copilot) → `skills/doc-and-modernize/SKILL.md`