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