diff options
Diffstat (limited to 'plugins/code-modernization/hooks/reader')
| -rw-r--r-- | plugins/code-modernization/hooks/reader/brief.ts | 10 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/reader/fs.ts | 29 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/reader/modernized.ts | 71 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/reader/progress.ts | 259 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/reader/rules.ts | 11 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/reader/tracks.ts | 3 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/reader/uplift.ts | 61 | ||||
| -rw-r--r-- | plugins/code-modernization/hooks/reader/verification.ts | 150 |
8 files changed, 487 insertions, 107 deletions
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 } +} |
