diff options
| author | Morgan Lunt <morganl@anthropic.com> | 2026-09-24 18:07:14 -0700 |
|---|---|---|
| committer | Morgan Lunt <morganl@anthropic.com> | 2026-09-24 18:11:07 -0700 |
| commit | c9e990089c6c87cb96e227e998edbada1df82861 (patch) | |
| tree | 623eb2b217930fd1e56558946443cd2ddeb5b849 /plugins/code-modernization/hooks | |
| parent | 70caddcb673ac8995d6a5191e02ac51de579d6c3 (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/hooks')
25 files changed, 6830 insertions, 0 deletions
diff --git a/plugins/code-modernization/hooks/fleet/fleet.ts b/plugins/code-modernization/hooks/fleet/fleet.ts new file mode 100644 index 00000000..876b9512 --- /dev/null +++ b/plugins/code-modernization/hooks/fleet/fleet.ts @@ -0,0 +1,350 @@ +/** + * The fleet: every agent loop this session has seen a tool call from, kept + * from the events themselves. A workflow's agents carry ids no `$.agent.list()` + * names, so the registry is built from `tool.call` and `turn.complete` alone. + * + * It also watches for one failure repeating across agents: three agents + * hitting the same error is a fact about the playbook, not about the agents. + */ + +export type AgentRow = { + id: string + firstMs: number + lastMs: number + calls: number + errors: number + /** `Read`, `Bash`, and so on. */ + lastTool: string + /** A short rendering of the last call's subject: a file's name, a command's head. */ + lastSubject: string + isDone: boolean + /** The unit of work it appears to be on: the legacy module its calls touch most. */ + unit?: string +} + +export type Signature = { + /** The normalized failure text the agents share. */ + text: string + agents: Set<string> + firstMs: number + lastMs: number + /** How many agents shared it when it was last called out; 0 while it has not been. */ + announcedAt: number + /** When it was last called out. */ + announcedMs: number + /** What a few of the failing calls were aimed at: the part of the cause the text alone leaves out. */ + examples: string[] +} + +export type Fleet = { + agents: Map<string, AgentRow> + signatures: Map<string, Signature> + /** Units each agent touched, to name what it is working on. */ + unitHits: Map<string, Map<string, number>> + /** Counted as they happen, so pruning old rows does not shrink the totals. */ + seen: number + ended: number + calls: number + errors: number +} + +/** An agent with no call for this long reads as finished or stalled, in milliseconds. */ +export const IDLE_MS = 90_000 + +/** How many agents must share a failure before it counts as shared at all. */ +export const SIGNATURE_THRESHOLD = 3 + +/** A shared failure is called out again once it has spread this many times further. */ +export const ESCALATE_FACTOR = 5 + +/** And no sooner than this after the last time, in milliseconds: a fan-out fails all at once. */ +export const ESCALATE_QUIET_MS = 60_000 + +/** + * How many agents must share a failure before it is called out in the + * transcript. Three of five agents is a pattern; three of five hundred is not, + * so the bar rises with the fleet. The pane lists it from three either way. + */ +export const announceThresholdOf = (fleet: Fleet): number => + Math.max(SIGNATURE_THRESHOLD, Math.ceil(fleet.seen * 0.05)) + +/** Failures further apart than this are not the same incident, in milliseconds. */ +export const SIGNATURE_WINDOW_MS = 15 * 60_000 + +export const newFleet = (): Fleet => ({ + agents: new Map(), + signatures: new Map(), + unitHits: new Map(), + seen: 0, + ended: 0, + calls: 0, + errors: 0, +}) + +/** A short subject for a call, from the arguments tools commonly carry. */ +export function subjectOf(tool: string, args: Readonly<Record<string, unknown>>): string { + const str = (key: string) => (typeof args[key] === 'string' ? (args[key] as string) : undefined) + const path = str('file_path') ?? str('path') ?? str('notebook_path') + + if (path !== undefined) { + return path.split('/').slice(-1)[0] ?? path + } + + const command = str('command') + + if (command !== undefined) { + // What runs, not where: a leading `cd …`, `VAR=…;` or `export …` says nothing at a glance. + const lead = /^(?:\s*(?:cd\s+(?:"[^"]*"|'[^']*'|\S+)(?:\s+\d?>{1,2}\s*\S+)*|(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*))\s*(?:&&|;)\s*)+/ + + return command.replace(/\s+/g, ' ').replace(lead, '').slice(0, 48) + } + + return (str('pattern') ?? str('description') ?? str('query') ?? str('prompt') ?? '') + .replace(/\s+/g, ' ') + .slice(0, 48) +} + +/** Records the start of a call by `agentId`. */ +export function noteCall( + fleet: Fleet, + agentId: string, + tool: string, + subject: string, + nowMs: number, + unit?: string, +): AgentRow { + if (!fleet.agents.has(agentId)) { + fleet.seen += 1 + } + + fleet.calls += 1 + + const row = fleet.agents.get(agentId) ?? { + id: agentId, + firstMs: nowMs, + lastMs: nowMs, + calls: 0, + errors: 0, + lastTool: tool, + lastSubject: subject, + isDone: false, + } + + const next: AgentRow = { + ...row, + lastMs: nowMs, + calls: row.calls + 1, + lastTool: tool, + lastSubject: subject, + isDone: false, + } + + if (unit !== undefined) { + const hits = fleet.unitHits.get(agentId) ?? new Map<string, number>() + + hits.set(unit, (hits.get(unit) ?? 0) + 1) + fleet.unitHits.set(agentId, hits) + + const top = [...hits.entries()].sort((a, b) => b[1] - a[1])[0] + + if (top !== undefined) { + next.unit = top[0] + } + } + + fleet.agents.set(agentId, next) + + return next +} + +const ERRORISH = /error|fail|exception|cannot|not found|denied|refused|blocked|unresolved|undefined|no such|does not exist|does not match/i + +/** A path named by a "No such file" line, as the command printed it. */ +export function missingPathOf(text: string): string | undefined { + return /([^\s:'"]*\/[^\s:'"]+): (?:open: )?No such file or directory/.exec(text)?.[1] +} + +/** + * A failure text with what varies between agents taken out: paths, numbers, + * hex, quoted values, timestamps. Two agents hitting one cause then match. + * + * Empty when the text names no cause worth matching on: a bare exit code (a + * search that found nothing), or a malformed tool call, which is the model's + * slip and not something the agents share. + */ +export function normalizeFailure(text: string): string { + if (/InputValidationError|could not be parsed as JSON/.test(text)) { + return '' + } + + const line = + text + .split('\n') + .map(part => part.trim().replace(/^Exit code \d+\s*/i, '')) + .find(part => part !== '' && ERRORISH.test(part)) ?? '' + + if (line === '') { + return '' + } + + // Families: one cause that words itself differently per command or per call. + if (/file does not exist|no such file or directory|path does not exist/i.test(line)) { + return 'a path that does not exist' + } + + const denied = /^Permission to use (\w+) with command\s+(?:cd\s+\S+\s*(?:&&|;)\s*)?([\w./-]+)[\s\S]*has been denied/.exec(line) + + if (denied !== null) { + return `Permission to use ${denied[1]} with command ${denied[2]} … was denied` + } + + const blocked = /^([\w./-]+) to .+ was blocked by a deny rule/.exec(line) + + if (blocked !== null) { + return `${blocked[1]} was blocked by a deny rule` + } + + if (/does not match required schema/i.test(line)) { + // Which property broke which constraint, once each: `/rules/13/category` and `/rules/27/category` are one fact. + const clauses = new Set<string>() + + for (const match of line.matchAll(/((?:\/[\w-]+)+): (must [a-z ]+?)(?=:|,|$)/g)) { + clauses.add(`${(match[1] ?? '').replace(/\/\d+(?=\/|$)/g, '/<n>')}: ${(match[2] ?? '').trim()}`) + } + + return `Output does not match required schema: ${[...clauses].join('; ')}`.slice(0, 140) + } + + if (/\(eval\):\d+: =+\S* not found/.test(line)) { + return '(eval):<n>: ==… not found' + } + + const key = line + .replace(/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?Z?\b/g, '<time>') + .replace(/(?:[A-Za-z]:)?(?:\/[\w.@~+-]+){2,}\/?/g, '<path>') + .replace(/\b0x[0-9a-fA-F]+\b/g, '<hex>') + .replace(/\b[0-9a-f]{12,}\b/g, '<id>') + .replace(/(["'`]).{1,60}?\1/g, '<q>') + .replace(/\b\d+(?:\.\d+)?\b/g, '<n>') + .replace(/\s+/g, ' ') + .trim() + .slice(0, 140) + + // What is left must still say something: `<n> <q>` and the like match everything. + return key.replace(/<\w+>|[^A-Za-z]+/g, ' ').trim().split(/\s+/).filter(word => word.length > 2).length >= 2 ? key : '' +} + +/** + * Records a failed call. Returns the signature when this failure is one to + * call out now: the first time enough agents share it, and again each time it + * has spread `ESCALATE_FACTOR` times further. `example` is what the failing + * call was aimed at (a path, a command's head). + */ +export function noteFailure( + fleet: Fleet, + agentId: string, + errorText: string, + nowMs: number, + example?: string, +): Signature | null { + const row = fleet.agents.get(agentId) + + fleet.errors += 1 + + if (row !== undefined) { + fleet.agents.set(agentId, { ...row, errors: row.errors + 1 }) + } + + const key = normalizeFailure(errorText) + + if (key.length < 12) { + return null + } + + const held = fleet.signatures.get(key) + + const signature: Signature = + held !== undefined && nowMs - held.lastMs <= SIGNATURE_WINDOW_MS + ? held + : { text: key, agents: new Set(), firstMs: nowMs, lastMs: nowMs, announcedAt: 0, announcedMs: 0, examples: [] } + + signature.agents.add(agentId) + signature.lastMs = nowMs + + if (example !== undefined && example !== '' && signature.examples.length < 3 && !signature.examples.includes(example)) { + signature.examples.push(example) + } + + fleet.signatures.set(key, signature) + + const size = signature.agents.size + + const isDue = + signature.announcedAt === 0 + ? size >= announceThresholdOf(fleet) + : size >= signature.announcedAt * ESCALATE_FACTOR && nowMs - signature.announcedMs >= ESCALATE_QUIET_MS + + if (isDue) { + signature.announcedAt = size + signature.announcedMs = nowMs + + return signature + } + + return null +} + +/** A shared failure in one line, with what the failing calls were aimed at. */ +export function lineOf(signature: Signature, form: 'full' | 'short' = 'full'): string { + const examples = signature.examples.slice(0, form === 'short' ? 1 : 2).join(', ') + const lead = form === 'short' ? `${signature.agents.size} agents: ` : `${signature.agents.size} agents hit the same failure: ` + + return `${lead}${signature.text}${examples !== '' ? ` (e.g. ${examples})` : ''}` +} + +/** Marks an agent's loop as ended (its `turn.complete`). */ +export function noteDone(fleet: Fleet, agentId: string, nowMs: number): void { + const row = fleet.agents.get(agentId) + + if (row !== undefined) { + if (!row.isDone) { + fleet.ended += 1 + } + + fleet.agents.set(agentId, { ...row, isDone: true, lastMs: nowMs }) + } +} + +/** The fleet in numbers, as the pane's header line shows it. */ +export function tallyOf(fleet: Fleet, nowMs: number) { + const rows = [...fleet.agents.values()] + const active = rows.filter(row => !row.isDone && nowMs - row.lastMs < IDLE_MS) + + return { + total: fleet.seen, + active: active.length, + done: fleet.ended, + stalled: rows.filter(row => !row.isDone && nowMs - row.lastMs >= IDLE_MS).length, + calls: fleet.calls, + errors: fleet.errors, + recent: active.sort((a, b) => b.lastMs - a.lastMs), + // The widest-spread first: the pane has room for two or three. + shared: [...fleet.signatures.values()] + .filter(signature => signature.agents.size >= SIGNATURE_THRESHOLD) + .sort((a, b) => b.agents.size - a.agents.size), + } +} + +/** Forgets agents that ended long ago, keeping the registry bounded on a long run. */ +export function prune(fleet: Fleet, nowMs: number, keepMs = 30 * 60_000, max = 1500): void { + if (fleet.agents.size <= max) { + return + } + + for (const [id, row] of fleet.agents) { + if ((row.isDone || nowMs - row.lastMs > keepMs) && fleet.agents.size > max) { + fleet.agents.delete(id) + fleet.unitHits.delete(id) + } + } +} diff --git a/plugins/code-modernization/hooks/hooks.json b/plugins/code-modernization/hooks/hooks.json new file mode 100644 index 00000000..7e99b4e0 --- /dev/null +++ b/plugins/code-modernization/hooks/hooks.json @@ -0,0 +1,4 @@ +{ + "description": "The modernization pane and estate map, x-ray reads, the rule review deck, the sign-off dialog and the fleet view", + "modules": ["./register.ts"] +} diff --git a/plugins/code-modernization/hooks/host.ts b/plugins/code-modernization/hooks/host.ts new file mode 100644 index 00000000..c315fecf --- /dev/null +++ b/plugins/code-modernization/hooks/host.ts @@ -0,0 +1,37 @@ +import type { + CommandSpec, + PaneCloseArgs, + PaneOpenArgs, + PromptFillArgs, + PromptSubmitArgs, + TimerCall, + UiBlitArgs, + UiBlitResult, +} from 'claude-code' + +import type { ReaderFs } from './reader/fs' + +/** + * The engine as `session.start` bound it from its `$`: every later hook, + * timer and button press reaches the engine through this, so the rest of + * the module is plain functions over a small interface a test can stand in for. + */ +export type Host = { + fs: ReaderFs & { write: (path: string, text: string) => Promise<void> } + now: () => Promise<number> + after: TimerCall + every: TimerCall + storeGet: (key: string) => Promise<unknown> + storeSet: (key: string, value: unknown) => Promise<void> + invalidate: () => void + blit: (args: UiBlitArgs) => Promise<UiBlitResult> + status: (text: string | undefined) => void + toast: (text: string, timeoutMs?: number) => void + log: (text: string) => void + openPane: (pane: PaneOpenArgs) => Promise<void> + closePane: (pane: PaneCloseArgs) => Promise<void> + registerCommand: (spec: CommandSpec) => Promise<unknown> + fillPrompt: (input: PromptFillArgs) => Promise<{ isFilled: boolean }> + submitPrompt: (input: PromptSubmitArgs) => Promise<unknown> + abortTurn: (turnId: string) => Promise<void> +} diff --git a/plugins/code-modernization/hooks/map/estate.ts b/plugins/code-modernization/hooks/map/estate.ts new file mode 100644 index 00000000..b3bd3d3a --- /dev/null +++ b/plugins/code-modernization/hooks/map/estate.ts @@ -0,0 +1,191 @@ +import { estateOfTopology, type EstateUnit } from '../reader/estate-model' +import type { ModuleState } from '../reader/modernized' +import type { Snapshot } from '../reader/progress' +import { STATE_WORDS_BY_TRACK, type TrackKey } from '../reader/tracks' +import { DEFAULT_COLOR, luma, mix, packCells, type Cell } from './raster' +import { layoutGroups, type Rect } from './treemap' + +/** + * The estate map: every unit of the legacy system as a tile, sized by its lines of code + * (or bytes of source, where there is no map), grouped by domain or directory, coloured by + * how far its modernization has come, and lit for a moment when a file beneath it is read or written. + */ + +export type TouchKind = 'read' | 'write' + +export type Touch = { atMs: number; kind: TouchKind } + +export type TileState = ModuleState | 'untouched' + +export type Tile = { + id: string + name: string + domain: string + loc: number + state: TileState + rect: Rect + isNext: boolean +} + +export type Estate = { + columns: number + rows: number + tiles: Tile[] + /** Base64 for the Raster's `cells`. */ + cells: string + /** True while any tile is still fading from a touch, so another frame is due. */ + isAnimating: boolean +} + +/** How long a touch stays visible, in milliseconds. */ +export const FLASH_MS = 4000 + +export const STATE_COLORS: Record<TileState, number> = { + untouched: 0x39414f, + scaffolded: 0x4b5d80, + 'tests-written': 0x94741f, + 'tests-red': 0xb23b3b, + 'tests-green': 0x2c7a4c, + reviewed: 0x2fa568, + ported: 0x2b8ea6, + switched: 0x3bd184, +} + +/** What a state is called in a track: the same colors, worded for what the work is. */ +export const stateWord = (track: TrackKey, state: TileState): string => STATE_WORDS_BY_TRACK[track][state] ?? state + +const FLASH_COLORS: Record<TouchKind, number> = { + read: 0x9fd4ff, + write: 0xffe27a, +} + +/** A stable small jitter per tile, so neighbours of one state still read as separate tiles. */ +const jitterOf = (id: string): number => { + let hash = 2166136261 + + for (let index = 0; index < id.length; index += 1) { + hash = Math.imul(hash ^ id.charCodeAt(index), 16777619) + } + + return ((hash >>> 0) % 1000) / 1000 +} + +/** The module ids of the step the snapshot says comes next, when it is a transform. */ +function nextModuleOf(snapshot: Snapshot): string | null { + const text = snapshot.next?.text ?? '' + const match = /transform\s+\S+\s+(\S+)/.exec(text) + + return snapshot.next?.isByHand === false ? (match?.[1] ?? null) : null +} + +/** Lays the snapshot's estate out in `columns` by `rows` cells. */ +export function tilesOf(snapshot: Snapshot, columns: number, rows: number): Tile[] { + const estate = snapshot.estate ?? (snapshot.topology !== null ? estateOfTopology(snapshot.topology, 0) : null) + + if (estate === null || columns < 4 || rows < 2) { + return [] + } + + const next = nextModuleOf(snapshot) + const groups = new Map<string, EstateUnit[]>() + + for (const unit of estate.units) { + const members = groups.get(unit.group) ?? [] + + members.push(unit) + groups.set(unit.group, members) + } + + const placed = layoutGroups( + [...groups.entries()].map(([name, members]) => ({ + name, + items: members.map(unit => ({ item: unit, size: Math.max(1, unit.size) })), + })), + { x: 0, y: 0, w: columns, h: rows }, + ) + + return placed.flatMap(group => + group.items + .filter(entry => entry.rect.w > 0 && entry.rect.h > 0) + .map(entry => ({ + id: entry.item.id, + name: entry.item.name, + domain: group.name, + loc: entry.item.size, + state: snapshot.byNode.get(entry.item.id)?.state ?? ('untouched' as const), + rect: entry.rect, + isNext: entry.item.id === next, + })), + ) +} + +/** Paints the tiles into cells and packs them for the Raster. */ +export function paint( + tiles: readonly Tile[], + columns: number, + rows: number, + touches: ReadonlyMap<string, Touch>, + nowMs: number, +): Estate { + const blank: Cell = { glyph: ' ', fg: DEFAULT_COLOR, bg: DEFAULT_COLOR } + const cells: Cell[] = Array.from({ length: columns * rows }, () => blank) + let isAnimating = false + + for (const tile of tiles) { + const base = mix(STATE_COLORS[tile.state], 0xffffff, (jitterOf(tile.id) - 0.5) * 0.14 + 0.02) + const touch = touches.get(tile.id) + const age = touch !== undefined ? nowMs - touch.atMs : Infinity + const heat = age < FLASH_MS ? 1 - age / FLASH_MS : 0 + + if (heat > 0) { + isAnimating = true + } + + const body = heat > 0 && touch !== undefined ? mix(base, FLASH_COLORS[touch.kind], heat * 0.85) : base + const edge = mix(body, 0x000000, 0.32) + const ink = luma(body) > 140 ? 0x101418 : 0xf2f5f8 + const { x, y, w, h } = tile.rect + const hasBevel = w >= 3 && h >= 2 + const label = w >= 4 ? (tile.isNext ? '▸' : '') + tile.name : w >= 2 && tile.isNext ? '▸' : '' + const shown = label.slice(0, Math.max(0, w - (hasBevel ? 1 : 0))) + + for (let row = 0; row < h; row += 1) { + for (let col = 0; col < w; col += 1) { + const cx = x + col + const cy = y + row + + if (cx >= columns || cy >= rows) { + continue + } + + const isEdge = hasBevel && (col === w - 1 || row === h - 1) + const glyph = row === 0 && col < shown.length ? (shown[col] ?? ' ') : ' ' + + cells[cy * columns + cx] = { glyph, fg: ink, bg: isEdge ? edge : body } + } + } + } + + return { columns, rows, tiles: [...tiles], cells: packCells(cells), isAnimating } +} + +/** How many modules sit in each state, in the order the legend draws them. */ +export function countsOf(tiles: readonly Tile[]): { state: TileState; count: number }[] { + const order: TileState[] = [ + 'untouched', + 'scaffolded', + 'tests-written', + 'tests-red', + 'tests-green', + 'reviewed', + 'ported', + 'switched', + ] + + return order + .map(state => ({ state, count: tiles.filter(tile => tile.state === state).length })) + .filter(entry => entry.count > 0) +} + +/** `0x00RRGGBB` as the `#rrggbb` a `Text`'s `color` takes. */ +export const hexOf = (color: number): string => `#${(color & 0xffffff).toString(16).padStart(6, '0')}` diff --git a/plugins/code-modernization/hooks/map/raster.ts b/plugins/code-modernization/hooks/map/raster.ts new file mode 100644 index 00000000..1a9b0ee0 --- /dev/null +++ b/plugins/code-modernization/hooks/map/raster.ts @@ -0,0 +1,92 @@ +/** + * Packing for the terminal's `Raster` element: a grid of cells, each a glyph + * with a foreground and a background colour, as the base64 the element takes + * (`columns * rows` little-endian u32 triplets `[codePoint, fg, bg]`). + */ + +export type Cell = { glyph: string; fg: number; bg: number } + +/** The terminal's own default colour, as `RasterProps` spells it. */ +export const DEFAULT_COLOR = 0x01000000 + +const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + +/** Standard padded base64 of bytes, with no dependence on `btoa` or `Uint8Array.toBase64`. */ +export function base64Of(bytes: Uint8Array): string { + let out = '' + + for (let index = 0; index < bytes.length; index += 3) { + const a = bytes[index] ?? 0 + const b = bytes[index + 1] ?? 0 + const c = bytes[index + 2] ?? 0 + const has2 = index + 1 < bytes.length + const has3 = index + 2 < bytes.length + + out += + (B64[a >> 2] ?? '') + + (B64[((a & 3) << 4) | (b >> 4)] ?? '') + + (has2 ? (B64[((b & 15) << 2) | (c >> 6)] ?? '') : '=') + + (has3 ? (B64[c & 63] ?? '') : '=') + } + + return out +} + +/** A printable width-1 BMP code point for `glyph`, or a space when it is not one. */ +export function codePointOf(glyph: string): number { + const point = glyph.codePointAt(0) ?? 0x20 + + const isPrintable = + point >= 0x20 && + point <= 0xffff && + point !== 0x7f && + !(point >= 0x80 && point < 0xa0) && + !(point >= 0xd800 && point <= 0xdfff) && + // East Asian wide and fullwidth ranges draw two cells. + !(point >= 0x1100 && point <= 0x115f) && + !(point >= 0x2e80 && point <= 0xa4cf) && + !(point >= 0xac00 && point <= 0xd7a3) && + !(point >= 0xf900 && point <= 0xfaff) && + !(point >= 0xfe30 && point <= 0xfe6f) && + !(point >= 0xff00 && point <= 0xff60) && + !(point >= 0xffe0 && point <= 0xffe6) + + return isPrintable ? point : 0x20 +} + +/** Packs row-major `cells` (`columns * rows` of them) for a `Raster`'s `cells` prop. */ +export function packCells(cells: readonly Cell[]): string { + const bytes = new Uint8Array(cells.length * 12) + const view = new DataView(bytes.buffer) + + cells.forEach((cell, index) => { + view.setUint32(index * 12, codePointOf(cell.glyph), true) + view.setUint32(index * 12 + 4, cell.fg >>> 0, true) + view.setUint32(index * 12 + 8, cell.bg >>> 0, true) + }) + + return base64Of(bytes) +} + +/** `0x00RRGGBB` from three 0-255 channels. */ +export const rgb = (r: number, g: number, b: number): number => + ((Math.max(0, Math.min(255, Math.round(r))) << 16) | + (Math.max(0, Math.min(255, Math.round(g))) << 8) | + Math.max(0, Math.min(255, Math.round(b)))) >>> + 0 + +/** `a` moved `t` of the way (0 to 1) toward `b`, channel by channel. */ +export function mix(a: number, b: number, t: number): number { + const k = Math.max(0, Math.min(1, t)) + const ch = (c: number, shift: number) => (c >> shift) & 0xff + + return rgb( + ch(a, 16) + (ch(b, 16) - ch(a, 16)) * k, + ch(a, 8) + (ch(b, 8) - ch(a, 8)) * k, + ch(a, 0) + (ch(b, 0) - ch(a, 0)) * k, + ) +} + +/** Perceived brightness, 0 to 255. */ +export const luma = (color: number): number => + 0.299 * ((color >> 16) & 0xff) + 0.587 * ((color >> 8) & 0xff) + 0.114 * (color & 0xff) diff --git a/plugins/code-modernization/hooks/map/treemap.ts b/plugins/code-modernization/hooks/map/treemap.ts new file mode 100644 index 00000000..21042734 --- /dev/null +++ b/plugins/code-modernization/hooks/map/treemap.ts @@ -0,0 +1,156 @@ +/** + * A squarified treemap over a grid of terminal cells, two levels deep: + * groups (domains) first, then each group's items (modules) inside its + * rectangle. Pure: sizes in, integer cell rectangles out. + * + * A terminal cell is about twice as tall as it is wide, so the layout works + * in a space where each row counts double and rounds back to whole cells. + */ + +export type Rect = { x: number; y: number; w: number; h: number } + +export type Sized<T> = { item: T; size: number } + +export type Placed<T> = { item: T; rect: Rect } + +/** How much taller than wide one cell is; rows are weighted by it when judging squareness. */ +const CELL_ASPECT = 2 + +const worst = (row: number[], side: number, scale: number): number => { + const sum = row.reduce((a, b) => a + b, 0) + + if (sum === 0 || side === 0) { + return Infinity + } + + const max = Math.max(...row) + const min = Math.min(...row) + const s2 = sum * sum + const side2 = side * side * scale + + return Math.max((side2 * max) / s2, s2 / (side2 * min)) +} + +/** + * Squarified layout of `sizes` (already scaled so they sum to the area of + * `rect`) into fractional rectangles, in the order given. + */ +function squarify(sizes: number[], rect: Rect): Rect[] { + const out: Rect[] = [] + let { x, y, w, h } = rect + let index = 0 + + while (index < sizes.length) { + // Lay rows along the visually shorter side. + const isWide = w >= h * CELL_ASPECT + const side = isWide ? h : w + const scale = isWide ? CELL_ASPECT : 1 / CELL_ASPECT + const row: number[] = [] + + while (index < sizes.length) { + const next = sizes[index] ?? 0 + const grown = [...row, next] + + if (row.length > 0 && worst(grown, side, scale) > worst(row, side, scale)) { + break + } + + row.push(next) + index += 1 + } + + const sum = row.reduce((a, b) => a + b, 0) + const thick = side > 0 ? sum / side : 0 + let offset = 0 + + for (const size of row) { + const length = thick > 0 ? size / thick : 0 + + out.push( + isWide + ? { x, y: y + offset, w: thick, h: length } + : { x: x + offset, y, w: length, h: thick }, + ) + + offset += length + } + + if (isWide) { + x += thick + w -= thick + } else { + y += thick + h -= thick + } + + if (w <= 0 || h <= 0) { + // Out of room: whatever is left collapses onto the last edge. + while (index < sizes.length) { + out.push({ x: rect.x + rect.w, y: rect.y + rect.h, w: 0, h: 0 }) + index += 1 + } + } + } + + return out +} + +/** Rounds fractional rectangles to whole cells without gaps or overlaps on shared edges. */ +function snap(rects: Rect[], bounds: Rect): Rect[] { + const clampX = (v: number) => Math.min(bounds.x + bounds.w, Math.max(bounds.x, Math.round(v))) + const clampY = (v: number) => Math.min(bounds.y + bounds.h, Math.max(bounds.y, Math.round(v))) + + return rects.map(rect => { + const x0 = clampX(rect.x) + const y0 = clampY(rect.y) + const x1 = clampX(rect.x + rect.w) + const y1 = clampY(rect.y + rect.h) + + return { x: x0, y: y0, w: Math.max(0, x1 - x0), h: Math.max(0, y1 - y0) } + }) +} + +/** Lays `entries` out in `rect`, largest first, each given at least `floor` of the mean size. */ +export function layout<T>(entries: Sized<T>[], rect: Rect, floor = 0.35): Placed<T>[] { + if (entries.length === 0 || rect.w <= 0 || rect.h <= 0) { + return [] + } + + const positive = entries.map(entry => ({ ...entry, size: Math.max(0, entry.size) })) + const mean = positive.reduce((sum, entry) => sum + entry.size, 0) / positive.length || 1 + + // A tiny item next to a huge one would round to zero cells: lift it to a floor. + const lifted = positive + .map(entry => ({ ...entry, size: Math.max(entry.size, mean * floor) })) + .sort((a, b) => b.size - a.size) + + const total = lifted.reduce((sum, entry) => sum + entry.size, 0) + const area = rect.w * rect.h + const scaled = lifted.map(entry => (entry.size / total) * area) + const snapped = snap(squarify(scaled, rect), rect) + + return lifted.map((entry, index) => ({ + item: entry.item, + rect: snapped[index] ?? { x: rect.x, y: rect.y, w: 0, h: 0 }, + })) +} + +export type Group<T> = { name: string; items: Sized<T>[] } + +export type PlacedGroup<T> = { name: string; rect: Rect; items: Placed<T>[] } + +/** Two-level layout: groups by their items' total size, then items within each group. */ +export function layoutGroups<T>(groups: Group<T>[], rect: Rect): PlacedGroup<T>[] { + const sized = groups + .filter(group => group.items.length > 0) + .map(group => ({ + item: group, + size: group.items.reduce((sum, entry) => sum + Math.max(0, entry.size), 0), + })) + + return layout(sized, rect, 0.2).map(placed => ({ + name: placed.item.name, + rect: placed.rect, + items: layout(placed.item.items, placed.rect), + })) +} diff --git a/plugins/code-modernization/hooks/paths.ts b/plugins/code-modernization/hooks/paths.ts new file mode 100644 index 00000000..ce34edd1 --- /dev/null +++ b/plugins/code-modernization/hooks/paths.ts @@ -0,0 +1,94 @@ +/** + * Path helpers. A hooks module has no `path` module: these are the few + * string operations the hooks need, all over forward-slash paths. + */ + +/** Forward slashes, no doubled separators, no trailing slash (root stays `/`). */ +export function norm(path: string): string { + const clean = path.replace(/\\/g, '/').replace(/\/{2,}/g, '/') + + return clean.length > 1 && clean.endsWith('/') ? clean.slice(0, -1) : clean +} + +/** Resolves `.` and `..` segments lexically; absolute stays absolute. */ +export function resolveDots(path: string): string { + const isAbsolute = path.startsWith('/') + const out: string[] = [] + + for (const part of norm(path).split('/')) { + if (part === '' || part === '.') { + continue + } + + if (part === '..') { + if (out.length > 0 && out.at(-1) !== '..') { + out.pop() + } else if (!isAbsolute) { + out.push('..') + } + + continue + } + + out.push(part) + } + + return (isAbsolute ? '/' : '') + out.join('/') +} + +/** `path` made absolute against `cwd` when it is relative. */ +export function absOf(cwd: string, path: string): string { + return resolveDots(path.startsWith('/') ? path : `${norm(cwd)}/${path}`) +} + +/** + * `path` relative to `cwd` when it lies inside it, else null. Both may be + * given with or without the macOS `/private` prefix the engine sometimes adds. + */ +export function relTo(cwd: string, path: string): string | null { + const strip = (p: string) => p.replace(/^\/private(?=\/(?:tmp|var)\/)/, '') + const base = strip(norm(cwd)) + const full = strip(absOf(cwd, path)) + + if (full === base) { + return '' + } + + return full.startsWith(`${base}/`) ? full.slice(base.length + 1) : null +} + +/** True when relative path `rel` is `dir` or lies beneath it. */ +export function isUnder(rel: string, dir: string): boolean { + const d = norm(dir) + + return rel === d || rel.startsWith(`${d}/`) +} + +/** The last segment. */ +export function baseName(path: string): string { + const parts = norm(path).split('/') + + return parts.at(-1) ?? '' +} + +/** The last segment without its final extension. */ +export function stemOf(path: string): string { + const base = baseName(path) + const dot = base.lastIndexOf('.') + + return dot > 0 ? base.slice(0, dot) : base +} + +/** Everything but the last segment (`''` for a bare name). */ +export function dirName(path: string): string { + const parts = norm(path).split('/') + + parts.pop() + + return parts.join('/') +} + +/** Joins segments with single slashes. */ +export function join(...parts: string[]): string { + return norm(parts.filter(part => part !== '').join('/')) +} diff --git a/plugins/code-modernization/hooks/reader/brief.ts b/plugins/code-modernization/hooks/reader/brief.ts new file mode 100644 index 00000000..890aa58a --- /dev/null +++ b/plugins/code-modernization/hooks/reader/brief.ts @@ -0,0 +1,200 @@ +/** + * `analysis/<system>/MODERNIZATION_BRIEF.md`, read without a model: the + * target stack, the phases, which modules each phase names, the exit + * criteria boxes, and the approval block. + * + * The brief is prose an agent wrote, so every field is best-effort and a + * field that cannot be read is absent, never guessed. + */ + +export type Criterion = { + /** The line as written, checkbox included. */ + line: string + /** The criterion's text: the line without its checkbox and tick annotation. */ + text: string + isTicked: boolean +} + +export type Phase = { + number: number + title: string + /** `S`, `M`, `L`, `XL`, when the heading says. */ + size?: string + risk?: string + /** Module ids (as the caller's `knownModules` names them) the phase's text mentions. */ + modules: string[] + criteria: Criterion[] +} + +export type Approval = { + isSigned: boolean + by?: string + date?: string + /** `phase-1`, `full`, or undefined when the block does not say. */ + covers?: 'phase-1' | 'full' +} + +export type Brief = { + target?: string + phases: Phase[] + approval: Approval + /** Unticked `- [ ]` boxes under the Open Questions section. */ + openQuestions: number +} + +const PHASE_HEADING = /^#{2,4}\s+Phase\s+(\d+)\s*[—–:.\-]\s*(.+?)\s*$/i +const CHECKBOX = /^\s*[-*]\s+\[( |x|X)\]\s+(.*)$/ +const TICK_NOTE = /\s*\((?:[^()]*\d{4}-\d{2}-\d{2}[^()]*)\)\s*$/ + +const strip = (text: string) => text.replace(/\*\*/g, '').replace(/`/g, '').trim() + +/** The criterion text of a checkbox line, its tick annotation `(who, date)` removed. */ +export function criterionTextOf(line: string): string | null { + const match = CHECKBOX.exec(line) + + if (match === null) { + return null + } + + return strip((match[2] ?? '').replace(TICK_NOTE, '')).replace(/\s+/g, ' ') +} + +/** + * Parses the brief. + * + * @param text the file + * @param knownModules module ids from topology.json; a phase lists the ones + * its text mentions as whole words + */ +export function parseBrief(text: string, knownModules: readonly string[] = []): Brief { + const lines = text.split('\n') + + const titleLine = lines.find(line => /^#\s+/.test(line)) ?? '' + const arrow = /[→>]\s*(.+?)\s*$/.exec(titleLine.replace(/->/g, '→')) + const target = arrow?.[1] !== undefined ? strip(arrow[1]) : undefined + + const phases: Phase[] = [] + let current: { phase: Phase; body: string[]; level: number } | null = null + let section = '' + let openQuestions = 0 + + const closePhase = () => { + if (current === null) { + return + } + + const body = current.body.join('\n') + + // The modules a phase names, the pilot's first and the rest in the order the phase + // names them: the first one open is what the next step runs, and topology order + // would put an identity screen ahead of a batch job the brief chose as its pilot. + const wholeWord = (id: string) => + new RegExp(`(?<![A-Za-z0-9_])${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9_])`) + + const pilotLine = /^.*\bpilot unit\b.*$/im.exec(body)?.[0] ?? '' + + current.phase.modules = knownModules + .map(id => ({ id, at: body.search(wholeWord(id)), isPilot: wholeWord(id).test(pilotLine) })) + .filter(entry => entry.at >= 0) + .sort((a, b) => Number(b.isPilot) - Number(a.isPilot) || a.at - b.at) + .map(entry => entry.id) + + phases.push(current.phase) + current = null + } + + for (const line of lines) { + const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line) + + if (heading !== null) { + const level = heading[1]?.length ?? 1 + const phase = PHASE_HEADING.exec(line) + + if (phase !== null) { + closePhase() + + const parts = (phase[2] ?? '').split('·').map(part => strip(part)) + const size = parts.map(part => /^Size\s+(\w+)/i.exec(part)?.[1]).find(Boolean) + const risk = parts.map(part => /^Risk\s+(\w+)/i.exec(part)?.[1]).find(Boolean) + + current = { + level, + body: [line], + phase: { + number: Number(phase[1]), + title: parts[0] ?? '', + ...(size !== undefined && { size: size.toUpperCase() }), + ...(risk !== undefined && { risk }), + modules: [], + criteria: [], + }, + } + + continue + } + + if (current !== null && level <= current.level) { + closePhase() + } + + if (level <= 2) { + section = strip(heading[2] ?? '').toLowerCase() + } + } + + if (current !== null) { + current.body.push(line) + + const box = CHECKBOX.exec(line) + const textOf = criterionTextOf(line) + + if (box !== null && textOf !== null) { + current.phase.criteria.push({ + line, + text: textOf, + isTicked: box[1] !== ' ', + }) + } + + continue + } + + if (/open questions/.test(section) && /^\s*[-*]\s+\[ \]/.test(line)) { + openQuestions += 1 + } + } + + closePhase() + + const approvedLine = lines.find(line => /^\s*Approved by\s*:/i.test(line)) + const by = approvedLine?.replace(/^\s*Approved by\s*:/i, '').replace(/Date\s*:.*$/i, '').trim() + const isSigned = by !== undefined && by !== '' && !/^_+$/.test(by.replace(/\s/g, '')) + + const dateLine = lines.find(line => /^\s*(?:Approved by\s*:.*)?Date\s*:\s*\S/i.test(line)) + const date = /Date\s*:\s*(\d{4}-\d{2}-\d{2}|[^\s_][^_\n]*?)\s*$/i.exec(dateLine ?? '')?.[1] + + const coversLine = lines.find(line => /Approval covers\s*:/i.test(line)) ?? '' + const ticked = [...coversLine.matchAll(/\[\s*[xX]\s*\]\s*([^[\]|]+)/g)].map(m => (m[1] ?? '').trim()) + + const plain = coversLine.replace(/^.*Approval covers\s*:/i, '').trim() + + const coversText = ticked[0] ?? (/\[/.test(coversLine) || /\|/.test(plain) ? '' : plain) + + const covers = /full/i.test(coversText) + ? ('full' as const) + : /phase\s*1/i.test(coversText) + ? ('phase-1' as const) + : undefined + + return { + ...(target !== undefined && target !== '' && { target }), + phases, + approval: { + isSigned, + ...(isSigned && by !== undefined && { by }), + ...(isSigned && date !== undefined && { date: date.trim() }), + ...(isSigned && covers !== undefined && { covers }), + }, + openQuestions, + } +} diff --git a/plugins/code-modernization/hooks/reader/discover.ts b/plugins/code-modernization/hooks/reader/discover.ts new file mode 100644 index 00000000..b6ab6117 --- /dev/null +++ b/plugins/code-modernization/hooks/reader/discover.ts @@ -0,0 +1,341 @@ +import { baseName, join, stemOf } from '../paths' +import { + groupOfDir, + languageOf, + weightOf, + type EstateModel, + type EstateUnit, +} from './estate-model' +import { listOrEmpty, type ReaderFs } from './fs' + +/** + * Reads the estate off the legacy tree when no map exists: any language, any + * layout. A directory with a build file of its own is one unit (a Maven or Gradle + * module, an npm package, a .NET project, a Go module, a Python package); a tree + * with no build files is one unit per source file when it is small enough to show, + * else one per directory. Sizes are bytes of source: what the file system knows + * without reading a file. + */ + +/** Directories that hold what a build made or what someone else wrote, never the system's own code. */ +const SKIP_DIRS = new Set([ + '.git', '.hg', '.svn', 'node_modules', 'target', 'dist', 'obj', 'build', 'out', '.gradle', '.idea', '.vscode', + '__pycache__', '.venv', 'venv', '.tox', '.mypy_cache', '.pytest_cache', 'coverage', '.next', '.nuxt', 'Pods', + 'vendor', 'bower_components', 'site-packages', +]) + +const MANIFEST_NAMES = new Set([ + 'pom.xml', 'build.gradle', 'build.gradle.kts', 'package.json', 'go.mod', 'Cargo.toml', 'pyproject.toml', + 'setup.py', 'composer.json', 'Gemfile', 'mix.exs', 'CMakeLists.txt', 'pubspec.yaml', 'Package.swift', + 'build.sbt', 'project.clj', 'deps.edn', 'cpanfile', 'Makefile.PL', 'BUILD.bazel', 'Project.toml', +]) + +const MANIFEST_SUFFIXES = ['.csproj', '.fsproj', '.vbproj', '.vcxproj'] + +const isManifest = (name: string): boolean => MANIFEST_NAMES.has(name) || MANIFEST_SUFFIXES.some(suffix => name.endsWith(suffix)) + +/** What a walk may spend: directories read, and entries seen. */ +export type Budget = { dirs: number; entries: number } + +export const DEFAULT_BUDGET: Budget = { dirs: 4000, entries: 80_000 } + +/** A file-per-unit estate is shown only up to this many source files. */ +const MAX_FILE_UNITS = 500 + +/** The most units an estate keeps; the rest are too small to draw. */ +const MAX_UNITS = 1500 + +type DirInfo = { + /** Source bytes in files directly in this directory. */ + bytes: number + /** The same, counting files of a kind no list knows: the tree may be written in a language this one does not name. */ + lenientBytes: number + files: { name: string; size: number; lenient: number; raw: number }[] + dirs: string[] + hasManifest: boolean +} + +/** Reads every directory under `root` that the budget allows, keyed by path relative to it (`''` is the root). */ +export async function walk( + fs: ReaderFs, + root: string, + budget: Budget, +): Promise<{ dirs: Map<string, DirInfo>; isPartial: boolean; files: number; bytesByLanguage: Map<string, number> }> { + const dirs = new Map<string, DirInfo>() + const bytesByLanguage = new Map<string, number>() + let queue: string[] = [''] + let readDirs = 0 + let entries = 0 + let files = 0 + let isPartial = false + + while (queue.length > 0) { + const room = budget.dirs - readDirs + + if (room <= 0 || entries > budget.entries) { + isPartial = true + + break + } + + const level = queue.slice(0, Math.min(16, room)) + + queue = queue.slice(level.length) + readDirs += level.length + + const listed = await Promise.all(level.map(rel => listOrEmpty(fs, rel === '' ? root : join(root, rel)))) + + level.forEach((rel, index) => { + const list = listed[index] ?? [] + const info: DirInfo = { bytes: 0, lenientBytes: 0, files: [], dirs: [], hasManifest: false } + + entries += list.length + + for (const entry of list) { + if (entry.kind === 'dir') { + if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) { + info.dirs.push(entry.name) + queue.push(rel === '' ? entry.name : `${rel}/${entry.name}`) + } + + continue + } + + if (entry.kind !== 'file') { + continue + } + + if (isManifest(entry.name)) { + info.hasManifest = true + } + + const strict = weightOf(entry.name, entry.size) + const lenient = weightOf(entry.name, entry.size, true) + + if (lenient > 0) { + info.files.push({ name: entry.name, size: strict, lenient, raw: entry.size }) + info.bytes += strict + info.lenientBytes += lenient + files += 1 + } + + const language = strict > 0 ? languageOf(entry.name) : undefined + + if (language !== undefined) { + bytesByLanguage.set(language, (bytesByLanguage.get(language) ?? 0) + strict) + } + } + + dirs.set(rel, info) + }) + } + + if (queue.length > 0) { + isPartial = true + } + + return { dirs, isPartial, files, bytesByLanguage } +} + +/** Every file a walk counted, by path relative to its root, with its size in bytes. */ +export function sizesOf(dirs: Map<string, DirInfo>): Map<string, number> { + const sizes = new Map<string, number>() + + for (const [rel, info] of dirs) { + for (const file of info.files) { + sizes.set(rel === '' ? file.name : `${rel}/${file.name}`, file.raw) + } + } + + return sizes +} + +/** + * The files under `root` and their sizes, read with the file API alone: nothing is run inside the tree. + * Null when the walk hit its budget, since a partial listing would call every unread file changed. + */ +export async function sourceSizes(fs: ReaderFs, root: string, budget: Budget = DEFAULT_BUDGET): Promise<Map<string, number> | null> { + const walked = await walk(fs, root, budget) + + return walked.isPartial ? null : sizesOf(walked.dirs) +} + +/** Bytes under `rel`, every directory beneath included. */ +function totalBytes(dirs: Map<string, DirInfo>, rel: string): number { + const info = dirs.get(rel) + + if (info === undefined) { + return 0 + } + + return info.dirs.reduce( + (sum, name) => sum + totalBytes(dirs, rel === '' ? name : `${rel}/${name}`), + info.bytes, + ) +} + +const under = (path: string, dir: string): boolean => dir === '' || path === dir || path.startsWith(`${dir}/`) + +/** Units where each directory with a build file is one, sized by the bytes not inside a unit beneath it. */ +function buildModules(dirs: Map<string, DirInfo>, rootLabel: string): EstateUnit[] { + const manifestDirs = [...dirs.entries()].filter(([, info]) => info.hasManifest).map(([rel]) => rel) + const set = new Set(manifestDirs) + + const ownBytes = (rel: string): number => { + const info = dirs.get(rel) + + if (info === undefined) { + return 0 + } + + return info.dirs.reduce((sum, name) => { + const child = rel === '' ? name : `${rel}/${name}` + + return set.has(child) ? sum : sum + ownBytes(child) + }, info.bytes) + } + + return manifestDirs + .map(rel => ({ + id: rel === '' ? '.' : rel, + name: rel === '' ? rootLabel : baseName(rel), + group: rel === '' ? rootLabel : groupOfDir(rel, rootLabel), + size: ownBytes(rel), + dir: rel, + })) + .filter(unit => unit.size > 0) +} + +/** One unit per source file, grouped by the directory it sits in. */ +function fileUnits(dirs: Map<string, DirInfo>, rootLabel: string): EstateUnit[] { + const units: EstateUnit[] = [] + + for (const [rel, info] of dirs) { + for (const file of info.files) { + if (file.size <= 0) { + continue + } + + const path = rel === '' ? file.name : `${rel}/${file.name}` + + units.push({ + id: path, + name: stemOf(file.name), + group: rel === '' ? rootLabel : rel, + size: Math.max(1, file.size), + file: path, + }) + } + } + + return units +} + +/** One unit per directory: the top-level ones, and the children of a lone directory that holds nearly everything. */ +function directoryUnits(dirs: Map<string, DirInfo>, rootLabel: string): EstateUnit[] { + const total = totalBytes(dirs, '') + let parent = '' + + for (let guard = 0; guard < 4; guard += 1) { + const info = dirs.get(parent) + const children = info?.dirs ?? [] + const sizes = children.map(name => ({ name, bytes: totalBytes(dirs, parent === '' ? name : `${parent}/${name}`) })) + const largest = sizes.sort((a, b) => b.bytes - a.bytes)[0] + + if (largest === undefined || total === 0 || largest.bytes / total < 0.85 || (info?.bytes ?? 0) / total > 0.05) { + break + } + + parent = parent === '' ? largest.name : `${parent}/${largest.name}` + } + + const info = dirs.get(parent) + const units: EstateUnit[] = [] + + for (const name of info?.dirs ?? []) { + const rel = parent === '' ? name : `${parent}/${name}` + const size = totalBytes(dirs, rel) + + if (size > 0) { + units.push({ id: rel, name, group: parent === '' ? rootLabel : parent, size, dir: rel }) + } + } + + if ((info?.bytes ?? 0) > 0) { + units.push({ id: parent === '' ? '.' : parent, name: parent === '' ? `${rootLabel} (files)` : `${baseName(parent)} (files)`, group: parent === '' ? rootLabel : parent, size: info?.bytes ?? 0, dir: parent }) + } + + return units +} + +/** + * The estate of one system, read off `<root>` (its directory under the legacy tree). Null when the + * directory holds no source. + */ +export async function discoverEstate( + fs: ReaderFs, + root: string, + rootLabel: string, + budget: Budget = DEFAULT_BUDGET, +): Promise<EstateModel | null> { + const walked = await walk(fs, root, budget) + + if (walked.files === 0) { + return null + } + + // A tree written in a language nobody listed has almost no weight on a strict count: count every file of an unknown + // kind as source then, so the estate is the tree and not the few configuration files beside it. + const strictTotal = [...walked.dirs.values()].reduce((sum, info) => sum + info.bytes, 0) + const lenientTotal = [...walked.dirs.values()].reduce((sum, info) => sum + info.lenientBytes, 0) + + if (lenientTotal > 0 && strictTotal < lenientTotal * 0.35) { + for (const info of walked.dirs.values()) { + info.bytes = info.lenientBytes + + for (const file of info.files) { + file.size = file.lenient + } + } + } + + const counted = [...walked.dirs.values()].reduce((sum, info) => sum + info.files.filter(file => file.size > 0).length, 0) + const manifestCount = [...walked.dirs.entries()].filter(([rel, info]) => info.hasManifest && rel !== '').length + + let units: EstateUnit[] + let granularity: EstateModel['granularity'] + + if (manifestCount >= 2) { + units = buildModules(walked.dirs, rootLabel) + granularity = 'build module' + } else if (counted <= MAX_FILE_UNITS) { + units = fileUnits(walked.dirs, rootLabel) + granularity = 'file' + } else { + units = directoryUnits(walked.dirs, rootLabel) + granularity = 'directory' + } + + if (units.length === 0) { + return null + } + + const total = [...walked.bytesByLanguage.values()].reduce((sum, bytes) => sum + bytes, 0) + + const languages = [...walked.bytesByLanguage.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, 3) + .map(([name, bytes]) => ({ name, share: total > 0 ? bytes / total : 0 })) + + return { + source: 'tree', + measure: 'bytes', + granularity, + units: units.sort((a, b) => b.size - a.size).slice(0, MAX_UNITS), + files: counted, + languages, + isPartial: walked.isPartial, + fileSizes: sizesOf(walked.dirs), + } +} + diff --git a/plugins/code-modernization/hooks/reader/estate-model.ts b/plugins/code-modernization/hooks/reader/estate-model.ts new file mode 100644 index 00000000..fb8204a3 --- /dev/null +++ b/plugins/code-modernization/hooks/reader/estate-model.ts @@ -0,0 +1,213 @@ +import { baseName, dirName, norm, stemOf } from '../paths' +import { nodeOfFile, type Topology } from './topology' + +/** + * The estate: the units a system's code is divided into, whatever its language. + * They come from the map's `topology.json` when there is one and from the legacy + * tree itself when there is not, so the pane has a map from the first minute of + * a session in any workspace. + */ + +export type EstateUnit = { + id: string + name: string + /** What the tile sits under: a domain, or the directory that holds the unit. */ + group: string + /** Lines when the map gave them, bytes of source when the unit was read off the tree. */ + size: number + /** The unit as a directory, relative to `legacy/<system>/` (`''` is the system root). */ + dir?: string + /** The unit as one file, relative to `legacy/<system>/`. */ + file?: string +} + +/** What one unit is: a module the map named, a source file, a build module (a directory with its own build file), or a directory. */ +export type Granularity = 'module' | 'file' | 'build module' | 'directory' + +export type EstateModel = { + source: 'map' | 'tree' + /** What `size` counts. */ + measure: 'lines' | 'bytes' + /** What a unit is, for the pane's words. */ + granularity: Granularity + units: EstateUnit[] + /** Source files seen under the system root. */ + files: number + /** The languages the files are written in, largest first, as shares of the source bytes. */ + languages: { name: string; share: number }[] + /** True when the walk stopped at its budget: the sizes are a floor. */ + isPartial: boolean + /** Every source or configuration file the walk saw, relative to the system root, with its size in bytes. Kept to compare a working copy with the tree it was copied from; absent for an estate the map gave. */ + fileSizes?: ReadonlyMap<string, number> +} + +/** A language's name by file extension: the common ones, and the mainframe and scripting ones legacy work meets. */ +const LANGUAGES: Record<string, string> = { + java: 'Java', kt: 'Kotlin', kts: 'Kotlin', scala: 'Scala', groovy: 'Groovy', clj: 'Clojure', + cs: 'C#', vb: 'VB.NET', fs: 'F#', aspx: 'ASP.NET', ascx: 'ASP.NET', cshtml: 'Razor', asp: 'Classic ASP', + py: 'Python', rb: 'Ruby', php: 'PHP', pl: 'Perl', pm: 'Perl', lua: 'Lua', r: 'R', + js: 'JavaScript', mjs: 'JavaScript', cjs: 'JavaScript', jsx: 'JavaScript', ts: 'TypeScript', tsx: 'TypeScript', + go: 'Go', rs: 'Rust', swift: 'Swift', dart: 'Dart', ex: 'Elixir', exs: 'Elixir', erl: 'Erlang', hs: 'Haskell', + c: 'C', h: 'C', cc: 'C++', cpp: 'C++', cxx: 'C++', hpp: 'C++', m: 'Objective-C', + cbl: 'COBOL', cob: 'COBOL', cpy: 'COBOL', cobol: 'COBOL', pco: 'COBOL', jcl: 'JCL', bms: 'BMS', prc: 'JCL', + rpg: 'RPG', rpgle: 'RPG', sqlrpgle: 'RPG', clle: 'CL', pli: 'PL/I', pl1: 'PL/I', nat: 'Natural', asm: 'Assembler', + pas: 'Pascal', dpr: 'Delphi', bas: 'Basic', frm: 'VB6', cls: 'VB6', vbs: 'VBScript', + sql: 'SQL', sh: 'Shell', bash: 'Shell', ps1: 'PowerShell', bat: 'Batch', cmd: 'Batch', + jsp: 'JSP', xhtml: 'JSF', cfm: 'ColdFusion', tcl: 'Tcl', f: 'Fortran', f90: 'Fortran', for: 'Fortran', +} + +/** Extensions that are not source: assets, binaries, archives, lock files, data and prose. */ +const NOT_SOURCE = new Set([ + 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'bmp', 'webp', 'pdf', 'zip', 'gz', 'tgz', 'tar', 'jar', 'war', 'ear', + 'class', 'dll', 'exe', 'so', 'dylib', 'a', 'o', 'lib', 'pyc', 'woff', 'woff2', 'ttf', 'eot', 'otf', 'mp3', 'mp4', + 'mov', 'avi', 'wav', 'ogg', 'bin', 'dat', 'db', 'sqlite', 'log', 'lock', 'md', 'txt', 'rst', 'adoc', 'csv', 'tsv', + 'map', 'tmp', 'bak', 'orig', 'swp', 'ds_store', 'jks', 'p12', 'pem', 'crt', 'key', 'der', 'iso', 'img', 'rpm', 'deb', +]) + +/** Configuration and markup a build reads: part of the system, but never the bulk of its code. */ +const CONFIG_EXT = new Set([ + 'xml', 'json', 'yaml', 'yml', 'toml', 'properties', 'gradle', 'cfg', 'conf', 'ini', 'html', 'htm', 'css', 'scss', + 'less', 'vue', 'svelte', 'xsl', 'xslt', 'xsd', 'wsdl', 'proto', 'graphql', 'ftl', 'vm', 'tpl', 'twig', 'erb', + 'jspx', 'tag', 'tld', 'dtd', 'mustache', 'hbs', +]) + +const CONFIG_NAMES = new Set(['Makefile', 'Dockerfile', 'Jenkinsfile', 'Rakefile', 'Gemfile', 'Vagrantfile', 'Procfile']) + +const extOf = (name: string): string => { + const dot = name.lastIndexOf('.') + + return dot > 0 && dot < name.length - 1 ? name.slice(dot + 1).toLowerCase() : '' +} + +/** A single file counts for at most this much: one binary blob or one generated file must not be a system's bulk. */ +const CAP_SOURCE = 400_000 +const CAP_CONFIG = 100_000 + +/** + * What a file adds to the estate's size: its bytes (capped) when it is source or configuration, nothing when it is + * an asset, an archive, a document or a file of no known kind. `isLenient` counts unknown kinds as source too, for + * a language this list does not know. + */ +export function weightOf(name: string, size: number, isLenient = false): number { + if (name.startsWith('.')) { + return 0 + } + + const ext = extOf(name) + + if (NOT_SOURCE.has(ext)) { + return 0 + } + + if (LANGUAGES[ext] !== undefined) { + return Math.min(size, CAP_SOURCE) + } + + if (CONFIG_EXT.has(ext) || CONFIG_NAMES.has(name)) { + return Math.min(size, CAP_CONFIG) + } + + return isLenient ? Math.min(size, CAP_SOURCE) : 0 +} + +/** Whether a file is one the estate counts (source or configuration). */ +export const isSourceFile = (name: string): boolean => weightOf(name, 1) > 0 + +export const languageOf = (name: string): string | undefined => LANGUAGES[extOf(name)] + +/** A language name as a person writes it, from what a map recorded (`cobol` -> `COBOL`, `java` -> `Java`). */ +const nameOfLanguage = (raw: string): string => { + const known = Object.values(LANGUAGES).find(name => name.toLowerCase() === raw.toLowerCase()) + + return known ?? (raw.length <= 4 ? raw.toUpperCase() : raw.charAt(0).toUpperCase() + raw.slice(1)) +} + +/** The estate as a topology's modules, sized in lines. */ +export function estateOfTopology(topology: Topology, files: number): EstateModel { + const byLanguage = new Map<string, number>() + + for (const node of topology.modules) { + if (node.language !== undefined) { + byLanguage.set(nameOfLanguage(node.language), (byLanguage.get(nameOfLanguage(node.language)) ?? 0) + Math.max(1, node.loc)) + } + } + + const total = [...byLanguage.values()].reduce((sum, size) => sum + size, 0) + + return { + source: 'map', + measure: 'lines', + granularity: 'module', + units: topology.modules.map(node => ({ + id: node.id, + name: node.name, + group: node.domain ?? 'Other', + size: Math.max(1, node.loc), + ...(node.file !== undefined && { file: node.file }), + })), + files, + languages: [...byLanguage.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, 3) + .map(([name, size]) => ({ name, share: total > 0 ? size / total : 0 })), + isPartial: false, + } +} + +/** + * The unit a path under `legacy/<system>/` belongs to: by the map's own file + * where there is a map, else by the file itself or the nearest directory that is a unit. + */ +export function unitOfPath( + estate: EstateModel, + topology: Topology | null, + rel: string, +): EstateUnit | null { + const wanted = norm(rel) + + if (estate.source === 'map' && topology !== null) { + const node = nodeOfFile(topology, wanted) + + return node === null ? null : (estate.units.find(unit => unit.id === node.id) ?? null) + } + + const exact = estate.units.find(unit => unit.file === wanted) + + if (exact !== undefined) { + return exact + } + + let best: EstateUnit | null = null + let bestLength = -1 + + for (const unit of estate.units) { + const dir = unit.dir + + if (dir === undefined) { + continue + } + + const isInside = dir === '' || wanted === dir || wanted.startsWith(`${dir}/`) + + if (isInside && dir.length > bestLength) { + best = unit + bestLength = dir.length + } + } + + return best +} + +/** The names a transformed directory may be matched to a unit by: the id, the name, and the last path segment. */ +export function keysOfUnit(unit: EstateUnit): string[] { + const own = unit.dir !== undefined && unit.dir !== '' ? baseName(unit.dir) : unit.file !== undefined ? stemOf(unit.file) : '' + + return [unit.id, unit.name, own].filter(key => key !== '') +} + +/** The group a unit's directory sits in: its parent directory, or the root's own label. */ +export const groupOfDir = (dir: string, rootLabel: string): string => { + const parent = dirName(dir) + + return parent === '' ? rootLabel : parent +} diff --git a/plugins/code-modernization/hooks/reader/fs.ts b/plugins/code-modernization/hooks/reader/fs.ts new file mode 100644 index 00000000..44b570ed --- /dev/null +++ b/plugins/code-modernization/hooks/reader/fs.ts @@ -0,0 +1,54 @@ +/** + * The file access the reader needs, narrow enough that `$.fs` and a test's + * in-memory tree both satisfy it. Paths are relative to the session's + * working directory or absolute, as `$.fs` takes them. + */ +export type ReaderFs = { + read: (path: string) => Promise<string> + list: (path: string) => Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number }[]> + exists: (path: string) => Promise<boolean> + stat: (path: string) => Promise<{ kind: 'file' | 'dir' | 'other'; size: number; mtimeMs: number }> +} + +/** `read`, or null when the file is missing, unreadable or over the size cap. */ +export async function readOrNull(fs: ReaderFs, path: string): Promise<string | null> { + try { + // `exists` never rejects; asking first keeps a missing optional file out of the error log. + if (!(await fs.exists(path))) { + return null + } + + return await fs.read(path) + } catch { + return null + } +} + +/** `list`, or an empty list when the directory is missing. */ +export async function listOrEmpty( + fs: ReaderFs, + path: string, +): Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number }[]> { + try { + if (!(await fs.exists(path))) { + return [] + } + + return await fs.list(path) + } catch { + return [] + } +} + +/** `stat`'s mtime, or null when the path is missing. */ +export async function mtimeOrNull(fs: ReaderFs, path: string): Promise<number | null> { + try { + if (!(await fs.exists(path))) { + return null + } + + return (await fs.stat(path)).mtimeMs + } catch { + return null + } +} diff --git a/plugins/code-modernization/hooks/reader/modernized.ts b/plugins/code-modernization/hooks/reader/modernized.ts new file mode 100644 index 00000000..600e1d39 --- /dev/null +++ b/plugins/code-modernization/hooks/reader/modernized.ts @@ -0,0 +1,384 @@ +import { join } from '../paths' +import { listOrEmpty, readOrNull, type ReaderFs } from './fs' + +/** + * The state of each transformed module, read from `modernized/<system>/`: + * what exists on disk, what the test reports say, what the notes record. + * No inference: a fact that is not on disk is absent. + */ + +export type TestTotals = { + tests: number + failures: number + errors: number + skipped: number + /** How many report files were read. */ + reports: number +} + +export type ModuleState = + | 'scaffolded' + | 'tests-written' + | 'tests-red' + | 'tests-green' + | 'reviewed' + | 'ported' + | 'switched' + +export type ModernizedModule = { + /** The directory's name under `modernized/<system>/`. */ + dir: string + /** Path relative to the working directory. */ + path: string + hasMain: boolean + hasTests: boolean + hasNotes: boolean + /** The date in the notes' "Architecture review" section; absent when none. */ + reviewDate?: string + hasReviewSection: boolean + /** The notes say "ported, not switched". */ + isPortedNotSwitched: boolean + /** The notes say the route was switched. */ + isSwitched: boolean + /** Open follow-ups the notes list (bullets under a Follow-ups heading). */ + followUps: number + tests: TestTotals | null + state: ModuleState + /** Newest mtime among the notes and test reports; 0 when unknown. */ + mtimeMs: number +} + +/** States a unit of work counts as finished in: the review is done, or the module is ported or switched. */ +const DONE_STATES: ReadonlySet<ModuleState> = new Set(['reviewed', 'ported', 'switched']) + +/** + * Whether a module's work is finished. Green tests with notes written count: the notes are where the plugin's + * review step lists what the critic found, and how they headline it varies, so a missing headline is not unfinished work. + */ +export const isDone = (module: Pick<ModernizedModule, 'state' | 'hasNotes'>): boolean => + DONE_STATES.has(module.state) || (module.state === 'tests-green' && module.hasNotes) + +const EMPTY: TestTotals = { tests: 0, failures: 0, errors: 0, skipped: 0, reports: 0 } + +/** Totals of one Visual Studio test result file (`.trx`), the report `dotnet test --logger trx` leaves. */ +export function totalsOfTrx(xml: string): TestTotals | null { + const counters = /<Counters\b[^>]*>/.exec(xml)?.[0] + + if (counters === undefined || !/\btotal="\d+"/.test(counters)) { + return null + } + + return { + tests: attr(counters, 'total'), + failures: attr(counters, 'failed'), + errors: attr(counters, 'error') + attr(counters, 'timeout') + attr(counters, 'aborted'), + skipped: attr(counters, 'notExecuted') + attr(counters, 'inconclusive'), + reports: 1, + } +} + +const attr = (tag: string, name: string): number => { + const match = new RegExp(`\\b${name}="(\\d+)"`).exec(tag) + + return match?.[1] !== undefined ? Number(match[1]) : 0 +} + +/** Totals of one JUnit-style XML report (`<testsuite ...>` / `<testsuites ...>`). */ +export function totalsOfJunitXml(xml: string): TestTotals | null { + const suites = /<testsuites\b[^>]*>/.exec(xml)?.[0] + + if (suites !== undefined && /\btests="\d+"/.test(suites)) { + return { + tests: attr(suites, 'tests'), + failures: attr(suites, 'failures'), + errors: attr(suites, 'errors'), + skipped: attr(suites, 'skipped') + attr(suites, 'disabled'), + reports: 1, + } + } + + const all = [...xml.matchAll(/<testsuite\b[^>]*>/g)].map(match => match[0]) + + if (all.length === 0) { + return null + } + + return all.reduce<TestTotals>( + (sum, tag) => ({ + tests: sum.tests + attr(tag, 'tests'), + failures: sum.failures + attr(tag, 'failures'), + errors: sum.errors + attr(tag, 'errors'), + skipped: sum.skipped + attr(tag, 'skipped') + attr(tag, 'disabled'), + reports: 1, + }), + { ...EMPTY, reports: 1 }, + ) +} + +const add = (a: TestTotals, b: TestTotals): TestTotals => ({ + tests: a.tests + b.tests, + failures: a.failures + b.failures, + errors: a.errors + b.errors, + skipped: a.skipped + b.skipped, + reports: a.reports + b.reports, +}) + +/** Where test runners leave JUnit XML, relative to a module's directory. */ +const REPORT_DIRS = [ + 'target/surefire-reports', + 'target/failsafe-reports', + 'build/test-results/test', + 'build/test-results', + 'build/logs', + 'test-results', + 'test-reports', + 'reports/junit', + 'TestResults', +] + +const REPORT_FILES = ['junit.xml', 'report.xml', 'test-report.xml', 'pytest.xml'] + +/** The test totals a directory's report files hold: a custom JSON report, JUnit XML, or a `.trx`. */ +export async function readTests(fs: ReaderFs, dir: string): Promise<TestTotals | null> { + const custom = await readOrNull(fs, join(dir, '.modernize/test-report.json')) + + if (custom !== null) { + try { + const raw = JSON.parse(custom) as Record<string, unknown> + const num = (key: string) => (typeof raw[key] === 'number' ? (raw[key] as number) : 0) + + return { + tests: num('tests'), + failures: num('failures'), + errors: num('errors'), + skipped: num('skipped'), + reports: 1, + } + } catch { + // fall through to the XML reports + } + } + + let total: TestTotals | null = null + + for (const sub of REPORT_DIRS) { + const entries = await listOrEmpty(fs, join(dir, sub)) + + for (const entry of entries) { + const isTrx = entry.name.endsWith('.trx') + + if (entry.kind !== 'file' || !(entry.name.endsWith('.xml') || isTrx) || entry.size > 3_500_000) { + continue + } + + const xml = await readOrNull(fs, join(dir, sub, entry.name)) + const totals = xml === null ? null : isTrx ? totalsOfTrx(xml) : totalsOfJunitXml(xml) + + if (totals !== null) { + total = total === null ? totals : add(total, totals) + } + } + + if (total !== null) { + return total + } + } + + for (const name of REPORT_FILES) { + const xml = await readOrNull(fs, join(dir, name)) + const totals = xml !== null ? totalsOfJunitXml(xml) : null + + if (totals !== null) { + return totals + } + } + + return null +} + +const TEST_DIRS = ['src/test', 'tests', 'test', 'spec', '__tests__'] +const MAIN_DIRS = ['src/main', 'src', 'app', 'lib'] + +async function anyDir(fs: ReaderFs, dir: string, names: readonly string[]): Promise<boolean> { + for (const name of names) { + if ((await listOrEmpty(fs, join(dir, name))).length > 0) { + return true + } + } + + return false +} + +/** What the notes record, read by heading and phrase. */ +export function readNotes(notes: string): { + hasReviewSection: boolean + reviewDate?: string + isPortedNotSwitched: boolean + isSwitched: boolean + followUps: number +} { + const lines = notes.split('\n') + // The plugin's review step spawns the architecture critic and lists what it found in the notes; how the notes + // headline that varies, so any heading that says review or critic counts, and so does naming the critic. + const named = lines.findIndex(line => /^#{1,4}\s+.*\b(?:review|critic)/i.test(line)) + const start = named >= 0 ? named : -1 + let reviewDate: string | undefined + + if (start >= 0) { + const level = /^(#+)/.exec(lines[start] ?? '')?.[1]?.length ?? 2 + + const end = lines.findIndex( + (line, index) => index > start && new RegExp(`^#{1,${level}}\\s`).test(line), + ) + + const section = lines.slice(start, end < 0 ? undefined : end).join('\n') + + reviewDate = /\b(\d{4}-\d{2}-\d{2})\b/.exec(section)?.[1] + } + + const followStart = lines.findIndex(line => /^#{1,4}\s+.*follow-?ups?/i.test(line)) + let followUps = 0 + + if (followStart >= 0) { + for (const line of lines.slice(followStart + 1)) { + if (/^#{1,4}\s/.test(line)) { + break + } + + if (/^\s*[-*]\s+(?!\[[xX]\])/.test(line) || /^\s*\d+\.\s+/.test(line)) { + followUps += 1 + } + } + } + + const isPortedNotSwitched = /ported,?\s+not\s+switched/i.test(notes) + + return { + hasReviewSection: start >= 0 || /architecture[- ]critic/i.test(notes), + ...(reviewDate !== undefined && { reviewDate }), + isPortedNotSwitched, + isSwitched: + !isPortedNotSwitched && + /\b(?:route|traffic)\b[^\n]{0,40}\bswitched\b|\bswitched\b[^\n]{0,20}\b\d{4}-\d{2}-\d{2}\b/i.test( + notes, + ), + followUps, + } +} + +/** The state a module's facts add up to, furthest first. */ +export function stateOf(module: Omit<ModernizedModule, 'state'>): ModuleState { + const tests = module.tests + const isRed = tests !== null && tests.failures + tests.errors > 0 + const isGreen = tests !== null && tests.tests > 0 && !isRed + + if (module.isSwitched && isGreen && module.hasReviewSection) { + return 'switched' + } + + if (module.isPortedNotSwitched && isGreen) { + return 'ported' + } + + if (isGreen && module.hasReviewSection) { + return 'reviewed' + } + + if (isRed) { + return 'tests-red' + } + + if (isGreen) { + return 'tests-green' + } + + if (module.hasTests) { + return 'tests-written' + } + + return 'scaffolded' +} + +/** + * The state of one unit of an uplift's working copy: worse than its baseline, matching or exceeding it + * (every test that passed on the source runtime still passes, none is missing), tested but not comparable + * to a baseline row, changed and not yet tested, or not touched at all. + */ +export function stateOfUplift( + tests: TestTotals | null, + baseline: { pass: number; fail: number; error: number; skip: number } | null, + isChanged: boolean, +): ModuleState | 'untouched' { + if (tests !== null && tests.tests > 0) { + const bad = tests.failures + tests.errors + const allowed = baseline === null ? 0 : baseline.fail + baseline.error + + if (bad > allowed) { + return 'tests-red' + } + + const passed = tests.tests - bad - tests.skipped + const isCovered = baseline !== null && tests.tests >= baseline.pass + baseline.fail + baseline.error + baseline.skip && passed >= baseline.pass + + return isCovered ? 'reviewed' : 'tests-green' + } + + return isChanged ? 'scaffolded' : 'untouched' +} + +/** Reads every code directory under `modernized/<system>/`. */ +export async function readModernized( + fs: ReaderFs, + system: string, +): Promise<ModernizedModule[]> { + return readModernizedIn(fs, join('modernized', system)) +} + +/** Reads every code directory directly under `root`: a transformed system's modules, or a reimagined system's services. */ +export async function readModernizedIn( + fs: ReaderFs, + root: string, + observed: ReadonlyMap<string, TestTotals> = new Map(), +): Promise<ModernizedModule[]> { + const entries = await listOrEmpty(fs, root) + const out: ModernizedModule[] = [] + + for (const entry of entries) { + if (entry.kind !== 'dir' || entry.name.startsWith('.')) { + continue + } + + const path = join(root, entry.name) + const notes = await readOrNull(fs, join(path, 'TRANSFORMATION_NOTES.md')) + const read = notes !== null ? readNotes(notes) : null + const tests = (await readTests(fs, path)) ?? observed.get(path) ?? null + let mtimeMs = 0 + + if (notes !== null) { + try { + mtimeMs = (await fs.stat(join(path, 'TRANSFORMATION_NOTES.md'))).mtimeMs + } catch { + mtimeMs = 0 + } + } + + const facts = { + dir: entry.name, + path, + hasMain: await anyDir(fs, path, MAIN_DIRS), + hasTests: await anyDir(fs, path, TEST_DIRS), + hasNotes: notes !== null, + hasReviewSection: read?.hasReviewSection ?? false, + ...(read?.reviewDate !== undefined && { reviewDate: read.reviewDate }), + isPortedNotSwitched: read?.isPortedNotSwitched ?? false, + isSwitched: read?.isSwitched ?? false, + followUps: read?.followUps ?? 0, + tests, + mtimeMs, + } + + out.push({ ...facts, state: stateOf(facts) }) + } + + return out +} diff --git a/plugins/code-modernization/hooks/reader/progress.ts b/plugins/code-modernization/hooks/reader/progress.ts new file mode 100644 index 00000000..711cabac --- /dev/null +++ b/plugins/code-modernization/hooks/reader/progress.ts @@ -0,0 +1,849 @@ +import { join } from '../paths' +import { parseBrief, type Brief, type Phase } from './brief' +import { discoverEstate, sourceSizes } from './discover' +import { estateOfTopology, keysOfUnit, type EstateModel, type EstateUnit } from './estate-model' +import { listOrEmpty, mtimeOrNull, readOrNull, type ReaderFs } from './fs' +import { isDone, readModernizedIn, type ModernizedModule, type TestTotals } from './modernized' +import { needsReview, parseRules, type RuleSet } from './rules' +import { pickTrack, TRACK_LABELS, type TrackKey } from './tracks' +import { parseTopology, type Topology } from './topology' +import { + changedUnitsOf, + parseBaseline, + parseCatalog, + changedPathsOf, + readUpliftUnits, + type Baseline, + type Catalog, +} from './uplift' + +/** + * One reading of a system's modernization state, from the artifacts on disk + * alone. Everything here is a fact of a file that exists; nothing is inferred + * by a model, and what cannot be read is absent. + */ + +export type StageKey = + | 'preflight' + | 'assess' + | 'map' + | 'rules' + | 'brief' + | 'transform' + | 'harden' + | 'deltas' + | 'baseline' + | 'pilot' + | 'migrate' + | 'verify' + | 'spec' + | 'design' + | 'scaffold' + | 'tests' + +export type Stage = { + key: StageKey + label: string + isDone: boolean + mtimeMs: number | null + /** One short qualifier (`signed`, `319 rules`), when there is one. */ + detail?: string +} + +export type ReviewVerdict = 'confirmed' | 'wrong' | 'discuss' + +export type ReviewLedger = Record< + string, + { verdict: ReviewVerdict; at: string; title?: string; note?: string } +> + +export type NextStep = { + /** The slash command to run, or what to do by hand. */ + text: string + isByHand: boolean + reason: string +} + +/** What an uplift has left on disk, beyond the modules it changed. */ +export type UpliftFacts = { + catalog: Catalog | null + baseline: Baseline | null + hasPlaybook: boolean + hasNotes: boolean + hasCopy: boolean + /** Whether the working copy's changes could be read (a version-control status), or only its test reports. */ + isChangeKnown: boolean +} + +export type Snapshot = { + system: string + systems: string[] + /** Which way the plugin's commands are working on the system. */ + track: TrackKey + /** True once the system has any artifact under `analysis/`: modernization is under way, not only possible. */ + hasAnalysis: boolean + stages: Stage[] + /** The units the estate map draws: the map's modules, or what the legacy tree holds. */ + estate: EstateModel | null + topology: Topology | null + rules: RuleSet | null + brief: Brief | null + /** The units of work under way: transformed modules, uplifted modules, or reimagined services. */ + modules: ModernizedModule[] + /** Estate unit id to its unit of work, where one matches. */ + byNode: Map<string, ModernizedModule> + /** Units of work that match no unit of the estate. */ + extras: ModernizedModule[] + uplift: UpliftFacts | null + findings: { exists: boolean; isScan: boolean } + reviews: ReviewLedger + /** Size of the units finished over the estate's total; null without an estate, or where units of work are not the estate's own. */ + percent: number | null + totals: { modules: number; done: number; loc: number; locDone: number } + attention: string[] + next: NextStep | null + readAtMs: number +} + +export const STAGE_LABELS: Record<StageKey, string> = { + preflight: 'preflight', + assess: 'assess', + map: 'map', + rules: 'rules', + brief: 'brief', + transform: 'transform', + harden: 'harden', + deltas: 'deltas', + baseline: 'baseline', + pilot: 'pilot', + migrate: 'migrate', + verify: 'verify', + spec: 'spec', + design: 'design', + scaffold: 'scaffold', + tests: 'tests', +} + +const STAGE_FILES = { + preflight: 'PREFLIGHT.md', + assess: 'ASSESSMENT.md', + map: 'topology.json', + rules: 'BUSINESS_RULES.md', + brief: 'MODERNIZATION_BRIEF.md', + transform: 'TRANSFORMATION_NOTES.md', + harden: 'SECURITY_FINDINGS.md', + deltas: 'DELTA_CATALOG.md', + baseline: 'BASELINE.md', + pilot: 'PLAYBOOK.md', + spec: 'AI_NATIVE_SPEC.md', + design: 'REIMAGINED_ARCHITECTURE.md', +} as const + +export const REVIEWS_FILE = 'RULE_REVIEWS.json' + +/** Parsed files kept by path and mtime, so an unchanged file is parsed once. */ +export type ReaderCache = Map<string, { mtimeMs: number; value: unknown }> + +async function cached<T>( + fs: ReaderFs, + cache: ReaderCache, + path: string, + parse: (text: string) => T, +): Promise<{ value: T | null; mtimeMs: number | null }> { + const mtimeMs = await mtimeOrNull(fs, path) + + if (mtimeMs === null) { + cache.delete(path) + + return { value: null, mtimeMs: null } + } + + const hit = cache.get(path) + + if (hit !== undefined && hit.mtimeMs === mtimeMs) { + return { value: hit.value as T, mtimeMs } + } + + const text = await readOrNull(fs, path) + + if (text === null) { + return { value: null, mtimeMs } + } + + const value = parse(text) + + cache.set(path, { mtimeMs, value }) + + return { value, mtimeMs } +} + +/** The systems the workspace holds: each directory under `analysis/` and under the legacy tree. */ +export async function systemsOf(fs: ReaderFs, legacyDir = 'legacy'): Promise<string[]> { + const names = new Set<string>() + + for (const root of ['analysis', legacyDir]) { + for (const entry of await listOrEmpty(fs, root)) { + if (entry.kind === 'dir' && !entry.name.startsWith('.')) { + names.add(entry.name) + } + } + } + + return [...names].sort() +} + +const slugOf = (target: string) => + target + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + +/** How a transformed directory's name is matched to a unit's names. */ +const keyOf = (name: string) => name.toLowerCase().replace(/::/g, '-').replace(/[^a-z0-9]+/g, '-') + +function approvedPhases(brief: Brief): Phase[] { + if (!brief.approval.isSigned) { + return [] + } + + const ordered = [...brief.phases].sort((a, b) => a.number - b.number) + + return brief.approval.covers === 'full' ? ordered : ordered.slice(0, 1) +} + +/** Whether one unit of work is finished, by what the track counts as finished. */ +export function isUnitDone( + snapshot: Pick<Snapshot, 'track' | 'uplift'>, + module: Pick<ModernizedModule, 'state' | 'hasNotes'>, +): boolean { + if (snapshot.track !== 'uplift') { + return isDone(module) + } + + // An uplift is proven by reproducing the baseline; with no per-module baseline, passing is all there is to compare. + const hasRows = (snapshot.uplift?.baseline?.rows.size ?? 0) > 0 + + return module.state === 'reviewed' || (module.state === 'tests-green' && !hasRows) +} + +function nextOfTransform( + prefix: string, + system: string, + stages: Stage[], + brief: Brief | null, + byNode: Map<string, ModernizedModule>, +): NextStep | null { + const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true + const cmd = (name: string, rest = '') => `${prefix}${name} ${system}${rest === '' ? '' : ` ${rest}`}` + + if (!done('preflight') && !done('assess')) { + return { text: cmd('preflight'), isByHand: false, reason: 'check the environment before analysis' } + } + + if (!done('assess')) { + return { text: cmd('assess'), isByHand: false, reason: 'inventory and complexity come first' } + } + + if (!done('map')) { + return { text: cmd('map'), isByHand: false, reason: 'the brief and the rules both read the topology' } + } + + if (!done('rules')) { + return { text: cmd('extract-rules'), isByHand: false, reason: 'the behavior contract comes from the rules' } + } + + if (!done('brief') || brief === null) { + return { text: cmd('brief'), isByHand: false, reason: 'discovery is complete; plan the phases' } + } + + if (!brief.approval.isSigned) { + return { + text: 'approve the brief: tell Claude which phases you approve', + isByHand: true, + reason: 'execution commands treat an unapproved brief as not approved', + } + } + + const target = brief.target !== undefined ? slugOf(brief.target) : '' + + for (const phase of approvedPhases(brief)) { + const open = phase.modules.find(id => { + const module = byNode.get(id) + + return module === undefined || !isDone(module) + }) + + if (open !== undefined) { + return { + text: cmd('transform', `${open}${target === '' ? '' : ` ${target}`}`), + isByHand: false, + reason: `Phase ${phase.number} names ${open} and it is not reviewed yet`, + } + } + + if (phase.modules.length === 0) { + return { + text: `pick Phase ${phase.number}'s first module and run ${prefix}transform ${system} <module>${target === '' ? '' : ` ${target}`}`, + isByHand: true, + reason: `Phase ${phase.number} names no module the map knows`, + } + } + } + + return { + text: cmd('status'), + isByHand: false, + reason: + brief.approval.covers === 'full' + ? 'every approved phase is reviewed' + : 'Phase 1 is reviewed; its retrospective revises the brief before Phase 2 is approved', + } +} + +/** The uplift command needs both versions, which only a person knows: the hint is by hand. */ +function nextOfUplift(prefix: string, system: string, stages: Stage[]): NextStep { + const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true + const command = `${prefix}uplift ${system} <from> <to>` + + if (!done('deltas')) { + return { text: command, isByHand: true, reason: 'the delta catalog comes first: what the target version breaks here' } + } + + if (!done('baseline')) { + return { text: command, isByHand: true, reason: 'record the baseline before any module is migrated: it is the equivalence target' } + } + + if (!done('pilot')) { + return { text: command, isByHand: true, reason: 'migrate one representative module and write the playbook before the rest' } + } + + if (!done('verify')) { + return { text: command, isByHand: true, reason: 'migrate the rest in batches by the playbook, then run the dual-run diff' } + } + + return { text: `${prefix}status ${system}`, isByHand: false, reason: 'every uplift artifact is written; status checks what is stale' } +} + +function nextOfReimagine(prefix: string, system: string, stages: Stage[]): NextStep { + const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true + const command = `${prefix}reimagine ${system} <vision>` + + if (!done('spec')) { + return { text: command, isByHand: true, reason: 'the spec is mined from the legacy code first' } + } + + if (!done('design')) { + return { text: command, isByHand: true, reason: 'the target architecture is designed and reviewed against the spec' } + } + + if (!done('scaffold')) { + return { text: command, isByHand: true, reason: 'scaffold each service from the approved architecture' } + } + + return { text: `${prefix}status ${system}`, isByHand: false, reason: 'the services are scaffolded; status checks what is stale' } +} + +export type ReadOptions = { + /** The system to read; the first one found when absent or unknown. */ + system?: string + /** What a command is written with, up to its verb (`/code-modernization:modernize-`). */ + commandPrefix: string + nowMs: number + /** The read-only tree holding the systems, relative to the workspace; `legacy` when absent. */ + legacyDir?: string + /** Which way to follow the system; `auto` when absent: whichever one's artifacts are newest. */ + track?: TrackKey | 'auto' + /** Units of an uplift's working copy that were written during this session: they count as changed even when the file kept its size. */ + writtenUnits?: ReadonlySet<string> + /** How long a listing of the working copy is reused, in milliseconds; 15 seconds when absent. */ + changedTtlMs?: number + /** Test totals read off commands this session, by module path, for modules that left no report file. */ + observed?: ReadonlyMap<string, TestTotals> +} + +const newest = (...times: (number | null)[]): number | null => { + const known = times.filter((time): time is number => time !== null) + + return known.length === 0 ? null : Math.max(...known) +} + +/** The files of an uplift's working copy and their sizes, reused for a short while so an idle pane does not walk the tree again and again. */ +async function workingSizesOf( + fs: ReaderFs, + cache: ReaderCache, + root: string, + nowMs: number, + ttlMs: number, +): Promise<Map<string, number> | null> { + const key = `changed:${root}` + const hit = cache.get(key) + + if (hit !== undefined && nowMs - hit.mtimeMs < ttlMs) { + return hit.value as Map<string, number> | null + } + + const value = await sourceSizes(fs, root) + + cache.set(key, { mtimeMs: nowMs, value }) + + return value +} + +/** The estate to draw: the map's modules, or what the legacy tree holds. Read once per system, then kept. */ +async function estateOf( + fs: ReaderFs, + cache: ReaderCache, + track: TrackKey, + topology: Topology | null, + legacyRoot: string, + system: string, +): Promise<EstateModel | null> { + if (topology !== null && track !== 'uplift') { + return estateOfTopology(topology, 0) + } + + const key = `estate:${legacyRoot}` + const at = (await mtimeOrNull(fs, legacyRoot)) ?? 0 + const hit = cache.get(key) + + if (hit !== undefined && hit.mtimeMs === at) { + return hit.value as EstateModel | null + } + + const found = await discoverEstate(fs, legacyRoot, system) + + cache.set(key, { mtimeMs: at, value: found }) + + return found ?? (topology !== null ? estateOfTopology(topology, 0) : null) +} + +/** Reads one system's state. Null when the workspace holds no system. */ +export async function readSnapshot( + fs: ReaderFs, + cache: ReaderCache, + options: ReadOptions, +): Promise<Snapshot | null> { + const legacyDir = options.legacyDir ?? 'legacy' + const systems = await systemsOf(fs, legacyDir) + + const system = + options.system !== undefined && systems.includes(options.system) + ? options.system + : systems[0] + + if (system === undefined) { + return null + } + + const dir = join('analysis', system) + const legacyRoot = join(legacyDir, system) + const transformRoot = join('modernized', system) + const upliftRoot = join('modernized', `${system}-uplifted`) + const reimagineRoot = join('modernized', `${system}-reimagined`) + const observed = options.observed ?? new Map<string, TestTotals>() + + const [topo, rules, catalog, baseline, reviewsRaw, findingsHead, marks] = await Promise.all([ + cached(fs, cache, join(dir, STAGE_FILES.map), parseTopology), + cached(fs, cache, join(dir, STAGE_FILES.rules), parseRules), + cached(fs, cache, join(dir, STAGE_FILES.deltas), parseCatalog), + cached(fs, cache, join(dir, STAGE_FILES.baseline), parseBaseline), + readOrNull(fs, join(dir, REVIEWS_FILE)), + readOrNull(fs, join(dir, STAGE_FILES.harden)), + Promise.all( + [ + mtimeOrNull(fs, dir), + mtimeOrNull(fs, join(dir, STAGE_FILES.preflight)), + mtimeOrNull(fs, join(dir, STAGE_FILES.assess)), + mtimeOrNull(fs, join(dir, STAGE_FILES.pilot)), + mtimeOrNull(fs, join(upliftRoot, 'UPLIFT_NOTES.md')), + mtimeOrNull(fs, upliftRoot), + mtimeOrNull(fs, join(dir, STAGE_FILES.spec)), + mtimeOrNull(fs, join(dir, STAGE_FILES.design)), + mtimeOrNull(fs, reimagineRoot), + mtimeOrNull(fs, transformRoot), + ], + ), + ]) + + const [analysisAt, preflightAt, assessAt, playbookAt, upliftNotesAt, upliftCopyAt, specAt, designAt, reimagineDirAt, transformDirAt] = marks + + const topology = topo.value + const moduleIds = topology?.modules.map(node => node.id) ?? [] + + const brief = await cached(fs, cache, join(dir, STAGE_FILES.brief), text => + parseBrief(text, moduleIds), + ) + + // A brief parsed before the map existed named no modules: parse it again. + if ( + brief.value !== null && + moduleIds.length > 0 && + brief.value.phases.length > 0 && + brief.value.phases.every(phase => phase.modules.length === 0) + ) { + const text = await readOrNull(fs, join(dir, STAGE_FILES.brief)) + + if (text !== null) { + brief.value = parseBrief(text, moduleIds) + cache.set(join(dir, STAGE_FILES.brief), { mtimeMs: brief.mtimeMs ?? 0, value: brief.value }) + } + } + + let reviews: ReviewLedger = {} + + if (reviewsRaw !== null) { + try { + const parsed = JSON.parse(reviewsRaw) as { reviews?: ReviewLedger } + + reviews = parsed.reviews ?? {} + } catch { + reviews = {} + } + } + + const isScan = findingsHead !== null && /generated-by:\s*modernize-harden/.test(findingsHead.split('\n')[0] ?? '') + + const transformed = await readModernizedIn(fs, transformRoot, observed) + + const track = pickTrack(options.track ?? 'auto', { + transformAt: newest(transformDirAt, ...transformed.map(module => module.mtimeMs)), + // A baseline says nothing of the track: a rewrite records one too, for the legacy behavior it must keep. + upliftAt: newest(catalog.mtimeMs, playbookAt, upliftNotesAt, upliftCopyAt), + reimagineAt: newest(specAt, designAt, reimagineDirAt), + }) + + const estate = await estateOf(fs, cache, track, topology, legacyRoot, system) + + let modules: ModernizedModule[] = [] + const byNode = new Map<string, ModernizedModule>() + const extras: ModernizedModule[] = [] + let uplift: UpliftFacts | null = null + + if (track === 'uplift') { + const hasCopy = upliftCopyAt !== null + const legacySizes = estate?.isPartial === false ? estate.fileSizes : undefined + const workingSizes = hasCopy && legacySizes !== undefined ? await workingSizesOf(fs, cache, upliftRoot, options.nowMs, options.changedTtlMs ?? 15_000) : null + const changedPaths = legacySizes !== undefined && workingSizes !== null ? changedPathsOf(legacySizes, workingSizes) : null + const changed = estate !== null && changedPaths !== null ? changedUnitsOf(estate, changedPaths) : new Set<string>() + + for (const id of options.writtenUnits ?? []) { + changed.add(id) + } + + const pairs = + estate !== null && hasCopy + ? await readUpliftUnits(fs, upliftRoot, estate, changed, baseline.value, observed) + : [] + + modules = pairs.map(pair => pair.module) + + for (const pair of pairs) { + byNode.set(pair.unit.id, pair.module) + } + + uplift = { + catalog: catalog.value, + baseline: baseline.value, + hasPlaybook: playbookAt !== null, + hasNotes: upliftNotesAt !== null, + hasCopy, + isChangeKnown: changedPaths !== null, + } + } else { + modules = track === 'reimagine' ? await readModernizedIn(fs, reimagineRoot, observed) : transformed + + if (track === 'transform') { + const byKey = new Map<string, EstateUnit>() + + for (const unit of estate?.units ?? []) { + for (const key of keysOfUnit(unit)) { + byKey.set(keyOf(key), unit) + } + } + + for (const module of modules) { + const unit = byKey.get(keyOf(module.dir)) + + if (unit !== undefined) { + byNode.set(unit.id, module) + } else { + extras.push(module) + } + } + } else { + extras.push(...modules) + } + } + + const snapshotFacts = { track, uplift } + const done = modules.filter(module => isUnitDone(snapshotFacts, module)) + + const green = modules.filter( + module => module.state === 'tests-green' || module.state === 'reviewed' || isUnitDone(snapshotFacts, module), + ) + + const passing = green.reduce( + (sum, module) => sum + Math.max(0, (module.tests?.tests ?? 0) - (module.tests?.failures ?? 0) - (module.tests?.errors ?? 0)), + 0, + ) + + const withFindings: Stage[] = + findingsHead !== null || track === 'transform' + ? [ + { + key: 'harden', + label: STAGE_LABELS.harden, + // Any findings file counts. A harden marker on its first line says the command wrote it, and older or + // newer versions of the command may or may not stamp one, so its absence is not a reason to doubt the file. + isDone: findingsHead !== null, + mtimeMs: null, + }, + ] + : [] + + const stages: Stage[] = [ + ...(track === 'transform' + ? [ + { key: 'preflight' as const, label: STAGE_LABELS.preflight, isDone: preflightAt !== null, mtimeMs: preflightAt }, + { key: 'assess' as const, label: STAGE_LABELS.assess, isDone: assessAt !== null, mtimeMs: assessAt }, + { + key: 'map' as const, + label: STAGE_LABELS.map, + isDone: topology !== null, + mtimeMs: topo.mtimeMs, + ...(topology !== null && { detail: `${topology.modules.length} modules` }), + }, + { + key: 'rules' as const, + label: STAGE_LABELS.rules, + isDone: rules.value !== null && rules.value.rules.length > 0, + mtimeMs: rules.mtimeMs, + ...(rules.value !== null && { detail: `${rules.value.rules.length} rules` }), + }, + { + key: 'brief' as const, + label: STAGE_LABELS.brief, + isDone: brief.value !== null, + mtimeMs: brief.mtimeMs, + ...(brief.value !== null && { + detail: brief.value.approval.isSigned ? 'approved' : 'unapproved', + }), + }, + { + // Transform writes under modernized/, not analysis/: this stage is done once a module's tests are green. + key: 'transform' as const, + label: STAGE_LABELS.transform, + isDone: green.length > 0, + mtimeMs: null, + ...(modules.length > 0 && { + detail: green.length === 0 ? 'in progress' : passing > 0 ? `${passing} green` : `${green.length} module${green.length === 1 ? '' : 's'}`, + }), + }, + ] + : track === 'uplift' + ? [ + { key: 'preflight' as const, label: STAGE_LABELS.preflight, isDone: preflightAt !== null, mtimeMs: preflightAt }, + { + key: 'deltas' as const, + label: STAGE_LABELS.deltas, + isDone: catalog.mtimeMs !== null, + mtimeMs: catalog.mtimeMs, + ...(catalog.value !== null && { detail: `${catalog.value.count} deltas` }), + }, + { + key: 'baseline' as const, + label: STAGE_LABELS.baseline, + isDone: baseline.mtimeMs !== null, + mtimeMs: baseline.mtimeMs, + ...(baseline.value !== null && { + detail: baseline.value.isTargetOnly + ? 'target-only' + : baseline.value.results !== null + ? `${baseline.value.results.toLocaleString('en-US')} tests` + : undefined, + }), + }, + { key: 'pilot' as const, label: STAGE_LABELS.pilot, isDone: playbookAt !== null, mtimeMs: playbookAt }, + { + key: 'migrate' as const, + label: STAGE_LABELS.migrate, + isDone: modules.length > 0 && playbookAt !== null, + mtimeMs: null, + ...(modules.length > 0 && { detail: `${modules.length} module${modules.length === 1 ? '' : 's'}` }), + }, + { + key: 'verify' as const, + label: STAGE_LABELS.verify, + isDone: upliftNotesAt !== null, + mtimeMs: upliftNotesAt, + ...(modules.length > 0 && { detail: `${done.length}/${modules.length} match` }), + }, + ] + : [ + { key: 'preflight' as const, label: STAGE_LABELS.preflight, isDone: preflightAt !== null, mtimeMs: preflightAt }, + { key: 'spec' as const, label: STAGE_LABELS.spec, isDone: specAt !== null, mtimeMs: specAt }, + { key: 'design' as const, label: STAGE_LABELS.design, isDone: designAt !== null, mtimeMs: designAt }, + { + key: 'scaffold' as const, + label: STAGE_LABELS.scaffold, + isDone: modules.length > 0, + mtimeMs: null, + ...(modules.length > 0 && { detail: `${modules.length} service${modules.length === 1 ? '' : 's'}` }), + }, + { + key: 'tests' as const, + label: STAGE_LABELS.tests, + isDone: modules.length > 0 && green.length === modules.length, + mtimeMs: null, + ...(modules.length > 0 && { detail: `${green.length}/${modules.length} green` }), + }, + ]), + ...withFindings, + ] + + const loc = (estate?.units ?? []).reduce((sum, unit) => sum + Math.max(1, unit.size), 0) + + const locDone = (estate?.units ?? []).reduce((sum, unit) => { + const module = byNode.get(unit.id) + + return module !== undefined && isUnitDone(snapshotFacts, module) ? sum + Math.max(1, unit.size) : sum + }, 0) + + const attention: string[] = [] + + for (const module of modules) { + const row = track === 'uplift' ? (baseline.value?.rows.get(module.dir.toLowerCase()) ?? null) : null + + if (module.state === 'tests-red' && module.tests !== null) { + const bad = module.tests.failures + module.tests.errors + + attention.push( + track === 'uplift' + ? `${module.dir}: ${bad} failing, the baseline had ${row === null ? 0 : row.fail + row.error}` + : `${module.dir}: ${bad} of ${module.tests.tests} tests red`, + ) + } + + if (module.tests !== null && module.tests.reports > 0 && module.tests.tests === 0) { + attention.push(`${module.dir}: test reports exist but 0 cases executed`) + } + + if (track === 'transform' && module.state === 'tests-green' && module.hasNotes && !module.hasReviewSection) { + attention.push(`${module.dir}: tests green; the notes do not show the architecture review`) + } + } + + for (const extra of extras) { + if (track === 'transform' && extra.hasMain && (!extra.hasNotes || !extra.hasTests)) { + attention.push( + `${extra.dir}: shared code without ${[!extra.hasTests && 'tests', !extra.hasNotes && 'notes'].filter(Boolean).join(' or ')}; an unfinished transform`, + ) + } + + if (track === 'reimagine' && extra.hasMain && !extra.hasTests) { + attention.push(`${extra.dir}: scaffolded with no acceptance tests`) + } + } + + if (track === 'uplift' && uplift !== null) { + if (uplift.baseline?.isTargetOnly === true) { + attention.push('the baseline is target-only: the source runtime could not run, so nothing is compared') + } + + if (modules.length > 0 && !uplift.hasPlaybook) { + attention.push(`${modules.length} module${modules.length === 1 ? '' : 's'} touched before a playbook was written: pilot one first`) + } + + if (modules.length > 0 && uplift.baseline === null) { + attention.push('modules touched before a baseline was recorded: nothing to compare them with') + } + } + + if ( + brief.mtimeMs !== null && + rules.mtimeMs !== null && + brief.mtimeMs < rules.mtimeMs + ) { + attention.push('the brief is older than the rule set it was planned from') + } + + if (rules.value !== null) { + const pending = rules.value.rules.filter( + rule => rule.priority === 'P0' && needsReview(rule) && reviews[rule.id] === undefined, + ).length + + const wrong = Object.values(reviews).filter(entry => entry.verdict === 'wrong').length + + if (wrong > 0) { + attention.push(`${wrong} rule${wrong === 1 ? '' : 's'} marked wrong by a reviewer`) + } + + if (pending > 0) { + attention.push(`${pending} P0 rule${pending === 1 ? '' : 's'} flagged for a person and not reviewed yet`) + } + } + + const next: NextStep | null = + track === 'uplift' + ? nextOfUplift(options.commandPrefix, system, stages) + : track === 'reimagine' + ? nextOfReimagine(options.commandPrefix, system, stages) + : nextOfTransform(options.commandPrefix, system, stages, brief.value, byNode) + + return { + system, + systems, + track, + hasAnalysis: analysisAt !== null, + stages, + estate, + topology, + rules: rules.value, + brief: brief.value, + modules, + byNode, + extras, + uplift, + findings: { exists: findingsHead !== null, isScan }, + reviews, + percent: track === 'reimagine' || loc === 0 ? null : locDone / loc, + totals: { + modules: estate?.units.length ?? 0, + done: [...byNode.values()].filter(module => isUnitDone(snapshotFacts, module)).length, + loc, + locDone, + }, + attention, + next, + readAtMs: options.nowMs, + } +} + +/** One line for the status bar and the prompt's hidden context. */ +export function oneLineOf(snapshot: Snapshot): string { + const countable = snapshot.stages.filter(stage => stage.key !== 'harden' && stage.key !== 'transform') + const done = countable.filter(stage => stage.isDone).length + + const parts = + snapshot.track === 'transform' + ? [`${snapshot.system}: discovery ${done}/5`] + : [`${snapshot.system}: ${TRACK_LABELS[snapshot.track]} ${done}/${countable.length} steps`] + + if (snapshot.brief !== null) { + parts.push(snapshot.brief.approval.isSigned ? 'brief approved' : 'brief awaiting approval') + } + + if (snapshot.totals.modules > 0 && snapshot.modules.length > 0) { + parts.push( + snapshot.track === 'reimagine' + ? `${snapshot.modules.length} services scaffolded` + : `${snapshot.totals.done}/${snapshot.totals.modules} modules ${snapshot.track === 'uplift' ? 'match the baseline' : 'reviewed'}`, + ) + } + + if (snapshot.attention.length > 0) { + parts.push(`${snapshot.attention.length} need attention`) + } + + return parts.join(' · ') +} diff --git a/plugins/code-modernization/hooks/reader/rules.ts b/plugins/code-modernization/hooks/reader/rules.ts new file mode 100644 index 00000000..dec397fd --- /dev/null +++ b/plugins/code-modernization/hooks/reader/rules.ts @@ -0,0 +1,437 @@ +import { baseName } from '../paths' + +/** + * `analysis/<system>/BUSINESS_RULES.md`, read into rule cards. + * + * The file is written by an agent, and the agent's layout varies between models and + * runs. Three shapes are read: a card per rule under a `### <ID> · <title>` heading with + * a header line (`P0 · Calculation · confidence High · file:line`), the same heading with + * labelled fields (`**Category:**`, `**Priority:**`, `**Plain English:**`, a fenced + * Given/When/Then block, `**Edge cases handled:**`, `**Suspected defect:**`), and table + * rows for the lower priorities. Anything else is skipped, never thrown on. + */ + +export type Citation = { + /** The path as written (`legacy/x/app/cbl/A.cbl`, `A.cbl`, `app/cpy/B.cpy`). */ + path: string + /** Lower-cased base name, the key the x-ray matches a read file by. */ + base: string + from: number + to: number +} + +export type Rule = { + /** `P0-052`, or `R-<hash>` of the title for a table row that carries no id. */ + id: string + title: string + /** `P0`, `P1`, `P2`, or `''` when the file does not say. */ + priority: string + category?: string + confidence?: string + /** The rule's one-paragraph statement. */ + statement: string + given?: string + when?: string + then?: string + edgeCases: string[] + defect?: string + sme?: string + /** Every `file:line` the card names; the first is the rule's own source. */ + citations: Citation[] + /** The domain heading (`## D6 Interest & Fees`) the rule sits under. */ + domain?: string +} + +export type RuleSet = { + rules: Rule[] + byId: Map<string, Rule> + /** Lower-cased base name of a cited file, to the rules citing it. */ + byFileBase: Map<string, Rule[]> +} + +const CITATION = + /([A-Za-z0-9_][A-Za-z0-9_./-]*\.[A-Za-z][A-Za-z0-9]{0,7}):(\d+)(?:\s*[-–]\s*(\d+))?/g + +/** `P0-052`, `RULE-001`, `BR-D7-09`: letters, optional segments (a domain), then the number. */ +const ID = '[A-Z][A-Z0-9]*(?:-[A-Z][A-Z0-9]*)*-\\d+[a-z]?' + +const CARD_HEADING = new RegExp(`^#{3,4}\\s+(${ID})\\s*[·:\\-–—]\\s*(.+?)\\s*$`) + +/** Sections that describe or summarise the rules rather than hold them: a legend, a panel summary, appendices, provenance. */ +const SKIPPED_SECTION = + /\b(?:index|appendix|open questions|rejected|refuted|how to read|p0 confirmation|provenance)\b/i + +const DOMAIN_HEADING = /^##\s+(.+?)\s*$/ + +const clean = (text: string) => + text + .replace(/\*\*/g, '') + .replace(/<br\s*\/?>(\s*)/gi, ' ') + .replace(/\s+/g, ' ') + .trim() + +/** Every `file:line[-line]` in `text`, in order, without duplicates. */ +export function citationsIn(text: string): Citation[] { + const seen = new Set<string>() + const out: Citation[] = [] + + for (const match of text.matchAll(CITATION)) { + const path = match[1] ?? '' + const from = Number(match[2]) + const to = match[3] !== undefined ? Number(match[3]) : from + const key = `${path}:${from}-${to}` + + if (path === '' || !Number.isFinite(from) || seen.has(key)) { + continue + } + + seen.add(key) + + out.push({ + path, + base: baseName(path).toLowerCase(), + from, + to: Math.max(from, to), + }) + } + + return out +} + +const priorityOf = (id: string, body: string): string => { + const fromId = /^(P\d)\b/.exec(id)?.[1] + + if (fromId !== undefined) { + return fromId + } + + const fromLabel = /\bPriority:?\s*\**\s*(P\d)\b/i.exec(body)?.[1]?.toUpperCase() + + if (fromLabel !== undefined) { + return fromLabel + } + + // `P0` · Calculation · confidence High · `app/cbl/A.cbl:10-20` + const header = body.split('\n').find(line => line.trim() !== '') ?? '' + + return /^\s*`?\**(P\d)\**`?\s*(?:·|$)/.exec(header)?.[1] ?? '' +} + +const gwtOf = (body: string, word: string): string | undefined => { + const match = new RegExp( + `\\*\\*${word}\\*\\*\\s*([\\s\\S]*?)(?=\\n[ \\t]*(?:[-*][ \\t]+)?>?\\s*\\*\\*(?:Given|When|Then)\\*\\*|\\n\\s*\\n|$)`, + 'i', + ).exec(body) + + const text = + match?.[1] !== undefined + ? clean(match[1].replace(/\n>\s?/g, ' ')).replace(/^[—–:-]\s*/, '') + : '' + + return text === '' ? undefined : text +} + +const markedOf = (body: string, marker: RegExp): string | undefined => { + for (const line of body.split('\n')) { + if (marker.test(line)) { + const text = clean(line.replace(/^>\s*/, '').replace(marker, '')) + .replace(/^[—–-]\s*/, '') + .trim() + + return text === '' ? undefined : text + } + } + + return undefined +} + +/** The text after `**Name:**` (or `**Name**:`) on its own line, for the labelled-fields layout. */ +const labelledOf = (body: string, name: string): string | undefined => { + const match = new RegExp(`^[ \\t]*\\*\\*${name}:?\\*\\*:?[ \\t]*(.*)$`, 'im').exec(body) + const text = match?.[1] !== undefined ? clean(match[1]) : '' + + return text === '' ? undefined : text +} + +/** + * Given/When/Then written as lines (`Given …`, `When …`, `Then …`, `And …`), usually inside a + * fenced block under `**Specification:**`. `And` lines continue the clause before them. + */ +const specOf = (body: string): { given?: string; when?: string; then?: string } => { + const block = /\*\*Specification:?\*\*:?\s*([\s\S]*?)(?=\n[ \t]*\*\*[A-Za-z][^*\n]*\*\*|$)/i.exec(body)?.[1] ?? '' + const clauses: Record<'given' | 'when' | 'then', string[]> = { given: [], when: [], then: [] } + let current: 'given' | 'when' | 'then' | undefined + + for (const raw of block.split('\n')) { + const line = raw.trim().replace(/^```\w*$/, '').replace(/^[-*]\s+/, '') + const match = /^(Given|When|Then|And)\s+(.*)$/.exec(line) + + if (match === null) { + continue + } + + const word = match[1] ?? '' + const rest = clean(match[2] ?? '') + + if (word === 'And') { + if (current !== undefined) { + clauses[current].push(rest) + } + + continue + } + + current = word.toLowerCase() as 'given' | 'when' | 'then' + clauses[current].push(rest) + } + + const join = (parts: string[]) => (parts.length === 0 ? undefined : parts.join(' · ')) + + return { given: join(clauses.given), when: join(clauses.when), then: join(clauses.then) } +} + +function cardOf( + id: string, + title: string, + body: string, + domain: string | undefined, +): Rule { + const lines = body.split('\n') + const header = lines.find(line => line.trim() !== '') ?? '' + const headerParts = header.split('·').map(part => clean(part)) + + const category = + headerParts + .slice(1) + .find(part => part !== '' && !/confidence/i.test(part) && !/`/.test(part)) ?? labelledOf(body, 'Category') + + const confidence = + /confidence\s*:?\s*\**\s*(High|Medium|Low)\b/i.exec(body)?.[1] ?? undefined + + const statement = + labelledOf(body, 'Plain English') ?? + lines + .slice(lines.indexOf(header) + 1) + .map(line => line.trim()) + .find( + line => + line !== '' && + !line.startsWith('>') && + !line.startsWith('|') && + !line.startsWith('**') && + !line.startsWith('-') && + !line.startsWith('#') && + !line.startsWith('`'), + ) ?? '' + + const edgeStart = lines.findIndex(line => /^\*\*Edge cases?[^*]*\*\*/i.test(line.trim())) + + const edgeCases: string[] = [] + + if (edgeStart >= 0) { + for (const line of lines.slice(edgeStart + 1)) { + const trimmed = line.trim() + + if (trimmed.startsWith('- ')) { + edgeCases.push(clean(trimmed.slice(2))) + } else if (trimmed !== '' && edgeCases.length > 0) { + break + } + } + } + + const spec = specOf(body) + const given = gwtOf(body, 'Given') ?? spec.given + const when = gwtOf(body, 'When') ?? spec.when + const then = gwtOf(body, 'Then') ?? spec.then + const defect = markedOf(body, /(?:⚠️?\s*\**\s*Suspected defect\**|^\s*\*\*Suspected defect:?\*\*:?)/i) + + // `❓ **SME question** — …`, or `**Confidence:** Medium — SME question: …` on the confidence line. + const smeInline = /\bSME questions?\s*:\s*(.+)$/im.exec(body)?.[1] + + const sme = + markedOf(body, /❓\s*\**\s*SME(?:\s+questions?)?\**/i) ?? + (smeInline !== undefined && clean(smeInline) !== '' ? clean(smeInline) : undefined) + + return { + id, + title: clean(title), + priority: priorityOf(id, body), + ...(category !== undefined && { category }), + ...(confidence !== undefined && { + confidence: confidence[0]?.toUpperCase() + confidence.slice(1).toLowerCase(), + }), + statement: clean(statement), + ...(given !== undefined && { given }), + ...(when !== undefined && { when }), + ...(then !== undefined && { then }), + edgeCases, + ...(defect !== undefined && { defect }), + ...(sme !== undefined && { sme }), + citations: citationsIn(body), + ...(domain !== undefined && { domain }), + } +} + +/** A short stable id for a rule that carries none: a hash of its title, so a verdict survives the table being rewritten in another order. */ +export function idOfTitle(title: string): string { + let hash = 2166136261 + + for (const char of title.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()) { + hash = Math.imul(hash ^ char.charCodeAt(0), 16777619) + } + + return `R-${(hash >>> 0).toString(16).padStart(8, '0').slice(0, 6)}` +} + +function rowOf( + line: string, + domain: string | undefined, +): Rule | null { + const cells = line + .split('|') + .slice(1, -1) + .map(cell => cell.trim()) + + const first = cells[0] ?? '' + const titleMatch = /\*\*(.+?)\*\*/.exec(first) + + if (cells.length < 2 || titleMatch === null || /^-+$/.test(first)) { + return null + } + + const title = clean(titleMatch[1] ?? '') + + if (title === '' || /^rule$/i.test(title)) { + return null + } + + const idInTitle = new RegExp(`^(${ID})\\b`).exec(title)?.[1] + const category = clean(first.replace(titleMatch[0], '').replace(/<br\s*\/?>/gi, ' ')) + const gwt = cells[1] ?? '' + const part = (tag: string) => + clean(new RegExp(`\\*\\*${tag}\\*\\*\\s*(.*?)(?=\\*\\*[GWT]\\*\\*|$)`).exec(gwt)?.[1] ?? '') + + const given = part('G') + const when = part('W') + const then = part('T') + const flags = cells.slice(3).join(' ') + const priority = /\b(P\d)\b/.exec(`${flags} ${first}`)?.[1] ?? '' + + return { + id: idInTitle ?? idOfTitle(title), + title, + priority, + ...(category !== '' && { category }), + statement: '', + ...(given !== '' && { given }), + ...(when !== '' && { when }), + ...(then !== '' && { then }), + edgeCases: [], + ...(/⚠|defect/i.test(flags) && { defect: clean(flags) }), + ...(/❓|SME/i.test(flags) && { sme: clean(flags) }), + citations: citationsIn(line), + ...(domain !== undefined && { domain }), + } +} + +/** Parses BUSINESS_RULES.md. Never throws; an unreadable file is no rules. */ +export function parseRules(text: string): RuleSet { + const lines = text.split('\n') + const rules: Rule[] = [] + let domain: string | undefined + /** Set by a top-level heading: `# P1 rules` gives its rows a priority, an index or appendix is skipped. */ + let sectionPriority = '' + let isTopSkipped = false + let isSectionSkipped = false + + let open: { id: string; title: string; start: number; domain: string | undefined } | null = + null + + const close = (end: number) => { + if (open !== null) { + rules.push( + cardOf(open.id, open.title, lines.slice(open.start, end).join('\n'), open.domain), + ) + + open = null + } + } + + lines.forEach((line, index) => { + const isSkipped = isTopSkipped || isSectionSkipped + const card = isSkipped ? null : CARD_HEADING.exec(line) + + if (card !== null) { + close(index) + open = { id: card[1] ?? '', title: card[2] ?? '', start: index + 1, domain } + + return + } + + const top = /^#\s+(.+?)\s*$/.exec(line) + + if (top !== null) { + close(index) + sectionPriority = /\b(P\d)\b/.exec(top[1] ?? '')?.[1] ?? '' + isTopSkipped = SKIPPED_SECTION.test(top[1] ?? '') + isSectionSkipped = false + domain = undefined + + return + } + + const heading = DOMAIN_HEADING.exec(line) + + if (heading !== null && !line.startsWith('###')) { + close(index) + domain = clean(heading[1] ?? '') + isSectionSkipped = SKIPPED_SECTION.test(heading[1] ?? '') + + return + } + + if (/^#{1,4}\s/.test(line)) { + close(index) + + return + } + + if (open === null && !(isTopSkipped || isSectionSkipped) && line.startsWith('|')) { + const row = rowOf(line, domain) + + if (row !== null) { + rules.push(row.priority === '' ? { ...row, priority: sectionPriority } : row) + } + } + }) + + close(lines.length) + + const byId = new Map<string, Rule>() + const byFileBase = new Map<string, Rule[]>() + + for (const rule of rules) { + if (!byId.has(rule.id)) { + byId.set(rule.id, rule) + } + + for (const base of new Set(rule.citations.map(citation => citation.base))) { + const bucket = byFileBase.get(base) ?? [] + + bucket.push(rule) + byFileBase.set(base, bucket) + } + } + + return { rules, byId, byFileBase } +} + +/** The rules that need a person: a suspected defect, an SME note, or less than High confidence. */ +export function needsReview(rule: Rule): boolean { + return ( + rule.sme !== undefined || + rule.defect !== undefined || + (rule.confidence !== undefined && rule.confidence !== 'High') + ) +} diff --git a/plugins/code-modernization/hooks/reader/topology.ts b/plugins/code-modernization/hooks/reader/topology.ts new file mode 100644 index 00000000..b0f5adb5 --- /dev/null +++ b/plugins/code-modernization/hooks/reader/topology.ts @@ -0,0 +1,243 @@ +import { baseName, norm } from '../paths' + +/** + * `analysis/<system>/topology.json`, read into the few shapes the live pane uses. + * + * The file is written by an agent, so every field is treated as optional and + * of unknown shape: anything that does not fit is dropped, never thrown on. + */ + +export type TopoNode = { + id: string + name: string + /** `module`, `datastore`, `screen`, or whatever the map stage wrote. */ + kind: string + /** Lines of code; 0 when the map gave none. */ + loc: number + /** Source file relative to `legacy/<system>/`, when the node is one file. */ + file?: string + /** The name of the domain (first ancestor of kind `domain`) it sits under. */ + domain?: string + /** The language the map recorded for it, as written (`cobol`, `java`, `php`). */ + language?: string +} + +export type TopoEdge = { source: string; target: string; kind: string } + +export type TopoFlow = { + name: string + persona?: string + steps: { label: string; nodes: string[] }[] +} + +export type Topology = { + system: string + nodes: TopoNode[] + /** Nodes that are code (`kind: module`, or any leaf with a file and loc). */ + modules: TopoNode[] + domains: { name: string; modules: TopoNode[] }[] + edges: TopoEdge[] + entryPoints: Set<string> + deadEnds: Set<string> + flows: TopoFlow[] + byId: Map<string, TopoNode> + /** Lower-cased base name of a node's file, to the nodes that have it. */ + byFileBase: Map<string, TopoNode[]> +} + +const str = (value: unknown): string | undefined => + typeof value === 'string' && value !== '' ? value : undefined + +const isRecord = (value: unknown): value is Record<string, unknown> => + typeof value === 'object' && value !== null && !Array.isArray(value) + +const list = (value: unknown): unknown[] => (Array.isArray(value) ? value : []) + +function walk( + raw: unknown, + domain: string | undefined, + out: TopoNode[], + depth: number, +): void { + if (!isRecord(raw) || depth > 12) { + return + } + + const id = str(raw.id) ?? str(raw.name) + + if (id === undefined) { + return + } + + const kind = str(raw.kind) ?? 'node' + const name = str(raw.name) ?? id + const children = list(raw.children) + const here = kind === 'domain' ? name : domain + const loc = typeof raw.loc === 'number' && raw.loc > 0 ? raw.loc : 0 + const file = str(raw.file) + const language = str(raw.language) + + if (children.length === 0 || kind === 'module') { + out.push({ + id, + name, + kind, + loc, + ...(file !== undefined && { file: norm(file) }), + ...(here !== undefined && { domain: here }), + ...(language !== undefined && { language }), + }) + } + + for (const child of children) { + walk(child, here, out, depth + 1) + } +} + +/** Parses topology.json; null when the text is not a usable topology. */ +export function parseTopology(text: string): Topology | null { + let raw: unknown + + try { + raw = JSON.parse(text) + } catch { + return null + } + + if (!isRecord(raw)) { + return null + } + + const nodes: TopoNode[] = [] + + if (isRecord(raw.root)) { + walk(raw.root, undefined, nodes, 0) + } + + for (const flat of list(raw.nodes)) { + walk(flat, undefined, nodes, 0) + } + + if (nodes.length === 0) { + return null + } + + const byId = new Map<string, TopoNode>() + + for (const node of nodes) { + if (!byId.has(node.id)) { + byId.set(node.id, node) + } + } + + const unique = [...byId.values()] + + const modules = unique.filter( + node => + node.kind === 'module' || + (node.file !== undefined && node.loc > 0 && node.kind !== 'datastore'), + ) + + const byDomain = new Map<string, TopoNode[]>() + + for (const node of modules) { + const key = node.domain ?? 'Other' + const bucket = byDomain.get(key) ?? [] + + bucket.push(node) + byDomain.set(key, bucket) + } + + const byFileBase = new Map<string, TopoNode[]>() + + for (const node of unique) { + if (node.file === undefined) { + continue + } + + const key = baseName(node.file).toLowerCase() + const bucket = byFileBase.get(key) ?? [] + + bucket.push(node) + byFileBase.set(key, bucket) + } + + const edges: TopoEdge[] = [] + + for (const edge of list(raw.edges)) { + if (!isRecord(edge)) { + continue + } + + const source = str(edge.source) ?? str(edge.from) + const target = str(edge.target) ?? str(edge.to) + + if (source !== undefined && target !== undefined) { + edges.push({ source, target, kind: str(edge.kind) ?? 'uses' }) + } + } + + const flows: TopoFlow[] = [] + + for (const flow of list(raw.flows)) { + if (!isRecord(flow)) { + continue + } + + const name = str(flow.name) + + if (name === undefined) { + continue + } + + const persona = str(flow.persona) + + flows.push({ + name, + ...(persona !== undefined && { persona }), + steps: list(flow.steps) + .filter(isRecord) + .map(step => ({ + label: str(step.label) ?? '', + nodes: list(step.nodes).filter( + (node): node is string => typeof node === 'string', + ), + })), + }) + } + + const ids = (value: unknown) => + new Set(list(value).filter((id): id is string => typeof id === 'string')) + + return { + system: str(raw.system) ?? '', + nodes: unique, + modules, + domains: [...byDomain.entries()].map(([name, members]) => ({ + name, + modules: members, + })), + edges, + entryPoints: ids(raw.entryPoints), + deadEnds: ids(raw.deadEnds), + flows, + byId, + byFileBase, + } +} + +/** + * The topology node a legacy file belongs to: by its path relative to + * `legacy/<system>/` when the map recorded one, else by base name alone. + */ +export function nodeOfFile(topo: Topology, fileRel: string): TopoNode | null { + const wanted = norm(fileRel) + const candidates = topo.byFileBase.get(baseName(wanted).toLowerCase()) ?? [] + + return ( + candidates.find(node => node.file === wanted) ?? + candidates.find(node => wanted.endsWith(node.file ?? '\0')) ?? + candidates[0] ?? + null + ) +} diff --git a/plugins/code-modernization/hooks/reader/tracks.ts b/plugins/code-modernization/hooks/reader/tracks.ts new file mode 100644 index 00000000..8ce75985 --- /dev/null +++ b/plugins/code-modernization/hooks/reader/tracks.ts @@ -0,0 +1,86 @@ +/** + * The three ways the plugin's commands work on a system, and what each leaves behind. The pane follows + * whichever one the artifacts on disk say is under way, so a same-stack version uplift or a greenfield + * rebuild is followed as closely as a rewrite is. + */ + +export type TrackKey = 'transform' | 'uplift' | 'reimagine' + +export const TRACK_LABELS: Record<TrackKey, string> = { + transform: 'rewrite', + uplift: 'uplift', + reimagine: 'reimagine', +} + +/** The unit of work in each track, as the pane names a list of them. */ +export const TRACK_UNITS: Record<TrackKey, { one: string; many: string }> = { + transform: { one: 'module', many: 'Modules' }, + uplift: { one: 'module', many: 'Modules' }, + reimagine: { one: 'service', many: 'Services' }, +} + +/** What each state of a unit of work is called, by track: the same colors, worded for what the work is. */ +export const STATE_WORDS_BY_TRACK: Record<TrackKey, Record<string, string>> = { + transform: { + untouched: 'untouched', + scaffolded: 'scaffolded', + 'tests-written': 'tests written', + 'tests-red': 'tests red', + 'tests-green': 'tests green', + reviewed: 'reviewed', + ported: 'ported', + switched: 'switched', + }, + uplift: { + untouched: 'not migrated', + scaffolded: 'changed', + 'tests-written': 'tests written', + 'tests-red': 'worse than baseline', + 'tests-green': 'tests pass', + reviewed: 'matches baseline', + ported: 'ported', + switched: 'switched', + }, + reimagine: { + untouched: 'legacy', + scaffolded: 'scaffolded', + 'tests-written': 'tests written', + 'tests-red': 'tests red', + 'tests-green': 'tests green', + reviewed: 'reviewed', + ported: 'ported', + switched: 'switched', + }, +} + +/** Times (ms) of the artifacts that mark each track as under way; null where the artifact is absent. */ +export type TrackFacts = { + transformAt: number | null + upliftAt: number | null + reimagineAt: number | null +} + +/** + * The track under way: the one whose own artifacts were written last. The discovery artifacts (preflight, + * assess, map, rules, brief) feed all three and decide nothing. With no track's own artifacts a system + * is at the start of the rewrite path, which is where the plugin's commands begin. + */ +export function pickTrack(option: TrackKey | 'auto', facts: TrackFacts): TrackKey { + if (option !== 'auto') { + return option + } + + const ranked = ( + [ + ['transform', facts.transformAt], + ['reimagine', facts.reimagineAt], + ['uplift', facts.upliftAt], + ] as const + ).filter((entry): entry is readonly [TrackKey, number] => entry[1] !== null) + + if (ranked.length === 0) { + return 'transform' + } + + return ranked.reduce((best, entry) => (entry[1] > best[1] ? entry : best))[0] +} diff --git a/plugins/code-modernization/hooks/reader/uplift.ts b/plugins/code-modernization/hooks/reader/uplift.ts new file mode 100644 index 00000000..58e99060 --- /dev/null +++ b/plugins/code-modernization/hooks/reader/uplift.ts @@ -0,0 +1,238 @@ +import { join } from '../paths' +import { unitOfPath, type EstateModel, type EstateUnit } from './estate-model' +import type { ReaderFs } from './fs' +import { readTests, stateOfUplift, type ModernizedModule, type ModuleState, type TestTotals } from './modernized' + +/** + * What a same-stack uplift leaves on disk, read without knowing the stack: the + * baseline's per-module results, the delta catalog's size, and which modules of the + * working copy differ from the legacy tree. + */ + +export type BaselineRow = { pass: number; fail: number; error: number; skip: number } + +export type Baseline = { + /** The file says the source runtime could not run here, so there is no per-test table. */ + isTargetOnly: boolean + /** Test results in all, from the table or the file's own totals line. */ + results: number | null + /** One row per module, keyed by the module path lower-cased with no trailing slash. */ + rows: Map<string, BaselineRow> +} + +const int = (text: string | undefined): number => { + const value = Number((text ?? '').replace(/[,\s_]/g, '')) + + return Number.isFinite(value) ? value : 0 +} + +const cellsOf = (line: string): string[] => + line + .trim() + .replace(/^\|/, '') + .replace(/\|$/, '') + .split('|') + .map(cell => cell.trim()) + +const keyOf = (text: string): string => + text + .replace(/[`*]/g, '') + .replace(/^\.\//, '') + .replace(/\/+$/, '') + .trim() + .toLowerCase() + +/** The module key a working-copy path is looked up by. */ +export const baselineKeyOf = keyOf + +/** Reads a baseline file: any table with pass and fail columns gives a row per module. */ +export function parseBaseline(text: string): Baseline { + const rows = new Map<string, BaselineRow>() + const lines = text.split('\n') + + for (let index = 0; index < lines.length - 1; index += 1) { + const head = lines[index] ?? '' + + if (!head.trim().startsWith('|') || !/^\s*\|?\s*:?-{2,}/.test(lines[index + 1] ?? '')) { + continue + } + + const names = cellsOf(head).map(name => name.replace(/[`*]/g, '').toLowerCase()) + const passAt = names.findIndex(name => /^pass/.test(name)) + const failAt = names.findIndex(name => /^fail/.test(name)) + + if (passAt < 0 || failAt < 0) { + continue + } + + const errorAt = names.findIndex(name => /^err/.test(name)) + const skipAt = names.findIndex(name => /^(skip|ignor|pending)/.test(name)) + const found = names.findIndex(name => /^(module|project|unit|suite|package|assembly|component|name)/.test(name)) + const keyAt = found >= 0 ? found : 0 + + for (let row = index + 2; row < lines.length && (lines[row] ?? '').trim().startsWith('|'); row += 1) { + const cells = cellsOf(lines[row] ?? '') + const key = keyOf(cells[keyAt] ?? '') + + if (key === '' || /^(total|totals|sum|all|overall)\b/.test(key)) { + continue + } + + rows.set(key, { + pass: int(cells[passAt]), + fail: int(cells[failAt]), + error: errorAt >= 0 ? int(cells[errorAt]) : 0, + skip: skipAt >= 0 ? int(cells[skipAt]) : 0, + }) + } + } + + const totals = /([\d,]+)\s+test\s+results?/i.exec(text)?.[1] ?? /\btotal\b[^\n]{0,40}?([\d,]{2,})\s+tests?\b/i.exec(text)?.[1] + const summed = [...rows.values()].reduce((sum, row) => sum + row.pass + row.fail + row.error + row.skip, 0) + + return { + isTargetOnly: /^\s*target-only:/im.test(text), + results: totals !== undefined ? int(totals) : rows.size > 0 ? summed : null, + rows, + } +} + +export type Catalog = { + count: number + /** Lower-cased base name of a file the catalog cites, to the delta ids it is cited under. */ + byFileBase: Map<string, string[]> +} + +/** + * What the delta catalog holds: how many deltas (its own statement of the count, else its `D<n>` ids), and which + * delta each file it names is cited under: the delta a table row or a heading names last, before the file. + */ +export function parseCatalog(text: string): Catalog | null { + const stated = /\b(\d+)\s+(?:distinct\s+)?deltas\b/i.exec(text)?.[1] + const ids = new Set<string>() + const byFileBase = new Map<string, string[]>() + let current: string | null = null + + for (const line of text.split('\n')) { + const opens = /^\s*(?:\|\s*\**|#{1,6}\s+\**)(D-?\d{1,3})\b/.exec(line)?.[1] + + if (opens !== undefined) { + current = opens + ids.add(opens) + } + + for (const found of line.matchAll(/D-?\d{1,3}\b/g)) { + ids.add(found[0]) + } + + if (current === null) { + continue + } + + for (const cited of line.matchAll(/`([\w./@+-]+\.[A-Za-z0-9]{1,8})(?::\d+(?:[-–]\d+)?)?`/g)) { + const base = (cited[1] ?? '').split('/').at(-1)?.toLowerCase() ?? '' + const held = byFileBase.get(base) ?? [] + + if (base !== '' && !held.includes(current)) { + held.push(current) + byFileBase.set(base, held) + } + } + } + + const count = stated !== undefined && int(stated) > 0 ? int(stated) : ids.size + + return count > 0 ? { count, byFileBase } : null +} + +/** + * The paths that differ between a tree and the working copy made from it: a file present in both with another size, + * one only the copy has, and one only the tree has. It compares names and sizes, so an edit that keeps a file's size + * exactly is not seen here; a test run in that module, or an edit made during the session, shows it. + */ +export function changedPathsOf(before: ReadonlyMap<string, number>, after: ReadonlyMap<string, number>): string[] { + const out: string[] = [] + + for (const [path, size] of after) { + if (before.get(path) !== size) { + out.push(path) + } + } + + for (const path of before.keys()) { + if (!after.has(path)) { + out.push(path) + } + } + + return out +} + +/** The estate's unit ids that hold at least one of the changed paths. */ +export function changedUnitsOf(estate: EstateModel, changed: readonly string[]): Set<string> { + const ids = new Set<string>() + + for (const path of changed) { + const unit = unitOfPath(estate, null, path) + + if (unit !== null) { + ids.add(unit.id) + } + } + + return ids +} + +/** + * Each unit of the working copy that the uplift has touched or tested, with its state: + * changed, tested, matching the baseline, or worse than it. `observed` holds the totals of test + * runs seen this session, used where no report file was left. + */ +export async function readUpliftUnits( + fs: ReaderFs, + workingRoot: string, + estate: EstateModel, + changed: ReadonlySet<string>, + baseline: Baseline | null, + observed: ReadonlyMap<string, TestTotals>, +): Promise<{ unit: EstateUnit; module: ModernizedModule }[]> { + const out: { unit: EstateUnit; module: ModernizedModule }[] = [] + + for (const unit of estate.units) { + if (unit.dir === undefined) { + if (changed.has(unit.id)) { + out.push({ unit, module: moduleOf(unit.name, join(workingRoot, unit.file ?? unit.id), null, 'scaffolded') }) + } + + continue + } + + const path = unit.dir === '' ? workingRoot : join(workingRoot, unit.dir) + const tests = (await readTests(fs, path)) ?? observed.get(path) ?? null + const row = baseline?.rows.get(keyOf(unit.dir)) ?? null + const state = stateOfUplift(tests, row, changed.has(unit.id)) + + if (state !== 'untouched') { + out.push({ unit, module: moduleOf(unit.dir === '' ? unit.name : unit.dir, path, tests, state) }) + } + } + + return out +} + +function moduleOf(dir: string, path: string, tests: TestTotals | null, state: ModuleState): ModernizedModule { + return { + dir, + path, + hasMain: true, + hasTests: tests !== null, + hasNotes: false, + hasReviewSection: false, + isPortedNotSwitched: false, + isSwitched: false, + followUps: 0, + tests, + state, + mtimeMs: 0, + } +} diff --git a/plugins/code-modernization/hooks/register.ts b/plugins/code-modernization/hooks/register.ts new file mode 100644 index 00000000..09e5822e --- /dev/null +++ b/plugins/code-modernization/hooks/register.ts @@ -0,0 +1,1256 @@ +import type { EngineInterface, On, PluginOptions, ResultOf } from 'claude-code' + +import { lineOf, missingPathOf, noteCall, noteDone, noteFailure, prune, subjectOf } from './fleet/fleet' +import type { Host } from './host' +import { paint, tilesOf, type TouchKind } from './map/estate' +import { absOf, baseName, isUnder, join, norm, relTo } from './paths' +import { keysOfUnit, unitOfPath } from './reader/estate-model' +import { readOrNull } from './reader/fs' +import type { TestTotals } from './reader/modernized' +import { oneLineOf, readSnapshot, REVIEWS_FILE } from './reader/progress' +import type { ReviewVerdict } from './reader/progress' +import { nodeOfFile } from './reader/topology' +import { decide, ledgerJson, ledgerMarkdown, nextUnreviewed, queueOf, undecide, type DeckScope } from './review/deck' +import { signBrief } from './sign' +import { + newActivity, + newState, + PANE_ID, + PLUGIN_NAME, + RASTER_KEY, + SIGN_ID, + type FinishedCall, + type State, +} from './state' +import { readTestRun, TEST_COMMAND } from './tests-run' +import { deckView, signView } from './views/deck' +import { headerRowsOf, paneView, planOf, showBar, type Kit } from './views/pane' +import { xrayOf } from './xray/xray' + +const REFRESH_DEBOUNCE_MS = 450 +const FRAME_MS = 140 +const CLOCK_MS = 1000 +const POLL_MS = 20_000 +const WRITE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit']) +const QUIET_TOOLS = new Set(['Read', 'Glob', 'Grep', 'LS', 'WebFetch', 'WebSearch', 'TodoWrite', 'ToolSearch']) +const PARENT_TOOLS = new Set(['Agent', 'Task', 'Workflow']) +const STEP = /\/(?:[\w-]+:)?(modernize-[a-z-]+)\b[^\n]*/ + +const nowMs = (): number => Date.now() + +/** A cell count as the engine reports it, made safe to do layout arithmetic on. */ +const wholeOf = (value: unknown): number => + typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0 + +/** + * Binds a Host from `$`. Declared in this file, each member spelled + * `$.noun.event(...)`, so the engine reads what the module calls off its source. + */ +function hostOf($: EngineInterface): Host { + return { + fs: { + read: path => $.fs.read(path), + write: (path, text) => $.fs.write(path, text), + list: path => $.fs.list(path), + exists: path => $.fs.exists(path), + stat: path => $.fs.stat(path), + }, + now: () => $.clock.now(), + after: (ms, fn) => $.clock.after(ms, fn), + every: (ms, fn) => $.clock.every(ms, fn), + storeGet: key => $.store.get(key), + storeSet: (key, value) => $.store.set(key, value), + invalidate: () => $.ui.invalidate('ui.render'), + blit: args => $.ui.blit(args), + status: text => $.ui.status(text), + toast: (text, timeoutMs) => $.ui.toast(text, timeoutMs !== undefined ? { timeoutMs } : undefined), + log: text => $.ui.log(text), + openPane: pane => $.ui.open(pane), + closePane: pane => $.ui.close(pane), + registerCommand: spec => $.command.register(spec), + fillPrompt: input => $.prompt.fill(input), + submitPrompt: input => $.prompt.submit(input), + abortTurn: turnId => $.turn.abort({ turnId }), + } +} + +/** + * `fs` with every relative path rooted at `cwd`: the artifacts live under the + * session's working directory, wherever the process itself happens to stand. + */ +function rootedAt(fs: Host['fs'], cwd: string): Host['fs'] { + return { + read: path => fs.read(absOf(cwd, path)), + write: (path, text) => fs.write(absOf(cwd, path), text), + list: path => fs.list(absOf(cwd, path)), + exists: path => fs.exists(absOf(cwd, path)), + stat: path => fs.stat(absOf(cwd, path)), + } +} + +/** + * Registers the plugin's live hooks: the pane and its estate map, x-ray + * reads, the rule review deck, the fleet view and the sign-off dialog. + * `session.start` binds the engine; every hook after + * it works over that binding and one state object. + * + * @param on the engine's registrar + * @param raw the plugin's options as the settings hold them + */ +export function register(on: On, raw: PluginOptions) { + const state: State = newState(raw) + + // ---------------------------------------------------------------- reading + + async function refresh(host: Host): Promise<void> { + if (state.isRefreshing) { + state.isRefreshQueued = true + + return + } + + state.isRefreshing = true + + try { + const snapshot = await readSnapshot(host.fs, state.cache, { + ...((state.pickedSystem ?? state.options.system) !== '' && { system: state.pickedSystem ?? state.options.system }), + commandPrefix: state.options.commandPrefix, + legacyDir: state.options.legacyDir, + track: state.options.track, + writtenUnits: state.writtenUnits, + observed: state.observed, + nowMs: nowMs(), + }) + + // The pane opens by itself once there is modernization to show: the first artifact under analysis/, + // not only a legacy system that has not been touched. + const isFirstSight = snapshot !== null && snapshot.hasAnalysis && state.snapshot?.hasAnalysis !== true + + state.snapshot = snapshot + state.readError = null + + if (isFirstSight) { + maybeAutoOpen() + } + + if (snapshot !== null) { + if (!state.deck.isOpen) { + state.deck.ledger = snapshot.reviews + } + + // The pane says all of this already, and so does the bar that stands where it was while it is hidden. The + // pinned line is for a person who turned the pane off. A workspace that holds a legacy system and nothing + // yet under analysis/ has no modernization to report. + host.status(state.pane.isOpen || !snapshot.hasAnalysis || state.options.panel !== 'off' ? undefined : oneLineOf(snapshot)) + } + + if (state.estate !== null) { + state.estate = { ...state.estate, tiles: [] } + } + } catch (error) { + state.readError = error instanceof Error ? error.message : String(error) + } finally { + state.isRefreshing = false + host.invalidate() + + if (state.isRefreshQueued) { + state.isRefreshQueued = false + scheduleRefresh(host) + } + } + } + + function scheduleRefresh(host: Host): void { + state.timers.get('refresh')?.cancel() + + state.timers.set( + 'refresh', + host.after(REFRESH_DEBOUNCE_MS, () => { + state.timers.delete('refresh') + void refresh(host) + }), + ) + } + + // ------------------------------------------------------------- animation + + function frameOf(): { cells: string; isAnimating: boolean } | null { + const estate = state.estate + + if (estate === null || state.snapshot === null) { + return null + } + + const painted = paint(estate.tiles, estate.columns, estate.rows, state.touches, nowMs()) + + return { cells: painted.cells, isAnimating: painted.isAnimating } + } + + function animate(host: Host): void { + if (state.timers.has('frames') || !state.pane.isOpen) { + return + } + + state.timers.set( + 'frames', + host.every(FRAME_MS, () => { + const estate = state.estate + const frame = frameOf() + + if (estate === null || frame === null || !state.pane.isOpen) { + state.timers.get('frames')?.cancel() + state.timers.delete('frames') + + return + } + + void host + .blit({ + requestId: PANE_ID, + key: RASTER_KEY, + cells: frame.cells, + columns: estate.columns, + rows: estate.rows, + }) + .then(result => { + // Said once: a refused repaint means the map is stale, which is worth knowing. + if (result.deny !== undefined && !state.timers.has('blit-refused')) { + state.timers.set('blit-refused', host.after(60_000, () => state.timers.delete('blit-refused'))) + host.log(`estate map: repaint refused (${result.deny})`) + } + }) + .catch(() => undefined) + + if (!frame.isAnimating) { + state.timers.get('frames')?.cancel() + state.timers.delete('frames') + } + }), + ) + } + + function touch(host: Host, nodeId: string, kind: TouchKind): void { + const held = state.touches.get(nodeId) + + // A write outranks a read that is still fading. + if (held !== undefined && held.kind === 'write' && kind === 'read' && nowMs() - held.atMs < 1200) { + return + } + + state.touches.set(nodeId, { atMs: nowMs(), kind }) + animate(host) + } + + /** The estate unit ids a tool call's paths and command text name, with how each was touched. */ + function nodesTouched(tool: string, args: Readonly<Record<string, unknown>>): { id: string; kind: TouchKind }[] { + const snapshot = state.snapshot + const estate = snapshot?.estate + + if (snapshot === null || estate === null || estate === undefined) { + return [] + } + + const legacyRoot = join(state.options.legacyDir, snapshot.system) + const modernRoot = join('modernized', snapshot.system) + const upliftRoot = join('modernized', `${snapshot.system}-uplifted`) + const out = new Map<string, TouchKind>() + const kind: TouchKind = WRITE_TOOLS.has(tool) ? 'write' : 'read' + + const take = (path: string, how: TouchKind) => { + const rel = relTo(state.cwd, path) + + if (rel === null) { + return + } + + if (isUnder(rel, legacyRoot) && rel !== legacyRoot) { + const unit = unitOfPath(estate, snapshot.topology, rel.slice(legacyRoot.length + 1)) + + if (unit !== null) { + out.set(unit.id, how) + } + } else if (isUnder(rel, upliftRoot) && rel !== upliftRoot) { + // An uplift's working copy has the legacy tree's own layout, so the same path names the same unit. + const unit = unitOfPath(estate, snapshot.topology, rel.slice(upliftRoot.length + 1)) + + if (unit !== null) { + out.set(unit.id, how) + + // An edit that keeps a file's size is invisible to the size comparison; a write seen here is not. + if (how === 'write') { + state.writtenUnits.add(unit.id) + } + } + } else if (isUnder(rel, modernRoot) && rel !== modernRoot) { + const dir = (rel.slice(modernRoot.length + 1).split('/')[0] ?? '').toLowerCase() + + const unit = estate.units.find(candidate => keysOfUnit(candidate).some(key => key.toLowerCase() === dir)) + + if (unit !== undefined) { + out.set(unit.id, how === 'read' ? 'read' : 'write') + } + } + } + + for (const key of ['file_path', 'path', 'notebook_path']) { + const value = args[key] + + if (typeof value === 'string') { + take(value, kind) + } + } + + const command = typeof args.command === 'string' ? args.command : '' + + if (command !== '') { + const paths = command.match(/(?:\.{0,2}\/)?[\w.@~+-]+(?:\/[\w.@~+-]+)+/g) ?? [] + const writes = /(?:>|\btee\b|\bsed\s+-i|\bmv\b|\bcp\b|\brm\b|\bpatch\b|\bgit\s+(?:apply|checkout|restore))/.test(command) + + for (const path of paths.slice(0, 24)) { + const rel = relTo(state.cwd, path) ?? '' + + take(path, writes && (isUnder(rel, modernRoot) || isUnder(rel, upliftRoot)) ? 'write' : 'read') + } + } + + return [...out.entries()].map(([id, how]) => ({ id, kind: how })) + } + + /** The module a shell command's text names by path, of those the pane knows: the longest path wins. */ + function moduleOfCommand(command: string): string | null { + const snapshot = state.snapshot + + if (snapshot === null) { + return null + } + + const upliftRoot = join('modernized', `${snapshot.system}-uplifted`) + + const candidates = [ + ...snapshot.modules.map(module => module.path), + ...(snapshot.track === 'uplift' + ? (snapshot.estate?.units ?? []).flatMap(unit => (unit.dir !== undefined && unit.dir !== '' ? [join(upliftRoot, unit.dir)] : [])) + : []), + ].sort((a, b) => b.length - a.length) + + const escaped = (path: string) => path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + + return ( + candidates.find(path => new RegExp(`(?:^|[\\s'"=:@])(?:\\./)?${escaped(path)}(?=[\\s/'"]|$)`).test(command)) ?? null + ) + } + + // ------------------------------------------------------------------ deck + + async function openDeck(host: Host, scope: DeckScope, filter: string): Promise<string> { + const snapshot = state.snapshot + + if (snapshot === null || snapshot.rules === null) { + return 'No BUSINESS_RULES.md to review yet. Run the extract-rules command first.' + } + + const queue = queueOf(snapshot.rules, scope, filter) + + state.deck = { + isOpen: true, + scope, + filter, + queue, + ledger: snapshot.reviews, + index: nextUnreviewed(queue, snapshot.reviews, 0), + source: null, + isSourceShown: false, + } + + // The deck draws in the band above the prompt: nothing to open, only to draw. + host.invalidate() + + return queue.length === 0 + ? 'Nothing to review under that scope.' + : `Reviewing ${queue.length} rule${queue.length === 1 ? '' : 's'}.` + } + + async function saveLedger(host: Host): Promise<void> { + const system = state.snapshot?.system + + if (system === undefined) { + return + } + + await host.fs.write(join('analysis', system, REVIEWS_FILE), ledgerJson(system, state.deck.ledger)) + await host.fs.write(join('analysis', system, 'RULE_REVIEWS.md'), ledgerMarkdown(system, state.deck.ledger)) + scheduleRefresh(host) + } + + async function loadSource(host: Host): Promise<void> { + const rule = state.deck.queue[state.deck.index] + const snapshot = state.snapshot + const citation = rule?.citations[0] + + if (rule === undefined || snapshot === null || citation === undefined) { + return + } + + const legacyRoot = join(state.options.legacyDir, snapshot.system) + const written = norm(citation.path) + const viaMap = snapshot.topology !== null ? nodeOfFile(snapshot.topology, written)?.file : undefined + + const candidates = [ + written, + join(legacyRoot, written), + ...(viaMap !== undefined ? [join(legacyRoot, viaMap)] : []), + ] + + for (const path of candidates) { + const text = await readOrNull(host.fs, path) + + if (text === null) { + continue + } + + const lines = text.split('\n') + // From the cited line itself: in a short band every row of lead-in costs a row of the rule's own code. + const from = Math.max(1, citation.from) + const to = Math.min(lines.length, Math.max(citation.to + 2, from + 11), from + 39) + + state.deck.source = { + ruleId: rule.id, + path, + startLine: from, + text: lines + .slice(from - 1, to) + .join('\n') + .replace(/[^\x09\x0a\x20-\x7e -]/g, ' ') + .slice(0, 9000), + } + + return + } + + state.deck.source = { ruleId: rule.id, path: written, startLine: citation.from, text: '(source file not found)' } + } + + const deckActionsOf = (host: Host) => ({ + decide: (verdict: ReviewVerdict) => { + const rule = state.deck.queue[state.deck.index] + + if (rule === undefined) { + return + } + + state.deck.ledger = decide(state.deck.ledger, rule, verdict, new Date(nowMs()).toISOString()) + state.deck.index = nextUnreviewed(state.deck.queue, state.deck.ledger, state.deck.index + 1) + state.deck.isSourceShown = false + void saveLedger(host).catch(() => undefined) + host.invalidate() + }, + undo: () => { + const rule = state.deck.queue[state.deck.index] + + if (rule !== undefined) { + state.deck.ledger = undecide(state.deck.ledger, rule.id) + void saveLedger(host).catch(() => undefined) + host.invalidate() + } + }, + prev: () => { + const size = state.deck.queue.length + + state.deck.index = size === 0 ? 0 : (state.deck.index - 1 + size) % size + state.deck.isSourceShown = false + host.invalidate() + }, + next: () => { + const size = state.deck.queue.length + + state.deck.index = size === 0 ? 0 : (state.deck.index + 1) % size + state.deck.isSourceShown = false + host.invalidate() + }, + source: () => { + state.deck.isSourceShown = !state.deck.isSourceShown + + if (state.deck.isSourceShown) { + void loadSource(host).then(() => host.invalidate()) + } + + host.invalidate() + }, + close: () => { + state.deck.isOpen = false + host.invalidate() + }, + }) + + // ------------------------------------------------------------------ sign + + async function openSign(host: Host, name = ''): Promise<string> { + const snapshot = state.snapshot + + if (snapshot === null || snapshot.brief === null) { + return 'There is no brief to sign yet. Run the brief command first.' + } + + if (snapshot.brief.approval.isSigned) { + return `The brief is already signed${snapshot.brief.approval.by !== undefined ? ` by ${snapshot.brief.approval.by}` : ''}.` + } + + if (state.activity.isWorking) { + return 'Wait for the running turn to finish before signing.' + } + + state.sign = { isOpen: true, name: name !== '' ? name : state.sign.name, covers: 'phase-1', error: null } + + await host.openPane({ + id: SIGN_ID, + title: 'Sign the brief', + focus: true, + closeOnEscape: true, + holdToasts: true, + rows: 12, + }) + + host.invalidate() + + return '' + } + + const signActionsOf = (host: Host) => ({ + name: (value: string) => { + state.sign.name = value + }, + covers: (value: 'phase-1' | 'full') => { + state.sign.covers = value + host.invalidate() + }, + cancel: () => { + state.sign.isOpen = false + void host.closePane({ id: SIGN_ID }).catch(() => undefined) + }, + sign: () => { + void (async () => { + const system = state.snapshot?.system + const name = state.sign.name.trim() + + if (system === undefined) { + return + } + + if (name === '') { + state.sign.error = 'Type the approver\'s name first.' + host.invalidate() + + return + } + + if (state.activity.isWorking) { + state.sign.error = 'A turn is running; sign once it has finished.' + host.invalidate() + + return + } + + const path = join('analysis', system, 'MODERNIZATION_BRIEF.md') + const text = await readOrNull(host.fs, path) + const signed = text !== null ? signBrief(text, name, new Date(nowMs()).toISOString().slice(0, 10), state.sign.covers) : null + + if (signed === null) { + state.sign.error = 'The brief has no approval block to sign.' + host.invalidate() + + return + } + + await host.fs.write(path, signed) + state.sign.isOpen = false + await host.closePane({ id: SIGN_ID }).catch(() => undefined) + host.log(`brief signed by ${name} (${state.sign.covers === 'full' ? 'full plan' : 'Phase 1 only'})`) + await refresh(host) + })() + }, + }) + + // ------------------------------------------------------------------ pane + + async function openPane(host: Host): Promise<void> { + await host.openPane({ id: PANE_ID, title: 'Modernization' }) + state.pane.isOpen = true + state.pane.isClosedByPerson = false + void refresh(host) + } + + const paneActionsOf = (host: Host) => ({ + system: () => { + const systems = state.snapshot?.systems ?? [] + const current = state.snapshot?.system + + if (systems.length < 2 || current === undefined) { + return + } + + // A different system is a different estate, a different brief and a different set of lit tiles. + state.pickedSystem = systems[(systems.indexOf(current) + 1) % systems.length] ?? current + state.touches.clear() + state.writtenUnits.clear() + state.estate = null + void refresh(host) + }, + next: () => { + const next = state.snapshot?.next + + if (next === null || next === undefined || next.isByHand) { + return + } + + void host + .fillPrompt({ text: next.text }) + .then(result => { + if (!result.isFilled) { + host.toast(`Next: ${next.text}`, 8000) + } + }) + .catch(() => undefined) + }, + refresh: () => { + state.cache.clear() + void refresh(host) + }, + review: () => { + void openDeck(host, 'flagged', '').catch(() => undefined) + }, + sign: () => { + void openSign(host) + .then(message => { + if (message !== '') { + host.toast(message, 6000) + } + }) + .catch(() => undefined) + }, + close: () => { + state.pane.isOpen = false + state.pane.isClosedByPerson = true + void host.closePane({ id: PANE_ID }).catch(() => undefined) + }, + stop: () => { + const turnId = state.activity.turnId + + if (turnId !== null) { + void host.abortTurn(turnId).catch(() => undefined) + } + }, + }) + + /** + * Opens the pane by itself once there is something to show, the person has not closed it, and + * the layout docks panes (the fullscreen layout). What the layout is comes from whichever render + * last said: not every build draws every site, so each render hook reports what it saw. + */ + function maybeAutoOpen(viewport?: { columns?: number; isFullscreen?: boolean }): void { + state.viewport.columns = viewport?.columns ?? state.viewport.columns + state.viewport.isFullscreen = viewport?.isFullscreen ?? state.viewport.isFullscreen + + const host = state.host + + const shouldOpen = + host !== null && + state.options.panel === 'auto' && + !state.pane.isOpen && + !state.pane.isClosedByPerson && + !state.timers.has('auto-open') && + state.snapshot !== null && + state.snapshot.hasAnalysis && + state.viewport.isFullscreen === true + + if (shouldOpen && host !== null) { + // Opened from a timer: a render hook only draws. + state.timers.set( + 'auto-open', + host.after(50, () => { + state.timers.delete('auto-open') + void openPane(host).catch(() => undefined) + }), + ) + } + } + + // ------------------------------------------------------------- lifecycle + + on('session.start', async ($, e, next) => { + const bound = hostOf($) + const host: Host = { ...bound, fs: rootedAt(bound.fs, e.cwd) } + + state.host = host + state.cwd = e.cwd + + for (const timer of state.timers.values()) { + timer.cancel() + } + + state.timers.clear() + + await Promise.all([ + host + .registerCommand({ + name: 'modernize-panel', + description: 'Show or hide the modernization progress pane and estate map', + argumentHint: '[open|close|json]', + immediate: true, + }) + .catch(() => undefined), + host + .registerCommand({ + name: 'modernize-review', + description: 'Review business rules one card at a time: confirm, wrong, or discuss', + argumentHint: '[flagged|p0|all] [filter]', + }) + .catch(() => undefined), + host + .registerCommand({ + name: 'modernize-sign', + description: 'Sign the modernization brief\'s approval block (a person\'s action)', + argumentHint: '[approver name, role]', + }) + .catch(() => undefined), + ]) + + await refresh(host) + + state.timers.set( + 'clock', + host.every(CLOCK_MS, () => { + if (state.pane.isOpen && (state.activity.isWorking || state.activity.running.size > 0)) { + host.invalidate() + } + }), + ) + + state.timers.set( + 'poll', + host.every(POLL_MS, () => { + if (state.pane.isOpen && !state.activity.isWorking) { + scheduleRefresh(host) + } + }), + ) + + return next(e) + }) + + on('ui.render', { component: 'PromptHint' }, ($, e, next) => { + if (e.surface === 'terminal') { + maybeAutoOpen(e.viewport) + } + + return next(e) + }) + + on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => { + const host = state.host + + if (e.surface === 'terminal') { + // Not every build reports `isFullscreen`. The band's `maxRows` tells the same fact: under the + // fullscreen layout it is what the bottom slot has left; otherwise it is the terminal's height. + const rows = e.viewport?.rows + const inferred = rows !== undefined && e.props.maxRows > 0 ? e.props.maxRows < rows : undefined + + maybeAutoOpen({ + ...(e.viewport?.columns !== undefined && { columns: e.viewport.columns }), + ...((e.viewport?.isFullscreen ?? inferred) !== undefined && { + isFullscreen: e.viewport?.isFullscreen ?? inferred, + }), + }) + } + + // A survey holds the band first; the deck waits behind it. + if (host === null || e.props.hasSurvey || e.surface !== 'terminal') { + return next(e) + } + + const table = $.ui.resolve(e) + + // With no deck open, a hidden pane leaves one row and a button to bring it back: the pane is + // always one press away, on a terminal too narrow to open it unasked as well as on a wide one. + if (!state.deck.isOpen) { + const snapshot = state.snapshot + + if (state.options.panel === 'off' || state.pane.isOpen || snapshot === null || !snapshot.hasAnalysis) { + return next(e) + } + + return showBar( + { Box: table.Box, Text: table.Text, Button: table.Button }, + oneLineOf(snapshot), + e.props.bodyColumns, + () => { + void openPane(host).catch(() => undefined) + }, + ) + } + + return deckView( + { Box: table.Box, Text: table.Text, Button: table.Button, Code: table.Code }, + state.deck, + e.props.bodyColumns, + e.props.maxRows, + deckActionsOf(host), + ) + }) + + on('ui.render', { component: 'Pane' }, async ($, e, next) => { + const host = state.host + + if (host === null || (e.requestId !== PANE_ID && e.requestId !== SIGN_ID)) { + return next(e) + } + + const table = $.ui.resolve(e) + const kit: Kit = { + Box: table.Box, + Text: table.Text, + Button: table.Button, + ...('Raster' in table && { Raster: table.Raster }), + ...('Code' in table && { Code: table.Code }), + ...('Input' in table && { Input: table.Input }), + ...('Select' in table && { Select: table.Select }), + } + + const columns = Math.max(24, wholeOf(e.props.bodyColumns) - 1) + + if (e.requestId === SIGN_ID) { + return signView( + kit, + state.sign, + state.snapshot?.system ?? '', + state.snapshot?.brief?.openQuestions ?? 0, + columns, + signActionsOf(host), + ) + } + + // A squeezed pane (a dialog or another panel has its rows) can report a body of no rows at all. + const rows = wholeOf(e.props.scroll.bodyRows) + + state.pane.isOpen = true + state.pane.bodyColumns = columns + state.pane.bodyRows = rows + state.pane.placement = e.props.placement + + const snapshot = state.snapshot + + const plan = planOf(rows, e.props.placement, { + phases: snapshot?.brief?.phases.length ?? 0, + modules: snapshot?.modules.length ?? 0, + attention: + (snapshot?.attention.length ?? 0) + + [...state.fleet.signatures.values()].filter(signature => signature.agents.size >= 3).length, + hasMap: snapshot !== null && snapshot.estate !== null && kit.Raster !== undefined, + headerRows: headerRowsOf(snapshot, columns), + }) + + let estate: { cells: string; columns: number; rows: number; tiles: State['estate'] extends infer T ? (T extends { tiles: infer U } ? U : never) : never } | null = null + + // The plan sheds the map first when the body is too short; a Raster of no rows is refused. + if (snapshot !== null && snapshot.estate !== null && kit.Raster !== undefined && plan.estate >= 1 && columns >= 1) { + const mapRows = Math.min(256, plan.estate) + const held = state.estate + + const tiles = + held !== null && held.columns === columns && held.rows === mapRows && held.tiles.length > 0 + ? held.tiles + : tilesOf(snapshot, columns, mapRows) + + state.estate = { tiles, columns, rows: mapRows, isMounted: true } + + const painted = paint(tiles, columns, mapRows, state.touches, nowMs()) + + estate = { cells: painted.cells, columns, rows: mapRows, tiles } + + if (painted.isAnimating) { + animate(host) + } + } else { + // No map drawn: nothing for the frame timer to repaint. + state.estate = null + } + + return paneView( + kit, + state, + { columns, rows, placement: e.props.placement, nowMs: nowMs(), estate, plan }, + paneActionsOf(host), + ) + }) + + on('ui.close', async ($, e, next) => { + const result = await next(e) + + if (result.deny !== undefined) { + return result + } + + if (e.id === PANE_ID) { + state.pane.isOpen = false + state.pane.isClosedByPerson = e.origin.kind === 'person' || state.pane.isClosedByPerson + + if (state.estate !== null) { + state.estate.isMounted = false + } + } else if (e.id === SIGN_ID) { + state.sign.isOpen = false + } + + return result + }) + + // -------------------------------------------------------------- commands + + on('command.run', { command: 'modernize-panel' }, async ($, e, next) => { + const host = state.host + + if (host === null) { + return next(e) + } + + state.viewport.isFullscreen = e.presentation.isFullscreen + state.viewport.columns = e.presentation.columns + + const arg = e.args.trim().toLowerCase() + + if (arg === 'json') { + await refresh(host) + + const snapshot = state.snapshot + + return { + text: + snapshot === null + ? 'no system under analysis/' + : `\`\`\`json\n${JSON.stringify( + { + system: snapshot.system, + stages: snapshot.stages.map(stage => ({ key: stage.key, done: stage.isDone, detail: stage.detail })), + brief: snapshot.brief && { + target: snapshot.brief.target, + approval: snapshot.brief.approval, + phases: snapshot.brief.phases.map(phase => ({ + number: phase.number, + title: phase.title, + size: phase.size, + modules: phase.modules, + criteria: phase.criteria.length, + ticked: phase.criteria.filter(criterion => criterion.isTicked).length, + })), + }, + modules: snapshot.modules.map(module => ({ + dir: module.dir, + state: module.state, + tests: module.tests, + reviewDate: module.reviewDate, + })), + totals: snapshot.totals, + percent: snapshot.percent, + attention: snapshot.attention, + next: snapshot.next, + }, + null, + 2, + )}\n\`\`\``, + } + } + + const wantsClose = arg === 'close' || (arg === '' && state.pane.isOpen) + + if (wantsClose) { + state.pane.isOpen = false + state.pane.isClosedByPerson = true + await host.closePane({ id: PANE_ID }).catch(() => undefined) + + return { text: 'Modernization pane hidden' } + } + + await openPane(host) + + return { text: 'Modernization pane shown' } + }) + + on('command.run', { command: 'modernize-review' }, async ($, e, next) => { + const host = state.host + + if (host === null) { + return next(e) + } + + await refresh(host) + + const words = e.args.trim().split(/\s+/).filter(word => word !== '') + const first = (words[0] ?? '').toLowerCase() + const scope: DeckScope = first === 'p0' || first === 'all' || first === 'flagged' ? first : 'flagged' + const filter = (scope === first ? words.slice(1) : words).join(' ') + const text = await openDeck(host, scope, filter) + + return { text } + }) + + on('command.run', { command: 'modernize-sign' }, async ($, e, next) => { + const host = state.host + + if (host === null) { + return next(e) + } + + await refresh(host) + + const message = await openSign(host, e.args.replace(/\s+/g, ' ').trim()) + + return message === '' ? {} : { text: message } + }) + + on('command.run', { command: ['clear', 'resume'] }, async ($, e, next) => { + const result = await next(e) + + state.activity = newActivity() + state.touches.clear() + state.writtenUnits.clear() + state.lastContextLine = '' + + return result + }) + + // ----------------------------------------------------------------- turns + + on('prompt.submit', async ($, e, next) => { + const host = state.host + const step = STEP.exec(e.text) + + if (step !== null) { + state.activity.step = step[0].trim().slice(0, 120) + } + + const snapshot = state.snapshot + + if (host === null || snapshot === null || e.origin.kind !== 'composer') { + return next(e) + } + + const line = `${oneLineOf(snapshot)}${snapshot.next !== null ? ` · next: ${snapshot.next.text}` : ''}` + + if (line === state.lastContextLine) { + return next(e) + } + + state.lastContextLine = line + + return next({ + ...e, + context: [...(e.context ?? []), `Modernization state, read from the artifacts on disk: ${line}`], + }) + }) + + on('turn.start', async ($, e, next) => { + const host = state.host + + state.activity.isWorking = true + state.activity.turnId = e.turnId + state.activity.turnStartMs = nowMs() + state.activity.xraysThisTurn = 0 + + if (host !== null) { + host.invalidate() + } + + return next(e) + }) + + on('turn.complete', async ($, e, next) => { + const host = state.host + + if (e.agentId !== undefined) { + noteDone(state.fleet, e.agentId, nowMs()) + + return next(e) + } + + state.activity.isWorking = false + state.activity.running.clear() + + if (host !== null) { + if (state.activity.xraysThisTurn > 0) { + host.log( + `x-ray: ${state.activity.xraysThisTurn} legacy read${state.activity.xraysThisTurn === 1 ? '' : 's'} this turn carried what the analysis already knows`, + ) + } + + prune(state.fleet, nowMs()) + scheduleRefresh(host) + } + + return next(e) + }) + + // ------------------------------------------------------------ tool calls + + on('tool.call', async ($, e, next) => { + const host = state.host + + if (host === null) { + return next(e) + } + + const args = e as unknown as Readonly<Record<string, unknown>> + const tool = e.tool + const agentId = e.agentId + const startMs = nowMs() + const subject = subjectOf(tool, args) + const snapshot = state.snapshot + const touched = nodesTouched(tool, args) + + for (const entry of touched) { + touch(host, entry.id, entry.kind) + } + + if (agentId !== undefined) { + const unit = touched[0] !== undefined ? snapshot?.estate?.units.find(candidate => candidate.id === touched[0]?.id)?.name : undefined + + noteCall(state.fleet, agentId, tool, subject, startMs, unit) + } + + state.activity.running.set(e.tool_use_id, { + id: e.tool_use_id, + tool, + subject, + startMs, + ...(agentId !== undefined && { agentId }), + }) + + const path = typeof args.file_path === 'string' ? args.file_path : typeof args.notebook_path === 'string' ? args.notebook_path : undefined + const rel = path !== undefined ? relTo(state.cwd, path) : null + + let result: ResultOf['tool.call'] | undefined + let note: string | undefined + + try { + result = await next(e) + + if (result.deny !== undefined) { + return result + } + + const extra: string[] = [] + const isError = result.isError === true + const text = typeof result.text === 'string' ? result.text : '' + + if (isError && agentId !== undefined) { + // What the call was aimed at is half of the cause: the path as the agent gave it, else the command's head. + const missing = missingPathOf(text) + const example = rel ?? (missing !== undefined ? (relTo(state.cwd, missing) ?? missing) : subject) + const signature = noteFailure(state.fleet, agentId, text, nowMs(), example) + + if (signature !== null) { + const line = lineOf(signature) + + host.toast(`Fleet: ${line}`, 9000) + host.log(`fleet: ${line}. One cause across agents usually belongs in the playbook, not in each agent.`) + } + } + + if (tool === 'Read' && !isError && state.options.isXrayOn && snapshot !== null && rel !== null) { + const legacyRoot = join(state.options.legacyDir, snapshot.system) + + if (isUnder(rel, legacyRoot) && rel !== legacyRoot) { + const xray = xrayOf(snapshot, { + fileRel: rel.slice(legacyRoot.length + 1), + ...(typeof args.offset === 'number' && { offset: args.offset }), + ...(typeof args.limit === 'number' && { limit: args.limit }), + }) + + if (xray !== null) { + extra.push(xray.text) + note = xray.summary.replace(/^x-ray [^:]+: /, 'x-ray ') + state.activity.xrays += 1 + + if (agentId === undefined) { + state.activity.xraysThisTurn += 1 + } + } + } + } + + // A citation in the analysis is relative to the legacy system's root, and an agent handed one + // often reads it from the workspace root. Say where the file is rather than let it search. + if (tool === 'Read' && isError && state.options.isXrayOn && snapshot !== null && rel !== null && /does not exist/i.test(text)) { + const legacyRoot = join(state.options.legacyDir, snapshot.system) + const candidate = join(legacyRoot, rel) + + if (!isUnder(rel, state.options.legacyDir) && (await host.fs.exists(candidate))) { + extra.push( + `There is no ${rel} in the workspace, but ${candidate} exists. Paths cited under analysis/${snapshot.system}/ are relative to ${legacyRoot}/.`, + ) + note = 'x-ray: the path exists under the legacy root' + } + } + + if ((tool === 'Bash' || tool === 'PowerShell') && typeof args.command === 'string' && TEST_COMMAND.test(args.command)) { + const run = readTestRun(text) + const spent = nowMs() - startMs + + if (agentId === undefined) { + state.activity.testMs += spent + state.activity.testRuns += 1 + } + + if (run !== null) { + note = `${run.executed} executed${run.skipped > 0 ? `, ${run.skipped} skipped` : ''}${run.failed > 0 ? `, ${run.failed} failed` : ''}` + + // A run in a module's own directory is its result even where its runner left no report file behind. + const home = moduleOfCommand(args.command) + + if (home !== null && run.executed + run.skipped > 0) { + const seen: TestTotals = { tests: run.executed + run.skipped, failures: run.failed, errors: 0, skipped: run.skipped, reports: 1 } + + state.observed.set(home, seen) + } + } + } + + return extra.length > 0 ? { ...result, context: [...(result.context ?? []), ...extra] } : result + } finally { + const ms = nowMs() - startMs + + state.activity.running.delete(e.tool_use_id) + + if (agentId === undefined) { + state.activity.toolMs += ms + + const finished: FinishedCall = { + tool, + subject, + isOk: result !== undefined && result.deny === undefined && result.isError !== true, + ms, + ...(note !== undefined && { note }), + } + + state.activity.finished = [...state.activity.finished, finished].slice(-8) + } + + if (!QUIET_TOOLS.has(tool) || tool === 'Read') { + const wrote = WRITE_TOOLS.has(tool) || tool === 'Bash' || tool === 'PowerShell' || PARENT_TOOLS.has(tool) + + if (wrote) { + // A write may have changed the working copy: the next read lists it afresh. + for (const key of [...state.cache.keys()]) { + if (key.startsWith('changed:')) { + state.cache.delete(key) + } + } + + scheduleRefresh(host) + } else if (state.pane.isOpen) { + host.invalidate() + } + } + } + }) +} + +export { PLUGIN_NAME } diff --git a/plugins/code-modernization/hooks/review/deck.ts b/plugins/code-modernization/hooks/review/deck.ts new file mode 100644 index 00000000..823b7969 --- /dev/null +++ b/plugins/code-modernization/hooks/review/deck.ts @@ -0,0 +1,121 @@ +import type { ReviewLedger, ReviewVerdict } from '../reader/progress' +import { needsReview, type Rule, type RuleSet } from '../reader/rules' + +/** + * The rule review deck: the rules a person should look at, in the order they + * matter, and the ledger of what that person decided. The ledger is a file + * of its own beside the rules (`RULE_REVIEWS.json`, with a readable + * `RULE_REVIEWS.md`), so the agent-written rules file is never edited. + */ + +export type DeckScope = 'flagged' | 'p0' | 'all' + +const weight = (rule: Rule): number => + (rule.priority === 'P0' ? 0 : rule.priority === 'P1' ? 10 : 20) + + (rule.sme !== undefined ? 0 : 2) + + (rule.defect !== undefined ? 0 : 1) + + (rule.confidence !== undefined && rule.confidence !== 'High' ? 0 : 1) + +/** The rules to review under `scope`, optionally only those citing a file or under a domain. */ +export function queueOf(rules: RuleSet, scope: DeckScope, filter = ''): Rule[] { + const wanted = filter.trim().toLowerCase() + + return rules.rules + .filter(rule => { + if (scope === 'flagged' && !(rule.priority === 'P0' && needsReview(rule))) { + return false + } + + if (scope === 'p0' && rule.priority !== 'P0') { + return false + } + + if (wanted === '') { + return true + } + + return ( + rule.id.toLowerCase() === wanted || + (rule.domain ?? '').toLowerCase().includes(wanted) || + rule.title.toLowerCase().includes(wanted) || + rule.citations.some(citation => citation.base.includes(wanted)) || + // What the rule says and what is suspected of it: "truncat" finds the rounding defect whatever its title. + [rule.statement, rule.then, rule.defect].some(text => (text ?? '').toLowerCase().includes(wanted)) + ) + }) + .map((rule, index) => ({ rule, index })) + .sort((a, b) => weight(a.rule) - weight(b.rule) || a.index - b.index) + .map(entry => entry.rule) +} + +/** The first card at or after `from` that has no verdict yet; `from` itself when all have. */ +export function nextUnreviewed(queue: readonly Rule[], ledger: ReviewLedger, from: number): number { + for (let step = 0; step < queue.length; step += 1) { + const index = (from + step) % queue.length + const rule = queue[index] + + if (rule !== undefined && ledger[rule.id] === undefined) { + return index + } + } + + return Math.min(Math.max(0, from), Math.max(0, queue.length - 1)) +} + +/** `ledger` with `rule` decided. */ +export function decide( + ledger: ReviewLedger, + rule: Rule, + verdict: ReviewVerdict, + atIso: string, +): ReviewLedger { + return { ...ledger, [rule.id]: { verdict, at: atIso, title: rule.title } } +} + +/** `ledger` with `rule`'s verdict taken back. */ +export function undecide(ledger: ReviewLedger, ruleId: string): ReviewLedger { + const { [ruleId]: _gone, ...rest } = ledger + + return rest +} + +export const tallyOf = (queue: readonly Rule[], ledger: ReviewLedger) => ({ + total: queue.length, + confirmed: queue.filter(rule => ledger[rule.id]?.verdict === 'confirmed').length, + wrong: queue.filter(rule => ledger[rule.id]?.verdict === 'wrong').length, + discuss: queue.filter(rule => ledger[rule.id]?.verdict === 'discuss').length, + open: queue.filter(rule => ledger[rule.id] === undefined).length, +}) + +/** The ledger as `RULE_REVIEWS.json` stores it. */ +export function ledgerJson(system: string, ledger: ReviewLedger): string { + return `${JSON.stringify({ system, version: 1, reviews: ledger }, null, 2)}\n` +} + +const VERDICT_WORDS: Record<ReviewVerdict, string> = { + confirmed: 'Confirmed', + wrong: 'Wrong', + discuss: 'Needs discussion', +} + +/** The ledger as a page a person or a model reads: `RULE_REVIEWS.md`. */ +export function ledgerMarkdown(system: string, ledger: ReviewLedger): string { + const entries = Object.entries(ledger).sort((a, b) => a[0].localeCompare(b[0], 'en', { numeric: true })) + const count = (verdict: ReviewVerdict) => entries.filter(([, entry]) => entry.verdict === verdict).length + + return [ + `# Rule reviews: ${system}`, + '', + `A person's verdict on individual business rules in \`BUSINESS_RULES.md\`, recorded from the review deck. ${count('confirmed')} confirmed, ${count('wrong')} wrong, ${count('discuss')} needing discussion.`, + '', + 'A rule marked **Wrong** or **Needs discussion** is not settled: do not build on it until it is resolved. A rule with no row here has not been reviewed.', + '', + '| Rule | Verdict | When | Title |', + '|---|---|---|---|', + ...entries.map( + ([id, entry]) => + `| ${id} | ${VERDICT_WORDS[entry.verdict]} | ${entry.at.slice(0, 10)} | ${(entry.title ?? '').replace(/\|/g, '\\|')} |`, + ), + '', + ].join('\n') +} diff --git a/plugins/code-modernization/hooks/sign.ts b/plugins/code-modernization/hooks/sign.ts new file mode 100644 index 00000000..3eeb6157 --- /dev/null +++ b/plugins/code-modernization/hooks/sign.ts @@ -0,0 +1,77 @@ +/** + * Writing a person's signature into the brief's approval block. The block + * comes in a few shapes (one line or several, checkboxes or a choice in + * words); each is filled in where it stands, and nothing else is touched. + */ + +const COVER_WORDS = { 'phase-1': 'Phase 1 only', full: 'Full plan' } as const + +/** + * The brief with its approval block signed; null when it has no `Approved by:` line. + * + * @param text the brief + * @param name who approves + * @param date `YYYY-MM-DD` + * @param covers what the approval covers + */ +export function signBrief( + text: string, + name: string, + date: string, + covers: 'phase-1' | 'full', +): string | null { + const lines = text.split('\n') + const at = lines.findIndex(line => /^\s*Approved by\s*:/i.test(line)) + + if (at < 0) { + return null + } + + const who = name.replace(/\s+/g, ' ').trim() + const line = lines[at] ?? '' + const indent = /^\s*/.exec(line)?.[0] ?? '' + const hasInlineDate = /\bDate\s*:/i.test(line) + + lines[at] = hasInlineDate ? `${indent}Approved by: ${who} Date: ${date}` : `${indent}Approved by: ${who}` + + // The block ends at a blank-line-separated heading or code fence; look a short way down. + const end = Math.min(lines.length, at + 12) + + if (!hasInlineDate) { + const dateAt = lines.findIndex((candidate, index) => index > at && index < end && /^\s*Date\s*:/i.test(candidate)) + + if (dateAt >= 0) { + const head = /^(\s*Date\s*:\s*)/i.exec(lines[dateAt] ?? '')?.[1] ?? 'Date: ' + + lines[dateAt] = `${head}${date}` + } else { + lines.splice(at + 1, 0, `${indent}Date: ${date}`) + } + } + + const coversAt = lines.findIndex( + (candidate, index) => index >= at && index < end + 1 && /Approval covers\s*:/i.test(candidate), + ) + + if (coversAt >= 0) { + const current = lines[coversAt] ?? '' + + if (/\[[ xX]?\]/.test(current)) { + lines[coversAt] = current.replace(/\[[ xX]?\](\s*)([^[\]|]+)/g, (_match, gap: string, label: string) => { + const isFull = /full/i.test(label) + const isPhase = /phase\s*1/i.test(label) + const isChosen = covers === 'full' ? isFull : isPhase + + return `[${isChosen ? 'X' : ' '}]${gap}${label}` + }) + } else { + const head = /^(.*Approval covers\s*:\s*)/i.exec(current)?.[1] ?? 'Approval covers: ' + + lines[coversAt] = `${head}${COVER_WORDS[covers]}` + } + } else { + lines.splice(at + (hasInlineDate ? 1 : 2), 0, `${indent}Approval covers: ${COVER_WORDS[covers]}`) + } + + return lines.join('\n') +} diff --git a/plugins/code-modernization/hooks/state.ts b/plugins/code-modernization/hooks/state.ts new file mode 100644 index 00000000..2ce9b3f8 --- /dev/null +++ b/plugins/code-modernization/hooks/state.ts @@ -0,0 +1,180 @@ +import type { PluginOptions, Timer } from 'claude-code' + +import { newFleet, type Fleet } from './fleet/fleet' +import type { Host } from './host' +import type { Tile, Touch } from './map/estate' +import type { TestTotals } from './reader/modernized' +import type { ReaderCache, ReviewLedger, Snapshot } from './reader/progress' +import type { TrackKey } from './reader/tracks' +import type { Rule } from './reader/rules' +import type { DeckScope } from './review/deck' + +export const PANE_ID = 'modernize' +export const DECK_ID = 'modernize-review' +export const SIGN_ID = 'modernize-sign' +export const RASTER_KEY = 'estate' +export const PLUGIN_NAME = 'code-modernization' + +export type Options = { + system: string + /** Which way to follow the system: the one whose artifacts are newest (`auto`), or one named. */ + track: TrackKey | 'auto' + panel: 'auto' | 'command' | 'off' + isXrayOn: boolean + commandPrefix: string + legacyDir: string +} + +const pick = <T extends string>(value: unknown, allowed: readonly T[], fallback: T): T => + typeof value === 'string' && (allowed as readonly string[]).includes(value) ? (value as T) : fallback + +/** The options with their defaults applied, whatever the settings held. */ +export function optionsOf(raw: PluginOptions): Options { + const str = (key: string, fallback: string) => { + const value = raw[key] + + return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback + } + + return { + system: str('system', ''), + track: pick(raw.track, ['auto', 'transform', 'uplift', 'reimagine'] as const, 'auto'), + panel: pick(raw.panel, ['auto', 'command', 'off'] as const, 'auto'), + isXrayOn: raw.xray !== false, + commandPrefix: str('commandPrefix', '/code-modernization:modernize-'), + legacyDir: str('legacyDir', 'legacy').replace(/^\.?\/+|\/+$/g, ''), + } +} + +export type RunningCall = { + id: string + tool: string + subject: string + startMs: number + agentId?: string +} + +export type FinishedCall = { + tool: string + subject: string + isOk: boolean + ms: number + note?: string +} + +export type Activity = { + isWorking: boolean + turnId: string | null + turnStartMs: number + /** The `/…modernize-<verb>` the current or last turn began with. */ + step: string | null + running: Map<string, RunningCall> + finished: FinishedCall[] + /** Milliseconds the main loop spent in tool calls, and in those that ran tests. */ + toolMs: number + testMs: number + testRuns: number + xrays: number + xraysThisTurn: number +} + +export type DeckState = { + isOpen: boolean + scope: DeckScope + filter: string + queue: Rule[] + index: number + ledger: ReviewLedger + /** The source lines of the card in view, once asked for. */ + source: { ruleId: string; path: string; startLine: number; text: string } | null + isSourceShown: boolean +} + +export type SignState = { + isOpen: boolean + name: string + covers: 'phase-1' | 'full' + error: string | null +} + +export type State = { + host: Host | null + cwd: string + /** The system a person switched to with the pane's button, over the `system` option. */ + pickedSystem: string | null + options: Options + cache: ReaderCache + snapshot: Snapshot | null + readError: string | null + isRefreshing: boolean + isRefreshQueued: boolean + timers: Map<string, Timer> + pane: { + isOpen: boolean + isClosedByPerson: boolean + bodyColumns: number + bodyRows: number + placement: 'dock' | 'inline' + } + viewport: { columns: number | null; isFullscreen: boolean | null } + activity: Activity + touches: Map<string, Touch> + /** Test totals seen in commands this session, by the module path each was run in. */ + observed: Map<string, TestTotals> + /** Units of an uplift's working copy written during this session. */ + writtenUnits: Set<string> + estate: { tiles: Tile[]; columns: number; rows: number; isMounted: boolean } | null + fleet: Fleet + deck: DeckState + sign: SignState + lastContextLine: string +} + +export const newActivity = (): Activity => ({ + isWorking: false, + turnId: null, + turnStartMs: 0, + step: null, + running: new Map(), + finished: [], + toolMs: 0, + testMs: 0, + testRuns: 0, + xrays: 0, + xraysThisTurn: 0, +}) + +export function newState(raw: PluginOptions): State { + return { + host: null, + cwd: '', + pickedSystem: null, + options: optionsOf(raw), + cache: new Map(), + snapshot: null, + readError: null, + isRefreshing: false, + isRefreshQueued: false, + timers: new Map(), + pane: { isOpen: false, isClosedByPerson: false, bodyColumns: 48, bodyRows: 30, placement: 'dock' }, + viewport: { columns: null, isFullscreen: null }, + activity: newActivity(), + touches: new Map(), + observed: new Map(), + writtenUnits: new Set(), + estate: null, + fleet: newFleet(), + deck: { + isOpen: false, + scope: 'flagged', + filter: '', + queue: [], + index: 0, + ledger: {}, + source: null, + isSourceShown: false, + }, + sign: { isOpen: false, name: '', covers: 'phase-1', error: null }, + lastContextLine: '', + } +} diff --git a/plugins/code-modernization/hooks/tests-run.ts b/plugins/code-modernization/hooks/tests-run.ts new file mode 100644 index 00000000..cdc97eb3 --- /dev/null +++ b/plugins/code-modernization/hooks/tests-run.ts @@ -0,0 +1,87 @@ +/** + * Reading a test run off a shell command's output: how many cases executed, + * failed and were skipped, for the runners a modernized module usually has. + */ + +const RUNNER = + /^(?:(?:\.\/)?mvnw?\b.*\b(?:test|verify|surefire:test)\b|(?:\.\/)?gradlew?\b.*\b(?:test|check)\b|pytest\b|py\.test\b|python3?\s+-m\s+(?:pytest|unittest)\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:npx\s+|bunx\s+)?(?:jest|vitest|mocha)\b|dotnet\s+test\b|go\s+test\b|cargo\s+test\b|(?:bundle\s+exec\s+)?rspec\b|prove\b|ctest\b|(?:\.\/vendor\/bin\/)?phpunit\b|make\s+(?:test|check)\b)/ + +/** + * Whether a shell command runs a test suite: a runner in command position in + * any of its segments, not a mere mention of one (`cat pytest.ini` is not). + */ +export function isTestCommand(command: string): boolean { + return command + .split(/&&|\|\||[;|\n(]/) + .map(segment => + segment + .trim() + // Leading `VAR=value` assignments, `time`, `env`, `sudo`, `exec` do not change what runs. + .replace(/^(?:(?:[A-Za-z_][A-Za-z0-9_]*=\S*|time|env|sudo|exec|nice|command)\s+)+/, ''), + ) + .some(segment => RUNNER.test(segment)) +} + +/** Kept for callers that test a whole command string. */ +export const TEST_COMMAND = { test: isTestCommand } + +export type TestRun = { executed: number; failed: number; skipped: number } + +const num = (value: string | undefined) => (value !== undefined ? Number(value) : 0) + +/** The run's totals, or null when the output names none. */ +export function readTestRun(output: string): TestRun | null { + // Maven Surefire / Gradle: the last "Tests run:" line is the total. + const maven = [...output.matchAll(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/g)].at(-1) + + if (maven !== undefined) { + const run = num(maven[1]) + const skipped = num(maven[4]) + + return { executed: Math.max(0, run - skipped), failed: num(maven[2]) + num(maven[3]), skipped } + } + + // pytest: "== 3 passed, 1 skipped, 2 failed in 0.12s ==" or "collected 0 items". + const pytest = /=+\s*((?:\d+\s+\w+,?\s*)+)\s+in\s+[\d.]+s/.exec(output) + + if (pytest !== null) { + const count = (word: string) => num(new RegExp(`(\\d+)\\s+${word}`).exec(pytest[1] ?? '')?.[1]) + const failed = count('failed') + count('error') + count('errors') + + return { executed: count('passed') + failed + count('xfailed') + count('xpassed'), failed, skipped: count('skipped') + count('deselected') } + } + + if (/collected 0 items|no tests ran/i.test(output)) { + return { executed: 0, failed: 0, skipped: 0 } + } + + // Jest / Vitest: "Tests: 1 failed, 2 skipped, 9 passed, 12 total". + const jest = /Tests:\s+([^\n]+?)\s+total/i.exec(output) ?? /Tests\s+([^\n]*\d+\s+passed[^\n]*)/i.exec(output) + + if (jest !== null) { + const count = (word: string) => num(new RegExp(`(\\d+)\\s+${word}`).exec(jest[1] ?? '')?.[1]) + const failed = count('failed') + + return { executed: count('passed') + failed, failed, skipped: count('skipped') + count('todo') } + } + + // dotnet test: "Passed! - Failed: 0, Passed: 12, Skipped: 1, Total: 13". + const dotnet = /Failed:\s*(\d+),\s*Passed:\s*(\d+),\s*Skipped:\s*(\d+),\s*Total:\s*(\d+)/.exec(output) + + if (dotnet !== null) { + return { executed: num(dotnet[1]) + num(dotnet[2]), failed: num(dotnet[1]), skipped: num(dotnet[3]) } + } + + // go test / cargo test. + const cargo = /test result:[^\n]*?(\d+)\s+passed;\s*(\d+)\s+failed;\s*(\d+)\s+ignored/.exec(output) + + if (cargo !== null) { + return { executed: num(cargo[1]) + num(cargo[2]), failed: num(cargo[2]), skipped: num(cargo[3]) } + } + + if (/\bno test files\b|\[no tests to run\]/.test(output)) { + return { executed: 0, failed: 0, skipped: 0 } + } + + return null +} diff --git a/plugins/code-modernization/hooks/views/deck.tsx b/plugins/code-modernization/hooks/views/deck.tsx new file mode 100644 index 00000000..3d81f744 --- /dev/null +++ b/plugins/code-modernization/hooks/views/deck.tsx @@ -0,0 +1,310 @@ +/* @jsxRuntime classic */ +/* @jsx h */ +/* @jsxFrag Fragment */ +import type { RenderChildren, RenderElement } from 'claude-code' + +import type { ReviewVerdict } from '../reader/progress' +import { tallyOf } from '../review/deck' +import type { DeckState, SignState } from '../state' +import type { Kit } from './pane' + +export type DeckActions = { + decide: (verdict: ReviewVerdict) => void + undo: () => void + prev: () => void + next: () => void + source: () => void + close: () => void +} + +const SCOPE_WORDS = { flagged: 'P0 rules flagged for a person', p0: 'all P0 rules', all: 'all rules' } +const SCOPE_SHORT = { flagged: 'flagged P0', p0: 'P0', all: 'all' } + +const VERDICT_COLORS: Record<ReviewVerdict, string> = { + confirmed: 'green', + wrong: 'red', + discuss: 'yellow', +} + +/** `text` word-wrapped to `width` cells, at most `maxLines` rows, the last ending in an ellipsis when cut. */ +export function wrapLines(text: string, width: number, maxLines: number): string[] { + const out: string[] = [] + const limit = Math.max(8, width) + let line = '' + + const push = (value: string) => { + out.push(value) + } + + for (const word of text.split(/\s+/).filter(part => part !== '')) { + let rest = word + + while (rest.length > limit) { + if (line !== '') { + push(line) + line = '' + } + + push(rest.slice(0, limit)) + rest = rest.slice(limit) + } + + if (line === '') { + line = rest + } else if (line.length + 1 + rest.length <= limit) { + line = `${line} ${rest}` + } else { + push(line) + line = rest + } + } + + if (line !== '') { + push(line) + } + + if (out.length <= maxLines) { + return out + } + + const kept = out.slice(0, Math.max(1, maxLines)) + const last = kept[kept.length - 1] ?? '' + + kept[kept.length - 1] = `${last.slice(0, Math.max(0, limit - 1))}…` + + return kept +} + +/** + * The review deck's body: one rule card, its verdict, and the keys. + * + * It draws in the band above the prompt, where a bare digit presses a Button + * from an empty composer. A tree taller than the band scrolls and disarms the + * digits, so the card wraps its own text into counted rows and never exceeds + * `maxRows`. + */ +export function deckView( + kit: Kit, + deck: DeckState, + columns: number, + maxRows: number, + actions: DeckActions, +): RenderElement { + const { Box, Text, Button, Code } = kit + const width = Math.max(30, columns - 2) + const rule = deck.queue[deck.index] + const tally = tallyOf(deck.queue, deck.ledger) + + if (rule === undefined) { + return ( + <Box flexDirection="column"> + <Text bold color="cyan">Rule review</Text> + <Text dimColor wrap="truncate-end"> + {`Nothing to review under "${SCOPE_WORDS[deck.scope]}"${deck.filter !== '' ? ` matching "${deck.filter}"` : ''}. Try /modernize-review all.`} + </Text> + <Button key="close" hotkey="0" plain onPress={actions.close}>close</Button> + </Box> + ) + } + + const verdict = deck.ledger[rule.id] + const first = rule.citations[0] + const shownSource = deck.isSourceShown && deck.source !== null && deck.source.ruleId === rule.id ? deck.source : null + + const meta = [ + rule.domain, + rule.category, + rule.confidence !== undefined ? `confidence ${rule.confidence}` : undefined, + first !== undefined ? `${first.path.split('/').pop()}:${first.from}${first.to !== first.from ? `-${first.to}` : ''}` : undefined, + ].filter((part): part is string => part !== undefined && part !== '') + + const keys = ( + <Box columnGap={2}> + <Button key="confirm" hotkey="1" plain onPress={() => actions.decide('confirmed')}>confirm</Button> + <Button key="wrong" hotkey="2" plain onPress={() => actions.decide('wrong')}>wrong</Button> + <Button key="discuss" hotkey="3" plain onPress={() => actions.decide('discuss')}>discuss</Button> + <Button key="prev" hotkey="4" plain onPress={actions.prev}>back</Button> + <Button key="skip" hotkey="5" plain onPress={actions.next}>skip</Button> + <Button key="source" hotkey="6" plain onPress={actions.source}>{deck.isSourceShown ? 'hide source' : 'source'}</Button> + {verdict !== undefined ? <Button key="undo" hotkey="7" plain onPress={actions.undo}>undo</Button> : null} + <Button key="close" hotkey="0" plain onPress={actions.close}>close</Button> + </Box> + ) + + const verdictLine = + verdict !== undefined ? ( + <Text color={VERDICT_COLORS[verdict.verdict]} bold>{`Verdict: ${verdict.verdict} (${verdict.at.slice(0, 10)})`}</Text> + ) : ( + <Text dimColor>Verdict: none yet</Text> + ) + + const headline = ( + <Text wrap="truncate-end"> + <Text bold color="cyan">Rule review</Text> + <Text bold>{` ${deck.index + 1}/${tally.total}`}</Text> + <Text dimColor>{' '}</Text> + <Text color="green">{`✓ ${tally.confirmed}`}</Text> + <Text dimColor>{' '}</Text> + <Text color="red">{`✗ ${tally.wrong}`}</Text> + <Text dimColor>{' '}</Text> + <Text color="yellow">{`? ${tally.discuss}`}</Text> + <Text dimColor>{` ${tally.open} open · ${width < 96 ? SCOPE_SHORT[deck.scope] : SCOPE_WORDS[deck.scope]}${deck.filter !== '' ? ` · "${deck.filter}"` : ''}`}</Text> + </Text> + ) + + // With the source open the code gets the room: the rule in one line, no blank rows, and as many + // cited lines as the band holds. Seven rows are spoken for: headline, title, meta, statement, + // path, verdict, keys. + if (shownSource !== null && Code !== undefined) { + const codeRows = Math.max(3, Math.min(24, maxRows - 8)) + const gist = rule.statement !== '' ? rule.statement : (rule.then ?? rule.given ?? '') + + return ( + <Box flexDirection="column" width={width}> + {headline} + <Text bold wrap="truncate-end">{`${rule.id.startsWith('R-') ? rule.priority : rule.id} · ${rule.title}`}</Text> + <Text dimColor wrap="truncate-end">{meta.join(' · ')}</Text> + <Text wrap="truncate-end">{wrapLines(gist, width, 1)[0] ?? ''}</Text> + <Text dimColor wrap="truncate-end">{`${shownSource.path}:${shownSource.startLine}`}</Text> + <Code + source={shownSource.text.split('\n').slice(0, codeRows).join('\n')} + path={shownSource.path} + startLine={shownSource.startLine} + wrap="truncate-end" + /> + {verdictLine} + {keys} + </Box> + ) + } + + // Rows that are always there: header, blank, title, meta, blank, [body], blank, verdict, keys. + const fixed = 8 + // One row of slack: a band exactly full still scrolls on some layouts. + const isTight = maxRows < 16 + const room = Math.max(1, maxRows - (isTight ? fixed - 3 : fixed) - 1) + const prose = Math.max(1, room) + + // Share the prose rows: flags one row each, the statement up to two, the rest split over Given/When/Then. + const flagRows = (rule.defect !== undefined ? 1 : 0) + (rule.sme !== undefined ? 1 : 0) + const statementRows = rule.statement !== '' ? Math.min(2, Math.max(0, prose - flagRows - 3)) : 0 + const parts = [rule.given, rule.when, rule.then].filter(part => part !== undefined).length + const each = parts > 0 ? Math.max(1, Math.floor((prose - flagRows - statementRows) / parts)) : 0 + + type Row = { text: string; color?: string; label?: string } + const rows: Row[] = [] + + for (const line of wrapLines(rule.statement, width, statementRows)) { + rows.push({ text: line }) + } + + const block = (label: string, text: string | undefined) => { + if (text === undefined) { + return + } + + wrapLines(`${label} ${text}`, width, each).forEach((line, index) => { + rows.push(index === 0 ? { label, text: line.slice(label.length + 1) } : { text: line }) + }) + } + + block('Given', rule.given) + block('When', rule.when) + block('Then', rule.then) + + if (rule.defect !== undefined) { + rows.push({ text: wrapLines(`⚠ Suspected defect: ${rule.defect}`, width, 1)[0] ?? '', color: 'yellow' }) + } + + if (rule.sme !== undefined) { + rows.push({ text: wrapLines(`? For an SME: ${rule.sme}`, width, 1)[0] ?? '', color: 'magenta' }) + } + + return ( + <Box flexDirection="column" width={width}> + {headline} + <Box marginTop={isTight ? 0 : 1} flexDirection="column"> + <Text bold wrap="truncate-end">{`${rule.id.startsWith('R-') ? rule.priority : rule.id} · ${rule.title}`}</Text> + <Text dimColor wrap="truncate-end">{meta.join(' · ')}</Text> + </Box> + <Box marginTop={isTight ? 0 : 1} flexDirection="column"> + {rows.slice(0, prose).map(row => ( + <Text wrap="truncate-end" color={row.color}> + {row.label !== undefined ? <Text bold color="cyan">{`${row.label} `}</Text> : null} + {row.text} + </Text> + ))} + </Box> + <Box marginTop={isTight ? 0 : 1}>{verdictLine}</Box> + {keys} + </Box> + ) +} + +export type SignActions = { + name: (value: string) => void + covers: (value: 'phase-1' | 'full') => void + sign: () => void + cancel: () => void +} + +/** The sign-off dialog: a person's name, what the approval covers, and the button that writes it. */ +export function signView( + kit: Kit, + sign: SignState, + system: string, + openQuestions: number, + columns: number, + actions: SignActions, +): RenderElement { + const { Box, Text, Button, Input } = kit + const width = Math.max(30, columns) + + return ( + <Box flexDirection="column" width={width}> + <Text bold color="cyan">Sign the brief</Text> + <Text dimColor wrap="wrap"> + {`analysis/${system}/MODERNIZATION_BRIEF.md · execution commands treat an unsigned brief as not approved.`} + </Text> + {openQuestions > 0 ? ( + <Text color="yellow" wrap="wrap">{`${openQuestions} open question${openQuestions === 1 ? '' : 's'} in the brief ${openQuestions === 1 ? 'is' : 'are'} still unticked.`}</Text> + ) : null} + <Box marginTop={1} flexDirection="column"> + {Input !== undefined ? ( + <Input + key="signer" + label="Approved by" + placeholder="name, role" + value={sign.name} + submitLabel="sign" + autoFocus + onInput={actions.name} + onSubmit={value => { + actions.name(value) + actions.sign() + }} + /> + ) : ( + <Text>{`Approved by: ${sign.name}`}</Text> + )} + </Box> + <Box marginTop={1} columnGap={2}> + <Text dimColor>Covers:</Text> + <Button key="phase1" plain onPress={() => actions.covers('phase-1')}> + {`${sign.covers === 'phase-1' ? '◉' : '○'} Phase 1 only`} + </Button> + <Button key="full" plain onPress={() => actions.covers('full')}> + {`${sign.covers === 'full' ? '◉' : '○'} Full plan`} + </Button> + </Box> + {sign.error !== null ? <Text color="red" wrap="wrap">{sign.error}</Text> : null} + <Box marginTop={1} columnGap={2}> + <Button key="do-sign" onPress={actions.sign}>sign</Button> + <Button key="cancel" dimColor onPress={actions.cancel}>cancel</Button> + </Box> + <Box> + <Text dimColor>enter signs · tab moves · esc cancels</Text> + </Box> + </Box> + ) +} diff --git a/plugins/code-modernization/hooks/views/pane.tsx b/plugins/code-modernization/hooks/views/pane.tsx new file mode 100644 index 00000000..7e9ad1b6 --- /dev/null +++ b/plugins/code-modernization/hooks/views/pane.tsx @@ -0,0 +1,567 @@ +/* @jsxRuntime classic */ +/* @jsx h */ +/* @jsxFrag Fragment */ +import type { Elements, RenderChildren, RenderElement } from 'claude-code' + +import { lineOf, tallyOf } from '../fleet/fleet' +import { countsOf, hexOf, STATE_COLORS, stateWord, type Tile } from '../map/estate' +import { isUnitDone, type Snapshot } from '../reader/progress' +import { TRACK_LABELS, TRACK_UNITS } from '../reader/tracks' +import { RASTER_KEY, type State } from '../state' + +/** The elements a pane draws with; `Raster` only where the surface has it (the terminal). */ +export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & + Partial<Pick<Elements['terminal'], 'Raster' | 'Code' | 'Input' | 'Select'>> + +export type PaneActions = { + /** Follow the workspace's next system, when it holds more than one. */ + system: () => void + next: () => void + refresh: () => void + review: () => void + sign: () => void + close: () => void + stop: () => void +} + +export type PaneFrame = { + columns: number + rows: number + placement: 'dock' | 'inline' + nowMs: number + /** The packed cells for the estate, when there is room and a map to draw. */ + estate: { cells: string; columns: number; rows: number; tiles: Tile[] } | null + plan: PanePlan +} + +const pad = (text: string, width: number) => + text.length >= width ? text.slice(0, Math.max(0, width)) : text + ' '.repeat(width - text.length) + +const clip = (text: string, width: number) => + text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…` + +const ago = (ms: number): string => { + const s = Math.max(0, Math.round(ms / 1000)) + + return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m` +} + +const barOf = (fraction: number, width: number): { full: string; rest: string } => { + const filled = Math.max(0, Math.min(width, Math.round(fraction * width))) + + return { full: '━'.repeat(filled), rest: '─'.repeat(width - filled) } +} + +function rule(kit: Kit, title: string, width: number, right = ''): RenderChildren { + const { Box, Text } = kit + const fill = Math.max(1, width - title.length - right.length - 2) + + return ( + <Box> + <Text bold color="cyan">{title}</Text> + <Text dimColor>{` ${'─'.repeat(fill)} `}</Text> + <Text color="yellow">{right}</Text> + </Box> + ) +} + +/** The rows the stage rail takes when it wraps at `width`. */ +const railRowsOf = (snapshot: Snapshot, width: number): number => + Math.max(1, Math.ceil(snapshot.stages.reduce((sum, stage) => sum + stage.label.length + 3, 0) / Math.max(10, width))) + +/** What the estate is made of, in one dim line: its languages, and how many units it was read into. */ +function estateLine(snapshot: Snapshot): string { + const estate = snapshot.estate + + if (estate === null) { + return '' + } + + const languages = estate.languages + .filter(entry => entry.share >= 0.03) + .map(entry => `${entry.name} ${Math.round(entry.share * 100)}%`) + .join(' · ') + + const noun = estate.granularity === 'build module' ? 'build module' : estate.granularity === 'module' ? 'module' : estate.granularity + const count = `${estate.units.length.toLocaleString('en-US')} ${noun}${estate.units.length === 1 ? '' : 's'}` + const from = estate.source === 'map' ? '' : ' (read off the tree)' + + return `${languages === '' ? '' : `${languages} · `}${count}${estate.isPartial ? '+' : ''}${from}` +} + +/** The rows the header takes: the title, the stage rail, the estate line and the progress bar. */ +export const headerRowsOf = (snapshot: Snapshot | null, width: number): number => + snapshot === null + ? 3 + : 1 + railRowsOf(snapshot, width) + (estateLine(snapshot) === '' ? 0 : 1) + (snapshot.percent !== null ? 1 : 0) + +function header(kit: Kit, snapshot: Snapshot, width: number, actions: PaneActions): RenderChildren { + const { Box, Text, Button } = kit + const target = snapshot.brief?.target + const percent = snapshot.percent + const measure = snapshot.estate?.measure === 'bytes' ? 'size' : 'loc' + const right = percent === null ? '' : `${(percent * 100).toFixed(percent < 0.1 ? 1 : 0)}% by ${measure}` + const left = `${snapshot.system}${target !== undefined ? ` → ${target}` : ''}` + const bar = barOf(percent ?? 0, Math.max(4, width - right.length - 1)) + const summary = estateLine(snapshot) + const at = snapshot.systems.indexOf(snapshot.system) + const many = snapshot.systems.length > 1 + + return ( + <Box flexDirection="column"> + <Box justifyContent="space-between"> + <Text bold wrap="truncate-end">{clip(`${left} · ${TRACK_LABELS[snapshot.track]}`, Math.max(8, width - (many ? 22 : 9)))}</Text> + <Box columnGap={1}> + {many ? <Button key="system" dimColor onPress={actions.system}>{`system ${at + 1}/${snapshot.systems.length}`}</Button> : null} + <Button key="hide" dimColor onPress={actions.close}>hide</Button> + </Box> + </Box> + <Box flexWrap="wrap"> + {snapshot.stages.map(stage => ( + <Text color={stage.isDone ? 'green' : undefined} dimColor={!stage.isDone}> + {`${stage.isDone ? '✓' : '·'} ${stage.label} `} + </Text> + ))} + </Box> + {summary !== '' ? <Text dimColor wrap="truncate-end">{clip(summary, width)}</Text> : null} + {percent !== null ? ( + <Box> + <Text color="green">{bar.full}</Text> + <Text dimColor>{bar.rest}</Text> + <Text>{` ${right}`}</Text> + </Box> + ) : null} + </Box> + ) +} + +function estate(kit: Kit, snapshot: Snapshot, frame: PaneFrame, width: number): RenderChildren { + const { Box, Text, Raster } = kit + + if (frame.estate === null || Raster === undefined) { + return null + } + + const counts = countsOf(frame.estate.tiles) + + return ( + <Box flexDirection="column"> + <Raster + key={RASTER_KEY} + columns={frame.estate.columns} + rows={frame.estate.rows} + cells={frame.estate.cells} + /> + <Box flexWrap="wrap" width={width}> + {counts.map(entry => ( + <Text> + <Text color={hexOf(STATE_COLORS[entry.state])}>■</Text> + <Text dimColor>{` ${stateWord(snapshot.track, entry.state)} ${entry.count} `}</Text> + </Text> + ))} + </Box> + </Box> + ) +} + +function phases(kit: Kit, snapshot: Snapshot, width: number, max: number): RenderChildren { + const { Box, Text } = kit + const brief = snapshot.brief + + if (brief === null || brief.phases.length === 0) { + return null + } + + const isDone = (ids: readonly string[]) => + ids.length > 0 && + ids.every(id => { + const module = snapshot.byNode.get(id) + + return module !== undefined && isUnitDone(snapshot, module) + }) + + const ordered = [...brief.phases].sort((a, b) => a.number - b.number) + const currentIndex = Math.max(0, ordered.findIndex(phase => !isDone(phase.modules))) + const start = Math.max(0, Math.min(currentIndex - 1, ordered.length - max)) + const shown = ordered.slice(start, start + max) + const doneCount = ordered.filter(phase => isDone(phase.modules)).length + + return ( + <Box flexDirection="column"> + {rule(kit, 'Phases', width, `${doneCount}/${ordered.length}`)} + {shown.map(phase => { + const done = isDone(phase.modules) + const isCurrent = ordered[currentIndex] === phase && !done + const ticked = phase.criteria.filter(criterion => criterion.isTicked).length + const right = `${phase.criteria.length > 0 ? `${ticked}/${phase.criteria.length} ☑ ` : ''}${pad(phase.size ?? '', 2)}` + const label = `${done ? '✓' : isCurrent ? '▸' : '·'} P${phase.number} ${phase.title}` + + return ( + <Box> + <Text + color={done ? 'green' : isCurrent ? 'cyan' : undefined} + bold={isCurrent} + dimColor={!done && !isCurrent} + > + {pad(clip(label, width - right.length - 1), width - right.length - 1)} + </Text> + <Text dimColor>{` ${right}`}</Text> + </Box> + ) + })} + {ordered.length > shown.length ? ( + <Text dimColor>{` … ${ordered.length - shown.length} more phases`}</Text> + ) : null} + </Box> + ) +} + +/** Units of work in the order that helps most: problems first in an uplift, the newest first in a rewrite. */ +function orderOf(snapshot: Snapshot): Snapshot['modules'] { + if (snapshot.track !== 'uplift') { + return [...snapshot.modules].sort((a, b) => b.mtimeMs - a.mtimeMs) + } + + const rank = (state: string) => (state === 'tests-red' ? 0 : state === 'scaffolded' ? 1 : state === 'tests-green' ? 2 : 3) + + return [...snapshot.modules].sort((a, b) => rank(a.state) - rank(b.state) || (b.tests?.tests ?? 0) - (a.tests?.tests ?? 0)) +} + +function modules(kit: Kit, snapshot: Snapshot, width: number, max: number): RenderChildren { + const { Box, Text } = kit + const all = orderOf(snapshot) + + if (all.length === 0) { + return null + } + + return ( + <Box flexDirection="column"> + {rule(kit, TRACK_UNITS[snapshot.track].many, width, snapshot.track === 'reimagine' ? String(all.length) : `${snapshot.totals.done}/${snapshot.totals.modules}`)} + {all.slice(0, max).map(module => { + const tests = module.tests + const bad = tests === null ? 0 : tests.failures + tests.errors + const isWorse = module.state === 'tests-red' + + // In an uplift a module may fail what the baseline already failed: red is only for what got worse. + const testText = + tests === null + ? '' + : isWorse + ? snapshot.track === 'uplift' + ? `${bad} failing` + : `${bad}/${tests.tests} red` + : bad > 0 && snapshot.track !== 'uplift' + ? `${bad}/${tests.tests} red` + : `${tests.tests} ${snapshot.track === 'uplift' ? 'tests' : 'green'}` + + const color = hexOf(STATE_COLORS[module.state]) + const word = stateWord(snapshot.track, module.state) + const name = clip(module.dir, Math.max(8, width - word.length - testText.length - 5)) + + return ( + <Box> + <Text color={color}>■ </Text> + <Text bold>{name}</Text> + <Text dimColor>{` ${word}`}</Text> + <Text color={isWorse || (bad > 0 && snapshot.track !== 'uplift') ? 'red' : 'green'}> + {testText === '' ? '' : ` ${testText}`} + </Text> + </Box> + ) + })} + {all.length > max ? <Text dimColor>{` … ${all.length - max} more`}</Text> : null} + </Box> + ) +} + +function session(kit: Kit, state: State, frame: PaneFrame, width: number, max: number): RenderChildren { + const { Box, Text } = kit + const activity = state.activity + const fleet = tallyOf(state.fleet, frame.nowMs) + + // A workflow's agents run on while the main loop waits between turns: that is not idle. + const status = activity.isWorking + ? `● working ${ago(frame.nowMs - activity.turnStartMs)}` + : fleet.active > 0 + ? `● ${fleet.active} agents working` + : '○ idle' + + const running = [...activity.running.values()] + .filter(call => call.agentId === undefined) + .sort((a, b) => a.startMs - b.startMs) + + const share = activity.toolMs > 0 ? Math.round((activity.testMs / activity.toolMs) * 100) : 0 + + // Rows in the order they matter; the block draws as many as it was given. + const rows: RenderChildren[] = [] + + if (activity.step !== null) { + rows.push(<Text color="cyan" wrap="truncate-end">{clip(` ${activity.step}`, width)}</Text>) + } + + if (fleet.total > 0) { + rows.push( + <Text wrap="truncate-end"> + <Text color="cyan">{' ⛭ '}</Text> + <Text>{`${fleet.active} agents active`}</Text> + <Text dimColor>{` · ${fleet.done}/${fleet.total} done · ${fleet.calls} calls${fleet.errors > 0 ? ` · ${fleet.errors} errors` : ''}${fleet.stalled > 0 ? ` · ${fleet.stalled} quiet` : ''}`}</Text> + </Text>, + ) + } + + for (const call of running.slice(-2)) { + rows.push( + <Box> + <Text color="yellow">{' ◌ '}</Text> + <Text>{pad(clip(`${call.tool} ${call.subject}`, width - 10), width - 10)}</Text> + <Text dimColor>{` ${ago(frame.nowMs - call.startMs)}`}</Text> + </Box>, + ) + } + + const summary = [ + activity.xrays > 0 ? `x-ray notes ${activity.xrays}` : '', + activity.testRuns > 0 ? `tests ${share}% of tool time (${activity.testRuns} runs)` : '', + ].filter(part => part !== '') + + const tail: RenderChildren[] = summary.length > 0 ? [<Text dimColor wrap="truncate-end">{clip(` ${summary.join(' · ')}`, width)}</Text>] : [] + const room = Math.max(0, max - rows.length - tail.length) + const agents = fleet.recent.slice(0, Math.min(3, Math.floor(room / 2))) + + for (const row of agents) { + rows.push( + <Text dimColor wrap="truncate-end"> + {clip(` ${row.unit !== undefined ? `${row.unit} ` : ''}${row.lastTool} ${row.lastSubject}`, width)} + </Text>, + ) + } + + for (const call of activity.finished.slice(-Math.max(0, max - rows.length - tail.length))) { + rows.push( + <Box> + <Text color={call.isOk ? 'green' : 'red'}>{call.isOk ? ' ✓ ' : ' ✗ '}</Text> + <Text dimColor wrap="truncate-end">{clip(`${call.tool} ${call.subject}${call.note !== undefined ? ` · ${call.note}` : ''}`, width - 4)}</Text> + </Box>, + ) + } + + return ( + <Box flexDirection="column"> + {rule(kit, 'Session', width, status)} + {[...rows.slice(0, Math.max(0, max - tail.length)), ...tail]} + </Box> + ) +} + +function attention(kit: Kit, state: State, snapshot: Snapshot, width: number, max: number): RenderChildren { + const { Box, Text } = kit + const shared = tallyOf(state.fleet, 0).shared.map(signature => lineOf(signature, 'short')) + + const lines = [...shared, ...snapshot.attention] + + if (lines.length === 0) { + return null + } + + return ( + <Box flexDirection="column"> + {rule(kit, 'Attention', width, String(lines.length))} + {lines.slice(0, max).map(line => ( + <Text color="yellow" wrap="truncate-end">{clip(` ! ${line}`, width)}</Text> + ))} + {lines.length > max ? <Text dimColor>{` … ${lines.length - max} more`}</Text> : null} + </Box> + ) +} + +function nextBlock( + kit: Kit, + snapshot: Snapshot, + actions: PaneActions, + state: State, + width: number, + hasHint: boolean, +): RenderChildren { + const { Box, Text, Button } = kit + const next = snapshot.next + const hasRules = (snapshot.rules?.rules.length ?? 0) > 0 + + return ( + <Box flexDirection="column"> + {rule(kit, 'Next', width)} + {next !== null ? ( + <Box flexDirection="column" paddingLeft={2}> + <Text color={next.isByHand ? undefined : 'cyan'} bold={!next.isByHand} wrap="truncate-end"> + {`${next.text}${next.isByHand ? ' (by hand)' : ''}`} + </Text> + <Text dimColor wrap="truncate-end">{next.reason}</Text> + </Box> + ) : ( + <Text dimColor>{' nothing to suggest'}</Text> + )} + <Box marginTop={1} flexWrap="wrap" columnGap={1}> + {next !== null && !next.isByHand ? ( + <Button key="next" onPress={actions.next}>next</Button> + ) : null} + {hasRules ? <Button key="review" onPress={actions.review}>review rules</Button> : null} + {state.activity.isWorking && state.fleet.seen > 0 ? ( + <Button key="stop" onPress={actions.stop}>stop the run</Button> + ) : null} + <Button key="refresh" dimColor onPress={actions.refresh}>refresh</Button> + </Box> + {hasHint ? <Text dimColor>{'click, or ctrl+x tab then tab and enter'}</Text> : null} + </Box> + ) +} + +/** How the pane's rows are shared out, so the whole of it shows without scrolling. */ +export type PanePlan = { + estate: number + phases: number + modules: number + attention: number + session: number + /** Blank rows between blocks. */ + gap: 0 | 1 + /** Whether the dim hint under the buttons is drawn. */ + hasHint: boolean +} + +/** + * Shares `rows` body rows between the blocks. Fixed costs first (header, + * legend, the Next block, each list's title), then the lists at their + * minimum, then what is left goes to the map and the phase list. + */ +export function planOf( + rows: number, + placement: 'dock' | 'inline', + counts: { phases: number; modules: number; attention: number; hasMap: boolean; headerRows: number }, +): PanePlan { + if (placement === 'inline') { + return { + estate: counts.hasMap ? Math.max(4, Math.min(6, rows - 6 - counts.headerRows)) : 0, + phases: 0, + modules: Math.min(1, counts.modules), + attention: Math.min(1, counts.attention), + session: 1, + gap: 0, + hasHint: false, + } + } + + const gap: 0 | 1 = rows >= 52 ? 1 : 0 + const hasHint = rows >= 44 + const attention = Math.min(counts.attention, rows >= 40 ? 3 : 2) + const modules = Math.min(counts.modules, rows >= 48 ? 3 : rows >= 38 ? 2 : 1) + const sessionMin = rows >= 40 ? 4 : 3 + + // header · legend 1 · next: title, command, reason, blank, buttons (+hint) + const fixed = + counts.headerRows + + (counts.hasMap ? 1 : 0) + + (5 + (hasHint ? 1 : 0)) + + (attention > 0 ? 1 + attention : 0) + + (modules > 0 ? 1 + modules : 0) + + (1 + sessionMin) + + (counts.phases > 0 ? 1 : 0) + + const blocks = 3 + (counts.hasMap ? 1 : 0) + (attention > 0 ? 1 : 0) + (modules > 0 ? 1 : 0) + (counts.phases > 0 ? 1 : 0) + const spare = Math.max(0, rows - fixed - gap * (blocks - 1)) + const phases = counts.phases > 0 ? Math.max(1, Math.min(counts.phases, Math.floor(spare * 0.3))) : 0 + const estate = counts.hasMap ? Math.max(4, Math.min(16, spare - phases - (counts.phases > phases ? 1 : 0))) : 0 + const left = Math.max(0, spare - phases - estate - (counts.phases > phases ? 1 : 0)) + + const plan: PanePlan = { estate, phases, modules, attention, session: sessionMin + Math.min(4, left), gap, hasHint } + + // A body too short for even the minimums sheds rows in the order they matter least. + const totalOf = (p: PanePlan) => + counts.headerRows + + (p.estate > 0 ? p.estate + 1 : 0) + + (p.phases > 0 ? 1 + p.phases + (counts.phases > p.phases ? 1 : 0) : 0) + + (p.modules > 0 ? 1 + p.modules + (counts.modules > p.modules ? 1 : 0) : 0) + + (5 + (p.hasHint ? 1 : 0)) + + (p.attention > 0 ? 1 + p.attention + (counts.attention > p.attention ? 1 : 0) : 0) + + (1 + p.session) + + const shed: (() => boolean)[] = [ + () => (plan.hasHint ? ((plan.hasHint = false), true) : false), + () => (plan.estate > 4 ? ((plan.estate -= 1), true) : false), + () => (plan.phases > 1 ? ((plan.phases -= 1), true) : false), + () => (plan.session > 2 ? ((plan.session -= 1), true) : false), + () => (plan.attention > 1 ? ((plan.attention -= 1), true) : false), + () => (plan.modules > 0 ? ((plan.modules = 0), true) : false), + () => (plan.phases > 0 ? ((plan.phases = 0), true) : false), + () => (plan.estate > 0 ? ((plan.estate = 0), true) : false), + () => (plan.attention > 0 ? ((plan.attention = 0), true) : false), + () => (plan.session > 1 ? ((plan.session -= 1), true) : false), + ] + + for (let guard = 0; guard < 80 && totalOf(plan) > rows; guard += 1) { + if (!shed.some(step => step())) { + break + } + } + + return plan +} + +/** The pane's body. */ +export function paneView( + kit: Kit, + state: State, + frame: PaneFrame, + actions: PaneActions, +): RenderElement { + const { Box, Text } = kit + const width = Math.max(20, frame.columns) + const snapshot = state.snapshot + + if (snapshot === null) { + return ( + <Box flexDirection="column" paddingRight={1}> + <Text bold>modernization</Text> + <Text dimColor wrap="wrap"> + {state.readError !== null + ? `could not read the workspace: ${state.readError}` + : 'no system found under legacy/ or analysis/ yet. Put the system under legacy/<name>/ and run the preflight command to begin.'} + </Text> + </Box> + ) + } + + const plan = frame.plan + + return ( + <Box flexDirection="column" paddingRight={1} rowGap={plan.gap}> + {header(kit, snapshot, width, actions)} + {estate(kit, snapshot, frame, width)} + {plan.phases > 0 ? phases(kit, snapshot, width, plan.phases) : null} + {plan.modules > 0 ? modules(kit, snapshot, width, plan.modules) : null} + {nextBlock(kit, snapshot, actions, state, width, plan.hasHint)} + {plan.attention > 0 ? attention(kit, state, snapshot, width, plan.attention) : null} + {session(kit, state, frame, width, plan.session)} + </Box> + ) +} + +/** + * The one row that stands where the pane was while it is hidden: what the workspace says in a line, and the + * button that brings the pane back. It is drawn in the band above the prompt, which the person can collapse. + */ +export function showBar( + kit: Pick<Kit, 'Box' | 'Text' | 'Button'>, + line: string, + width: number, + onShow: () => void, +): RenderElement { + const { Box, Text, Button } = kit + + return ( + // The band draws its own `[-]` collapse control at its right edge: leave it room. + <Box justifyContent="space-between" paddingRight={5}> + <Text dimColor wrap="truncate-end">{clip(line, Math.max(8, width - 24))}</Text> + <Button key="show-pane" hotkey="m" onPress={onShow}>show pane</Button> + </Box> + ) +} diff --git a/plugins/code-modernization/hooks/xray/xray.ts b/plugins/code-modernization/hooks/xray/xray.ts new file mode 100644 index 00000000..93c6bd74 --- /dev/null +++ b/plugins/code-modernization/hooks/xray/xray.ts @@ -0,0 +1,263 @@ +import { baseName } from '../paths' +import { unitOfPath } from '../reader/estate-model' +import type { Snapshot } from '../reader/progress' +import type { Rule } from '../reader/rules' +import { stateWord } from '../map/estate' +import { baselineKeyOf } from '../reader/uplift' +import { nodeOfFile, type TopoNode, type Topology } from '../reader/topology' + +/** + * X-ray reads: when the model reads a legacy file, what the analysis stages + * already worked out about that file rides along as context the model reads + * and the person never sees. Every line is lifted from an artifact on disk. + */ + +export type XrayRequest = { + /** The file read, relative to `legacy/<system>/`. */ + fileRel: string + /** First line read (1-based) and how many, when the read was a window. */ + offset?: number + limit?: number +} + +export type XrayNote = { + text: string + /** One short line for the status bar. */ + summary: string + rules: number + node: string | null +} + +/** Keeps a note well inside the 32,000-character cap a call's context has. */ +const MAX_CHARS = 2400 +const MAX_RULES = 9 +const MAX_NAMES = 8 + +const some = (names: string[], max = MAX_NAMES): string => + names.length <= max ? names.join(', ') : `${names.slice(0, max).join(', ')} +${names.length - max} more` + +const nameOf = (topo: Topology, id: string): string => topo.byId.get(id)?.name ?? id + +function edgesOf(topo: Topology, node: TopoNode) { + const incoming = topo.edges.filter(edge => edge.target === node.id) + const outgoing = topo.edges.filter(edge => edge.source === node.id) + const isCode = (kind: string) => kind === 'call' || kind === 'dispatch' || kind === 'uses' + const uniq = (ids: string[]) => [...new Set(ids)].map(id => nameOf(topo, id)) + + return { + callers: uniq(incoming.filter(edge => isCode(edge.kind)).map(edge => edge.source)), + callees: uniq(outgoing.filter(edge => isCode(edge.kind)).map(edge => edge.target)), + reads: uniq(outgoing.filter(edge => edge.kind === 'read').map(edge => edge.target)), + writes: uniq(outgoing.filter(edge => edge.kind === 'write').map(edge => edge.target)), + } +} + +const rank = (rule: Rule): number => + (rule.priority === 'P0' ? 0 : rule.priority === 'P1' ? 1 : 2) * 2 + (rule.defect !== undefined ? 0 : 1) + +function ruleLine(rule: Rule, base: string): string { + const spans = rule.citations + .filter(citation => citation.base === base) + .slice(0, 2) + .map(citation => (citation.from === citation.to ? `L${citation.from}` : `L${citation.from}-${citation.to}`)) + + const flags = [ + rule.defect !== undefined ? 'suspected defect' : '', + rule.sme !== undefined ? 'needs SME' : '', + rule.confidence !== undefined && rule.confidence !== 'High' ? `${rule.confidence} confidence` : '', + ].filter(flag => flag !== '') + + const label = rule.id.startsWith('R-') ? rule.priority || 'rule' : rule.id + + return `- ${label} ${rule.title}${spans.length > 0 ? ` (${spans.join(', ')})` : ''}${flags.length > 0 ? ` [${flags.join('; ')}]` : ''}` +} + +/** + * What an uplift already knows about a file: which module it is in, what that module's baseline was on the + * source runtime (the failures there are part of the oracle), where the module stands in the working copy, and + * which deltas the catalog cites the file under. + */ +function upliftXray(snapshot: Snapshot, request: XrayRequest): XrayNote | null { + const estate = snapshot.estate + const unit = estate !== null ? unitOfPath(estate, null, request.fileRel) : null + const deltas = snapshot.uplift?.catalog?.byFileBase.get(baseName(request.fileRel).toLowerCase()) ?? [] + const row = unit?.dir !== undefined ? (snapshot.uplift?.baseline?.rows.get(baselineKeyOf(unit.dir)) ?? null) : null + const module = unit !== null ? snapshot.byNode.get(unit.id) : undefined + + if (deltas.length === 0 && row === null && module === undefined) { + return null + } + + const lines = [ + `[x-ray for ${request.fileRel}${unit !== null ? ` · ${unit.dir === '' || unit.dir === undefined ? unit.name : unit.dir}` : ''} · uplift] (from analysis/${snapshot.system}/; facts already established, do not re-derive)`, + ] + + if (row !== null) { + lines.push( + `Baseline on the source runtime: ${row.pass} pass, ${row.fail} fail, ${row.error} error, ${row.skip} skip. What fails there is part of the oracle: reproduce it, do not fix it.`, + ) + } + + if (module !== undefined) { + const tests = module.tests + + lines.push( + `In the working copy: ${stateWord('uplift', module.state)}${tests !== null ? ` (${tests.tests} tests, ${tests.failures + tests.errors} failing)` : ''}.`, + ) + } + + if (deltas.length > 0) { + lines.push(`The delta catalog cites this file under ${some(deltas, 6)}.`) + } + + return { + text: lines.join('\n'), + summary: `x-ray ${baseName(request.fileRel)}: ${deltas.length} delta${deltas.length === 1 ? '' : 's'}${row !== null ? ', baseline' : ''}`, + rules: 0, + node: unit?.id ?? null, + } +} + +/** Builds the note for one read; null when the artifacts know nothing about the file. */ +export function xrayOf(snapshot: Snapshot, request: XrayRequest): XrayNote | null { + if (snapshot.track === 'uplift') { + return upliftXray(snapshot, request) + } + + const base = baseName(request.fileRel).toLowerCase() + const topo = snapshot.topology + const node = topo !== null ? nodeOfFile(topo, request.fileRel) : null + const cited = snapshot.rules?.byFileBase.get(base) ?? [] + + if (node === null && cited.length === 0) { + return null + } + + const lines: string[] = [] + const head = [`x-ray for ${request.fileRel}`] + + if (node !== null) { + head.push(node.name) + + if (node.domain !== undefined) { + head.push(node.domain) + } + + if (node.loc > 0) { + head.push(`${node.loc} lines`) + } + } + + lines.push(`[${head.join(' · ')}] (from analysis/${snapshot.system}/; facts already established, do not re-derive)`) + + if (topo !== null && node !== null) { + const edges = edgesOf(topo, node) + const roles: string[] = [] + + if (topo.entryPoints.has(node.id)) { + roles.push('an entry point') + } + + if (topo.deadEnds.has(node.id)) { + roles.push('flagged as a dead end by the map') + } + + if (roles.length > 0) { + lines.push(`Role: ${roles.join(', ')}.`) + } + + if (edges.callers.length > 0) { + lines.push(`Reached from: ${some(edges.callers)}.`) + } else if (!topo.entryPoints.has(node.id) && node.kind === 'module') { + lines.push('Reached from: nothing the map found (check dynamic dispatch before calling it dead).') + } + + if (edges.callees.length > 0) { + lines.push(`Calls: ${some(edges.callees)}.`) + } + + if (edges.reads.length > 0) { + lines.push(`Reads: ${some(edges.reads)}.`) + } + + if (edges.writes.length > 0) { + lines.push(`Writes: ${some(edges.writes)}.`) + } + + const flows = topo.flows.filter(flow => flow.steps.some(step => step.nodes.includes(node.id))) + + if (flows.length > 0) { + lines.push(`Business flows through it: ${some(flows.map(flow => `"${flow.name}"`), 4)}.`) + } + } + + if (cited.length > 0) { + const p0 = cited.filter(rule => rule.priority === 'P0').length + const from = request.offset + const to = from !== undefined && request.limit !== undefined ? from + request.limit - 1 : undefined + + const inWindow = + from !== undefined && to !== undefined + ? cited.filter(rule => + rule.citations.some( + citation => citation.base === base && citation.from <= to && citation.to >= from, + ), + ) + : [] + + const shown = (inWindow.length > 0 ? inWindow : [...cited]).sort((a, b) => rank(a) - rank(b)).slice(0, MAX_RULES) + + lines.push( + `Business rules citing this file: ${cited.length}${p0 > 0 ? ` (${p0} P0)` : ''}, in analysis/${snapshot.system}/BUSINESS_RULES.md.${inWindow.length > 0 ? ` In the lines just read (${from}-${to}):` : ' Highest priority first:'}`, + ) + + for (const rule of shown) { + lines.push(ruleLine(rule, base)) + } + + const rest = (inWindow.length > 0 ? inWindow.length : cited.length) - shown.length + + if (rest > 0) { + lines.push(`- and ${rest} more.`) + } + + const verdicts = cited + .map(rule => ({ rule, review: snapshot.reviews[rule.id] })) + .filter(entry => entry.review !== undefined && entry.review.verdict !== 'confirmed') + + if (verdicts.length > 0) { + lines.push( + `A reviewer disputed: ${some(verdicts.map(entry => `${entry.rule.id} (${entry.review?.verdict})`), 6)}. Do not treat those as settled.`, + ) + } + } + + const unitId = node?.id ?? (snapshot.estate !== null ? unitOfPath(snapshot.estate, topo, request.fileRel)?.id : undefined) + + if (unitId !== undefined) { + const module = snapshot.byNode.get(unitId) + + if (module !== undefined) { + const tests = module.tests + + lines.push( + `Already transformed at ${module.path}: ${module.state.replace('-', ' ')}${tests !== null ? `, ${tests.tests - tests.failures - tests.errors}/${tests.tests} tests passing` : ''}.`, + ) + } + } + + let text = lines.join('\n') + + if (text.length > MAX_CHARS) { + text = `${text.slice(0, MAX_CHARS - 40).replace(/\n[^\n]*$/, '')}\n- (note trimmed)` + } + + const callers = topo !== null && node !== null ? edgesOf(topo, node).callers.length : 0 + + return { + text, + summary: `x-ray ${node?.name ?? baseName(request.fileRel)}: ${cited.length} rule${cited.length === 1 ? '' : 's'}${callers > 0 ? `, ${callers} caller${callers === 1 ? '' : 's'}` : ''}`, + rules: cited.length, + node: node?.id ?? null, + } +} |
