summaryrefslogtreecommitdiff
path: root/plugins/code-modernization/tests
diff options
context:
space:
mode:
authorMorgan Lunt <morganl@anthropic.com>2026-09-24 18:07:14 -0700
committerMorgan Lunt <morganl@anthropic.com>2026-09-24 18:11:07 -0700
commitc9e990089c6c87cb96e227e998edbada1df82861 (patch)
tree623eb2b217930fd1e56558946443cd2ddeb5b849 /plugins/code-modernization/tests
parent70caddcb673ac8995d6a5191e02ac51de579d6c3 (diff)
code-modernization: add an optional live progress pane
Adds a hooks module, off unless the CLI's early-access function hooks are enabled, that draws a pane beside the transcript while the commands run: the system, which steps are done, a map of its code, each unit of work and where it stands, what needs attention, and the next command. It reads only the artifacts the commands write and the legacy tree, so it works for any language and for a rewrite, a same-stack uplift or a greenfield rebuild. The map comes from topology.json when there is one and from the source tree when there is not. In an uplift each module is set against the baseline; tests are read from JUnit XML, .trx reports or the runs a session sees; a button shows and hides the pane, and /modernize-panel does the same from the keyboard. The same module adds x-ray context on legacy reads, a review deck for business rules (/modernize-review), a sign-off dialog (/modernize-sign) and a fleet view that spots one failure repeating across agents. It only watches: it never blocks, rewrites or restores an edit, and it runs no program inside the trees it reads. An uplift's changed modules are found by comparing the working copy with the tree by file name and size through the file API. Its options are the plugin's userConfig. Without the flag nothing loads and the commands, agents and workflows behave as before. 91 tests in tests/ run with "claude plugin test"; plugin validate passes on the release build with the flag on and off.
Diffstat (limited to 'plugins/code-modernization/tests')
-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
7 files changed, 2269 insertions, 0 deletions
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%')
+ })
+})