summaryrefslogtreecommitdiff
path: root/plugins/code-modernization
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/code-modernization')
-rw-r--r--plugins/code-modernization/.claude-plugin/plugin.json51
-rw-r--r--plugins/code-modernization/README.md121
-rw-r--r--plugins/code-modernization/hooks/fleet/fleet.ts350
-rw-r--r--plugins/code-modernization/hooks/hooks.json4
-rw-r--r--plugins/code-modernization/hooks/host.ts37
-rw-r--r--plugins/code-modernization/hooks/map/estate.ts191
-rw-r--r--plugins/code-modernization/hooks/map/raster.ts92
-rw-r--r--plugins/code-modernization/hooks/map/treemap.ts156
-rw-r--r--plugins/code-modernization/hooks/paths.ts94
-rw-r--r--plugins/code-modernization/hooks/reader/brief.ts200
-rw-r--r--plugins/code-modernization/hooks/reader/discover.ts341
-rw-r--r--plugins/code-modernization/hooks/reader/estate-model.ts213
-rw-r--r--plugins/code-modernization/hooks/reader/fs.ts54
-rw-r--r--plugins/code-modernization/hooks/reader/modernized.ts384
-rw-r--r--plugins/code-modernization/hooks/reader/progress.ts849
-rw-r--r--plugins/code-modernization/hooks/reader/rules.ts437
-rw-r--r--plugins/code-modernization/hooks/reader/topology.ts243
-rw-r--r--plugins/code-modernization/hooks/reader/tracks.ts86
-rw-r--r--plugins/code-modernization/hooks/reader/uplift.ts238
-rw-r--r--plugins/code-modernization/hooks/register.ts1256
-rw-r--r--plugins/code-modernization/hooks/review/deck.ts121
-rw-r--r--plugins/code-modernization/hooks/sign.ts77
-rw-r--r--plugins/code-modernization/hooks/state.ts180
-rw-r--r--plugins/code-modernization/hooks/tests-run.ts87
-rw-r--r--plugins/code-modernization/hooks/views/deck.tsx310
-rw-r--r--plugins/code-modernization/hooks/views/pane.tsx567
-rw-r--r--plugins/code-modernization/hooks/xray/xray.ts263
-rw-r--r--plugins/code-modernization/tests/fixtures/inputs.ts55
-rw-r--r--plugins/code-modernization/tests/fixtures/stacks.ts207
-rw-r--r--plugins/code-modernization/tests/fixtures/workspace.ts306
-rw-r--r--plugins/code-modernization/tests/fixtures/world.ts259
-rw-r--r--plugins/code-modernization/tests/logic.test.ts570
-rw-r--r--plugins/code-modernization/tests/register.test.ts428
-rw-r--r--plugins/code-modernization/tests/stacks.test.ts444
-rw-r--r--plugins/code-modernization/tsconfig.json10
35 files changed, 9280 insertions, 1 deletions
diff --git a/plugins/code-modernization/.claude-plugin/plugin.json b/plugins/code-modernization/.claude-plugin/plugin.json
index 431fe9b3..274d539d 100644
--- a/plugins/code-modernization/.claude-plugin/plugin.json
+++ b/plugins/code-modernization/.claude-plugin/plugin.json
@@ -1,8 +1,57 @@
{
"name": "code-modernization",
- "description": "Modernize legacy codebases (COBOL, legacy Java/C++/.NET, monolith web apps) with a structured preflight / assess / map / extract-rules / brief / (reimagine | transform | uplift) / harden / status workflow. Cross-stack rewrites, greenfield reimagining, and same-stack version uplifts (e.g. .NET Framework → .NET 8); an interactive topology viewer; specialist agents; and optional dynamic-workflow orchestration with adversarial verification.",
+ "description": "Modernize legacy codebases (COBOL, legacy Java/C++/.NET, monolith web apps) with a structured preflight / assess / map / extract-rules / brief / (reimagine | transform | uplift) / harden / status workflow. Cross-stack rewrites, greenfield reimagining, and same-stack version uplifts (e.g. .NET Framework → .NET 8); an interactive topology viewer; an optional live progress pane (early access); specialist agents; and optional dynamic-workflow orchestration with adversarial verification.",
"author": {
"name": "Anthropic",
"email": "support@anthropic.com"
+ },
+ "userConfig": {
+ "system": {
+ "type": "string",
+ "title": "System",
+ "description": "The system under analysis/ to follow. Empty follows the first one found.",
+ "default": ""
+ },
+ "track": {
+ "type": "string",
+ "title": "Track to follow",
+ "description": "auto follows whichever way the plugin's commands are working on the system: a rewrite, a same-stack uplift or a greenfield reimagine, by the newest artifacts. Name one to pin it.",
+ "default": "auto",
+ "options": [
+ "auto",
+ "transform",
+ "uplift",
+ "reimagine"
+ ]
+ },
+ "panel": {
+ "type": "string",
+ "title": "Progress pane",
+ "description": "auto opens the pane when a session starts in a workspace that has analysis/; command opens it only when you press its button or type /modernize-panel; off never opens it and never draws the button.",
+ "default": "auto",
+ "options": [
+ "auto",
+ "command",
+ "off"
+ ]
+ },
+ "xray": {
+ "type": "boolean",
+ "title": "X-ray reads",
+ "description": "When Claude reads a legacy file, attach what the analysis already knows about it (callers, data it touches, the rules citing it) as context only the model sees.",
+ "default": true
+ },
+ "commandPrefix": {
+ "type": "string",
+ "title": "Command prefix",
+ "description": "How the plugin's commands are written up to their verb, for the pane's Next line.",
+ "default": "/code-modernization:modernize-"
+ },
+ "legacyDir": {
+ "type": "string",
+ "title": "Legacy directory",
+ "description": "The read-only tree holding the legacy systems, relative to the workspace.",
+ "default": "legacy"
+ }
}
}
diff --git a/plugins/code-modernization/README.md b/plugins/code-modernization/README.md
index 087d5430..96a3c8a6 100644
--- a/plugins/code-modernization/README.md
+++ b/plugins/code-modernization/README.md
@@ -83,6 +83,127 @@ Specialist subagents invoked by the commands (or directly):
- **`uplift-migrator`** — Migrates one project/module of an in-flight uplift by following the pilot's playbook, then runs that unit's real build to prove it; refuses to migrate anything if no playbook exists yet. Writes only inside its own unit's directory. *(uplift)*
- **`scaffolder`** — Builds one service of a reimagined system; writes only within its own `modernized/.../<service>/` directory. *(reimagine)*
+## Live progress pane (early access)
+
+While the commands run, the plugin can draw a live pane beside the transcript: for a system in any language, what the
+commands are doing to it, how far along each part is, and what to run next. It is built on Claude Code's function hooks,
+which are early access and off by default. Start with the flag to turn them on:
+
+```sh
+CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude
+```
+
+Without the flag nothing changes: the commands, agents and workflows behave the same and the pane never loads. Everything
+it shows is read from the artifacts the commands write under `analysis/<system>/` and `modernized/<system>/`, and from the
+legacy tree itself. Nothing is inferred by a model, and a fact that is not on disk is shown as absent. The hooks are written
+against a feature that may change between releases; they were run on 2.1.280 and 2.1.283.
+
+### What it adds
+
+**A progress pane with an estate map.** Docked beside the transcript, for whatever system is under `legacy/` and in
+whatever language: the system and what the plugin's commands are doing to it, which steps are done, a treemap of its
+code, each unit of work and where it stands, what needs attention, and the next command to run.
+
+- **Any language.** The pane reads no language of its own. The map comes from `topology.json` when `/modernize-map` has run.
+ Until then it is read off the legacy tree: one tile per build module where the tree has build files (Maven, Gradle, npm,
+ .NET projects, Go, Cargo, Python packages, Composer, and more), one per source file for a tree without them, one per
+ directory for a tree too big for that. Its header names the languages by the share of the code (COBOL, Java, C#, PHP,
+ Perl, RPG, and any other by file type) and how many units it found.
+- **Any way of working.** It follows the track whose artifacts are newest: a **rewrite** (map, rules, brief, transform), a
+ same-stack **uplift** (delta catalog, baseline, playbook, working copy), or a **reimagine** (spec, architecture, services).
+ Each has its own steps, its own next command, and tiles coloured by its own progress. An uplift's modules are set against
+ the baseline: *matches baseline* means every test that passed on the source runtime still passes and none is missing;
+ *worse than baseline* means more failures than it had (failures the baseline already had are not called worse). Set
+ `track` to pin one.
+- **Any test runner.** A module's tests come from the reports it left (JUnit XML in the usual places, Visual Studio `.trx`,
+ or `.modernize/test-report.json`), and, where a runner leaves none, from a test command run in the module's directory during
+ the session (Maven, Gradle, pytest, Jest, dotnet, go, cargo, rspec, phpunit and more).
+- **A tile lights up** for a few seconds when Claude or one of its agents reads (blue) or writes (yellow) a file under it,
+ in the legacy tree or in an uplift's working copy, so a fan-out is something you watch move across the system.
+- **Show it and hide it.** It opens by itself under the fullscreen layout once the workspace has an `analysis/` directory.
+ A **hide** button at the top of the pane closes it. While it is hidden, one row above the prompt says where the
+ workspace stands and holds a **show pane** button that brings it back, on a terminal too narrow to dock it as well as a wide
+ one. `/modernize-panel` does the same from the keyboard, and shows the pane for a legacy tree nothing has analysed yet.
+ Set `panel` to `command` to have it open only on request, or `off` to have no pane and no button.
+
+**X-ray reads.** When Claude reads a file under `legacy/<system>/`, what the analysis already
+established about that file rides along as context only the model sees: the map's callers,
+callees and data stores, the business flows through it, the rules in `BUSINESS_RULES.md` that
+cite it (narrowed to the lines just read when the read was a window), any rule a reviewer
+disputed, and whether it has already been transformed. In an uplift it carries the module's
+baseline (what fails on the source runtime is part of the oracle, so it is reproduced, not fixed),
+where the module stands in the working copy, and the deltas the catalog cites the file under. The model stops re-deriving what three
+stages already worked out, and stops calling code dead that the map knows is reached. A read
+that misses because a cited path was taken from the workspace root is told where the file is
+under the legacy root.
+
+**A review deck for business rules.** `/modernize-review [flagged|p0|all] [filter]` pages through
+rule cards in the band above the prompt: the rule, its citation, Given / When / Then, the
+suspected defect, the question for an SME. From an empty prompt, `1` confirms, `2` marks it wrong,
+`3` sends it to discussion, `6` shows the cited legacy lines. Verdicts go to
+`analysis/<system>/RULE_REVIEWS.json` and a readable `RULE_REVIEWS.md`; the agent-written rules
+file is never edited. Disputed rules show up in the pane and in later x-ray notes.
+
+**A sign-off dialog.** `/modernize-sign [name, role]` fills in the brief's approval block: who,
+when, and whether it covers Phase 1 or the full plan.
+
+**A fleet view.** Every agent loop that makes a tool call is counted, including a workflow's
+agents, which `$.agent.list()` does not name. The pane shows how many are active and done, and
+what the most recent are doing. When agents fail the same way (paths, numbers and quoted values
+folded out, and one cause that words itself differently per command folded together), the pane
+lists it with an example of what the failing calls were aimed at. The transcript says so once it
+is a pattern for a fleet that size (three agents, or one in twenty), and once more if it spreads
+fivefold: one cause across agents belongs in the playbook, not in each agent. A bare exit code
+or a malformed call is not a cause and is not counted as one.
+
+### Pane commands
+
+| | |
+|---|---|
+| `/modernize-panel [open\|close\|json]` | Show or hide the pane (the same switch as its **hide** and **show pane** buttons); `json` prints the reading it draws from. |
+| `/modernize-review [flagged\|p0\|all] [filter]` | Review rules. `flagged` (default) is the P0 rules with a defect, an SME note or less than High confidence. The filter matches an id, a domain, a title or a cited file. |
+| `/modernize-sign [name, role]` | Sign the brief's approval block. |
+
+### Pane options
+
+Set in `/config`, or under `pluginConfigs` in settings.
+
+| Option | Default | |
+|---|---|---|
+| `system` | first under `analysis/`, else under `legacy/` | The system to follow. |
+| `track` | `auto` | `auto` follows whichever way the commands are working on the system; `transform`, `uplift` or `reimagine` pins one. |
+| `panel` | `auto` | `auto` opens the pane by itself and draws the show button while it is hidden; `command` opens it only when the button or `/modernize-panel` asks; `off` neither opens it nor draws the button. |
+| `xray` | on | Attach analysis context to legacy reads. |
+| `commandPrefix` | `/code-modernization:modernize-` | How the pane writes the plugin's commands. |
+| `legacyDir` | `legacy` | The read-only tree. |
+
+### Pane keys
+
+Hotkeys work in the band above the prompt (the review deck's digits, from an empty prompt). A
+pane's buttons are pressed by clicking, or `ctrl+x tab` to give the pane the keyboard, then Tab
+and Enter.
+
+### What the pane does not do
+
+- An uplift's changed modules are found by comparing the working copy with the legacy tree by file name and size, with the
+ file API alone: the pane runs no program inside either tree. An edit that keeps a file exactly the same size is not seen by
+ that comparison, but a test run in the module, or a write during the session, shows it.
+- Sizes are lines where the map gave them and bytes of source where the estate was read off the tree; a single file counts for
+ at most 400 KB, so a binary in a test folder is not a system's bulk.
+- It never runs a command by itself. The pane's **next** button puts the command in the prompt
+ box; a person presses Enter.
+- It does not call a model. The brief's phases and approval are read by pattern from the file;
+ what cannot be read that way is shown as unknown, not guessed.
+- It only watches. It does not block or rewrite any edit or command; the workspace's own permission rules
+ (`Edit(/legacy/**)` denied, see Recommended workspace setup) are what keep `legacy/` read-only.
+- The cut-over console (live legacy-versus-modern traffic diff with automatic fallback) and
+ approvals from a phone are not built: both need an environment this repository cannot test.
+
+To work on the pane, `hooks/register.ts` is the module: it binds the engine at `session.start` and wires the hooks, and
+everything it calls is a plain function under `hooks/`. `claude plugin test .` runs the tests in `tests/` (parsers, layout,
+estates in eight stacks, and the hooks through the engine's own `$`); `tsc -p .` typechecks them against the
+declaration file `/plugin-types` writes into `.claude/types/`.
+
## Recommended workspace setup
The commands never edit `legacy/`, by convention. A `.claude/settings.json` in the project you're modernizing backs that up with a deny rule for `legacy/` and allow rules for `analysis/` and `modernized/`; `/code-modernization:modernize-preflight` checks for the deny rule:
diff --git a/plugins/code-modernization/hooks/fleet/fleet.ts b/plugins/code-modernization/hooks/fleet/fleet.ts
new file mode 100644
index 00000000..876b9512
--- /dev/null
+++ b/plugins/code-modernization/hooks/fleet/fleet.ts
@@ -0,0 +1,350 @@
+/**
+ * The fleet: every agent loop this session has seen a tool call from, kept
+ * from the events themselves. A workflow's agents carry ids no `$.agent.list()`
+ * names, so the registry is built from `tool.call` and `turn.complete` alone.
+ *
+ * It also watches for one failure repeating across agents: three agents
+ * hitting the same error is a fact about the playbook, not about the agents.
+ */
+
+export type AgentRow = {
+ id: string
+ firstMs: number
+ lastMs: number
+ calls: number
+ errors: number
+ /** `Read`, `Bash`, and so on. */
+ lastTool: string
+ /** A short rendering of the last call's subject: a file's name, a command's head. */
+ lastSubject: string
+ isDone: boolean
+ /** The unit of work it appears to be on: the legacy module its calls touch most. */
+ unit?: string
+}
+
+export type Signature = {
+ /** The normalized failure text the agents share. */
+ text: string
+ agents: Set<string>
+ firstMs: number
+ lastMs: number
+ /** How many agents shared it when it was last called out; 0 while it has not been. */
+ announcedAt: number
+ /** When it was last called out. */
+ announcedMs: number
+ /** What a few of the failing calls were aimed at: the part of the cause the text alone leaves out. */
+ examples: string[]
+}
+
+export type Fleet = {
+ agents: Map<string, AgentRow>
+ signatures: Map<string, Signature>
+ /** Units each agent touched, to name what it is working on. */
+ unitHits: Map<string, Map<string, number>>
+ /** Counted as they happen, so pruning old rows does not shrink the totals. */
+ seen: number
+ ended: number
+ calls: number
+ errors: number
+}
+
+/** An agent with no call for this long reads as finished or stalled, in milliseconds. */
+export const IDLE_MS = 90_000
+
+/** How many agents must share a failure before it counts as shared at all. */
+export const SIGNATURE_THRESHOLD = 3
+
+/** A shared failure is called out again once it has spread this many times further. */
+export const ESCALATE_FACTOR = 5
+
+/** And no sooner than this after the last time, in milliseconds: a fan-out fails all at once. */
+export const ESCALATE_QUIET_MS = 60_000
+
+/**
+ * How many agents must share a failure before it is called out in the
+ * transcript. Three of five agents is a pattern; three of five hundred is not,
+ * so the bar rises with the fleet. The pane lists it from three either way.
+ */
+export const announceThresholdOf = (fleet: Fleet): number =>
+ Math.max(SIGNATURE_THRESHOLD, Math.ceil(fleet.seen * 0.05))
+
+/** Failures further apart than this are not the same incident, in milliseconds. */
+export const SIGNATURE_WINDOW_MS = 15 * 60_000
+
+export const newFleet = (): Fleet => ({
+ agents: new Map(),
+ signatures: new Map(),
+ unitHits: new Map(),
+ seen: 0,
+ ended: 0,
+ calls: 0,
+ errors: 0,
+})
+
+/** A short subject for a call, from the arguments tools commonly carry. */
+export function subjectOf(tool: string, args: Readonly<Record<string, unknown>>): string {
+ const str = (key: string) => (typeof args[key] === 'string' ? (args[key] as string) : undefined)
+ const path = str('file_path') ?? str('path') ?? str('notebook_path')
+
+ if (path !== undefined) {
+ return path.split('/').slice(-1)[0] ?? path
+ }
+
+ const command = str('command')
+
+ if (command !== undefined) {
+ // What runs, not where: a leading `cd …`, `VAR=…;` or `export …` says nothing at a glance.
+ const lead = /^(?:\s*(?:cd\s+(?:"[^"]*"|'[^']*'|\S+)(?:\s+\d?>{1,2}\s*\S+)*|(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*))\s*(?:&&|;)\s*)+/
+
+ return command.replace(/\s+/g, ' ').replace(lead, '').slice(0, 48)
+ }
+
+ return (str('pattern') ?? str('description') ?? str('query') ?? str('prompt') ?? '')
+ .replace(/\s+/g, ' ')
+ .slice(0, 48)
+}
+
+/** Records the start of a call by `agentId`. */
+export function noteCall(
+ fleet: Fleet,
+ agentId: string,
+ tool: string,
+ subject: string,
+ nowMs: number,
+ unit?: string,
+): AgentRow {
+ if (!fleet.agents.has(agentId)) {
+ fleet.seen += 1
+ }
+
+ fleet.calls += 1
+
+ const row = fleet.agents.get(agentId) ?? {
+ id: agentId,
+ firstMs: nowMs,
+ lastMs: nowMs,
+ calls: 0,
+ errors: 0,
+ lastTool: tool,
+ lastSubject: subject,
+ isDone: false,
+ }
+
+ const next: AgentRow = {
+ ...row,
+ lastMs: nowMs,
+ calls: row.calls + 1,
+ lastTool: tool,
+ lastSubject: subject,
+ isDone: false,
+ }
+
+ if (unit !== undefined) {
+ const hits = fleet.unitHits.get(agentId) ?? new Map<string, number>()
+
+ hits.set(unit, (hits.get(unit) ?? 0) + 1)
+ fleet.unitHits.set(agentId, hits)
+
+ const top = [...hits.entries()].sort((a, b) => b[1] - a[1])[0]
+
+ if (top !== undefined) {
+ next.unit = top[0]
+ }
+ }
+
+ fleet.agents.set(agentId, next)
+
+ return next
+}
+
+const ERRORISH = /error|fail|exception|cannot|not found|denied|refused|blocked|unresolved|undefined|no such|does not exist|does not match/i
+
+/** A path named by a "No such file" line, as the command printed it. */
+export function missingPathOf(text: string): string | undefined {
+ return /([^\s:'"]*\/[^\s:'"]+): (?:open: )?No such file or directory/.exec(text)?.[1]
+}
+
+/**
+ * A failure text with what varies between agents taken out: paths, numbers,
+ * hex, quoted values, timestamps. Two agents hitting one cause then match.
+ *
+ * Empty when the text names no cause worth matching on: a bare exit code (a
+ * search that found nothing), or a malformed tool call, which is the model's
+ * slip and not something the agents share.
+ */
+export function normalizeFailure(text: string): string {
+ if (/InputValidationError|could not be parsed as JSON/.test(text)) {
+ return ''
+ }
+
+ const line =
+ text
+ .split('\n')
+ .map(part => part.trim().replace(/^Exit code \d+\s*/i, ''))
+ .find(part => part !== '' && ERRORISH.test(part)) ?? ''
+
+ if (line === '') {
+ return ''
+ }
+
+ // Families: one cause that words itself differently per command or per call.
+ if (/file does not exist|no such file or directory|path does not exist/i.test(line)) {
+ return 'a path that does not exist'
+ }
+
+ const denied = /^Permission to use (\w+) with command\s+(?:cd\s+\S+\s*(?:&&|;)\s*)?([\w./-]+)[\s\S]*has been denied/.exec(line)
+
+ if (denied !== null) {
+ return `Permission to use ${denied[1]} with command ${denied[2]} … was denied`
+ }
+
+ const blocked = /^([\w./-]+) to .+ was blocked by a deny rule/.exec(line)
+
+ if (blocked !== null) {
+ return `${blocked[1]} was blocked by a deny rule`
+ }
+
+ if (/does not match required schema/i.test(line)) {
+ // Which property broke which constraint, once each: `/rules/13/category` and `/rules/27/category` are one fact.
+ const clauses = new Set<string>()
+
+ for (const match of line.matchAll(/((?:\/[\w-]+)+): (must [a-z ]+?)(?=:|,|$)/g)) {
+ clauses.add(`${(match[1] ?? '').replace(/\/\d+(?=\/|$)/g, '/<n>')}: ${(match[2] ?? '').trim()}`)
+ }
+
+ return `Output does not match required schema: ${[...clauses].join('; ')}`.slice(0, 140)
+ }
+
+ if (/\(eval\):\d+: =+\S* not found/.test(line)) {
+ return '(eval):<n>: ==… not found'
+ }
+
+ const key = line
+ .replace(/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?Z?\b/g, '<time>')
+ .replace(/(?:[A-Za-z]:)?(?:\/[\w.@~+-]+){2,}\/?/g, '<path>')
+ .replace(/\b0x[0-9a-fA-F]+\b/g, '<hex>')
+ .replace(/\b[0-9a-f]{12,}\b/g, '<id>')
+ .replace(/(["'`]).{1,60}?\1/g, '<q>')
+ .replace(/\b\d+(?:\.\d+)?\b/g, '<n>')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, 140)
+
+ // What is left must still say something: `<n> <q>` and the like match everything.
+ return key.replace(/<\w+>|[^A-Za-z]+/g, ' ').trim().split(/\s+/).filter(word => word.length > 2).length >= 2 ? key : ''
+}
+
+/**
+ * Records a failed call. Returns the signature when this failure is one to
+ * call out now: the first time enough agents share it, and again each time it
+ * has spread `ESCALATE_FACTOR` times further. `example` is what the failing
+ * call was aimed at (a path, a command's head).
+ */
+export function noteFailure(
+ fleet: Fleet,
+ agentId: string,
+ errorText: string,
+ nowMs: number,
+ example?: string,
+): Signature | null {
+ const row = fleet.agents.get(agentId)
+
+ fleet.errors += 1
+
+ if (row !== undefined) {
+ fleet.agents.set(agentId, { ...row, errors: row.errors + 1 })
+ }
+
+ const key = normalizeFailure(errorText)
+
+ if (key.length < 12) {
+ return null
+ }
+
+ const held = fleet.signatures.get(key)
+
+ const signature: Signature =
+ held !== undefined && nowMs - held.lastMs <= SIGNATURE_WINDOW_MS
+ ? held
+ : { text: key, agents: new Set(), firstMs: nowMs, lastMs: nowMs, announcedAt: 0, announcedMs: 0, examples: [] }
+
+ signature.agents.add(agentId)
+ signature.lastMs = nowMs
+
+ if (example !== undefined && example !== '' && signature.examples.length < 3 && !signature.examples.includes(example)) {
+ signature.examples.push(example)
+ }
+
+ fleet.signatures.set(key, signature)
+
+ const size = signature.agents.size
+
+ const isDue =
+ signature.announcedAt === 0
+ ? size >= announceThresholdOf(fleet)
+ : size >= signature.announcedAt * ESCALATE_FACTOR && nowMs - signature.announcedMs >= ESCALATE_QUIET_MS
+
+ if (isDue) {
+ signature.announcedAt = size
+ signature.announcedMs = nowMs
+
+ return signature
+ }
+
+ return null
+}
+
+/** A shared failure in one line, with what the failing calls were aimed at. */
+export function lineOf(signature: Signature, form: 'full' | 'short' = 'full'): string {
+ const examples = signature.examples.slice(0, form === 'short' ? 1 : 2).join(', ')
+ const lead = form === 'short' ? `${signature.agents.size} agents: ` : `${signature.agents.size} agents hit the same failure: `
+
+ return `${lead}${signature.text}${examples !== '' ? ` (e.g. ${examples})` : ''}`
+}
+
+/** Marks an agent's loop as ended (its `turn.complete`). */
+export function noteDone(fleet: Fleet, agentId: string, nowMs: number): void {
+ const row = fleet.agents.get(agentId)
+
+ if (row !== undefined) {
+ if (!row.isDone) {
+ fleet.ended += 1
+ }
+
+ fleet.agents.set(agentId, { ...row, isDone: true, lastMs: nowMs })
+ }
+}
+
+/** The fleet in numbers, as the pane's header line shows it. */
+export function tallyOf(fleet: Fleet, nowMs: number) {
+ const rows = [...fleet.agents.values()]
+ const active = rows.filter(row => !row.isDone && nowMs - row.lastMs < IDLE_MS)
+
+ return {
+ total: fleet.seen,
+ active: active.length,
+ done: fleet.ended,
+ stalled: rows.filter(row => !row.isDone && nowMs - row.lastMs >= IDLE_MS).length,
+ calls: fleet.calls,
+ errors: fleet.errors,
+ recent: active.sort((a, b) => b.lastMs - a.lastMs),
+ // The widest-spread first: the pane has room for two or three.
+ shared: [...fleet.signatures.values()]
+ .filter(signature => signature.agents.size >= SIGNATURE_THRESHOLD)
+ .sort((a, b) => b.agents.size - a.agents.size),
+ }
+}
+
+/** Forgets agents that ended long ago, keeping the registry bounded on a long run. */
+export function prune(fleet: Fleet, nowMs: number, keepMs = 30 * 60_000, max = 1500): void {
+ if (fleet.agents.size <= max) {
+ return
+ }
+
+ for (const [id, row] of fleet.agents) {
+ if ((row.isDone || nowMs - row.lastMs > keepMs) && fleet.agents.size > max) {
+ fleet.agents.delete(id)
+ fleet.unitHits.delete(id)
+ }
+ }
+}
diff --git a/plugins/code-modernization/hooks/hooks.json b/plugins/code-modernization/hooks/hooks.json
new file mode 100644
index 00000000..7e99b4e0
--- /dev/null
+++ b/plugins/code-modernization/hooks/hooks.json
@@ -0,0 +1,4 @@
+{
+ "description": "The modernization pane and estate map, x-ray reads, the rule review deck, the sign-off dialog and the fleet view",
+ "modules": ["./register.ts"]
+}
diff --git a/plugins/code-modernization/hooks/host.ts b/plugins/code-modernization/hooks/host.ts
new file mode 100644
index 00000000..c315fecf
--- /dev/null
+++ b/plugins/code-modernization/hooks/host.ts
@@ -0,0 +1,37 @@
+import type {
+ CommandSpec,
+ PaneCloseArgs,
+ PaneOpenArgs,
+ PromptFillArgs,
+ PromptSubmitArgs,
+ TimerCall,
+ UiBlitArgs,
+ UiBlitResult,
+} from 'claude-code'
+
+import type { ReaderFs } from './reader/fs'
+
+/**
+ * The engine as `session.start` bound it from its `$`: every later hook,
+ * timer and button press reaches the engine through this, so the rest of
+ * the module is plain functions over a small interface a test can stand in for.
+ */
+export type Host = {
+ fs: ReaderFs & { write: (path: string, text: string) => Promise<void> }
+ now: () => Promise<number>
+ after: TimerCall
+ every: TimerCall
+ storeGet: (key: string) => Promise<unknown>
+ storeSet: (key: string, value: unknown) => Promise<void>
+ invalidate: () => void
+ blit: (args: UiBlitArgs) => Promise<UiBlitResult>
+ status: (text: string | undefined) => void
+ toast: (text: string, timeoutMs?: number) => void
+ log: (text: string) => void
+ openPane: (pane: PaneOpenArgs) => Promise<void>
+ closePane: (pane: PaneCloseArgs) => Promise<void>
+ registerCommand: (spec: CommandSpec) => Promise<unknown>
+ fillPrompt: (input: PromptFillArgs) => Promise<{ isFilled: boolean }>
+ submitPrompt: (input: PromptSubmitArgs) => Promise<unknown>
+ abortTurn: (turnId: string) => Promise<void>
+}
diff --git a/plugins/code-modernization/hooks/map/estate.ts b/plugins/code-modernization/hooks/map/estate.ts
new file mode 100644
index 00000000..b3bd3d3a
--- /dev/null
+++ b/plugins/code-modernization/hooks/map/estate.ts
@@ -0,0 +1,191 @@
+import { estateOfTopology, type EstateUnit } from '../reader/estate-model'
+import type { ModuleState } from '../reader/modernized'
+import type { Snapshot } from '../reader/progress'
+import { STATE_WORDS_BY_TRACK, type TrackKey } from '../reader/tracks'
+import { DEFAULT_COLOR, luma, mix, packCells, type Cell } from './raster'
+import { layoutGroups, type Rect } from './treemap'
+
+/**
+ * The estate map: every unit of the legacy system as a tile, sized by its lines of code
+ * (or bytes of source, where there is no map), grouped by domain or directory, coloured by
+ * how far its modernization has come, and lit for a moment when a file beneath it is read or written.
+ */
+
+export type TouchKind = 'read' | 'write'
+
+export type Touch = { atMs: number; kind: TouchKind }
+
+export type TileState = ModuleState | 'untouched'
+
+export type Tile = {
+ id: string
+ name: string
+ domain: string
+ loc: number
+ state: TileState
+ rect: Rect
+ isNext: boolean
+}
+
+export type Estate = {
+ columns: number
+ rows: number
+ tiles: Tile[]
+ /** Base64 for the Raster's `cells`. */
+ cells: string
+ /** True while any tile is still fading from a touch, so another frame is due. */
+ isAnimating: boolean
+}
+
+/** How long a touch stays visible, in milliseconds. */
+export const FLASH_MS = 4000
+
+export const STATE_COLORS: Record<TileState, number> = {
+ untouched: 0x39414f,
+ scaffolded: 0x4b5d80,
+ 'tests-written': 0x94741f,
+ 'tests-red': 0xb23b3b,
+ 'tests-green': 0x2c7a4c,
+ reviewed: 0x2fa568,
+ ported: 0x2b8ea6,
+ switched: 0x3bd184,
+}
+
+/** What a state is called in a track: the same colors, worded for what the work is. */
+export const stateWord = (track: TrackKey, state: TileState): string => STATE_WORDS_BY_TRACK[track][state] ?? state
+
+const FLASH_COLORS: Record<TouchKind, number> = {
+ read: 0x9fd4ff,
+ write: 0xffe27a,
+}
+
+/** A stable small jitter per tile, so neighbours of one state still read as separate tiles. */
+const jitterOf = (id: string): number => {
+ let hash = 2166136261
+
+ for (let index = 0; index < id.length; index += 1) {
+ hash = Math.imul(hash ^ id.charCodeAt(index), 16777619)
+ }
+
+ return ((hash >>> 0) % 1000) / 1000
+}
+
+/** The module ids of the step the snapshot says comes next, when it is a transform. */
+function nextModuleOf(snapshot: Snapshot): string | null {
+ const text = snapshot.next?.text ?? ''
+ const match = /transform\s+\S+\s+(\S+)/.exec(text)
+
+ return snapshot.next?.isByHand === false ? (match?.[1] ?? null) : null
+}
+
+/** Lays the snapshot's estate out in `columns` by `rows` cells. */
+export function tilesOf(snapshot: Snapshot, columns: number, rows: number): Tile[] {
+ const estate = snapshot.estate ?? (snapshot.topology !== null ? estateOfTopology(snapshot.topology, 0) : null)
+
+ if (estate === null || columns < 4 || rows < 2) {
+ return []
+ }
+
+ const next = nextModuleOf(snapshot)
+ const groups = new Map<string, EstateUnit[]>()
+
+ for (const unit of estate.units) {
+ const members = groups.get(unit.group) ?? []
+
+ members.push(unit)
+ groups.set(unit.group, members)
+ }
+
+ const placed = layoutGroups(
+ [...groups.entries()].map(([name, members]) => ({
+ name,
+ items: members.map(unit => ({ item: unit, size: Math.max(1, unit.size) })),
+ })),
+ { x: 0, y: 0, w: columns, h: rows },
+ )
+
+ return placed.flatMap(group =>
+ group.items
+ .filter(entry => entry.rect.w > 0 && entry.rect.h > 0)
+ .map(entry => ({
+ id: entry.item.id,
+ name: entry.item.name,
+ domain: group.name,
+ loc: entry.item.size,
+ state: snapshot.byNode.get(entry.item.id)?.state ?? ('untouched' as const),
+ rect: entry.rect,
+ isNext: entry.item.id === next,
+ })),
+ )
+}
+
+/** Paints the tiles into cells and packs them for the Raster. */
+export function paint(
+ tiles: readonly Tile[],
+ columns: number,
+ rows: number,
+ touches: ReadonlyMap<string, Touch>,
+ nowMs: number,
+): Estate {
+ const blank: Cell = { glyph: ' ', fg: DEFAULT_COLOR, bg: DEFAULT_COLOR }
+ const cells: Cell[] = Array.from({ length: columns * rows }, () => blank)
+ let isAnimating = false
+
+ for (const tile of tiles) {
+ const base = mix(STATE_COLORS[tile.state], 0xffffff, (jitterOf(tile.id) - 0.5) * 0.14 + 0.02)
+ const touch = touches.get(tile.id)
+ const age = touch !== undefined ? nowMs - touch.atMs : Infinity
+ const heat = age < FLASH_MS ? 1 - age / FLASH_MS : 0
+
+ if (heat > 0) {
+ isAnimating = true
+ }
+
+ const body = heat > 0 && touch !== undefined ? mix(base, FLASH_COLORS[touch.kind], heat * 0.85) : base
+ const edge = mix(body, 0x000000, 0.32)
+ const ink = luma(body) > 140 ? 0x101418 : 0xf2f5f8
+ const { x, y, w, h } = tile.rect
+ const hasBevel = w >= 3 && h >= 2
+ const label = w >= 4 ? (tile.isNext ? '▸' : '') + tile.name : w >= 2 && tile.isNext ? '▸' : ''
+ const shown = label.slice(0, Math.max(0, w - (hasBevel ? 1 : 0)))
+
+ for (let row = 0; row < h; row += 1) {
+ for (let col = 0; col < w; col += 1) {
+ const cx = x + col
+ const cy = y + row
+
+ if (cx >= columns || cy >= rows) {
+ continue
+ }
+
+ const isEdge = hasBevel && (col === w - 1 || row === h - 1)
+ const glyph = row === 0 && col < shown.length ? (shown[col] ?? ' ') : ' '
+
+ cells[cy * columns + cx] = { glyph, fg: ink, bg: isEdge ? edge : body }
+ }
+ }
+ }
+
+ return { columns, rows, tiles: [...tiles], cells: packCells(cells), isAnimating }
+}
+
+/** How many modules sit in each state, in the order the legend draws them. */
+export function countsOf(tiles: readonly Tile[]): { state: TileState; count: number }[] {
+ const order: TileState[] = [
+ 'untouched',
+ 'scaffolded',
+ 'tests-written',
+ 'tests-red',
+ 'tests-green',
+ 'reviewed',
+ 'ported',
+ 'switched',
+ ]
+
+ return order
+ .map(state => ({ state, count: tiles.filter(tile => tile.state === state).length }))
+ .filter(entry => entry.count > 0)
+}
+
+/** `0x00RRGGBB` as the `#rrggbb` a `Text`'s `color` takes. */
+export const hexOf = (color: number): string => `#${(color & 0xffffff).toString(16).padStart(6, '0')}`
diff --git a/plugins/code-modernization/hooks/map/raster.ts b/plugins/code-modernization/hooks/map/raster.ts
new file mode 100644
index 00000000..1a9b0ee0
--- /dev/null
+++ b/plugins/code-modernization/hooks/map/raster.ts
@@ -0,0 +1,92 @@
+/**
+ * Packing for the terminal's `Raster` element: a grid of cells, each a glyph
+ * with a foreground and a background colour, as the base64 the element takes
+ * (`columns * rows` little-endian u32 triplets `[codePoint, fg, bg]`).
+ */
+
+export type Cell = { glyph: string; fg: number; bg: number }
+
+/** The terminal's own default colour, as `RasterProps` spells it. */
+export const DEFAULT_COLOR = 0x01000000
+
+const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+
+/** Standard padded base64 of bytes, with no dependence on `btoa` or `Uint8Array.toBase64`. */
+export function base64Of(bytes: Uint8Array): string {
+ let out = ''
+
+ for (let index = 0; index < bytes.length; index += 3) {
+ const a = bytes[index] ?? 0
+ const b = bytes[index + 1] ?? 0
+ const c = bytes[index + 2] ?? 0
+ const has2 = index + 1 < bytes.length
+ const has3 = index + 2 < bytes.length
+
+ out +=
+ (B64[a >> 2] ?? '') +
+ (B64[((a & 3) << 4) | (b >> 4)] ?? '') +
+ (has2 ? (B64[((b & 15) << 2) | (c >> 6)] ?? '') : '=') +
+ (has3 ? (B64[c & 63] ?? '') : '=')
+ }
+
+ return out
+}
+
+/** A printable width-1 BMP code point for `glyph`, or a space when it is not one. */
+export function codePointOf(glyph: string): number {
+ const point = glyph.codePointAt(0) ?? 0x20
+
+ const isPrintable =
+ point >= 0x20 &&
+ point <= 0xffff &&
+ point !== 0x7f &&
+ !(point >= 0x80 && point < 0xa0) &&
+ !(point >= 0xd800 && point <= 0xdfff) &&
+ // East Asian wide and fullwidth ranges draw two cells.
+ !(point >= 0x1100 && point <= 0x115f) &&
+ !(point >= 0x2e80 && point <= 0xa4cf) &&
+ !(point >= 0xac00 && point <= 0xd7a3) &&
+ !(point >= 0xf900 && point <= 0xfaff) &&
+ !(point >= 0xfe30 && point <= 0xfe6f) &&
+ !(point >= 0xff00 && point <= 0xff60) &&
+ !(point >= 0xffe0 && point <= 0xffe6)
+
+ return isPrintable ? point : 0x20
+}
+
+/** Packs row-major `cells` (`columns * rows` of them) for a `Raster`'s `cells` prop. */
+export function packCells(cells: readonly Cell[]): string {
+ const bytes = new Uint8Array(cells.length * 12)
+ const view = new DataView(bytes.buffer)
+
+ cells.forEach((cell, index) => {
+ view.setUint32(index * 12, codePointOf(cell.glyph), true)
+ view.setUint32(index * 12 + 4, cell.fg >>> 0, true)
+ view.setUint32(index * 12 + 8, cell.bg >>> 0, true)
+ })
+
+ return base64Of(bytes)
+}
+
+/** `0x00RRGGBB` from three 0-255 channels. */
+export const rgb = (r: number, g: number, b: number): number =>
+ ((Math.max(0, Math.min(255, Math.round(r))) << 16) |
+ (Math.max(0, Math.min(255, Math.round(g))) << 8) |
+ Math.max(0, Math.min(255, Math.round(b)))) >>>
+ 0
+
+/** `a` moved `t` of the way (0 to 1) toward `b`, channel by channel. */
+export function mix(a: number, b: number, t: number): number {
+ const k = Math.max(0, Math.min(1, t))
+ const ch = (c: number, shift: number) => (c >> shift) & 0xff
+
+ return rgb(
+ ch(a, 16) + (ch(b, 16) - ch(a, 16)) * k,
+ ch(a, 8) + (ch(b, 8) - ch(a, 8)) * k,
+ ch(a, 0) + (ch(b, 0) - ch(a, 0)) * k,
+ )
+}
+
+/** Perceived brightness, 0 to 255. */
+export const luma = (color: number): number =>
+ 0.299 * ((color >> 16) & 0xff) + 0.587 * ((color >> 8) & 0xff) + 0.114 * (color & 0xff)
diff --git a/plugins/code-modernization/hooks/map/treemap.ts b/plugins/code-modernization/hooks/map/treemap.ts
new file mode 100644
index 00000000..21042734
--- /dev/null
+++ b/plugins/code-modernization/hooks/map/treemap.ts
@@ -0,0 +1,156 @@
+/**
+ * A squarified treemap over a grid of terminal cells, two levels deep:
+ * groups (domains) first, then each group's items (modules) inside its
+ * rectangle. Pure: sizes in, integer cell rectangles out.
+ *
+ * A terminal cell is about twice as tall as it is wide, so the layout works
+ * in a space where each row counts double and rounds back to whole cells.
+ */
+
+export type Rect = { x: number; y: number; w: number; h: number }
+
+export type Sized<T> = { item: T; size: number }
+
+export type Placed<T> = { item: T; rect: Rect }
+
+/** How much taller than wide one cell is; rows are weighted by it when judging squareness. */
+const CELL_ASPECT = 2
+
+const worst = (row: number[], side: number, scale: number): number => {
+ const sum = row.reduce((a, b) => a + b, 0)
+
+ if (sum === 0 || side === 0) {
+ return Infinity
+ }
+
+ const max = Math.max(...row)
+ const min = Math.min(...row)
+ const s2 = sum * sum
+ const side2 = side * side * scale
+
+ return Math.max((side2 * max) / s2, s2 / (side2 * min))
+}
+
+/**
+ * Squarified layout of `sizes` (already scaled so they sum to the area of
+ * `rect`) into fractional rectangles, in the order given.
+ */
+function squarify(sizes: number[], rect: Rect): Rect[] {
+ const out: Rect[] = []
+ let { x, y, w, h } = rect
+ let index = 0
+
+ while (index < sizes.length) {
+ // Lay rows along the visually shorter side.
+ const isWide = w >= h * CELL_ASPECT
+ const side = isWide ? h : w
+ const scale = isWide ? CELL_ASPECT : 1 / CELL_ASPECT
+ const row: number[] = []
+
+ while (index < sizes.length) {
+ const next = sizes[index] ?? 0
+ const grown = [...row, next]
+
+ if (row.length > 0 && worst(grown, side, scale) > worst(row, side, scale)) {
+ break
+ }
+
+ row.push(next)
+ index += 1
+ }
+
+ const sum = row.reduce((a, b) => a + b, 0)
+ const thick = side > 0 ? sum / side : 0
+ let offset = 0
+
+ for (const size of row) {
+ const length = thick > 0 ? size / thick : 0
+
+ out.push(
+ isWide
+ ? { x, y: y + offset, w: thick, h: length }
+ : { x: x + offset, y, w: length, h: thick },
+ )
+
+ offset += length
+ }
+
+ if (isWide) {
+ x += thick
+ w -= thick
+ } else {
+ y += thick
+ h -= thick
+ }
+
+ if (w <= 0 || h <= 0) {
+ // Out of room: whatever is left collapses onto the last edge.
+ while (index < sizes.length) {
+ out.push({ x: rect.x + rect.w, y: rect.y + rect.h, w: 0, h: 0 })
+ index += 1
+ }
+ }
+ }
+
+ return out
+}
+
+/** Rounds fractional rectangles to whole cells without gaps or overlaps on shared edges. */
+function snap(rects: Rect[], bounds: Rect): Rect[] {
+ const clampX = (v: number) => Math.min(bounds.x + bounds.w, Math.max(bounds.x, Math.round(v)))
+ const clampY = (v: number) => Math.min(bounds.y + bounds.h, Math.max(bounds.y, Math.round(v)))
+
+ return rects.map(rect => {
+ const x0 = clampX(rect.x)
+ const y0 = clampY(rect.y)
+ const x1 = clampX(rect.x + rect.w)
+ const y1 = clampY(rect.y + rect.h)
+
+ return { x: x0, y: y0, w: Math.max(0, x1 - x0), h: Math.max(0, y1 - y0) }
+ })
+}
+
+/** Lays `entries` out in `rect`, largest first, each given at least `floor` of the mean size. */
+export function layout<T>(entries: Sized<T>[], rect: Rect, floor = 0.35): Placed<T>[] {
+ if (entries.length === 0 || rect.w <= 0 || rect.h <= 0) {
+ return []
+ }
+
+ const positive = entries.map(entry => ({ ...entry, size: Math.max(0, entry.size) }))
+ const mean = positive.reduce((sum, entry) => sum + entry.size, 0) / positive.length || 1
+
+ // A tiny item next to a huge one would round to zero cells: lift it to a floor.
+ const lifted = positive
+ .map(entry => ({ ...entry, size: Math.max(entry.size, mean * floor) }))
+ .sort((a, b) => b.size - a.size)
+
+ const total = lifted.reduce((sum, entry) => sum + entry.size, 0)
+ const area = rect.w * rect.h
+ const scaled = lifted.map(entry => (entry.size / total) * area)
+ const snapped = snap(squarify(scaled, rect), rect)
+
+ return lifted.map((entry, index) => ({
+ item: entry.item,
+ rect: snapped[index] ?? { x: rect.x, y: rect.y, w: 0, h: 0 },
+ }))
+}
+
+export type Group<T> = { name: string; items: Sized<T>[] }
+
+export type PlacedGroup<T> = { name: string; rect: Rect; items: Placed<T>[] }
+
+/** Two-level layout: groups by their items' total size, then items within each group. */
+export function layoutGroups<T>(groups: Group<T>[], rect: Rect): PlacedGroup<T>[] {
+ const sized = groups
+ .filter(group => group.items.length > 0)
+ .map(group => ({
+ item: group,
+ size: group.items.reduce((sum, entry) => sum + Math.max(0, entry.size), 0),
+ }))
+
+ return layout(sized, rect, 0.2).map(placed => ({
+ name: placed.item.name,
+ rect: placed.rect,
+ items: layout(placed.item.items, placed.rect),
+ }))
+}
diff --git a/plugins/code-modernization/hooks/paths.ts b/plugins/code-modernization/hooks/paths.ts
new file mode 100644
index 00000000..ce34edd1
--- /dev/null
+++ b/plugins/code-modernization/hooks/paths.ts
@@ -0,0 +1,94 @@
+/**
+ * Path helpers. A hooks module has no `path` module: these are the few
+ * string operations the hooks need, all over forward-slash paths.
+ */
+
+/** Forward slashes, no doubled separators, no trailing slash (root stays `/`). */
+export function norm(path: string): string {
+ const clean = path.replace(/\\/g, '/').replace(/\/{2,}/g, '/')
+
+ return clean.length > 1 && clean.endsWith('/') ? clean.slice(0, -1) : clean
+}
+
+/** Resolves `.` and `..` segments lexically; absolute stays absolute. */
+export function resolveDots(path: string): string {
+ const isAbsolute = path.startsWith('/')
+ const out: string[] = []
+
+ for (const part of norm(path).split('/')) {
+ if (part === '' || part === '.') {
+ continue
+ }
+
+ if (part === '..') {
+ if (out.length > 0 && out.at(-1) !== '..') {
+ out.pop()
+ } else if (!isAbsolute) {
+ out.push('..')
+ }
+
+ continue
+ }
+
+ out.push(part)
+ }
+
+ return (isAbsolute ? '/' : '') + out.join('/')
+}
+
+/** `path` made absolute against `cwd` when it is relative. */
+export function absOf(cwd: string, path: string): string {
+ return resolveDots(path.startsWith('/') ? path : `${norm(cwd)}/${path}`)
+}
+
+/**
+ * `path` relative to `cwd` when it lies inside it, else null. Both may be
+ * given with or without the macOS `/private` prefix the engine sometimes adds.
+ */
+export function relTo(cwd: string, path: string): string | null {
+ const strip = (p: string) => p.replace(/^\/private(?=\/(?:tmp|var)\/)/, '')
+ const base = strip(norm(cwd))
+ const full = strip(absOf(cwd, path))
+
+ if (full === base) {
+ return ''
+ }
+
+ return full.startsWith(`${base}/`) ? full.slice(base.length + 1) : null
+}
+
+/** True when relative path `rel` is `dir` or lies beneath it. */
+export function isUnder(rel: string, dir: string): boolean {
+ const d = norm(dir)
+
+ return rel === d || rel.startsWith(`${d}/`)
+}
+
+/** The last segment. */
+export function baseName(path: string): string {
+ const parts = norm(path).split('/')
+
+ return parts.at(-1) ?? ''
+}
+
+/** The last segment without its final extension. */
+export function stemOf(path: string): string {
+ const base = baseName(path)
+ const dot = base.lastIndexOf('.')
+
+ return dot > 0 ? base.slice(0, dot) : base
+}
+
+/** Everything but the last segment (`''` for a bare name). */
+export function dirName(path: string): string {
+ const parts = norm(path).split('/')
+
+ parts.pop()
+
+ return parts.join('/')
+}
+
+/** Joins segments with single slashes. */
+export function join(...parts: string[]): string {
+ return norm(parts.filter(part => part !== '').join('/'))
+}
diff --git a/plugins/code-modernization/hooks/reader/brief.ts b/plugins/code-modernization/hooks/reader/brief.ts
new file mode 100644
index 00000000..890aa58a
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/brief.ts
@@ -0,0 +1,200 @@
+/**
+ * `analysis/<system>/MODERNIZATION_BRIEF.md`, read without a model: the
+ * target stack, the phases, which modules each phase names, the exit
+ * criteria boxes, and the approval block.
+ *
+ * The brief is prose an agent wrote, so every field is best-effort and a
+ * field that cannot be read is absent, never guessed.
+ */
+
+export type Criterion = {
+ /** The line as written, checkbox included. */
+ line: string
+ /** The criterion's text: the line without its checkbox and tick annotation. */
+ text: string
+ isTicked: boolean
+}
+
+export type Phase = {
+ number: number
+ title: string
+ /** `S`, `M`, `L`, `XL`, when the heading says. */
+ size?: string
+ risk?: string
+ /** Module ids (as the caller's `knownModules` names them) the phase's text mentions. */
+ modules: string[]
+ criteria: Criterion[]
+}
+
+export type Approval = {
+ isSigned: boolean
+ by?: string
+ date?: string
+ /** `phase-1`, `full`, or undefined when the block does not say. */
+ covers?: 'phase-1' | 'full'
+}
+
+export type Brief = {
+ target?: string
+ phases: Phase[]
+ approval: Approval
+ /** Unticked `- [ ]` boxes under the Open Questions section. */
+ openQuestions: number
+}
+
+const PHASE_HEADING = /^#{2,4}\s+Phase\s+(\d+)\s*[—–:.\-]\s*(.+?)\s*$/i
+const CHECKBOX = /^\s*[-*]\s+\[( |x|X)\]\s+(.*)$/
+const TICK_NOTE = /\s*\((?:[^()]*\d{4}-\d{2}-\d{2}[^()]*)\)\s*$/
+
+const strip = (text: string) => text.replace(/\*\*/g, '').replace(/`/g, '').trim()
+
+/** The criterion text of a checkbox line, its tick annotation `(who, date)` removed. */
+export function criterionTextOf(line: string): string | null {
+ const match = CHECKBOX.exec(line)
+
+ if (match === null) {
+ return null
+ }
+
+ return strip((match[2] ?? '').replace(TICK_NOTE, '')).replace(/\s+/g, ' ')
+}
+
+/**
+ * Parses the brief.
+ *
+ * @param text the file
+ * @param knownModules module ids from topology.json; a phase lists the ones
+ * its text mentions as whole words
+ */
+export function parseBrief(text: string, knownModules: readonly string[] = []): Brief {
+ const lines = text.split('\n')
+
+ const titleLine = lines.find(line => /^#\s+/.test(line)) ?? ''
+ const arrow = /[→>]\s*(.+?)\s*$/.exec(titleLine.replace(/->/g, '→'))
+ const target = arrow?.[1] !== undefined ? strip(arrow[1]) : undefined
+
+ const phases: Phase[] = []
+ let current: { phase: Phase; body: string[]; level: number } | null = null
+ let section = ''
+ let openQuestions = 0
+
+ const closePhase = () => {
+ if (current === null) {
+ return
+ }
+
+ const body = current.body.join('\n')
+
+ // The modules a phase names, the pilot's first and the rest in the order the phase
+ // names them: the first one open is what the next step runs, and topology order
+ // would put an identity screen ahead of a batch job the brief chose as its pilot.
+ const wholeWord = (id: string) =>
+ new RegExp(`(?<![A-Za-z0-9_])${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9_])`)
+
+ const pilotLine = /^.*\bpilot unit\b.*$/im.exec(body)?.[0] ?? ''
+
+ current.phase.modules = knownModules
+ .map(id => ({ id, at: body.search(wholeWord(id)), isPilot: wholeWord(id).test(pilotLine) }))
+ .filter(entry => entry.at >= 0)
+ .sort((a, b) => Number(b.isPilot) - Number(a.isPilot) || a.at - b.at)
+ .map(entry => entry.id)
+
+ phases.push(current.phase)
+ current = null
+ }
+
+ for (const line of lines) {
+ const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line)
+
+ if (heading !== null) {
+ const level = heading[1]?.length ?? 1
+ const phase = PHASE_HEADING.exec(line)
+
+ if (phase !== null) {
+ closePhase()
+
+ const parts = (phase[2] ?? '').split('·').map(part => strip(part))
+ const size = parts.map(part => /^Size\s+(\w+)/i.exec(part)?.[1]).find(Boolean)
+ const risk = parts.map(part => /^Risk\s+(\w+)/i.exec(part)?.[1]).find(Boolean)
+
+ current = {
+ level,
+ body: [line],
+ phase: {
+ number: Number(phase[1]),
+ title: parts[0] ?? '',
+ ...(size !== undefined && { size: size.toUpperCase() }),
+ ...(risk !== undefined && { risk }),
+ modules: [],
+ criteria: [],
+ },
+ }
+
+ continue
+ }
+
+ if (current !== null && level <= current.level) {
+ closePhase()
+ }
+
+ if (level <= 2) {
+ section = strip(heading[2] ?? '').toLowerCase()
+ }
+ }
+
+ if (current !== null) {
+ current.body.push(line)
+
+ const box = CHECKBOX.exec(line)
+ const textOf = criterionTextOf(line)
+
+ if (box !== null && textOf !== null) {
+ current.phase.criteria.push({
+ line,
+ text: textOf,
+ isTicked: box[1] !== ' ',
+ })
+ }
+
+ continue
+ }
+
+ if (/open questions/.test(section) && /^\s*[-*]\s+\[ \]/.test(line)) {
+ openQuestions += 1
+ }
+ }
+
+ closePhase()
+
+ const approvedLine = lines.find(line => /^\s*Approved by\s*:/i.test(line))
+ const by = approvedLine?.replace(/^\s*Approved by\s*:/i, '').replace(/Date\s*:.*$/i, '').trim()
+ const isSigned = by !== undefined && by !== '' && !/^_+$/.test(by.replace(/\s/g, ''))
+
+ const dateLine = lines.find(line => /^\s*(?:Approved by\s*:.*)?Date\s*:\s*\S/i.test(line))
+ const date = /Date\s*:\s*(\d{4}-\d{2}-\d{2}|[^\s_][^_\n]*?)\s*$/i.exec(dateLine ?? '')?.[1]
+
+ const coversLine = lines.find(line => /Approval covers\s*:/i.test(line)) ?? ''
+ const ticked = [...coversLine.matchAll(/\[\s*[xX]\s*\]\s*([^[\]|]+)/g)].map(m => (m[1] ?? '').trim())
+
+ const plain = coversLine.replace(/^.*Approval covers\s*:/i, '').trim()
+
+ const coversText = ticked[0] ?? (/\[/.test(coversLine) || /\|/.test(plain) ? '' : plain)
+
+ const covers = /full/i.test(coversText)
+ ? ('full' as const)
+ : /phase\s*1/i.test(coversText)
+ ? ('phase-1' as const)
+ : undefined
+
+ return {
+ ...(target !== undefined && target !== '' && { target }),
+ phases,
+ approval: {
+ isSigned,
+ ...(isSigned && by !== undefined && { by }),
+ ...(isSigned && date !== undefined && { date: date.trim() }),
+ ...(isSigned && covers !== undefined && { covers }),
+ },
+ openQuestions,
+ }
+}
diff --git a/plugins/code-modernization/hooks/reader/discover.ts b/plugins/code-modernization/hooks/reader/discover.ts
new file mode 100644
index 00000000..b6ab6117
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/discover.ts
@@ -0,0 +1,341 @@
+import { baseName, join, stemOf } from '../paths'
+import {
+ groupOfDir,
+ languageOf,
+ weightOf,
+ type EstateModel,
+ type EstateUnit,
+} from './estate-model'
+import { listOrEmpty, type ReaderFs } from './fs'
+
+/**
+ * Reads the estate off the legacy tree when no map exists: any language, any
+ * layout. A directory with a build file of its own is one unit (a Maven or Gradle
+ * module, an npm package, a .NET project, a Go module, a Python package); a tree
+ * with no build files is one unit per source file when it is small enough to show,
+ * else one per directory. Sizes are bytes of source: what the file system knows
+ * without reading a file.
+ */
+
+/** Directories that hold what a build made or what someone else wrote, never the system's own code. */
+const SKIP_DIRS = new Set([
+ '.git', '.hg', '.svn', 'node_modules', 'target', 'dist', 'obj', 'build', 'out', '.gradle', '.idea', '.vscode',
+ '__pycache__', '.venv', 'venv', '.tox', '.mypy_cache', '.pytest_cache', 'coverage', '.next', '.nuxt', 'Pods',
+ 'vendor', 'bower_components', 'site-packages',
+])
+
+const MANIFEST_NAMES = new Set([
+ 'pom.xml', 'build.gradle', 'build.gradle.kts', 'package.json', 'go.mod', 'Cargo.toml', 'pyproject.toml',
+ 'setup.py', 'composer.json', 'Gemfile', 'mix.exs', 'CMakeLists.txt', 'pubspec.yaml', 'Package.swift',
+ 'build.sbt', 'project.clj', 'deps.edn', 'cpanfile', 'Makefile.PL', 'BUILD.bazel', 'Project.toml',
+])
+
+const MANIFEST_SUFFIXES = ['.csproj', '.fsproj', '.vbproj', '.vcxproj']
+
+const isManifest = (name: string): boolean => MANIFEST_NAMES.has(name) || MANIFEST_SUFFIXES.some(suffix => name.endsWith(suffix))
+
+/** What a walk may spend: directories read, and entries seen. */
+export type Budget = { dirs: number; entries: number }
+
+export const DEFAULT_BUDGET: Budget = { dirs: 4000, entries: 80_000 }
+
+/** A file-per-unit estate is shown only up to this many source files. */
+const MAX_FILE_UNITS = 500
+
+/** The most units an estate keeps; the rest are too small to draw. */
+const MAX_UNITS = 1500
+
+type DirInfo = {
+ /** Source bytes in files directly in this directory. */
+ bytes: number
+ /** The same, counting files of a kind no list knows: the tree may be written in a language this one does not name. */
+ lenientBytes: number
+ files: { name: string; size: number; lenient: number; raw: number }[]
+ dirs: string[]
+ hasManifest: boolean
+}
+
+/** Reads every directory under `root` that the budget allows, keyed by path relative to it (`''` is the root). */
+export async function walk(
+ fs: ReaderFs,
+ root: string,
+ budget: Budget,
+): Promise<{ dirs: Map<string, DirInfo>; isPartial: boolean; files: number; bytesByLanguage: Map<string, number> }> {
+ const dirs = new Map<string, DirInfo>()
+ const bytesByLanguage = new Map<string, number>()
+ let queue: string[] = ['']
+ let readDirs = 0
+ let entries = 0
+ let files = 0
+ let isPartial = false
+
+ while (queue.length > 0) {
+ const room = budget.dirs - readDirs
+
+ if (room <= 0 || entries > budget.entries) {
+ isPartial = true
+
+ break
+ }
+
+ const level = queue.slice(0, Math.min(16, room))
+
+ queue = queue.slice(level.length)
+ readDirs += level.length
+
+ const listed = await Promise.all(level.map(rel => listOrEmpty(fs, rel === '' ? root : join(root, rel))))
+
+ level.forEach((rel, index) => {
+ const list = listed[index] ?? []
+ const info: DirInfo = { bytes: 0, lenientBytes: 0, files: [], dirs: [], hasManifest: false }
+
+ entries += list.length
+
+ for (const entry of list) {
+ if (entry.kind === 'dir') {
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {
+ info.dirs.push(entry.name)
+ queue.push(rel === '' ? entry.name : `${rel}/${entry.name}`)
+ }
+
+ continue
+ }
+
+ if (entry.kind !== 'file') {
+ continue
+ }
+
+ if (isManifest(entry.name)) {
+ info.hasManifest = true
+ }
+
+ const strict = weightOf(entry.name, entry.size)
+ const lenient = weightOf(entry.name, entry.size, true)
+
+ if (lenient > 0) {
+ info.files.push({ name: entry.name, size: strict, lenient, raw: entry.size })
+ info.bytes += strict
+ info.lenientBytes += lenient
+ files += 1
+ }
+
+ const language = strict > 0 ? languageOf(entry.name) : undefined
+
+ if (language !== undefined) {
+ bytesByLanguage.set(language, (bytesByLanguage.get(language) ?? 0) + strict)
+ }
+ }
+
+ dirs.set(rel, info)
+ })
+ }
+
+ if (queue.length > 0) {
+ isPartial = true
+ }
+
+ return { dirs, isPartial, files, bytesByLanguage }
+}
+
+/** Every file a walk counted, by path relative to its root, with its size in bytes. */
+export function sizesOf(dirs: Map<string, DirInfo>): Map<string, number> {
+ const sizes = new Map<string, number>()
+
+ for (const [rel, info] of dirs) {
+ for (const file of info.files) {
+ sizes.set(rel === '' ? file.name : `${rel}/${file.name}`, file.raw)
+ }
+ }
+
+ return sizes
+}
+
+/**
+ * The files under `root` and their sizes, read with the file API alone: nothing is run inside the tree.
+ * Null when the walk hit its budget, since a partial listing would call every unread file changed.
+ */
+export async function sourceSizes(fs: ReaderFs, root: string, budget: Budget = DEFAULT_BUDGET): Promise<Map<string, number> | null> {
+ const walked = await walk(fs, root, budget)
+
+ return walked.isPartial ? null : sizesOf(walked.dirs)
+}
+
+/** Bytes under `rel`, every directory beneath included. */
+function totalBytes(dirs: Map<string, DirInfo>, rel: string): number {
+ const info = dirs.get(rel)
+
+ if (info === undefined) {
+ return 0
+ }
+
+ return info.dirs.reduce(
+ (sum, name) => sum + totalBytes(dirs, rel === '' ? name : `${rel}/${name}`),
+ info.bytes,
+ )
+}
+
+const under = (path: string, dir: string): boolean => dir === '' || path === dir || path.startsWith(`${dir}/`)
+
+/** Units where each directory with a build file is one, sized by the bytes not inside a unit beneath it. */
+function buildModules(dirs: Map<string, DirInfo>, rootLabel: string): EstateUnit[] {
+ const manifestDirs = [...dirs.entries()].filter(([, info]) => info.hasManifest).map(([rel]) => rel)
+ const set = new Set(manifestDirs)
+
+ const ownBytes = (rel: string): number => {
+ const info = dirs.get(rel)
+
+ if (info === undefined) {
+ return 0
+ }
+
+ return info.dirs.reduce((sum, name) => {
+ const child = rel === '' ? name : `${rel}/${name}`
+
+ return set.has(child) ? sum : sum + ownBytes(child)
+ }, info.bytes)
+ }
+
+ return manifestDirs
+ .map(rel => ({
+ id: rel === '' ? '.' : rel,
+ name: rel === '' ? rootLabel : baseName(rel),
+ group: rel === '' ? rootLabel : groupOfDir(rel, rootLabel),
+ size: ownBytes(rel),
+ dir: rel,
+ }))
+ .filter(unit => unit.size > 0)
+}
+
+/** One unit per source file, grouped by the directory it sits in. */
+function fileUnits(dirs: Map<string, DirInfo>, rootLabel: string): EstateUnit[] {
+ const units: EstateUnit[] = []
+
+ for (const [rel, info] of dirs) {
+ for (const file of info.files) {
+ if (file.size <= 0) {
+ continue
+ }
+
+ const path = rel === '' ? file.name : `${rel}/${file.name}`
+
+ units.push({
+ id: path,
+ name: stemOf(file.name),
+ group: rel === '' ? rootLabel : rel,
+ size: Math.max(1, file.size),
+ file: path,
+ })
+ }
+ }
+
+ return units
+}
+
+/** One unit per directory: the top-level ones, and the children of a lone directory that holds nearly everything. */
+function directoryUnits(dirs: Map<string, DirInfo>, rootLabel: string): EstateUnit[] {
+ const total = totalBytes(dirs, '')
+ let parent = ''
+
+ for (let guard = 0; guard < 4; guard += 1) {
+ const info = dirs.get(parent)
+ const children = info?.dirs ?? []
+ const sizes = children.map(name => ({ name, bytes: totalBytes(dirs, parent === '' ? name : `${parent}/${name}`) }))
+ const largest = sizes.sort((a, b) => b.bytes - a.bytes)[0]
+
+ if (largest === undefined || total === 0 || largest.bytes / total < 0.85 || (info?.bytes ?? 0) / total > 0.05) {
+ break
+ }
+
+ parent = parent === '' ? largest.name : `${parent}/${largest.name}`
+ }
+
+ const info = dirs.get(parent)
+ const units: EstateUnit[] = []
+
+ for (const name of info?.dirs ?? []) {
+ const rel = parent === '' ? name : `${parent}/${name}`
+ const size = totalBytes(dirs, rel)
+
+ if (size > 0) {
+ units.push({ id: rel, name, group: parent === '' ? rootLabel : parent, size, dir: rel })
+ }
+ }
+
+ if ((info?.bytes ?? 0) > 0) {
+ units.push({ id: parent === '' ? '.' : parent, name: parent === '' ? `${rootLabel} (files)` : `${baseName(parent)} (files)`, group: parent === '' ? rootLabel : parent, size: info?.bytes ?? 0, dir: parent })
+ }
+
+ return units
+}
+
+/**
+ * The estate of one system, read off `<root>` (its directory under the legacy tree). Null when the
+ * directory holds no source.
+ */
+export async function discoverEstate(
+ fs: ReaderFs,
+ root: string,
+ rootLabel: string,
+ budget: Budget = DEFAULT_BUDGET,
+): Promise<EstateModel | null> {
+ const walked = await walk(fs, root, budget)
+
+ if (walked.files === 0) {
+ return null
+ }
+
+ // A tree written in a language nobody listed has almost no weight on a strict count: count every file of an unknown
+ // kind as source then, so the estate is the tree and not the few configuration files beside it.
+ const strictTotal = [...walked.dirs.values()].reduce((sum, info) => sum + info.bytes, 0)
+ const lenientTotal = [...walked.dirs.values()].reduce((sum, info) => sum + info.lenientBytes, 0)
+
+ if (lenientTotal > 0 && strictTotal < lenientTotal * 0.35) {
+ for (const info of walked.dirs.values()) {
+ info.bytes = info.lenientBytes
+
+ for (const file of info.files) {
+ file.size = file.lenient
+ }
+ }
+ }
+
+ const counted = [...walked.dirs.values()].reduce((sum, info) => sum + info.files.filter(file => file.size > 0).length, 0)
+ const manifestCount = [...walked.dirs.entries()].filter(([rel, info]) => info.hasManifest && rel !== '').length
+
+ let units: EstateUnit[]
+ let granularity: EstateModel['granularity']
+
+ if (manifestCount >= 2) {
+ units = buildModules(walked.dirs, rootLabel)
+ granularity = 'build module'
+ } else if (counted <= MAX_FILE_UNITS) {
+ units = fileUnits(walked.dirs, rootLabel)
+ granularity = 'file'
+ } else {
+ units = directoryUnits(walked.dirs, rootLabel)
+ granularity = 'directory'
+ }
+
+ if (units.length === 0) {
+ return null
+ }
+
+ const total = [...walked.bytesByLanguage.values()].reduce((sum, bytes) => sum + bytes, 0)
+
+ const languages = [...walked.bytesByLanguage.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 3)
+ .map(([name, bytes]) => ({ name, share: total > 0 ? bytes / total : 0 }))
+
+ return {
+ source: 'tree',
+ measure: 'bytes',
+ granularity,
+ units: units.sort((a, b) => b.size - a.size).slice(0, MAX_UNITS),
+ files: counted,
+ languages,
+ isPartial: walked.isPartial,
+ fileSizes: sizesOf(walked.dirs),
+ }
+}
+
diff --git a/plugins/code-modernization/hooks/reader/estate-model.ts b/plugins/code-modernization/hooks/reader/estate-model.ts
new file mode 100644
index 00000000..fb8204a3
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/estate-model.ts
@@ -0,0 +1,213 @@
+import { baseName, dirName, norm, stemOf } from '../paths'
+import { nodeOfFile, type Topology } from './topology'
+
+/**
+ * The estate: the units a system's code is divided into, whatever its language.
+ * They come from the map's `topology.json` when there is one and from the legacy
+ * tree itself when there is not, so the pane has a map from the first minute of
+ * a session in any workspace.
+ */
+
+export type EstateUnit = {
+ id: string
+ name: string
+ /** What the tile sits under: a domain, or the directory that holds the unit. */
+ group: string
+ /** Lines when the map gave them, bytes of source when the unit was read off the tree. */
+ size: number
+ /** The unit as a directory, relative to `legacy/<system>/` (`''` is the system root). */
+ dir?: string
+ /** The unit as one file, relative to `legacy/<system>/`. */
+ file?: string
+}
+
+/** What one unit is: a module the map named, a source file, a build module (a directory with its own build file), or a directory. */
+export type Granularity = 'module' | 'file' | 'build module' | 'directory'
+
+export type EstateModel = {
+ source: 'map' | 'tree'
+ /** What `size` counts. */
+ measure: 'lines' | 'bytes'
+ /** What a unit is, for the pane's words. */
+ granularity: Granularity
+ units: EstateUnit[]
+ /** Source files seen under the system root. */
+ files: number
+ /** The languages the files are written in, largest first, as shares of the source bytes. */
+ languages: { name: string; share: number }[]
+ /** True when the walk stopped at its budget: the sizes are a floor. */
+ isPartial: boolean
+ /** Every source or configuration file the walk saw, relative to the system root, with its size in bytes. Kept to compare a working copy with the tree it was copied from; absent for an estate the map gave. */
+ fileSizes?: ReadonlyMap<string, number>
+}
+
+/** A language's name by file extension: the common ones, and the mainframe and scripting ones legacy work meets. */
+const LANGUAGES: Record<string, string> = {
+ java: 'Java', kt: 'Kotlin', kts: 'Kotlin', scala: 'Scala', groovy: 'Groovy', clj: 'Clojure',
+ cs: 'C#', vb: 'VB.NET', fs: 'F#', aspx: 'ASP.NET', ascx: 'ASP.NET', cshtml: 'Razor', asp: 'Classic ASP',
+ py: 'Python', rb: 'Ruby', php: 'PHP', pl: 'Perl', pm: 'Perl', lua: 'Lua', r: 'R',
+ js: 'JavaScript', mjs: 'JavaScript', cjs: 'JavaScript', jsx: 'JavaScript', ts: 'TypeScript', tsx: 'TypeScript',
+ go: 'Go', rs: 'Rust', swift: 'Swift', dart: 'Dart', ex: 'Elixir', exs: 'Elixir', erl: 'Erlang', hs: 'Haskell',
+ c: 'C', h: 'C', cc: 'C++', cpp: 'C++', cxx: 'C++', hpp: 'C++', m: 'Objective-C',
+ cbl: 'COBOL', cob: 'COBOL', cpy: 'COBOL', cobol: 'COBOL', pco: 'COBOL', jcl: 'JCL', bms: 'BMS', prc: 'JCL',
+ rpg: 'RPG', rpgle: 'RPG', sqlrpgle: 'RPG', clle: 'CL', pli: 'PL/I', pl1: 'PL/I', nat: 'Natural', asm: 'Assembler',
+ pas: 'Pascal', dpr: 'Delphi', bas: 'Basic', frm: 'VB6', cls: 'VB6', vbs: 'VBScript',
+ sql: 'SQL', sh: 'Shell', bash: 'Shell', ps1: 'PowerShell', bat: 'Batch', cmd: 'Batch',
+ jsp: 'JSP', xhtml: 'JSF', cfm: 'ColdFusion', tcl: 'Tcl', f: 'Fortran', f90: 'Fortran', for: 'Fortran',
+}
+
+/** Extensions that are not source: assets, binaries, archives, lock files, data and prose. */
+const NOT_SOURCE = new Set([
+ 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'bmp', 'webp', 'pdf', 'zip', 'gz', 'tgz', 'tar', 'jar', 'war', 'ear',
+ 'class', 'dll', 'exe', 'so', 'dylib', 'a', 'o', 'lib', 'pyc', 'woff', 'woff2', 'ttf', 'eot', 'otf', 'mp3', 'mp4',
+ 'mov', 'avi', 'wav', 'ogg', 'bin', 'dat', 'db', 'sqlite', 'log', 'lock', 'md', 'txt', 'rst', 'adoc', 'csv', 'tsv',
+ 'map', 'tmp', 'bak', 'orig', 'swp', 'ds_store', 'jks', 'p12', 'pem', 'crt', 'key', 'der', 'iso', 'img', 'rpm', 'deb',
+])
+
+/** Configuration and markup a build reads: part of the system, but never the bulk of its code. */
+const CONFIG_EXT = new Set([
+ 'xml', 'json', 'yaml', 'yml', 'toml', 'properties', 'gradle', 'cfg', 'conf', 'ini', 'html', 'htm', 'css', 'scss',
+ 'less', 'vue', 'svelte', 'xsl', 'xslt', 'xsd', 'wsdl', 'proto', 'graphql', 'ftl', 'vm', 'tpl', 'twig', 'erb',
+ 'jspx', 'tag', 'tld', 'dtd', 'mustache', 'hbs',
+])
+
+const CONFIG_NAMES = new Set(['Makefile', 'Dockerfile', 'Jenkinsfile', 'Rakefile', 'Gemfile', 'Vagrantfile', 'Procfile'])
+
+const extOf = (name: string): string => {
+ const dot = name.lastIndexOf('.')
+
+ return dot > 0 && dot < name.length - 1 ? name.slice(dot + 1).toLowerCase() : ''
+}
+
+/** A single file counts for at most this much: one binary blob or one generated file must not be a system's bulk. */
+const CAP_SOURCE = 400_000
+const CAP_CONFIG = 100_000
+
+/**
+ * What a file adds to the estate's size: its bytes (capped) when it is source or configuration, nothing when it is
+ * an asset, an archive, a document or a file of no known kind. `isLenient` counts unknown kinds as source too, for
+ * a language this list does not know.
+ */
+export function weightOf(name: string, size: number, isLenient = false): number {
+ if (name.startsWith('.')) {
+ return 0
+ }
+
+ const ext = extOf(name)
+
+ if (NOT_SOURCE.has(ext)) {
+ return 0
+ }
+
+ if (LANGUAGES[ext] !== undefined) {
+ return Math.min(size, CAP_SOURCE)
+ }
+
+ if (CONFIG_EXT.has(ext) || CONFIG_NAMES.has(name)) {
+ return Math.min(size, CAP_CONFIG)
+ }
+
+ return isLenient ? Math.min(size, CAP_SOURCE) : 0
+}
+
+/** Whether a file is one the estate counts (source or configuration). */
+export const isSourceFile = (name: string): boolean => weightOf(name, 1) > 0
+
+export const languageOf = (name: string): string | undefined => LANGUAGES[extOf(name)]
+
+/** A language name as a person writes it, from what a map recorded (`cobol` -> `COBOL`, `java` -> `Java`). */
+const nameOfLanguage = (raw: string): string => {
+ const known = Object.values(LANGUAGES).find(name => name.toLowerCase() === raw.toLowerCase())
+
+ return known ?? (raw.length <= 4 ? raw.toUpperCase() : raw.charAt(0).toUpperCase() + raw.slice(1))
+}
+
+/** The estate as a topology's modules, sized in lines. */
+export function estateOfTopology(topology: Topology, files: number): EstateModel {
+ const byLanguage = new Map<string, number>()
+
+ for (const node of topology.modules) {
+ if (node.language !== undefined) {
+ byLanguage.set(nameOfLanguage(node.language), (byLanguage.get(nameOfLanguage(node.language)) ?? 0) + Math.max(1, node.loc))
+ }
+ }
+
+ const total = [...byLanguage.values()].reduce((sum, size) => sum + size, 0)
+
+ return {
+ source: 'map',
+ measure: 'lines',
+ granularity: 'module',
+ units: topology.modules.map(node => ({
+ id: node.id,
+ name: node.name,
+ group: node.domain ?? 'Other',
+ size: Math.max(1, node.loc),
+ ...(node.file !== undefined && { file: node.file }),
+ })),
+ files,
+ languages: [...byLanguage.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 3)
+ .map(([name, size]) => ({ name, share: total > 0 ? size / total : 0 })),
+ isPartial: false,
+ }
+}
+
+/**
+ * The unit a path under `legacy/<system>/` belongs to: by the map's own file
+ * where there is a map, else by the file itself or the nearest directory that is a unit.
+ */
+export function unitOfPath(
+ estate: EstateModel,
+ topology: Topology | null,
+ rel: string,
+): EstateUnit | null {
+ const wanted = norm(rel)
+
+ if (estate.source === 'map' && topology !== null) {
+ const node = nodeOfFile(topology, wanted)
+
+ return node === null ? null : (estate.units.find(unit => unit.id === node.id) ?? null)
+ }
+
+ const exact = estate.units.find(unit => unit.file === wanted)
+
+ if (exact !== undefined) {
+ return exact
+ }
+
+ let best: EstateUnit | null = null
+ let bestLength = -1
+
+ for (const unit of estate.units) {
+ const dir = unit.dir
+
+ if (dir === undefined) {
+ continue
+ }
+
+ const isInside = dir === '' || wanted === dir || wanted.startsWith(`${dir}/`)
+
+ if (isInside && dir.length > bestLength) {
+ best = unit
+ bestLength = dir.length
+ }
+ }
+
+ return best
+}
+
+/** The names a transformed directory may be matched to a unit by: the id, the name, and the last path segment. */
+export function keysOfUnit(unit: EstateUnit): string[] {
+ const own = unit.dir !== undefined && unit.dir !== '' ? baseName(unit.dir) : unit.file !== undefined ? stemOf(unit.file) : ''
+
+ return [unit.id, unit.name, own].filter(key => key !== '')
+}
+
+/** The group a unit's directory sits in: its parent directory, or the root's own label. */
+export const groupOfDir = (dir: string, rootLabel: string): string => {
+ const parent = dirName(dir)
+
+ return parent === '' ? rootLabel : parent
+}
diff --git a/plugins/code-modernization/hooks/reader/fs.ts b/plugins/code-modernization/hooks/reader/fs.ts
new file mode 100644
index 00000000..44b570ed
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/fs.ts
@@ -0,0 +1,54 @@
+/**
+ * The file access the reader needs, narrow enough that `$.fs` and a test's
+ * in-memory tree both satisfy it. Paths are relative to the session's
+ * working directory or absolute, as `$.fs` takes them.
+ */
+export type ReaderFs = {
+ read: (path: string) => Promise<string>
+ list: (path: string) => Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number }[]>
+ exists: (path: string) => Promise<boolean>
+ stat: (path: string) => Promise<{ kind: 'file' | 'dir' | 'other'; size: number; mtimeMs: number }>
+}
+
+/** `read`, or null when the file is missing, unreadable or over the size cap. */
+export async function readOrNull(fs: ReaderFs, path: string): Promise<string | null> {
+ try {
+ // `exists` never rejects; asking first keeps a missing optional file out of the error log.
+ if (!(await fs.exists(path))) {
+ return null
+ }
+
+ return await fs.read(path)
+ } catch {
+ return null
+ }
+}
+
+/** `list`, or an empty list when the directory is missing. */
+export async function listOrEmpty(
+ fs: ReaderFs,
+ path: string,
+): Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number }[]> {
+ try {
+ if (!(await fs.exists(path))) {
+ return []
+ }
+
+ return await fs.list(path)
+ } catch {
+ return []
+ }
+}
+
+/** `stat`'s mtime, or null when the path is missing. */
+export async function mtimeOrNull(fs: ReaderFs, path: string): Promise<number | null> {
+ try {
+ if (!(await fs.exists(path))) {
+ return null
+ }
+
+ return (await fs.stat(path)).mtimeMs
+ } catch {
+ return null
+ }
+}
diff --git a/plugins/code-modernization/hooks/reader/modernized.ts b/plugins/code-modernization/hooks/reader/modernized.ts
new file mode 100644
index 00000000..600e1d39
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/modernized.ts
@@ -0,0 +1,384 @@
+import { join } from '../paths'
+import { listOrEmpty, readOrNull, type ReaderFs } from './fs'
+
+/**
+ * The state of each transformed module, read from `modernized/<system>/`:
+ * what exists on disk, what the test reports say, what the notes record.
+ * No inference: a fact that is not on disk is absent.
+ */
+
+export type TestTotals = {
+ tests: number
+ failures: number
+ errors: number
+ skipped: number
+ /** How many report files were read. */
+ reports: number
+}
+
+export type ModuleState =
+ | 'scaffolded'
+ | 'tests-written'
+ | 'tests-red'
+ | 'tests-green'
+ | 'reviewed'
+ | 'ported'
+ | 'switched'
+
+export type ModernizedModule = {
+ /** The directory's name under `modernized/<system>/`. */
+ dir: string
+ /** Path relative to the working directory. */
+ path: string
+ hasMain: boolean
+ hasTests: boolean
+ hasNotes: boolean
+ /** The date in the notes' "Architecture review" section; absent when none. */
+ reviewDate?: string
+ hasReviewSection: boolean
+ /** The notes say "ported, not switched". */
+ isPortedNotSwitched: boolean
+ /** The notes say the route was switched. */
+ isSwitched: boolean
+ /** Open follow-ups the notes list (bullets under a Follow-ups heading). */
+ followUps: number
+ tests: TestTotals | null
+ state: ModuleState
+ /** Newest mtime among the notes and test reports; 0 when unknown. */
+ mtimeMs: number
+}
+
+/** States a unit of work counts as finished in: the review is done, or the module is ported or switched. */
+const DONE_STATES: ReadonlySet<ModuleState> = new Set(['reviewed', 'ported', 'switched'])
+
+/**
+ * Whether a module's work is finished. Green tests with notes written count: the notes are where the plugin's
+ * review step lists what the critic found, and how they headline it varies, so a missing headline is not unfinished work.
+ */
+export const isDone = (module: Pick<ModernizedModule, 'state' | 'hasNotes'>): boolean =>
+ DONE_STATES.has(module.state) || (module.state === 'tests-green' && module.hasNotes)
+
+const EMPTY: TestTotals = { tests: 0, failures: 0, errors: 0, skipped: 0, reports: 0 }
+
+/** Totals of one Visual Studio test result file (`.trx`), the report `dotnet test --logger trx` leaves. */
+export function totalsOfTrx(xml: string): TestTotals | null {
+ const counters = /<Counters\b[^>]*>/.exec(xml)?.[0]
+
+ if (counters === undefined || !/\btotal="\d+"/.test(counters)) {
+ return null
+ }
+
+ return {
+ tests: attr(counters, 'total'),
+ failures: attr(counters, 'failed'),
+ errors: attr(counters, 'error') + attr(counters, 'timeout') + attr(counters, 'aborted'),
+ skipped: attr(counters, 'notExecuted') + attr(counters, 'inconclusive'),
+ reports: 1,
+ }
+}
+
+const attr = (tag: string, name: string): number => {
+ const match = new RegExp(`\\b${name}="(\\d+)"`).exec(tag)
+
+ return match?.[1] !== undefined ? Number(match[1]) : 0
+}
+
+/** Totals of one JUnit-style XML report (`<testsuite ...>` / `<testsuites ...>`). */
+export function totalsOfJunitXml(xml: string): TestTotals | null {
+ const suites = /<testsuites\b[^>]*>/.exec(xml)?.[0]
+
+ if (suites !== undefined && /\btests="\d+"/.test(suites)) {
+ return {
+ tests: attr(suites, 'tests'),
+ failures: attr(suites, 'failures'),
+ errors: attr(suites, 'errors'),
+ skipped: attr(suites, 'skipped') + attr(suites, 'disabled'),
+ reports: 1,
+ }
+ }
+
+ const all = [...xml.matchAll(/<testsuite\b[^>]*>/g)].map(match => match[0])
+
+ if (all.length === 0) {
+ return null
+ }
+
+ return all.reduce<TestTotals>(
+ (sum, tag) => ({
+ tests: sum.tests + attr(tag, 'tests'),
+ failures: sum.failures + attr(tag, 'failures'),
+ errors: sum.errors + attr(tag, 'errors'),
+ skipped: sum.skipped + attr(tag, 'skipped') + attr(tag, 'disabled'),
+ reports: 1,
+ }),
+ { ...EMPTY, reports: 1 },
+ )
+}
+
+const add = (a: TestTotals, b: TestTotals): TestTotals => ({
+ tests: a.tests + b.tests,
+ failures: a.failures + b.failures,
+ errors: a.errors + b.errors,
+ skipped: a.skipped + b.skipped,
+ reports: a.reports + b.reports,
+})
+
+/** Where test runners leave JUnit XML, relative to a module's directory. */
+const REPORT_DIRS = [
+ 'target/surefire-reports',
+ 'target/failsafe-reports',
+ 'build/test-results/test',
+ 'build/test-results',
+ 'build/logs',
+ 'test-results',
+ 'test-reports',
+ 'reports/junit',
+ 'TestResults',
+]
+
+const REPORT_FILES = ['junit.xml', 'report.xml', 'test-report.xml', 'pytest.xml']
+
+/** The test totals a directory's report files hold: a custom JSON report, JUnit XML, or a `.trx`. */
+export async function readTests(fs: ReaderFs, dir: string): Promise<TestTotals | null> {
+ const custom = await readOrNull(fs, join(dir, '.modernize/test-report.json'))
+
+ if (custom !== null) {
+ try {
+ const raw = JSON.parse(custom) as Record<string, unknown>
+ const num = (key: string) => (typeof raw[key] === 'number' ? (raw[key] as number) : 0)
+
+ return {
+ tests: num('tests'),
+ failures: num('failures'),
+ errors: num('errors'),
+ skipped: num('skipped'),
+ reports: 1,
+ }
+ } catch {
+ // fall through to the XML reports
+ }
+ }
+
+ let total: TestTotals | null = null
+
+ for (const sub of REPORT_DIRS) {
+ const entries = await listOrEmpty(fs, join(dir, sub))
+
+ for (const entry of entries) {
+ const isTrx = entry.name.endsWith('.trx')
+
+ if (entry.kind !== 'file' || !(entry.name.endsWith('.xml') || isTrx) || entry.size > 3_500_000) {
+ continue
+ }
+
+ const xml = await readOrNull(fs, join(dir, sub, entry.name))
+ const totals = xml === null ? null : isTrx ? totalsOfTrx(xml) : totalsOfJunitXml(xml)
+
+ if (totals !== null) {
+ total = total === null ? totals : add(total, totals)
+ }
+ }
+
+ if (total !== null) {
+ return total
+ }
+ }
+
+ for (const name of REPORT_FILES) {
+ const xml = await readOrNull(fs, join(dir, name))
+ const totals = xml !== null ? totalsOfJunitXml(xml) : null
+
+ if (totals !== null) {
+ return totals
+ }
+ }
+
+ return null
+}
+
+const TEST_DIRS = ['src/test', 'tests', 'test', 'spec', '__tests__']
+const MAIN_DIRS = ['src/main', 'src', 'app', 'lib']
+
+async function anyDir(fs: ReaderFs, dir: string, names: readonly string[]): Promise<boolean> {
+ for (const name of names) {
+ if ((await listOrEmpty(fs, join(dir, name))).length > 0) {
+ return true
+ }
+ }
+
+ return false
+}
+
+/** What the notes record, read by heading and phrase. */
+export function readNotes(notes: string): {
+ hasReviewSection: boolean
+ reviewDate?: string
+ isPortedNotSwitched: boolean
+ isSwitched: boolean
+ followUps: number
+} {
+ const lines = notes.split('\n')
+ // The plugin's review step spawns the architecture critic and lists what it found in the notes; how the notes
+ // headline that varies, so any heading that says review or critic counts, and so does naming the critic.
+ const named = lines.findIndex(line => /^#{1,4}\s+.*\b(?:review|critic)/i.test(line))
+ const start = named >= 0 ? named : -1
+ let reviewDate: string | undefined
+
+ if (start >= 0) {
+ const level = /^(#+)/.exec(lines[start] ?? '')?.[1]?.length ?? 2
+
+ const end = lines.findIndex(
+ (line, index) => index > start && new RegExp(`^#{1,${level}}\\s`).test(line),
+ )
+
+ const section = lines.slice(start, end < 0 ? undefined : end).join('\n')
+
+ reviewDate = /\b(\d{4}-\d{2}-\d{2})\b/.exec(section)?.[1]
+ }
+
+ const followStart = lines.findIndex(line => /^#{1,4}\s+.*follow-?ups?/i.test(line))
+ let followUps = 0
+
+ if (followStart >= 0) {
+ for (const line of lines.slice(followStart + 1)) {
+ if (/^#{1,4}\s/.test(line)) {
+ break
+ }
+
+ if (/^\s*[-*]\s+(?!\[[xX]\])/.test(line) || /^\s*\d+\.\s+/.test(line)) {
+ followUps += 1
+ }
+ }
+ }
+
+ const isPortedNotSwitched = /ported,?\s+not\s+switched/i.test(notes)
+
+ return {
+ hasReviewSection: start >= 0 || /architecture[- ]critic/i.test(notes),
+ ...(reviewDate !== undefined && { reviewDate }),
+ isPortedNotSwitched,
+ isSwitched:
+ !isPortedNotSwitched &&
+ /\b(?:route|traffic)\b[^\n]{0,40}\bswitched\b|\bswitched\b[^\n]{0,20}\b\d{4}-\d{2}-\d{2}\b/i.test(
+ notes,
+ ),
+ followUps,
+ }
+}
+
+/** The state a module's facts add up to, furthest first. */
+export function stateOf(module: Omit<ModernizedModule, 'state'>): ModuleState {
+ const tests = module.tests
+ const isRed = tests !== null && tests.failures + tests.errors > 0
+ const isGreen = tests !== null && tests.tests > 0 && !isRed
+
+ if (module.isSwitched && isGreen && module.hasReviewSection) {
+ return 'switched'
+ }
+
+ if (module.isPortedNotSwitched && isGreen) {
+ return 'ported'
+ }
+
+ if (isGreen && module.hasReviewSection) {
+ return 'reviewed'
+ }
+
+ if (isRed) {
+ return 'tests-red'
+ }
+
+ if (isGreen) {
+ return 'tests-green'
+ }
+
+ if (module.hasTests) {
+ return 'tests-written'
+ }
+
+ return 'scaffolded'
+}
+
+/**
+ * The state of one unit of an uplift's working copy: worse than its baseline, matching or exceeding it
+ * (every test that passed on the source runtime still passes, none is missing), tested but not comparable
+ * to a baseline row, changed and not yet tested, or not touched at all.
+ */
+export function stateOfUplift(
+ tests: TestTotals | null,
+ baseline: { pass: number; fail: number; error: number; skip: number } | null,
+ isChanged: boolean,
+): ModuleState | 'untouched' {
+ if (tests !== null && tests.tests > 0) {
+ const bad = tests.failures + tests.errors
+ const allowed = baseline === null ? 0 : baseline.fail + baseline.error
+
+ if (bad > allowed) {
+ return 'tests-red'
+ }
+
+ const passed = tests.tests - bad - tests.skipped
+ const isCovered = baseline !== null && tests.tests >= baseline.pass + baseline.fail + baseline.error + baseline.skip && passed >= baseline.pass
+
+ return isCovered ? 'reviewed' : 'tests-green'
+ }
+
+ return isChanged ? 'scaffolded' : 'untouched'
+}
+
+/** Reads every code directory under `modernized/<system>/`. */
+export async function readModernized(
+ fs: ReaderFs,
+ system: string,
+): Promise<ModernizedModule[]> {
+ return readModernizedIn(fs, join('modernized', system))
+}
+
+/** Reads every code directory directly under `root`: a transformed system's modules, or a reimagined system's services. */
+export async function readModernizedIn(
+ fs: ReaderFs,
+ root: string,
+ observed: ReadonlyMap<string, TestTotals> = new Map(),
+): Promise<ModernizedModule[]> {
+ const entries = await listOrEmpty(fs, root)
+ const out: ModernizedModule[] = []
+
+ for (const entry of entries) {
+ if (entry.kind !== 'dir' || entry.name.startsWith('.')) {
+ continue
+ }
+
+ const path = join(root, entry.name)
+ const notes = await readOrNull(fs, join(path, 'TRANSFORMATION_NOTES.md'))
+ const read = notes !== null ? readNotes(notes) : null
+ const tests = (await readTests(fs, path)) ?? observed.get(path) ?? null
+ let mtimeMs = 0
+
+ if (notes !== null) {
+ try {
+ mtimeMs = (await fs.stat(join(path, 'TRANSFORMATION_NOTES.md'))).mtimeMs
+ } catch {
+ mtimeMs = 0
+ }
+ }
+
+ const facts = {
+ dir: entry.name,
+ path,
+ hasMain: await anyDir(fs, path, MAIN_DIRS),
+ hasTests: await anyDir(fs, path, TEST_DIRS),
+ hasNotes: notes !== null,
+ hasReviewSection: read?.hasReviewSection ?? false,
+ ...(read?.reviewDate !== undefined && { reviewDate: read.reviewDate }),
+ isPortedNotSwitched: read?.isPortedNotSwitched ?? false,
+ isSwitched: read?.isSwitched ?? false,
+ followUps: read?.followUps ?? 0,
+ tests,
+ mtimeMs,
+ }
+
+ out.push({ ...facts, state: stateOf(facts) })
+ }
+
+ return out
+}
diff --git a/plugins/code-modernization/hooks/reader/progress.ts b/plugins/code-modernization/hooks/reader/progress.ts
new file mode 100644
index 00000000..711cabac
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/progress.ts
@@ -0,0 +1,849 @@
+import { join } from '../paths'
+import { parseBrief, type Brief, type Phase } from './brief'
+import { discoverEstate, sourceSizes } from './discover'
+import { estateOfTopology, keysOfUnit, type EstateModel, type EstateUnit } from './estate-model'
+import { listOrEmpty, mtimeOrNull, readOrNull, type ReaderFs } from './fs'
+import { isDone, readModernizedIn, type ModernizedModule, type TestTotals } from './modernized'
+import { needsReview, parseRules, type RuleSet } from './rules'
+import { pickTrack, TRACK_LABELS, type TrackKey } from './tracks'
+import { parseTopology, type Topology } from './topology'
+import {
+ changedUnitsOf,
+ parseBaseline,
+ parseCatalog,
+ changedPathsOf,
+ readUpliftUnits,
+ type Baseline,
+ type Catalog,
+} from './uplift'
+
+/**
+ * One reading of a system's modernization state, from the artifacts on disk
+ * alone. Everything here is a fact of a file that exists; nothing is inferred
+ * by a model, and what cannot be read is absent.
+ */
+
+export type StageKey =
+ | 'preflight'
+ | 'assess'
+ | 'map'
+ | 'rules'
+ | 'brief'
+ | 'transform'
+ | 'harden'
+ | 'deltas'
+ | 'baseline'
+ | 'pilot'
+ | 'migrate'
+ | 'verify'
+ | 'spec'
+ | 'design'
+ | 'scaffold'
+ | 'tests'
+
+export type Stage = {
+ key: StageKey
+ label: string
+ isDone: boolean
+ mtimeMs: number | null
+ /** One short qualifier (`signed`, `319 rules`), when there is one. */
+ detail?: string
+}
+
+export type ReviewVerdict = 'confirmed' | 'wrong' | 'discuss'
+
+export type ReviewLedger = Record<
+ string,
+ { verdict: ReviewVerdict; at: string; title?: string; note?: string }
+>
+
+export type NextStep = {
+ /** The slash command to run, or what to do by hand. */
+ text: string
+ isByHand: boolean
+ reason: string
+}
+
+/** What an uplift has left on disk, beyond the modules it changed. */
+export type UpliftFacts = {
+ catalog: Catalog | null
+ baseline: Baseline | null
+ hasPlaybook: boolean
+ hasNotes: boolean
+ hasCopy: boolean
+ /** Whether the working copy's changes could be read (a version-control status), or only its test reports. */
+ isChangeKnown: boolean
+}
+
+export type Snapshot = {
+ system: string
+ systems: string[]
+ /** Which way the plugin's commands are working on the system. */
+ track: TrackKey
+ /** True once the system has any artifact under `analysis/`: modernization is under way, not only possible. */
+ hasAnalysis: boolean
+ stages: Stage[]
+ /** The units the estate map draws: the map's modules, or what the legacy tree holds. */
+ estate: EstateModel | null
+ topology: Topology | null
+ rules: RuleSet | null
+ brief: Brief | null
+ /** The units of work under way: transformed modules, uplifted modules, or reimagined services. */
+ modules: ModernizedModule[]
+ /** Estate unit id to its unit of work, where one matches. */
+ byNode: Map<string, ModernizedModule>
+ /** Units of work that match no unit of the estate. */
+ extras: ModernizedModule[]
+ uplift: UpliftFacts | null
+ findings: { exists: boolean; isScan: boolean }
+ reviews: ReviewLedger
+ /** Size of the units finished over the estate's total; null without an estate, or where units of work are not the estate's own. */
+ percent: number | null
+ totals: { modules: number; done: number; loc: number; locDone: number }
+ attention: string[]
+ next: NextStep | null
+ readAtMs: number
+}
+
+export const STAGE_LABELS: Record<StageKey, string> = {
+ preflight: 'preflight',
+ assess: 'assess',
+ map: 'map',
+ rules: 'rules',
+ brief: 'brief',
+ transform: 'transform',
+ harden: 'harden',
+ deltas: 'deltas',
+ baseline: 'baseline',
+ pilot: 'pilot',
+ migrate: 'migrate',
+ verify: 'verify',
+ spec: 'spec',
+ design: 'design',
+ scaffold: 'scaffold',
+ tests: 'tests',
+}
+
+const STAGE_FILES = {
+ preflight: 'PREFLIGHT.md',
+ assess: 'ASSESSMENT.md',
+ map: 'topology.json',
+ rules: 'BUSINESS_RULES.md',
+ brief: 'MODERNIZATION_BRIEF.md',
+ transform: 'TRANSFORMATION_NOTES.md',
+ harden: 'SECURITY_FINDINGS.md',
+ deltas: 'DELTA_CATALOG.md',
+ baseline: 'BASELINE.md',
+ pilot: 'PLAYBOOK.md',
+ spec: 'AI_NATIVE_SPEC.md',
+ design: 'REIMAGINED_ARCHITECTURE.md',
+} as const
+
+export const REVIEWS_FILE = 'RULE_REVIEWS.json'
+
+/** Parsed files kept by path and mtime, so an unchanged file is parsed once. */
+export type ReaderCache = Map<string, { mtimeMs: number; value: unknown }>
+
+async function cached<T>(
+ fs: ReaderFs,
+ cache: ReaderCache,
+ path: string,
+ parse: (text: string) => T,
+): Promise<{ value: T | null; mtimeMs: number | null }> {
+ const mtimeMs = await mtimeOrNull(fs, path)
+
+ if (mtimeMs === null) {
+ cache.delete(path)
+
+ return { value: null, mtimeMs: null }
+ }
+
+ const hit = cache.get(path)
+
+ if (hit !== undefined && hit.mtimeMs === mtimeMs) {
+ return { value: hit.value as T, mtimeMs }
+ }
+
+ const text = await readOrNull(fs, path)
+
+ if (text === null) {
+ return { value: null, mtimeMs }
+ }
+
+ const value = parse(text)
+
+ cache.set(path, { mtimeMs, value })
+
+ return { value, mtimeMs }
+}
+
+/** The systems the workspace holds: each directory under `analysis/` and under the legacy tree. */
+export async function systemsOf(fs: ReaderFs, legacyDir = 'legacy'): Promise<string[]> {
+ const names = new Set<string>()
+
+ for (const root of ['analysis', legacyDir]) {
+ for (const entry of await listOrEmpty(fs, root)) {
+ if (entry.kind === 'dir' && !entry.name.startsWith('.')) {
+ names.add(entry.name)
+ }
+ }
+ }
+
+ return [...names].sort()
+}
+
+const slugOf = (target: string) =>
+ target
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+
+/** How a transformed directory's name is matched to a unit's names. */
+const keyOf = (name: string) => name.toLowerCase().replace(/::/g, '-').replace(/[^a-z0-9]+/g, '-')
+
+function approvedPhases(brief: Brief): Phase[] {
+ if (!brief.approval.isSigned) {
+ return []
+ }
+
+ const ordered = [...brief.phases].sort((a, b) => a.number - b.number)
+
+ return brief.approval.covers === 'full' ? ordered : ordered.slice(0, 1)
+}
+
+/** Whether one unit of work is finished, by what the track counts as finished. */
+export function isUnitDone(
+ snapshot: Pick<Snapshot, 'track' | 'uplift'>,
+ module: Pick<ModernizedModule, 'state' | 'hasNotes'>,
+): boolean {
+ if (snapshot.track !== 'uplift') {
+ return isDone(module)
+ }
+
+ // An uplift is proven by reproducing the baseline; with no per-module baseline, passing is all there is to compare.
+ const hasRows = (snapshot.uplift?.baseline?.rows.size ?? 0) > 0
+
+ return module.state === 'reviewed' || (module.state === 'tests-green' && !hasRows)
+}
+
+function nextOfTransform(
+ prefix: string,
+ system: string,
+ stages: Stage[],
+ brief: Brief | null,
+ byNode: Map<string, ModernizedModule>,
+): NextStep | null {
+ const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true
+ const cmd = (name: string, rest = '') => `${prefix}${name} ${system}${rest === '' ? '' : ` ${rest}`}`
+
+ if (!done('preflight') && !done('assess')) {
+ return { text: cmd('preflight'), isByHand: false, reason: 'check the environment before analysis' }
+ }
+
+ if (!done('assess')) {
+ return { text: cmd('assess'), isByHand: false, reason: 'inventory and complexity come first' }
+ }
+
+ if (!done('map')) {
+ return { text: cmd('map'), isByHand: false, reason: 'the brief and the rules both read the topology' }
+ }
+
+ if (!done('rules')) {
+ return { text: cmd('extract-rules'), isByHand: false, reason: 'the behavior contract comes from the rules' }
+ }
+
+ if (!done('brief') || brief === null) {
+ return { text: cmd('brief'), isByHand: false, reason: 'discovery is complete; plan the phases' }
+ }
+
+ if (!brief.approval.isSigned) {
+ return {
+ text: 'approve the brief: tell Claude which phases you approve',
+ isByHand: true,
+ reason: 'execution commands treat an unapproved brief as not approved',
+ }
+ }
+
+ const target = brief.target !== undefined ? slugOf(brief.target) : ''
+
+ for (const phase of approvedPhases(brief)) {
+ const open = phase.modules.find(id => {
+ const module = byNode.get(id)
+
+ return module === undefined || !isDone(module)
+ })
+
+ if (open !== undefined) {
+ return {
+ text: cmd('transform', `${open}${target === '' ? '' : ` ${target}`}`),
+ isByHand: false,
+ reason: `Phase ${phase.number} names ${open} and it is not reviewed yet`,
+ }
+ }
+
+ if (phase.modules.length === 0) {
+ return {
+ text: `pick Phase ${phase.number}'s first module and run ${prefix}transform ${system} <module>${target === '' ? '' : ` ${target}`}`,
+ isByHand: true,
+ reason: `Phase ${phase.number} names no module the map knows`,
+ }
+ }
+ }
+
+ return {
+ text: cmd('status'),
+ isByHand: false,
+ reason:
+ brief.approval.covers === 'full'
+ ? 'every approved phase is reviewed'
+ : 'Phase 1 is reviewed; its retrospective revises the brief before Phase 2 is approved',
+ }
+}
+
+/** The uplift command needs both versions, which only a person knows: the hint is by hand. */
+function nextOfUplift(prefix: string, system: string, stages: Stage[]): NextStep {
+ const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true
+ const command = `${prefix}uplift ${system} <from> <to>`
+
+ if (!done('deltas')) {
+ return { text: command, isByHand: true, reason: 'the delta catalog comes first: what the target version breaks here' }
+ }
+
+ if (!done('baseline')) {
+ return { text: command, isByHand: true, reason: 'record the baseline before any module is migrated: it is the equivalence target' }
+ }
+
+ if (!done('pilot')) {
+ return { text: command, isByHand: true, reason: 'migrate one representative module and write the playbook before the rest' }
+ }
+
+ if (!done('verify')) {
+ return { text: command, isByHand: true, reason: 'migrate the rest in batches by the playbook, then run the dual-run diff' }
+ }
+
+ return { text: `${prefix}status ${system}`, isByHand: false, reason: 'every uplift artifact is written; status checks what is stale' }
+}
+
+function nextOfReimagine(prefix: string, system: string, stages: Stage[]): NextStep {
+ const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true
+ const command = `${prefix}reimagine ${system} <vision>`
+
+ if (!done('spec')) {
+ return { text: command, isByHand: true, reason: 'the spec is mined from the legacy code first' }
+ }
+
+ if (!done('design')) {
+ return { text: command, isByHand: true, reason: 'the target architecture is designed and reviewed against the spec' }
+ }
+
+ if (!done('scaffold')) {
+ return { text: command, isByHand: true, reason: 'scaffold each service from the approved architecture' }
+ }
+
+ return { text: `${prefix}status ${system}`, isByHand: false, reason: 'the services are scaffolded; status checks what is stale' }
+}
+
+export type ReadOptions = {
+ /** The system to read; the first one found when absent or unknown. */
+ system?: string
+ /** What a command is written with, up to its verb (`/code-modernization:modernize-`). */
+ commandPrefix: string
+ nowMs: number
+ /** The read-only tree holding the systems, relative to the workspace; `legacy` when absent. */
+ legacyDir?: string
+ /** Which way to follow the system; `auto` when absent: whichever one's artifacts are newest. */
+ track?: TrackKey | 'auto'
+ /** Units of an uplift's working copy that were written during this session: they count as changed even when the file kept its size. */
+ writtenUnits?: ReadonlySet<string>
+ /** How long a listing of the working copy is reused, in milliseconds; 15 seconds when absent. */
+ changedTtlMs?: number
+ /** Test totals read off commands this session, by module path, for modules that left no report file. */
+ observed?: ReadonlyMap<string, TestTotals>
+}
+
+const newest = (...times: (number | null)[]): number | null => {
+ const known = times.filter((time): time is number => time !== null)
+
+ return known.length === 0 ? null : Math.max(...known)
+}
+
+/** The files of an uplift's working copy and their sizes, reused for a short while so an idle pane does not walk the tree again and again. */
+async function workingSizesOf(
+ fs: ReaderFs,
+ cache: ReaderCache,
+ root: string,
+ nowMs: number,
+ ttlMs: number,
+): Promise<Map<string, number> | null> {
+ const key = `changed:${root}`
+ const hit = cache.get(key)
+
+ if (hit !== undefined && nowMs - hit.mtimeMs < ttlMs) {
+ return hit.value as Map<string, number> | null
+ }
+
+ const value = await sourceSizes(fs, root)
+
+ cache.set(key, { mtimeMs: nowMs, value })
+
+ return value
+}
+
+/** The estate to draw: the map's modules, or what the legacy tree holds. Read once per system, then kept. */
+async function estateOf(
+ fs: ReaderFs,
+ cache: ReaderCache,
+ track: TrackKey,
+ topology: Topology | null,
+ legacyRoot: string,
+ system: string,
+): Promise<EstateModel | null> {
+ if (topology !== null && track !== 'uplift') {
+ return estateOfTopology(topology, 0)
+ }
+
+ const key = `estate:${legacyRoot}`
+ const at = (await mtimeOrNull(fs, legacyRoot)) ?? 0
+ const hit = cache.get(key)
+
+ if (hit !== undefined && hit.mtimeMs === at) {
+ return hit.value as EstateModel | null
+ }
+
+ const found = await discoverEstate(fs, legacyRoot, system)
+
+ cache.set(key, { mtimeMs: at, value: found })
+
+ return found ?? (topology !== null ? estateOfTopology(topology, 0) : null)
+}
+
+/** Reads one system's state. Null when the workspace holds no system. */
+export async function readSnapshot(
+ fs: ReaderFs,
+ cache: ReaderCache,
+ options: ReadOptions,
+): Promise<Snapshot | null> {
+ const legacyDir = options.legacyDir ?? 'legacy'
+ const systems = await systemsOf(fs, legacyDir)
+
+ const system =
+ options.system !== undefined && systems.includes(options.system)
+ ? options.system
+ : systems[0]
+
+ if (system === undefined) {
+ return null
+ }
+
+ const dir = join('analysis', system)
+ const legacyRoot = join(legacyDir, system)
+ const transformRoot = join('modernized', system)
+ const upliftRoot = join('modernized', `${system}-uplifted`)
+ const reimagineRoot = join('modernized', `${system}-reimagined`)
+ const observed = options.observed ?? new Map<string, TestTotals>()
+
+ const [topo, rules, catalog, baseline, reviewsRaw, findingsHead, marks] = await Promise.all([
+ cached(fs, cache, join(dir, STAGE_FILES.map), parseTopology),
+ cached(fs, cache, join(dir, STAGE_FILES.rules), parseRules),
+ cached(fs, cache, join(dir, STAGE_FILES.deltas), parseCatalog),
+ cached(fs, cache, join(dir, STAGE_FILES.baseline), parseBaseline),
+ readOrNull(fs, join(dir, REVIEWS_FILE)),
+ readOrNull(fs, join(dir, STAGE_FILES.harden)),
+ Promise.all(
+ [
+ mtimeOrNull(fs, dir),
+ mtimeOrNull(fs, join(dir, STAGE_FILES.preflight)),
+ mtimeOrNull(fs, join(dir, STAGE_FILES.assess)),
+ mtimeOrNull(fs, join(dir, STAGE_FILES.pilot)),
+ mtimeOrNull(fs, join(upliftRoot, 'UPLIFT_NOTES.md')),
+ mtimeOrNull(fs, upliftRoot),
+ mtimeOrNull(fs, join(dir, STAGE_FILES.spec)),
+ mtimeOrNull(fs, join(dir, STAGE_FILES.design)),
+ mtimeOrNull(fs, reimagineRoot),
+ mtimeOrNull(fs, transformRoot),
+ ],
+ ),
+ ])
+
+ const [analysisAt, preflightAt, assessAt, playbookAt, upliftNotesAt, upliftCopyAt, specAt, designAt, reimagineDirAt, transformDirAt] = marks
+
+ const topology = topo.value
+ const moduleIds = topology?.modules.map(node => node.id) ?? []
+
+ const brief = await cached(fs, cache, join(dir, STAGE_FILES.brief), text =>
+ parseBrief(text, moduleIds),
+ )
+
+ // A brief parsed before the map existed named no modules: parse it again.
+ if (
+ brief.value !== null &&
+ moduleIds.length > 0 &&
+ brief.value.phases.length > 0 &&
+ brief.value.phases.every(phase => phase.modules.length === 0)
+ ) {
+ const text = await readOrNull(fs, join(dir, STAGE_FILES.brief))
+
+ if (text !== null) {
+ brief.value = parseBrief(text, moduleIds)
+ cache.set(join(dir, STAGE_FILES.brief), { mtimeMs: brief.mtimeMs ?? 0, value: brief.value })
+ }
+ }
+
+ let reviews: ReviewLedger = {}
+
+ if (reviewsRaw !== null) {
+ try {
+ const parsed = JSON.parse(reviewsRaw) as { reviews?: ReviewLedger }
+
+ reviews = parsed.reviews ?? {}
+ } catch {
+ reviews = {}
+ }
+ }
+
+ const isScan = findingsHead !== null && /generated-by:\s*modernize-harden/.test(findingsHead.split('\n')[0] ?? '')
+
+ const transformed = await readModernizedIn(fs, transformRoot, observed)
+
+ const track = pickTrack(options.track ?? 'auto', {
+ transformAt: newest(transformDirAt, ...transformed.map(module => module.mtimeMs)),
+ // A baseline says nothing of the track: a rewrite records one too, for the legacy behavior it must keep.
+ upliftAt: newest(catalog.mtimeMs, playbookAt, upliftNotesAt, upliftCopyAt),
+ reimagineAt: newest(specAt, designAt, reimagineDirAt),
+ })
+
+ const estate = await estateOf(fs, cache, track, topology, legacyRoot, system)
+
+ let modules: ModernizedModule[] = []
+ const byNode = new Map<string, ModernizedModule>()
+ const extras: ModernizedModule[] = []
+ let uplift: UpliftFacts | null = null
+
+ if (track === 'uplift') {
+ const hasCopy = upliftCopyAt !== null
+ const legacySizes = estate?.isPartial === false ? estate.fileSizes : undefined
+ const workingSizes = hasCopy && legacySizes !== undefined ? await workingSizesOf(fs, cache, upliftRoot, options.nowMs, options.changedTtlMs ?? 15_000) : null
+ const changedPaths = legacySizes !== undefined && workingSizes !== null ? changedPathsOf(legacySizes, workingSizes) : null
+ const changed = estate !== null && changedPaths !== null ? changedUnitsOf(estate, changedPaths) : new Set<string>()
+
+ for (const id of options.writtenUnits ?? []) {
+ changed.add(id)
+ }
+
+ const pairs =
+ estate !== null && hasCopy
+ ? await readUpliftUnits(fs, upliftRoot, estate, changed, baseline.value, observed)
+ : []
+
+ modules = pairs.map(pair => pair.module)
+
+ for (const pair of pairs) {
+ byNode.set(pair.unit.id, pair.module)
+ }
+
+ uplift = {
+ catalog: catalog.value,
+ baseline: baseline.value,
+ hasPlaybook: playbookAt !== null,
+ hasNotes: upliftNotesAt !== null,
+ hasCopy,
+ isChangeKnown: changedPaths !== null,
+ }
+ } else {
+ modules = track === 'reimagine' ? await readModernizedIn(fs, reimagineRoot, observed) : transformed
+
+ if (track === 'transform') {
+ const byKey = new Map<string, EstateUnit>()
+
+ for (const unit of estate?.units ?? []) {
+ for (const key of keysOfUnit(unit)) {
+ byKey.set(keyOf(key), unit)
+ }
+ }
+
+ for (const module of modules) {
+ const unit = byKey.get(keyOf(module.dir))
+
+ if (unit !== undefined) {
+ byNode.set(unit.id, module)
+ } else {
+ extras.push(module)
+ }
+ }
+ } else {
+ extras.push(...modules)
+ }
+ }
+
+ const snapshotFacts = { track, uplift }
+ const done = modules.filter(module => isUnitDone(snapshotFacts, module))
+
+ const green = modules.filter(
+ module => module.state === 'tests-green' || module.state === 'reviewed' || isUnitDone(snapshotFacts, module),
+ )
+
+ const passing = green.reduce(
+ (sum, module) => sum + Math.max(0, (module.tests?.tests ?? 0) - (module.tests?.failures ?? 0) - (module.tests?.errors ?? 0)),
+ 0,
+ )
+
+ const withFindings: Stage[] =
+ findingsHead !== null || track === 'transform'
+ ? [
+ {
+ key: 'harden',
+ label: STAGE_LABELS.harden,
+ // Any findings file counts. A harden marker on its first line says the command wrote it, and older or
+ // newer versions of the command may or may not stamp one, so its absence is not a reason to doubt the file.
+ isDone: findingsHead !== null,
+ mtimeMs: null,
+ },
+ ]
+ : []
+
+ const stages: Stage[] = [
+ ...(track === 'transform'
+ ? [
+ { key: 'preflight' as const, label: STAGE_LABELS.preflight, isDone: preflightAt !== null, mtimeMs: preflightAt },
+ { key: 'assess' as const, label: STAGE_LABELS.assess, isDone: assessAt !== null, mtimeMs: assessAt },
+ {
+ key: 'map' as const,
+ label: STAGE_LABELS.map,
+ isDone: topology !== null,
+ mtimeMs: topo.mtimeMs,
+ ...(topology !== null && { detail: `${topology.modules.length} modules` }),
+ },
+ {
+ key: 'rules' as const,
+ label: STAGE_LABELS.rules,
+ isDone: rules.value !== null && rules.value.rules.length > 0,
+ mtimeMs: rules.mtimeMs,
+ ...(rules.value !== null && { detail: `${rules.value.rules.length} rules` }),
+ },
+ {
+ key: 'brief' as const,
+ label: STAGE_LABELS.brief,
+ isDone: brief.value !== null,
+ mtimeMs: brief.mtimeMs,
+ ...(brief.value !== null && {
+ detail: brief.value.approval.isSigned ? 'approved' : 'unapproved',
+ }),
+ },
+ {
+ // Transform writes under modernized/, not analysis/: this stage is done once a module's tests are green.
+ key: 'transform' as const,
+ label: STAGE_LABELS.transform,
+ isDone: green.length > 0,
+ mtimeMs: null,
+ ...(modules.length > 0 && {
+ detail: green.length === 0 ? 'in progress' : passing > 0 ? `${passing} green` : `${green.length} module${green.length === 1 ? '' : 's'}`,
+ }),
+ },
+ ]
+ : track === 'uplift'
+ ? [
+ { key: 'preflight' as const, label: STAGE_LABELS.preflight, isDone: preflightAt !== null, mtimeMs: preflightAt },
+ {
+ key: 'deltas' as const,
+ label: STAGE_LABELS.deltas,
+ isDone: catalog.mtimeMs !== null,
+ mtimeMs: catalog.mtimeMs,
+ ...(catalog.value !== null && { detail: `${catalog.value.count} deltas` }),
+ },
+ {
+ key: 'baseline' as const,
+ label: STAGE_LABELS.baseline,
+ isDone: baseline.mtimeMs !== null,
+ mtimeMs: baseline.mtimeMs,
+ ...(baseline.value !== null && {
+ detail: baseline.value.isTargetOnly
+ ? 'target-only'
+ : baseline.value.results !== null
+ ? `${baseline.value.results.toLocaleString('en-US')} tests`
+ : undefined,
+ }),
+ },
+ { key: 'pilot' as const, label: STAGE_LABELS.pilot, isDone: playbookAt !== null, mtimeMs: playbookAt },
+ {
+ key: 'migrate' as const,
+ label: STAGE_LABELS.migrate,
+ isDone: modules.length > 0 && playbookAt !== null,
+ mtimeMs: null,
+ ...(modules.length > 0 && { detail: `${modules.length} module${modules.length === 1 ? '' : 's'}` }),
+ },
+ {
+ key: 'verify' as const,
+ label: STAGE_LABELS.verify,
+ isDone: upliftNotesAt !== null,
+ mtimeMs: upliftNotesAt,
+ ...(modules.length > 0 && { detail: `${done.length}/${modules.length} match` }),
+ },
+ ]
+ : [
+ { key: 'preflight' as const, label: STAGE_LABELS.preflight, isDone: preflightAt !== null, mtimeMs: preflightAt },
+ { key: 'spec' as const, label: STAGE_LABELS.spec, isDone: specAt !== null, mtimeMs: specAt },
+ { key: 'design' as const, label: STAGE_LABELS.design, isDone: designAt !== null, mtimeMs: designAt },
+ {
+ key: 'scaffold' as const,
+ label: STAGE_LABELS.scaffold,
+ isDone: modules.length > 0,
+ mtimeMs: null,
+ ...(modules.length > 0 && { detail: `${modules.length} service${modules.length === 1 ? '' : 's'}` }),
+ },
+ {
+ key: 'tests' as const,
+ label: STAGE_LABELS.tests,
+ isDone: modules.length > 0 && green.length === modules.length,
+ mtimeMs: null,
+ ...(modules.length > 0 && { detail: `${green.length}/${modules.length} green` }),
+ },
+ ]),
+ ...withFindings,
+ ]
+
+ const loc = (estate?.units ?? []).reduce((sum, unit) => sum + Math.max(1, unit.size), 0)
+
+ const locDone = (estate?.units ?? []).reduce((sum, unit) => {
+ const module = byNode.get(unit.id)
+
+ return module !== undefined && isUnitDone(snapshotFacts, module) ? sum + Math.max(1, unit.size) : sum
+ }, 0)
+
+ const attention: string[] = []
+
+ for (const module of modules) {
+ const row = track === 'uplift' ? (baseline.value?.rows.get(module.dir.toLowerCase()) ?? null) : null
+
+ if (module.state === 'tests-red' && module.tests !== null) {
+ const bad = module.tests.failures + module.tests.errors
+
+ attention.push(
+ track === 'uplift'
+ ? `${module.dir}: ${bad} failing, the baseline had ${row === null ? 0 : row.fail + row.error}`
+ : `${module.dir}: ${bad} of ${module.tests.tests} tests red`,
+ )
+ }
+
+ if (module.tests !== null && module.tests.reports > 0 && module.tests.tests === 0) {
+ attention.push(`${module.dir}: test reports exist but 0 cases executed`)
+ }
+
+ if (track === 'transform' && module.state === 'tests-green' && module.hasNotes && !module.hasReviewSection) {
+ attention.push(`${module.dir}: tests green; the notes do not show the architecture review`)
+ }
+ }
+
+ for (const extra of extras) {
+ if (track === 'transform' && extra.hasMain && (!extra.hasNotes || !extra.hasTests)) {
+ attention.push(
+ `${extra.dir}: shared code without ${[!extra.hasTests && 'tests', !extra.hasNotes && 'notes'].filter(Boolean).join(' or ')}; an unfinished transform`,
+ )
+ }
+
+ if (track === 'reimagine' && extra.hasMain && !extra.hasTests) {
+ attention.push(`${extra.dir}: scaffolded with no acceptance tests`)
+ }
+ }
+
+ if (track === 'uplift' && uplift !== null) {
+ if (uplift.baseline?.isTargetOnly === true) {
+ attention.push('the baseline is target-only: the source runtime could not run, so nothing is compared')
+ }
+
+ if (modules.length > 0 && !uplift.hasPlaybook) {
+ attention.push(`${modules.length} module${modules.length === 1 ? '' : 's'} touched before a playbook was written: pilot one first`)
+ }
+
+ if (modules.length > 0 && uplift.baseline === null) {
+ attention.push('modules touched before a baseline was recorded: nothing to compare them with')
+ }
+ }
+
+ if (
+ brief.mtimeMs !== null &&
+ rules.mtimeMs !== null &&
+ brief.mtimeMs < rules.mtimeMs
+ ) {
+ attention.push('the brief is older than the rule set it was planned from')
+ }
+
+ if (rules.value !== null) {
+ const pending = rules.value.rules.filter(
+ rule => rule.priority === 'P0' && needsReview(rule) && reviews[rule.id] === undefined,
+ ).length
+
+ const wrong = Object.values(reviews).filter(entry => entry.verdict === 'wrong').length
+
+ if (wrong > 0) {
+ attention.push(`${wrong} rule${wrong === 1 ? '' : 's'} marked wrong by a reviewer`)
+ }
+
+ if (pending > 0) {
+ attention.push(`${pending} P0 rule${pending === 1 ? '' : 's'} flagged for a person and not reviewed yet`)
+ }
+ }
+
+ const next: NextStep | null =
+ track === 'uplift'
+ ? nextOfUplift(options.commandPrefix, system, stages)
+ : track === 'reimagine'
+ ? nextOfReimagine(options.commandPrefix, system, stages)
+ : nextOfTransform(options.commandPrefix, system, stages, brief.value, byNode)
+
+ return {
+ system,
+ systems,
+ track,
+ hasAnalysis: analysisAt !== null,
+ stages,
+ estate,
+ topology,
+ rules: rules.value,
+ brief: brief.value,
+ modules,
+ byNode,
+ extras,
+ uplift,
+ findings: { exists: findingsHead !== null, isScan },
+ reviews,
+ percent: track === 'reimagine' || loc === 0 ? null : locDone / loc,
+ totals: {
+ modules: estate?.units.length ?? 0,
+ done: [...byNode.values()].filter(module => isUnitDone(snapshotFacts, module)).length,
+ loc,
+ locDone,
+ },
+ attention,
+ next,
+ readAtMs: options.nowMs,
+ }
+}
+
+/** One line for the status bar and the prompt's hidden context. */
+export function oneLineOf(snapshot: Snapshot): string {
+ const countable = snapshot.stages.filter(stage => stage.key !== 'harden' && stage.key !== 'transform')
+ const done = countable.filter(stage => stage.isDone).length
+
+ const parts =
+ snapshot.track === 'transform'
+ ? [`${snapshot.system}: discovery ${done}/5`]
+ : [`${snapshot.system}: ${TRACK_LABELS[snapshot.track]} ${done}/${countable.length} steps`]
+
+ if (snapshot.brief !== null) {
+ parts.push(snapshot.brief.approval.isSigned ? 'brief approved' : 'brief awaiting approval')
+ }
+
+ if (snapshot.totals.modules > 0 && snapshot.modules.length > 0) {
+ parts.push(
+ snapshot.track === 'reimagine'
+ ? `${snapshot.modules.length} services scaffolded`
+ : `${snapshot.totals.done}/${snapshot.totals.modules} modules ${snapshot.track === 'uplift' ? 'match the baseline' : 'reviewed'}`,
+ )
+ }
+
+ if (snapshot.attention.length > 0) {
+ parts.push(`${snapshot.attention.length} need attention`)
+ }
+
+ return parts.join(' · ')
+}
diff --git a/plugins/code-modernization/hooks/reader/rules.ts b/plugins/code-modernization/hooks/reader/rules.ts
new file mode 100644
index 00000000..dec397fd
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/rules.ts
@@ -0,0 +1,437 @@
+import { baseName } from '../paths'
+
+/**
+ * `analysis/<system>/BUSINESS_RULES.md`, read into rule cards.
+ *
+ * The file is written by an agent, and the agent's layout varies between models and
+ * runs. Three shapes are read: a card per rule under a `### <ID> · <title>` heading with
+ * a header line (`P0 · Calculation · confidence High · file:line`), the same heading with
+ * labelled fields (`**Category:**`, `**Priority:**`, `**Plain English:**`, a fenced
+ * Given/When/Then block, `**Edge cases handled:**`, `**Suspected defect:**`), and table
+ * rows for the lower priorities. Anything else is skipped, never thrown on.
+ */
+
+export type Citation = {
+ /** The path as written (`legacy/x/app/cbl/A.cbl`, `A.cbl`, `app/cpy/B.cpy`). */
+ path: string
+ /** Lower-cased base name, the key the x-ray matches a read file by. */
+ base: string
+ from: number
+ to: number
+}
+
+export type Rule = {
+ /** `P0-052`, or `R-<hash>` of the title for a table row that carries no id. */
+ id: string
+ title: string
+ /** `P0`, `P1`, `P2`, or `''` when the file does not say. */
+ priority: string
+ category?: string
+ confidence?: string
+ /** The rule's one-paragraph statement. */
+ statement: string
+ given?: string
+ when?: string
+ then?: string
+ edgeCases: string[]
+ defect?: string
+ sme?: string
+ /** Every `file:line` the card names; the first is the rule's own source. */
+ citations: Citation[]
+ /** The domain heading (`## D6 Interest & Fees`) the rule sits under. */
+ domain?: string
+}
+
+export type RuleSet = {
+ rules: Rule[]
+ byId: Map<string, Rule>
+ /** Lower-cased base name of a cited file, to the rules citing it. */
+ byFileBase: Map<string, Rule[]>
+}
+
+const CITATION =
+ /([A-Za-z0-9_][A-Za-z0-9_./-]*\.[A-Za-z][A-Za-z0-9]{0,7}):(\d+)(?:\s*[-–]\s*(\d+))?/g
+
+/** `P0-052`, `RULE-001`, `BR-D7-09`: letters, optional segments (a domain), then the number. */
+const ID = '[A-Z][A-Z0-9]*(?:-[A-Z][A-Z0-9]*)*-\\d+[a-z]?'
+
+const CARD_HEADING = new RegExp(`^#{3,4}\\s+(${ID})\\s*[·:\\-–—]\\s*(.+?)\\s*$`)
+
+/** Sections that describe or summarise the rules rather than hold them: a legend, a panel summary, appendices, provenance. */
+const SKIPPED_SECTION =
+ /\b(?:index|appendix|open questions|rejected|refuted|how to read|p0 confirmation|provenance)\b/i
+
+const DOMAIN_HEADING = /^##\s+(.+?)\s*$/
+
+const clean = (text: string) =>
+ text
+ .replace(/\*\*/g, '')
+ .replace(/<br\s*\/?>(\s*)/gi, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+
+/** Every `file:line[-line]` in `text`, in order, without duplicates. */
+export function citationsIn(text: string): Citation[] {
+ const seen = new Set<string>()
+ const out: Citation[] = []
+
+ for (const match of text.matchAll(CITATION)) {
+ const path = match[1] ?? ''
+ const from = Number(match[2])
+ const to = match[3] !== undefined ? Number(match[3]) : from
+ const key = `${path}:${from}-${to}`
+
+ if (path === '' || !Number.isFinite(from) || seen.has(key)) {
+ continue
+ }
+
+ seen.add(key)
+
+ out.push({
+ path,
+ base: baseName(path).toLowerCase(),
+ from,
+ to: Math.max(from, to),
+ })
+ }
+
+ return out
+}
+
+const priorityOf = (id: string, body: string): string => {
+ const fromId = /^(P\d)\b/.exec(id)?.[1]
+
+ if (fromId !== undefined) {
+ return fromId
+ }
+
+ const fromLabel = /\bPriority:?\s*\**\s*(P\d)\b/i.exec(body)?.[1]?.toUpperCase()
+
+ if (fromLabel !== undefined) {
+ return fromLabel
+ }
+
+ // `P0` · Calculation · confidence High · `app/cbl/A.cbl:10-20`
+ const header = body.split('\n').find(line => line.trim() !== '') ?? ''
+
+ return /^\s*`?\**(P\d)\**`?\s*(?:·|$)/.exec(header)?.[1] ?? ''
+}
+
+const gwtOf = (body: string, word: string): string | undefined => {
+ const match = new RegExp(
+ `\\*\\*${word}\\*\\*\\s*([\\s\\S]*?)(?=\\n[ \\t]*(?:[-*][ \\t]+)?>?\\s*\\*\\*(?:Given|When|Then)\\*\\*|\\n\\s*\\n|$)`,
+ 'i',
+ ).exec(body)
+
+ const text =
+ match?.[1] !== undefined
+ ? clean(match[1].replace(/\n>\s?/g, ' ')).replace(/^[—–:-]\s*/, '')
+ : ''
+
+ return text === '' ? undefined : text
+}
+
+const markedOf = (body: string, marker: RegExp): string | undefined => {
+ for (const line of body.split('\n')) {
+ if (marker.test(line)) {
+ const text = clean(line.replace(/^>\s*/, '').replace(marker, ''))
+ .replace(/^[—–-]\s*/, '')
+ .trim()
+
+ return text === '' ? undefined : text
+ }
+ }
+
+ return undefined
+}
+
+/** The text after `**Name:**` (or `**Name**:`) on its own line, for the labelled-fields layout. */
+const labelledOf = (body: string, name: string): string | undefined => {
+ const match = new RegExp(`^[ \\t]*\\*\\*${name}:?\\*\\*:?[ \\t]*(.*)$`, 'im').exec(body)
+ const text = match?.[1] !== undefined ? clean(match[1]) : ''
+
+ return text === '' ? undefined : text
+}
+
+/**
+ * Given/When/Then written as lines (`Given …`, `When …`, `Then …`, `And …`), usually inside a
+ * fenced block under `**Specification:**`. `And` lines continue the clause before them.
+ */
+const specOf = (body: string): { given?: string; when?: string; then?: string } => {
+ const block = /\*\*Specification:?\*\*:?\s*([\s\S]*?)(?=\n[ \t]*\*\*[A-Za-z][^*\n]*\*\*|$)/i.exec(body)?.[1] ?? ''
+ const clauses: Record<'given' | 'when' | 'then', string[]> = { given: [], when: [], then: [] }
+ let current: 'given' | 'when' | 'then' | undefined
+
+ for (const raw of block.split('\n')) {
+ const line = raw.trim().replace(/^```\w*$/, '').replace(/^[-*]\s+/, '')
+ const match = /^(Given|When|Then|And)\s+(.*)$/.exec(line)
+
+ if (match === null) {
+ continue
+ }
+
+ const word = match[1] ?? ''
+ const rest = clean(match[2] ?? '')
+
+ if (word === 'And') {
+ if (current !== undefined) {
+ clauses[current].push(rest)
+ }
+
+ continue
+ }
+
+ current = word.toLowerCase() as 'given' | 'when' | 'then'
+ clauses[current].push(rest)
+ }
+
+ const join = (parts: string[]) => (parts.length === 0 ? undefined : parts.join(' · '))
+
+ return { given: join(clauses.given), when: join(clauses.when), then: join(clauses.then) }
+}
+
+function cardOf(
+ id: string,
+ title: string,
+ body: string,
+ domain: string | undefined,
+): Rule {
+ const lines = body.split('\n')
+ const header = lines.find(line => line.trim() !== '') ?? ''
+ const headerParts = header.split('·').map(part => clean(part))
+
+ const category =
+ headerParts
+ .slice(1)
+ .find(part => part !== '' && !/confidence/i.test(part) && !/`/.test(part)) ?? labelledOf(body, 'Category')
+
+ const confidence =
+ /confidence\s*:?\s*\**\s*(High|Medium|Low)\b/i.exec(body)?.[1] ?? undefined
+
+ const statement =
+ labelledOf(body, 'Plain English') ??
+ lines
+ .slice(lines.indexOf(header) + 1)
+ .map(line => line.trim())
+ .find(
+ line =>
+ line !== '' &&
+ !line.startsWith('>') &&
+ !line.startsWith('|') &&
+ !line.startsWith('**') &&
+ !line.startsWith('-') &&
+ !line.startsWith('#') &&
+ !line.startsWith('`'),
+ ) ?? ''
+
+ const edgeStart = lines.findIndex(line => /^\*\*Edge cases?[^*]*\*\*/i.test(line.trim()))
+
+ const edgeCases: string[] = []
+
+ if (edgeStart >= 0) {
+ for (const line of lines.slice(edgeStart + 1)) {
+ const trimmed = line.trim()
+
+ if (trimmed.startsWith('- ')) {
+ edgeCases.push(clean(trimmed.slice(2)))
+ } else if (trimmed !== '' && edgeCases.length > 0) {
+ break
+ }
+ }
+ }
+
+ const spec = specOf(body)
+ const given = gwtOf(body, 'Given') ?? spec.given
+ const when = gwtOf(body, 'When') ?? spec.when
+ const then = gwtOf(body, 'Then') ?? spec.then
+ const defect = markedOf(body, /(?:⚠️?\s*\**\s*Suspected defect\**|^\s*\*\*Suspected defect:?\*\*:?)/i)
+
+ // `❓ **SME question** — …`, or `**Confidence:** Medium — SME question: …` on the confidence line.
+ const smeInline = /\bSME questions?\s*:\s*(.+)$/im.exec(body)?.[1]
+
+ const sme =
+ markedOf(body, /❓\s*\**\s*SME(?:\s+questions?)?\**/i) ??
+ (smeInline !== undefined && clean(smeInline) !== '' ? clean(smeInline) : undefined)
+
+ return {
+ id,
+ title: clean(title),
+ priority: priorityOf(id, body),
+ ...(category !== undefined && { category }),
+ ...(confidence !== undefined && {
+ confidence: confidence[0]?.toUpperCase() + confidence.slice(1).toLowerCase(),
+ }),
+ statement: clean(statement),
+ ...(given !== undefined && { given }),
+ ...(when !== undefined && { when }),
+ ...(then !== undefined && { then }),
+ edgeCases,
+ ...(defect !== undefined && { defect }),
+ ...(sme !== undefined && { sme }),
+ citations: citationsIn(body),
+ ...(domain !== undefined && { domain }),
+ }
+}
+
+/** A short stable id for a rule that carries none: a hash of its title, so a verdict survives the table being rewritten in another order. */
+export function idOfTitle(title: string): string {
+ let hash = 2166136261
+
+ for (const char of title.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()) {
+ hash = Math.imul(hash ^ char.charCodeAt(0), 16777619)
+ }
+
+ return `R-${(hash >>> 0).toString(16).padStart(8, '0').slice(0, 6)}`
+}
+
+function rowOf(
+ line: string,
+ domain: string | undefined,
+): Rule | null {
+ const cells = line
+ .split('|')
+ .slice(1, -1)
+ .map(cell => cell.trim())
+
+ const first = cells[0] ?? ''
+ const titleMatch = /\*\*(.+?)\*\*/.exec(first)
+
+ if (cells.length < 2 || titleMatch === null || /^-+$/.test(first)) {
+ return null
+ }
+
+ const title = clean(titleMatch[1] ?? '')
+
+ if (title === '' || /^rule$/i.test(title)) {
+ return null
+ }
+
+ const idInTitle = new RegExp(`^(${ID})\\b`).exec(title)?.[1]
+ const category = clean(first.replace(titleMatch[0], '').replace(/<br\s*\/?>/gi, ' '))
+ const gwt = cells[1] ?? ''
+ const part = (tag: string) =>
+ clean(new RegExp(`\\*\\*${tag}\\*\\*\\s*(.*?)(?=\\*\\*[GWT]\\*\\*|$)`).exec(gwt)?.[1] ?? '')
+
+ const given = part('G')
+ const when = part('W')
+ const then = part('T')
+ const flags = cells.slice(3).join(' ')
+ const priority = /\b(P\d)\b/.exec(`${flags} ${first}`)?.[1] ?? ''
+
+ return {
+ id: idInTitle ?? idOfTitle(title),
+ title,
+ priority,
+ ...(category !== '' && { category }),
+ statement: '',
+ ...(given !== '' && { given }),
+ ...(when !== '' && { when }),
+ ...(then !== '' && { then }),
+ edgeCases: [],
+ ...(/⚠|defect/i.test(flags) && { defect: clean(flags) }),
+ ...(/❓|SME/i.test(flags) && { sme: clean(flags) }),
+ citations: citationsIn(line),
+ ...(domain !== undefined && { domain }),
+ }
+}
+
+/** Parses BUSINESS_RULES.md. Never throws; an unreadable file is no rules. */
+export function parseRules(text: string): RuleSet {
+ const lines = text.split('\n')
+ const rules: Rule[] = []
+ let domain: string | undefined
+ /** Set by a top-level heading: `# P1 rules` gives its rows a priority, an index or appendix is skipped. */
+ let sectionPriority = ''
+ let isTopSkipped = false
+ let isSectionSkipped = false
+
+ let open: { id: string; title: string; start: number; domain: string | undefined } | null =
+ null
+
+ const close = (end: number) => {
+ if (open !== null) {
+ rules.push(
+ cardOf(open.id, open.title, lines.slice(open.start, end).join('\n'), open.domain),
+ )
+
+ open = null
+ }
+ }
+
+ lines.forEach((line, index) => {
+ const isSkipped = isTopSkipped || isSectionSkipped
+ const card = isSkipped ? null : CARD_HEADING.exec(line)
+
+ if (card !== null) {
+ close(index)
+ open = { id: card[1] ?? '', title: card[2] ?? '', start: index + 1, domain }
+
+ return
+ }
+
+ const top = /^#\s+(.+?)\s*$/.exec(line)
+
+ if (top !== null) {
+ close(index)
+ sectionPriority = /\b(P\d)\b/.exec(top[1] ?? '')?.[1] ?? ''
+ isTopSkipped = SKIPPED_SECTION.test(top[1] ?? '')
+ isSectionSkipped = false
+ domain = undefined
+
+ return
+ }
+
+ const heading = DOMAIN_HEADING.exec(line)
+
+ if (heading !== null && !line.startsWith('###')) {
+ close(index)
+ domain = clean(heading[1] ?? '')
+ isSectionSkipped = SKIPPED_SECTION.test(heading[1] ?? '')
+
+ return
+ }
+
+ if (/^#{1,4}\s/.test(line)) {
+ close(index)
+
+ return
+ }
+
+ if (open === null && !(isTopSkipped || isSectionSkipped) && line.startsWith('|')) {
+ const row = rowOf(line, domain)
+
+ if (row !== null) {
+ rules.push(row.priority === '' ? { ...row, priority: sectionPriority } : row)
+ }
+ }
+ })
+
+ close(lines.length)
+
+ const byId = new Map<string, Rule>()
+ const byFileBase = new Map<string, Rule[]>()
+
+ for (const rule of rules) {
+ if (!byId.has(rule.id)) {
+ byId.set(rule.id, rule)
+ }
+
+ for (const base of new Set(rule.citations.map(citation => citation.base))) {
+ const bucket = byFileBase.get(base) ?? []
+
+ bucket.push(rule)
+ byFileBase.set(base, bucket)
+ }
+ }
+
+ return { rules, byId, byFileBase }
+}
+
+/** The rules that need a person: a suspected defect, an SME note, or less than High confidence. */
+export function needsReview(rule: Rule): boolean {
+ return (
+ rule.sme !== undefined ||
+ rule.defect !== undefined ||
+ (rule.confidence !== undefined && rule.confidence !== 'High')
+ )
+}
diff --git a/plugins/code-modernization/hooks/reader/topology.ts b/plugins/code-modernization/hooks/reader/topology.ts
new file mode 100644
index 00000000..b0f5adb5
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/topology.ts
@@ -0,0 +1,243 @@
+import { baseName, norm } from '../paths'
+
+/**
+ * `analysis/<system>/topology.json`, read into the few shapes the live pane uses.
+ *
+ * The file is written by an agent, so every field is treated as optional and
+ * of unknown shape: anything that does not fit is dropped, never thrown on.
+ */
+
+export type TopoNode = {
+ id: string
+ name: string
+ /** `module`, `datastore`, `screen`, or whatever the map stage wrote. */
+ kind: string
+ /** Lines of code; 0 when the map gave none. */
+ loc: number
+ /** Source file relative to `legacy/<system>/`, when the node is one file. */
+ file?: string
+ /** The name of the domain (first ancestor of kind `domain`) it sits under. */
+ domain?: string
+ /** The language the map recorded for it, as written (`cobol`, `java`, `php`). */
+ language?: string
+}
+
+export type TopoEdge = { source: string; target: string; kind: string }
+
+export type TopoFlow = {
+ name: string
+ persona?: string
+ steps: { label: string; nodes: string[] }[]
+}
+
+export type Topology = {
+ system: string
+ nodes: TopoNode[]
+ /** Nodes that are code (`kind: module`, or any leaf with a file and loc). */
+ modules: TopoNode[]
+ domains: { name: string; modules: TopoNode[] }[]
+ edges: TopoEdge[]
+ entryPoints: Set<string>
+ deadEnds: Set<string>
+ flows: TopoFlow[]
+ byId: Map<string, TopoNode>
+ /** Lower-cased base name of a node's file, to the nodes that have it. */
+ byFileBase: Map<string, TopoNode[]>
+}
+
+const str = (value: unknown): string | undefined =>
+ typeof value === 'string' && value !== '' ? value : undefined
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+
+const list = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
+
+function walk(
+ raw: unknown,
+ domain: string | undefined,
+ out: TopoNode[],
+ depth: number,
+): void {
+ if (!isRecord(raw) || depth > 12) {
+ return
+ }
+
+ const id = str(raw.id) ?? str(raw.name)
+
+ if (id === undefined) {
+ return
+ }
+
+ const kind = str(raw.kind) ?? 'node'
+ const name = str(raw.name) ?? id
+ const children = list(raw.children)
+ const here = kind === 'domain' ? name : domain
+ const loc = typeof raw.loc === 'number' && raw.loc > 0 ? raw.loc : 0
+ const file = str(raw.file)
+ const language = str(raw.language)
+
+ if (children.length === 0 || kind === 'module') {
+ out.push({
+ id,
+ name,
+ kind,
+ loc,
+ ...(file !== undefined && { file: norm(file) }),
+ ...(here !== undefined && { domain: here }),
+ ...(language !== undefined && { language }),
+ })
+ }
+
+ for (const child of children) {
+ walk(child, here, out, depth + 1)
+ }
+}
+
+/** Parses topology.json; null when the text is not a usable topology. */
+export function parseTopology(text: string): Topology | null {
+ let raw: unknown
+
+ try {
+ raw = JSON.parse(text)
+ } catch {
+ return null
+ }
+
+ if (!isRecord(raw)) {
+ return null
+ }
+
+ const nodes: TopoNode[] = []
+
+ if (isRecord(raw.root)) {
+ walk(raw.root, undefined, nodes, 0)
+ }
+
+ for (const flat of list(raw.nodes)) {
+ walk(flat, undefined, nodes, 0)
+ }
+
+ if (nodes.length === 0) {
+ return null
+ }
+
+ const byId = new Map<string, TopoNode>()
+
+ for (const node of nodes) {
+ if (!byId.has(node.id)) {
+ byId.set(node.id, node)
+ }
+ }
+
+ const unique = [...byId.values()]
+
+ const modules = unique.filter(
+ node =>
+ node.kind === 'module' ||
+ (node.file !== undefined && node.loc > 0 && node.kind !== 'datastore'),
+ )
+
+ const byDomain = new Map<string, TopoNode[]>()
+
+ for (const node of modules) {
+ const key = node.domain ?? 'Other'
+ const bucket = byDomain.get(key) ?? []
+
+ bucket.push(node)
+ byDomain.set(key, bucket)
+ }
+
+ const byFileBase = new Map<string, TopoNode[]>()
+
+ for (const node of unique) {
+ if (node.file === undefined) {
+ continue
+ }
+
+ const key = baseName(node.file).toLowerCase()
+ const bucket = byFileBase.get(key) ?? []
+
+ bucket.push(node)
+ byFileBase.set(key, bucket)
+ }
+
+ const edges: TopoEdge[] = []
+
+ for (const edge of list(raw.edges)) {
+ if (!isRecord(edge)) {
+ continue
+ }
+
+ const source = str(edge.source) ?? str(edge.from)
+ const target = str(edge.target) ?? str(edge.to)
+
+ if (source !== undefined && target !== undefined) {
+ edges.push({ source, target, kind: str(edge.kind) ?? 'uses' })
+ }
+ }
+
+ const flows: TopoFlow[] = []
+
+ for (const flow of list(raw.flows)) {
+ if (!isRecord(flow)) {
+ continue
+ }
+
+ const name = str(flow.name)
+
+ if (name === undefined) {
+ continue
+ }
+
+ const persona = str(flow.persona)
+
+ flows.push({
+ name,
+ ...(persona !== undefined && { persona }),
+ steps: list(flow.steps)
+ .filter(isRecord)
+ .map(step => ({
+ label: str(step.label) ?? '',
+ nodes: list(step.nodes).filter(
+ (node): node is string => typeof node === 'string',
+ ),
+ })),
+ })
+ }
+
+ const ids = (value: unknown) =>
+ new Set(list(value).filter((id): id is string => typeof id === 'string'))
+
+ return {
+ system: str(raw.system) ?? '',
+ nodes: unique,
+ modules,
+ domains: [...byDomain.entries()].map(([name, members]) => ({
+ name,
+ modules: members,
+ })),
+ edges,
+ entryPoints: ids(raw.entryPoints),
+ deadEnds: ids(raw.deadEnds),
+ flows,
+ byId,
+ byFileBase,
+ }
+}
+
+/**
+ * The topology node a legacy file belongs to: by its path relative to
+ * `legacy/<system>/` when the map recorded one, else by base name alone.
+ */
+export function nodeOfFile(topo: Topology, fileRel: string): TopoNode | null {
+ const wanted = norm(fileRel)
+ const candidates = topo.byFileBase.get(baseName(wanted).toLowerCase()) ?? []
+
+ return (
+ candidates.find(node => node.file === wanted) ??
+ candidates.find(node => wanted.endsWith(node.file ?? '\0')) ??
+ candidates[0] ??
+ null
+ )
+}
diff --git a/plugins/code-modernization/hooks/reader/tracks.ts b/plugins/code-modernization/hooks/reader/tracks.ts
new file mode 100644
index 00000000..8ce75985
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/tracks.ts
@@ -0,0 +1,86 @@
+/**
+ * The three ways the plugin's commands work on a system, and what each leaves behind. The pane follows
+ * whichever one the artifacts on disk say is under way, so a same-stack version uplift or a greenfield
+ * rebuild is followed as closely as a rewrite is.
+ */
+
+export type TrackKey = 'transform' | 'uplift' | 'reimagine'
+
+export const TRACK_LABELS: Record<TrackKey, string> = {
+ transform: 'rewrite',
+ uplift: 'uplift',
+ reimagine: 'reimagine',
+}
+
+/** The unit of work in each track, as the pane names a list of them. */
+export const TRACK_UNITS: Record<TrackKey, { one: string; many: string }> = {
+ transform: { one: 'module', many: 'Modules' },
+ uplift: { one: 'module', many: 'Modules' },
+ reimagine: { one: 'service', many: 'Services' },
+}
+
+/** What each state of a unit of work is called, by track: the same colors, worded for what the work is. */
+export const STATE_WORDS_BY_TRACK: Record<TrackKey, Record<string, string>> = {
+ transform: {
+ untouched: 'untouched',
+ scaffolded: 'scaffolded',
+ 'tests-written': 'tests written',
+ 'tests-red': 'tests red',
+ 'tests-green': 'tests green',
+ reviewed: 'reviewed',
+ ported: 'ported',
+ switched: 'switched',
+ },
+ uplift: {
+ untouched: 'not migrated',
+ scaffolded: 'changed',
+ 'tests-written': 'tests written',
+ 'tests-red': 'worse than baseline',
+ 'tests-green': 'tests pass',
+ reviewed: 'matches baseline',
+ ported: 'ported',
+ switched: 'switched',
+ },
+ reimagine: {
+ untouched: 'legacy',
+ scaffolded: 'scaffolded',
+ 'tests-written': 'tests written',
+ 'tests-red': 'tests red',
+ 'tests-green': 'tests green',
+ reviewed: 'reviewed',
+ ported: 'ported',
+ switched: 'switched',
+ },
+}
+
+/** Times (ms) of the artifacts that mark each track as under way; null where the artifact is absent. */
+export type TrackFacts = {
+ transformAt: number | null
+ upliftAt: number | null
+ reimagineAt: number | null
+}
+
+/**
+ * The track under way: the one whose own artifacts were written last. The discovery artifacts (preflight,
+ * assess, map, rules, brief) feed all three and decide nothing. With no track's own artifacts a system
+ * is at the start of the rewrite path, which is where the plugin's commands begin.
+ */
+export function pickTrack(option: TrackKey | 'auto', facts: TrackFacts): TrackKey {
+ if (option !== 'auto') {
+ return option
+ }
+
+ const ranked = (
+ [
+ ['transform', facts.transformAt],
+ ['reimagine', facts.reimagineAt],
+ ['uplift', facts.upliftAt],
+ ] as const
+ ).filter((entry): entry is readonly [TrackKey, number] => entry[1] !== null)
+
+ if (ranked.length === 0) {
+ return 'transform'
+ }
+
+ return ranked.reduce((best, entry) => (entry[1] > best[1] ? entry : best))[0]
+}
diff --git a/plugins/code-modernization/hooks/reader/uplift.ts b/plugins/code-modernization/hooks/reader/uplift.ts
new file mode 100644
index 00000000..58e99060
--- /dev/null
+++ b/plugins/code-modernization/hooks/reader/uplift.ts
@@ -0,0 +1,238 @@
+import { join } from '../paths'
+import { unitOfPath, type EstateModel, type EstateUnit } from './estate-model'
+import type { ReaderFs } from './fs'
+import { readTests, stateOfUplift, type ModernizedModule, type ModuleState, type TestTotals } from './modernized'
+
+/**
+ * What a same-stack uplift leaves on disk, read without knowing the stack: the
+ * baseline's per-module results, the delta catalog's size, and which modules of the
+ * working copy differ from the legacy tree.
+ */
+
+export type BaselineRow = { pass: number; fail: number; error: number; skip: number }
+
+export type Baseline = {
+ /** The file says the source runtime could not run here, so there is no per-test table. */
+ isTargetOnly: boolean
+ /** Test results in all, from the table or the file's own totals line. */
+ results: number | null
+ /** One row per module, keyed by the module path lower-cased with no trailing slash. */
+ rows: Map<string, BaselineRow>
+}
+
+const int = (text: string | undefined): number => {
+ const value = Number((text ?? '').replace(/[,\s_]/g, ''))
+
+ return Number.isFinite(value) ? value : 0
+}
+
+const cellsOf = (line: string): string[] =>
+ line
+ .trim()
+ .replace(/^\|/, '')
+ .replace(/\|$/, '')
+ .split('|')
+ .map(cell => cell.trim())
+
+const keyOf = (text: string): string =>
+ text
+ .replace(/[`*]/g, '')
+ .replace(/^\.\//, '')
+ .replace(/\/+$/, '')
+ .trim()
+ .toLowerCase()
+
+/** The module key a working-copy path is looked up by. */
+export const baselineKeyOf = keyOf
+
+/** Reads a baseline file: any table with pass and fail columns gives a row per module. */
+export function parseBaseline(text: string): Baseline {
+ const rows = new Map<string, BaselineRow>()
+ const lines = text.split('\n')
+
+ for (let index = 0; index < lines.length - 1; index += 1) {
+ const head = lines[index] ?? ''
+
+ if (!head.trim().startsWith('|') || !/^\s*\|?\s*:?-{2,}/.test(lines[index + 1] ?? '')) {
+ continue
+ }
+
+ const names = cellsOf(head).map(name => name.replace(/[`*]/g, '').toLowerCase())
+ const passAt = names.findIndex(name => /^pass/.test(name))
+ const failAt = names.findIndex(name => /^fail/.test(name))
+
+ if (passAt < 0 || failAt < 0) {
+ continue
+ }
+
+ const errorAt = names.findIndex(name => /^err/.test(name))
+ const skipAt = names.findIndex(name => /^(skip|ignor|pending)/.test(name))
+ const found = names.findIndex(name => /^(module|project|unit|suite|package|assembly|component|name)/.test(name))
+ const keyAt = found >= 0 ? found : 0
+
+ for (let row = index + 2; row < lines.length && (lines[row] ?? '').trim().startsWith('|'); row += 1) {
+ const cells = cellsOf(lines[row] ?? '')
+ const key = keyOf(cells[keyAt] ?? '')
+
+ if (key === '' || /^(total|totals|sum|all|overall)\b/.test(key)) {
+ continue
+ }
+
+ rows.set(key, {
+ pass: int(cells[passAt]),
+ fail: int(cells[failAt]),
+ error: errorAt >= 0 ? int(cells[errorAt]) : 0,
+ skip: skipAt >= 0 ? int(cells[skipAt]) : 0,
+ })
+ }
+ }
+
+ const totals = /([\d,]+)\s+test\s+results?/i.exec(text)?.[1] ?? /\btotal\b[^\n]{0,40}?([\d,]{2,})\s+tests?\b/i.exec(text)?.[1]
+ const summed = [...rows.values()].reduce((sum, row) => sum + row.pass + row.fail + row.error + row.skip, 0)
+
+ return {
+ isTargetOnly: /^\s*target-only:/im.test(text),
+ results: totals !== undefined ? int(totals) : rows.size > 0 ? summed : null,
+ rows,
+ }
+}
+
+export type Catalog = {
+ count: number
+ /** Lower-cased base name of a file the catalog cites, to the delta ids it is cited under. */
+ byFileBase: Map<string, string[]>
+}
+
+/**
+ * What the delta catalog holds: how many deltas (its own statement of the count, else its `D<n>` ids), and which
+ * delta each file it names is cited under: the delta a table row or a heading names last, before the file.
+ */
+export function parseCatalog(text: string): Catalog | null {
+ const stated = /\b(\d+)\s+(?:distinct\s+)?deltas\b/i.exec(text)?.[1]
+ const ids = new Set<string>()
+ const byFileBase = new Map<string, string[]>()
+ let current: string | null = null
+
+ for (const line of text.split('\n')) {
+ const opens = /^\s*(?:\|\s*\**|#{1,6}\s+\**)(D-?\d{1,3})\b/.exec(line)?.[1]
+
+ if (opens !== undefined) {
+ current = opens
+ ids.add(opens)
+ }
+
+ for (const found of line.matchAll(/D-?\d{1,3}\b/g)) {
+ ids.add(found[0])
+ }
+
+ if (current === null) {
+ continue
+ }
+
+ for (const cited of line.matchAll(/`([\w./@+-]+\.[A-Za-z0-9]{1,8})(?::\d+(?:[-–]\d+)?)?`/g)) {
+ const base = (cited[1] ?? '').split('/').at(-1)?.toLowerCase() ?? ''
+ const held = byFileBase.get(base) ?? []
+
+ if (base !== '' && !held.includes(current)) {
+ held.push(current)
+ byFileBase.set(base, held)
+ }
+ }
+ }
+
+ const count = stated !== undefined && int(stated) > 0 ? int(stated) : ids.size
+
+ return count > 0 ? { count, byFileBase } : null
+}
+
+/**
+ * The paths that differ between a tree and the working copy made from it: a file present in both with another size,
+ * one only the copy has, and one only the tree has. It compares names and sizes, so an edit that keeps a file's size
+ * exactly is not seen here; a test run in that module, or an edit made during the session, shows it.
+ */
+export function changedPathsOf(before: ReadonlyMap<string, number>, after: ReadonlyMap<string, number>): string[] {
+ const out: string[] = []
+
+ for (const [path, size] of after) {
+ if (before.get(path) !== size) {
+ out.push(path)
+ }
+ }
+
+ for (const path of before.keys()) {
+ if (!after.has(path)) {
+ out.push(path)
+ }
+ }
+
+ return out
+}
+
+/** The estate's unit ids that hold at least one of the changed paths. */
+export function changedUnitsOf(estate: EstateModel, changed: readonly string[]): Set<string> {
+ const ids = new Set<string>()
+
+ for (const path of changed) {
+ const unit = unitOfPath(estate, null, path)
+
+ if (unit !== null) {
+ ids.add(unit.id)
+ }
+ }
+
+ return ids
+}
+
+/**
+ * Each unit of the working copy that the uplift has touched or tested, with its state:
+ * changed, tested, matching the baseline, or worse than it. `observed` holds the totals of test
+ * runs seen this session, used where no report file was left.
+ */
+export async function readUpliftUnits(
+ fs: ReaderFs,
+ workingRoot: string,
+ estate: EstateModel,
+ changed: ReadonlySet<string>,
+ baseline: Baseline | null,
+ observed: ReadonlyMap<string, TestTotals>,
+): Promise<{ unit: EstateUnit; module: ModernizedModule }[]> {
+ const out: { unit: EstateUnit; module: ModernizedModule }[] = []
+
+ for (const unit of estate.units) {
+ if (unit.dir === undefined) {
+ if (changed.has(unit.id)) {
+ out.push({ unit, module: moduleOf(unit.name, join(workingRoot, unit.file ?? unit.id), null, 'scaffolded') })
+ }
+
+ continue
+ }
+
+ const path = unit.dir === '' ? workingRoot : join(workingRoot, unit.dir)
+ const tests = (await readTests(fs, path)) ?? observed.get(path) ?? null
+ const row = baseline?.rows.get(keyOf(unit.dir)) ?? null
+ const state = stateOfUplift(tests, row, changed.has(unit.id))
+
+ if (state !== 'untouched') {
+ out.push({ unit, module: moduleOf(unit.dir === '' ? unit.name : unit.dir, path, tests, state) })
+ }
+ }
+
+ return out
+}
+
+function moduleOf(dir: string, path: string, tests: TestTotals | null, state: ModuleState): ModernizedModule {
+ return {
+ dir,
+ path,
+ hasMain: true,
+ hasTests: tests !== null,
+ hasNotes: false,
+ hasReviewSection: false,
+ isPortedNotSwitched: false,
+ isSwitched: false,
+ followUps: 0,
+ tests,
+ state,
+ mtimeMs: 0,
+ }
+}
diff --git a/plugins/code-modernization/hooks/register.ts b/plugins/code-modernization/hooks/register.ts
new file mode 100644
index 00000000..09e5822e
--- /dev/null
+++ b/plugins/code-modernization/hooks/register.ts
@@ -0,0 +1,1256 @@
+import type { EngineInterface, On, PluginOptions, ResultOf } from 'claude-code'
+
+import { lineOf, missingPathOf, noteCall, noteDone, noteFailure, prune, subjectOf } from './fleet/fleet'
+import type { Host } from './host'
+import { paint, tilesOf, type TouchKind } from './map/estate'
+import { absOf, baseName, isUnder, join, norm, relTo } from './paths'
+import { keysOfUnit, unitOfPath } from './reader/estate-model'
+import { readOrNull } from './reader/fs'
+import type { TestTotals } from './reader/modernized'
+import { oneLineOf, readSnapshot, REVIEWS_FILE } from './reader/progress'
+import type { ReviewVerdict } from './reader/progress'
+import { nodeOfFile } from './reader/topology'
+import { decide, ledgerJson, ledgerMarkdown, nextUnreviewed, queueOf, undecide, type DeckScope } from './review/deck'
+import { signBrief } from './sign'
+import {
+ newActivity,
+ newState,
+ PANE_ID,
+ PLUGIN_NAME,
+ RASTER_KEY,
+ SIGN_ID,
+ type FinishedCall,
+ type State,
+} from './state'
+import { readTestRun, TEST_COMMAND } from './tests-run'
+import { deckView, signView } from './views/deck'
+import { headerRowsOf, paneView, planOf, showBar, type Kit } from './views/pane'
+import { xrayOf } from './xray/xray'
+
+const REFRESH_DEBOUNCE_MS = 450
+const FRAME_MS = 140
+const CLOCK_MS = 1000
+const POLL_MS = 20_000
+const WRITE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit'])
+const QUIET_TOOLS = new Set(['Read', 'Glob', 'Grep', 'LS', 'WebFetch', 'WebSearch', 'TodoWrite', 'ToolSearch'])
+const PARENT_TOOLS = new Set(['Agent', 'Task', 'Workflow'])
+const STEP = /\/(?:[\w-]+:)?(modernize-[a-z-]+)\b[^\n]*/
+
+const nowMs = (): number => Date.now()
+
+/** A cell count as the engine reports it, made safe to do layout arithmetic on. */
+const wholeOf = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0
+
+/**
+ * Binds a Host from `$`. Declared in this file, each member spelled
+ * `$.noun.event(...)`, so the engine reads what the module calls off its source.
+ */
+function hostOf($: EngineInterface): Host {
+ return {
+ fs: {
+ read: path => $.fs.read(path),
+ write: (path, text) => $.fs.write(path, text),
+ list: path => $.fs.list(path),
+ exists: path => $.fs.exists(path),
+ stat: path => $.fs.stat(path),
+ },
+ now: () => $.clock.now(),
+ after: (ms, fn) => $.clock.after(ms, fn),
+ every: (ms, fn) => $.clock.every(ms, fn),
+ storeGet: key => $.store.get(key),
+ storeSet: (key, value) => $.store.set(key, value),
+ invalidate: () => $.ui.invalidate('ui.render'),
+ blit: args => $.ui.blit(args),
+ status: text => $.ui.status(text),
+ toast: (text, timeoutMs) => $.ui.toast(text, timeoutMs !== undefined ? { timeoutMs } : undefined),
+ log: text => $.ui.log(text),
+ openPane: pane => $.ui.open(pane),
+ closePane: pane => $.ui.close(pane),
+ registerCommand: spec => $.command.register(spec),
+ fillPrompt: input => $.prompt.fill(input),
+ submitPrompt: input => $.prompt.submit(input),
+ abortTurn: turnId => $.turn.abort({ turnId }),
+ }
+}
+
+/**
+ * `fs` with every relative path rooted at `cwd`: the artifacts live under the
+ * session's working directory, wherever the process itself happens to stand.
+ */
+function rootedAt(fs: Host['fs'], cwd: string): Host['fs'] {
+ return {
+ read: path => fs.read(absOf(cwd, path)),
+ write: (path, text) => fs.write(absOf(cwd, path), text),
+ list: path => fs.list(absOf(cwd, path)),
+ exists: path => fs.exists(absOf(cwd, path)),
+ stat: path => fs.stat(absOf(cwd, path)),
+ }
+}
+
+/**
+ * Registers the plugin's live hooks: the pane and its estate map, x-ray
+ * reads, the rule review deck, the fleet view and the sign-off dialog.
+ * `session.start` binds the engine; every hook after
+ * it works over that binding and one state object.
+ *
+ * @param on the engine's registrar
+ * @param raw the plugin's options as the settings hold them
+ */
+export function register(on: On, raw: PluginOptions) {
+ const state: State = newState(raw)
+
+ // ---------------------------------------------------------------- reading
+
+ async function refresh(host: Host): Promise<void> {
+ if (state.isRefreshing) {
+ state.isRefreshQueued = true
+
+ return
+ }
+
+ state.isRefreshing = true
+
+ try {
+ const snapshot = await readSnapshot(host.fs, state.cache, {
+ ...((state.pickedSystem ?? state.options.system) !== '' && { system: state.pickedSystem ?? state.options.system }),
+ commandPrefix: state.options.commandPrefix,
+ legacyDir: state.options.legacyDir,
+ track: state.options.track,
+ writtenUnits: state.writtenUnits,
+ observed: state.observed,
+ nowMs: nowMs(),
+ })
+
+ // The pane opens by itself once there is modernization to show: the first artifact under analysis/,
+ // not only a legacy system that has not been touched.
+ const isFirstSight = snapshot !== null && snapshot.hasAnalysis && state.snapshot?.hasAnalysis !== true
+
+ state.snapshot = snapshot
+ state.readError = null
+
+ if (isFirstSight) {
+ maybeAutoOpen()
+ }
+
+ if (snapshot !== null) {
+ if (!state.deck.isOpen) {
+ state.deck.ledger = snapshot.reviews
+ }
+
+ // The pane says all of this already, and so does the bar that stands where it was while it is hidden. The
+ // pinned line is for a person who turned the pane off. A workspace that holds a legacy system and nothing
+ // yet under analysis/ has no modernization to report.
+ host.status(state.pane.isOpen || !snapshot.hasAnalysis || state.options.panel !== 'off' ? undefined : oneLineOf(snapshot))
+ }
+
+ if (state.estate !== null) {
+ state.estate = { ...state.estate, tiles: [] }
+ }
+ } catch (error) {
+ state.readError = error instanceof Error ? error.message : String(error)
+ } finally {
+ state.isRefreshing = false
+ host.invalidate()
+
+ if (state.isRefreshQueued) {
+ state.isRefreshQueued = false
+ scheduleRefresh(host)
+ }
+ }
+ }
+
+ function scheduleRefresh(host: Host): void {
+ state.timers.get('refresh')?.cancel()
+
+ state.timers.set(
+ 'refresh',
+ host.after(REFRESH_DEBOUNCE_MS, () => {
+ state.timers.delete('refresh')
+ void refresh(host)
+ }),
+ )
+ }
+
+ // ------------------------------------------------------------- animation
+
+ function frameOf(): { cells: string; isAnimating: boolean } | null {
+ const estate = state.estate
+
+ if (estate === null || state.snapshot === null) {
+ return null
+ }
+
+ const painted = paint(estate.tiles, estate.columns, estate.rows, state.touches, nowMs())
+
+ return { cells: painted.cells, isAnimating: painted.isAnimating }
+ }
+
+ function animate(host: Host): void {
+ if (state.timers.has('frames') || !state.pane.isOpen) {
+ return
+ }
+
+ state.timers.set(
+ 'frames',
+ host.every(FRAME_MS, () => {
+ const estate = state.estate
+ const frame = frameOf()
+
+ if (estate === null || frame === null || !state.pane.isOpen) {
+ state.timers.get('frames')?.cancel()
+ state.timers.delete('frames')
+
+ return
+ }
+
+ void host
+ .blit({
+ requestId: PANE_ID,
+ key: RASTER_KEY,
+ cells: frame.cells,
+ columns: estate.columns,
+ rows: estate.rows,
+ })
+ .then(result => {
+ // Said once: a refused repaint means the map is stale, which is worth knowing.
+ if (result.deny !== undefined && !state.timers.has('blit-refused')) {
+ state.timers.set('blit-refused', host.after(60_000, () => state.timers.delete('blit-refused')))
+ host.log(`estate map: repaint refused (${result.deny})`)
+ }
+ })
+ .catch(() => undefined)
+
+ if (!frame.isAnimating) {
+ state.timers.get('frames')?.cancel()
+ state.timers.delete('frames')
+ }
+ }),
+ )
+ }
+
+ function touch(host: Host, nodeId: string, kind: TouchKind): void {
+ const held = state.touches.get(nodeId)
+
+ // A write outranks a read that is still fading.
+ if (held !== undefined && held.kind === 'write' && kind === 'read' && nowMs() - held.atMs < 1200) {
+ return
+ }
+
+ state.touches.set(nodeId, { atMs: nowMs(), kind })
+ animate(host)
+ }
+
+ /** The estate unit ids a tool call's paths and command text name, with how each was touched. */
+ function nodesTouched(tool: string, args: Readonly<Record<string, unknown>>): { id: string; kind: TouchKind }[] {
+ const snapshot = state.snapshot
+ const estate = snapshot?.estate
+
+ if (snapshot === null || estate === null || estate === undefined) {
+ return []
+ }
+
+ const legacyRoot = join(state.options.legacyDir, snapshot.system)
+ const modernRoot = join('modernized', snapshot.system)
+ const upliftRoot = join('modernized', `${snapshot.system}-uplifted`)
+ const out = new Map<string, TouchKind>()
+ const kind: TouchKind = WRITE_TOOLS.has(tool) ? 'write' : 'read'
+
+ const take = (path: string, how: TouchKind) => {
+ const rel = relTo(state.cwd, path)
+
+ if (rel === null) {
+ return
+ }
+
+ if (isUnder(rel, legacyRoot) && rel !== legacyRoot) {
+ const unit = unitOfPath(estate, snapshot.topology, rel.slice(legacyRoot.length + 1))
+
+ if (unit !== null) {
+ out.set(unit.id, how)
+ }
+ } else if (isUnder(rel, upliftRoot) && rel !== upliftRoot) {
+ // An uplift's working copy has the legacy tree's own layout, so the same path names the same unit.
+ const unit = unitOfPath(estate, snapshot.topology, rel.slice(upliftRoot.length + 1))
+
+ if (unit !== null) {
+ out.set(unit.id, how)
+
+ // An edit that keeps a file's size is invisible to the size comparison; a write seen here is not.
+ if (how === 'write') {
+ state.writtenUnits.add(unit.id)
+ }
+ }
+ } else if (isUnder(rel, modernRoot) && rel !== modernRoot) {
+ const dir = (rel.slice(modernRoot.length + 1).split('/')[0] ?? '').toLowerCase()
+
+ const unit = estate.units.find(candidate => keysOfUnit(candidate).some(key => key.toLowerCase() === dir))
+
+ if (unit !== undefined) {
+ out.set(unit.id, how === 'read' ? 'read' : 'write')
+ }
+ }
+ }
+
+ for (const key of ['file_path', 'path', 'notebook_path']) {
+ const value = args[key]
+
+ if (typeof value === 'string') {
+ take(value, kind)
+ }
+ }
+
+ const command = typeof args.command === 'string' ? args.command : ''
+
+ if (command !== '') {
+ const paths = command.match(/(?:\.{0,2}\/)?[\w.@~+-]+(?:\/[\w.@~+-]+)+/g) ?? []
+ const writes = /(?:>|\btee\b|\bsed\s+-i|\bmv\b|\bcp\b|\brm\b|\bpatch\b|\bgit\s+(?:apply|checkout|restore))/.test(command)
+
+ for (const path of paths.slice(0, 24)) {
+ const rel = relTo(state.cwd, path) ?? ''
+
+ take(path, writes && (isUnder(rel, modernRoot) || isUnder(rel, upliftRoot)) ? 'write' : 'read')
+ }
+ }
+
+ return [...out.entries()].map(([id, how]) => ({ id, kind: how }))
+ }
+
+ /** The module a shell command's text names by path, of those the pane knows: the longest path wins. */
+ function moduleOfCommand(command: string): string | null {
+ const snapshot = state.snapshot
+
+ if (snapshot === null) {
+ return null
+ }
+
+ const upliftRoot = join('modernized', `${snapshot.system}-uplifted`)
+
+ const candidates = [
+ ...snapshot.modules.map(module => module.path),
+ ...(snapshot.track === 'uplift'
+ ? (snapshot.estate?.units ?? []).flatMap(unit => (unit.dir !== undefined && unit.dir !== '' ? [join(upliftRoot, unit.dir)] : []))
+ : []),
+ ].sort((a, b) => b.length - a.length)
+
+ const escaped = (path: string) => path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+
+ return (
+ candidates.find(path => new RegExp(`(?:^|[\\s'"=:@])(?:\\./)?${escaped(path)}(?=[\\s/'"]|$)`).test(command)) ?? null
+ )
+ }
+
+ // ------------------------------------------------------------------ deck
+
+ async function openDeck(host: Host, scope: DeckScope, filter: string): Promise<string> {
+ const snapshot = state.snapshot
+
+ if (snapshot === null || snapshot.rules === null) {
+ return 'No BUSINESS_RULES.md to review yet. Run the extract-rules command first.'
+ }
+
+ const queue = queueOf(snapshot.rules, scope, filter)
+
+ state.deck = {
+ isOpen: true,
+ scope,
+ filter,
+ queue,
+ ledger: snapshot.reviews,
+ index: nextUnreviewed(queue, snapshot.reviews, 0),
+ source: null,
+ isSourceShown: false,
+ }
+
+ // The deck draws in the band above the prompt: nothing to open, only to draw.
+ host.invalidate()
+
+ return queue.length === 0
+ ? 'Nothing to review under that scope.'
+ : `Reviewing ${queue.length} rule${queue.length === 1 ? '' : 's'}.`
+ }
+
+ async function saveLedger(host: Host): Promise<void> {
+ const system = state.snapshot?.system
+
+ if (system === undefined) {
+ return
+ }
+
+ await host.fs.write(join('analysis', system, REVIEWS_FILE), ledgerJson(system, state.deck.ledger))
+ await host.fs.write(join('analysis', system, 'RULE_REVIEWS.md'), ledgerMarkdown(system, state.deck.ledger))
+ scheduleRefresh(host)
+ }
+
+ async function loadSource(host: Host): Promise<void> {
+ const rule = state.deck.queue[state.deck.index]
+ const snapshot = state.snapshot
+ const citation = rule?.citations[0]
+
+ if (rule === undefined || snapshot === null || citation === undefined) {
+ return
+ }
+
+ const legacyRoot = join(state.options.legacyDir, snapshot.system)
+ const written = norm(citation.path)
+ const viaMap = snapshot.topology !== null ? nodeOfFile(snapshot.topology, written)?.file : undefined
+
+ const candidates = [
+ written,
+ join(legacyRoot, written),
+ ...(viaMap !== undefined ? [join(legacyRoot, viaMap)] : []),
+ ]
+
+ for (const path of candidates) {
+ const text = await readOrNull(host.fs, path)
+
+ if (text === null) {
+ continue
+ }
+
+ const lines = text.split('\n')
+ // From the cited line itself: in a short band every row of lead-in costs a row of the rule's own code.
+ const from = Math.max(1, citation.from)
+ const to = Math.min(lines.length, Math.max(citation.to + 2, from + 11), from + 39)
+
+ state.deck.source = {
+ ruleId: rule.id,
+ path,
+ startLine: from,
+ text: lines
+ .slice(from - 1, to)
+ .join('\n')
+ .replace(/[^\x09\x0a\x20-\x7e -￿]/g, ' ')
+ .slice(0, 9000),
+ }
+
+ return
+ }
+
+ state.deck.source = { ruleId: rule.id, path: written, startLine: citation.from, text: '(source file not found)' }
+ }
+
+ const deckActionsOf = (host: Host) => ({
+ decide: (verdict: ReviewVerdict) => {
+ const rule = state.deck.queue[state.deck.index]
+
+ if (rule === undefined) {
+ return
+ }
+
+ state.deck.ledger = decide(state.deck.ledger, rule, verdict, new Date(nowMs()).toISOString())
+ state.deck.index = nextUnreviewed(state.deck.queue, state.deck.ledger, state.deck.index + 1)
+ state.deck.isSourceShown = false
+ void saveLedger(host).catch(() => undefined)
+ host.invalidate()
+ },
+ undo: () => {
+ const rule = state.deck.queue[state.deck.index]
+
+ if (rule !== undefined) {
+ state.deck.ledger = undecide(state.deck.ledger, rule.id)
+ void saveLedger(host).catch(() => undefined)
+ host.invalidate()
+ }
+ },
+ prev: () => {
+ const size = state.deck.queue.length
+
+ state.deck.index = size === 0 ? 0 : (state.deck.index - 1 + size) % size
+ state.deck.isSourceShown = false
+ host.invalidate()
+ },
+ next: () => {
+ const size = state.deck.queue.length
+
+ state.deck.index = size === 0 ? 0 : (state.deck.index + 1) % size
+ state.deck.isSourceShown = false
+ host.invalidate()
+ },
+ source: () => {
+ state.deck.isSourceShown = !state.deck.isSourceShown
+
+ if (state.deck.isSourceShown) {
+ void loadSource(host).then(() => host.invalidate())
+ }
+
+ host.invalidate()
+ },
+ close: () => {
+ state.deck.isOpen = false
+ host.invalidate()
+ },
+ })
+
+ // ------------------------------------------------------------------ sign
+
+ async function openSign(host: Host, name = ''): Promise<string> {
+ const snapshot = state.snapshot
+
+ if (snapshot === null || snapshot.brief === null) {
+ return 'There is no brief to sign yet. Run the brief command first.'
+ }
+
+ if (snapshot.brief.approval.isSigned) {
+ return `The brief is already signed${snapshot.brief.approval.by !== undefined ? ` by ${snapshot.brief.approval.by}` : ''}.`
+ }
+
+ if (state.activity.isWorking) {
+ return 'Wait for the running turn to finish before signing.'
+ }
+
+ state.sign = { isOpen: true, name: name !== '' ? name : state.sign.name, covers: 'phase-1', error: null }
+
+ await host.openPane({
+ id: SIGN_ID,
+ title: 'Sign the brief',
+ focus: true,
+ closeOnEscape: true,
+ holdToasts: true,
+ rows: 12,
+ })
+
+ host.invalidate()
+
+ return ''
+ }
+
+ const signActionsOf = (host: Host) => ({
+ name: (value: string) => {
+ state.sign.name = value
+ },
+ covers: (value: 'phase-1' | 'full') => {
+ state.sign.covers = value
+ host.invalidate()
+ },
+ cancel: () => {
+ state.sign.isOpen = false
+ void host.closePane({ id: SIGN_ID }).catch(() => undefined)
+ },
+ sign: () => {
+ void (async () => {
+ const system = state.snapshot?.system
+ const name = state.sign.name.trim()
+
+ if (system === undefined) {
+ return
+ }
+
+ if (name === '') {
+ state.sign.error = 'Type the approver\'s name first.'
+ host.invalidate()
+
+ return
+ }
+
+ if (state.activity.isWorking) {
+ state.sign.error = 'A turn is running; sign once it has finished.'
+ host.invalidate()
+
+ return
+ }
+
+ const path = join('analysis', system, 'MODERNIZATION_BRIEF.md')
+ const text = await readOrNull(host.fs, path)
+ const signed = text !== null ? signBrief(text, name, new Date(nowMs()).toISOString().slice(0, 10), state.sign.covers) : null
+
+ if (signed === null) {
+ state.sign.error = 'The brief has no approval block to sign.'
+ host.invalidate()
+
+ return
+ }
+
+ await host.fs.write(path, signed)
+ state.sign.isOpen = false
+ await host.closePane({ id: SIGN_ID }).catch(() => undefined)
+ host.log(`brief signed by ${name} (${state.sign.covers === 'full' ? 'full plan' : 'Phase 1 only'})`)
+ await refresh(host)
+ })()
+ },
+ })
+
+ // ------------------------------------------------------------------ pane
+
+ async function openPane(host: Host): Promise<void> {
+ await host.openPane({ id: PANE_ID, title: 'Modernization' })
+ state.pane.isOpen = true
+ state.pane.isClosedByPerson = false
+ void refresh(host)
+ }
+
+ const paneActionsOf = (host: Host) => ({
+ system: () => {
+ const systems = state.snapshot?.systems ?? []
+ const current = state.snapshot?.system
+
+ if (systems.length < 2 || current === undefined) {
+ return
+ }
+
+ // A different system is a different estate, a different brief and a different set of lit tiles.
+ state.pickedSystem = systems[(systems.indexOf(current) + 1) % systems.length] ?? current
+ state.touches.clear()
+ state.writtenUnits.clear()
+ state.estate = null
+ void refresh(host)
+ },
+ next: () => {
+ const next = state.snapshot?.next
+
+ if (next === null || next === undefined || next.isByHand) {
+ return
+ }
+
+ void host
+ .fillPrompt({ text: next.text })
+ .then(result => {
+ if (!result.isFilled) {
+ host.toast(`Next: ${next.text}`, 8000)
+ }
+ })
+ .catch(() => undefined)
+ },
+ refresh: () => {
+ state.cache.clear()
+ void refresh(host)
+ },
+ review: () => {
+ void openDeck(host, 'flagged', '').catch(() => undefined)
+ },
+ sign: () => {
+ void openSign(host)
+ .then(message => {
+ if (message !== '') {
+ host.toast(message, 6000)
+ }
+ })
+ .catch(() => undefined)
+ },
+ close: () => {
+ state.pane.isOpen = false
+ state.pane.isClosedByPerson = true
+ void host.closePane({ id: PANE_ID }).catch(() => undefined)
+ },
+ stop: () => {
+ const turnId = state.activity.turnId
+
+ if (turnId !== null) {
+ void host.abortTurn(turnId).catch(() => undefined)
+ }
+ },
+ })
+
+ /**
+ * Opens the pane by itself once there is something to show, the person has not closed it, and
+ * the layout docks panes (the fullscreen layout). What the layout is comes from whichever render
+ * last said: not every build draws every site, so each render hook reports what it saw.
+ */
+ function maybeAutoOpen(viewport?: { columns?: number; isFullscreen?: boolean }): void {
+ state.viewport.columns = viewport?.columns ?? state.viewport.columns
+ state.viewport.isFullscreen = viewport?.isFullscreen ?? state.viewport.isFullscreen
+
+ const host = state.host
+
+ const shouldOpen =
+ host !== null &&
+ state.options.panel === 'auto' &&
+ !state.pane.isOpen &&
+ !state.pane.isClosedByPerson &&
+ !state.timers.has('auto-open') &&
+ state.snapshot !== null &&
+ state.snapshot.hasAnalysis &&
+ state.viewport.isFullscreen === true
+
+ if (shouldOpen && host !== null) {
+ // Opened from a timer: a render hook only draws.
+ state.timers.set(
+ 'auto-open',
+ host.after(50, () => {
+ state.timers.delete('auto-open')
+ void openPane(host).catch(() => undefined)
+ }),
+ )
+ }
+ }
+
+ // ------------------------------------------------------------- lifecycle
+
+ on('session.start', async ($, e, next) => {
+ const bound = hostOf($)
+ const host: Host = { ...bound, fs: rootedAt(bound.fs, e.cwd) }
+
+ state.host = host
+ state.cwd = e.cwd
+
+ for (const timer of state.timers.values()) {
+ timer.cancel()
+ }
+
+ state.timers.clear()
+
+ await Promise.all([
+ host
+ .registerCommand({
+ name: 'modernize-panel',
+ description: 'Show or hide the modernization progress pane and estate map',
+ argumentHint: '[open|close|json]',
+ immediate: true,
+ })
+ .catch(() => undefined),
+ host
+ .registerCommand({
+ name: 'modernize-review',
+ description: 'Review business rules one card at a time: confirm, wrong, or discuss',
+ argumentHint: '[flagged|p0|all] [filter]',
+ })
+ .catch(() => undefined),
+ host
+ .registerCommand({
+ name: 'modernize-sign',
+ description: 'Sign the modernization brief\'s approval block (a person\'s action)',
+ argumentHint: '[approver name, role]',
+ })
+ .catch(() => undefined),
+ ])
+
+ await refresh(host)
+
+ state.timers.set(
+ 'clock',
+ host.every(CLOCK_MS, () => {
+ if (state.pane.isOpen && (state.activity.isWorking || state.activity.running.size > 0)) {
+ host.invalidate()
+ }
+ }),
+ )
+
+ state.timers.set(
+ 'poll',
+ host.every(POLL_MS, () => {
+ if (state.pane.isOpen && !state.activity.isWorking) {
+ scheduleRefresh(host)
+ }
+ }),
+ )
+
+ return next(e)
+ })
+
+ on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
+ if (e.surface === 'terminal') {
+ maybeAutoOpen(e.viewport)
+ }
+
+ return next(e)
+ })
+
+ on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
+ const host = state.host
+
+ if (e.surface === 'terminal') {
+ // Not every build reports `isFullscreen`. The band's `maxRows` tells the same fact: under the
+ // fullscreen layout it is what the bottom slot has left; otherwise it is the terminal's height.
+ const rows = e.viewport?.rows
+ const inferred = rows !== undefined && e.props.maxRows > 0 ? e.props.maxRows < rows : undefined
+
+ maybeAutoOpen({
+ ...(e.viewport?.columns !== undefined && { columns: e.viewport.columns }),
+ ...((e.viewport?.isFullscreen ?? inferred) !== undefined && {
+ isFullscreen: e.viewport?.isFullscreen ?? inferred,
+ }),
+ })
+ }
+
+ // A survey holds the band first; the deck waits behind it.
+ if (host === null || e.props.hasSurvey || e.surface !== 'terminal') {
+ return next(e)
+ }
+
+ const table = $.ui.resolve(e)
+
+ // With no deck open, a hidden pane leaves one row and a button to bring it back: the pane is
+ // always one press away, on a terminal too narrow to open it unasked as well as on a wide one.
+ if (!state.deck.isOpen) {
+ const snapshot = state.snapshot
+
+ if (state.options.panel === 'off' || state.pane.isOpen || snapshot === null || !snapshot.hasAnalysis) {
+ return next(e)
+ }
+
+ return showBar(
+ { Box: table.Box, Text: table.Text, Button: table.Button },
+ oneLineOf(snapshot),
+ e.props.bodyColumns,
+ () => {
+ void openPane(host).catch(() => undefined)
+ },
+ )
+ }
+
+ return deckView(
+ { Box: table.Box, Text: table.Text, Button: table.Button, Code: table.Code },
+ state.deck,
+ e.props.bodyColumns,
+ e.props.maxRows,
+ deckActionsOf(host),
+ )
+ })
+
+ on('ui.render', { component: 'Pane' }, async ($, e, next) => {
+ const host = state.host
+
+ if (host === null || (e.requestId !== PANE_ID && e.requestId !== SIGN_ID)) {
+ return next(e)
+ }
+
+ const table = $.ui.resolve(e)
+ const kit: Kit = {
+ Box: table.Box,
+ Text: table.Text,
+ Button: table.Button,
+ ...('Raster' in table && { Raster: table.Raster }),
+ ...('Code' in table && { Code: table.Code }),
+ ...('Input' in table && { Input: table.Input }),
+ ...('Select' in table && { Select: table.Select }),
+ }
+
+ const columns = Math.max(24, wholeOf(e.props.bodyColumns) - 1)
+
+ if (e.requestId === SIGN_ID) {
+ return signView(
+ kit,
+ state.sign,
+ state.snapshot?.system ?? '',
+ state.snapshot?.brief?.openQuestions ?? 0,
+ columns,
+ signActionsOf(host),
+ )
+ }
+
+ // A squeezed pane (a dialog or another panel has its rows) can report a body of no rows at all.
+ const rows = wholeOf(e.props.scroll.bodyRows)
+
+ state.pane.isOpen = true
+ state.pane.bodyColumns = columns
+ state.pane.bodyRows = rows
+ state.pane.placement = e.props.placement
+
+ const snapshot = state.snapshot
+
+ const plan = planOf(rows, e.props.placement, {
+ phases: snapshot?.brief?.phases.length ?? 0,
+ modules: snapshot?.modules.length ?? 0,
+ attention:
+ (snapshot?.attention.length ?? 0) +
+ [...state.fleet.signatures.values()].filter(signature => signature.agents.size >= 3).length,
+ hasMap: snapshot !== null && snapshot.estate !== null && kit.Raster !== undefined,
+ headerRows: headerRowsOf(snapshot, columns),
+ })
+
+ let estate: { cells: string; columns: number; rows: number; tiles: State['estate'] extends infer T ? (T extends { tiles: infer U } ? U : never) : never } | null = null
+
+ // The plan sheds the map first when the body is too short; a Raster of no rows is refused.
+ if (snapshot !== null && snapshot.estate !== null && kit.Raster !== undefined && plan.estate >= 1 && columns >= 1) {
+ const mapRows = Math.min(256, plan.estate)
+ const held = state.estate
+
+ const tiles =
+ held !== null && held.columns === columns && held.rows === mapRows && held.tiles.length > 0
+ ? held.tiles
+ : tilesOf(snapshot, columns, mapRows)
+
+ state.estate = { tiles, columns, rows: mapRows, isMounted: true }
+
+ const painted = paint(tiles, columns, mapRows, state.touches, nowMs())
+
+ estate = { cells: painted.cells, columns, rows: mapRows, tiles }
+
+ if (painted.isAnimating) {
+ animate(host)
+ }
+ } else {
+ // No map drawn: nothing for the frame timer to repaint.
+ state.estate = null
+ }
+
+ return paneView(
+ kit,
+ state,
+ { columns, rows, placement: e.props.placement, nowMs: nowMs(), estate, plan },
+ paneActionsOf(host),
+ )
+ })
+
+ on('ui.close', async ($, e, next) => {
+ const result = await next(e)
+
+ if (result.deny !== undefined) {
+ return result
+ }
+
+ if (e.id === PANE_ID) {
+ state.pane.isOpen = false
+ state.pane.isClosedByPerson = e.origin.kind === 'person' || state.pane.isClosedByPerson
+
+ if (state.estate !== null) {
+ state.estate.isMounted = false
+ }
+ } else if (e.id === SIGN_ID) {
+ state.sign.isOpen = false
+ }
+
+ return result
+ })
+
+ // -------------------------------------------------------------- commands
+
+ on('command.run', { command: 'modernize-panel' }, async ($, e, next) => {
+ const host = state.host
+
+ if (host === null) {
+ return next(e)
+ }
+
+ state.viewport.isFullscreen = e.presentation.isFullscreen
+ state.viewport.columns = e.presentation.columns
+
+ const arg = e.args.trim().toLowerCase()
+
+ if (arg === 'json') {
+ await refresh(host)
+
+ const snapshot = state.snapshot
+
+ return {
+ text:
+ snapshot === null
+ ? 'no system under analysis/'
+ : `\`\`\`json\n${JSON.stringify(
+ {
+ system: snapshot.system,
+ stages: snapshot.stages.map(stage => ({ key: stage.key, done: stage.isDone, detail: stage.detail })),
+ brief: snapshot.brief && {
+ target: snapshot.brief.target,
+ approval: snapshot.brief.approval,
+ phases: snapshot.brief.phases.map(phase => ({
+ number: phase.number,
+ title: phase.title,
+ size: phase.size,
+ modules: phase.modules,
+ criteria: phase.criteria.length,
+ ticked: phase.criteria.filter(criterion => criterion.isTicked).length,
+ })),
+ },
+ modules: snapshot.modules.map(module => ({
+ dir: module.dir,
+ state: module.state,
+ tests: module.tests,
+ reviewDate: module.reviewDate,
+ })),
+ totals: snapshot.totals,
+ percent: snapshot.percent,
+ attention: snapshot.attention,
+ next: snapshot.next,
+ },
+ null,
+ 2,
+ )}\n\`\`\``,
+ }
+ }
+
+ const wantsClose = arg === 'close' || (arg === '' && state.pane.isOpen)
+
+ if (wantsClose) {
+ state.pane.isOpen = false
+ state.pane.isClosedByPerson = true
+ await host.closePane({ id: PANE_ID }).catch(() => undefined)
+
+ return { text: 'Modernization pane hidden' }
+ }
+
+ await openPane(host)
+
+ return { text: 'Modernization pane shown' }
+ })
+
+ on('command.run', { command: 'modernize-review' }, async ($, e, next) => {
+ const host = state.host
+
+ if (host === null) {
+ return next(e)
+ }
+
+ await refresh(host)
+
+ const words = e.args.trim().split(/\s+/).filter(word => word !== '')
+ const first = (words[0] ?? '').toLowerCase()
+ const scope: DeckScope = first === 'p0' || first === 'all' || first === 'flagged' ? first : 'flagged'
+ const filter = (scope === first ? words.slice(1) : words).join(' ')
+ const text = await openDeck(host, scope, filter)
+
+ return { text }
+ })
+
+ on('command.run', { command: 'modernize-sign' }, async ($, e, next) => {
+ const host = state.host
+
+ if (host === null) {
+ return next(e)
+ }
+
+ await refresh(host)
+
+ const message = await openSign(host, e.args.replace(/\s+/g, ' ').trim())
+
+ return message === '' ? {} : { text: message }
+ })
+
+ on('command.run', { command: ['clear', 'resume'] }, async ($, e, next) => {
+ const result = await next(e)
+
+ state.activity = newActivity()
+ state.touches.clear()
+ state.writtenUnits.clear()
+ state.lastContextLine = ''
+
+ return result
+ })
+
+ // ----------------------------------------------------------------- turns
+
+ on('prompt.submit', async ($, e, next) => {
+ const host = state.host
+ const step = STEP.exec(e.text)
+
+ if (step !== null) {
+ state.activity.step = step[0].trim().slice(0, 120)
+ }
+
+ const snapshot = state.snapshot
+
+ if (host === null || snapshot === null || e.origin.kind !== 'composer') {
+ return next(e)
+ }
+
+ const line = `${oneLineOf(snapshot)}${snapshot.next !== null ? ` · next: ${snapshot.next.text}` : ''}`
+
+ if (line === state.lastContextLine) {
+ return next(e)
+ }
+
+ state.lastContextLine = line
+
+ return next({
+ ...e,
+ context: [...(e.context ?? []), `Modernization state, read from the artifacts on disk: ${line}`],
+ })
+ })
+
+ on('turn.start', async ($, e, next) => {
+ const host = state.host
+
+ state.activity.isWorking = true
+ state.activity.turnId = e.turnId
+ state.activity.turnStartMs = nowMs()
+ state.activity.xraysThisTurn = 0
+
+ if (host !== null) {
+ host.invalidate()
+ }
+
+ return next(e)
+ })
+
+ on('turn.complete', async ($, e, next) => {
+ const host = state.host
+
+ if (e.agentId !== undefined) {
+ noteDone(state.fleet, e.agentId, nowMs())
+
+ return next(e)
+ }
+
+ state.activity.isWorking = false
+ state.activity.running.clear()
+
+ if (host !== null) {
+ if (state.activity.xraysThisTurn > 0) {
+ host.log(
+ `x-ray: ${state.activity.xraysThisTurn} legacy read${state.activity.xraysThisTurn === 1 ? '' : 's'} this turn carried what the analysis already knows`,
+ )
+ }
+
+ prune(state.fleet, nowMs())
+ scheduleRefresh(host)
+ }
+
+ return next(e)
+ })
+
+ // ------------------------------------------------------------ tool calls
+
+ on('tool.call', async ($, e, next) => {
+ const host = state.host
+
+ if (host === null) {
+ return next(e)
+ }
+
+ const args = e as unknown as Readonly<Record<string, unknown>>
+ const tool = e.tool
+ const agentId = e.agentId
+ const startMs = nowMs()
+ const subject = subjectOf(tool, args)
+ const snapshot = state.snapshot
+ const touched = nodesTouched(tool, args)
+
+ for (const entry of touched) {
+ touch(host, entry.id, entry.kind)
+ }
+
+ if (agentId !== undefined) {
+ const unit = touched[0] !== undefined ? snapshot?.estate?.units.find(candidate => candidate.id === touched[0]?.id)?.name : undefined
+
+ noteCall(state.fleet, agentId, tool, subject, startMs, unit)
+ }
+
+ state.activity.running.set(e.tool_use_id, {
+ id: e.tool_use_id,
+ tool,
+ subject,
+ startMs,
+ ...(agentId !== undefined && { agentId }),
+ })
+
+ const path = typeof args.file_path === 'string' ? args.file_path : typeof args.notebook_path === 'string' ? args.notebook_path : undefined
+ const rel = path !== undefined ? relTo(state.cwd, path) : null
+
+ let result: ResultOf['tool.call'] | undefined
+ let note: string | undefined
+
+ try {
+ result = await next(e)
+
+ if (result.deny !== undefined) {
+ return result
+ }
+
+ const extra: string[] = []
+ const isError = result.isError === true
+ const text = typeof result.text === 'string' ? result.text : ''
+
+ if (isError && agentId !== undefined) {
+ // What the call was aimed at is half of the cause: the path as the agent gave it, else the command's head.
+ const missing = missingPathOf(text)
+ const example = rel ?? (missing !== undefined ? (relTo(state.cwd, missing) ?? missing) : subject)
+ const signature = noteFailure(state.fleet, agentId, text, nowMs(), example)
+
+ if (signature !== null) {
+ const line = lineOf(signature)
+
+ host.toast(`Fleet: ${line}`, 9000)
+ host.log(`fleet: ${line}. One cause across agents usually belongs in the playbook, not in each agent.`)
+ }
+ }
+
+ if (tool === 'Read' && !isError && state.options.isXrayOn && snapshot !== null && rel !== null) {
+ const legacyRoot = join(state.options.legacyDir, snapshot.system)
+
+ if (isUnder(rel, legacyRoot) && rel !== legacyRoot) {
+ const xray = xrayOf(snapshot, {
+ fileRel: rel.slice(legacyRoot.length + 1),
+ ...(typeof args.offset === 'number' && { offset: args.offset }),
+ ...(typeof args.limit === 'number' && { limit: args.limit }),
+ })
+
+ if (xray !== null) {
+ extra.push(xray.text)
+ note = xray.summary.replace(/^x-ray [^:]+: /, 'x-ray ')
+ state.activity.xrays += 1
+
+ if (agentId === undefined) {
+ state.activity.xraysThisTurn += 1
+ }
+ }
+ }
+ }
+
+ // A citation in the analysis is relative to the legacy system's root, and an agent handed one
+ // often reads it from the workspace root. Say where the file is rather than let it search.
+ if (tool === 'Read' && isError && state.options.isXrayOn && snapshot !== null && rel !== null && /does not exist/i.test(text)) {
+ const legacyRoot = join(state.options.legacyDir, snapshot.system)
+ const candidate = join(legacyRoot, rel)
+
+ if (!isUnder(rel, state.options.legacyDir) && (await host.fs.exists(candidate))) {
+ extra.push(
+ `There is no ${rel} in the workspace, but ${candidate} exists. Paths cited under analysis/${snapshot.system}/ are relative to ${legacyRoot}/.`,
+ )
+ note = 'x-ray: the path exists under the legacy root'
+ }
+ }
+
+ if ((tool === 'Bash' || tool === 'PowerShell') && typeof args.command === 'string' && TEST_COMMAND.test(args.command)) {
+ const run = readTestRun(text)
+ const spent = nowMs() - startMs
+
+ if (agentId === undefined) {
+ state.activity.testMs += spent
+ state.activity.testRuns += 1
+ }
+
+ if (run !== null) {
+ note = `${run.executed} executed${run.skipped > 0 ? `, ${run.skipped} skipped` : ''}${run.failed > 0 ? `, ${run.failed} failed` : ''}`
+
+ // A run in a module's own directory is its result even where its runner left no report file behind.
+ const home = moduleOfCommand(args.command)
+
+ if (home !== null && run.executed + run.skipped > 0) {
+ const seen: TestTotals = { tests: run.executed + run.skipped, failures: run.failed, errors: 0, skipped: run.skipped, reports: 1 }
+
+ state.observed.set(home, seen)
+ }
+ }
+ }
+
+ return extra.length > 0 ? { ...result, context: [...(result.context ?? []), ...extra] } : result
+ } finally {
+ const ms = nowMs() - startMs
+
+ state.activity.running.delete(e.tool_use_id)
+
+ if (agentId === undefined) {
+ state.activity.toolMs += ms
+
+ const finished: FinishedCall = {
+ tool,
+ subject,
+ isOk: result !== undefined && result.deny === undefined && result.isError !== true,
+ ms,
+ ...(note !== undefined && { note }),
+ }
+
+ state.activity.finished = [...state.activity.finished, finished].slice(-8)
+ }
+
+ if (!QUIET_TOOLS.has(tool) || tool === 'Read') {
+ const wrote = WRITE_TOOLS.has(tool) || tool === 'Bash' || tool === 'PowerShell' || PARENT_TOOLS.has(tool)
+
+ if (wrote) {
+ // A write may have changed the working copy: the next read lists it afresh.
+ for (const key of [...state.cache.keys()]) {
+ if (key.startsWith('changed:')) {
+ state.cache.delete(key)
+ }
+ }
+
+ scheduleRefresh(host)
+ } else if (state.pane.isOpen) {
+ host.invalidate()
+ }
+ }
+ }
+ })
+}
+
+export { PLUGIN_NAME }
diff --git a/plugins/code-modernization/hooks/review/deck.ts b/plugins/code-modernization/hooks/review/deck.ts
new file mode 100644
index 00000000..823b7969
--- /dev/null
+++ b/plugins/code-modernization/hooks/review/deck.ts
@@ -0,0 +1,121 @@
+import type { ReviewLedger, ReviewVerdict } from '../reader/progress'
+import { needsReview, type Rule, type RuleSet } from '../reader/rules'
+
+/**
+ * The rule review deck: the rules a person should look at, in the order they
+ * matter, and the ledger of what that person decided. The ledger is a file
+ * of its own beside the rules (`RULE_REVIEWS.json`, with a readable
+ * `RULE_REVIEWS.md`), so the agent-written rules file is never edited.
+ */
+
+export type DeckScope = 'flagged' | 'p0' | 'all'
+
+const weight = (rule: Rule): number =>
+ (rule.priority === 'P0' ? 0 : rule.priority === 'P1' ? 10 : 20) +
+ (rule.sme !== undefined ? 0 : 2) +
+ (rule.defect !== undefined ? 0 : 1) +
+ (rule.confidence !== undefined && rule.confidence !== 'High' ? 0 : 1)
+
+/** The rules to review under `scope`, optionally only those citing a file or under a domain. */
+export function queueOf(rules: RuleSet, scope: DeckScope, filter = ''): Rule[] {
+ const wanted = filter.trim().toLowerCase()
+
+ return rules.rules
+ .filter(rule => {
+ if (scope === 'flagged' && !(rule.priority === 'P0' && needsReview(rule))) {
+ return false
+ }
+
+ if (scope === 'p0' && rule.priority !== 'P0') {
+ return false
+ }
+
+ if (wanted === '') {
+ return true
+ }
+
+ return (
+ rule.id.toLowerCase() === wanted ||
+ (rule.domain ?? '').toLowerCase().includes(wanted) ||
+ rule.title.toLowerCase().includes(wanted) ||
+ rule.citations.some(citation => citation.base.includes(wanted)) ||
+ // What the rule says and what is suspected of it: "truncat" finds the rounding defect whatever its title.
+ [rule.statement, rule.then, rule.defect].some(text => (text ?? '').toLowerCase().includes(wanted))
+ )
+ })
+ .map((rule, index) => ({ rule, index }))
+ .sort((a, b) => weight(a.rule) - weight(b.rule) || a.index - b.index)
+ .map(entry => entry.rule)
+}
+
+/** The first card at or after `from` that has no verdict yet; `from` itself when all have. */
+export function nextUnreviewed(queue: readonly Rule[], ledger: ReviewLedger, from: number): number {
+ for (let step = 0; step < queue.length; step += 1) {
+ const index = (from + step) % queue.length
+ const rule = queue[index]
+
+ if (rule !== undefined && ledger[rule.id] === undefined) {
+ return index
+ }
+ }
+
+ return Math.min(Math.max(0, from), Math.max(0, queue.length - 1))
+}
+
+/** `ledger` with `rule` decided. */
+export function decide(
+ ledger: ReviewLedger,
+ rule: Rule,
+ verdict: ReviewVerdict,
+ atIso: string,
+): ReviewLedger {
+ return { ...ledger, [rule.id]: { verdict, at: atIso, title: rule.title } }
+}
+
+/** `ledger` with `rule`'s verdict taken back. */
+export function undecide(ledger: ReviewLedger, ruleId: string): ReviewLedger {
+ const { [ruleId]: _gone, ...rest } = ledger
+
+ return rest
+}
+
+export const tallyOf = (queue: readonly Rule[], ledger: ReviewLedger) => ({
+ total: queue.length,
+ confirmed: queue.filter(rule => ledger[rule.id]?.verdict === 'confirmed').length,
+ wrong: queue.filter(rule => ledger[rule.id]?.verdict === 'wrong').length,
+ discuss: queue.filter(rule => ledger[rule.id]?.verdict === 'discuss').length,
+ open: queue.filter(rule => ledger[rule.id] === undefined).length,
+})
+
+/** The ledger as `RULE_REVIEWS.json` stores it. */
+export function ledgerJson(system: string, ledger: ReviewLedger): string {
+ return `${JSON.stringify({ system, version: 1, reviews: ledger }, null, 2)}\n`
+}
+
+const VERDICT_WORDS: Record<ReviewVerdict, string> = {
+ confirmed: 'Confirmed',
+ wrong: 'Wrong',
+ discuss: 'Needs discussion',
+}
+
+/** The ledger as a page a person or a model reads: `RULE_REVIEWS.md`. */
+export function ledgerMarkdown(system: string, ledger: ReviewLedger): string {
+ const entries = Object.entries(ledger).sort((a, b) => a[0].localeCompare(b[0], 'en', { numeric: true }))
+ const count = (verdict: ReviewVerdict) => entries.filter(([, entry]) => entry.verdict === verdict).length
+
+ return [
+ `# Rule reviews: ${system}`,
+ '',
+ `A person's verdict on individual business rules in \`BUSINESS_RULES.md\`, recorded from the review deck. ${count('confirmed')} confirmed, ${count('wrong')} wrong, ${count('discuss')} needing discussion.`,
+ '',
+ 'A rule marked **Wrong** or **Needs discussion** is not settled: do not build on it until it is resolved. A rule with no row here has not been reviewed.',
+ '',
+ '| Rule | Verdict | When | Title |',
+ '|---|---|---|---|',
+ ...entries.map(
+ ([id, entry]) =>
+ `| ${id} | ${VERDICT_WORDS[entry.verdict]} | ${entry.at.slice(0, 10)} | ${(entry.title ?? '').replace(/\|/g, '\\|')} |`,
+ ),
+ '',
+ ].join('\n')
+}
diff --git a/plugins/code-modernization/hooks/sign.ts b/plugins/code-modernization/hooks/sign.ts
new file mode 100644
index 00000000..3eeb6157
--- /dev/null
+++ b/plugins/code-modernization/hooks/sign.ts
@@ -0,0 +1,77 @@
+/**
+ * Writing a person's signature into the brief's approval block. The block
+ * comes in a few shapes (one line or several, checkboxes or a choice in
+ * words); each is filled in where it stands, and nothing else is touched.
+ */
+
+const COVER_WORDS = { 'phase-1': 'Phase 1 only', full: 'Full plan' } as const
+
+/**
+ * The brief with its approval block signed; null when it has no `Approved by:` line.
+ *
+ * @param text the brief
+ * @param name who approves
+ * @param date `YYYY-MM-DD`
+ * @param covers what the approval covers
+ */
+export function signBrief(
+ text: string,
+ name: string,
+ date: string,
+ covers: 'phase-1' | 'full',
+): string | null {
+ const lines = text.split('\n')
+ const at = lines.findIndex(line => /^\s*Approved by\s*:/i.test(line))
+
+ if (at < 0) {
+ return null
+ }
+
+ const who = name.replace(/\s+/g, ' ').trim()
+ const line = lines[at] ?? ''
+ const indent = /^\s*/.exec(line)?.[0] ?? ''
+ const hasInlineDate = /\bDate\s*:/i.test(line)
+
+ lines[at] = hasInlineDate ? `${indent}Approved by: ${who} Date: ${date}` : `${indent}Approved by: ${who}`
+
+ // The block ends at a blank-line-separated heading or code fence; look a short way down.
+ const end = Math.min(lines.length, at + 12)
+
+ if (!hasInlineDate) {
+ const dateAt = lines.findIndex((candidate, index) => index > at && index < end && /^\s*Date\s*:/i.test(candidate))
+
+ if (dateAt >= 0) {
+ const head = /^(\s*Date\s*:\s*)/i.exec(lines[dateAt] ?? '')?.[1] ?? 'Date: '
+
+ lines[dateAt] = `${head}${date}`
+ } else {
+ lines.splice(at + 1, 0, `${indent}Date: ${date}`)
+ }
+ }
+
+ const coversAt = lines.findIndex(
+ (candidate, index) => index >= at && index < end + 1 && /Approval covers\s*:/i.test(candidate),
+ )
+
+ if (coversAt >= 0) {
+ const current = lines[coversAt] ?? ''
+
+ if (/\[[ xX]?\]/.test(current)) {
+ lines[coversAt] = current.replace(/\[[ xX]?\](\s*)([^[\]|]+)/g, (_match, gap: string, label: string) => {
+ const isFull = /full/i.test(label)
+ const isPhase = /phase\s*1/i.test(label)
+ const isChosen = covers === 'full' ? isFull : isPhase
+
+ return `[${isChosen ? 'X' : ' '}]${gap}${label}`
+ })
+ } else {
+ const head = /^(.*Approval covers\s*:\s*)/i.exec(current)?.[1] ?? 'Approval covers: '
+
+ lines[coversAt] = `${head}${COVER_WORDS[covers]}`
+ }
+ } else {
+ lines.splice(at + (hasInlineDate ? 1 : 2), 0, `${indent}Approval covers: ${COVER_WORDS[covers]}`)
+ }
+
+ return lines.join('\n')
+}
diff --git a/plugins/code-modernization/hooks/state.ts b/plugins/code-modernization/hooks/state.ts
new file mode 100644
index 00000000..2ce9b3f8
--- /dev/null
+++ b/plugins/code-modernization/hooks/state.ts
@@ -0,0 +1,180 @@
+import type { PluginOptions, Timer } from 'claude-code'
+
+import { newFleet, type Fleet } from './fleet/fleet'
+import type { Host } from './host'
+import type { Tile, Touch } from './map/estate'
+import type { TestTotals } from './reader/modernized'
+import type { ReaderCache, ReviewLedger, Snapshot } from './reader/progress'
+import type { TrackKey } from './reader/tracks'
+import type { Rule } from './reader/rules'
+import type { DeckScope } from './review/deck'
+
+export const PANE_ID = 'modernize'
+export const DECK_ID = 'modernize-review'
+export const SIGN_ID = 'modernize-sign'
+export const RASTER_KEY = 'estate'
+export const PLUGIN_NAME = 'code-modernization'
+
+export type Options = {
+ system: string
+ /** Which way to follow the system: the one whose artifacts are newest (`auto`), or one named. */
+ track: TrackKey | 'auto'
+ panel: 'auto' | 'command' | 'off'
+ isXrayOn: boolean
+ commandPrefix: string
+ legacyDir: string
+}
+
+const pick = <T extends string>(value: unknown, allowed: readonly T[], fallback: T): T =>
+ typeof value === 'string' && (allowed as readonly string[]).includes(value) ? (value as T) : fallback
+
+/** The options with their defaults applied, whatever the settings held. */
+export function optionsOf(raw: PluginOptions): Options {
+ const str = (key: string, fallback: string) => {
+ const value = raw[key]
+
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
+ }
+
+ return {
+ system: str('system', ''),
+ track: pick(raw.track, ['auto', 'transform', 'uplift', 'reimagine'] as const, 'auto'),
+ panel: pick(raw.panel, ['auto', 'command', 'off'] as const, 'auto'),
+ isXrayOn: raw.xray !== false,
+ commandPrefix: str('commandPrefix', '/code-modernization:modernize-'),
+ legacyDir: str('legacyDir', 'legacy').replace(/^\.?\/+|\/+$/g, ''),
+ }
+}
+
+export type RunningCall = {
+ id: string
+ tool: string
+ subject: string
+ startMs: number
+ agentId?: string
+}
+
+export type FinishedCall = {
+ tool: string
+ subject: string
+ isOk: boolean
+ ms: number
+ note?: string
+}
+
+export type Activity = {
+ isWorking: boolean
+ turnId: string | null
+ turnStartMs: number
+ /** The `/…modernize-<verb>` the current or last turn began with. */
+ step: string | null
+ running: Map<string, RunningCall>
+ finished: FinishedCall[]
+ /** Milliseconds the main loop spent in tool calls, and in those that ran tests. */
+ toolMs: number
+ testMs: number
+ testRuns: number
+ xrays: number
+ xraysThisTurn: number
+}
+
+export type DeckState = {
+ isOpen: boolean
+ scope: DeckScope
+ filter: string
+ queue: Rule[]
+ index: number
+ ledger: ReviewLedger
+ /** The source lines of the card in view, once asked for. */
+ source: { ruleId: string; path: string; startLine: number; text: string } | null
+ isSourceShown: boolean
+}
+
+export type SignState = {
+ isOpen: boolean
+ name: string
+ covers: 'phase-1' | 'full'
+ error: string | null
+}
+
+export type State = {
+ host: Host | null
+ cwd: string
+ /** The system a person switched to with the pane's button, over the `system` option. */
+ pickedSystem: string | null
+ options: Options
+ cache: ReaderCache
+ snapshot: Snapshot | null
+ readError: string | null
+ isRefreshing: boolean
+ isRefreshQueued: boolean
+ timers: Map<string, Timer>
+ pane: {
+ isOpen: boolean
+ isClosedByPerson: boolean
+ bodyColumns: number
+ bodyRows: number
+ placement: 'dock' | 'inline'
+ }
+ viewport: { columns: number | null; isFullscreen: boolean | null }
+ activity: Activity
+ touches: Map<string, Touch>
+ /** Test totals seen in commands this session, by the module path each was run in. */
+ observed: Map<string, TestTotals>
+ /** Units of an uplift's working copy written during this session. */
+ writtenUnits: Set<string>
+ estate: { tiles: Tile[]; columns: number; rows: number; isMounted: boolean } | null
+ fleet: Fleet
+ deck: DeckState
+ sign: SignState
+ lastContextLine: string
+}
+
+export const newActivity = (): Activity => ({
+ isWorking: false,
+ turnId: null,
+ turnStartMs: 0,
+ step: null,
+ running: new Map(),
+ finished: [],
+ toolMs: 0,
+ testMs: 0,
+ testRuns: 0,
+ xrays: 0,
+ xraysThisTurn: 0,
+})
+
+export function newState(raw: PluginOptions): State {
+ return {
+ host: null,
+ cwd: '',
+ pickedSystem: null,
+ options: optionsOf(raw),
+ cache: new Map(),
+ snapshot: null,
+ readError: null,
+ isRefreshing: false,
+ isRefreshQueued: false,
+ timers: new Map(),
+ pane: { isOpen: false, isClosedByPerson: false, bodyColumns: 48, bodyRows: 30, placement: 'dock' },
+ viewport: { columns: null, isFullscreen: null },
+ activity: newActivity(),
+ touches: new Map(),
+ observed: new Map(),
+ writtenUnits: new Set(),
+ estate: null,
+ fleet: newFleet(),
+ deck: {
+ isOpen: false,
+ scope: 'flagged',
+ filter: '',
+ queue: [],
+ index: 0,
+ ledger: {},
+ source: null,
+ isSourceShown: false,
+ },
+ sign: { isOpen: false, name: '', covers: 'phase-1', error: null },
+ lastContextLine: '',
+ }
+}
diff --git a/plugins/code-modernization/hooks/tests-run.ts b/plugins/code-modernization/hooks/tests-run.ts
new file mode 100644
index 00000000..cdc97eb3
--- /dev/null
+++ b/plugins/code-modernization/hooks/tests-run.ts
@@ -0,0 +1,87 @@
+/**
+ * Reading a test run off a shell command's output: how many cases executed,
+ * failed and were skipped, for the runners a modernized module usually has.
+ */
+
+const RUNNER =
+ /^(?:(?:\.\/)?mvnw?\b.*\b(?:test|verify|surefire:test)\b|(?:\.\/)?gradlew?\b.*\b(?:test|check)\b|pytest\b|py\.test\b|python3?\s+-m\s+(?:pytest|unittest)\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:npx\s+|bunx\s+)?(?:jest|vitest|mocha)\b|dotnet\s+test\b|go\s+test\b|cargo\s+test\b|(?:bundle\s+exec\s+)?rspec\b|prove\b|ctest\b|(?:\.\/vendor\/bin\/)?phpunit\b|make\s+(?:test|check)\b)/
+
+/**
+ * Whether a shell command runs a test suite: a runner in command position in
+ * any of its segments, not a mere mention of one (`cat pytest.ini` is not).
+ */
+export function isTestCommand(command: string): boolean {
+ return command
+ .split(/&&|\|\||[;|\n(]/)
+ .map(segment =>
+ segment
+ .trim()
+ // Leading `VAR=value` assignments, `time`, `env`, `sudo`, `exec` do not change what runs.
+ .replace(/^(?:(?:[A-Za-z_][A-Za-z0-9_]*=\S*|time|env|sudo|exec|nice|command)\s+)+/, ''),
+ )
+ .some(segment => RUNNER.test(segment))
+}
+
+/** Kept for callers that test a whole command string. */
+export const TEST_COMMAND = { test: isTestCommand }
+
+export type TestRun = { executed: number; failed: number; skipped: number }
+
+const num = (value: string | undefined) => (value !== undefined ? Number(value) : 0)
+
+/** The run's totals, or null when the output names none. */
+export function readTestRun(output: string): TestRun | null {
+ // Maven Surefire / Gradle: the last "Tests run:" line is the total.
+ const maven = [...output.matchAll(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/g)].at(-1)
+
+ if (maven !== undefined) {
+ const run = num(maven[1])
+ const skipped = num(maven[4])
+
+ return { executed: Math.max(0, run - skipped), failed: num(maven[2]) + num(maven[3]), skipped }
+ }
+
+ // pytest: "== 3 passed, 1 skipped, 2 failed in 0.12s ==" or "collected 0 items".
+ const pytest = /=+\s*((?:\d+\s+\w+,?\s*)+)\s+in\s+[\d.]+s/.exec(output)
+
+ if (pytest !== null) {
+ const count = (word: string) => num(new RegExp(`(\\d+)\\s+${word}`).exec(pytest[1] ?? '')?.[1])
+ const failed = count('failed') + count('error') + count('errors')
+
+ return { executed: count('passed') + failed + count('xfailed') + count('xpassed'), failed, skipped: count('skipped') + count('deselected') }
+ }
+
+ if (/collected 0 items|no tests ran/i.test(output)) {
+ return { executed: 0, failed: 0, skipped: 0 }
+ }
+
+ // Jest / Vitest: "Tests: 1 failed, 2 skipped, 9 passed, 12 total".
+ const jest = /Tests:\s+([^\n]+?)\s+total/i.exec(output) ?? /Tests\s+([^\n]*\d+\s+passed[^\n]*)/i.exec(output)
+
+ if (jest !== null) {
+ const count = (word: string) => num(new RegExp(`(\\d+)\\s+${word}`).exec(jest[1] ?? '')?.[1])
+ const failed = count('failed')
+
+ return { executed: count('passed') + failed, failed, skipped: count('skipped') + count('todo') }
+ }
+
+ // dotnet test: "Passed! - Failed: 0, Passed: 12, Skipped: 1, Total: 13".
+ const dotnet = /Failed:\s*(\d+),\s*Passed:\s*(\d+),\s*Skipped:\s*(\d+),\s*Total:\s*(\d+)/.exec(output)
+
+ if (dotnet !== null) {
+ return { executed: num(dotnet[1]) + num(dotnet[2]), failed: num(dotnet[1]), skipped: num(dotnet[3]) }
+ }
+
+ // go test / cargo test.
+ const cargo = /test result:[^\n]*?(\d+)\s+passed;\s*(\d+)\s+failed;\s*(\d+)\s+ignored/.exec(output)
+
+ if (cargo !== null) {
+ return { executed: num(cargo[1]) + num(cargo[2]), failed: num(cargo[2]), skipped: num(cargo[3]) }
+ }
+
+ if (/\bno test files\b|\[no tests to run\]/.test(output)) {
+ return { executed: 0, failed: 0, skipped: 0 }
+ }
+
+ return null
+}
diff --git a/plugins/code-modernization/hooks/views/deck.tsx b/plugins/code-modernization/hooks/views/deck.tsx
new file mode 100644
index 00000000..3d81f744
--- /dev/null
+++ b/plugins/code-modernization/hooks/views/deck.tsx
@@ -0,0 +1,310 @@
+/* @jsxRuntime classic */
+/* @jsx h */
+/* @jsxFrag Fragment */
+import type { RenderChildren, RenderElement } from 'claude-code'
+
+import type { ReviewVerdict } from '../reader/progress'
+import { tallyOf } from '../review/deck'
+import type { DeckState, SignState } from '../state'
+import type { Kit } from './pane'
+
+export type DeckActions = {
+ decide: (verdict: ReviewVerdict) => void
+ undo: () => void
+ prev: () => void
+ next: () => void
+ source: () => void
+ close: () => void
+}
+
+const SCOPE_WORDS = { flagged: 'P0 rules flagged for a person', p0: 'all P0 rules', all: 'all rules' }
+const SCOPE_SHORT = { flagged: 'flagged P0', p0: 'P0', all: 'all' }
+
+const VERDICT_COLORS: Record<ReviewVerdict, string> = {
+ confirmed: 'green',
+ wrong: 'red',
+ discuss: 'yellow',
+}
+
+/** `text` word-wrapped to `width` cells, at most `maxLines` rows, the last ending in an ellipsis when cut. */
+export function wrapLines(text: string, width: number, maxLines: number): string[] {
+ const out: string[] = []
+ const limit = Math.max(8, width)
+ let line = ''
+
+ const push = (value: string) => {
+ out.push(value)
+ }
+
+ for (const word of text.split(/\s+/).filter(part => part !== '')) {
+ let rest = word
+
+ while (rest.length > limit) {
+ if (line !== '') {
+ push(line)
+ line = ''
+ }
+
+ push(rest.slice(0, limit))
+ rest = rest.slice(limit)
+ }
+
+ if (line === '') {
+ line = rest
+ } else if (line.length + 1 + rest.length <= limit) {
+ line = `${line} ${rest}`
+ } else {
+ push(line)
+ line = rest
+ }
+ }
+
+ if (line !== '') {
+ push(line)
+ }
+
+ if (out.length <= maxLines) {
+ return out
+ }
+
+ const kept = out.slice(0, Math.max(1, maxLines))
+ const last = kept[kept.length - 1] ?? ''
+
+ kept[kept.length - 1] = `${last.slice(0, Math.max(0, limit - 1))}…`
+
+ return kept
+}
+
+/**
+ * The review deck's body: one rule card, its verdict, and the keys.
+ *
+ * It draws in the band above the prompt, where a bare digit presses a Button
+ * from an empty composer. A tree taller than the band scrolls and disarms the
+ * digits, so the card wraps its own text into counted rows and never exceeds
+ * `maxRows`.
+ */
+export function deckView(
+ kit: Kit,
+ deck: DeckState,
+ columns: number,
+ maxRows: number,
+ actions: DeckActions,
+): RenderElement {
+ const { Box, Text, Button, Code } = kit
+ const width = Math.max(30, columns - 2)
+ const rule = deck.queue[deck.index]
+ const tally = tallyOf(deck.queue, deck.ledger)
+
+ if (rule === undefined) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="cyan">Rule review</Text>
+ <Text dimColor wrap="truncate-end">
+ {`Nothing to review under "${SCOPE_WORDS[deck.scope]}"${deck.filter !== '' ? ` matching "${deck.filter}"` : ''}. Try /modernize-review all.`}
+ </Text>
+ <Button key="close" hotkey="0" plain onPress={actions.close}>close</Button>
+ </Box>
+ )
+ }
+
+ const verdict = deck.ledger[rule.id]
+ const first = rule.citations[0]
+ const shownSource = deck.isSourceShown && deck.source !== null && deck.source.ruleId === rule.id ? deck.source : null
+
+ const meta = [
+ rule.domain,
+ rule.category,
+ rule.confidence !== undefined ? `confidence ${rule.confidence}` : undefined,
+ first !== undefined ? `${first.path.split('/').pop()}:${first.from}${first.to !== first.from ? `-${first.to}` : ''}` : undefined,
+ ].filter((part): part is string => part !== undefined && part !== '')
+
+ const keys = (
+ <Box columnGap={2}>
+ <Button key="confirm" hotkey="1" plain onPress={() => actions.decide('confirmed')}>confirm</Button>
+ <Button key="wrong" hotkey="2" plain onPress={() => actions.decide('wrong')}>wrong</Button>
+ <Button key="discuss" hotkey="3" plain onPress={() => actions.decide('discuss')}>discuss</Button>
+ <Button key="prev" hotkey="4" plain onPress={actions.prev}>back</Button>
+ <Button key="skip" hotkey="5" plain onPress={actions.next}>skip</Button>
+ <Button key="source" hotkey="6" plain onPress={actions.source}>{deck.isSourceShown ? 'hide source' : 'source'}</Button>
+ {verdict !== undefined ? <Button key="undo" hotkey="7" plain onPress={actions.undo}>undo</Button> : null}
+ <Button key="close" hotkey="0" plain onPress={actions.close}>close</Button>
+ </Box>
+ )
+
+ const verdictLine =
+ verdict !== undefined ? (
+ <Text color={VERDICT_COLORS[verdict.verdict]} bold>{`Verdict: ${verdict.verdict} (${verdict.at.slice(0, 10)})`}</Text>
+ ) : (
+ <Text dimColor>Verdict: none yet</Text>
+ )
+
+ const headline = (
+ <Text wrap="truncate-end">
+ <Text bold color="cyan">Rule review</Text>
+ <Text bold>{` ${deck.index + 1}/${tally.total}`}</Text>
+ <Text dimColor>{' '}</Text>
+ <Text color="green">{`✓ ${tally.confirmed}`}</Text>
+ <Text dimColor>{' '}</Text>
+ <Text color="red">{`✗ ${tally.wrong}`}</Text>
+ <Text dimColor>{' '}</Text>
+ <Text color="yellow">{`? ${tally.discuss}`}</Text>
+ <Text dimColor>{` ${tally.open} open · ${width < 96 ? SCOPE_SHORT[deck.scope] : SCOPE_WORDS[deck.scope]}${deck.filter !== '' ? ` · "${deck.filter}"` : ''}`}</Text>
+ </Text>
+ )
+
+ // With the source open the code gets the room: the rule in one line, no blank rows, and as many
+ // cited lines as the band holds. Seven rows are spoken for: headline, title, meta, statement,
+ // path, verdict, keys.
+ if (shownSource !== null && Code !== undefined) {
+ const codeRows = Math.max(3, Math.min(24, maxRows - 8))
+ const gist = rule.statement !== '' ? rule.statement : (rule.then ?? rule.given ?? '')
+
+ return (
+ <Box flexDirection="column" width={width}>
+ {headline}
+ <Text bold wrap="truncate-end">{`${rule.id.startsWith('R-') ? rule.priority : rule.id} · ${rule.title}`}</Text>
+ <Text dimColor wrap="truncate-end">{meta.join(' · ')}</Text>
+ <Text wrap="truncate-end">{wrapLines(gist, width, 1)[0] ?? ''}</Text>
+ <Text dimColor wrap="truncate-end">{`${shownSource.path}:${shownSource.startLine}`}</Text>
+ <Code
+ source={shownSource.text.split('\n').slice(0, codeRows).join('\n')}
+ path={shownSource.path}
+ startLine={shownSource.startLine}
+ wrap="truncate-end"
+ />
+ {verdictLine}
+ {keys}
+ </Box>
+ )
+ }
+
+ // Rows that are always there: header, blank, title, meta, blank, [body], blank, verdict, keys.
+ const fixed = 8
+ // One row of slack: a band exactly full still scrolls on some layouts.
+ const isTight = maxRows < 16
+ const room = Math.max(1, maxRows - (isTight ? fixed - 3 : fixed) - 1)
+ const prose = Math.max(1, room)
+
+ // Share the prose rows: flags one row each, the statement up to two, the rest split over Given/When/Then.
+ const flagRows = (rule.defect !== undefined ? 1 : 0) + (rule.sme !== undefined ? 1 : 0)
+ const statementRows = rule.statement !== '' ? Math.min(2, Math.max(0, prose - flagRows - 3)) : 0
+ const parts = [rule.given, rule.when, rule.then].filter(part => part !== undefined).length
+ const each = parts > 0 ? Math.max(1, Math.floor((prose - flagRows - statementRows) / parts)) : 0
+
+ type Row = { text: string; color?: string; label?: string }
+ const rows: Row[] = []
+
+ for (const line of wrapLines(rule.statement, width, statementRows)) {
+ rows.push({ text: line })
+ }
+
+ const block = (label: string, text: string | undefined) => {
+ if (text === undefined) {
+ return
+ }
+
+ wrapLines(`${label} ${text}`, width, each).forEach((line, index) => {
+ rows.push(index === 0 ? { label, text: line.slice(label.length + 1) } : { text: line })
+ })
+ }
+
+ block('Given', rule.given)
+ block('When', rule.when)
+ block('Then', rule.then)
+
+ if (rule.defect !== undefined) {
+ rows.push({ text: wrapLines(`⚠ Suspected defect: ${rule.defect}`, width, 1)[0] ?? '', color: 'yellow' })
+ }
+
+ if (rule.sme !== undefined) {
+ rows.push({ text: wrapLines(`? For an SME: ${rule.sme}`, width, 1)[0] ?? '', color: 'magenta' })
+ }
+
+ return (
+ <Box flexDirection="column" width={width}>
+ {headline}
+ <Box marginTop={isTight ? 0 : 1} flexDirection="column">
+ <Text bold wrap="truncate-end">{`${rule.id.startsWith('R-') ? rule.priority : rule.id} · ${rule.title}`}</Text>
+ <Text dimColor wrap="truncate-end">{meta.join(' · ')}</Text>
+ </Box>
+ <Box marginTop={isTight ? 0 : 1} flexDirection="column">
+ {rows.slice(0, prose).map(row => (
+ <Text wrap="truncate-end" color={row.color}>
+ {row.label !== undefined ? <Text bold color="cyan">{`${row.label} `}</Text> : null}
+ {row.text}
+ </Text>
+ ))}
+ </Box>
+ <Box marginTop={isTight ? 0 : 1}>{verdictLine}</Box>
+ {keys}
+ </Box>
+ )
+}
+
+export type SignActions = {
+ name: (value: string) => void
+ covers: (value: 'phase-1' | 'full') => void
+ sign: () => void
+ cancel: () => void
+}
+
+/** The sign-off dialog: a person's name, what the approval covers, and the button that writes it. */
+export function signView(
+ kit: Kit,
+ sign: SignState,
+ system: string,
+ openQuestions: number,
+ columns: number,
+ actions: SignActions,
+): RenderElement {
+ const { Box, Text, Button, Input } = kit
+ const width = Math.max(30, columns)
+
+ return (
+ <Box flexDirection="column" width={width}>
+ <Text bold color="cyan">Sign the brief</Text>
+ <Text dimColor wrap="wrap">
+ {`analysis/${system}/MODERNIZATION_BRIEF.md · execution commands treat an unsigned brief as not approved.`}
+ </Text>
+ {openQuestions > 0 ? (
+ <Text color="yellow" wrap="wrap">{`${openQuestions} open question${openQuestions === 1 ? '' : 's'} in the brief ${openQuestions === 1 ? 'is' : 'are'} still unticked.`}</Text>
+ ) : null}
+ <Box marginTop={1} flexDirection="column">
+ {Input !== undefined ? (
+ <Input
+ key="signer"
+ label="Approved by"
+ placeholder="name, role"
+ value={sign.name}
+ submitLabel="sign"
+ autoFocus
+ onInput={actions.name}
+ onSubmit={value => {
+ actions.name(value)
+ actions.sign()
+ }}
+ />
+ ) : (
+ <Text>{`Approved by: ${sign.name}`}</Text>
+ )}
+ </Box>
+ <Box marginTop={1} columnGap={2}>
+ <Text dimColor>Covers:</Text>
+ <Button key="phase1" plain onPress={() => actions.covers('phase-1')}>
+ {`${sign.covers === 'phase-1' ? '◉' : '○'} Phase 1 only`}
+ </Button>
+ <Button key="full" plain onPress={() => actions.covers('full')}>
+ {`${sign.covers === 'full' ? '◉' : '○'} Full plan`}
+ </Button>
+ </Box>
+ {sign.error !== null ? <Text color="red" wrap="wrap">{sign.error}</Text> : null}
+ <Box marginTop={1} columnGap={2}>
+ <Button key="do-sign" onPress={actions.sign}>sign</Button>
+ <Button key="cancel" dimColor onPress={actions.cancel}>cancel</Button>
+ </Box>
+ <Box>
+ <Text dimColor>enter signs · tab moves · esc cancels</Text>
+ </Box>
+ </Box>
+ )
+}
diff --git a/plugins/code-modernization/hooks/views/pane.tsx b/plugins/code-modernization/hooks/views/pane.tsx
new file mode 100644
index 00000000..7e9ad1b6
--- /dev/null
+++ b/plugins/code-modernization/hooks/views/pane.tsx
@@ -0,0 +1,567 @@
+/* @jsxRuntime classic */
+/* @jsx h */
+/* @jsxFrag Fragment */
+import type { Elements, RenderChildren, RenderElement } from 'claude-code'
+
+import { lineOf, tallyOf } from '../fleet/fleet'
+import { countsOf, hexOf, STATE_COLORS, stateWord, type Tile } from '../map/estate'
+import { isUnitDone, type Snapshot } from '../reader/progress'
+import { TRACK_LABELS, TRACK_UNITS } from '../reader/tracks'
+import { RASTER_KEY, type State } from '../state'
+
+/** The elements a pane draws with; `Raster` only where the surface has it (the terminal). */
+export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> &
+ Partial<Pick<Elements['terminal'], 'Raster' | 'Code' | 'Input' | 'Select'>>
+
+export type PaneActions = {
+ /** Follow the workspace's next system, when it holds more than one. */
+ system: () => void
+ next: () => void
+ refresh: () => void
+ review: () => void
+ sign: () => void
+ close: () => void
+ stop: () => void
+}
+
+export type PaneFrame = {
+ columns: number
+ rows: number
+ placement: 'dock' | 'inline'
+ nowMs: number
+ /** The packed cells for the estate, when there is room and a map to draw. */
+ estate: { cells: string; columns: number; rows: number; tiles: Tile[] } | null
+ plan: PanePlan
+}
+
+const pad = (text: string, width: number) =>
+ text.length >= width ? text.slice(0, Math.max(0, width)) : text + ' '.repeat(width - text.length)
+
+const clip = (text: string, width: number) =>
+ text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…`
+
+const ago = (ms: number): string => {
+ const s = Math.max(0, Math.round(ms / 1000))
+
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
+}
+
+const barOf = (fraction: number, width: number): { full: string; rest: string } => {
+ const filled = Math.max(0, Math.min(width, Math.round(fraction * width)))
+
+ return { full: '━'.repeat(filled), rest: '─'.repeat(width - filled) }
+}
+
+function rule(kit: Kit, title: string, width: number, right = ''): RenderChildren {
+ const { Box, Text } = kit
+ const fill = Math.max(1, width - title.length - right.length - 2)
+
+ return (
+ <Box>
+ <Text bold color="cyan">{title}</Text>
+ <Text dimColor>{` ${'─'.repeat(fill)} `}</Text>
+ <Text color="yellow">{right}</Text>
+ </Box>
+ )
+}
+
+/** The rows the stage rail takes when it wraps at `width`. */
+const railRowsOf = (snapshot: Snapshot, width: number): number =>
+ Math.max(1, Math.ceil(snapshot.stages.reduce((sum, stage) => sum + stage.label.length + 3, 0) / Math.max(10, width)))
+
+/** What the estate is made of, in one dim line: its languages, and how many units it was read into. */
+function estateLine(snapshot: Snapshot): string {
+ const estate = snapshot.estate
+
+ if (estate === null) {
+ return ''
+ }
+
+ const languages = estate.languages
+ .filter(entry => entry.share >= 0.03)
+ .map(entry => `${entry.name} ${Math.round(entry.share * 100)}%`)
+ .join(' · ')
+
+ const noun = estate.granularity === 'build module' ? 'build module' : estate.granularity === 'module' ? 'module' : estate.granularity
+ const count = `${estate.units.length.toLocaleString('en-US')} ${noun}${estate.units.length === 1 ? '' : 's'}`
+ const from = estate.source === 'map' ? '' : ' (read off the tree)'
+
+ return `${languages === '' ? '' : `${languages} · `}${count}${estate.isPartial ? '+' : ''}${from}`
+}
+
+/** The rows the header takes: the title, the stage rail, the estate line and the progress bar. */
+export const headerRowsOf = (snapshot: Snapshot | null, width: number): number =>
+ snapshot === null
+ ? 3
+ : 1 + railRowsOf(snapshot, width) + (estateLine(snapshot) === '' ? 0 : 1) + (snapshot.percent !== null ? 1 : 0)
+
+function header(kit: Kit, snapshot: Snapshot, width: number, actions: PaneActions): RenderChildren {
+ const { Box, Text, Button } = kit
+ const target = snapshot.brief?.target
+ const percent = snapshot.percent
+ const measure = snapshot.estate?.measure === 'bytes' ? 'size' : 'loc'
+ const right = percent === null ? '' : `${(percent * 100).toFixed(percent < 0.1 ? 1 : 0)}% by ${measure}`
+ const left = `${snapshot.system}${target !== undefined ? ` → ${target}` : ''}`
+ const bar = barOf(percent ?? 0, Math.max(4, width - right.length - 1))
+ const summary = estateLine(snapshot)
+ const at = snapshot.systems.indexOf(snapshot.system)
+ const many = snapshot.systems.length > 1
+
+ return (
+ <Box flexDirection="column">
+ <Box justifyContent="space-between">
+ <Text bold wrap="truncate-end">{clip(`${left} · ${TRACK_LABELS[snapshot.track]}`, Math.max(8, width - (many ? 22 : 9)))}</Text>
+ <Box columnGap={1}>
+ {many ? <Button key="system" dimColor onPress={actions.system}>{`system ${at + 1}/${snapshot.systems.length}`}</Button> : null}
+ <Button key="hide" dimColor onPress={actions.close}>hide</Button>
+ </Box>
+ </Box>
+ <Box flexWrap="wrap">
+ {snapshot.stages.map(stage => (
+ <Text color={stage.isDone ? 'green' : undefined} dimColor={!stage.isDone}>
+ {`${stage.isDone ? '✓' : '·'} ${stage.label} `}
+ </Text>
+ ))}
+ </Box>
+ {summary !== '' ? <Text dimColor wrap="truncate-end">{clip(summary, width)}</Text> : null}
+ {percent !== null ? (
+ <Box>
+ <Text color="green">{bar.full}</Text>
+ <Text dimColor>{bar.rest}</Text>
+ <Text>{` ${right}`}</Text>
+ </Box>
+ ) : null}
+ </Box>
+ )
+}
+
+function estate(kit: Kit, snapshot: Snapshot, frame: PaneFrame, width: number): RenderChildren {
+ const { Box, Text, Raster } = kit
+
+ if (frame.estate === null || Raster === undefined) {
+ return null
+ }
+
+ const counts = countsOf(frame.estate.tiles)
+
+ return (
+ <Box flexDirection="column">
+ <Raster
+ key={RASTER_KEY}
+ columns={frame.estate.columns}
+ rows={frame.estate.rows}
+ cells={frame.estate.cells}
+ />
+ <Box flexWrap="wrap" width={width}>
+ {counts.map(entry => (
+ <Text>
+ <Text color={hexOf(STATE_COLORS[entry.state])}>■</Text>
+ <Text dimColor>{` ${stateWord(snapshot.track, entry.state)} ${entry.count} `}</Text>
+ </Text>
+ ))}
+ </Box>
+ </Box>
+ )
+}
+
+function phases(kit: Kit, snapshot: Snapshot, width: number, max: number): RenderChildren {
+ const { Box, Text } = kit
+ const brief = snapshot.brief
+
+ if (brief === null || brief.phases.length === 0) {
+ return null
+ }
+
+ const isDone = (ids: readonly string[]) =>
+ ids.length > 0 &&
+ ids.every(id => {
+ const module = snapshot.byNode.get(id)
+
+ return module !== undefined && isUnitDone(snapshot, module)
+ })
+
+ const ordered = [...brief.phases].sort((a, b) => a.number - b.number)
+ const currentIndex = Math.max(0, ordered.findIndex(phase => !isDone(phase.modules)))
+ const start = Math.max(0, Math.min(currentIndex - 1, ordered.length - max))
+ const shown = ordered.slice(start, start + max)
+ const doneCount = ordered.filter(phase => isDone(phase.modules)).length
+
+ return (
+ <Box flexDirection="column">
+ {rule(kit, 'Phases', width, `${doneCount}/${ordered.length}`)}
+ {shown.map(phase => {
+ const done = isDone(phase.modules)
+ const isCurrent = ordered[currentIndex] === phase && !done
+ const ticked = phase.criteria.filter(criterion => criterion.isTicked).length
+ const right = `${phase.criteria.length > 0 ? `${ticked}/${phase.criteria.length} ☑ ` : ''}${pad(phase.size ?? '', 2)}`
+ const label = `${done ? '✓' : isCurrent ? '▸' : '·'} P${phase.number} ${phase.title}`
+
+ return (
+ <Box>
+ <Text
+ color={done ? 'green' : isCurrent ? 'cyan' : undefined}
+ bold={isCurrent}
+ dimColor={!done && !isCurrent}
+ >
+ {pad(clip(label, width - right.length - 1), width - right.length - 1)}
+ </Text>
+ <Text dimColor>{` ${right}`}</Text>
+ </Box>
+ )
+ })}
+ {ordered.length > shown.length ? (
+ <Text dimColor>{` … ${ordered.length - shown.length} more phases`}</Text>
+ ) : null}
+ </Box>
+ )
+}
+
+/** Units of work in the order that helps most: problems first in an uplift, the newest first in a rewrite. */
+function orderOf(snapshot: Snapshot): Snapshot['modules'] {
+ if (snapshot.track !== 'uplift') {
+ return [...snapshot.modules].sort((a, b) => b.mtimeMs - a.mtimeMs)
+ }
+
+ const rank = (state: string) => (state === 'tests-red' ? 0 : state === 'scaffolded' ? 1 : state === 'tests-green' ? 2 : 3)
+
+ return [...snapshot.modules].sort((a, b) => rank(a.state) - rank(b.state) || (b.tests?.tests ?? 0) - (a.tests?.tests ?? 0))
+}
+
+function modules(kit: Kit, snapshot: Snapshot, width: number, max: number): RenderChildren {
+ const { Box, Text } = kit
+ const all = orderOf(snapshot)
+
+ if (all.length === 0) {
+ return null
+ }
+
+ return (
+ <Box flexDirection="column">
+ {rule(kit, TRACK_UNITS[snapshot.track].many, width, snapshot.track === 'reimagine' ? String(all.length) : `${snapshot.totals.done}/${snapshot.totals.modules}`)}
+ {all.slice(0, max).map(module => {
+ const tests = module.tests
+ const bad = tests === null ? 0 : tests.failures + tests.errors
+ const isWorse = module.state === 'tests-red'
+
+ // In an uplift a module may fail what the baseline already failed: red is only for what got worse.
+ const testText =
+ tests === null
+ ? ''
+ : isWorse
+ ? snapshot.track === 'uplift'
+ ? `${bad} failing`
+ : `${bad}/${tests.tests} red`
+ : bad > 0 && snapshot.track !== 'uplift'
+ ? `${bad}/${tests.tests} red`
+ : `${tests.tests} ${snapshot.track === 'uplift' ? 'tests' : 'green'}`
+
+ const color = hexOf(STATE_COLORS[module.state])
+ const word = stateWord(snapshot.track, module.state)
+ const name = clip(module.dir, Math.max(8, width - word.length - testText.length - 5))
+
+ return (
+ <Box>
+ <Text color={color}>■ </Text>
+ <Text bold>{name}</Text>
+ <Text dimColor>{` ${word}`}</Text>
+ <Text color={isWorse || (bad > 0 && snapshot.track !== 'uplift') ? 'red' : 'green'}>
+ {testText === '' ? '' : ` ${testText}`}
+ </Text>
+ </Box>
+ )
+ })}
+ {all.length > max ? <Text dimColor>{` … ${all.length - max} more`}</Text> : null}
+ </Box>
+ )
+}
+
+function session(kit: Kit, state: State, frame: PaneFrame, width: number, max: number): RenderChildren {
+ const { Box, Text } = kit
+ const activity = state.activity
+ const fleet = tallyOf(state.fleet, frame.nowMs)
+
+ // A workflow's agents run on while the main loop waits between turns: that is not idle.
+ const status = activity.isWorking
+ ? `● working ${ago(frame.nowMs - activity.turnStartMs)}`
+ : fleet.active > 0
+ ? `● ${fleet.active} agents working`
+ : '○ idle'
+
+ const running = [...activity.running.values()]
+ .filter(call => call.agentId === undefined)
+ .sort((a, b) => a.startMs - b.startMs)
+
+ const share = activity.toolMs > 0 ? Math.round((activity.testMs / activity.toolMs) * 100) : 0
+
+ // Rows in the order they matter; the block draws as many as it was given.
+ const rows: RenderChildren[] = []
+
+ if (activity.step !== null) {
+ rows.push(<Text color="cyan" wrap="truncate-end">{clip(` ${activity.step}`, width)}</Text>)
+ }
+
+ if (fleet.total > 0) {
+ rows.push(
+ <Text wrap="truncate-end">
+ <Text color="cyan">{' ⛭ '}</Text>
+ <Text>{`${fleet.active} agents active`}</Text>
+ <Text dimColor>{` · ${fleet.done}/${fleet.total} done · ${fleet.calls} calls${fleet.errors > 0 ? ` · ${fleet.errors} errors` : ''}${fleet.stalled > 0 ? ` · ${fleet.stalled} quiet` : ''}`}</Text>
+ </Text>,
+ )
+ }
+
+ for (const call of running.slice(-2)) {
+ rows.push(
+ <Box>
+ <Text color="yellow">{' ◌ '}</Text>
+ <Text>{pad(clip(`${call.tool} ${call.subject}`, width - 10), width - 10)}</Text>
+ <Text dimColor>{` ${ago(frame.nowMs - call.startMs)}`}</Text>
+ </Box>,
+ )
+ }
+
+ const summary = [
+ activity.xrays > 0 ? `x-ray notes ${activity.xrays}` : '',
+ activity.testRuns > 0 ? `tests ${share}% of tool time (${activity.testRuns} runs)` : '',
+ ].filter(part => part !== '')
+
+ const tail: RenderChildren[] = summary.length > 0 ? [<Text dimColor wrap="truncate-end">{clip(` ${summary.join(' · ')}`, width)}</Text>] : []
+ const room = Math.max(0, max - rows.length - tail.length)
+ const agents = fleet.recent.slice(0, Math.min(3, Math.floor(room / 2)))
+
+ for (const row of agents) {
+ rows.push(
+ <Text dimColor wrap="truncate-end">
+ {clip(` ${row.unit !== undefined ? `${row.unit} ` : ''}${row.lastTool} ${row.lastSubject}`, width)}
+ </Text>,
+ )
+ }
+
+ for (const call of activity.finished.slice(-Math.max(0, max - rows.length - tail.length))) {
+ rows.push(
+ <Box>
+ <Text color={call.isOk ? 'green' : 'red'}>{call.isOk ? ' ✓ ' : ' ✗ '}</Text>
+ <Text dimColor wrap="truncate-end">{clip(`${call.tool} ${call.subject}${call.note !== undefined ? ` · ${call.note}` : ''}`, width - 4)}</Text>
+ </Box>,
+ )
+ }
+
+ return (
+ <Box flexDirection="column">
+ {rule(kit, 'Session', width, status)}
+ {[...rows.slice(0, Math.max(0, max - tail.length)), ...tail]}
+ </Box>
+ )
+}
+
+function attention(kit: Kit, state: State, snapshot: Snapshot, width: number, max: number): RenderChildren {
+ const { Box, Text } = kit
+ const shared = tallyOf(state.fleet, 0).shared.map(signature => lineOf(signature, 'short'))
+
+ const lines = [...shared, ...snapshot.attention]
+
+ if (lines.length === 0) {
+ return null
+ }
+
+ return (
+ <Box flexDirection="column">
+ {rule(kit, 'Attention', width, String(lines.length))}
+ {lines.slice(0, max).map(line => (
+ <Text color="yellow" wrap="truncate-end">{clip(` ! ${line}`, width)}</Text>
+ ))}
+ {lines.length > max ? <Text dimColor>{` … ${lines.length - max} more`}</Text> : null}
+ </Box>
+ )
+}
+
+function nextBlock(
+ kit: Kit,
+ snapshot: Snapshot,
+ actions: PaneActions,
+ state: State,
+ width: number,
+ hasHint: boolean,
+): RenderChildren {
+ const { Box, Text, Button } = kit
+ const next = snapshot.next
+ const hasRules = (snapshot.rules?.rules.length ?? 0) > 0
+
+ return (
+ <Box flexDirection="column">
+ {rule(kit, 'Next', width)}
+ {next !== null ? (
+ <Box flexDirection="column" paddingLeft={2}>
+ <Text color={next.isByHand ? undefined : 'cyan'} bold={!next.isByHand} wrap="truncate-end">
+ {`${next.text}${next.isByHand ? ' (by hand)' : ''}`}
+ </Text>
+ <Text dimColor wrap="truncate-end">{next.reason}</Text>
+ </Box>
+ ) : (
+ <Text dimColor>{' nothing to suggest'}</Text>
+ )}
+ <Box marginTop={1} flexWrap="wrap" columnGap={1}>
+ {next !== null && !next.isByHand ? (
+ <Button key="next" onPress={actions.next}>next</Button>
+ ) : null}
+ {hasRules ? <Button key="review" onPress={actions.review}>review rules</Button> : null}
+ {state.activity.isWorking && state.fleet.seen > 0 ? (
+ <Button key="stop" onPress={actions.stop}>stop the run</Button>
+ ) : null}
+ <Button key="refresh" dimColor onPress={actions.refresh}>refresh</Button>
+ </Box>
+ {hasHint ? <Text dimColor>{'click, or ctrl+x tab then tab and enter'}</Text> : null}
+ </Box>
+ )
+}
+
+/** How the pane's rows are shared out, so the whole of it shows without scrolling. */
+export type PanePlan = {
+ estate: number
+ phases: number
+ modules: number
+ attention: number
+ session: number
+ /** Blank rows between blocks. */
+ gap: 0 | 1
+ /** Whether the dim hint under the buttons is drawn. */
+ hasHint: boolean
+}
+
+/**
+ * Shares `rows` body rows between the blocks. Fixed costs first (header,
+ * legend, the Next block, each list's title), then the lists at their
+ * minimum, then what is left goes to the map and the phase list.
+ */
+export function planOf(
+ rows: number,
+ placement: 'dock' | 'inline',
+ counts: { phases: number; modules: number; attention: number; hasMap: boolean; headerRows: number },
+): PanePlan {
+ if (placement === 'inline') {
+ return {
+ estate: counts.hasMap ? Math.max(4, Math.min(6, rows - 6 - counts.headerRows)) : 0,
+ phases: 0,
+ modules: Math.min(1, counts.modules),
+ attention: Math.min(1, counts.attention),
+ session: 1,
+ gap: 0,
+ hasHint: false,
+ }
+ }
+
+ const gap: 0 | 1 = rows >= 52 ? 1 : 0
+ const hasHint = rows >= 44
+ const attention = Math.min(counts.attention, rows >= 40 ? 3 : 2)
+ const modules = Math.min(counts.modules, rows >= 48 ? 3 : rows >= 38 ? 2 : 1)
+ const sessionMin = rows >= 40 ? 4 : 3
+
+ // header · legend 1 · next: title, command, reason, blank, buttons (+hint)
+ const fixed =
+ counts.headerRows +
+ (counts.hasMap ? 1 : 0) +
+ (5 + (hasHint ? 1 : 0)) +
+ (attention > 0 ? 1 + attention : 0) +
+ (modules > 0 ? 1 + modules : 0) +
+ (1 + sessionMin) +
+ (counts.phases > 0 ? 1 : 0)
+
+ const blocks = 3 + (counts.hasMap ? 1 : 0) + (attention > 0 ? 1 : 0) + (modules > 0 ? 1 : 0) + (counts.phases > 0 ? 1 : 0)
+ const spare = Math.max(0, rows - fixed - gap * (blocks - 1))
+ const phases = counts.phases > 0 ? Math.max(1, Math.min(counts.phases, Math.floor(spare * 0.3))) : 0
+ const estate = counts.hasMap ? Math.max(4, Math.min(16, spare - phases - (counts.phases > phases ? 1 : 0))) : 0
+ const left = Math.max(0, spare - phases - estate - (counts.phases > phases ? 1 : 0))
+
+ const plan: PanePlan = { estate, phases, modules, attention, session: sessionMin + Math.min(4, left), gap, hasHint }
+
+ // A body too short for even the minimums sheds rows in the order they matter least.
+ const totalOf = (p: PanePlan) =>
+ counts.headerRows +
+ (p.estate > 0 ? p.estate + 1 : 0) +
+ (p.phases > 0 ? 1 + p.phases + (counts.phases > p.phases ? 1 : 0) : 0) +
+ (p.modules > 0 ? 1 + p.modules + (counts.modules > p.modules ? 1 : 0) : 0) +
+ (5 + (p.hasHint ? 1 : 0)) +
+ (p.attention > 0 ? 1 + p.attention + (counts.attention > p.attention ? 1 : 0) : 0) +
+ (1 + p.session)
+
+ const shed: (() => boolean)[] = [
+ () => (plan.hasHint ? ((plan.hasHint = false), true) : false),
+ () => (plan.estate > 4 ? ((plan.estate -= 1), true) : false),
+ () => (plan.phases > 1 ? ((plan.phases -= 1), true) : false),
+ () => (plan.session > 2 ? ((plan.session -= 1), true) : false),
+ () => (plan.attention > 1 ? ((plan.attention -= 1), true) : false),
+ () => (plan.modules > 0 ? ((plan.modules = 0), true) : false),
+ () => (plan.phases > 0 ? ((plan.phases = 0), true) : false),
+ () => (plan.estate > 0 ? ((plan.estate = 0), true) : false),
+ () => (plan.attention > 0 ? ((plan.attention = 0), true) : false),
+ () => (plan.session > 1 ? ((plan.session -= 1), true) : false),
+ ]
+
+ for (let guard = 0; guard < 80 && totalOf(plan) > rows; guard += 1) {
+ if (!shed.some(step => step())) {
+ break
+ }
+ }
+
+ return plan
+}
+
+/** The pane's body. */
+export function paneView(
+ kit: Kit,
+ state: State,
+ frame: PaneFrame,
+ actions: PaneActions,
+): RenderElement {
+ const { Box, Text } = kit
+ const width = Math.max(20, frame.columns)
+ const snapshot = state.snapshot
+
+ if (snapshot === null) {
+ return (
+ <Box flexDirection="column" paddingRight={1}>
+ <Text bold>modernization</Text>
+ <Text dimColor wrap="wrap">
+ {state.readError !== null
+ ? `could not read the workspace: ${state.readError}`
+ : 'no system found under legacy/ or analysis/ yet. Put the system under legacy/<name>/ and run the preflight command to begin.'}
+ </Text>
+ </Box>
+ )
+ }
+
+ const plan = frame.plan
+
+ return (
+ <Box flexDirection="column" paddingRight={1} rowGap={plan.gap}>
+ {header(kit, snapshot, width, actions)}
+ {estate(kit, snapshot, frame, width)}
+ {plan.phases > 0 ? phases(kit, snapshot, width, plan.phases) : null}
+ {plan.modules > 0 ? modules(kit, snapshot, width, plan.modules) : null}
+ {nextBlock(kit, snapshot, actions, state, width, plan.hasHint)}
+ {plan.attention > 0 ? attention(kit, state, snapshot, width, plan.attention) : null}
+ {session(kit, state, frame, width, plan.session)}
+ </Box>
+ )
+}
+
+/**
+ * The one row that stands where the pane was while it is hidden: what the workspace says in a line, and the
+ * button that brings the pane back. It is drawn in the band above the prompt, which the person can collapse.
+ */
+export function showBar(
+ kit: Pick<Kit, 'Box' | 'Text' | 'Button'>,
+ line: string,
+ width: number,
+ onShow: () => void,
+): RenderElement {
+ const { Box, Text, Button } = kit
+
+ return (
+ // The band draws its own `[-]` collapse control at its right edge: leave it room.
+ <Box justifyContent="space-between" paddingRight={5}>
+ <Text dimColor wrap="truncate-end">{clip(line, Math.max(8, width - 24))}</Text>
+ <Button key="show-pane" hotkey="m" onPress={onShow}>show pane</Button>
+ </Box>
+ )
+}
diff --git a/plugins/code-modernization/hooks/xray/xray.ts b/plugins/code-modernization/hooks/xray/xray.ts
new file mode 100644
index 00000000..93c6bd74
--- /dev/null
+++ b/plugins/code-modernization/hooks/xray/xray.ts
@@ -0,0 +1,263 @@
+import { baseName } from '../paths'
+import { unitOfPath } from '../reader/estate-model'
+import type { Snapshot } from '../reader/progress'
+import type { Rule } from '../reader/rules'
+import { stateWord } from '../map/estate'
+import { baselineKeyOf } from '../reader/uplift'
+import { nodeOfFile, type TopoNode, type Topology } from '../reader/topology'
+
+/**
+ * X-ray reads: when the model reads a legacy file, what the analysis stages
+ * already worked out about that file rides along as context the model reads
+ * and the person never sees. Every line is lifted from an artifact on disk.
+ */
+
+export type XrayRequest = {
+ /** The file read, relative to `legacy/<system>/`. */
+ fileRel: string
+ /** First line read (1-based) and how many, when the read was a window. */
+ offset?: number
+ limit?: number
+}
+
+export type XrayNote = {
+ text: string
+ /** One short line for the status bar. */
+ summary: string
+ rules: number
+ node: string | null
+}
+
+/** Keeps a note well inside the 32,000-character cap a call's context has. */
+const MAX_CHARS = 2400
+const MAX_RULES = 9
+const MAX_NAMES = 8
+
+const some = (names: string[], max = MAX_NAMES): string =>
+ names.length <= max ? names.join(', ') : `${names.slice(0, max).join(', ')} +${names.length - max} more`
+
+const nameOf = (topo: Topology, id: string): string => topo.byId.get(id)?.name ?? id
+
+function edgesOf(topo: Topology, node: TopoNode) {
+ const incoming = topo.edges.filter(edge => edge.target === node.id)
+ const outgoing = topo.edges.filter(edge => edge.source === node.id)
+ const isCode = (kind: string) => kind === 'call' || kind === 'dispatch' || kind === 'uses'
+ const uniq = (ids: string[]) => [...new Set(ids)].map(id => nameOf(topo, id))
+
+ return {
+ callers: uniq(incoming.filter(edge => isCode(edge.kind)).map(edge => edge.source)),
+ callees: uniq(outgoing.filter(edge => isCode(edge.kind)).map(edge => edge.target)),
+ reads: uniq(outgoing.filter(edge => edge.kind === 'read').map(edge => edge.target)),
+ writes: uniq(outgoing.filter(edge => edge.kind === 'write').map(edge => edge.target)),
+ }
+}
+
+const rank = (rule: Rule): number =>
+ (rule.priority === 'P0' ? 0 : rule.priority === 'P1' ? 1 : 2) * 2 + (rule.defect !== undefined ? 0 : 1)
+
+function ruleLine(rule: Rule, base: string): string {
+ const spans = rule.citations
+ .filter(citation => citation.base === base)
+ .slice(0, 2)
+ .map(citation => (citation.from === citation.to ? `L${citation.from}` : `L${citation.from}-${citation.to}`))
+
+ const flags = [
+ rule.defect !== undefined ? 'suspected defect' : '',
+ rule.sme !== undefined ? 'needs SME' : '',
+ rule.confidence !== undefined && rule.confidence !== 'High' ? `${rule.confidence} confidence` : '',
+ ].filter(flag => flag !== '')
+
+ const label = rule.id.startsWith('R-') ? rule.priority || 'rule' : rule.id
+
+ return `- ${label} ${rule.title}${spans.length > 0 ? ` (${spans.join(', ')})` : ''}${flags.length > 0 ? ` [${flags.join('; ')}]` : ''}`
+}
+
+/**
+ * What an uplift already knows about a file: which module it is in, what that module's baseline was on the
+ * source runtime (the failures there are part of the oracle), where the module stands in the working copy, and
+ * which deltas the catalog cites the file under.
+ */
+function upliftXray(snapshot: Snapshot, request: XrayRequest): XrayNote | null {
+ const estate = snapshot.estate
+ const unit = estate !== null ? unitOfPath(estate, null, request.fileRel) : null
+ const deltas = snapshot.uplift?.catalog?.byFileBase.get(baseName(request.fileRel).toLowerCase()) ?? []
+ const row = unit?.dir !== undefined ? (snapshot.uplift?.baseline?.rows.get(baselineKeyOf(unit.dir)) ?? null) : null
+ const module = unit !== null ? snapshot.byNode.get(unit.id) : undefined
+
+ if (deltas.length === 0 && row === null && module === undefined) {
+ return null
+ }
+
+ const lines = [
+ `[x-ray for ${request.fileRel}${unit !== null ? ` · ${unit.dir === '' || unit.dir === undefined ? unit.name : unit.dir}` : ''} · uplift] (from analysis/${snapshot.system}/; facts already established, do not re-derive)`,
+ ]
+
+ if (row !== null) {
+ lines.push(
+ `Baseline on the source runtime: ${row.pass} pass, ${row.fail} fail, ${row.error} error, ${row.skip} skip. What fails there is part of the oracle: reproduce it, do not fix it.`,
+ )
+ }
+
+ if (module !== undefined) {
+ const tests = module.tests
+
+ lines.push(
+ `In the working copy: ${stateWord('uplift', module.state)}${tests !== null ? ` (${tests.tests} tests, ${tests.failures + tests.errors} failing)` : ''}.`,
+ )
+ }
+
+ if (deltas.length > 0) {
+ lines.push(`The delta catalog cites this file under ${some(deltas, 6)}.`)
+ }
+
+ return {
+ text: lines.join('\n'),
+ summary: `x-ray ${baseName(request.fileRel)}: ${deltas.length} delta${deltas.length === 1 ? '' : 's'}${row !== null ? ', baseline' : ''}`,
+ rules: 0,
+ node: unit?.id ?? null,
+ }
+}
+
+/** Builds the note for one read; null when the artifacts know nothing about the file. */
+export function xrayOf(snapshot: Snapshot, request: XrayRequest): XrayNote | null {
+ if (snapshot.track === 'uplift') {
+ return upliftXray(snapshot, request)
+ }
+
+ const base = baseName(request.fileRel).toLowerCase()
+ const topo = snapshot.topology
+ const node = topo !== null ? nodeOfFile(topo, request.fileRel) : null
+ const cited = snapshot.rules?.byFileBase.get(base) ?? []
+
+ if (node === null && cited.length === 0) {
+ return null
+ }
+
+ const lines: string[] = []
+ const head = [`x-ray for ${request.fileRel}`]
+
+ if (node !== null) {
+ head.push(node.name)
+
+ if (node.domain !== undefined) {
+ head.push(node.domain)
+ }
+
+ if (node.loc > 0) {
+ head.push(`${node.loc} lines`)
+ }
+ }
+
+ lines.push(`[${head.join(' · ')}] (from analysis/${snapshot.system}/; facts already established, do not re-derive)`)
+
+ if (topo !== null && node !== null) {
+ const edges = edgesOf(topo, node)
+ const roles: string[] = []
+
+ if (topo.entryPoints.has(node.id)) {
+ roles.push('an entry point')
+ }
+
+ if (topo.deadEnds.has(node.id)) {
+ roles.push('flagged as a dead end by the map')
+ }
+
+ if (roles.length > 0) {
+ lines.push(`Role: ${roles.join(', ')}.`)
+ }
+
+ if (edges.callers.length > 0) {
+ lines.push(`Reached from: ${some(edges.callers)}.`)
+ } else if (!topo.entryPoints.has(node.id) && node.kind === 'module') {
+ lines.push('Reached from: nothing the map found (check dynamic dispatch before calling it dead).')
+ }
+
+ if (edges.callees.length > 0) {
+ lines.push(`Calls: ${some(edges.callees)}.`)
+ }
+
+ if (edges.reads.length > 0) {
+ lines.push(`Reads: ${some(edges.reads)}.`)
+ }
+
+ if (edges.writes.length > 0) {
+ lines.push(`Writes: ${some(edges.writes)}.`)
+ }
+
+ const flows = topo.flows.filter(flow => flow.steps.some(step => step.nodes.includes(node.id)))
+
+ if (flows.length > 0) {
+ lines.push(`Business flows through it: ${some(flows.map(flow => `"${flow.name}"`), 4)}.`)
+ }
+ }
+
+ if (cited.length > 0) {
+ const p0 = cited.filter(rule => rule.priority === 'P0').length
+ const from = request.offset
+ const to = from !== undefined && request.limit !== undefined ? from + request.limit - 1 : undefined
+
+ const inWindow =
+ from !== undefined && to !== undefined
+ ? cited.filter(rule =>
+ rule.citations.some(
+ citation => citation.base === base && citation.from <= to && citation.to >= from,
+ ),
+ )
+ : []
+
+ const shown = (inWindow.length > 0 ? inWindow : [...cited]).sort((a, b) => rank(a) - rank(b)).slice(0, MAX_RULES)
+
+ lines.push(
+ `Business rules citing this file: ${cited.length}${p0 > 0 ? ` (${p0} P0)` : ''}, in analysis/${snapshot.system}/BUSINESS_RULES.md.${inWindow.length > 0 ? ` In the lines just read (${from}-${to}):` : ' Highest priority first:'}`,
+ )
+
+ for (const rule of shown) {
+ lines.push(ruleLine(rule, base))
+ }
+
+ const rest = (inWindow.length > 0 ? inWindow.length : cited.length) - shown.length
+
+ if (rest > 0) {
+ lines.push(`- and ${rest} more.`)
+ }
+
+ const verdicts = cited
+ .map(rule => ({ rule, review: snapshot.reviews[rule.id] }))
+ .filter(entry => entry.review !== undefined && entry.review.verdict !== 'confirmed')
+
+ if (verdicts.length > 0) {
+ lines.push(
+ `A reviewer disputed: ${some(verdicts.map(entry => `${entry.rule.id} (${entry.review?.verdict})`), 6)}. Do not treat those as settled.`,
+ )
+ }
+ }
+
+ const unitId = node?.id ?? (snapshot.estate !== null ? unitOfPath(snapshot.estate, topo, request.fileRel)?.id : undefined)
+
+ if (unitId !== undefined) {
+ const module = snapshot.byNode.get(unitId)
+
+ if (module !== undefined) {
+ const tests = module.tests
+
+ lines.push(
+ `Already transformed at ${module.path}: ${module.state.replace('-', ' ')}${tests !== null ? `, ${tests.tests - tests.failures - tests.errors}/${tests.tests} tests passing` : ''}.`,
+ )
+ }
+ }
+
+ let text = lines.join('\n')
+
+ if (text.length > MAX_CHARS) {
+ text = `${text.slice(0, MAX_CHARS - 40).replace(/\n[^\n]*$/, '')}\n- (note trimmed)`
+ }
+
+ const callers = topo !== null && node !== null ? edgesOf(topo, node).callers.length : 0
+
+ return {
+ text,
+ summary: `x-ray ${node?.name ?? baseName(request.fileRel)}: ${cited.length} rule${cited.length === 1 ? '' : 's'}${callers > 0 ? `, ${callers} caller${callers === 1 ? '' : 's'}` : ''}`,
+ rules: cited.length,
+ node: node?.id ?? null,
+ }
+}
diff --git a/plugins/code-modernization/tests/fixtures/inputs.ts b/plugins/code-modernization/tests/fixtures/inputs.ts
new file mode 100644
index 00000000..ad1bd6e1
--- /dev/null
+++ b/plugins/code-modernization/tests/fixtures/inputs.ts
@@ -0,0 +1,55 @@
+import type { RenderInput, SessionStartInput } from 'claude-code'
+
+export const SESSION: SessionStartInput = { surface: 'terminal', isInteractive: true, cwd: '/work' }
+
+export const HINT: RenderInput<'PromptHint'> = {
+ component: 'PromptHint',
+ surface: 'terminal',
+ requestId: 'hint',
+ viewport: { columns: 180, rows: 48, isFullscreen: true },
+ props: { isDraft: false, isWorking: false, hint: '' },
+}
+
+export const MAIN_SCREEN_HINT: RenderInput<'PromptHint'> = {
+ ...HINT,
+ viewport: { columns: 180, rows: 48, isFullscreen: false },
+}
+
+export const PANE: RenderInput<'Pane'> = {
+ component: 'Pane',
+ surface: 'terminal',
+ requestId: 'modernize',
+ viewport: { columns: 180, rows: 48, isFullscreen: true },
+ props: {
+ title: 'Modernization',
+ isFocused: false,
+ bodyColumns: 72,
+ placement: 'dock',
+ scroll: { offset: 0, bodyRows: 44 },
+ view: {},
+ },
+}
+
+export const SIGN_PANE: RenderInput<'Pane'> = { ...PANE, requestId: 'modernize-sign', props: { ...PANE.props, placement: 'inline' } }
+
+export const BAND: RenderInput<'AbovePrompt'> = {
+ component: 'AbovePrompt',
+ surface: 'terminal',
+ requestId: 'band',
+ viewport: { columns: 180, rows: 48, isFullscreen: true },
+ props: {
+ hasSurvey: false,
+ isWorking: false,
+ maxRows: 20,
+ bodyColumns: 100,
+ scroll: { offset: 0, bodyRows: 19 },
+ view: {},
+ },
+}
+
+export const command = (name: string, args = '') => ({
+ command: name,
+ args,
+ origin: { kind: 'composer' as const },
+ presentation: { isFullscreen: true, columns: 180 },
+})
diff --git a/plugins/code-modernization/tests/fixtures/stacks.ts b/plugins/code-modernization/tests/fixtures/stacks.ts
new file mode 100644
index 00000000..15f60e21
--- /dev/null
+++ b/plugins/code-modernization/tests/fixtures/stacks.ts
@@ -0,0 +1,207 @@
+import { norm } from '../../hooks/paths'
+import type { ReaderFs } from '../../hooks/reader/fs'
+
+/**
+ * Workspaces in the shape the plugin's commands leave, in stacks that are not COBOL: a Maven
+ * project being uplifted, a PHP shop with no map, a .NET solution, a Node monorepo, a greenfield
+ * rebuild, and a legacy tree nobody has analysed yet. Sizes are the length of the text given.
+ */
+
+/** A file tree in memory, read the way the reader reads `$.fs`. */
+export function memoryFs(files: Readonly<Record<string, string>>, mtimes: Readonly<Record<string, number>> = {}): ReaderFs {
+ const dirs = new Set<string>([''])
+
+ for (const path of Object.keys(files)) {
+ const parts = path.split('/')
+
+ for (let index = 1; index < parts.length; index += 1) {
+ dirs.add(parts.slice(0, index).join('/'))
+ }
+ }
+
+ const at = (path: string) => mtimes[path] ?? 1_000
+
+ return {
+ read: async path => {
+ const text = files[norm(path)]
+
+ if (text === undefined) {
+ throw new Error(`ENOENT: ${path}`)
+ }
+
+ return text
+ },
+ exists: async path => files[norm(path)] !== undefined || dirs.has(norm(path)),
+ stat: async path => {
+ const key = norm(path)
+ const text = files[key]
+
+ if (text !== undefined) {
+ return { kind: 'file' as const, size: text.length, mtimeMs: at(key) }
+ }
+
+ if (dirs.has(key)) {
+ return { kind: 'dir' as const, size: 0, mtimeMs: at(key) }
+ }
+
+ throw new Error(`ENOENT: ${path}`)
+ },
+ list: async path => {
+ const dir = norm(path)
+ const names = new Map<string, 'file' | 'dir'>()
+
+ for (const file of Object.keys(files)) {
+ if (dir !== '' && !file.startsWith(`${dir}/`)) {
+ continue
+ }
+
+ const rest = dir === '' ? file : file.slice(dir.length + 1)
+ const name = rest.split('/')[0] ?? ''
+
+ names.set(name, rest.includes('/') ? 'dir' : 'file')
+ }
+
+ return [...names.entries()].sort().map(([name, kind]) => ({
+ name,
+ kind,
+ size: kind === 'file' ? (files[dir === '' ? name : `${dir}/${name}`]?.length ?? 0) : 0,
+ }))
+ },
+ }
+}
+
+const code = (bytes: number) => 'x'.repeat(bytes)
+
+const junit = (tests: number, failures: number, errors: number, skipped: number) =>
+ `<testsuite name="s" tests="${tests}" failures="${failures}" errors="${errors}" skipped="${skipped}"></testsuite>`
+
+// ---------------------------------------------------------------- Java / Maven uplift
+
+/**
+ * `shop`: a three-module Maven system moved to a newer JDK. The baseline is a per-module table; two modules
+ * were tested on the new runtime (`shop-core` reproduces its baseline, `shop-web` has three new failures).
+ */
+export const MAVEN_UPLIFT: Record<string, string> = {
+ 'legacy/shop/pom.xml': '<project/>',
+ 'legacy/shop/shop-core/pom.xml': '<project/>',
+ 'legacy/shop/shop-core/src/main/java/Ledger.java': code(4000),
+ 'legacy/shop/shop-web/pom.xml': '<project/>',
+ 'legacy/shop/shop-web/src/main/java/Page.java': code(6000),
+ 'legacy/shop/shop-batch/pom.xml': '<project/>',
+ 'legacy/shop/shop-batch/src/main/java/Nightly.java': code(2000),
+ 'analysis/shop/PREFLIGHT.md': '# Preflight',
+ 'analysis/shop/DELTA_CATALOG.md': [
+ '# Delta catalog',
+ '',
+ 'The survey found **12 distinct deltas** in this code.',
+ '',
+ '| Delta | What breaks | Where |',
+ '|---|---|---|',
+ '| **D08** | `Ledger` reflects into `java.base` | `shop-core/src/main/java/Ledger.java:41` |',
+ '| **D15** | Mapped buffers | `shop-core/src/main/java/Ledger.java:77-90`, `shop-web/src/main/java/Page.java:12` |',
+ '',
+ ].join('\n'),
+ 'analysis/shop/BASELINE.md': [
+ '# BASELINE',
+ '',
+ '**78 test results** in 3 modules: error = 0, fail = 1, pass = 75, skip = 2',
+ '',
+ '| Module | pass | fail | error | skip |',
+ '|---|---:|---:|---:|---:|',
+ '| `shop-core` | 40 | 1 | 0 | 2 |',
+ '| `shop-web` | 25 | 0 | 0 | 0 |',
+ '| `shop-batch` | 10 | 0 | 0 | 0 |',
+ ].join('\n'),
+ 'analysis/shop/PLAYBOOK.md': '# Playbook',
+ 'modernized/shop-uplifted/pom.xml': '<project/>',
+ 'modernized/shop-uplifted/shop-core/pom.xml': '<project/>',
+ 'modernized/shop-uplifted/shop-core/src/main/java/Ledger.java': code(4010),
+ 'modernized/shop-uplifted/shop-core/target/surefire-reports/TEST-Ledger.xml': junit(43, 1, 0, 2),
+ 'modernized/shop-uplifted/shop-web/pom.xml': '<project/>',
+ 'modernized/shop-uplifted/shop-web/src/main/java/Page.java': code(6000),
+ 'modernized/shop-uplifted/shop-web/target/surefire-reports/TEST-Page.xml': junit(25, 3, 0, 0),
+ 'modernized/shop-uplifted/shop-batch/pom.xml': '<project/>',
+ 'modernized/shop-uplifted/shop-batch/src/main/java/Nightly.java': code(2050),
+}
+
+// ---------------------------------------------------------------------- PHP, no map
+
+const phpPages = Object.fromEntries(
+ Array.from({ length: 24 }, (_, index) => [`legacy/webshop/catalog/page${index}.php`, code(300 + index * 40)]),
+)
+
+/** `webshop`: a PHP shop with no build files and no map, one file per unit; only the preflight has run. */
+export const PHP_NO_MAP: Record<string, string> = {
+ ...phpPages,
+ 'legacy/webshop/includes/db.php': code(2500),
+ 'legacy/webshop/includes/cart.php': code(3100),
+ 'legacy/webshop/index.php': code(900),
+ 'legacy/webshop/images/logo.png': code(50_000),
+ 'legacy/webshop/README.md': code(4000),
+ 'analysis/webshop/PREFLIGHT.md': '# Preflight',
+}
+
+// ----------------------------------------------------------------------------- .NET
+
+/** `ledger`: a .NET solution rewritten module by module; the core module's tests left a .trx report. */
+export const DOTNET_REWRITE: Record<string, string> = {
+ 'legacy/ledger/Ledger.sln': 'sln',
+ 'legacy/ledger/Ledger.Core/Ledger.Core.csproj': '<Project/>',
+ 'legacy/ledger/Ledger.Core/Accounts.cs': code(5000),
+ 'legacy/ledger/Ledger.Core/Interest.vb': code(3000),
+ 'legacy/ledger/Ledger.Web/Ledger.Web.csproj': '<Project/>',
+ 'legacy/ledger/Ledger.Web/Default.aspx': code(2000),
+ 'analysis/ledger/ASSESSMENT.md': '# Assessment',
+ 'modernized/ledger/Ledger.Core/src/main/Accounts.cs': code(4800),
+ 'modernized/ledger/Ledger.Core/tests/AccountsTests.cs': code(900),
+ 'modernized/ledger/Ledger.Core/TestResults/run.trx':
+ '<TestRun><ResultSummary><Counters total="14" executed="14" passed="14" failed="0" error="0" timeout="0" aborted="0" inconclusive="0" notExecuted="0"/></ResultSummary></TestRun>',
+ 'modernized/ledger/Ledger.Core/TRANSFORMATION_NOTES.md': '# Notes\n\n## Follow-ups\n- none\n',
+}
+
+// ------------------------------------------------------------------- Node monorepo
+
+/** `portal`: a Node monorepo; a module of the rewrite is tested by a runner that leaves no report file. */
+export const NODE_REWRITE: Record<string, string> = {
+ 'legacy/portal/package.json': '{"workspaces":["packages/*"]}',
+ 'legacy/portal/packages/auth/package.json': '{}',
+ 'legacy/portal/packages/auth/index.js': code(3000),
+ 'legacy/portal/packages/billing/package.json': '{}',
+ 'legacy/portal/packages/billing/index.js': code(9000),
+ 'legacy/portal/packages/ui/package.json': '{}',
+ 'legacy/portal/packages/ui/index.js': code(5000),
+ 'analysis/portal/ASSESSMENT.md': '# Assessment',
+ 'modernized/portal/billing/src/main.ts': code(2000),
+ 'modernized/portal/billing/tests/billing.test.ts': code(800),
+}
+
+// -------------------------------------------------------------------- reimagine
+
+/** `crm`: a greenfield rebuild with two scaffolded services; only one has acceptance tests. */
+export const REIMAGINE: Record<string, string> = {
+ 'legacy/crm/app.pl': code(4000),
+ 'legacy/crm/lib/Contact.pm': code(3000),
+ 'analysis/crm/AI_NATIVE_SPEC.md': '# Spec',
+ 'analysis/crm/REIMAGINED_ARCHITECTURE.md': '# Architecture',
+ 'modernized/crm-reimagined/CLAUDE.md': '# Context',
+ 'modernized/crm-reimagined/accounts/src/main.py': code(1200),
+ 'modernized/crm-reimagined/accounts/tests/test_accounts.py': code(600),
+ 'modernized/crm-reimagined/accounts/pytest.xml': junit(6, 0, 0, 0),
+ 'modernized/crm-reimagined/billing/src/main.py': code(900),
+}
+
+// ------------------------------------------------------------ legacy, not analysed
+
+/** `ops`: a legacy system somebody dropped in `legacy/`; nothing has been run on it. */
+export const LEGACY_ONLY: Record<string, string> = {
+ 'legacy/ops/jobs/nightly.cbl': code(4000),
+ 'legacy/ops/jobs/monthly.cbl': code(2500),
+ 'legacy/ops/copy/rates.cpy': code(700),
+}
+
+// ------------------------------------------------------------------ bigger trees
+
+/** 620 Python files in six packages under `src/`, no build files: too many for a tile each. */
+export const PYTHON_BIG: Record<string, string> = Object.fromEntries(
+ Array.from({ length: 620 }, (_, index) => [`legacy/erp/src/pkg${index % 6}/mod${index}.py`, code(200 + (index % 17) * 30)]),
+)
diff --git a/plugins/code-modernization/tests/fixtures/workspace.ts b/plugins/code-modernization/tests/fixtures/workspace.ts
new file mode 100644
index 00000000..156f73fd
--- /dev/null
+++ b/plugins/code-modernization/tests/fixtures/workspace.ts
@@ -0,0 +1,306 @@
+/**
+ * A small workspace in the shape the plugin's commands write: one system,
+ * `billing`, mapped, with rules, a brief, and one transformed module.
+ */
+
+export const TOPOLOGY = JSON.stringify({
+ system: 'Billing',
+ root: {
+ id: 'sys',
+ name: 'Billing',
+ kind: 'system',
+ children: [
+ {
+ id: 'dom:interest',
+ name: 'D1 Interest',
+ kind: 'domain',
+ children: [
+ { id: 'INTCALC', name: 'INTCALC', kind: 'module', language: 'cobol', loc: 600, file: 'app/cbl/INTCALC.cbl' },
+ { id: 'ds:RATES', name: 'RATES', kind: 'datastore', store: 'vsam' },
+ ],
+ },
+ {
+ id: 'dom:accounts',
+ name: 'D2 Accounts',
+ kind: 'domain',
+ children: [
+ { id: 'ACCTUPD', name: 'ACCTUPD', kind: 'module', language: 'cobol', loc: 900, file: 'app/cbl/ACCTUPD.cbl' },
+ { id: 'ACCTVIEW', name: 'ACCTVIEW', kind: 'module', language: 'cobol', loc: 300, file: 'app/cbl/ACCTVIEW.cbl' },
+ ],
+ },
+ ],
+ },
+ edges: [
+ { source: 'ACCTUPD', target: 'INTCALC', kind: 'call' },
+ { source: 'INTCALC', target: 'ds:RATES', kind: 'read' },
+ { source: 'INTCALC', target: 'ds:ACCOUNTS', kind: 'write' },
+ ],
+ entryPoints: ['ACCTUPD'],
+ deadEnds: ['ACCTVIEW'],
+ flows: [{ name: 'Month-end interest', persona: 'Cardholder', steps: [{ label: 'Interest runs', nodes: ['INTCALC'] }] }],
+})
+
+/**
+ * The layout the plugin's own command wrote in practice: ids that carry a domain (`BR-D7-09`),
+ * the priority in a backticked header line, list-style Given/When/Then, and legend and appendix
+ * tables that are not rules.
+ */
+export const RULES_BR = `# Business Rules — CardDemo
+
+## How to read this
+
+| Element | Meaning |
+|---|---|
+| **ID** | \`BR-<domain>-<n>\` |
+| **Priority** | P0 money movement |
+
+## D7 Interest & Fee Accrual
+
+#### BR-D7-09 · Monthly interest per transaction-category balance
+
+\`P0\` · Calculation · confidence High · \`app/cbl/CBACT04C.cbl:462-470\`
+
+For each balance bucket, monthly interest equals balance times rate divided by 1200.
+
+- **Given** — A balance of 1250.00 at rate 15.00
+- **When** — The interest batch processes that row
+- **Then** — Interest is 15.62 (truncated, NOT rounded)
+
+**Edge cases**
+
+- COMPUTE has no ROUNDED clause
+
+> ⚠️ **Suspected defect** — Truncation where most products round half-up.
+
+---
+
+#### BR-D7-10 · Interest statement line
+
+\`P2\` · Lifecycle · confidence Medium · \`app/cbl/CBSTM03A.cbl:10-12\`
+
+The statement prints the interest line.
+
+- **Given** — A posted interest amount
+- **When** — The statement is produced
+- **Then** — The line shows the amount
+
+> ❓ **SME question** — Should zero interest print?
+
+## Appendix A — Suspected defects
+
+| **BR-D7-09** | truncation | \`app/cbl/CBACT04C.cbl:462\` |
+`
+
+/**
+ * The labelled-fields layout a later model wrote: `### RULE-007: title`, `**Category:**`, `**Priority:**`,
+ * `**Source:**`, `**Plain English:**`, a fenced Given/When/Then block, `**Edge cases handled:**`,
+ * `**Suspected defect:**`, and the SME question inside the confidence line. A summary table lists every
+ * rule up front and is not a set of rules.
+ */
+export const RULES_LABELLED = `# Business Rules — carddemo
+
+## Summary
+
+| ID | Name | Category | Priority | Source | Confidence |
+|---|---|---|---|---|---|
+| RULE-007 | Monthly interest per transaction category | Calculation | P0 | \`app/cbl/CBACT04C.cbl:188-222, 415-470\` | High |
+
+## Calculation rules
+
+### RULE-007: Monthly interest per transaction category using disclosure-group rate
+**Category:** Calculation
+**Priority:** P0
+**Source:** \`app/cbl/CBACT04C.cbl:188-222, 415-470\`
+**Plain English:** The monthly interest is the balance times the annual rate divided by 1200, truncated to cents.
+**Specification:**
+\`\`\`
+Given Account in group 'GOLD' has TRAN-CAT-BAL $1,250.00 and DIS-INT-RATE 18.50
+When CBACT04C processes that category record
+Then WS-MONTHLY-INT = 1250.00 * 18.50 / 1200 = $19.27 (truncated not rounded)
+And If the group is not in DISCGRP, the rate is read from 'DEFAULT'
+\`\`\`
+**Parameters:** Divisor 1200
+**Edge cases handled:**
+ - No ROUNDED clause on the COMPUTE; result is truncated to cents
+ - Negative balances produce negative interest
+**Confidence:** High
+
+### RULE-004: Pending authorization summary counters updated per decision
+**Category:** Lifecycle
+**Priority:** P0
+**Source:** \`app/app-authorization-ims-db2-mq/cbl/COPAUA0C.cbl:700-720\`
+**Plain English:** Each decision updates the pending-authorization counters.
+**Specification:**
+\`\`\`
+Given A declined authorization
+When The decision is recorded
+Then The declined-amount total is increased
+\`\`\`
+**Parameters:** none
+**Edge cases handled:**
+ - none
+**Suspected defect:** Line 821 adds a stale amount to the declined total.
+**Confidence:** Medium — SME question: Should declined-amount accumulate the current request's amount?
+
+### RULE-090: Statement footer prints the page count
+**Category:** Policy
+**Priority:** P2
+**Source:** \`app/cbl/CBSTM03A.cbl:10-12\`
+**Plain English:** The footer shows the page count.
+**Specification:**
+\`\`\`
+Given A statement of two pages
+When The footer prints
+Then It reads page 2 of 2
+\`\`\`
+**Parameters:** none
+**Edge cases handled:**
+ - none
+**Confidence:** High
+
+## Appendix A — Rejected candidates
+
+### RULE-999: Not a rule
+**Priority:** P0
+`
+
+export const RULES = `# Business Rules — Billing
+
+# P0 rules
+
+## D1 Interest
+
+### P0-001 · Monthly interest is truncated, not rounded
+
+\`legacy/billing/app/cbl/INTCALC.cbl:462-470\` · Calculation · confidence **High**
+
+Monthly interest equals balance times rate over 1200, truncated to cents.
+
+> **Given** A balance of $1,250.00 at 18.50%
+> **When** The interest batch runs
+> **Then** Interest is $19.27, not $19.28
+
+**Edge cases**
+
+- A zero rate skips the account
+
+> ⚠️ **Suspected defect** — Truncation where most products round half-up.
+
+### P0-002 · Missing rate row aborts the run
+
+\`legacy/billing/app/cbl/INTCALC.cbl:415-460\` · Calculation · confidence **Medium**
+
+If no rate row exists the whole batch abends.
+
+> **Given** An account with no rate row
+> **When** The batch reads the rate file
+> **Then** The program abends with code 999
+
+> ❓ **SME** — Should the account be skipped instead?
+
+## D2 Accounts
+
+### P0-003 · Account update checks for concurrent change
+
+\`legacy/billing/app/cbl/ACCTUPD.cbl:100-140\` · Validation · confidence **High**
+
+An update is refused when the record changed since it was read.
+
+> **Given** Two operators on one account
+> **When** The second saves
+> **Then** The save is refused
+
+# P1 rules
+
+## D2 Accounts
+
+| Rule | Given / When / Then | Source | Flags |
+|---|---|---|---|
+| **View shows masked id**<br/>Policy | **G** An operator opens an account **W** The screen draws **T** The id is masked | \`legacy/billing/app/cbl/ACCTVIEW.cbl:50-60\` | |
+
+# Appendix — rules rejected at citation verification
+
+| Rule | Why |
+|---|---|
+| **Not a rule** | rejected |
+`
+
+export const BRIEF_UNSIGNED = `# Modernization Brief — Billing → Java / Spring
+
+## 3. Phased Sequence
+
+### Phase 1 — Interest pilot (D1) · **Size M** · Risk **Medium**
+
+Scope: INTCALC.
+
+Exit criteria:
+
+- [ ] All P0 interest rules proven equivalent against recorded traces.
+- [ ] Golden-master diff is clean on the full fixture set.
+
+### Phase 2 — Accounts (D2) · **Size L** · Risk **High**
+
+Scope: ACCTUPD and ACCTVIEW.
+
+Exit criteria:
+
+- [ ] Concurrency rule proven under load.
+
+## 7. Open Questions
+
+- [ ] Who owns the rate table?
+
+## 8. Approval Block
+
+\`\`\`
+Approved by: ________________
+Date: __________
+
+Approval covers: [ ] Phase 1 only [ ] Full plan
+\`\`\`
+`
+
+export const BRIEF_SIGNED = BRIEF_UNSIGNED.replace('Approved by: ________________', 'Approved by: VP Engineering')
+ .replace('Date: __________', 'Date: 2026-09-15')
+ .replace('[ ] Phase 1 only', '[X] Phase 1 only')
+
+export const NOTES_REVIEWED = `# Transformation Notes — INTCALC
+
+## Behaviour mapping
+
+...
+
+## Follow-ups for Phase 2
+
+- Rate cache
+
+## Architecture review
+
+Reviewed 2026-09-15. HIGH-1 applied.
+`
+
+export const surefire = (tests: number, failures = 0, skipped = 0) =>
+ `<?xml version="1.0"?>\n<testsuite name="x" tests="${tests}" errors="0" skipped="${skipped}" failures="${failures}"></testsuite>`
+
+/** Discovery done, brief signed, INTCALC transformed and reviewed. */
+export const FULL: Record<string, string> = {
+ 'analysis/billing/PREFLIGHT.md': '# Preflight',
+ 'analysis/billing/ASSESSMENT.md': '# Assessment',
+ 'analysis/billing/topology.json': TOPOLOGY,
+ 'analysis/billing/BUSINESS_RULES.md': RULES,
+ 'analysis/billing/MODERNIZATION_BRIEF.md': BRIEF_SIGNED,
+ 'legacy/billing/app/cbl/INTCALC.cbl': Array.from({ length: 600 }, (_, i) => ` LINE ${i + 1}.`).join('\n'),
+ 'legacy/billing/app/cbl/ACCTUPD.cbl': ' IDENTIFICATION DIVISION.',
+ 'legacy/billing/app/cbl/ACCTVIEW.cbl': ' IDENTIFICATION DIVISION.',
+ 'modernized/billing/INTCALC/src/main/java/Interest.java': 'class Interest {}',
+ 'modernized/billing/INTCALC/src/test/java/InterestTest.java': 'class InterestTest {}',
+ 'modernized/billing/INTCALC/TRANSFORMATION_NOTES.md': NOTES_REVIEWED,
+ 'modernized/billing/INTCALC/target/surefire-reports/TEST-InterestTest.xml': surefire(12),
+}
+
+/** Discovery done and a brief written, not yet signed; nothing transformed. */
+export const UNSIGNED: Record<string, string> = Object.fromEntries(
+ Object.entries({ ...FULL, 'analysis/billing/MODERNIZATION_BRIEF.md': BRIEF_UNSIGNED }).filter(
+ ([path]) => !path.startsWith('modernized/'),
+ ),
+)
diff --git a/plugins/code-modernization/tests/fixtures/world.ts b/plugins/code-modernization/tests/fixtures/world.ts
new file mode 100644
index 00000000..076c7879
--- /dev/null
+++ b/plugins/code-modernization/tests/fixtures/world.ts
@@ -0,0 +1,259 @@
+import type { On, RenderElement, RenderNode } from 'claude-code'
+
+/**
+ * The world beneath the plugin, in memory: a file tree the `$.fs` calls are
+ * answered from, and a record of everything the plugin asked the engine to do.
+ */
+export type World = {
+ files: Map<string, string>
+ mtimes: Map<string, number>
+ writes: { path: string; text: string }[]
+ opened: { id: string; focus: boolean }[]
+ closed: string[]
+ logs: string[]
+ toasts: string[]
+ statuses: (string | undefined)[]
+ blits: number
+ invalidations: number
+ fills: string[]
+ commands: string[]
+ aborted: string[]
+ /** Every path the plugin asked the file system about, as it arrived. */
+ asked: string[]
+ /** Replaces a file's text as something outside the engine would, moving its mtime on. */
+ put: (path: string, text: string) => void
+}
+
+export const CWD = '/work'
+
+const relOf = (path: string) => (path.startsWith(`${CWD}/`) ? path.slice(CWD.length + 1) : path.replace(/^\.\//, ''))
+
+/** Seats the in-memory world beneath the plugin. */
+export function worldOf(on: On, files: Readonly<Record<string, string>>, env: Readonly<Record<string, string>> = {}): World {
+ let tick = 1_000
+
+ const world: World = {
+ files: new Map(Object.entries(files)),
+ mtimes: new Map(Object.keys(files).map(path => [path, 1_000])),
+ writes: [],
+ opened: [],
+ closed: [],
+ logs: [],
+ toasts: [],
+ statuses: [],
+ blits: 0,
+ invalidations: 0,
+ fills: [],
+ commands: [],
+ aborted: [],
+ asked: [],
+ put: (path, text) => {
+ tick += 1_000
+ world.files.set(path, text)
+ world.mtimes.set(path, tick)
+ },
+ }
+
+ const isDir = (path: string) => [...world.files.keys()].some(file => file.startsWith(`${path}/`))
+
+ on('fs.read', ($, e) => {
+ world.asked.push(`read ${e.path}`)
+
+ const text = world.files.get(relOf(e.path))
+
+ return text === undefined ? { deny: `ENOENT: ${e.path}` } : { value: text }
+ })
+
+ on('fs.exists', ($, e) => {
+ world.asked.push(`exists ${e.path}`)
+
+ return { value: world.files.has(relOf(e.path)) || isDir(relOf(e.path)) }
+ })
+
+ on('fs.stat', ($, e) => {
+ const path = relOf(e.path)
+ const text = world.files.get(path)
+
+ if (text !== undefined) {
+ return { value: { kind: 'file' as const, size: text.length, mtimeMs: world.mtimes.get(path) ?? 0 } }
+ }
+
+ return isDir(path) ? { value: { kind: 'dir' as const, size: 0, mtimeMs: 0 } } : { deny: `ENOENT: ${e.path}` }
+ })
+
+ on('fs.list', ($, e) => {
+ world.asked.push(`list ${e.path}`)
+
+ const dir = relOf(e.path)
+ const names = new Map<string, 'file' | 'dir'>()
+
+ for (const file of world.files.keys()) {
+ if (!file.startsWith(`${dir}/`)) {
+ continue
+ }
+
+ const rest = file.slice(dir.length + 1)
+ const name = rest.split('/')[0] ?? ''
+
+ names.set(name, rest.includes('/') ? 'dir' : 'file')
+ }
+
+ return {
+ value: [...names.entries()].sort().map(([name, kind]) => ({
+ name,
+ kind,
+ size: kind === 'file' ? (world.files.get(`${dir}/${name}`)?.length ?? 0) : 0,
+ })),
+ }
+ })
+
+ on('fs.write', ($, e) => {
+ world.writes.push({ path: relOf(e.path), text: e.text })
+ world.put(relOf(e.path), e.text)
+
+ return { value: undefined }
+ })
+
+ on('env.get', ($, e) => ({ value: env[e.name] }))
+ on('store.get', () => ({ value: undefined }))
+ on('store.set', () => ({ value: undefined }))
+
+ on('command.register', ($, e) => {
+ world.commands.push(e.name)
+
+ return { value: { command: e.name } }
+ })
+
+ on('ui.open', ($, e) => {
+ world.opened.push({ id: e.id, focus: e.focus === true })
+
+ return { value: undefined }
+ })
+
+ on('ui.close', ($, e) => {
+ world.closed.push(e.id)
+
+ return { value: undefined }
+ })
+
+ on('ui.log', ($, e) => {
+ world.logs.push(e.text)
+
+ return { value: undefined }
+ })
+
+ on('ui.toast', ($, e) => {
+ world.toasts.push(e.text)
+
+ return { value: undefined }
+ })
+
+ on('ui.status', ($, e) => {
+ world.statuses.push(e.text)
+
+ return { value: undefined }
+ })
+
+ on('ui.invalidate', () => {
+ world.invalidations += 1
+
+ return { value: undefined }
+ })
+
+ on('ui.blit', () => {
+ world.blits += 1
+
+ return { value: {} }
+ })
+
+ on('prompt.fill', ($, e) => {
+ world.fills.push(e.text)
+
+ return { isFilled: true }
+ })
+
+ on('turn.abort', ($, e) => {
+ world.aborted.push(e.turnId)
+
+ return { value: undefined }
+ })
+
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('turn.start', ($, e) => ({ turnId: e.turnId }))
+ on('turn.complete', ($, e) => ({ text: e.answer }))
+ on('prompt.submit', ($, e) => ({ text: e.text, ...(e.context !== undefined && { context: e.context }) }))
+
+ return world
+}
+
+/** Every string a drawn tree holds, in drawing order. */
+export function stringsOf(node: RenderNode | RenderElement | null | undefined): string[] {
+ if (node === null || node === undefined) {
+ return []
+ }
+
+ if (typeof node === 'string') {
+ return [node]
+ }
+
+ const own: string[] = []
+ const props = (node as { props?: Record<string, unknown> }).props
+
+ if (node.type === 'Button' && typeof props?.label === 'string') {
+ own.push(props.label)
+ }
+
+ if (node.type === 'Code' && typeof props?.source === 'string') {
+ own.push(props.source)
+ }
+
+ if (node.type === 'Input') {
+ own.push(`${typeof props?.label === 'string' ? props.label : ''}: ${typeof props?.value === 'string' ? props.value : ''}`)
+ }
+
+ const children = (node as { children?: readonly RenderNode[] }).children ?? []
+
+ return [...own, ...children.flatMap(child => stringsOf(child))]
+}
+
+/** A drawn tree as one string. */
+export const textOf = (node: RenderNode | RenderElement | null | undefined): string => stringsOf(node).join('')
+
+/** Every element of `type` in a drawn tree. */
+export function elementsOf(node: RenderNode | RenderElement | null | undefined, type: string): RenderElement[] {
+ if (node === null || node === undefined || typeof node === 'string') {
+ return []
+ }
+
+ const children = (node as { children?: readonly RenderNode[] }).children ?? []
+
+ return [...(node.type === type ? [node] : []), ...children.flatMap(child => elementsOf(child, type))]
+}
+
+/** How many terminal rows a drawn tree takes, counting each Text as one row (the pane wraps its own). */
+export function rowsOf(tree: unknown): number {
+ const node = tree as { type?: string; props?: Record<string, unknown>; children?: unknown[] } | string | null | undefined
+
+ if (node === null || node === undefined || typeof node === 'string') {
+ return 0
+ }
+
+ if (node.type === 'Text' || node.type === 'Button' || node.type === 'Input') {
+ return 1
+ }
+
+ if (node.type === 'Raster') {
+ return Number(node.props?.rows ?? 0)
+ }
+
+ if (node.type === 'Code') {
+ return String(node.props?.source ?? '').split('\n').length
+ }
+
+ const kids = (node.children ?? []).map(rowsOf)
+ const isRow = node.type === 'Box' && node.props?.flexDirection !== 'column'
+ const gap = !isRow ? Number(node.props?.rowGap ?? 0) * Math.max(0, kids.filter(count => count > 0).length - 1) : 0
+ const inner = isRow ? Math.max(0, ...kids) : kids.reduce((a, b) => a + b, 0)
+
+ return inner + gap + Number(node.props?.marginTop ?? 0)
+}
diff --git a/plugins/code-modernization/tests/logic.test.ts b/plugins/code-modernization/tests/logic.test.ts
new file mode 100644
index 00000000..f4c258e9
--- /dev/null
+++ b/plugins/code-modernization/tests/logic.test.ts
@@ -0,0 +1,570 @@
+import { describe, expect, test } from 'claude-code/testing'
+
+import {
+ announceThresholdOf,
+ lineOf,
+ missingPathOf,
+ newFleet,
+ normalizeFailure,
+ noteCall,
+ noteDone,
+ noteFailure,
+ prune,
+ subjectOf,
+ tallyOf,
+} from '../hooks/fleet/fleet'
+import { paint, tilesOf } from '../hooks/map/estate'
+import { base64Of, codePointOf, mix, packCells } from '../hooks/map/raster'
+import { layout, layoutGroups } from '../hooks/map/treemap'
+import { absOf, isUnder, relTo, resolveDots } from '../hooks/paths'
+import { criterionTextOf, parseBrief } from '../hooks/reader/brief'
+import { readNotes, stateOf, totalsOfJunitXml } from '../hooks/reader/modernized'
+import { citationsIn, idOfTitle, needsReview, parseRules } from '../hooks/reader/rules'
+import { nodeOfFile, parseTopology } from '../hooks/reader/topology'
+import { decide, ledgerMarkdown, nextUnreviewed, queueOf, undecide } from '../hooks/review/deck'
+import { signBrief } from '../hooks/sign'
+import { readTestRun, TEST_COMMAND } from '../hooks/tests-run'
+import { wrapLines } from '../hooks/views/deck'
+import { BRIEF_SIGNED, BRIEF_UNSIGNED, RULES, RULES_BR, RULES_LABELLED, TOPOLOGY } from './fixtures/workspace'
+
+describe('paths', () => {
+ test('relative and absolute paths resolve against the working directory', () => {
+ expect(absOf('/work', 'a/../b/./c')).toBe('/work/b/c')
+ expect(resolveDots('/a/b/../../c')).toBe('/c')
+ expect(relTo('/work', '/work/legacy/x.cbl')).toBe('legacy/x.cbl')
+ expect(relTo('/work', 'legacy/x.cbl')).toBe('legacy/x.cbl')
+ expect(relTo('/work', '/elsewhere/x')).toBe(null)
+ expect(relTo('/private/tmp/ws', '/tmp/ws/a')).toBe('a')
+ })
+
+ test('isUnder does not confuse a sibling whose name starts the same', () => {
+ expect(isUnder('legacy/a.cbl', 'legacy')).toBe(true)
+ expect(isUnder('legacy-old/a.cbl', 'legacy')).toBe(false)
+ expect(isUnder('legacy', 'legacy')).toBe(true)
+ })
+})
+
+describe('topology', () => {
+ test('reads modules, domains, edges and flows, and maps a file to its node', () => {
+ const topo = parseTopology(TOPOLOGY)
+
+ expect(topo?.modules.map(node => node.id)).toEqual(['INTCALC', 'ACCTUPD', 'ACCTVIEW'])
+ expect(topo?.domains.map(domain => `${domain.name}:${domain.modules.length}`)).toEqual(['D1 Interest:1', 'D2 Accounts:2'])
+ expect(topo?.edges.length).toBe(3)
+ expect(topo && nodeOfFile(topo, 'app/cbl/INTCALC.cbl')?.id).toBe('INTCALC')
+ expect(topo && nodeOfFile(topo, 'INTCALC.cbl')?.id).toBe('INTCALC')
+ expect(topo && nodeOfFile(topo, 'app/cbl/NOPE.cbl')).toBe(null)
+ })
+
+ test('garbage is no topology, never a throw', () => {
+ expect(parseTopology('not json')).toBe(null)
+ expect(parseTopology('[]')).toBe(null)
+ expect(parseTopology('{"root": 7}')).toBe(null)
+ })
+})
+
+describe('rules', () => {
+ test('cards and table rows parse, with priorities from ids and section headings', () => {
+ const rules = parseRules(RULES)
+
+ expect(rules.rules.map(rule => `${rule.id.replace(/^R-[0-9a-f]{6}$/, 'R-hash')}:${rule.priority}`)).toEqual([
+ 'P0-001:P0',
+ 'P0-002:P0',
+ 'P0-003:P0',
+ 'R-hash:P1',
+ ])
+ expect(idOfTitle('View shows masked id!'), 'the id is of the title, whatever its punctuation').toBe(rules.rules[3]?.id)
+
+ const first = rules.byId.get('P0-001')
+
+ expect(first?.title).toBe('Monthly interest is truncated, not rounded')
+ expect(first?.confidence).toBe('High')
+ expect(first?.category).toBe('Calculation')
+ expect(first?.given).toContain('$1,250.00')
+ expect(first?.then).toContain('$19.27')
+ expect(first?.defect).toContain('Truncation')
+ expect(first?.edgeCases).toEqual(['A zero rate skips the account'])
+ expect(first?.citations[0]).toEqual({ path: 'legacy/billing/app/cbl/INTCALC.cbl', base: 'intcalc.cbl', from: 462, to: 470 })
+ expect(first?.domain).toBe('D1 Interest')
+ })
+
+ test('the appendix is skipped, and rules index by the file they cite', () => {
+ const rules = parseRules(RULES)
+
+ expect(rules.rules.some(rule => rule.title === 'Not a rule')).toBe(false)
+ expect(rules.byFileBase.get('intcalc.cbl')?.map(rule => rule.id)).toEqual(['P0-001', 'P0-002'])
+ })
+
+ test('needsReview picks the defect, the SME note and the lower confidence', () => {
+ const rules = parseRules(RULES)
+
+ expect(rules.rules.filter(needsReview).map(rule => rule.id)).toEqual(['P0-001', 'P0-002'])
+ })
+
+ test('a card whose id carries a domain, with the priority in its header line and list-style Given/When/Then, reads whole', () => {
+ const rules = parseRules(RULES_BR)
+
+ expect(rules.rules.map(rule => `${rule.id}:${rule.priority}`)).toEqual(['BR-D7-09:P0', 'BR-D7-10:P2'])
+
+ const interest = rules.byId.get('BR-D7-09')
+
+ expect(interest?.category).toBe('Calculation')
+ expect(interest?.confidence).toBe('High')
+ expect(interest?.given).toBe('A balance of 1250.00 at rate 15.00')
+ expect(interest?.when).toBe('The interest batch processes that row')
+ expect(interest?.then).toBe('Interest is 15.62 (truncated, NOT rounded)')
+ expect(interest?.citations[0]).toEqual({ path: 'app/cbl/CBACT04C.cbl', base: 'cbact04c.cbl', from: 462, to: 470 })
+ expect(interest?.defect).toContain('Truncation')
+ expect(rules.byId.get('BR-D7-10')?.sme).toBe('Should zero interest print?')
+ })
+
+ test('the legend and appendix tables of that layout are not rules', () => {
+ expect(parseRules(RULES_BR).rules.map(rule => rule.title)).toEqual([
+ 'Monthly interest per transaction-category balance',
+ 'Interest statement line',
+ ])
+ })
+
+ test('the labelled-fields layout reads whole: statement, fenced Given/When/Then, edge cases, defect and SME question', () => {
+ const rules = parseRules(RULES_LABELLED)
+
+ expect(rules.rules.map(rule => `${rule.id}:${rule.priority}`), 'the summary table and the appendix are not rules').toEqual([
+ 'RULE-007:P0',
+ 'RULE-004:P0',
+ 'RULE-090:P2',
+ ])
+
+ const interest = rules.byId.get('RULE-007')
+
+ expect(interest?.title).toBe('Monthly interest per transaction category using disclosure-group rate')
+ expect(interest?.category).toBe('Calculation')
+ expect(interest?.confidence).toBe('High')
+ expect(interest?.statement).toContain('divided by 1200')
+ expect(interest?.given).toContain("Account in group 'GOLD'")
+ expect(interest?.when).toBe('CBACT04C processes that category record')
+ expect(interest?.then).toContain('truncated not rounded')
+ expect(interest?.then, 'an And line continues the Then').toContain("read from 'DEFAULT'")
+ expect(interest?.edgeCases).toEqual(['No ROUNDED clause on the COMPUTE; result is truncated to cents', 'Negative balances produce negative interest'])
+ expect(interest?.citations[0]).toEqual({ path: 'app/cbl/CBACT04C.cbl', base: 'cbact04c.cbl', from: 188, to: 222 })
+ expect(interest?.domain).toBe('Calculation rules')
+ expect(interest?.defect).toBeUndefined()
+ expect(interest?.sme).toBeUndefined()
+
+ const counters = rules.byId.get('RULE-004')
+
+ expect(counters?.defect).toBe('Line 821 adds a stale amount to the declined total.')
+ expect(counters?.sme).toBe("Should declined-amount accumulate the current request's amount?")
+ expect(counters?.confidence).toBe('Medium')
+ expect(rules.rules.filter(needsReview).map(rule => rule.id)).toEqual(['RULE-004'])
+ })
+
+ test('citations are found bare, ranged and with an en dash', () => {
+ expect(citationsIn('see A.cbl:10 and app/cpy/B.cpy:4–9, not http://x:80').map(c => `${c.base}:${c.from}-${c.to}`)).toEqual([
+ 'a.cbl:10-10',
+ 'b.cpy:4-9',
+ ])
+ })
+})
+
+describe('brief', () => {
+ test('phases, the modules they name, criteria and the unsigned block', () => {
+ const brief = parseBrief(BRIEF_UNSIGNED, ['INTCALC', 'ACCTUPD', 'ACCTVIEW'])
+
+ expect(brief.target).toBe('Java / Spring')
+ expect(brief.phases.map(phase => `${phase.number}:${phase.size}:${phase.modules.join('+')}:${phase.criteria.length}`)).toEqual([
+ '1:M:INTCALC:2',
+ '2:L:ACCTUPD+ACCTVIEW:1',
+ ])
+ expect(brief.approval).toEqual({ isSigned: false })
+ expect(brief.openQuestions).toBe(1)
+ })
+
+ test('a phase lists its pilot first and the rest in the order it names them, not in topology order', () => {
+ const text = [
+ '### Phase 1 — Harness plus one job · **Size M** · Risk **High**',
+ '',
+ 'Scope: `ACCTUPD`, `INTCALC`.',
+ '',
+ '**🎯 Pilot unit — `INTCALC`.** One program, taken end to end.',
+ '',
+ '| Risk | Mitigation |',
+ '| --- | --- |',
+ '| The online path is not proven | Phase 2 names `ACCTVIEW` |',
+ ].join('\n')
+
+ expect(parseBrief(text, ['ACCTVIEW', 'ACCTUPD', 'INTCALC']).phases[0]?.modules).toEqual(['INTCALC', 'ACCTUPD', 'ACCTVIEW'])
+ })
+
+ test('a signed block reads who, when and what it covers', () => {
+ expect(parseBrief(BRIEF_SIGNED).approval).toEqual({
+ isSigned: true,
+ by: 'VP Engineering',
+ date: '2026-09-15',
+ covers: 'phase-1',
+ })
+ })
+
+ test('a module id is matched as a whole word only', () => {
+ const brief = parseBrief('### Phase 1 — X\n\nScope: INTCALC2 and XINTCALC.\n', ['INTCALC'])
+
+ expect(brief.phases[0]?.modules).toEqual([])
+ })
+
+ test('a tick annotation is not part of a criterion text', () => {
+ expect(criterionTextOf('- [x] Diff is clean (Ana, 2026-09-16)')).toBe('Diff is clean')
+ expect(criterionTextOf('not a box')).toBe(null)
+ })
+})
+
+describe('modernized', () => {
+ test('junit totals from a suite and from a suites wrapper', () => {
+ expect(totalsOfJunitXml('<testsuite tests="9" failures="1" errors="2" skipped="3">')).toEqual({ tests: 9, failures: 1, errors: 2, skipped: 3, reports: 1 })
+ expect(totalsOfJunitXml('<testsuites tests="4" failures="0" errors="0"><testsuite tests="4"/></testsuites>')?.tests).toBe(4)
+ expect(totalsOfJunitXml('<html/>')).toBe(null)
+ })
+
+ test('notes yield the review date, follow-ups and the switch state', () => {
+ expect(readNotes('## Architecture review\nReviewed 2026-09-15.\n## Follow-ups\n- a\n- b\n')).toEqual({
+ hasReviewSection: true,
+ reviewDate: '2026-09-15',
+ isPortedNotSwitched: false,
+ isSwitched: false,
+ followUps: 2,
+ })
+ expect(readNotes('Status: ported, not switched').isPortedNotSwitched).toBe(true)
+ expect(readNotes('Route switched 2026-09-10.').isSwitched).toBe(true)
+ })
+
+ test('states follow the facts, furthest first', () => {
+ const base = { dir: 'm', path: 'p', hasMain: true, hasTests: true, hasNotes: true, hasReviewSection: false, isPortedNotSwitched: false, isSwitched: false, followUps: 0, mtimeMs: 0 }
+ const green = { tests: 5, failures: 0, errors: 0, skipped: 0, reports: 1 }
+
+ expect(stateOf({ ...base, hasTests: false, tests: null })).toBe('scaffolded')
+ expect(stateOf({ ...base, tests: null })).toBe('tests-written')
+ expect(stateOf({ ...base, tests: { ...green, failures: 1 } })).toBe('tests-red')
+ expect(stateOf({ ...base, tests: green })).toBe('tests-green')
+ expect(stateOf({ ...base, tests: green, hasReviewSection: true })).toBe('reviewed')
+ expect(stateOf({ ...base, tests: green, hasReviewSection: true, isPortedNotSwitched: true })).toBe('ported')
+ expect(stateOf({ ...base, tests: green, hasReviewSection: true, isSwitched: true })).toBe('switched')
+ expect(stateOf({ ...base, tests: { ...green, tests: 0 } }), 'reports with zero cases are not green').toBe('tests-written')
+ })
+})
+
+describe('sign', () => {
+ test('fills the block in place and nothing else', () => {
+ const signed = signBrief(BRIEF_UNSIGNED, ' Ana Lopez ', '2026-09-16', 'phase-1')
+
+ expect(signed).toContain('Approved by: Ana Lopez')
+ expect(signed).toContain('Date: 2026-09-16')
+ expect(signed).toContain('[X] Phase 1 only [ ] Full plan')
+ expect(parseBrief(signed ?? '').approval).toEqual({ isSigned: true, by: 'Ana Lopez', date: '2026-09-16', covers: 'phase-1' })
+ })
+
+ test('the one-line and the worded forms are filled too', () => {
+ const oneLine = '## 8. Approval Block\n```\nApproved by: ________________ Date: __________\nApproval covers: Phase 1 only | Full plan\n```\n'
+ const signed = signBrief(oneLine, 'Ana', '2026-09-16', 'full')
+
+ expect(signed).toContain('Approved by: Ana Date: 2026-09-16')
+ expect(signed).toContain('Approval covers: Full plan')
+ expect(parseBrief(signed ?? '').approval.covers).toBe('full')
+ expect(signBrief('no block here', 'Ana', '2026-09-16', 'full')).toBe(null)
+ })
+})
+
+describe('test runs', () => {
+ test('commands that run a suite are recognised, others are not', () => {
+ for (const command of ['mvn -q test', './mvnw verify', 'cd x && gradle test', 'pytest -q', 'npm test', 'npm run test', 'dotnet test', 'go test ./...', 'cargo test', 'JAVA_HOME=/x mvn -q -o test 2>&1 | tail -40', 'cd modernized/x; time ./gradlew check']) {
+ expect(TEST_COMMAND.test(command), command).toBe(true)
+ }
+
+ for (const command of ['mvn compile', 'ls test', 'git status', 'cat pytest.ini', 'grep -rn pytest .', 'echo "run npm test later"']) {
+ expect(TEST_COMMAND.test(command), command).toBe(false)
+ }
+ })
+
+ test('totals are read per runner, and a run of nothing is zero executed', () => {
+ expect(readTestRun('Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\nTests run: 174, Failures: 1, Errors: 0, Skipped: 2')).toEqual({ executed: 172, failed: 1, skipped: 2 })
+ expect(readTestRun('Tests run: 12, Failures: 0, Errors: 0, Skipped: 12\nBUILD SUCCESS')).toEqual({ executed: 0, failed: 0, skipped: 12 })
+ expect(readTestRun('==== 3 passed, 1 skipped in 0.12s ====')).toEqual({ executed: 3, failed: 0, skipped: 1 })
+ expect(readTestRun('collected 0 items')).toEqual({ executed: 0, failed: 0, skipped: 0 })
+ expect(readTestRun('Tests: 1 failed, 2 skipped, 9 passed, 12 total')).toEqual({ executed: 10, failed: 1, skipped: 2 })
+ expect(readTestRun('Passed! - Failed: 0, Passed: 12, Skipped: 1, Total: 13')).toEqual({ executed: 12, failed: 0, skipped: 1 })
+ expect(readTestRun('test result: ok. 7 passed; 0 failed; 1 ignored')).toEqual({ executed: 7, failed: 0, skipped: 1 })
+ expect(readTestRun('compiled fine')).toBe(null)
+ })
+})
+
+describe('treemap and raster', () => {
+ test('every item is placed without overlap and the area is covered', () => {
+ const items = [500, 300, 120, 80, 40, 20, 5, 1].map((size, index) => ({ item: index, size }))
+ const placed = layout(items, { x: 0, y: 0, w: 40, h: 10 })
+ const owner = new Array<number>(400).fill(-1)
+ let overlaps = 0
+
+ for (const entry of placed) {
+ for (let row = 0; row < entry.rect.h; row += 1) {
+ for (let col = 0; col < entry.rect.w; col += 1) {
+ const key = (entry.rect.y + row) * 40 + entry.rect.x + col
+
+ overlaps += owner[key] === -1 ? 0 : 1
+ owner[key] = entry.item
+ }
+ }
+ }
+
+ expect(placed.length).toBe(8)
+ expect(overlaps).toBe(0)
+ expect(owner.filter(id => id === -1).length).toBe(0)
+ })
+
+ test('groups keep their items inside their own rectangle', () => {
+ const placed = layoutGroups(
+ [
+ { name: 'a', items: [{ item: 'a1', size: 10 }, { item: 'a2', size: 5 }] },
+ { name: 'b', items: [{ item: 'b1', size: 30 }] },
+ { name: 'empty', items: [] },
+ ],
+ { x: 0, y: 0, w: 30, h: 8 },
+ )
+
+ expect(placed.map(group => group.name).sort()).toEqual(['a', 'b'])
+
+ for (const group of placed) {
+ for (const entry of group.items) {
+ expect(entry.rect.x >= group.rect.x && entry.rect.x + entry.rect.w <= group.rect.x + group.rect.w).toBe(true)
+ expect(entry.rect.y >= group.rect.y && entry.rect.y + entry.rect.h <= group.rect.y + group.rect.h).toBe(true)
+ }
+ }
+ })
+
+ test('cells pack to twelve bytes each, base64 is standard, odd glyphs become spaces', () => {
+ expect(base64Of(new Uint8Array([77, 97, 110]))).toBe('TWFu')
+ expect(base64Of(new Uint8Array([77, 97]))).toBe('TWE=')
+ expect(base64Of(new Uint8Array([77]))).toBe('TQ==')
+ expect(packCells([{ glyph: 'A', fg: 0x112233, bg: 0x01000000 }]).length).toBe(16)
+ expect(codePointOf('\u{1F600}')).toBe(0x20)
+ expect(codePointOf('漢')).toBe(0x20)
+ expect(codePointOf('▸')).toBe(0x25b8)
+ expect(mix(0x000000, 0xffffff, 0.5)).toBe(0x808080)
+ })
+})
+
+describe('fleet', () => {
+ test('a failure shared by three agents is announced once', () => {
+ const fleet = newFleet()
+ const error = (n: number) => `error CS0246: The type 'NUnit${n}' could not be found in /src/proj${n}/A.cs(12,3)`
+
+ for (const id of ['a', 'b', 'c', 'd']) {
+ noteCall(fleet, id, 'Bash', 'dotnet build', 1)
+ }
+
+ expect(normalizeFailure(error(1))).toBe(normalizeFailure(error(2)))
+ expect(noteFailure(fleet, 'a', error(1), 10)).toBe(null)
+ expect(noteFailure(fleet, 'a', error(1), 11), 'the same agent twice is still one agent').toBe(null)
+ expect(noteFailure(fleet, 'b', error(2), 12)).toBe(null)
+ expect(noteFailure(fleet, 'c', error(3), 13)?.agents.size).toBe(3)
+ expect(noteFailure(fleet, 'd', error(4), 14), 'announced once').toBe(null)
+ expect(tallyOf(fleet, 20).shared.length).toBe(1)
+ })
+
+ test('what names no cause is not a signature', () => {
+ // A search that found nothing, and a malformed call: neither is something agents share.
+ expect(normalizeFailure('Exit code 1\napp/data/ASCII/:\nacctdata.txt carddata.txt')).toBe('')
+ expect(normalizeFailure('Exit code 1')).toBe('')
+ expect(normalizeFailure('<tool_use_error>InputValidationError: Read was called with input that could not be parsed as JSON.')).toBe('')
+ expect(normalizeFailure('Exit code 2\n12 "x"'), 'only placeholders left').toBe('')
+ })
+
+ test('one cause worded per command or per call is one signature', () => {
+ const missing = [
+ 'File does not exist. Note: your current working directory is /Users/x/workspace.',
+ 'Exit code 2\nugrep: warning: /Users/x/workspace/app/cbl/CBTRN02C.cbl: No such file or directory',
+ 'Exit code 1\nwc: /Users/x/workspace/app/cbl/COPAUA0C.cbl: open: No such file or directory',
+ 'Exit code 1 ls: /Users/x/workspace/app/cbl/: No such file or directory',
+ ]
+
+ expect(new Set(missing.map(normalizeFailure))).toEqual(new Set(['a path that does not exist']))
+ expect(missingPathOf(missing[2] ?? '')).toBe('/Users/x/workspace/app/cbl/COPAUA0C.cbl')
+ expect(missingPathOf(missing[0] ?? '')).toBe(undefined)
+
+ expect(
+ normalizeFailure("Permission to use Bash with command cd /Users/x/legacy/carddemo && sed -n '/^ 5000-PROCESS/,/^ 5000-EXIT/p' app/cbl/A.cbl has been denied."),
+ ).toBe(normalizeFailure("Permission to use Bash with command sed -n '/1245-EDIT\\./,/1245-EXIT\\./p' /Users/x/legacy/carddemo/app/cbl/B.cbl has been denied."))
+
+ // Which property broke which rule survives; which element of the array does not.
+ const schema = (n: number, twice: boolean) =>
+ `Output does not match required schema: /rules/${n}/category: must be equal to one of the allowed values: ["Calculation","Validation"]` +
+ (twice ? `, /rules/${n + 6}/category: must be equal to one of the allowed values: ["Calculation","Validation"]` : '')
+
+ expect(normalizeFailure(schema(13, true))).toBe(normalizeFailure(schema(27, false)))
+ expect(normalizeFailure(schema(13, true))).toBe(
+ 'Output does not match required schema: /rules/<n>/category: must be equal to one of the allowed values',
+ )
+
+ expect(normalizeFailure('Exit code 1\n2575: PERFORM 9000-READ\n(eval):1: == not found')).toBe(
+ normalizeFailure('Exit code 1\n(eval):3: ==DATA=== not found'),
+ )
+ })
+
+ test('the bar for calling a failure out rises with the fleet, and it is called out again only once it has spread', () => {
+ const fleet = newFleet()
+ const miss = 'File does not exist. Note: your current working directory is /w.'
+
+ for (let index = 0; index < 200; index += 1) {
+ noteCall(fleet, `agent-${index}`, 'Read', 'A.cbl', 1)
+ }
+
+ expect(announceThresholdOf(fleet)).toBe(10)
+
+ const hits: number[] = []
+
+ for (let index = 0; index < 120; index += 1) {
+ // One failure a second: the quiet minute has long passed by the time it has spread fivefold.
+ const hit = noteFailure(fleet, `agent-${index}`, miss, 1000 + index * 1000, `app/cbl/P${index}.cbl`)
+
+ if (hit !== null) {
+ hits.push(hit.agents.size)
+ }
+ }
+
+ expect(hits, 'at the bar, then once it has spread fivefold and a minute has passed').toEqual([10, 70])
+
+ const shared = tallyOf(fleet, 0).shared[0]
+
+ expect(shared !== undefined ? lineOf(shared) : '').toBe(
+ '120 agents hit the same failure: a path that does not exist (e.g. app/cbl/P0.cbl, app/cbl/P1.cbl)',
+ )
+ expect(shared !== undefined ? lineOf(shared, 'short') : '').toBe('120 agents: a path that does not exist (e.g. app/cbl/P0.cbl)')
+ })
+
+ test('a fan-out that fails all at once is not called out twice in a minute', () => {
+ const fleet = newFleet()
+
+ for (let index = 0; index < 40; index += 1) {
+ noteCall(fleet, `agent-${index}`, 'Read', 'A.cbl', 1)
+ }
+
+ const hits: number[] = []
+
+ for (let index = 0; index < 40; index += 1) {
+ const hit = noteFailure(fleet, `agent-${index}`, 'File does not exist.', 1000 + index * 100)
+
+ if (hit !== null) {
+ hits.push(hit.agents.size)
+ }
+ }
+
+ expect(hits).toEqual([3])
+ })
+
+ test('the widest-spread failure is listed first', () => {
+ const fleet = newFleet()
+
+ for (let index = 0; index < 8; index += 1) {
+ noteCall(fleet, `agent-${index}`, 'Bash', 'x', 1)
+ }
+
+ for (let index = 0; index < 3; index += 1) {
+ noteFailure(fleet, `agent-${index}`, 'error TS2304: Cannot find name', 10)
+ }
+
+ for (let index = 0; index < 6; index += 1) {
+ noteFailure(fleet, `agent-${index}`, 'File does not exist.', 20)
+ }
+
+ expect(tallyOf(fleet, 30).shared.map(signature => signature.agents.size)).toEqual([6, 3])
+ })
+
+ test('a shell call is labelled by what runs, not where', () => {
+ expect(subjectOf('Bash', { command: 'cd /very/long/path 2>/dev/null; ls -la' })).toBe('ls -la')
+ expect(subjectOf('Bash', { command: 'cd /very/long/path/to/module && mvn -q test' })).toBe('mvn -q test')
+ expect(subjectOf('Bash', { command: 'W=/tmp/x; cd "$W/analysis" && export A=1 && cat RULES.md' })).toBe('cat RULES.md')
+ expect(subjectOf('Read', { file_path: '/a/b/C.cbl' })).toBe('C.cbl')
+ })
+
+ test('totals survive pruning', () => {
+ const fleet = newFleet()
+
+ for (let index = 0; index < 20; index += 1) {
+ noteCall(fleet, `agent-${index}`, 'Read', 'a.cbl', index, 'MOD')
+ noteDone(fleet, `agent-${index}`, index + 1)
+ }
+
+ prune(fleet, 100, 0, 5)
+
+ const tally = tallyOf(fleet, 100)
+
+ expect(fleet.agents.size <= 5).toBe(true)
+ expect(tally.total).toBe(20)
+ expect(tally.done).toBe(20)
+ expect(tally.calls).toBe(20)
+ })
+})
+
+describe('deck', () => {
+ test('flagged rules come first by weight, and verdicts move the cursor on', () => {
+ const rules = parseRules(RULES)
+ const queue = queueOf(rules, 'flagged')
+
+ expect(queue.map(rule => rule.id)).toEqual(['P0-002', 'P0-001'])
+ expect(queueOf(rules, 'p0').length).toBe(3)
+ expect(queueOf(rules, 'all').length).toBe(4)
+ expect(queueOf(rules, 'all', 'acctview').map(rule => rule.title)).toEqual(['View shows masked id'])
+ expect(queueOf(rules, 'p0', 'truncat').map(rule => rule.id), 'the filter reads what the rule says, not only its title').toEqual(['P0-001'])
+
+ const first = queue[0]
+
+ if (first === undefined) {
+ throw new Error('empty queue')
+ }
+
+ const ledger = decide({}, first, 'wrong', '2026-09-16T00:00:00Z')
+
+ expect(nextUnreviewed(queue, ledger, 0)).toBe(1)
+ expect(nextUnreviewed(queue, undecide(ledger, first.id), 0)).toBe(0)
+ expect(ledgerMarkdown('billing', ledger)).toContain('| P0-002 | Wrong | 2026-09-16 |')
+ })
+
+ test('cards wrap into counted rows', () => {
+ expect(wrapLines('one two three four five', 9, 5)).toEqual(['one two', 'three', 'four five'])
+ expect(wrapLines('one two three four five', 9, 2)).toEqual(['one two', 'three…'])
+ expect(wrapLines('', 9, 2)).toEqual([])
+ expect(wrapLines('abcdefghijklmnop', 8, 3)).toEqual(['abcdefgh', 'ijklmnop'])
+ })
+})
+
+describe('estate', () => {
+ test('tiles take their state from the transformed modules and flash when touched', () => {
+ const topology = parseTopology(TOPOLOGY)
+
+ if (topology === null) {
+ throw new Error('no topology')
+ }
+
+ const snapshot = {
+ system: 'billing',
+ topology,
+ byNode: new Map([['INTCALC', { state: 'reviewed' }]]),
+ next: { text: '/x:modernize-transform billing ACCTUPD java', isByHand: false, reason: '' },
+ } as never
+
+ const tiles = tilesOf(snapshot, 40, 8)
+
+ expect(tiles.map(tile => `${tile.id}:${tile.state}:${tile.isNext}`).sort()).toEqual([
+ 'ACCTUPD:untouched:true',
+ 'ACCTVIEW:untouched:false',
+ 'INTCALC:reviewed:false',
+ ])
+
+ const still = paint(tiles, 40, 8, new Map(), 10_000)
+ const hot = paint(tiles, 40, 8, new Map([['INTCALC', { atMs: 9_900, kind: 'write' as const }]]), 10_000)
+ const cold = paint(tiles, 40, 8, new Map([['INTCALC', { atMs: 1_000, kind: 'write' as const }]]), 10_000)
+
+ expect(still.isAnimating).toBe(false)
+ expect(hot.isAnimating).toBe(true)
+ expect(hot.cells === still.cells).toBe(false)
+ expect(cold.isAnimating).toBe(false)
+ expect(cold.cells).toBe(still.cells)
+ expect(atob(still.cells).length).toBe(40 * 8 * 12)
+ })
+})
diff --git a/plugins/code-modernization/tests/register.test.ts b/plugins/code-modernization/tests/register.test.ts
new file mode 100644
index 00000000..188fac41
--- /dev/null
+++ b/plugins/code-modernization/tests/register.test.ts
@@ -0,0 +1,428 @@
+import { describe, expect, mock, test } from 'claude-code/testing'
+
+import { parseBrief } from '../hooks/reader/brief'
+import { BAND, command, HINT, MAIN_SCREEN_HINT, PANE, SESSION, SIGN_PANE } from './fixtures/inputs'
+import { elementsOf, rowsOf, stringsOf, textOf, worldOf } from './fixtures/world'
+import { BRIEF_SIGNED, FULL, UNSIGNED } from './fixtures/workspace'
+
+const NAME = 'code-modernization'
+const BRIEF = 'analysis/billing/MODERNIZATION_BRIEF.md'
+
+describe('start and pane', () => {
+ test('the start registers the three commands and opens nothing by itself', async ($, on) => {
+ const world = worldOf(on, FULL)
+
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ expect(world.commands.sort()).toEqual(['modernize-panel', 'modernize-review', 'modernize-sign'])
+ expect(world.opened).toEqual([])
+ })
+
+ test('under the fullscreen layout the pane opens once the hint has drawn; on the main screen it waits to be asked', async ($, on) => {
+ const world = worldOf(on, FULL)
+ const clock = mock.clock(on)
+
+ on('ui.render', () => ({ type: 'Text', children: [''] }))
+ await $.session.start(SESSION)
+ await $.ui.render(MAIN_SCREEN_HINT)
+ await clock.advance(200)
+
+ expect(world.opened, 'not fullscreen: nothing opens unasked').toEqual([])
+
+ await $.ui.render(HINT)
+ await clock.advance(200)
+
+ expect(world.opened).toEqual([{ id: 'modernize', focus: false }])
+
+ await $.ui.render(HINT)
+ await clock.advance(200)
+
+ expect(world.opened.length, 'opened once').toBe(1)
+ })
+
+ test('a build that never draws the prompt hint still opens the pane, from the band\'s render', async ($, on) => {
+ const world = worldOf(on, FULL)
+ const clock = mock.clock(on)
+
+ on('ui.render', () => ({ type: 'Text', children: [''] }))
+ await $.session.start(SESSION)
+ // As 2.1.273 draws it: a viewport with no `isFullscreen`, and a band shorter than the screen.
+ await $.ui.render({ ...BAND, viewport: { columns: 160, rows: 45 }, props: { ...BAND.props, maxRows: 17 } })
+ await clock.advance(200)
+
+ expect(world.opened).toEqual([{ id: 'modernize', focus: false }])
+ })
+
+ test('on the main screen, where the band may be as tall as the terminal, nothing opens unasked', async ($, on) => {
+ const world = worldOf(on, FULL)
+ const clock = mock.clock(on)
+
+ on('ui.render', () => ({ type: 'Text', children: [''] }))
+ await $.session.start(SESSION)
+ await $.ui.render({ ...BAND, viewport: { columns: 160, rows: 45 }, props: { ...BAND.props, maxRows: 45 } })
+ await clock.advance(200)
+
+ expect(world.opened).toEqual([])
+ })
+
+ test('the pane opens when the first artifact appears, not only at the start', async ($, on) => {
+ const world = worldOf(on, { 'legacy/billing/app/cbl/INTCALC.cbl': 'x' })
+ const clock = mock.clock(on)
+
+ on('ui.render', () => ({ type: 'Text', children: [''] }))
+ on('tool.call', () => {
+ world.put('analysis/billing/PREFLIGHT.md', '# Preflight')
+
+ return { result: 'ok', text: 'ok' }
+ })
+
+ await $.session.start(SESSION)
+ await $.ui.render(BAND)
+ await clock.advance(200)
+ expect(world.opened, 'nothing to show yet').toEqual([])
+
+ await $.tool.call({ tool: 'Write', file_path: '/work/analysis/billing/PREFLIGHT.md', content: '# Preflight' })
+ await clock.advance(1000)
+
+ expect(world.opened).toEqual([{ id: 'modernize', focus: false }])
+ })
+
+ test('a workspace with no analysis opens no pane and says what to run', async ($, on) => {
+ const world = worldOf(on, { 'README.md': 'hi' })
+ const clock = mock.clock(on)
+
+ on('ui.render', () => ({ type: 'Text', children: [''] }))
+ await $.session.start(SESSION)
+ await $.ui.render(HINT)
+ await clock.advance(200)
+
+ expect(world.opened).toEqual([])
+ expect(textOf(await $.ui.render(PANE))).toContain('no system found under legacy/ or analysis/')
+ })
+
+ test('the pane draws the system, its stages, phases, the transformed module and the next step', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const tree = await $.ui.render(PANE)
+ const text = textOf(tree)
+
+ expect(text).toContain('billing → Java / Spring')
+ expect(text).toContain('✓ preflight')
+ expect(text).toContain('✓ brief')
+ expect(text).toContain('✓ transform')
+ expect(text).toContain('· harden')
+ expect(text).toContain('P1 Interest pilot (D1)')
+ expect(text).toContain('INTCALC')
+ expect(text).toContain('12 green')
+ expect(text).toContain('/code-modernization:modernize-status billing')
+
+ const raster = elementsOf(tree, 'Raster')[0] as { props: { columns: number; rows: number; cells: string } } | undefined
+
+ expect(raster?.props.columns).toBe(71)
+ expect(atob(raster?.props.cells ?? '').length).toBe(71 * (raster?.props.rows ?? 0) * 12)
+ })
+
+ test('/modernize-panel toggles the pane and says which, and json prints the reading', async ($, on) => {
+ const world = worldOf(on, FULL)
+
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ expect(await $.command.run(command('modernize-panel'))).toEqual({ text: 'Modernization pane shown' })
+ expect(world.opened.at(-1)?.id).toBe('modernize')
+ expect(await $.command.run(command('modernize-panel'))).toEqual({ text: 'Modernization pane hidden' })
+ expect(world.closed).toEqual(['modernize'])
+
+ const { text } = await $.command.run(command('modernize-panel', 'json'))
+
+ expect(JSON.parse((text ?? '').replace(/```json\n|\n```/g, '')).modules[0]).toEqual({
+ dir: 'INTCALC',
+ state: 'reviewed',
+ tests: { tests: 12, failures: 0, errors: 0, skipped: 0, reports: 1 },
+ reviewDate: '2026-09-15',
+ })
+ })
+
+ test('the next button puts the next command in the prompt box, never runs it', async ($, on) => {
+ const world = worldOf(on, { ...UNSIGNED, [BRIEF]: BRIEF_SIGNED })
+
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await $.ui.render(PANE)
+ await $.ui.press({ plugin: NAME, key: 'next' })
+
+ expect(world.fills).toEqual(['/code-modernization:modernize-transform billing INTCALC java-spring'])
+ })
+})
+
+describe('pane budget', () => {
+ test('the pane never draws more rows than its body has, busy or idle, tall or short', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ on('tool.call', ($, e) => (e.tool === 'Bash' ? { isError: true as const, result: 'x', text: 'error: the same thing broke here' } : { result: 'x', text: 'x' }))
+ await $.session.start(SESSION)
+ await $.turn.start({ text: '/code-modernization:modernize-transform billing INTCALC java', turnId: 't1' })
+
+ for (const agentId of ['w1', 'w2', 'w3', 'w4']) {
+ await $.tool.call({ tool: 'Read', file_path: '/work/legacy/billing/app/cbl/INTCALC.cbl', agentId } as never)
+ await $.tool.call({ tool: 'Bash', command: 'mvn -q test', agentId } as never)
+ }
+
+ await $.tool.call({ tool: 'Read', file_path: '/work/legacy/billing/app/cbl/INTCALC.cbl' })
+ await $.tool.call({ tool: 'Bash', command: 'mvn -q test' })
+
+ for (const bodyRows of [24, 30, 36, 41, 44, 52, 60]) {
+ const tree = await $.ui.render({ ...PANE, props: { ...PANE.props, scroll: { offset: 0, bodyRows } } })
+
+ expect(rowsOf(tree) <= bodyRows, `pane fits ${bodyRows} rows (drew ${rowsOf(tree)})`).toBe(true)
+ expect(textOf(tree), 'the session block is always in view').toContain('Session')
+ expect(textOf(tree)).toContain('agents active')
+ }
+
+ // A dialog or another panel can take nearly all of the pane's rows, and a body is not always a whole number.
+ for (const bodyRows of [0, 1, 3, 8, 12, 16.5, 20]) {
+ const tree = await $.ui.render({ ...PANE, props: { ...PANE.props, scroll: { offset: 0, bodyRows } } })
+
+ for (const raster of elementsOf(tree, 'Raster') as { props: { rows: number; columns: number } }[]) {
+ expect(Number.isInteger(raster.props.rows) && raster.props.rows >= 1, `a map of ${raster.props.rows} rows in a body of ${bodyRows}`).toBe(true)
+ expect(Number.isInteger(raster.props.columns) && raster.props.columns >= 1).toBe(true)
+ }
+
+ expect(textOf(tree), `a body of ${bodyRows} rows still draws the pane`).toContain('billing')
+ }
+ })
+})
+
+describe('x-ray and the estate', () => {
+ test('a read of a legacy file carries what the analysis knows, narrowed to the lines read', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ on('tool.call', () => ({ result: 'file text', text: 'file text' }))
+ await $.session.start(SESSION)
+
+ const whole = await $.tool.call({ tool: 'Read', file_path: '/work/legacy/billing/app/cbl/INTCALC.cbl' })
+ const note = (whole.context ?? []).join('\n')
+
+ expect(note).toContain('x-ray for app/cbl/INTCALC.cbl · INTCALC · D1 Interest · 600 lines')
+ expect(note).toContain('Reached from: ACCTUPD.')
+ expect(note).toContain('Reads: RATES.')
+ expect(note).toContain('Business rules citing this file: 2 (2 P0)')
+ expect(note).toContain('P0-001 Monthly interest is truncated, not rounded (L462-470) [suspected defect]')
+ expect(note).toContain('Already transformed at modernized/billing/INTCALC: reviewed, 12/12 tests passing.')
+
+ const window = await $.tool.call({ tool: 'Read', file_path: 'legacy/billing/app/cbl/INTCALC.cbl', offset: 410, limit: 20 })
+ const narrowed = (window.context ?? []).join('\n')
+
+ expect(narrowed).toContain('In the lines just read (410-429):')
+ expect(narrowed).toContain('P0-002')
+ expect(narrowed.includes('P0-001')).toBe(false)
+ })
+
+ test('a read outside the legacy tree, or of a file nothing knows, carries nothing', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ on('tool.call', () => ({ result: 'x', text: 'x' }))
+ await $.session.start(SESSION)
+
+ expect((await $.tool.call({ tool: 'Read', file_path: '/work/analysis/billing/ASSESSMENT.md' })).context).toBe(undefined)
+ expect((await $.tool.call({ tool: 'Read', file_path: '/work/legacy/billing/README.md' })).context).toBe(undefined)
+ })
+
+ test('a read that misses is told where the file is, when it is under the legacy root', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+
+ on('tool.call', () => ({
+ isError: true as const,
+ result: 'x',
+ text: 'File does not exist. Note: your current working directory is /work.',
+ }))
+
+ await $.session.start(SESSION)
+
+ // A citation as the rules file writes it, read from the workspace root.
+ const cited = await $.tool.call({ tool: 'Read', file_path: '/work/app/cbl/INTCALC.cbl' })
+
+ expect(cited.context?.join('\n')).toContain('legacy/billing/app/cbl/INTCALC.cbl exists')
+
+ // A path that is nowhere, and one already under the legacy tree, get no such note.
+ expect((await $.tool.call({ tool: 'Read', file_path: '/work/app/cbl/NOPE.cbl' })).context).toBe(undefined)
+ expect((await $.tool.call({ tool: 'Read', file_path: '/work/legacy/billing/app/cbl/NOPE.cbl' })).context).toBe(undefined)
+ })
+
+ test('a touched tile is repainted while it fades and the repainting stops once it has', async ($, on) => {
+ const world = worldOf(on, FULL)
+ const clock = mock.clock(on, { now: 0 })
+
+ on('tool.call', () => ({ result: 'x', text: 'x' }))
+ await $.session.start(SESSION)
+ await $.ui.render(PANE)
+
+ expect(world.blits).toBe(0)
+
+ await $.tool.call({ tool: 'Read', file_path: '/work/legacy/billing/app/cbl/ACCTUPD.cbl' })
+ await clock.advance(450)
+
+ expect(world.blits > 0, 'frames are painted while the touch fades').toBe(true)
+ })
+})
+
+describe('fleet', () => {
+ test('three agents failing the same way raise one alert', async ($, on) => {
+ const world = worldOf(on, FULL)
+
+ mock.clock(on)
+
+ on('tool.call', ($, e) => ({
+ isError: true as const,
+ result: 'x',
+ text: `error CS0246: The type 'NUnit' could not be found in /src/${String(e.agentId)}/A.cs(12,3)`,
+ }))
+
+ await $.session.start(SESSION)
+
+ for (const agentId of ['w1', 'w2', 'w3', 'w4']) {
+ // A subagent's call carries the loop it runs in; a test's call says so the same way.
+ await $.tool.call({ tool: 'Bash', command: 'dotnet build', agentId } as never)
+ }
+
+ expect(world.toasts.filter(text => text.startsWith('Fleet:')).length).toBe(1)
+ expect(world.logs.some(text => text.includes('3 agents hit the same failure'))).toBe(true)
+
+ const text = textOf(await $.ui.render(PANE))
+
+ expect(text).toContain('agents active')
+ expect(text).toContain('4 agents: error CS0246')
+ })
+})
+
+describe('review deck', () => {
+ test('/modernize-review draws the first flagged card in the band, and a digit decides it', async ($, on) => {
+ const world = worldOf(on, FULL)
+ const clock = mock.clock(on)
+
+ on('ui.render', () => ({ type: 'Text', children: ['engine'] }))
+ await $.session.start(SESSION)
+
+ expect(textOf(await $.ui.render(BAND)), 'closed: the band holds only the bar that shows the pane').toContain('show pane')
+ expect(await $.command.run(command('modernize-review'))).toEqual({ text: 'Reviewing 2 rules.' })
+
+ const card = await $.ui.render(BAND)
+ const text = textOf(card)
+
+ expect(text).toContain('1/2')
+ expect(text).toContain('P0-002 · Missing rate row aborts the run')
+ expect(text).toContain('For an SME')
+ expect(stringsOf(card).filter(part => part === 'confirm').length).toBe(1)
+
+ await $.ui.press({ plugin: NAME, key: 'wrong' })
+ await clock.settle()
+
+ const ledger = world.writes.find(write => write.path === 'analysis/billing/RULE_REVIEWS.json')
+
+ expect(JSON.parse(ledger?.text ?? '{}').reviews['P0-002'].verdict).toBe('wrong')
+ expect(world.writes.some(write => write.path === 'analysis/billing/RULE_REVIEWS.md' && write.text.includes('| P0-002 | Wrong |'))).toBe(true)
+ expect(world.files.get('analysis/billing/BUSINESS_RULES.md'), 'the rules file is never edited').toBe(FULL['analysis/billing/BUSINESS_RULES.md'])
+
+ const next = textOf(await $.ui.render(BAND))
+
+ expect(next).toContain('2/2')
+ expect(next).toContain('P0-001')
+ expect(next).toContain('✗ 1')
+ })
+
+ test('the card never draws more rows than the band has, source shown or not', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await $.command.run(command('modernize-review', 'all'))
+
+ for (const maxRows of [12, 16, 20, 30]) {
+ const input = { ...BAND, props: { ...BAND.props, maxRows } }
+
+ expect(rowsOf(await $.ui.render(input)) <= maxRows, `card fits ${maxRows} rows`).toBe(true)
+
+ await $.ui.press({ plugin: NAME, key: 'source' })
+ expect(rowsOf(await $.ui.render(input)) <= maxRows, `card with source fits ${maxRows} rows`).toBe(true)
+ await $.ui.press({ plugin: NAME, key: 'source' })
+ }
+ })
+
+ test('close hands the band back', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ on('ui.render', () => ({ type: 'Text', children: ['engine'] }))
+ await $.session.start(SESSION)
+ await $.command.run(command('modernize-review', 'p0'))
+ await $.ui.render(BAND)
+ await $.ui.press({ plugin: NAME, key: 'close' })
+
+ expect(textOf(await $.ui.render(BAND)), 'the bar that shows the pane is back').toContain('show pane')
+ })
+})
+
+describe('signing', () => {
+ test('a person signs through the dialog: the block is filled and nothing else changes', async ($, on) => {
+ const world = worldOf(on, UNSIGNED)
+ const clock = mock.clock(on)
+
+ on('tool.call', () => ({ result: 'ok', text: 'ok' }))
+ await $.session.start(SESSION)
+
+ expect(textOf(await $.ui.render(PANE))).toContain('approve the brief')
+ expect(await $.command.run(command('modernize-sign'))).toEqual({})
+ expect(world.opened.at(-1)).toEqual({ id: 'modernize-sign', focus: true })
+
+ const dialog = await $.ui.render(SIGN_PANE)
+
+ expect(textOf(dialog)).toContain('treat an unsigned brief as not approved')
+ expect(textOf(dialog)).toContain('1 open question')
+
+ await $.ui.press({ plugin: NAME, key: 'do-sign' })
+ await clock.settle()
+ expect(textOf(await $.ui.render(SIGN_PANE)), 'no name, no signature').toContain('Type the approver')
+
+ await $.ui.press({ plugin: NAME, key: 'cancel' })
+ expect(await $.command.run(command('modernize-sign', 'Ana Lopez, VP Eng')), 'the name can ride the command').toEqual({})
+ expect(textOf(await $.ui.render(SIGN_PANE))).toContain('Ana Lopez, VP Eng')
+ await $.ui.press({ plugin: NAME, key: 'full' })
+ await $.ui.press({ plugin: NAME, key: 'do-sign' })
+ await clock.settle()
+
+ const signed = world.files.get(BRIEF) ?? ''
+
+ expect(parseBrief(signed).approval).toEqual({ isSigned: true, by: 'Ana Lopez, VP Eng', date: parseBrief(signed).approval.date, covers: 'full' })
+ expect(world.closed).toContain('modernize-sign')
+ expect(world.logs.some(text => text.includes('brief signed by Ana Lopez, VP Eng (full plan)'))).toBe(true)
+
+ const after = await $.tool.call({ tool: 'Bash', command: 'ls' })
+
+ expect(after.context, 'the person\'s signature is not a violation').toBe(undefined)
+ expect(world.files.get(BRIEF)).toBe(signed)
+ })
+
+ test('a signed brief, or a running turn, opens no dialog', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ expect((await $.command.run(command('modernize-sign'))).text).toContain('already signed by VP Engineering')
+ })
+})
+
+describe('prompt context', () => {
+ test('the one-line state rides a typed prompt once per change', async ($, on) => {
+ worldOf(on, FULL)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const first = await $.prompt.submit({ text: 'hello', wait: false, origin: { kind: 'composer' } })
+ const second = await $.prompt.submit({ text: 'again', wait: false, origin: { kind: 'composer' } })
+
+ expect((first.context ?? []).join(' ')).toContain('billing: discovery 5/5 · brief approved · 1/3 modules reviewed')
+ expect(second.context, 'unchanged: not attached again').toBe(undefined)
+ })
+})
diff --git a/plugins/code-modernization/tests/stacks.test.ts b/plugins/code-modernization/tests/stacks.test.ts
new file mode 100644
index 00000000..377c8b55
--- /dev/null
+++ b/plugins/code-modernization/tests/stacks.test.ts
@@ -0,0 +1,444 @@
+import { describe, expect, mock, test } from 'claude-code/testing'
+
+import { tilesOf } from '../hooks/map/estate'
+import { discoverEstate } from '../hooks/reader/discover'
+import { xrayOf } from '../hooks/xray/xray'
+import { readNotes, stateOfUplift, totalsOfTrx } from '../hooks/reader/modernized'
+import { oneLineOf, readSnapshot, type ReadOptions, type Snapshot } from '../hooks/reader/progress'
+import { changedPathsOf, parseBaseline, parseCatalog } from '../hooks/reader/uplift'
+import { pickTrack } from '../hooks/reader/tracks'
+import { BAND, command, HINT, PANE, SESSION } from './fixtures/inputs'
+import {
+ DOTNET_REWRITE,
+ LEGACY_ONLY,
+ MAVEN_UPLIFT,
+ memoryFs,
+ NODE_REWRITE,
+ PHP_NO_MAP,
+ PYTHON_BIG,
+ REIMAGINE,
+} from './fixtures/stacks'
+import { elementsOf, rowsOf, textOf, worldOf } from './fixtures/world'
+import { FULL } from './fixtures/workspace'
+
+const NAME = 'code-modernization'
+const PREFIX = '/p:modernize-'
+
+async function read(files: Record<string, string>, more: Partial<ReadOptions> = {}): Promise<Snapshot> {
+ const snapshot = await readSnapshot(memoryFs(files), new Map(), { commandPrefix: PREFIX, nowMs: 0, ...more })
+
+ if (snapshot === null) {
+ throw new Error('no snapshot')
+ }
+
+ return snapshot
+}
+
+const stateOfUnit = (snapshot: Snapshot, name: string) => snapshot.byNode.get(name)?.state
+
+describe('uplift, whatever the stack', () => {
+ test('a Maven uplift is followed from its own artifacts: the delta catalog, the baseline, the playbook and the working copy', async () => {
+ const snapshot = await read(MAVEN_UPLIFT)
+
+ expect(snapshot.track).toBe('uplift')
+ expect(snapshot.stages.map(stage => `${stage.isDone ? '✓' : '·'}${stage.key}`)).toEqual([
+ '✓preflight',
+ '✓deltas',
+ '✓baseline',
+ '✓pilot',
+ '✓migrate',
+ '·verify',
+ ])
+ expect(snapshot.stages.find(stage => stage.key === 'deltas')?.detail).toBe('12 deltas')
+ expect(snapshot.stages.find(stage => stage.key === 'baseline')?.detail).toBe('78 tests')
+
+ // No map was run: the estate is read off the tree, one unit per module that has a build file of its own.
+ expect(snapshot.estate?.source).toBe('tree')
+ expect(snapshot.estate?.granularity).toBe('build module')
+ expect(snapshot.estate?.units.map(unit => unit.name).sort()).toEqual(['shop', 'shop-batch', 'shop-core', 'shop-web'].sort())
+ expect(snapshot.estate?.languages[0]?.name).toBe('Java')
+
+ // shop-core reproduces its baseline; shop-web has three failures the baseline did not; shop-batch was edited, not tested.
+ expect(stateOfUnit(snapshot, 'shop-core')).toBe('reviewed')
+ expect(stateOfUnit(snapshot, 'shop-web')).toBe('tests-red')
+ expect(stateOfUnit(snapshot, 'shop-batch')).toBe('scaffolded')
+ expect(snapshot.attention).toContain('shop-web: 3 failing, the baseline had 0')
+ expect(snapshot.uplift?.isChangeKnown).toBe(true)
+
+ // The uplift command needs both versions, which only a person knows.
+ expect(snapshot.next?.isByHand).toBe(true)
+ expect(snapshot.next?.text).toBe(`${PREFIX}uplift shop <from> <to>`)
+ expect(snapshot.next?.reason).toContain('dual-run diff')
+
+ expect(oneLineOf(snapshot)).toContain('shop: uplift 5/6 steps')
+ expect(snapshot.percent).not.toBe(null)
+ })
+
+ test('the working copy is compared with the tree by file name and size, and a write seen in the session counts too', async () => {
+ // shop-batch's Nightly.java is 2050 bytes in the copy and 2000 in the tree; shop-web's files are the same size in both.
+ const same = { ...MAVEN_UPLIFT, 'modernized/shop-uplifted/shop-batch/src/main/java/Nightly.java': 'x'.repeat(2000) }
+ const quiet = await read(same)
+
+ expect(stateOfUnit(quiet, 'shop-batch'), 'an edit that keeps a file the same size is not seen by the comparison').toBe(undefined)
+ expect(stateOfUnit(await read(same, { writtenUnits: new Set(['shop-batch']) }), 'shop-batch'), 'but a write the session saw is').toBe('scaffolded')
+
+ const added = await read({ ...same, 'modernized/shop-uplifted/shop-batch/src/main/java/Extra.java': 'x'.repeat(10) })
+
+ expect(stateOfUnit(added, 'shop-batch'), 'a file only the copy has').toBe('scaffolded')
+
+ const removed: Record<string, string> = { ...same }
+
+ delete removed['modernized/shop-uplifted/shop-batch/src/main/java/Nightly.java']
+ expect(stateOfUnit(await read(removed), 'shop-batch'), 'a file only the tree has').toBe('scaffolded')
+ })
+
+ test('with no working copy there is nothing to compare, and the pane says the changes are unread', async () => {
+ const files = Object.fromEntries(Object.entries(MAVEN_UPLIFT).filter(([path]) => !path.startsWith('modernized/')))
+ const snapshot = await read(files)
+
+ expect(snapshot.track).toBe('uplift')
+ expect(snapshot.uplift?.hasCopy).toBe(false)
+ expect(snapshot.uplift?.isChangeKnown).toBe(false)
+ expect(snapshot.modules).toEqual([])
+ })
+
+ test('a listing of the working copy is reused for a while, then read again', async () => {
+ const files: Record<string, string> = { ...MAVEN_UPLIFT, 'modernized/shop-uplifted/shop-batch/src/main/java/Nightly.java': 'x'.repeat(2000) }
+ const fs = memoryFs(files)
+ const cache = new Map()
+ const options = { commandPrefix: PREFIX, nowMs: 0 }
+ const first = await readSnapshot(fs, cache, options)
+
+ expect(first?.byNode.get('shop-batch')).toBe(undefined)
+ files['modernized/shop-uplifted/shop-batch/src/main/java/Nightly.java'] = 'x'.repeat(2100)
+
+ expect((await readSnapshot(fs, cache, { ...options, nowMs: 5_000 }))?.byNode.get('shop-batch'), 'read again too soon: the earlier listing stands').toBe(undefined)
+ expect((await readSnapshot(fs, cache, { ...options, nowMs: 20_000 }))?.byNode.get('shop-batch')?.state, 'past the interval it is read again').toBe('scaffolded')
+ expect((await readSnapshot(fs, cache, { ...options, nowMs: 21_000, changedTtlMs: 0 }))?.byNode.get('shop-batch')?.state).toBe('scaffolded')
+ })
+
+ test('a module counts as matching only when every baseline pass still passes and none is missing', () => {
+ const row = { pass: 40, fail: 1, error: 0, skip: 2 }
+ const totals = (tests: number, failures: number, skipped = 0) => ({ tests, failures, errors: 0, skipped, reports: 1 })
+
+ expect(stateOfUplift(totals(43, 1, 2), row, true)).toBe('reviewed')
+ expect(stateOfUplift(totals(50, 1, 2), row, true), 'new tests were added').toBe('reviewed')
+ expect(stateOfUplift(totals(40, 1, 2), row, true), 'three tests did not run').toBe('tests-green')
+ expect(stateOfUplift(totals(43, 2, 2), row, true), 'one more failure than the baseline').toBe('tests-red')
+ expect(stateOfUplift(totals(10, 0), null, true), 'nothing to compare with').toBe('tests-green')
+ expect(stateOfUplift(null, row, true)).toBe('scaffolded')
+ expect(stateOfUplift(null, row, false)).toBe('untouched')
+ })
+
+ test('baselines are read whatever the columns are called, and a target-only one has no table', () => {
+ const jvm = parseBaseline('| Module | pass | fail | error | skip |\n|---|---:|---:|---:|---:|\n| `a/b` | 3 | 1 | 0 | 2 |\n| **Total** | 3 | 1 | 0 | 2 |')
+
+ expect([...jvm.rows.entries()]).toEqual([['a/b', { pass: 3, fail: 1, error: 0, skip: 2 }]])
+ expect(jvm.results).toBe(6)
+
+ const dotnet = parseBaseline('| Project | Passed | Failed | Skipped |\n|---|---|---|---|\n| Ledger.Core | 1,204 | 0 | 12 |')
+
+ expect(dotnet.rows.get('ledger.core')).toEqual({ pass: 1204, fail: 0, error: 0, skip: 12 })
+
+ const target = parseBaseline('target-only: the .NET Framework runtime is not available here')
+
+ expect(target.isTargetOnly).toBe(true)
+ expect(target.rows.size).toBe(0)
+ })
+
+ test('the catalog says how many deltas it holds, or its ids do', () => {
+ expect(parseCatalog('into **41 distinct deltas** ranked')?.count).toBe(41)
+ expect(parseCatalog('| **D01** | a |\n| **D02** | b |\nD01 again')?.count).toBe(2)
+ expect(parseCatalog('| **D01** | uses `a/Foo.java:3` and `Bar.java` |\n| **D02** | b `Foo.java` |')?.byFileBase.get('foo.java')).toEqual(['D01', 'D02'])
+ expect(parseCatalog('nothing here')).toBe(null)
+ })
+
+ test('paths that differ between two trees are those with another size, and those only one of them has', () => {
+ const before = new Map([['a', 1], ['b', 2], ['c', 3]])
+ const after = new Map([['a', 1], ['b', 5], ['d', 9]])
+
+ expect(changedPathsOf(before, after)).toEqual(['b', 'd', 'c'])
+ expect(changedPathsOf(before, before)).toEqual([])
+ })
+
+ test('the newest track is the one followed, and a named one is pinned', () => {
+ expect(pickTrack('auto', { transformAt: 5, upliftAt: 9, reimagineAt: null })).toBe('uplift')
+ expect(pickTrack('auto', { transformAt: 12, upliftAt: 9, reimagineAt: 3 })).toBe('transform')
+ expect(pickTrack('auto', { transformAt: null, upliftAt: null, reimagineAt: 1 })).toBe('reimagine')
+ expect(pickTrack('auto', { transformAt: null, upliftAt: null, reimagineAt: null })).toBe('transform')
+ expect(pickTrack('transform', { transformAt: null, upliftAt: 9, reimagineAt: 3 })).toBe('transform')
+ })
+})
+
+describe('the estate, whatever the language', () => {
+ test('a PHP shop with no map and no build file is one tile per source file, and its assets and docs are not source', async () => {
+ const snapshot = await read(PHP_NO_MAP)
+
+ expect(snapshot.track).toBe('transform')
+ expect(snapshot.hasAnalysis).toBe(true)
+ expect(snapshot.estate?.source).toBe('tree')
+ expect(snapshot.estate?.granularity).toBe('file')
+ expect(snapshot.estate?.units.length).toBe(27)
+ expect(snapshot.estate?.units.some(unit => unit.name === 'logo' || unit.name === 'README')).toBe(false)
+ expect(snapshot.estate?.languages).toEqual([{ name: 'PHP', share: 1 }])
+ expect(snapshot.next?.text).toBe(`${PREFIX}assess webshop`)
+
+ const tiles = tilesOf(snapshot, 44, 12)
+
+ expect(tiles.length).toBeGreaterThan(10)
+ expect(new Set(tiles.map(tile => tile.domain))).toEqual(new Set(['catalog', 'includes', 'webshop']))
+ })
+
+ test('a .NET solution is one tile per project, named languages included, and its .trx report gives the module its tests', async () => {
+ const snapshot = await read(DOTNET_REWRITE)
+
+ expect(snapshot.track).toBe('transform')
+ expect(snapshot.estate?.granularity).toBe('build module')
+ expect(snapshot.estate?.units.map(unit => unit.name).sort()).toEqual(['Ledger.Core', 'Ledger.Web'])
+ expect(snapshot.estate?.languages.map(language => language.name)).toEqual(['C#', 'VB.NET', 'ASP.NET'])
+
+ const core = snapshot.byNode.get('Ledger.Core')
+
+ expect(core?.tests).toEqual({ tests: 14, failures: 0, errors: 0, skipped: 0, reports: 1 })
+ expect(core?.state).toBe('tests-green')
+ expect(snapshot.totals.done, 'green with the notes written is done').toBe(1)
+ expect(totalsOfTrx('<html/>')).toBe(null)
+ })
+
+ test('a module tested by a runner that leaves no report is read from the run the session saw', async () => {
+ const before = await read(NODE_REWRITE)
+
+ expect(before.modules.map(module => `${module.dir}:${module.state}`)).toEqual(['billing:tests-written'])
+
+ const after = await read(NODE_REWRITE, {
+ observed: new Map([['modernized/portal/billing', { tests: 9, failures: 0, errors: 0, skipped: 1, reports: 1 }]]),
+ })
+
+ expect(after.modules.map(module => `${module.dir}:${module.state}`)).toEqual(['billing:tests-green'])
+ expect(after.estate?.units.map(unit => unit.name).sort()).toEqual(['auth', 'billing', 'portal', 'ui'].sort())
+ expect(stateOfUnit(after, 'packages/billing')).toBe('tests-green')
+ })
+
+ test('a greenfield rebuild follows its services, and asks for acceptance tests where a service has none', async () => {
+ const snapshot = await read(REIMAGINE)
+
+ expect(snapshot.track).toBe('reimagine')
+ expect(snapshot.stages.map(stage => `${stage.isDone ? '✓' : '·'}${stage.key}`)).toEqual(['·preflight', '✓spec', '✓design', '✓scaffold', '·tests'])
+ expect(snapshot.modules.map(module => `${module.dir}:${module.state}`).sort()).toEqual(['accounts:tests-green', 'billing:scaffolded'])
+ expect(snapshot.attention).toContain('billing: scaffolded with no acceptance tests')
+ expect(snapshot.percent, 'services are not the legacy units').toBe(null)
+ expect(snapshot.next?.text).toBe(`${PREFIX}status crm`)
+ expect(snapshot.estate?.languages.map(language => language.name)).toEqual(['Perl'])
+ })
+
+ test('a legacy tree nobody has analysed is a system with an estate and nothing done', async () => {
+ const snapshot = await read(LEGACY_ONLY)
+
+ expect(snapshot.hasAnalysis).toBe(false)
+ expect(snapshot.stages.every(stage => !stage.isDone)).toBe(true)
+ expect(snapshot.estate?.languages).toEqual([{ name: 'COBOL', share: 1 }])
+ expect(snapshot.next?.text).toBe(`${PREFIX}preflight ops`)
+ })
+
+ test('a tree too big for a tile per file is read a directory at a time, and a lone wrapper directory is looked through', async () => {
+ const estate = await discoverEstate(memoryFs(PYTHON_BIG), 'legacy/erp', 'erp')
+
+ expect(estate?.granularity).toBe('directory')
+ expect(estate?.units.map(unit => unit.name).sort()).toEqual(['pkg0', 'pkg1', 'pkg2', 'pkg3', 'pkg4', 'pkg5'])
+ expect(estate?.files).toBe(620)
+ expect(estate?.isPartial).toBe(false)
+ })
+
+ test('a walk that runs out of budget says so instead of pretending the sizes are whole', async () => {
+ const estate = await discoverEstate(memoryFs(PYTHON_BIG), 'legacy/erp', 'erp', { dirs: 3, entries: 80_000 })
+
+ expect(estate?.isPartial).toBe(true)
+ })
+
+ test('a baseline alone does not make a rewrite an uplift: a rewrite records the legacy behavior it must keep too', async () => {
+ const snapshot = await read({ ...FULL, 'analysis/billing/BASELINE.md': '# Legacy baseline\n\nRecorded from the real program.' })
+
+ expect(snapshot.track).toBe('transform')
+ expect(snapshot.stages.map(stage => stage.key)).toContain('transform')
+ })
+
+ test('what the plain plugin writes is enough: a findings file with no marker is a finished harden step, and notes need no fixed headline', async () => {
+ const snapshot = await read({ ...FULL, 'analysis/billing/SECURITY_FINDINGS.md': '# Security findings\n\n| Severity | Finding |\n|---|---|\n| High | x |\n' })
+
+ expect(snapshot.stages.find(stage => stage.key === 'harden')?.isDone).toBe(true)
+ expect(snapshot.attention.some(line => line.includes('SECURITY_FINDINGS'))).toBe(false)
+
+ expect(readNotes('## Architecture review\nfine').hasReviewSection).toBe(true)
+ expect(readNotes('## Critic findings\n- HIGH: an open endpoint, fixed').hasReviewSection).toBe(true)
+ expect(readNotes('The architecture-critic subagent found two issues; both fixed.').hasReviewSection).toBe(true)
+ expect(readNotes('## Mapping table\n| a | b |').hasReviewSection).toBe(false)
+ })
+
+ test('a workspace with the map uses the map for a rewrite, and the tree for an uplift', async () => {
+ const mapped = await read({ ...FULL })
+
+ expect(mapped.estate?.source).toBe('map')
+ expect(mapped.estate?.measure).toBe('lines')
+ expect(mapped.estate?.languages[0]?.name).toBe('COBOL')
+ })
+})
+
+describe('the pane in another stack', () => {
+ test('an uplift is drawn as an uplift: its stages, the modules against their baseline, and the by-hand next step', async ($, on) => {
+ worldOf(on, MAVEN_UPLIFT)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const tree = await $.ui.render(PANE)
+ const text = textOf(tree)
+
+ expect(text).toContain('shop · uplift')
+ expect(text).toContain('deltas')
+ expect(text).toContain('baseline')
+ expect(text).toContain('Java 100%')
+ expect(text).toContain('matches baseline')
+ expect(text).toContain('worse than baseline')
+ expect(text).toContain('/code-modernization:modernize-uplift shop <from> <to>')
+ expect(text).toContain('(by hand)')
+ expect(text).not.toContain('extract-rules')
+ })
+
+ test('a rewrite in PHP with no map still draws an estate map and its legend', async ($, on) => {
+ worldOf(on, PHP_NO_MAP)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const tree = await $.ui.render(PANE)
+
+ expect(elementsOf(tree, 'Raster').length).toBe(1)
+ expect(textOf(tree)).toContain('PHP 100% · 27 files (read off the tree)')
+ expect(textOf(tree)).toContain('untouched 27')
+ })
+
+ for (const [name, files] of Object.entries({
+ 'a Maven uplift': MAVEN_UPLIFT,
+ 'a PHP shop': PHP_NO_MAP,
+ 'a .NET rewrite': DOTNET_REWRITE,
+ 'a Node monorepo': NODE_REWRITE,
+ 'a reimagine': REIMAGINE,
+ 'a legacy tree': LEGACY_ONLY,
+ 'the COBOL fixture': FULL,
+ })) {
+ test(`the pane fits its rows and columns for ${name}, tall or short, narrow or wide`, async ($, on) => {
+ worldOf(on, files)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ for (const [bodyRows, bodyColumns] of [
+ [44, 72],
+ [30, 60],
+ [20, 44],
+ [12, 36],
+ ] as const) {
+ const input = { ...PANE, props: { ...PANE.props, bodyColumns, scroll: { offset: 0, bodyRows } } }
+ const rows = rowsOf(await $.ui.render(input))
+
+ expect(rows <= bodyRows, `fits ${bodyRows} rows at ${bodyColumns} columns (drew ${rows})`).toBe(true)
+ }
+ })
+ }
+})
+
+describe('a workspace of several systems', () => {
+ const TWO = { ...MAVEN_UPLIFT, ...PHP_NO_MAP }
+
+ test('the pane follows one system and has a button that moves it to the next', async ($, on) => {
+ worldOf(on, TWO)
+ const clock = mock.clock(on)
+
+ await $.session.start(SESSION)
+
+ const first = textOf(await $.ui.render(PANE))
+
+ expect(first).toContain('shop · uplift')
+ expect(first).toContain('system 1/2')
+
+ await $.ui.press({ plugin: NAME, key: 'system' })
+ await clock.settle()
+
+ const second = textOf(await $.ui.render(PANE))
+
+ expect(second).toContain('webshop · rewrite')
+ expect(second).toContain('system 2/2')
+ expect(second).toContain('PHP 100%')
+ expect(second).not.toContain('baseline')
+ })
+
+ test('a workspace of one system draws no such button', async ($, on) => {
+ worldOf(on, MAVEN_UPLIFT)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ expect(textOf(await $.ui.render(PANE))).not.toContain('system 1/')
+ })
+})
+
+describe('showing and hiding the pane', () => {
+ test('a hidden pane leaves one bar with a button; pressing it shows the pane, and the pane has a button that hides it again', async ($, on) => {
+ const world = worldOf(on, FULL)
+ const clock = mock.clock(on)
+ // The main screen, where nothing opens unasked: the pane is hidden until the person shows it.
+ const band = { ...BAND, viewport: { columns: 100, rows: 45, isFullscreen: false }, props: { ...BAND.props, maxRows: 45 } }
+
+ on('ui.render', () => ({ type: 'Text', children: ['engine'] }))
+ await $.session.start(SESSION)
+
+ const bar = await $.ui.render(band)
+
+ expect(textOf(bar)).toContain('show pane')
+ expect(textOf(bar), 'the bar says where the workspace stands').toContain('billing: discovery 5/5')
+
+ await $.ui.press({ plugin: NAME, key: 'show-pane' })
+ await clock.settle()
+
+ expect(world.opened).toEqual([{ id: 'modernize', focus: false }])
+ expect(textOf(await $.ui.render(band)), 'the bar gives the band back while the pane is up').toBe('engine')
+
+ const pane = await $.ui.render(PANE)
+
+ expect(elementsOf(pane, 'Button').map(button => textOf(button))).toContain('hide')
+
+ await $.ui.press({ plugin: NAME, key: 'hide' })
+ await clock.settle()
+
+ expect(world.closed).toEqual(['modernize'])
+ expect(textOf(await $.ui.render(band))).toContain('show pane')
+
+ // Hidden by a person, it stays hidden until a person shows it: nothing reopens it unasked.
+ await $.ui.render(HINT)
+ await clock.advance(500)
+ expect(world.opened.length).toBe(1)
+ })
+
+ test('/modernize-panel is the same switch from the keyboard', async ($, on) => {
+ const world = worldOf(on, FULL)
+
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ expect(await $.command.run(command('modernize-panel'))).toEqual({ text: 'Modernization pane shown' })
+ expect(await $.command.run(command('modernize-panel'))).toEqual({ text: 'Modernization pane hidden' })
+ expect(world.opened.length).toBe(1)
+ expect(world.closed).toEqual(['modernize'])
+ })
+
+ test('a legacy tree with nothing analysed opens nothing and draws no bar, but the command still shows the pane and its estate', async ($, on) => {
+ const world = worldOf(on, LEGACY_ONLY)
+ const clock = mock.clock(on)
+
+ on('ui.render', () => ({ type: 'Text', children: ['engine'] }))
+ await $.session.start(SESSION)
+ await $.ui.render(HINT)
+ await clock.advance(500)
+
+ expect(world.opened).toEqual([])
+ expect(textOf(await $.ui.render(BAND))).toBe('engine')
+ expect(await $.command.run(command('modernize-panel'))).toEqual({ text: 'Modernization pane shown' })
+ expect(textOf(await $.ui.render(PANE))).toContain('COBOL 100%')
+ })
+})
diff --git a/plugins/code-modernization/tsconfig.json b/plugins/code-modernization/tsconfig.json
new file mode 100644
index 00000000..4b245ea3
--- /dev/null
+++ b/plugins/code-modernization/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "compilerOptions": {
+ "target": "es2023", "lib": ["es2023"], "types": [],
+ "module": "esnext", "moduleResolution": "bundler",
+ "strict": true, "noUncheckedIndexedAccess": true,
+ "noEmit": true, "skipLibCheck": true,
+ "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment"
+ },
+ "include": [".claude/types", "hooks", "tests"]
+}