diff options
| author | Claude <noreply@anthropic.com> | 2026-11-06 00:54:48 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-06 00:54:48 +0000 |
| commit | 7aba3deae3ff17d032c37e07d2929d1426b34278 (patch) | |
| tree | 9c482f9acda1599bd2f9bed95a6a46b75e634e80 /plugins/code-modernization/tests/fixtures | |
| parent | 5472f5f56e0070feeeb464318b316714fe3e9105 (diff) | |
| parent | b8331dd69ab3e132bbf8cd6e89b5d8c1747e21b1 (diff) | |
Merge remote-tracking branch 'origin/main' into add-plugin/xcodeadd-plugin/xcode
Diffstat (limited to 'plugins/code-modernization/tests/fixtures')
| -rw-r--r-- | plugins/code-modernization/tests/fixtures/inputs.ts | 55 | ||||
| -rw-r--r-- | plugins/code-modernization/tests/fixtures/stacks.ts | 217 | ||||
| -rw-r--r-- | plugins/code-modernization/tests/fixtures/workspace.ts | 306 | ||||
| -rw-r--r-- | plugins/code-modernization/tests/fixtures/world.ts | 279 |
4 files changed, 857 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..9de66e02 --- /dev/null +++ b/plugins/code-modernization/tests/fixtures/stacks.ts @@ -0,0 +1,217 @@ +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>> = {}, + /** Paths that are symbolic links to a directory: listed as `other`, as the engine lists a link; `stat` says `dir`. */ + links: readonly string[] = [], +): 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]) => { + const isLink = links.includes(dir === '' ? name : `${dir}/${name}`) + + return { + name, + kind: isLink ? ('other' as const) : kind, + size: kind === 'file' ? (files[dir === '' ? name : `${dir}/${name}`]?.length ?? 0) : 0, + isLink, + } + }) + }, + } +} + +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..43b8d154 --- /dev/null +++ b/plugins/code-modernization/tests/fixtures/world.ts @@ -0,0 +1,279 @@ +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 + /** How many of the next opens the engine holds back undrawn (unasked, on a terminal too narrow to dock a pane). */ + unplaced: 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>> = {}, + /** Paths (relative to the working directory) that are symbolic links to a directory: the engine lists a link as `other`. */ + links: readonly 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, + unplaced: 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]) => { + const isLink = links.includes(dir === '' ? name : `${dir}/${name}`) + + return { + name, + kind: isLink ? ('other' as const) : kind, + size: kind === 'file' ? (world.files.get(`${dir}/${name}`)?.length ?? 0) : 0, + isLink, + } + }), + } + }) + + 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 }) + + if (world.unplaced > 0) { + world.unplaced -= 1 + + return { value: { isPlaced: false, reason: 'unasked below 144 columns (120 now): press the pane\'s button or type /modernize-panel' } } as never + } + + return { value: { isPlaced: true } } as never + }) + + 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) +} |
