diff options
| author | Morgan Lunt <morganl@anthropic.com> | 2026-09-24 20:52:27 -0700 |
|---|---|---|
| committer | Morgan Lunt <morganl@anthropic.com> | 2026-09-24 20:52:27 -0700 |
| commit | 51b1ae9e20486d62b839ed9f37e1cfc7d55bf85c (patch) | |
| tree | eb31cc4964d84b4a82b8032452739fe1e9b37d3f /plugins/code-modernization/hooks | |
| parent | 5b8ec4b30f45b5e8b4c8a6efd63719730cf1a5ad (diff) | |
code-modernization: make the live pane work below 144 columns and show the proof
Found by exercising the pane against the real outputs of finished runs:
- Below 144 columns the engine holds an unasked pane back; the pane ignored
that, so it drew no pane, no show bar, and the panel command "hid" a pane
that was never there.
- A symlinked legacy/<name> lists as another kind of entry, so the source
link that preflight now creates was never recognized as a system.
- Uplift and reimagine next steps were placeholders with no button.
- The refresh debounce was starved while agents ran, so the map froze.
- Hostile lines in the brief, rules and baseline could take seconds to match;
lines are now capped. The rule-review ledger is validated on read and
merged on save, and keeps a reviewer's note.
- A baseline with no row read as "the baseline had 0"; one-module baseline
totals now count as that module's row.
New: a verdict chip with words on every built module, a verify-first next
step, and a readable palette that follows the terminal theme. 140 engine
tests pass and the type check is clean.
Diffstat (limited to 'plugins/code-modernization/hooks')
19 files changed, 956 insertions, 234 deletions
diff --git a/plugins/code-modernization/hooks/host.ts b/plugins/code-modernization/hooks/host.ts index c315fecf..9190a4cc 100644 --- a/plugins/code-modernization/hooks/host.ts +++ b/plugins/code-modernization/hooks/host.ts @@ -12,6 +12,12 @@ import type { import type { ReaderFs } from './reader/fs' /** + * What `$.ui.open` answers: drawn, or open but held back undrawn (unasked, on a terminal narrower than the engine docks a + * pane on) with the reason. A build that answers nothing has drawn it, as far as anyone can tell. + */ +export type OpenResult = { isPlaced: boolean; reason?: string } | void + +/** * 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. @@ -28,7 +34,7 @@ export type Host = { status: (text: string | undefined) => void toast: (text: string, timeoutMs?: number) => void log: (text: string) => void - openPane: (pane: PaneOpenArgs) => Promise<void> + openPane: (pane: PaneOpenArgs) => Promise<OpenResult> closePane: (pane: PaneCloseArgs) => Promise<void> registerCommand: (spec: CommandSpec) => Promise<unknown> fillPrompt: (input: PromptFillArgs) => Promise<{ isFilled: boolean }> diff --git a/plugins/code-modernization/hooks/map/estate.ts b/plugins/code-modernization/hooks/map/estate.ts index b3bd3d3a..c57f19a2 100644 --- a/plugins/code-modernization/hooks/map/estate.ts +++ b/plugins/code-modernization/hooks/map/estate.ts @@ -1,4 +1,4 @@ -import { estateOfTopology, type EstateUnit } from '../reader/estate-model' +import { estateOfTopology, languageOf, 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' @@ -17,12 +17,21 @@ export type Touch = { atMs: number; kind: TouchKind } export type TileState = ModuleState | 'untouched' +/** A module's verdict, as the map marks it: a tile's label starts with the mark. */ +export type TileProof = 'proven' | 'partly' | 'not' + +export const PROOF_MARKS: Record<TileProof, string> = { proven: '✓', partly: '±', not: '✗' } + export type Tile = { id: string name: string + /** What the tile shows of its name: the last path segment, without its extension and without the prefix most tiles share. */ + label: string domain: string loc: number state: TileState + /** What the proof says of the module, once the verify command has checked it. */ + proof?: TileProof rect: Rect isNext: boolean } @@ -40,11 +49,16 @@ export type Estate = { /** How long a touch stays visible, in milliseconds. */ export const FLASH_MS = 4000 +/** + * Mid-tones on purpose: a tile has to show against a dark terminal and a light one, and the map cannot ask which it is. + * The labels are drawn in whichever of light or dark ink reads on the tile. + */ export const STATE_COLORS: Record<TileState, number> = { - untouched: 0x39414f, - scaffolded: 0x4b5d80, + untouched: 0x5b6577, + scaffolded: 0x4a6cb0, 'tests-written': 0x94741f, 'tests-red': 0xb23b3b, + 'tests-failing': 0xc2683a, 'tests-green': 0x2c7a4c, reviewed: 0x2fa568, ported: 0x2b8ea6, @@ -78,6 +92,54 @@ function nextModuleOf(snapshot: Snapshot): string | null { return snapshot.next?.isByHand === false ? (match?.[1] ?? null) : null } +/** + * Short names for tiles, which show a few letters: a path is cut to its last segment, a source file's extension goes, and + * the prefix most of the units share (`jetty-` in `jetty-server`, `jetty-client`) goes too, so the letters that tell + * one tile from the next are the ones drawn. + */ +export function labelsOf(names: readonly string[]): string[] { + const stems = names.map(name => { + const last = name.includes('/') ? (name.split('/').filter(part => part !== '').at(-1) ?? name) : name + + return languageOf(last) !== undefined ? last.replace(/\.[^.]+$/, '') : last + }) + + const counts = new Map<string, number>() + + for (const stem of stems) { + const head = /^[^-_.\s]{2,}[-_.]/.exec(stem)?.[0] + + if (head !== undefined) { + counts.set(head, (counts.get(head) ?? 0) + 1) + } + } + + const [top, count] = [...counts.entries()].sort((a, b) => b[1] - a[1])[0] ?? ['', 0] + const isShared = top !== '' && count >= 4 && count >= names.length * 0.4 + + return stems.map(stem => (isShared && stem.startsWith(top) && stem.length > top.length ? stem.slice(top.length) : stem)) +} + +/** The tile's proof, when its module has a fresh verdict; nothing for a module nobody has checked or that changed since. */ +function proofMarkOf(snapshot: Snapshot, unitId: string): { proof: TileProof } | Record<string, never> { + const module = snapshot.byNode.get(unitId) + + if (module === undefined || snapshot.track === 'uplift') { + return {} + } + + const state = snapshot.proofs.get(module.dir.toLowerCase())?.state + + return state === 'proven' || state === 'partly' || state === 'not' ? { proof: state } : {} +} + +/** How many tiles carry each proof, in the order a legend draws them. */ +export function proofCountsOf(tiles: readonly Tile[]): { kind: TileProof; count: number }[] { + return (['proven', 'partly', 'not'] as const) + .map(kind => ({ kind, count: tiles.filter(tile => tile.proof === kind).length })) + .filter(entry => entry.count > 0) +} + /** 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) @@ -88,6 +150,8 @@ export function tilesOf(snapshot: Snapshot, columns: number, rows: number): Tile const next = nextModuleOf(snapshot) const groups = new Map<string, EstateUnit[]>() + const short = labelsOf(estate.units.map(unit => unit.name)) + const labels = new Map(estate.units.map((unit, index) => [unit.id, short[index] ?? unit.name] as const)) for (const unit of estate.units) { const members = groups.get(unit.group) ?? [] @@ -110,9 +174,11 @@ export function tilesOf(snapshot: Snapshot, columns: number, rows: number): Tile .map(entry => ({ id: entry.item.id, name: entry.item.name, + label: labels.get(entry.item.id) ?? entry.item.name, domain: group.name, loc: entry.item.size, state: snapshot.byNode.get(entry.item.id)?.state ?? ('untouched' as const), + ...proofMarkOf(snapshot, entry.item.id), rect: entry.rect, isNext: entry.item.id === next, })), @@ -146,7 +212,7 @@ export function paint( 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 label = w >= 5 && tile.proof !== undefined ? `${tile.isNext ? '▸' : ''}${PROOF_MARKS[tile.proof]}${tile.label}` : w >= 4 ? (tile.isNext ? '▸' : '') + tile.label : w >= 2 && tile.isNext ? '▸' : '' const shown = label.slice(0, Math.max(0, w - (hasBevel ? 1 : 0))) for (let row = 0; row < h; row += 1) { @@ -176,6 +242,7 @@ export function countsOf(tiles: readonly Tile[]): { state: TileState; count: num 'scaffolded', 'tests-written', 'tests-red', + 'tests-failing', 'tests-green', 'reviewed', 'ported', diff --git a/plugins/code-modernization/hooks/reader/brief.ts b/plugins/code-modernization/hooks/reader/brief.ts index 890aa58a..8ced2934 100644 --- a/plugins/code-modernization/hooks/reader/brief.ts +++ b/plugins/code-modernization/hooks/reader/brief.ts @@ -1,3 +1,5 @@ +import { linesOf } from '../text' + /** * `analysis/<system>/MODERNIZATION_BRIEF.md`, read without a model: the * target stack, the phases, which modules each phase names, the exit @@ -67,11 +69,15 @@ export function criterionTextOf(line: string): string | null { * its text mentions as whole words */ export function parseBrief(text: string, knownModules: readonly string[] = []): Brief { - const lines = text.split('\n') + const lines = linesOf(text) 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 + // The title may hold the arrow inside a parenthesis: `(COBOL/CICS → Java/Spring)`. The close is not part of the target. + const fromTitle = arrow?.[1] !== undefined ? strip(arrow[1]).replace(/\)$/, m => (arrow[1]?.includes('(') === true ? m : '')) : undefined + // The header's own `**Target stack:** `java-spring`` is the token the commands take: it wins when it is one plain token. + const stackToken = /\*\*Target stack:?\*\*:?\s*`([A-Za-z0-9][\w.+/-]{0,59})`/i.exec(text)?.[1] + const target = stackToken ?? fromTitle const phases: Phase[] = [] let current: { phase: Phase; body: string[]; level: number } | null = null diff --git a/plugins/code-modernization/hooks/reader/fs.ts b/plugins/code-modernization/hooks/reader/fs.ts index 44b570ed..1d8e9f6d 100644 --- a/plugins/code-modernization/hooks/reader/fs.ts +++ b/plugins/code-modernization/hooks/reader/fs.ts @@ -5,7 +5,8 @@ */ export type ReaderFs = { read: (path: string) => Promise<string> - list: (path: string) => Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number }[]> + /** An entry as it stands: a symbolic link is `other` (with `isLink`), whatever it leads to. `stat` says what that is. */ + list: (path: string) => Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number; isLink?: boolean }[]> exists: (path: string) => Promise<boolean> stat: (path: string) => Promise<{ kind: 'file' | 'dir' | 'other'; size: number; mtimeMs: number }> } @@ -28,7 +29,7 @@ export async function readOrNull(fs: ReaderFs, path: string): Promise<string | n export async function listOrEmpty( fs: ReaderFs, path: string, -): Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number }[]> { +): Promise<{ name: string; kind: 'file' | 'dir' | 'other'; size: number; isLink?: boolean }[]> { try { if (!(await fs.exists(path))) { return [] @@ -52,3 +53,27 @@ export async function mtimeOrNull(fs: ReaderFs, path: string): Promise<number | return null } } + +/** + * The directories under `path`, by name. A symbolic link to a directory counts: the engine lists a link as `other`, + * and a legacy tree is often a link to where the code really lives. + */ +export async function dirNamesOf(fs: ReaderFs, path: string): Promise<string[]> { + const names: string[] = [] + + for (const entry of await listOrEmpty(fs, path)) { + if (entry.kind === 'dir') { + names.push(entry.name) + } else if (entry.kind === 'other') { + try { + if ((await fs.stat(`${path}/${entry.name}`)).kind === 'dir') { + names.push(entry.name) + } + } catch { + // a link that leads nowhere is not a system + } + } + } + + return names +} diff --git a/plugins/code-modernization/hooks/reader/modernized.ts b/plugins/code-modernization/hooks/reader/modernized.ts index 600e1d39..d60b8f66 100644 --- a/plugins/code-modernization/hooks/reader/modernized.ts +++ b/plugins/code-modernization/hooks/reader/modernized.ts @@ -1,4 +1,5 @@ import { join } from '../paths' +import { linesOf } from '../text' import { listOrEmpty, readOrNull, type ReaderFs } from './fs' /** @@ -20,6 +21,8 @@ export type ModuleState = | 'scaffolded' | 'tests-written' | 'tests-red' + /** An uplift's tests fail and there is no baseline row to say whether the source runtime failed them too. */ + | 'tests-failing' | 'tests-green' | 'reviewed' | 'ported' @@ -138,9 +141,23 @@ const REPORT_DIRS = [ 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')) +/** When a file last changed; 0 when it cannot be said. */ +async function changedAt(fs: ReaderFs, path: string): Promise<number> { + try { + return (await fs.stat(path)).mtimeMs + } catch { + return 0 + } +} + +/** + * The test totals a directory's report files hold: a custom JSON report, JUnit XML, or a `.trx`, and when the newest of + * the files read last changed (what a verdict about the module is compared with). + */ +export async function readTestsAt(fs: ReaderFs, dir: string, withTime = true): Promise<{ totals: TestTotals; atMs: number } | null> { + const stamp = (path: string) => (withTime ? changedAt(fs, path) : Promise.resolve(0)) + const customPath = join(dir, '.modernize/test-report.json') + const custom = await readOrNull(fs, customPath) if (custom !== null) { try { @@ -148,11 +165,14 @@ export async function readTests(fs: ReaderFs, dir: string): Promise<TestTotals | 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, + totals: { + tests: num('tests'), + failures: num('failures'), + errors: num('errors'), + skipped: num('skipped'), + reports: 1, + }, + atMs: await stamp(customPath), } } catch { // fall through to the XML reports @@ -160,6 +180,7 @@ export async function readTests(fs: ReaderFs, dir: string): Promise<TestTotals | } let total: TestTotals | null = null + let atMs = 0 for (const sub of REPORT_DIRS) { const entries = await listOrEmpty(fs, join(dir, sub)) @@ -176,11 +197,12 @@ export async function readTests(fs: ReaderFs, dir: string): Promise<TestTotals | if (totals !== null) { total = total === null ? totals : add(total, totals) + atMs = Math.max(atMs, await stamp(join(dir, sub, entry.name))) } } if (total !== null) { - return total + return { totals: total, atMs } } } @@ -189,13 +211,18 @@ export async function readTests(fs: ReaderFs, dir: string): Promise<TestTotals | const totals = xml !== null ? totalsOfJunitXml(xml) : null if (totals !== null) { - return totals + return { totals, atMs: await stamp(join(dir, name)) } } } return null } +/** The test totals a directory's report files hold, without asking when each file changed. */ +export async function readTests(fs: ReaderFs, dir: string): Promise<TestTotals | null> { + return (await readTestsAt(fs, dir, false))?.totals ?? null +} + const TEST_DIRS = ['src/test', 'tests', 'test', 'spec', '__tests__'] const MAIN_DIRS = ['src/main', 'src', 'app', 'lib'] @@ -217,7 +244,7 @@ export function readNotes(notes: string): { isSwitched: boolean followUps: number } { - const lines = notes.split('\n') + const lines = linesOf(notes) // 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)) @@ -311,9 +338,13 @@ export function stateOfUplift( ): 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) { + // With no baseline row there is nothing to be worse than: the failures are said, not judged. + if (baseline === null && bad > 0) { + return 'tests-failing' + } + + if (baseline !== null && bad > baseline.fail + baseline.error) { return 'tests-red' } @@ -351,16 +382,10 @@ export async function readModernizedIn( 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 reported = await readTestsAt(fs, path) + const tests = reported?.totals ?? observed.get(path) ?? null + // The newest of the notes and the test reports: what a verdict about the module is checked against. + const mtimeMs = Math.max(notes !== null ? await changedAt(fs, join(path, 'TRANSFORMATION_NOTES.md')) : 0, reported?.atMs ?? 0) const facts = { dir: entry.name, diff --git a/plugins/code-modernization/hooks/reader/progress.ts b/plugins/code-modernization/hooks/reader/progress.ts index ee795978..be1901a8 100644 --- a/plugins/code-modernization/hooks/reader/progress.ts +++ b/plugins/code-modernization/hooks/reader/progress.ts @@ -3,12 +3,15 @@ import { isSystemName, isToken, plain } from '../text' 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 { dirNamesOf, 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 { parseVerification, proofOfModule, type ProofState, type Verification } from './verification' +import { parseLedger } from '../review/ledger' import { + baselineRowOf, changedUnitsOf, parseBaseline, parseCatalog, @@ -36,6 +39,7 @@ export type StageKey = | 'baseline' | 'pilot' | 'migrate' + | 'compare' | 'verify' | 'spec' | 'design' @@ -55,7 +59,7 @@ export type ReviewVerdict = 'confirmed' | 'wrong' | 'discuss' export type ReviewLedger = Record< string, - { verdict: ReviewVerdict; at: string; title?: string; note?: string } + { verdict: ReviewVerdict; at: string; title?: string; /** The reviewer's own words, when they gave any. */ note?: string } > export type NextStep = { @@ -63,6 +67,8 @@ export type NextStep = { text: string isByHand: boolean reason: string + /** A step the pane can do itself: `sign` opens the sign-off dialog. */ + action?: 'sign' } /** What an uplift has left on disk, beyond the modules it changed. */ @@ -97,6 +103,13 @@ export type Snapshot = { extras: ModernizedModule[] uplift: UpliftFacts | null findings: { exists: boolean; isScan: boolean } + /** The proof pack's verdicts, when the verify command has run. */ + verification: Verification | null + /** + * Where each built module stands with the proof, by its folder name lower-cased. An uplift is one piece, so it has one + * entry, under the name of its working copy (`<system>-uplifted`). + */ + proofs: Map<string, ProofState> 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 @@ -118,6 +131,7 @@ export const STAGE_LABELS: Record<StageKey, string> = { baseline: 'baseline', pilot: 'pilot', migrate: 'migrate', + compare: 'compare', verify: 'verify', spec: 'spec', design: 'design', @@ -133,6 +147,7 @@ const STAGE_FILES = { brief: 'MODERNIZATION_BRIEF.md', transform: 'TRANSFORMATION_NOTES.md', harden: 'SECURITY_FINDINGS.md', + verify: 'VERIFICATION.json', deltas: 'DELTA_CATALOG.md', baseline: 'BASELINE.md', pilot: 'PLAYBOOK.md', @@ -183,10 +198,10 @@ export async function systemsOf(fs: ReaderFs, legacyDir = 'legacy'): Promise<str const names = new Set<string>() for (const root of ['analysis', legacyDir]) { - for (const entry of await listOrEmpty(fs, root)) { + for (const name of await dirNamesOf(fs, root)) { // The names the plugin's workflows accept: anything else could not be run on, and is not put in a command or a note. - if (entry.kind === 'dir' && isSystemName(entry.name)) { - names.add(entry.name) + if (isSystemName(name)) { + names.add(name) } } } @@ -223,66 +238,106 @@ export function isUnitDone( } // 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 + const baseline = snapshot.uplift?.baseline + const hasRows = (baseline?.rows.size ?? 0) > 0 || (baseline?.headline ?? null) !== null return module.state === 'reviewed' || (module.state === 'tests-green' && !hasRows) } +/** The command that opens the whole process: the prefix without its verb dash (`/code-modernization:modernize`). */ +export const frontDoorOf = (prefix: string): string => prefix.replace(/-$/, '') + +/** + * The verify step a built module calls for: none yet, changed since it was verified, or failed. A module that is + * proven, or partly proven (which a person decides on), calls for nothing; nor does one with no notes and no verdict. + */ +function verifyStepOf(prefix: string, system: string, module: Pick<ModernizedModule, 'dir'>, proof: ProofState | undefined): NextStep | null { + if (proof === undefined || proof.state === 'proven' || proof.state === 'partly') { + return null + } + + const name = plain(module.dir, 60) + const text = `${prefix}verify ${system}${isToken(module.dir) ? ` ${module.dir}` : ''}` + + if (proof.state === 'none') { + return { text, isByHand: false, reason: `${name} is built, and nothing has checked yet that it behaves like the old code` } + } + + if (proof.state === 'changed') { + return { text, isByHand: false, reason: `${name} changed after it was verified: check it again` } + } + + return { text, isByHand: false, reason: `${name} is NOT PROVEN${proof.reason === '' ? '' : `: ${proof.reason}`}. Fix that, then check again` } +} + function nextOfTransform( prefix: string, system: string, stages: Stage[], brief: Brief | null, byNode: Map<string, ModernizedModule>, + hasAnalysis: boolean, + proofs: ReadonlyMap<string, ProofState>, ): NextStep | null { const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true const cmd = (name: string, rest = '') => `${prefix}${name} ${system}${rest === '' ? '' : ` ${rest}`}` + // Nothing has been written for this system yet: the front door asks what the person wants, once, and gives the first step. + if (!hasAnalysis) { + return { text: `${frontDoorOf(prefix)} ${system}`, isByHand: false, reason: 'start here: it asks what you want done, then gives you the first step' } + } + if (!done('preflight') && !done('assess')) { - return { text: cmd('preflight'), isByHand: false, reason: 'check the environment before analysis' } + return { text: cmd('preflight'), isByHand: false, reason: 'first, check the environment and that all the code is there' } } if (!done('assess')) { - return { text: cmd('assess'), isByHand: false, reason: 'inventory and complexity come first' } + return { text: cmd('assess'), isByHand: false, reason: 'what you have: size, complexity, risks and the recommended approach' } } if (!done('map')) { - return { text: cmd('map'), isByHand: false, reason: 'the brief and the rules both read the topology' } + return { text: cmd('map'), isByHand: false, reason: 'how the parts of the code connect: calls, data and business flows' } } if (!done('rules')) { - return { text: cmd('extract-rules'), isByHand: false, reason: 'the behavior contract comes from the rules' } + return { text: cmd('extract-rules'), isByHand: false, reason: 'what the code does, written as rules a business person can check' } } if (!done('brief') || brief === null) { - return { text: cmd('brief'), isByHand: false, reason: 'discovery is complete; plan the phases' } + return { text: cmd('brief'), isByHand: false, reason: 'the phased plan you approve before anything is built' } } if (!brief.approval.isSigned) { return { - text: 'approve the brief: tell Claude which phases you approve', + text: 'approve the brief', isByHand: true, - reason: 'execution commands treat an unapproved brief as not approved', + action: 'sign', + reason: 'nothing is built until a person approves the plan: sign it here, or tell Claude which phases you approve', } } const target = brief.target !== undefined ? slugOf(brief.target) : '' for (const phase of approvedPhases(brief)) { - const open = phase.modules.find(id => { + // In the order the phase names them: a module that is built and not yet verified is checked before the next one starts. + for (const id of phase.modules) { const module = byNode.get(id) - return module === undefined || !isDone(module) - }) + if (module === undefined || !isDone(module)) { + // A module id is text from the map: it goes in a command only when it is one plain token. + const isNamed = isToken(id) - if (open !== undefined) { - // A module id is text from the map: it goes in a command only when it is one plain token. - const isNamed = isToken(open) + return { + text: cmd('transform', `${isNamed ? id : '<module>'}${target === '' ? '' : ` ${target}`}`), + isByHand: !isNamed, + reason: `Phase ${phase.number} names ${plain(id, 60)} and it is not reviewed yet`, + } + } - return { - text: cmd('transform', `${isNamed ? open : '<module>'}${target === '' ? '' : ` ${target}`}`), - isByHand: !isNamed, - reason: `Phase ${phase.number} names ${plain(open, 60)} and it is not reviewed yet`, + const step = verifyStepOf(prefix, system, module, proofs.get(module.dir.toLowerCase())) + + if (step !== null) { + return step } } @@ -300,52 +355,67 @@ function nextOfTransform( 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', + ? 'every approved phase is built and checked' + : 'Phase 1 is built and checked; 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 { +/** The uplift command takes its two versions from what the person said at the start (`INTENT.md`, the brief), and asks when neither has them. */ +function nextOfUplift(prefix: string, system: string, stages: Stage[], proofs: ReadonlyMap<string, ProofState>): NextStep { const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true - const command = `${prefix}uplift ${system} <from> <to>` + const command = `${prefix}uplift ${system}` if (!done('deltas')) { - return { text: command, isByHand: true, reason: 'the delta catalog comes first: what the target version breaks here' } + return { text: command, isByHand: false, reason: 'first it lists what the newer version breaks in this code' } } if (!done('baseline')) { - return { text: command, isByHand: true, reason: 'record the baseline before any module is migrated: it is the equivalence target' } + return { text: command, isByHand: false, reason: 'next it records the baseline: what the tests do today, so the result can be compared' } } if (!done('pilot')) { - return { text: command, isByHand: true, reason: 'migrate one representative module and write the playbook before the rest' } + return { text: command, isByHand: false, reason: 'next it migrates one module and writes down what it learned, 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' } + if (!done('compare')) { + return { text: command, isByHand: false, reason: 'next it migrates the rest in batches and compares every result with the baseline' } } - return { text: `${prefix}status ${system}`, isByHand: false, reason: 'every uplift artifact is written; status checks what is stale' } + // The whole upgraded copy is one thing to prove, under the name of its working copy. + const step = verifyStepOf(prefix, system, { dir: `${system}-uplifted` }, proofs.get(`${system}-uplifted`)) + + if (step !== null) { + return { ...step, text: `${prefix}verify ${system}` } + } + + return { text: `${prefix}status ${system}`, isByHand: false, reason: 'the upgrade is built and checked; status says what is stale' } } -function nextOfReimagine(prefix: string, system: string, stages: Stage[]): NextStep { +function nextOfReimagine(prefix: string, system: string, stages: Stage[], modules: readonly ModernizedModule[], proofs: ReadonlyMap<string, ProofState>): NextStep { const done = (key: StageKey) => stages.find(stage => stage.key === key)?.isDone === true - const command = `${prefix}reimagine ${system} <vision>` + const command = `${prefix}reimagine ${system}` if (!done('spec')) { - return { text: command, isByHand: true, reason: 'the spec is mined from the legacy code first' } + return { text: command, isByHand: false, reason: 'first it writes down what the old system does, from its code' } } if (!done('design')) { - return { text: command, isByHand: true, reason: 'the target architecture is designed and reviewed against the spec' } + return { text: command, isByHand: false, reason: 'next it designs the new architecture and checks it against that spec' } } if (!done('scaffold')) { - return { text: command, isByHand: true, reason: 'scaffold each service from the approved architecture' } + return { text: command, isByHand: false, reason: 'next it builds each service of the approved design, with tests' } + } + + for (const module of modules) { + const step = verifyStepOf(prefix, system, module, proofs.get(module.dir.toLowerCase())) + + if (step !== null) { + return step + } } - return { text: `${prefix}status ${system}`, isByHand: false, reason: 'the services are scaffolded; status checks what is stale' } + return { text: `${prefix}status ${system}`, isByHand: false, reason: 'the services are built and checked; status says what is stale' } } export type ReadOptions = { @@ -447,11 +517,12 @@ export async function readSnapshot( 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([ + const [topo, rules, catalog, baseline, verificationRead, 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), + cached(fs, cache, join(dir, STAGE_FILES.verify), parseVerification), readOrNull(fs, join(dir, REVIEWS_FILE)), readOrNull(fs, join(dir, STAGE_FILES.harden)), Promise.all( @@ -494,17 +565,7 @@ export async function readSnapshot( } } - let reviews: ReviewLedger = {} - - if (reviewsRaw !== null) { - try { - const parsed = JSON.parse(reviewsRaw) as { reviews?: ReviewLedger } - - reviews = parsed.reviews ?? {} - } catch { - reviews = {} - } - } + const reviews = parseLedger(reviewsRaw) const isScan = findingsHead !== null && /generated-by:\s*modernize-harden/.test(findingsHead.split('\n')[0] ?? '') @@ -583,6 +644,48 @@ export async function readSnapshot( const snapshotFacts = { track, uplift } const done = modules.filter(module => isUnitDone(snapshotFacts, module)) + // Where each built module stands with the proof. An uplift is one piece: the whole working copy has the one verdict. + const verification = verificationRead.value + const proofs = new Map<string, ProofState>() + + if (track === 'uplift') { + const name = `${system}-uplifted` + const proof = proofOfModule(verification, 'uplift', name, upliftNotesAt ?? 0, upliftNotesAt !== null) + + if (proof !== null) { + proofs.set(name.toLowerCase(), proof) + } + } else { + for (const module of modules) { + const proof = proofOfModule(verification, track, module.dir, module.mtimeMs, module.hasNotes) + + if (proof !== null) { + proofs.set(module.dir.toLowerCase(), proof) + } + } + } + + const proofList = [...proofs.values()] + const isProofDone = (proof: ProofState) => proof.state === 'proven' || proof.state === 'partly' + + const verifyStage: Stage[] = + proofList.length === 0 && track !== 'uplift' && modules.length === 0 + ? [] + : [ + { + key: 'verify', + label: STAGE_LABELS.verify, + isDone: proofList.length > 0 && proofList.every(isProofDone), + mtimeMs: null, + ...(proofList.length > 0 && { + detail: + track === 'uplift' + ? (proofList[0]?.verdict ?? 'not verified yet').toLowerCase() + : `${proofList.filter(proof => proof.state === 'proven').length} of ${proofList.length} proven`, + }), + }, + ] + const green = modules.filter( module => module.state === 'tests-green' || module.state === 'reviewed' || isUnitDone(snapshotFacts, module), ) @@ -644,6 +747,7 @@ export async function readSnapshot( detail: green.length === 0 ? 'in progress' : passing > 0 ? `${passing} green` : `${green.length} module${green.length === 1 ? '' : 's'}`, }), }, + ...verifyStage, ] : track === 'uplift' ? [ @@ -677,12 +781,13 @@ export async function readSnapshot( ...(modules.length > 0 && { detail: `${modules.length} module${modules.length === 1 ? '' : 's'}` }), }, { - key: 'verify' as const, - label: STAGE_LABELS.verify, + key: 'compare' as const, + label: STAGE_LABELS.compare, isDone: upliftNotesAt !== null, mtimeMs: upliftNotesAt, ...(modules.length > 0 && { detail: `${done.length}/${modules.length} match` }), }, + ...verifyStage, ] : [ { key: 'preflight' as const, label: STAGE_LABELS.preflight, isDone: preflightAt !== null, mtimeMs: preflightAt }, @@ -702,6 +807,7 @@ export async function readSnapshot( mtimeMs: null, ...(modules.length > 0 && { detail: `${green.length}/${modules.length} green` }), }, + ...verifyStage, ]), ...withFindings, ] @@ -717,14 +823,16 @@ export async function readSnapshot( const attention: string[] = [] for (const module of modules) { - const row = track === 'uplift' ? (baseline.value?.rows.get(module.dir.toLowerCase()) ?? null) : null + const row = track === 'uplift' ? baselineRowOf(baseline.value, module.dir) : null - if (module.state === 'tests-red' && module.tests !== null) { + if ((module.state === 'tests-red' || module.state === 'tests-failing') && 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}` + ? row === null + ? `${module.dir}: ${bad} tests failing, and the baseline has no row for it to compare with` + : `${module.dir}: ${bad} failing, the baseline had ${row.fail + row.error}` : `${module.dir}: ${bad} of ${module.tests.tests} tests red`, ) } @@ -738,6 +846,12 @@ export async function readSnapshot( } } + for (const [name, proof] of proofs) { + if (proof.state === 'not') { + attention.push(`${track === 'uplift' ? 'the upgrade' : (modules.find(module => module.dir.toLowerCase() === name)?.dir ?? name)}: NOT PROVEN${proof.reason === '' ? '' : `: ${proof.reason}`}`) + } + } + for (const extra of extras) { if (track === 'transform' && extra.hasMain && (!extra.hasNotes || !extra.hasTests)) { attention.push( @@ -784,16 +898,16 @@ export async function readSnapshot( } if (pending > 0) { - attention.push(`${pending} P0 rule${pending === 1 ? '' : 's'} flagged for a person and not reviewed yet`) + attention.push(`${pending} high-priority rule${pending === 1 ? '' : 's'} still need${pending === 1 ? 's' : ''} a person's review`) } } const next: NextStep | null = track === 'uplift' - ? nextOfUplift(options.commandPrefix, system, stages) + ? nextOfUplift(options.commandPrefix, system, stages, proofs) : track === 'reimagine' - ? nextOfReimagine(options.commandPrefix, system, stages) - : nextOfTransform(options.commandPrefix, system, stages, brief.value, byNode) + ? nextOfReimagine(options.commandPrefix, system, stages, modules, proofs) + : nextOfTransform(options.commandPrefix, system, stages, brief.value, byNode, analysisAt !== null, proofs) return { system, @@ -810,6 +924,8 @@ export async function readSnapshot( extras, uplift, findings: { exists: findingsHead !== null, isScan }, + verification, + proofs, reviews, percent: track === 'reimagine' || loc === 0 ? null : locDone / loc, totals: { @@ -826,28 +942,35 @@ export async function readSnapshot( /** 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') + // A rewrite's five analysis steps are what "analysis 5/5" counts: its build, its proof and its scan are not among them. + const countable = snapshot.stages.filter(stage => stage.key !== 'harden' && stage.key !== 'transform' && !(snapshot.track === 'transform' && stage.key === 'verify')) 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`] + ? [`${snapshot.system}: analysis ${done}/5 steps done`] + : [`${snapshot.system}: ${TRACK_LABELS[snapshot.track]} ${done}/${countable.length} steps done`] if (snapshot.brief !== null) { - parts.push(snapshot.brief.approval.isSigned ? 'brief approved' : 'brief awaiting approval') + parts.push(snapshot.brief.approval.isSigned ? 'brief approved' : 'brief waiting for 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'}`, + ? `${snapshot.modules.length} service${snapshot.modules.length === 1 ? '' : 's'} built` + : `${snapshot.totals.done} of ${snapshot.totals.modules} modules ${snapshot.track === 'uplift' ? 'match the baseline' : 'reviewed'}`, ) } + const proven = [...snapshot.proofs.values()].filter(proof => proof.state === 'proven').length + + if (proven > 0) { + parts.push(snapshot.track === 'uplift' ? 'proven to behave the same' : `${proven} proven`) + } + if (snapshot.attention.length > 0) { - parts.push(`${snapshot.attention.length} need attention`) + parts.push(`${snapshot.attention.length} need${snapshot.attention.length === 1 ? 's' : ''} attention`) } return parts.join(' · ') diff --git a/plugins/code-modernization/hooks/reader/rules.ts b/plugins/code-modernization/hooks/reader/rules.ts index dec397fd..080edab8 100644 --- a/plugins/code-modernization/hooks/reader/rules.ts +++ b/plugins/code-modernization/hooks/reader/rules.ts @@ -1,4 +1,5 @@ import { baseName } from '../paths' +import { linesOf } from '../text' /** * `analysis/<system>/BUSINESS_RULES.md`, read into rule cards. @@ -112,7 +113,7 @@ const priorityOf = (id: string, body: string): string => { } // `P0` · Calculation · confidence High · `app/cbl/A.cbl:10-20` - const header = body.split('\n').find(line => line.trim() !== '') ?? '' + const header = linesOf(body).find(line => line.trim() !== '') ?? '' return /^\s*`?\**(P\d)\**`?\s*(?:·|$)/.exec(header)?.[1] ?? '' } @@ -132,7 +133,7 @@ const gwtOf = (body: string, word: string): string | undefined => { } const markedOf = (body: string, marker: RegExp): string | undefined => { - for (const line of body.split('\n')) { + for (const line of linesOf(body)) { if (marker.test(line)) { const text = clean(line.replace(/^>\s*/, '').replace(marker, '')) .replace(/^[—–-]\s*/, '') @@ -162,7 +163,7 @@ const specOf = (body: string): { given?: string; when?: string; then?: string } const clauses: Record<'given' | 'when' | 'then', string[]> = { given: [], when: [], then: [] } let current: 'given' | 'when' | 'then' | undefined - for (const raw of block.split('\n')) { + for (const raw of linesOf(block)) { const line = raw.trim().replace(/^```\w*$/, '').replace(/^[-*]\s+/, '') const match = /^(Given|When|Then|And)\s+(.*)$/.exec(line) @@ -196,7 +197,7 @@ function cardOf( body: string, domain: string | undefined, ): Rule { - const lines = body.split('\n') + const lines = linesOf(body) const header = lines.find(line => line.trim() !== '') ?? '' const headerParts = header.split('·').map(part => clean(part)) @@ -337,7 +338,7 @@ function rowOf( /** Parses BUSINESS_RULES.md. Never throws; an unreadable file is no rules. */ export function parseRules(text: string): RuleSet { - const lines = text.split('\n') + const lines = linesOf(text) 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. */ diff --git a/plugins/code-modernization/hooks/reader/tracks.ts b/plugins/code-modernization/hooks/reader/tracks.ts index 8ce75985..5dfd8e14 100644 --- a/plugins/code-modernization/hooks/reader/tracks.ts +++ b/plugins/code-modernization/hooks/reader/tracks.ts @@ -26,6 +26,7 @@ export const STATE_WORDS_BY_TRACK: Record<TrackKey, Record<string, string>> = { scaffolded: 'scaffolded', 'tests-written': 'tests written', 'tests-red': 'tests red', + 'tests-failing': 'tests failing', 'tests-green': 'tests green', reviewed: 'reviewed', ported: 'ported', @@ -36,6 +37,7 @@ export const STATE_WORDS_BY_TRACK: Record<TrackKey, Record<string, string>> = { scaffolded: 'changed', 'tests-written': 'tests written', 'tests-red': 'worse than baseline', + 'tests-failing': 'tests failing', 'tests-green': 'tests pass', reviewed: 'matches baseline', ported: 'ported', @@ -46,6 +48,7 @@ export const STATE_WORDS_BY_TRACK: Record<TrackKey, Record<string, string>> = { scaffolded: 'scaffolded', 'tests-written': 'tests written', 'tests-red': 'tests red', + 'tests-failing': 'tests failing', 'tests-green': 'tests green', reviewed: 'reviewed', ported: 'ported', diff --git a/plugins/code-modernization/hooks/reader/uplift.ts b/plugins/code-modernization/hooks/reader/uplift.ts index 58e99060..7cff7d36 100644 --- a/plugins/code-modernization/hooks/reader/uplift.ts +++ b/plugins/code-modernization/hooks/reader/uplift.ts @@ -1,4 +1,5 @@ import { join } from '../paths' +import { linesOf } from '../text' 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' @@ -18,6 +19,11 @@ export type Baseline = { results: number | null /** One row per module, keyed by the module path lower-cased with no trailing slash. */ rows: Map<string, BaselineRow> + /** + * A baseline of one module has no per-module table: its title names the module and a small table gives the totals + * (`| Passed | 945 |`). Those totals are that module's row. + */ + headline: { title: string; row: BaselineRow } | null } const int = (text: string | undefined): number => { @@ -42,13 +48,10 @@ const keyOf = (text: string): string => .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') + const lines = linesOf(text) for (let index = 0; index < lines.length - 1; index += 1) { const head = lines[index] ?? '' @@ -87,14 +90,58 @@ export function parseBaseline(text: string): Baseline { } } - 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 totals = /(?<![\d,])(\d[\d,]{0,14})\s+test\s+results?/i.exec(text)?.[1] ?? /\btotal\b[^\n]{0,40}?([\d,]{2,15})\s+tests?\b/i.exec(text)?.[1] const summed = [...rows.values()].reduce((sum, row) => sum + row.pass + row.fail + row.error + row.skip, 0) + // The first `| Passed | 945 |` style lines, whatever else the file holds. + const counts: Partial<Record<keyof BaselineRow, number>> = {} + + for (const line of lines) { + const found = /^\s*\|\s*\**\s*(pass(?:ed)?|fail(?:ed|ures?)?|errors?|skipped|skip)\s*\**\s*\|\s*\**\s*([\d,]+)\s*\**\s*\|?\s*$/i.exec(line) + + if (found !== null) { + const word = (found[1] ?? '').toLowerCase() + const key: keyof BaselineRow = word.startsWith('pass') ? 'pass' : word.startsWith('fail') ? 'fail' : word.startsWith('err') ? 'error' : 'skip' + + counts[key] ??= int(found[2]) + } + } + + const title = (lines.find(line => /^#\s+/.test(line)) ?? '').replace(/^#\s+/, '').replace(/[`*]/g, '').trim() + return { isTargetOnly: /^\s*target-only:/im.test(text), results: totals !== undefined ? int(totals) : rows.size > 0 ? summed : null, rows, + headline: + counts.pass !== undefined && counts.fail !== undefined && title !== '' + ? { title, row: { pass: counts.pass, fail: counts.fail, error: counts.error ?? 0, skip: counts.skip ?? 0 } } + : null, + } +} + +/** + * The baseline's row for one module: its own row, else the file's headline totals when its title names the module + * (a pilot's baseline is one module's, and says so in its title). Null when there is nothing to compare with. + */ +export function baselineRowOf(baseline: Baseline | null, dir: string): BaselineRow | null { + if (baseline === null || dir === '') { + return null + } + + const own = baseline.rows.get(keyOf(dir)) + + if (own !== undefined) { + return own + } + + if (baseline.headline === null) { + return null } + + const escaped = keyOf(dir).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + + return new RegExp(`(?<![\\w./-])${escaped}(?![\\w./-])`, 'i').test(baseline.headline.title) ? baseline.headline.row : null } export type Catalog = { @@ -113,7 +160,7 @@ export function parseCatalog(text: string): Catalog | null { const byFileBase = new Map<string, string[]>() let current: string | null = null - for (const line of text.split('\n')) { + for (const line of linesOf(text)) { const opens = /^\s*(?:\|\s*\**|#{1,6}\s+\**)(D-?\d{1,3})\b/.exec(line)?.[1] if (opens !== undefined) { @@ -209,7 +256,7 @@ export async function readUpliftUnits( 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 row = baselineRowOf(baseline, unit.dir) const state = stateOfUplift(tests, row, changed.has(unit.id)) if (state !== 'untouched') { diff --git a/plugins/code-modernization/hooks/reader/verification.ts b/plugins/code-modernization/hooks/reader/verification.ts new file mode 100644 index 00000000..c1d6e556 --- /dev/null +++ b/plugins/code-modernization/hooks/reader/verification.ts @@ -0,0 +1,150 @@ +import { plain } from '../text' +import type { TrackKey } from './tracks' + +/** + * `analysis/<system>/VERIFICATION.json`, written by the proof pack (`scripts/proof_pack.py`, run by the verify + * command): one verdict per built module, computed by a script from the evidence files. The pane shows the verdicts + * as they are and never computes one. + * + * The file is text from a run on an untrusted tree, and its shape may move between releases, so it is read + * tolerantly: a field of the wrong type is ignored, a verdict is only ever one of the three exact words, a name or a + * reason is cut to one short plain line, and how much is read is capped. + */ + +export type Verdict = 'PROVEN' | 'PARTLY PROVEN' | 'NOT PROVEN' + +const VERDICTS: readonly string[] = ['PROVEN', 'PARTLY PROVEN', 'NOT PROVEN'] + +/** What one module's verdict is, as the file says it. */ +export type ProofEntry = { + /** The module: a folder under `modernized/<system>/`, or the uplift's whole working copy. */ + name: string + track: TrackKey + verdict: Verdict + /** The first reason the verdict is not PROVEN, as one plain line; empty when the file gives none. */ + reason: string + /** When the module was checked; null when the file gives no time this can read. */ + atMs: number | null +} + +export type Verification = { + overall: Verdict | null + entries: ProofEntry[] +} + +/** How the module is standing with the proof, for a chip and for the next step. */ +export type ProofState = { + /** `none`: built, and nothing checked it yet. `changed`: checked, and its code or tests are newer than that check. */ + state: 'proven' | 'partly' | 'not' | 'changed' | 'none' + verdict?: Verdict + reason: string +} + +const MAX_TEXT = 4_000_000 +const MAX_ENTRIES = 1_000 +const MAX_NAME = 80 +const MAX_REASON = 160 + +/** The proof pack's own spelling of a track: a rewrite is `rewrite` there. */ +const TRACK_OF: Record<string, TrackKey> = { rewrite: 'transform', transform: 'transform', uplift: 'uplift', reimagine: 'reimagine' } + +/** `2026-09-24 20:31 UTC` (the pack's stamp) as milliseconds since the epoch; null when it is anything else. */ +function timeOf(value: unknown): number | null { + if (typeof value !== 'string') { + return null + } + + const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?\s*(?:UTC|Z)?$/.exec(value.trim()) + + if (match === null) { + return null + } + + const ms = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6] ?? 0)) + + return Number.isFinite(ms) ? ms : null +} + +const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value) + +/** The file's text as a Verification; null when it is not one. */ +export function parseVerification(text: string): Verification | null { + if (text.length > MAX_TEXT) { + return null + } + + let raw: unknown + + try { + raw = JSON.parse(text) + } catch { + return null + } + + if (!isRecord(raw) || !Array.isArray(raw.modules)) { + return null + } + + const entries: ProofEntry[] = [] + + for (const item of raw.modules.slice(0, MAX_ENTRIES) as unknown[]) { + if (!isRecord(item)) { + continue + } + + const name = typeof item.name === 'string' ? plain(item.name, MAX_NAME) : '' + const track = typeof item.track === 'string' ? TRACK_OF[item.track] : undefined + + // Only the exact words count: a verdict with anything added to it is not one. + if (name === '' || track === undefined || typeof item.verdict !== 'string' || !VERDICTS.includes(item.verdict)) { + continue + } + + const first = Array.isArray(item.reasons) ? (item.reasons as unknown[]).find(reason => typeof reason === 'string' && reason.trim() !== '') : undefined + + entries.push({ + name, + track, + verdict: item.verdict as Verdict, + reason: typeof first === 'string' ? plain(first, MAX_REASON) : '', + atMs: timeOf(item.verifiedAt), + }) + } + + const overall = isRecord(raw.overall) && typeof raw.overall.verdict === 'string' && VERDICTS.includes(raw.overall.verdict) ? (raw.overall.verdict as Verdict) : null + + return { overall, entries } +} + +/** The pack stamps minutes; a file written in the same minute as the check is not newer than it. */ +const SLACK_MS = 90_000 + +/** + * Where a built module stands with the proof. Null when it has no notes and no verdict, so nothing is claimed of a + * module still being built. + * + * @param verification the file, or null when there is none + * @param track the track the pane follows + * @param name the module's folder under `modernized/` + * @param changedAtMs when the module's notes or test reports last changed (0 when unknown) + * @param hasNotes whether the module has notes: the sign a module was finished being built + */ +export function proofOfModule( + verification: Verification | null, + track: TrackKey, + name: string, + changedAtMs: number, + hasNotes: boolean, +): ProofState | null { + const entry = verification?.entries.find(candidate => candidate.track === track && candidate.name.toLowerCase() === plain(name, MAX_NAME).toLowerCase()) + + if (entry === undefined) { + return hasNotes ? { state: 'none', reason: '' } : null + } + + if (entry.atMs !== null && changedAtMs > entry.atMs + SLACK_MS) { + return { state: 'changed', verdict: entry.verdict, reason: entry.reason } + } + + return { state: entry.verdict === 'PROVEN' ? 'proven' : entry.verdict === 'PARTLY PROVEN' ? 'partly' : 'not', verdict: entry.verdict, reason: entry.reason } +} diff --git a/plugins/code-modernization/hooks/register.ts b/plugins/code-modernization/hooks/register.ts index e74abe71..9cb2e2fa 100644 --- a/plugins/code-modernization/hooks/register.ts +++ b/plugins/code-modernization/hooks/register.ts @@ -1,7 +1,7 @@ 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 { lineOf, missingPathOf, noteCall, noteDone, noteFailure, prune, subjectOf, tallyOf } from './fleet/fleet' +import type { Host, OpenResult } 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' @@ -11,6 +11,7 @@ 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 { mergeLedger, parseLedger } from './review/ledger' import { signBrief } from './sign' import { newActivity, @@ -24,11 +25,13 @@ import { } 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 { headerRowsOf, legendRowsOf, nextRowsOf, paneView, planOf, showBar, type Kit } from './views/pane' import { plain } from './text' import { xrayOf } from './xray/xray' const REFRESH_DEBOUNCE_MS = 450 +/** While a fleet of agents is writing, a read of everything on disk is due this often, not after every call. */ +const REFRESH_BUSY_MS = 2500 const FRAME_MS = 140 const CLOCK_MS = 1000 const POLL_MS = 20_000 @@ -66,7 +69,7 @@ function hostOf($: EngineInterface): Host { 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), + openPane: pane => $.ui.open(pane) as Promise<OpenResult>, closePane: pane => $.ui.close(pane), registerCommand: spec => $.command.register(spec), fillPrompt: input => $.prompt.fill(input), @@ -162,11 +165,17 @@ export function register(on: On, raw: PluginOptions) { } function scheduleRefresh(host: Host): void { - state.timers.get('refresh')?.cancel() + // A read is already due, and it will see everything written so far. Pushing it out with every call would starve + // it for as long as agents keep writing, and the map would show nothing of a fan-out until it was over. + if (state.timers.has('refresh')) { + return + } + + const isBusy = tallyOf(state.fleet, nowMs()).active >= 3 state.timers.set( 'refresh', - host.after(REFRESH_DEBOUNCE_MS, () => { + host.after(isBusy ? REFRESH_BUSY_MS : REFRESH_DEBOUNCE_MS, () => { state.timers.delete('refresh') void refresh(host) }), @@ -358,6 +367,7 @@ export function register(on: On, raw: PluginOptions) { filter, queue, ledger: snapshot.reviews, + edits: new Map(), index: nextUnreviewed(queue, snapshot.reviews, 0), source: null, isSourceShown: false, @@ -378,8 +388,13 @@ export function register(on: On, raw: PluginOptions) { 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)) + // The review command writes this file too: what it added while the deck was open is kept, this session's decisions go on top. + const onDisk = parseLedger(await readOrNull(host.fs, join('analysis', system, REVIEWS_FILE))) + const merged = mergeLedger(onDisk, state.deck.edits) + + state.deck.ledger = merged + await host.fs.write(join('analysis', system, REVIEWS_FILE), ledgerJson(system, merged)) + await host.fs.write(join('analysis', system, 'RULE_REVIEWS.md'), ledgerMarkdown(system, merged)) scheduleRefresh(host) } @@ -445,6 +460,7 @@ export function register(on: On, raw: PluginOptions) { } state.deck.ledger = decide(state.deck.ledger, rule, verdict, new Date(nowMs()).toISOString()) + state.deck.edits.set(rule.id, state.deck.ledger[rule.id] ?? null) state.deck.index = nextUnreviewed(state.deck.queue, state.deck.ledger, state.deck.index + 1) state.deck.isSourceShown = false void saveLedger(host).catch(() => undefined) @@ -455,6 +471,7 @@ export function register(on: On, raw: PluginOptions) { if (rule !== undefined) { state.deck.ledger = undecide(state.deck.ledger, rule.id) + state.deck.edits.set(rule.id, null) void saveLedger(host).catch(() => undefined) host.invalidate() } @@ -578,11 +595,21 @@ export function register(on: On, raw: PluginOptions) { // ------------------------------------------------------------------ pane - async function openPane(host: Host): Promise<void> { - await host.openPane({ id: PANE_ID, title: 'Modernization' }) - state.pane.isOpen = true + /** + * Opens the pane. Opened unasked on a terminal too narrow to dock a pane, the engine holds it undrawn: it is not open to + * the person, so the bar with the show button stays where it was, and pressing that button (the person asking) seats + * the pane at any width. + */ + async function openPane(host: Host): Promise<{ isPlaced: boolean; reason: string }> { + const result: OpenResult = await host.openPane({ id: PANE_ID, title: 'Modernization' }) + const isPlaced = result === undefined || result.isPlaced !== false + + state.pane.isOpen = isPlaced + state.pane.isWaiting = !isPlaced state.pane.isClosedByPerson = false void refresh(host) + + return { isPlaced, reason: result !== undefined && result.reason !== undefined ? result.reason : '' } } const paneActionsOf = (host: Host) => ({ @@ -635,6 +662,7 @@ export function register(on: On, raw: PluginOptions) { }, close: () => { state.pane.isOpen = false + state.pane.isWaiting = false state.pane.isClosedByPerson = true void host.closePane({ id: PANE_ID }).catch(() => undefined) }, @@ -662,6 +690,7 @@ export function register(on: On, raw: PluginOptions) { host !== null && state.options.panel === 'auto' && !state.pane.isOpen && + !state.pane.isWaiting && !state.pane.isClosedByPerson && !state.timers.has('auto-open') && state.snapshot !== null && @@ -789,7 +818,13 @@ export function register(on: On, raw: PluginOptions) { oneLineOf(snapshot), e.props.bodyColumns, () => { - void openPane(host).catch(() => undefined) + void openPane(host) + .then(result => { + if (!result.isPlaced) { + host.toast(`The pane could not be shown: ${result.reason}`, 8000) + } + }) + .catch(() => undefined) }, ) } @@ -838,6 +873,7 @@ export function register(on: On, raw: PluginOptions) { const rows = wholeOf(e.props.scroll.bodyRows) state.pane.isOpen = true + state.pane.isWaiting = false state.pane.bodyColumns = columns state.pane.bodyRows = rows state.pane.placement = e.props.placement @@ -852,6 +888,8 @@ export function register(on: On, raw: PluginOptions) { [...state.fleet.signatures.values()].filter(signature => signature.agents.size >= 3).length, hasMap: snapshot !== null && snapshot.estate !== null && kit.Raster !== undefined, headerRows: headerRowsOf(snapshot, columns), + nextRows: nextRowsOf(snapshot, state, columns), + legendRows: legendRowsOf(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 @@ -897,6 +935,7 @@ export function register(on: On, raw: PluginOptions) { if (e.id === PANE_ID) { state.pane.isOpen = false + state.pane.isWaiting = false state.pane.isClosedByPerson = e.origin.kind === 'person' || state.pane.isClosedByPerson if (state.estate !== null) { @@ -954,6 +993,13 @@ export function register(on: On, raw: PluginOptions) { tests: module.tests, reviewDate: module.reviewDate, })), + proof: + snapshot.verification === null + ? null + : { + overall: snapshot.verification.overall, + modules: [...snapshot.proofs].map(([name, proof]) => ({ name, state: proof.state, verdict: proof.verdict ?? null, reason: proof.reason })), + }, totals: snapshot.totals, percent: snapshot.percent, attention: snapshot.attention, @@ -969,15 +1015,16 @@ export function register(on: On, raw: PluginOptions) { if (wantsClose) { state.pane.isOpen = false + state.pane.isWaiting = false state.pane.isClosedByPerson = true await host.closePane({ id: PANE_ID }).catch(() => undefined) return { text: 'Modernization pane hidden' } } - await openPane(host) + const opened = await openPane(host) - return { text: 'Modernization pane shown' } + return { text: opened.isPlaced ? 'Modernization pane shown' : `The pane could not be shown: ${opened.reason}` } }) on('command.run', { command: 'modernize-review' }, async ($, e, next) => { @@ -1199,12 +1246,6 @@ export function register(on: On, raw: PluginOptions) { 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` : ''}` @@ -1227,8 +1268,6 @@ export function register(on: On, raw: PluginOptions) { state.activity.running.delete(e.tool_use_id) if (agentId === undefined) { - state.activity.toolMs += ms - const finished: FinishedCall = { tool, subject, diff --git a/plugins/code-modernization/hooks/review/deck.ts b/plugins/code-modernization/hooks/review/deck.ts index 823b7969..b03739ea 100644 --- a/plugins/code-modernization/hooks/review/deck.ts +++ b/plugins/code-modernization/hooks/review/deck.ts @@ -69,7 +69,10 @@ export function decide( verdict: ReviewVerdict, atIso: string, ): ReviewLedger { - return { ...ledger, [rule.id]: { verdict, at: atIso, title: rule.title } } + // The reviewer's own words on the rule stay through a new verdict: the deck decides, it does not rewrite what was said. + const note = ledger[rule.id]?.note + + return { ...ledger, [rule.id]: { verdict, at: atIso, title: rule.title, ...(note !== undefined && { note }) } } } /** `ledger` with `rule`'s verdict taken back. */ @@ -98,6 +101,9 @@ const VERDICT_WORDS: Record<ReviewVerdict, string> = { discuss: 'Needs discussion', } +/** One table cell: one line, no pipe that would end it. */ +const cell = (text: string | undefined): string => (text ?? '').replace(/\s+/g, ' ').replace(/\\/g, '\\\\').replace(/\|/g, '\\|').trim() + /** 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 })) @@ -110,11 +116,11 @@ export function ledgerMarkdown(system: string, ledger: ReviewLedger): string { '', '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 |', - '|---|---|---|---|', + '| Rule | Verdict | When | Title | Note |', + '|---|---|---|---|---|', ...entries.map( ([id, entry]) => - `| ${id} | ${VERDICT_WORDS[entry.verdict]} | ${entry.at.slice(0, 10)} | ${(entry.title ?? '').replace(/\|/g, '\\|')} |`, + `| ${id} | ${VERDICT_WORDS[entry.verdict]} | ${entry.at.slice(0, 10)} | ${cell(entry.title)} | ${cell(entry.note)} |`, ), '', ].join('\n') diff --git a/plugins/code-modernization/hooks/review/ledger.ts b/plugins/code-modernization/hooks/review/ledger.ts new file mode 100644 index 00000000..4ebc3b0f --- /dev/null +++ b/plugins/code-modernization/hooks/review/ledger.ts @@ -0,0 +1,78 @@ +import { plain } from '../text' +import type { ReviewLedger, ReviewVerdict } from '../reader/progress' + +/** + * `RULE_REVIEWS.json`, read without trusting it. Two writers keep it: this deck, and the `modernize-review` command + * for people who work without the pane. Each entry is `{ verdict, at, title?, note? }`, the note being the reviewer's + * own words. The file sits in a workspace anyone may have edited, and a model may have written it, so every value is + * checked: a verdict is one of three exact words, a rule id is one plain token, a title or a note is cut to one short + * plain line, and anything else in an entry is dropped. + */ + +const VERDICTS: readonly string[] = ['confirmed', 'wrong', 'discuss'] + +/** What a note may hold: a reviewer's sentence or two, not a document. */ +export const MAX_NOTE = 500 +const MAX_TITLE = 120 +const MAX_ENTRIES = 5_000 +const RULE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/ +const FORBIDDEN_ID = new Set(['__proto__', 'constructor', 'prototype']) + +const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value) + +/** The ledger a file's text holds; empty when it is not one. */ +export function parseLedger(text: string | null): ReviewLedger { + if (text === null || text.length > 4_000_000) { + return {} + } + + let raw: unknown + + try { + raw = JSON.parse(text) + } catch { + return {} + } + + if (!isRecord(raw) || !isRecord(raw.reviews)) { + return {} + } + + const ledger: ReviewLedger = {} + + for (const [id, item] of Object.entries(raw.reviews).slice(0, MAX_ENTRIES)) { + if (!RULE_ID.test(id) || FORBIDDEN_ID.has(id) || !isRecord(item) || typeof item.verdict !== 'string' || !VERDICTS.includes(item.verdict)) { + continue + } + + const title = typeof item.title === 'string' ? plain(item.title, MAX_TITLE) : '' + const note = typeof item.note === 'string' ? plain(item.note, MAX_NOTE) : '' + // A time is kept only when it is one: the page shows its date. + const at = typeof item.at === 'string' && /^\d{4}-\d{2}-\d{2}/.test(item.at) ? item.at.slice(0, 40) : '' + + ledger[id] = { verdict: item.verdict as ReviewVerdict, at, ...(title !== '' && { title }), ...(note !== '' && { note }) } + } + + return ledger +} + +/** + * The file's ledger with this session's decisions on top. `edits` maps a rule id to what the deck set it to, or null when the + * deck took its verdict back. What the other writer put in the file meanwhile stays, and a note the deck did not write is + * kept on a rule the deck decided again. + */ +export function mergeLedger(onDisk: ReviewLedger, edits: ReadonlyMap<string, ReviewLedger[string] | null>): ReviewLedger { + const merged: ReviewLedger = { ...onDisk } + + for (const [id, edit] of edits) { + if (edit === null) { + delete merged[id] + } else { + const note = edit.note ?? onDisk[id]?.note + + merged[id] = { ...edit, ...(note !== undefined && { note }) } + } + } + + return merged +} diff --git a/plugins/code-modernization/hooks/state.ts b/plugins/code-modernization/hooks/state.ts index 2ce9b3f8..5fbf71cc 100644 --- a/plugins/code-modernization/hooks/state.ts +++ b/plugins/code-modernization/hooks/state.ts @@ -70,10 +70,6 @@ export type Activity = { 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 } @@ -85,6 +81,11 @@ export type DeckState = { queue: Rule[] index: number ledger: ReviewLedger + /** + * What this session set each rule to (null: its verdict taken back). The file is read again before it is written, and + * these are laid on top of it, so a verdict the other writer (the review command) put there meanwhile is not lost. + */ + edits: Map<string, ReviewLedger[string] | null> /** The source lines of the card in view, once asked for. */ source: { ruleId: string; path: string; startLine: number; text: string } | null isSourceShown: boolean @@ -110,7 +111,10 @@ export type State = { isRefreshQueued: boolean timers: Map<string, Timer> pane: { + /** Open and drawn. An open the engine holds back (unasked, on a terminal too narrow to dock a pane) is not this. */ isOpen: boolean + /** The engine holds the pane undrawn until the person asks for it or the terminal widens. */ + isWaiting: boolean isClosedByPerson: boolean bodyColumns: number bodyRows: number @@ -137,9 +141,6 @@ export const newActivity = (): Activity => ({ step: null, running: new Map(), finished: [], - toolMs: 0, - testMs: 0, - testRuns: 0, xrays: 0, xraysThisTurn: 0, }) @@ -156,7 +157,7 @@ export function newState(raw: PluginOptions): State { isRefreshing: false, isRefreshQueued: false, timers: new Map(), - pane: { isOpen: false, isClosedByPerson: false, bodyColumns: 48, bodyRows: 30, placement: 'dock' }, + pane: { isOpen: false, isWaiting: false, isClosedByPerson: false, bodyColumns: 48, bodyRows: 30, placement: 'dock' }, viewport: { columns: null, isFullscreen: null }, activity: newActivity(), touches: new Map(), @@ -171,6 +172,7 @@ export function newState(raw: PluginOptions): State { queue: [], index: 0, ledger: {}, + edits: new Map(), source: null, isSourceShown: false, }, diff --git a/plugins/code-modernization/hooks/text.ts b/plugins/code-modernization/hooks/text.ts index ecbf1bc5..f7c0cb38 100644 --- a/plugins/code-modernization/hooks/text.ts +++ b/plugins/code-modernization/hooks/text.ts @@ -35,3 +35,9 @@ const SYSTEM_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/ export const isToken = (value: string): boolean => TOKEN.test(value) export const isSystemName = (value: string): boolean => SYSTEM_NAME.test(value) + +/** The longest line a reader looks at. A line of a table or a heading is a few hundred characters; a longer one is not a card, and a pattern run over a million characters of it is what a hostile file is for. */ +export const MAX_LINE = 4_000 + +/** `text` as lines, each cut to what a reader looks at. */ +export const linesOf = (text: string): string[] => text.split('\n').map(line => (line.length > MAX_LINE ? line.slice(0, MAX_LINE) : line)) diff --git a/plugins/code-modernization/hooks/views/deck.tsx b/plugins/code-modernization/hooks/views/deck.tsx index 3d81f744..e25f30aa 100644 --- a/plugins/code-modernization/hooks/views/deck.tsx +++ b/plugins/code-modernization/hooks/views/deck.tsx @@ -7,6 +7,7 @@ import type { ReviewVerdict } from '../reader/progress' import { tallyOf } from '../review/deck' import type { DeckState, SignState } from '../state' import type { Kit } from './pane' +import { BAD, GOOD, HEAD, WARN } from './palette' export type DeckActions = { decide: (verdict: ReviewVerdict) => void @@ -17,13 +18,13 @@ export type DeckActions = { 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 SCOPE_WORDS = { flagged: 'high-priority rules a person should check', p0: 'all high-priority rules', all: 'all rules' } +const SCOPE_SHORT = { flagged: 'flagged', p0: 'high-priority', all: 'all' } const VERDICT_COLORS: Record<ReviewVerdict, string> = { - confirmed: 'green', - wrong: 'red', - discuss: 'yellow', + confirmed: GOOD, + wrong: BAD, + discuss: WARN, } /** `text` word-wrapped to `width` cells, at most `maxLines` rows, the last ending in an ellipsis when cut. */ @@ -98,9 +99,9 @@ export function deckView( if (rule === undefined) { return ( <Box flexDirection="column"> - <Text bold color="cyan">Rule review</Text> + <Text bold color={HEAD}>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.`} + {`Nothing to review among ${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> @@ -113,7 +114,7 @@ export function deckView( const meta = [ rule.domain, - rule.category, + rule.category !== undefined && rule.category.toLowerCase() === rule.domain?.toLowerCase() ? undefined : 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 !== '') @@ -133,22 +134,33 @@ export function deckView( const verdictLine = verdict !== undefined ? ( - <Text color={VERDICT_COLORS[verdict.verdict]} bold>{`Verdict: ${verdict.verdict} (${verdict.at.slice(0, 10)})`}</Text> + <Text color={VERDICT_COLORS[verdict.verdict]} bold>{`Your verdict: ${verdict.verdict} (${verdict.at.slice(0, 10)})`}</Text> ) : ( - <Text dimColor>Verdict: none yet</Text> + <Text dimColor>Is this rule right? No verdict yet.</Text> ) + // The reviewer's own words, when they gave any (the review command records them): one line, cut short. + const noteLine = + verdict?.note !== undefined ? ( + <Text wrap="truncate-end"> + <Text dimColor>Note: </Text> + <Text>{verdict.note}</Text> + </Text> + ) : null + + const noteRows = noteLine === null ? 0 : 1 + 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 bold color={HEAD}>Rule review</Text> + <Text bold>{` ${deck.index + 1} of ${tally.total}`}</Text> + <Text dimColor>{' · '}</Text> + <Text color={GOOD}>{`${tally.confirmed} confirmed`}</Text> + <Text dimColor>{' · '}</Text> + <Text color={BAD}>{`${tally.wrong} wrong`}</Text> + <Text dimColor>{' · '}</Text> + <Text color={WARN}>{`${tally.discuss} to discuss`}</Text> + <Text dimColor>{` · ${tally.open} open · ${width < 96 ? SCOPE_SHORT[deck.scope] : SCOPE_WORDS[deck.scope]}${deck.filter !== '' ? ` · "${deck.filter}"` : ''}`}</Text> </Text> ) @@ -156,7 +168,7 @@ export function deckView( // 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 codeRows = Math.max(3, Math.min(24, maxRows - 8 - noteRows)) const gist = rule.statement !== '' ? rule.statement : (rule.then ?? rule.given ?? '') return ( @@ -173,6 +185,7 @@ export function deckView( wrap="truncate-end" /> {verdictLine} + {noteLine} {keys} </Box> ) @@ -182,7 +195,7 @@ export function deckView( 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 room = Math.max(1, maxRows - (isTight ? fixed - 3 : fixed) - 1 - noteRows) 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. @@ -213,11 +226,11 @@ export function deckView( block('Then', rule.then) if (rule.defect !== undefined) { - rows.push({ text: wrapLines(`⚠ Suspected defect: ${rule.defect}`, width, 1)[0] ?? '', color: 'yellow' }) + rows.push({ text: wrapLines(`! Suspected defect: ${rule.defect}`, width, 1)[0] ?? '', color: WARN }) } if (rule.sme !== undefined) { - rows.push({ text: wrapLines(`? For an SME: ${rule.sme}`, width, 1)[0] ?? '', color: 'magenta' }) + rows.push({ text: wrapLines(`? For an SME: ${rule.sme}`, width, 1)[0] ?? '', color: HEAD }) } return ( @@ -230,12 +243,13 @@ export function deckView( <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.label !== undefined ? <Text bold color={HEAD}>{`${row.label} `}</Text> : null} {row.text} </Text> ))} </Box> <Box marginTop={isTight ? 0 : 1}>{verdictLine}</Box> + {noteLine} {keys} </Box> ) @@ -262,12 +276,12 @@ export function signView( return ( <Box flexDirection="column" width={width}> - <Text bold color="cyan">Sign the brief</Text> + <Text bold color={HEAD}>Sign the brief</Text> <Text dimColor wrap="wrap"> - {`analysis/${system}/MODERNIZATION_BRIEF.md · execution commands treat an unsigned brief as not approved.`} + {`Records who approved the plan in analysis/${system}/MODERNIZATION_BRIEF.md, and how much of it. Nothing is built until it is signed.`} </Text> {openQuestions > 0 ? ( - <Text color="yellow" wrap="wrap">{`${openQuestions} open question${openQuestions === 1 ? '' : 's'} in the brief ${openQuestions === 1 ? 'is' : 'are'} still unticked.`}</Text> + <Text color={WARN} 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 ? ( @@ -297,7 +311,7 @@ export function signView( {`${sign.covers === 'full' ? '◉' : '○'} Full plan`} </Button> </Box> - {sign.error !== null ? <Text color="red" wrap="wrap">{sign.error}</Text> : null} + {sign.error !== null ? <Text color={BAD} 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> diff --git a/plugins/code-modernization/hooks/views/palette.ts b/plugins/code-modernization/hooks/views/palette.ts new file mode 100644 index 00000000..49abe509 --- /dev/null +++ b/plugins/code-modernization/hooks/views/palette.ts @@ -0,0 +1,11 @@ +/** + * The colours the pane and the deck draw text in, by the names of Claude Code's own theme. A theme key is drawn + * in the person's theme, dark or light, so a green that reads on one background does not vanish on the other; the ANSI + * names (`cyan`, `yellow`) are whatever the terminal makes of them, and yellow or cyan text is hard to read on white. + */ +export const HEAD = 'suggestion' +export const GOOD = 'success' +export const BAD = 'error' +export const WARN = 'warning' +/** The one accent: what to do next. */ +export const ACCENT = 'claude' diff --git a/plugins/code-modernization/hooks/views/pane.tsx b/plugins/code-modernization/hooks/views/pane.tsx index 7e9ad1b6..dfc75f87 100644 --- a/plugins/code-modernization/hooks/views/pane.tsx +++ b/plugins/code-modernization/hooks/views/pane.tsx @@ -4,10 +4,12 @@ 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 { countsOf, hexOf, PROOF_MARKS, proofCountsOf, STATE_COLORS, stateWord, type Tile, type TileState } from '../map/estate' +import { frontDoorOf, isUnitDone, type Snapshot } from '../reader/progress' import { TRACK_LABELS, TRACK_UNITS } from '../reader/tracks' import { RASTER_KEY, type State } from '../state' +import type { ProofState } from '../reader/verification' +import { ACCENT, BAD, GOOD, HEAD, WARN } from './palette' /** The elements a pane draws with; `Raster` only where the surface has it (the terminal). */ export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & @@ -58,9 +60,9 @@ function rule(kit: Kit, title: string, width: number, right = ''): RenderChildre return ( <Box> - <Text bold color="cyan">{title}</Text> + <Text bold color={HEAD}>{title}</Text> <Text dimColor>{` ${'─'.repeat(fill)} `}</Text> - <Text color="yellow">{right}</Text> + <Text>{right}</Text> </Box> ) } @@ -84,9 +86,8 @@ function estateLine(snapshot: Snapshot): string { 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}` + return `${languages === '' ? '' : `${languages} · `}${count}${estate.isPartial ? '+' : ''}` } /** The rows the header takes: the title, the stage rail, the estate line and the progress bar. */ @@ -99,8 +100,7 @@ function header(kit: Kit, snapshot: Snapshot, width: number, actions: PaneAction 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 right = percent === null ? '' : `${(percent * 100).toFixed(percent < 0.1 ? 1 : 0)}% done` const left = `${snapshot.system}${target !== undefined ? ` → ${target}` : ''}` const bar = barOf(percent ?? 0, Math.max(4, width - right.length - 1)) const summary = estateLine(snapshot) @@ -118,7 +118,7 @@ function header(kit: Kit, snapshot: Snapshot, width: number, actions: PaneAction </Box> <Box flexWrap="wrap"> {snapshot.stages.map(stage => ( - <Text color={stage.isDone ? 'green' : undefined} dimColor={!stage.isDone}> + <Text color={stage.isDone ? GOOD : undefined} dimColor={!stage.isDone}> {`${stage.isDone ? '✓' : '·'} ${stage.label} `} </Text> ))} @@ -126,7 +126,7 @@ function header(kit: Kit, snapshot: Snapshot, width: number, actions: PaneAction {summary !== '' ? <Text dimColor wrap="truncate-end">{clip(summary, width)}</Text> : null} {percent !== null ? ( <Box> - <Text color="green">{bar.full}</Text> + <Text color={GOOD}>{bar.full}</Text> <Text dimColor>{bar.rest}</Text> <Text>{` ${right}`}</Text> </Box> @@ -159,6 +159,12 @@ function estate(kit: Kit, snapshot: Snapshot, frame: PaneFrame, width: number): <Text dimColor>{` ${stateWord(snapshot.track, entry.state)} ${entry.count} `}</Text> </Text> ))} + {proofCountsOf(frame.estate.tiles).map(entry => ( + <Text> + <Text color={entry.kind === 'proven' ? GOOD : entry.kind === 'partly' ? WARN : BAD} bold>{PROOF_MARKS[entry.kind]}</Text> + <Text dimColor>{` ${entry.kind === 'proven' ? 'proven' : entry.kind === 'partly' ? 'partly proven' : 'not proven'} ${entry.count} `}</Text> + </Text> + ))} </Box> </Box> ) @@ -193,13 +199,13 @@ function phases(kit: Kit, snapshot: Snapshot, width: number, max: number): Rende 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 right = phase.criteria.length > 0 ? `${ticked}/${phase.criteria.length} checks` : '' const label = `${done ? '✓' : isCurrent ? '▸' : '·'} P${phase.number} ${phase.title}` return ( <Box> <Text - color={done ? 'green' : isCurrent ? 'cyan' : undefined} + color={done ? GOOD : isCurrent ? HEAD : undefined} bold={isCurrent} dimColor={!done && !isCurrent} > @@ -222,26 +228,46 @@ function orderOf(snapshot: Snapshot): Snapshot['modules'] { 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) + const rank = (state: string) => (state === 'tests-red' || state === 'tests-failing' ? 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)) } +/** What a module's standing with the proof is called, and how it is drawn. Words as well as colour. */ +const CHIPS: Record<ProofState['state'], { text: string; color?: string; isBold?: boolean; isDim?: boolean }> = { + proven: { text: 'PROVEN', color: GOOD, isBold: true }, + partly: { text: 'PARTLY PROVEN', color: WARN, isBold: true }, + not: { text: 'NOT PROVEN', color: BAD, isBold: true }, + changed: { text: 'changed since verified', color: WARN }, + none: { text: 'not verified yet', isDim: true }, +} + function modules(kit: Kit, snapshot: Snapshot, width: number, max: number): RenderChildren { const { Box, Text } = kit const all = orderOf(snapshot) + // An uplift is proven as one piece: its working copy has the one verdict, drawn as the first row. + const whole = snapshot.track === 'uplift' ? snapshot.proofs.get(`${snapshot.system}-uplifted`.toLowerCase()) : undefined - if (all.length === 0) { + if (all.length === 0 && whole === undefined) { return null } + const rows = Math.max(0, max - (whole !== undefined ? 1 : 0)) + 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 => { + {whole !== undefined ? ( + <Text wrap="truncate-end"> + <Text dimColor>{'■ '}</Text> + <Text bold>the whole upgrade </Text> + <Text color={CHIPS[whole.state].color} bold={CHIPS[whole.state].isBold === true} dimColor={CHIPS[whole.state].isDim === true}>{CHIPS[whole.state].text}</Text> + </Text> + ) : null} + {all.slice(0, rows).map(module => { const tests = module.tests const bad = tests === null ? 0 : tests.failures + tests.errors - const isWorse = module.state === 'tests-red' + const isWorse = module.state === 'tests-red' || module.state === 'tests-failing' // In an uplift a module may fail what the baseline already failed: red is only for what got worse. const testText = @@ -250,27 +276,38 @@ function modules(kit: Kit, snapshot: Snapshot, width: number, max: number): Rend : isWorse ? snapshot.track === 'uplift' ? `${bad} failing` - : `${bad}/${tests.tests} red` + : `${bad} of ${tests.tests} tests fail` : bad > 0 && snapshot.track !== 'uplift' - ? `${bad}/${tests.tests} red` - : `${tests.tests} ${snapshot.track === 'uplift' ? 'tests' : 'green'}` + ? `${bad} of ${tests.tests} tests fail` + : snapshot.track === 'uplift' + ? `${tests.tests} tests` + : `${tests.tests} tests pass` + const proof = snapshot.track === 'uplift' ? undefined : snapshot.proofs.get(module.dir.toLowerCase()) + const chip = proof !== undefined ? CHIPS[proof.state] : undefined 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)) + + // One row, and the proof is the last thing to give way: the test counts go first, then the name is cut. + const room = width - 2 - (2 + word.length) - (chip !== undefined ? 2 + chip.text.length : 0) + const shownTests = testText !== '' && 8 + 2 + testText.length <= room ? testText : '' + const name = clip(module.dir, Math.max(4, room - (shownTests !== '' ? 2 + shownTests.length : 0))) return ( - <Box> + <Text wrap="truncate-end"> <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 color={isWorse || (bad > 0 && snapshot.track !== 'uplift') ? BAD : GOOD}> + {shownTests === '' ? '' : ` ${shownTests}`} </Text> - </Box> + {chip !== undefined ? ( + <Text color={chip.color} bold={chip.isBold === true} dimColor={chip.isDim === true}>{` ${chip.text}`}</Text> + ) : null} + </Text> ) })} - {all.length > max ? <Text dimColor>{` … ${all.length - max} more`}</Text> : null} + {all.length > rows ? <Text dimColor>{` … ${all.length - rows} more`}</Text> : null} </Box> ) } @@ -284,28 +321,26 @@ function session(kit: Kit, state: State, frame: PaneFrame, width: number, max: n const status = activity.isWorking ? `● working ${ago(frame.nowMs - activity.turnStartMs)}` : fleet.active > 0 - ? `● ${fleet.active} agents working` + ? `● ${fleet.active} agent${fleet.active === 1 ? '' : 's'} 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>) + rows.push(<Text color={HEAD} 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 color={HEAD}>{' ◆ '}</Text> + <Text>{`${fleet.active} agent${fleet.active === 1 ? '' : 's'} active`}</Text> + <Text dimColor>{` · ${fleet.done}/${fleet.total} done · ${fleet.calls} calls${fleet.errors > 0 ? ` · ${fleet.errors} error${fleet.errors === 1 ? '' : 's'}` : ''}${fleet.stalled > 0 ? ` · ${fleet.stalled} stalled` : ''}`}</Text> </Text>, ) } @@ -313,17 +348,14 @@ function session(kit: Kit, state: State, frame: PaneFrame, width: number, max: n for (const call of running.slice(-2)) { rows.push( <Box> - <Text color="yellow">{' ◌ '}</Text> + <Text color={HEAD}>{' ● '}</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 summary = [activity.xrays > 0 ? `x-ray: notes from the analysis went with ${activity.xrays} read${activity.xrays === 1 ? '' : 's'}` : ''].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) @@ -340,7 +372,7 @@ function session(kit: Kit, state: State, frame: PaneFrame, width: number, max: n 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 color={call.isOk ? GOOD : BAD}>{call.isOk ? ' ✓ ' : ' ✗ '}</Text> <Text dimColor wrap="truncate-end">{clip(`${call.tool} ${call.subject}${call.note !== undefined ? ` · ${call.note}` : ''}`, width - 4)}</Text> </Box>, ) @@ -368,13 +400,83 @@ function attention(kit: Kit, state: State, snapshot: Snapshot, width: number, ma <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> + <Text color={WARN} wrap="truncate-end">{clip(` ! ${line}`, width)}</Text> ))} {lines.length > max ? <Text dimColor>{` … ${lines.length - max} more`}</Text> : null} </Box> ) } +/** The buttons under the Next line, by their labels, in the order they are drawn. */ +function buttonsOf(snapshot: Snapshot, state: State): string[] { + const next = snapshot.next + + return [ + ...(next !== null && !next.isByHand ? ['put in prompt'] : []), + ...(next?.action === 'sign' ? ['sign the brief'] : []), + ...((snapshot.rules?.rules.length ?? 0) > 0 ? ['review rules'] : []), + ...(state.activity.isWorking && state.fleet.seen > 0 ? ['stop the run'] : []), + 'refresh', + ] +} + +/** The rows the legend under the map takes at `width`: it wraps, and a wrapped legend must not spill out of the body. */ +export function legendRowsOf(snapshot: Snapshot | null, width: number): number { + if (snapshot === null || snapshot.estate === null) { + return 1 + } + + const states = new Set<TileState>() + const proofs = new Set<string>() + + for (const module of snapshot.byNode.values()) { + states.add(module.state) + + const proof = snapshot.track === 'uplift' ? undefined : snapshot.proofs.get(module.dir.toLowerCase())?.state + + if (proof === 'proven' || proof === 'partly' || proof === 'not') { + proofs.add(proof) + } + } + + if (snapshot.byNode.size < snapshot.estate.units.length) { + states.add('untouched') + } + + // '■ word 123 ' per state; '✓ word 123 ' per proof. + const widths = [ + ...[...states].map(state => 3 + stateWord(snapshot.track, state).length + 5), + ...[...proofs].map(kind => 3 + (kind === 'proven' ? 6 : kind === 'partly' ? 13 : 10) + 5), + ] + + let rows = 1 + let used = 0 + + for (const entry of widths) { + if (used > 0 && used + entry > width) { + rows += 1 + used = 0 + } + + used += entry + } + + return rows +} + +/** The rows the Next block takes at `width`, without the hint: its title, the command (wrapped), the reason, a blank row and the buttons. */ +export function nextRowsOf(snapshot: Snapshot | null, state: State, width: number): number { + if (snapshot === null) { + return 5 + } + + const next = snapshot.next + const command = next === null ? 1 : Math.max(1, Math.ceil((next.text.length + (next.isByHand && next.action === undefined ? 12 : 0) + 2) / Math.max(10, width))) + const buttons = Math.max(1, Math.ceil(buttonsOf(snapshot, state).reduce((sum, label) => sum + label.length + 5, 0) / Math.max(10, width + 1))) + + return 1 + command + 1 + 1 + buttons +} + function nextBlock( kit: Kit, snapshot: Snapshot, @@ -392,8 +494,8 @@ function nextBlock( {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 color={next.isByHand ? undefined : ACCENT} bold={!next.isByHand} wrap="wrap"> + {`${next.text}${next.isByHand && next.action === undefined ? ' (by hand)' : ''}`} </Text> <Text dimColor wrap="truncate-end">{next.reason}</Text> </Box> @@ -402,15 +504,16 @@ function nextBlock( )} <Box marginTop={1} flexWrap="wrap" columnGap={1}> {next !== null && !next.isByHand ? ( - <Button key="next" onPress={actions.next}>next</Button> + <Button key="next" onPress={actions.next}>put in prompt</Button> ) : null} + {next?.action === 'sign' ? <Button key="sign" onPress={actions.sign}>sign the brief</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} + {hasHint ? <Text dimColor wrap="truncate-end">{clip('click a button, or ctrl+x tab then Tab, Enter', width)}</Text> : null} </Box> ) } @@ -436,8 +539,11 @@ export type PanePlan = { export function planOf( rows: number, placement: 'dock' | 'inline', - counts: { phases: number; modules: number; attention: number; hasMap: boolean; headerRows: number }, + counts: { phases: number; modules: number; attention: number; hasMap: boolean; headerRows: number; nextRows?: number; legendRows?: number }, ): PanePlan { + const nextRows = counts.nextRows ?? 5 + const legendRows = counts.legendRows ?? 1 + if (placement === 'inline') { return { estate: counts.hasMap ? Math.max(4, Math.min(6, rows - 6 - counts.headerRows)) : 0, @@ -451,7 +557,7 @@ export function planOf( } const gap: 0 | 1 = rows >= 52 ? 1 : 0 - const hasHint = rows >= 44 + const hasHint = rows >= 36 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 @@ -459,8 +565,8 @@ export function planOf( // header · legend 1 · next: title, command, reason, blank, buttons (+hint) const fixed = counts.headerRows + - (counts.hasMap ? 1 : 0) + - (5 + (hasHint ? 1 : 0)) + + (counts.hasMap ? legendRows : 0) + + (nextRows + (hasHint ? 1 : 0)) + (attention > 0 ? 1 + attention : 0) + (modules > 0 ? 1 + modules : 0) + (1 + sessionMin) + @@ -469,7 +575,7 @@ export function planOf( 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 estate = counts.hasMap ? Math.max(4, Math.min(24, 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 } @@ -477,10 +583,10 @@ export function planOf( // 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.estate > 0 ? p.estate + legendRows : 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)) + + (nextRows + (p.hasHint ? 1 : 0)) + (p.attention > 0 ? 1 + p.attention + (counts.attention > p.attention ? 1 : 0) : 0) + (1 + p.session) @@ -519,13 +625,20 @@ export function paneView( 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 flexDirection="column" paddingRight={1} rowGap={1}> + <Text bold>Modernization</Text> + {state.readError !== null ? ( + <Text dimColor wrap="wrap">{`could not read the workspace: ${state.readError}`}</Text> + ) : ( + <Box flexDirection="column"> + <Text wrap="wrap">Nothing to show yet: no legacy code under legacy/ and no analysis under analysis/.</Text> + <Text wrap="wrap"> + <Text>To begin, type </Text> + <Text bold color={ACCENT}>{frontDoorOf(state.options.commandPrefix)}</Text> + <Text>. It asks what you want done with your code, finds it, and gives you the first step.</Text> + </Text> + </Box> + )} </Box> ) } diff --git a/plugins/code-modernization/hooks/xray/xray.ts b/plugins/code-modernization/hooks/xray/xray.ts index a26db5be..77bf9b1b 100644 --- a/plugins/code-modernization/hooks/xray/xray.ts +++ b/plugins/code-modernization/hooks/xray/xray.ts @@ -4,7 +4,7 @@ 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 { baselineRowOf } from '../reader/uplift' import { nodeOfFile, type TopoNode, type Topology } from '../reader/topology' /** @@ -92,7 +92,7 @@ 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()) ?? []).map(id => plain(id, 24)) - const row = unit?.dir !== undefined ? (snapshot.uplift?.baseline?.rows.get(baselineKeyOf(unit.dir)) ?? null) : null + const row = unit?.dir !== undefined ? baselineRowOf(snapshot.uplift?.baseline ?? null, unit.dir) : null const module = unit !== null ? snapshot.byNode.get(unit.id) : undefined if (deltas.length === 0 && row === null && module === undefined) { @@ -238,7 +238,7 @@ export function xrayOf(snapshot: Snapshot, request: XrayRequest): XrayNote | nul if (verdicts.length > 0) { lines.push( - `A reviewer disputed: ${some(verdicts.map(entry => `${plain(entry.rule.id, 24)} (${plain(entry.review?.verdict, 16)})`), 6)}. Do not treat those as settled.`, + `A reviewer disputed: ${some(verdicts.map(entry => `${plain(entry.rule.id, 24)} (${plain(entry.review?.verdict, 16)})`), 6)}. A rule marked wrong is not an oracle to pin, and a P0 rule under discussion stops the build: do not treat any of these as settled.`, ) } } |
